diff --git a/.github/actions/build-push-image/action.yml b/.github/actions/build-push-image/action.yml index 1eb3300fd..4d3c6f123 100644 --- a/.github/actions/build-push-image/action.yml +++ b/.github/actions/build-push-image/action.yml @@ -1,7 +1,7 @@ name: Build and push image description: >- Shared tail for the container image builds: buildx setup, ghcr.io login, and a - gated build/push (publish only on main) with GitHub Actions layer cache. + gated build/push (publish on main, or on request) with GitHub Actions layer cache. Callers do their own checkout / values.yaml read / upstream clone as normal steps before calling this. @@ -30,6 +30,13 @@ inputs: description: Optional extra tag pushed with :latest and :sha- (e.g. the upstream version) required: false default: "" + publish: + description: >- + 'true' also publishes from a branch (a manual run), tagged only + :sha-; :latest and extra_tag move only from main. + Empty -> publish only on main. + required: false + default: "" platform: description: >- One platform to build (e.g. linux/arm64) on a runner of that architecture. @@ -53,11 +60,18 @@ runs: run: | owner=${OWNER,,} echo "owner=$owner" >> "$GITHUB_OUTPUT" + publish=false + if [ "$PUBLISH" = true ] || { [ "$EVENT" != pull_request ] && [ "$REF" = refs/heads/main ]; }; then + publish=true + fi + echo "publish=$publish" >> "$GITHUB_OUTPUT" { echo "tags<> "$GITHUB_OUTPUT" env: @@ -65,11 +79,14 @@ runs: IMAGE: ${{ inputs.image_name }} SHA: ${{ github.sha }} EXTRA_TAG: ${{ inputs.extra_tag }} + PUBLISH: ${{ inputs.publish }} + EVENT: ${{ github.event_name }} + REF: ${{ github.ref }} - uses: docker/setup-buildx-action@v3 - name: Log in to ghcr.io - if: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + if: ${{ steps.meta.outputs.publish == 'true' }} uses: docker/login-action@v3 with: registry: ghcr.io @@ -84,7 +101,7 @@ runs: context: ${{ inputs.context }} file: ${{ inputs.dockerfile }} build-args: ${{ inputs.build_args }} - push: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + push: ${{ steps.meta.outputs.publish == 'true' }} tags: ${{ steps.meta.outputs.tags }} labels: org.opencontainers.image.source=https://github.com/${{ github.repository }} cache-from: type=gha,scope=${{ inputs.cache_scope }} @@ -92,7 +109,7 @@ runs: provenance: false - uses: ./.github/actions/verify-public-image - if: ${{ inputs.platform == '' && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + if: ${{ inputs.platform == '' && steps.meta.outputs.publish == 'true' }} with: image: ghcr.io/${{ steps.meta.outputs.owner }}/${{ inputs.image_name }}:sha-${{ github.sha }} @@ -115,13 +132,13 @@ runs: platforms: ${{ inputs.platform }} tags: ghcr.io/${{ steps.meta.outputs.owner }}/${{ inputs.image_name }} labels: org.opencontainers.image.source=https://github.com/${{ github.repository }} - outputs: type=image,push-by-digest=true,name-canonical=true,push=${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + outputs: type=image,push-by-digest=true,name-canonical=true,push=${{ steps.meta.outputs.publish == 'true' }} cache-from: type=gha,scope=${{ inputs.cache_scope }}-${{ steps.plat.outputs.suffix }} cache-to: type=gha,mode=max,scope=${{ inputs.cache_scope }}-${{ steps.plat.outputs.suffix }},ignore-error=true provenance: false - name: Record digest - if: inputs.platform != '' && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + if: inputs.platform != '' && steps.meta.outputs.publish == 'true' shell: bash run: | mkdir -p "$RUNNER_TEMP/digests" @@ -130,7 +147,7 @@ runs: DIGEST: ${{ steps.digest-build.outputs.digest }} - uses: actions/upload-artifact@v4 - if: inputs.platform != '' && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + if: inputs.platform != '' && steps.meta.outputs.publish == 'true' with: name: digests-${{ inputs.image_name }}-${{ steps.plat.outputs.suffix }} path: ${{ runner.temp }}/digests/* diff --git a/.github/actions/merge-image/action.yml b/.github/actions/merge-image/action.yml index 7635530af..8f5d990d0 100644 --- a/.github/actions/merge-image/action.yml +++ b/.github/actions/merge-image/action.yml @@ -43,18 +43,25 @@ runs: owner=${OWNER,,} echo "owner=$owner" >> "$GITHUB_OUTPUT" repo="ghcr.io/$owner/$IMAGE" - tags=(-t "$repo:latest" -t "$repo:sha-$SHA") - if [ -n "$EXTRA_TAG" ]; then tags+=(-t "$repo:$EXTRA_TAG"); fi + tags=(-t "$repo:sha-$SHA") + # Moving tags only from main; a branch publish is reachable by commit. + if [ "$REF" = refs/heads/main ]; then + tags+=(-t "$repo:latest") + if [ -n "$EXTRA_TAG" ]; then tags+=(-t "$repo:$EXTRA_TAG"); fi + fi sources=() for d in *; do sources+=("$repo@sha256:$d"); done [ "${#sources[@]}" -ge 2 ] || { echo "expected a digest per platform, got: ${sources[*]}" >&2; exit 1; } docker buildx imagetools create "${tags[@]}" "${sources[@]}" - docker buildx imagetools inspect "$repo:latest" + docker buildx imagetools inspect "$repo:sha-$SHA" + echo "### $IMAGE" >> "$GITHUB_STEP_SUMMARY" + docker buildx imagetools inspect "$repo:sha-$SHA" --format '`{{.Manifest.Digest}}`' >> "$GITHUB_STEP_SUMMARY" env: OWNER: ${{ github.repository_owner }} IMAGE: ${{ inputs.image_name }} SHA: ${{ github.sha }} EXTRA_TAG: ${{ inputs.extra_tag }} + REF: ${{ github.ref }} - uses: ./.github/actions/verify-public-image with: diff --git a/.github/workflows/build-governance-interceptor.yml b/.github/workflows/build-governance-interceptor.yml index 254f73646..53de4c863 100644 --- a/.github/workflows/build-governance-interceptor.yml +++ b/.github/workflows/build-governance-interceptor.yml @@ -19,6 +19,11 @@ on: - tests/charts/test_governance_interceptor_image.py - image-builder-charts/helm/governance-interceptor-image/** workflow_dispatch: + inputs: + publish: + description: Publish this branch's build as ghcr.io//governance-interceptor:sha- + type: boolean + default: false permissions: contents: read @@ -31,7 +36,7 @@ jobs: # One native build per architecture (no QEMU), each pushed by digest; the # merge job joins them into one multi-arch :latest / :sha- tag. build: - if: github.event_name == 'pull_request' || github.ref != 'refs/heads/main' + if: github.event_name == 'pull_request' || (github.ref != 'refs/heads/main' && !inputs.publish) strategy: &platforms # Each architecture reports its own result; merge still needs both. fail-fast: false @@ -78,7 +83,8 @@ jobs: # the interceptor must match the SAW gateways' OpenShell release. extra_tag: ${{ steps.params.outputs.openshell_ref }} platform: ${{ matrix.platform }} - registry_token: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && secrets.GITHUB_TOKEN || '' }} + publish: ${{ inputs.publish && 'true' || '' }} + registry_token: ${{ ((github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish) && secrets.GITHUB_TOKEN || '' }} # Compile the OpenShift build source too, including its behavioral # tests, on each architecture. This targets the builder stage; no @@ -121,7 +127,7 @@ jobs: provenance: false publish: - if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + if: (github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish permissions: {contents: read, packages: write} strategy: *platforms runs-on: ${{ matrix.runner }} @@ -130,7 +136,7 @@ jobs: merge: needs: publish permissions: {contents: read, packages: write} - if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + if: (github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/build-kubernetes-runtime.yml b/.github/workflows/build-kubernetes-runtime.yml index 36a45f813..b9a449981 100644 --- a/.github/workflows/build-kubernetes-runtime.yml +++ b/.github/workflows/build-kubernetes-runtime.yml @@ -29,6 +29,11 @@ on: - .github/actions/merge-image/** - .github/actions/verify-public-image/** workflow_dispatch: + inputs: + publish: + description: Publish this branch's build as ghcr.io//saw-kubernetes-runtime:sha- + type: boolean + default: false permissions: contents: read @@ -39,7 +44,7 @@ concurrency: jobs: build: - if: github.event_name == 'pull_request' || github.ref != 'refs/heads/main' + if: github.event_name == 'pull_request' || (github.ref != 'refs/heads/main' && !inputs.publish) strategy: &platforms fail-fast: false matrix: @@ -58,9 +63,10 @@ jobs: dockerfile: kubernetes-runtime/Containerfile cache_scope: saw-kubernetes-runtime platform: ${{ matrix.platform }} - registry_token: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && secrets.GITHUB_TOKEN || '' }} + publish: ${{ inputs.publish && 'true' || '' }} + registry_token: ${{ ((github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish) && secrets.GITHUB_TOKEN || '' }} publish: - if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + if: (github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish permissions: {contents: read, packages: write} strategy: *platforms runs-on: ${{ matrix.runner }} @@ -69,7 +75,7 @@ jobs: merge: needs: publish permissions: {contents: read, packages: write} - if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + if: (github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/build-openclaw-image.yml b/.github/workflows/build-openclaw-image.yml new file mode 100644 index 000000000..a64d9f7d5 --- /dev/null +++ b/.github/workflows/build-openclaw-image.yml @@ -0,0 +1,106 @@ +name: Build the OpenShift-ready OpenClaw image + +# Publishes ghcr.io//saw-openclaw (linux/amd64 and +# linux/arm64): the notebook BOM's stock OpenClaw image with /sandbox +# searchable by OpenShift namespace UIDs (images/saw-openclaw/Containerfile). +# Pin the published digest in containerDefaults.profileImageOverrides. + +on: + push: + branches: [main] + paths: + - images/saw-openclaw/** + - charts/saw-bom/profiles/data-science/default/sandbox.yaml + - .github/workflows/build-openclaw-image.yml + - .github/actions/build-push-image/** + - .github/actions/merge-image/** + pull_request: + paths: + - images/saw-openclaw/** + - charts/saw-bom/profiles/data-science/default/sandbox.yaml + - .github/workflows/build-openclaw-image.yml + - .github/actions/build-push-image/** + - .github/actions/merge-image/** + workflow_dispatch: + inputs: + publish: + description: Publish this branch's build as ghcr.io//saw-openclaw:sha- + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: build-openclaw-image-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + if: github.event_name == 'pull_request' || (github.ref != 'refs/heads/main' && !inputs.publish) + strategy: &platforms + fail-fast: false + matrix: + include: + - platform: linux/amd64 + runner: ubuntu-latest + - platform: linux/arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + steps: &build_steps + - uses: actions/checkout@v4 + - name: Resolve the stock image and its user + id: source + env: + PLATFORM: ${{ matrix.platform }} + run: | + set -euo pipefail + image=$(yq -r '.spec.sandboxes[] | select(.name == "notebook") | .image' charts/saw-bom/profiles/data-science/default/sandbox.yaml) + [[ "$image" =~ ^[a-z0-9][a-z0-9./:_-]+@sha256:([0-9a-f]{64})$ ]] || { echo "notebook image must be pinned by digest: $image" >&2; exit 1; } + digest="${BASH_REMATCH[1]}" + user=$(docker buildx imagetools inspect "$image" --format '{{json .Image}}' | + jq -er --arg p "$PLATFORM" 'if has("config") then .config.User else .[$p].config.User end | select(type == "string" and length > 0)') + [[ "$user" =~ ^[A-Za-z0-9_-]+(:[A-Za-z0-9_-]+)?$ && "${user%%:*}" != root && "${user%%:*}" != 0 ]] || { echo "stock image must declare a non-root USER: $user" >&2; exit 1; } + { + echo "image=$image" + echo "user=$user" + echo "tag=src-${digest:0:12}" + } >> "$GITHUB_OUTPUT" + - uses: ./.github/actions/build-push-image + with: + image_name: saw-openclaw + context: images/saw-openclaw + dockerfile: images/saw-openclaw/Containerfile + cache_scope: saw-openclaw + platform: ${{ matrix.platform }} + publish: ${{ inputs.publish && 'true' || '' }} + build_args: | + SOURCE_IMAGE=${{ steps.source.outputs.image }} + IMAGE_USER=${{ steps.source.outputs.user }} + registry_token: ${{ ((github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish) && secrets.GITHUB_TOKEN || '' }} + + publish: + if: (github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish + permissions: {contents: read, packages: write} + strategy: *platforms + runs-on: ${{ matrix.runner }} + steps: *build_steps + + merge: + needs: publish + permissions: {contents: read, packages: write} + if: (github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Source tag + id: source + run: | + image=$(yq -r '.spec.sandboxes[] | select(.name == "notebook") | .image' charts/saw-bom/profiles/data-science/default/sandbox.yaml) + digest="${image##*@sha256:}" + echo "tag=src-${digest:0:12}" >> "$GITHUB_OUTPUT" + - uses: ./.github/actions/merge-image + with: + image_name: saw-openclaw + extra_tag: ${{ steps.source.outputs.tag }} + registry_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/Makefile b/Makefile index 7405b836e..96d8c9ff5 100644 --- a/Makefile +++ b/Makefile @@ -8,7 +8,9 @@ include Makefile-quickstart # SAW: a default StorageClass must exist before the GitOps apply provisions # the VM disks (they set no storageClassName). Interactive on a TTY; offers to # reuse an existing class or enable HPP. See scripts/storage-class-check.sh. -pattern-install: storage-class-check +# saw-init adds the container-mode checks when overrides/saw-users.yaml has +# container or kata users (scripts/saw-init.sh). +pattern-install: saw-init # Bootstrap stock GitOps before the framework selects its Argo CD namespace. .PHONY: prepare-gitops diff --git a/Makefile-quickstart b/Makefile-quickstart index df2eb1e81..4dcd8145e 100644 --- a/Makefile-quickstart +++ b/Makefile-quickstart @@ -119,7 +119,7 @@ endif governance-interceptor-build governance-interceptor-build-local \ keycloak-deploy keycloak-delete keycloak-check keycloak-issuer \ keycloak-register keycloak-redirects keycloak-redirects-sync \ - keycloak-passwords keycloak-harden keycloak-session-max keycloak-add-users keycloak-add-user keycloak-password keycloak-reset-password \ + keycloak-passwords keycloak-harden keycloak-session-max keycloak-add-users keycloak-add-user keycloak-password keycloak-reset-password keycloak-user-info saw-init \ login whoami logout saw-create saw-configure saw-list saw-logs saw-status \ saw-restart saw-restart-pending saw-vm-ssh saw-ssh saw-tui saw-gui saw-delete \ sandbox-pre-delete quickstart-delete status test test-deployment test-dependencies test-pattern-e2e test-pattern-e2e-install test-pattern-e2e-live test-pattern-e2e-cleanup test-harness-e2e lint \ @@ -140,6 +140,9 @@ quickstart-prereqs-check: ## Check tools, capacity, CNV, and RHBK before quickst storage-class-check: ## Ensure a default StorageClass exists for the VM disks (offers to reuse one or enable HPP) @$(SCRIPTS_DIR)/storage-class-check.sh +saw-init: storage-class-check ## Prepare the cluster before install: storage, and for container/kata users the APIs, a shared-filesystem class (offers EFS on AWS) and the runtime image + @$(SCRIPTS_DIR)/saw-init.sh + check-oidc-ca: ## Check if the OIDC issuer needs a CA bundle @$(SCRIPTS_DIR)/check-oidc-ca.sh @@ -372,6 +375,10 @@ keycloak-password: ## Copy a user's password to the clipboard / name its Secret @if [ -z "$(KC_USER)" ]; then echo "Error: KC_USER is required. Pass KC_USER=alice." >&2; exit 1; fi @$(SCRIPTS_DIR)/keycloak-users.sh password $(if $(SHOW),--show) "$(KC_USER)" +keycloak-user-info: ## Show a user's Keycloak subject (ownerSubject), enabled flag and email (KC_USER=alice) + @if [ -z "$(KC_USER)" ]; then echo "Error: KC_USER is required. Pass KC_USER=alice." >&2; exit 1; fi + @$(KC_USERS_ENV) $(SCRIPTS_DIR)/keycloak-users.sh user-info "$(KC_USER)" + keycloak-reset-password: ## Reset one user's password in a Secret (KC_USER=alice) @if [ -z "$(KC_USER)" ]; then echo "Error: KC_USER is required. Pass KC_USER=alice." >&2; exit 1; fi @$(SCRIPTS_DIR)/keycloak-users.sh reset-password "$(KC_USER)" @@ -435,6 +442,7 @@ check-container-topology: ## Compare the reviewed site network overlay with live saw-create: .check-saw-name .check-deployment-mode ## Provision one SAW using DEPLOYMENT_MODE=vm, container or kata @if [ "$(DEPLOYMENT_MODE)" != vm ]; then \ + $(SCRIPTS_DIR)/saw-init.sh && \ $(or $(PYTHON),uv run --locked python) $(SCRIPTS_DIR)/container-workspace.py apply; \ else $(SCRIPTS_DIR)/openshell-saw-create.sh; fi diff --git a/README.md b/README.md index 55f77877b..ed05472c2 100644 --- a/README.md +++ b/README.md @@ -284,6 +284,15 @@ make check-oidc-ca # docs/credential-isolation.md for migrations and required key rotation. # See docs/container-images.md for published images, releases and mirroring. +# 5d. Prepare the cluster. Checks the default StorageClass and, when +# overrides/saw-users.yaml has container or kata users, the container-mode +# APIs, a shared-filesystem (ReadWriteMany) StorageClass (with none, it stops and +# lists the options; SAW_SHARED_STORAGE=efs offers EFS on AWS, and +# SAW_SHARED_STORAGE=nfs creates a small in-cluster NFS server for dev/demo only) +# and the runtime image in overrides/saw-container-defaults.yaml. +# `make install` runs it too; running it first lets you answer its prompts. +make saw-init + # 6. Deploy the pattern (runs inside the VP utility container) # NOTE: The deploying branch must exist on your fork (origin): the Pattern # CR points Argo CD at it, and every later change (steps 7+) is a push there. @@ -295,15 +304,64 @@ make check-oidc-ca # A user's webSearch.enabled in overrides/saw-users.yaml overrides the global switch. # 7. Add your first user. The pattern ships overrides/saw-users.yaml with -# `users: []`, so no workspace VM exists yet. Add an entry for the account -# (a lowercase DNS label, at most 19 characters), push it to the deploying -# branch, and create the Keycloak account; Argo CD then builds saw-. +# `users: []`. Add an entry (the name is a lowercase DNS label, at most 19 +# characters) and push it to the deploying branch; Argo CD then builds +# saw-. Pick one of 7a (VM), 7b (container) or 7c (Kata). +# +# 7a. VM workspace (the default). # users: # - name: alice git add overrides/saw-users.yaml && git commit -m "Add alice" && git push make keycloak-add-users # creates the account; password in a Secret oc -n vp-gitops get application saw-alice # wait until Synced/Healthy make saw-logs OPENSHELL_SAW_NAME=alice # until "apply: Done" +# +# 7b. Container workspace. Once per cluster, after make saw-init (step 5d) +# and once Keycloak is up, generate the network overlay. It holds this +# cluster's API, DNS and Keycloak addresses, so it is not in this repository: +make container-topology > overrides/container-network.yaml +# In values-prod.yaml, list it after /overrides/saw-users.yaml in saw-users' +# extraValueFiles (and in openshell-rhdh's, if users create container +# workspaces in the portal), then commit and push both on your deploying branch: +git add overrides/container-network.yaml values-prod.yaml +git commit -m "Add this cluster's network overlay" && git push +# Without it, saw-users fails to render once a container user has an +# ownerSubject ("projection requires ... explicit API/DNS egress"). +# Enrollment is off in overrides/saw-container-defaults.yaml, so a new +# workspace deploys only its foundation until an operator reviews it +# (docs/container-installation.md). On a dev or demo cluster, list +# overrides/saw-container-demo.yaml after it to enroll on first observation. +# The entry needs the owner's Keycloak subject, so create the account first: +make keycloak-add-users +make keycloak-user-info KC_USER=alice # copy the subject (ownerSubject) +# users: +# - name: alice +# ownerSubject: +# profiles: [custom-inference] +# customInferenceURL: https:///v1 # custom-inference only +# modelInputs: {inference.model: } # custom-inference only +# values: {deployment: {mode: container}} +# Until ownerSubject is set the entry waits (ConfigMap saw-users-awaiting-owner) +# without blocking other users. +git add overrides/saw-users.yaml && git commit -m "Add alice (container)" && git push +oc -n vp-gitops get applications.argoproj.io | grep -E 'saw-alice|saw-c-' # Synced/Healthy +oc -n saw-alice get sandboxes.agents.x-k8s.io,pods # until the sandbox Pod is Ready +# See docs/container-installation.md#minimal-static-entries. +# +# 7c. Kata workspace. As 7b, on a cluster with OpenShift sandboxed containers +# and a RuntimeClass labelled openshell.ai/sandbox-attachable=true +# (docs/kata-workspaces.md). Set mode: kata and bind the reviewed class; its +# UID and placement digest come from the live object (see that guide): +# users: +# - name: alice +# ... # as 7b +# values: {deployment: {mode: kata}} +# containerSites: +# alice: +# kataRuntimeClass: {name: saw-kata, uid: , sha256: } +# Then push and watch it as in 7b. Kata sandboxes can take several minutes +# to start. +# # Without a fork: users create their own workspace in the self-service # portal (Red Hat Developer Hub, docs/rhdh-user-guide.md), or create one # outside GitOps with `make saw-create OPENSHELL_SAW_NAME=alice` (Option B). @@ -328,8 +386,9 @@ the command then reports a failure. Add or remove one `users:` entry in `overrides/saw-users.yaml` and push; Argo CD creates or removes `saw-`. Each user's virtual machine is named after them, in namespace `saw-` (Alice's machine is `alice` in `saw-alice`, not `openshell-saw`), the same layout as `make saw-create OPENSHELL_SAW_NAME=alice`. Set `OPENSHELL_SAW_NAME` to the user name; `SAW_NS` defaults to `saw-`. -Removing an entry deletes that user's Argo apps and leaves the VM running. +Removing a VM entry deletes that user's Argo apps and leaves the VM running. To delete the namespace and the VM as well, first set `pruneOnRemove: true` on that user's entry and push, then remove the entry and push. +Container and Kata entries default to `pruneOnRemove: true`, so removing one also removes its workspace; its audit history namespace is kept. Upgrading an install that still has the `openshell-saw` VM: see [Upgrading from the single-user layout](docs/deployment-guide.md#upgrading-from-the-single-user-layout). #### Option B: Quickstart (manual, step-by-step) @@ -354,6 +413,15 @@ make quickstart-prereqs-check # This check does not change the cluster. It can save ingress-ca.pem here. # make images-mirror enables the registry route. +# 4b. Container or kata workspaces only (DEPLOYMENT_MODE=container|kata): these +# also need OpenShift GitOps, since their components are Argo CD Applications +# even here. Prepare the cluster: the container-mode APIs, a shared-filesystem +# (ReadWriteMany) StorageClass and the runtime image. With no such class it +# stops and lists the options (SAW_SHARED_STORAGE=efs offers EFS on AWS; +# SAW_SHARED_STORAGE=nfs creates a small in-cluster NFS server, dev/demo only). +# `make saw-create` runs it too; running it first lets you answer its prompts. +make saw-init + # 5. Generate SSH keys make ssh-key-generate diff --git a/charts/governance-interceptor/values.yaml b/charts/governance-interceptor/values.yaml index 5b111ade4..0579b70b1 100644 --- a/charts/governance-interceptor/values.yaml +++ b/charts/governance-interceptor/values.yaml @@ -16,10 +16,10 @@ enabled: true # The pattern sets global.governance.engine (values-global.yaml), which wins. engine: interceptor -# Public NVIDIA/OpenShell v0.1.6 interceptor, built at repository fe19b46. -# Multi-arch index: linux/amd64 and linux/arm64. See the release record for -# build/source commits, architecture manifests and clean-install acceptance. -image: "ghcr.io/validatedpatterns-sandbox/governance-interceptor@sha256:19f145ac163822bca6d406898975b5b770b75b196fa0bee0bc86b108fad213b3" +# NVIDIA/OpenShell v0.1.6 interceptor with the SAW extension at this branch, +# which admits the container runtime's mTLS operator (118b4cfa). linux/amd64. +# Replace with the multi-arch main publish once this reaches main. +image: "ghcr.io/sauagarwa/governance-interceptor@sha256:7775d7247c60bce6f333687d70cb64b85be109685dd806db5e332e70a88f7722" # gRPC listen port port: 18081 # Provider profiles a deployment adds to the shipped catalog: a ConfigMap of diff --git a/charts/governance-policy/tool-actions.yaml b/charts/governance-policy/tool-actions.yaml index 3becbac16..029dc993c 100644 --- a/charts/governance-policy/tool-actions.yaml +++ b/charts/governance-policy/tool-actions.yaml @@ -42,24 +42,53 @@ rules: - openclaw cron get - openclaw cron show - openclaw cron runs + - openclaw cron --help + - openclaw cron add --help + - openclaw cron create --help + - openclaw cron edit --help + - openclaw cron rm --help + - openclaw cron remove --help + - openclaw cron delete --help + - openclaw cron enable --help + - openclaw cron disable --help + - openclaw cron run --help - openclaw automations list - openclaw automations status - openclaw automations get - openclaw automations show - openclaw automations runs + - openclaw automations --help + - openclaw automations add --help + - openclaw automations create --help + - openclaw automations edit --help + - openclaw automations rm --help + - openclaw automations remove --help + - openclaw automations delete --help + - openclaw automations enable --help + - openclaw automations disable --help + - openclaw automations run --help + # "Allow always" skips the card for later automation changes until the + # gateway restarts; each call is still audited. - id: exec-openclaw-automation-change tool: exec action: approval + allowAlways: true whenCommandMatches: - openclaw cron add + - openclaw cron create - openclaw cron edit - openclaw cron rm + - openclaw cron remove + - openclaw cron delete - openclaw cron enable - openclaw cron disable - openclaw cron run - openclaw automations add + - openclaw automations create - openclaw automations edit - openclaw automations rm + - openclaw automations remove + - openclaw automations delete - openclaw automations enable - openclaw automations disable - openclaw automations run diff --git a/charts/openshell-keycloak/files/relay-provisioner.py b/charts/openshell-keycloak/files/relay-provisioner.py new file mode 100644 index 000000000..0102d0218 --- /dev/null +++ b/charts/openshell-keycloak/files/relay-provisioner.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Keep the workspace relay registrar in place for container-mode SAW sites. + +Each container workspace's browser relay registers its own Keycloak client +(charts/saw-workspace-relay/files/identity.py). It does that with the +registrar this helper maintains, so no relay Job needs the master admin: + + - the client scope SCOPE (OpenShell audience plus the openshell-user role), + allowed for authenticated dynamic client registration; + - the confidential client NAME whose service account holds only + realm-management/create-client in REALM; + - its credential in the Secret NAME in this namespace, which relay Jobs mount. + +Runs in Keycloak's namespace and re-verifies every INTERVAL seconds, so a +cluster comes up without a manual step and drift is repaired. The Secret is +created here, not by Helm, so a GitOps self-heal never clears the generated +credential. Errors are retried; nothing is deleted. + +Env: REALM, KEYCLOAK_NAME, KEYCLOAK_NAMESPACE, KC_URL (empty: discover the +operator's HTTPS Route), CA_FILE, ADMIN_DIR (username, password), AUDIENCE, +INTERVAL. Standard library only. +""" +import base64 +import json +import os +import secrets +import ssl +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +import saw_tls + +SA = "/var/run/secrets/kubernetes.io/serviceaccount" +NAME = "saw-relay-provisioner" +SCOPE = "saw-workspace-relay" +LABEL = "saw.redhat.com/component" + + +def log(msg): + print(f"[relay-provisioner] {msg}", flush=True) + + +class HttpError(OSError): + """An OSError so saw_tls.tls_context treats it as a failed cluster read.""" + + def __init__(self, code, msg): + super().__init__(msg) + self.code = code + + +def call(url, method="GET", *, token=None, body=None, form=None, ctx=None, patch=False): + headers, data = {}, None + if form is not None: + headers["Content-Type"] = "application/x-www-form-urlencoded" + data = urllib.parse.urlencode(form).encode() + if body is not None: + headers["Content-Type"] = "application/merge-patch+json" if patch else "application/json" + data = json.dumps(body).encode() + if token: + headers["Authorization"] = "Bearer " + token + opener = urllib.request.build_opener(saw_tls.NoRedirect(), urllib.request.HTTPSHandler(context=ctx)) + try: + with opener.open(urllib.request.Request(url, data=data, method=method, headers=headers), + timeout=20) as response: + raw = response.read() + except urllib.error.HTTPError as exc: + raise HttpError(exc.code, f"HTTP {exc.code} at {urllib.parse.urlsplit(url).path}") from None + return json.loads(raw) if raw else None + + +class Kube: + def __init__(self): + host, port = os.environ["KUBERNETES_SERVICE_HOST"], os.environ.get("KUBERNETES_SERVICE_PORT", "443") + self.base = f"https://{host}:{port}" + self.ctx = ssl.create_default_context(cafile=f"{SA}/ca.crt") + + def __call__(self, path, method="GET", body=None, patch=False): + token = open(f"{SA}/token", encoding="utf-8").read().strip() + return call(self.base + path, method, token=token, body=body, ctx=self.ctx, patch=patch) + + def get(self, path): + return self(path) + + +def credential(kube, namespace, issuer): + """The registrar's client ID and secret, kept in a Secret only this helper writes.""" + path = f"/api/v1/namespaces/{namespace}/secrets/{NAME}" + fresh = {"client-id": NAME, "client-secret": secrets.token_urlsafe(40), "issuer": issuer} + try: + state = kube(path) + except HttpError as exc: + if exc.code != 404: + raise + kube(f"/api/v1/namespaces/{namespace}/secrets", "POST", { + "apiVersion": "v1", "kind": "Secret", "type": "Opaque", + "metadata": {"name": NAME, "labels": {LABEL: NAME}}, "stringData": fresh}) + log(f"Secret {NAME} created") + state = kube(path) + if (state["metadata"].get("labels") or {}).get(LABEL) != NAME: + raise ValueError(f"Secret {NAME} exists but is not this helper's") + if not state.get("data"): + state = kube(path, "PATCH", {"metadata": {"resourceVersion": state["metadata"]["resourceVersion"]}, + "stringData": fresh}, patch=True) + values = {k: base64.b64decode(v, validate=True).decode() for k, v in state["data"].items()} + if set(values) != {"issuer", "client-id", "client-secret"} or values["client-id"] != NAME: + raise ValueError(f"Secret {NAME} has unexpected contents") + if values["issuer"] != issuer: + raise ValueError(f"Secret {NAME} is for issuer {values['issuer']}, not {issuer}") + return values + + +def setup(kube, ctx, issuer, namespace): + base, realm = issuer.rsplit("/realms/", 1) + admin = os.environ["ADMIN_DIR"] + token = call(base + "/realms/master/protocol/openid-connect/token", "POST", ctx=ctx, form={ + "client_id": "admin-cli", "grant_type": "password", + "username": open(os.path.join(admin, "username"), encoding="utf-8").read().strip(), + "password": open(os.path.join(admin, "password"), encoding="utf-8").read().strip()})["access_token"] + + def kc(path, method="GET", body=None): + return call(base + "/admin/realms/" + realm + path, method, token=token, body=body, ctx=ctx) + + if kc("") is None: + raise ValueError(f"realm {realm} is not imported yet") + values = credential(kube, namespace, issuer) + audience = os.environ["AUDIENCE"] + mappers = [ + {"name": "relay-audience", "protocol": "openid-connect", "protocolMapper": "oidc-audience-mapper", + "config": {"included.client.audience": audience, "access.token.claim": "true"}}, + {"name": "relay-user", "protocol": "openid-connect", "protocolMapper": "oidc-hardcoded-claim-mapper", + "config": {"claim.name": "realm_access.roles", "claim.value": '["openshell-user"]', + "jsonType.label": "JSON", "access.token.claim": "true"}}] + if not any(s["name"] == SCOPE for s in kc("/client-scopes")): + kc("/client-scopes", "POST", {"name": SCOPE, "protocol": "openid-connect", + "description": "SAW registration-scoped workspace relay", + "protocolMappers": mappers}) + log(f"client scope {SCOPE} created") + scope = next(s for s in kc("/client-scopes") if s["name"] == SCOPE) + actual = kc("/client-scopes/" + scope["id"] + "/protocol-mappers/models") + if {m["name"] for m in actual} != {m["name"] for m in mappers}: + raise ValueError("unexpected relay scope mappers") + for desired in mappers: + found = next(m for m in actual if m["name"] == desired["name"]) + if found["protocolMapper"] != desired["protocolMapper"] or \ + any(found["config"].get(k) != v for k, v in desired["config"].items()): + raise ValueError("foreign relay scope configuration") + # Allow this pre-approved scope for authenticated registration. Clients + # never author their own role or audience mappers. + policies = kc("/components?" + urllib.parse.urlencode( + {"type": "org.keycloak.services.clientregistration.policy.ClientRegistrationPolicy"})) + allowed = [p for p in policies if p.get("providerId") == "allowed-client-templates" + and p.get("subType") == "authenticated"] + if len(allowed) != 1: + raise ValueError("expected one authenticated client-scope registration policy") + policy = allowed[0] + permitted = policy.setdefault("config", {}).setdefault("allowed-client-scopes", []) + if SCOPE not in permitted: + permitted.append(SCOPE) + kc("/components/" + policy["id"], "PUT", policy) + log(f"{SCOPE} allowed for authenticated registration") + + def lookup(client_id): + return next((c for c in kc("/clients?" + urllib.parse.urlencode({"clientId": client_id})) + if c["clientId"] == client_id), None) + settings = dict(clientId=NAME, enabled=True, protocol="openid-connect", publicClient=False, + serviceAccountsEnabled=True, standardFlowEnabled=False, implicitFlowEnabled=False, + directAccessGrantsEnabled=False, fullScopeAllowed=False) + if not lookup(NAME): + kc("/clients", "POST", {**settings, "secret": values["client-secret"], "attributes": {LABEL: NAME}, + "defaultClientScopes": ["basic", "roles"], "optionalClientScopes": []}) + log(f"client {NAME} created") + client = kc("/clients/" + lookup(NAME)["id"]) + if client.get("attributes", {}).get(LABEL) != NAME and \ + client.get("attributes", {}).get("saw.component") != NAME: + raise ValueError("refusing to adopt a foreign provisioning client") + if any(client.get(k) != v for k, v in settings.items()): + raise ValueError("provisioning client settings drifted") + prefix = "/clients/" + client["id"] + management = lookup("realm-management")["id"] + role = kc("/clients/" + management + "/roles/create-client") + user = kc(prefix + "/service-account-user")["id"] + for path in [prefix + "/scope-mappings/clients/" + management, + "/users/" + user + "/role-mappings/clients/" + management]: + current = kc(path) + if {r["name"] for r in current} - {"create-client"}: + raise ValueError("provisioner has unexpected realm-management privileges") + if not current: + kc(path, "POST", [role]) + result = call(issuer + "/protocol/openid-connect/token", "POST", ctx=ctx, form={ + "client_id": NAME, "client_secret": values["client-secret"], "grant_type": "client_credentials"}) + part = result["access_token"].split(".")[1] + claim = json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))) + if set(claim.get("resource_access", {}).get("realm-management", {}).get("roles", [])) != {"create-client"}: + raise ValueError("unexpected effective registrar privilege") + + +def main(argv): + kube = Kube() + namespace, name = os.environ["KEYCLOAK_NAMESPACE"], os.environ["KEYCLOAK_NAME"] + realm, interval = os.environ["REALM"], int(os.environ.get("INTERVAL", "300")) + once = "--once" in argv + while True: + try: + url = os.environ.get("KC_URL") or saw_tls.keycloak_url(name, namespace, kube.get) + ctx = saw_tls.tls_context(url, kube.get, log, os.environ.get("CA_FILE") or None) + issuer = url.rstrip("/") + "/realms/" + realm + setup(kube, ctx, issuer, namespace) + log(f"registrar verified for {issuer}: create-client only") + wait = interval + except (HttpError, OSError, KeyError, ValueError) as exc: + if once: + raise + log(f"WARN: {exc}; retrying in 15s") + wait = 15 + if once: + return 0 + time.sleep(wait) + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/charts/openshell-keycloak/templates/relay-provisioner.yaml b/charts/openshell-keycloak/templates/relay-provisioner.yaml new file mode 100644 index 000000000..cbdb96f5a --- /dev/null +++ b/charts/openshell-keycloak/templates/relay-provisioner.yaml @@ -0,0 +1,198 @@ +{{- /* +The workspace relay registrar (files/relay-provisioner.py). Container-mode +browser relays register their own Keycloak clients with the credential this +keeps in the saw-relay-provisioner Secret, so no relay Job needs the master +admin. Re-verified every interval; the helper creates the Secret itself, so a +GitOps self-heal never clears the generated credential. +*/ -}} +{{- if .Values.relayProvisioner.enabled }} +{{- $r := .Values.relayProvisioner }} +{{- $kc := .Values.keycloak.existing | default .Values.keycloak.name }} +{{- if and $r.keycloakUrl (not (hasPrefix "https://" $r.keycloakUrl)) }} +{{- fail "relayProvisioner.keycloakUrl must use HTTPS" }} +{{- end }} +{{- $name := "saw-relay-provisioner" }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ $name }} + labels: + app.kubernetes.io/name: {{ $name }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ $name }} + labels: + app.kubernetes.io/name: {{ $name }} +rules: + # Create cannot be limited by name; read and update only its own Secret. + - apiGroups: [""] + resources: ["secrets"] + verbs: ["create"] + - apiGroups: [""] + resources: ["secrets"] + resourceNames: [{{ $name | quote }}] + verbs: ["get", "patch"] + - apiGroups: ["route.openshift.io"] + resources: ["routes"] + verbs: ["list"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ $name }} + labels: + app.kubernetes.io/name: {{ $name }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ $name }} +subjects: + - kind: ServiceAccount + name: {{ $name }} + namespace: {{ .Release.Namespace }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ $name }}-{{ .Release.Namespace }} + labels: + app.kubernetes.io/name: {{ $name }} +rules: + - apiGroups: ["config.openshift.io"] + resources: ["ingresses"] + resourceNames: ["cluster"] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ $name }}-{{ .Release.Namespace }} + labels: + app.kubernetes.io/name: {{ $name }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ $name }}-{{ .Release.Namespace }} +subjects: + - kind: ServiceAccount + name: {{ $name }} + namespace: {{ .Release.Namespace }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ $name }}-{{ .Release.Namespace }} + namespace: openshift-config-managed +rules: + - apiGroups: [""] + resources: ["configmaps"] + resourceNames: ["default-ingress-cert"] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ $name }}-{{ .Release.Namespace }} + namespace: openshift-config-managed +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ $name }}-{{ .Release.Namespace }} +subjects: + - kind: ServiceAccount + name: {{ $name }} + namespace: {{ .Release.Namespace }} +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ $name }}-scripts + labels: + app.kubernetes.io/name: {{ $name }} +data: + ca-bundle.crt: | +{{ $r.caBundle | default "" | indent 4 }} + saw_tls.py: | +{{ .Files.Get "files/saw_tls.py" | indent 4 }} + relay-provisioner.py: | +{{ .Files.Get "files/relay-provisioner.py" | indent 4 }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ $name }} + labels: + app.kubernetes.io/name: {{ $name }} +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app.kubernetes.io/name: {{ $name }} + template: + metadata: + labels: + app.kubernetes.io/name: {{ $name }} + annotations: + checksum/script: {{ print (.Files.Get "files/relay-provisioner.py") (.Files.Get "files/saw_tls.py") ($r.caBundle | default "") | sha256sum }} + spec: + serviceAccountName: {{ $name }} + securityContext: + runAsNonRoot: true + seccompProfile: + type: RuntimeDefault + containers: + - name: provisioner + image: {{ $r.image | quote }} + command: ["python3", "/scripts/relay-provisioner.py"] + env: + - name: KC_URL + value: {{ $r.keycloakUrl | default "" | quote }} + - name: KEYCLOAK_NAME + value: {{ $kc | quote }} + - name: KEYCLOAK_NAMESPACE + value: {{ .Release.Namespace | quote }} + {{- if $r.caBundle }} + - name: CA_FILE + value: /scripts/ca-bundle.crt + {{- end }} + - name: REALM + value: {{ .Values.keycloak.realm | quote }} + - name: AUDIENCE + value: {{ $r.audience | quote }} + - name: ADMIN_DIR + value: /admin + - name: INTERVAL + value: {{ $r.intervalSeconds | quote }} + volumeMounts: + - name: scripts + mountPath: /scripts + readOnly: true + - name: admin + mountPath: /admin + readOnly: true + securityContext: + readOnlyRootFilesystem: true + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + resources: + requests: + cpu: 10m + memory: 48Mi + limits: + memory: 128Mi + volumes: + - name: scripts + configMap: + name: {{ $name }}-scripts + - name: admin + secret: + secretName: {{ $r.adminSecret | default (printf "%s-initial-admin" $kc) }} + items: + - {key: username, path: username} + - {key: password, path: password} +{{- end }} diff --git a/charts/openshell-keycloak/values.yaml b/charts/openshell-keycloak/values.yaml index 64ddcdc5f..bda9815cf 100644 --- a/charts/openshell-keycloak/values.yaml +++ b/charts/openshell-keycloak/values.yaml @@ -144,6 +144,22 @@ redirectRegistrar: hostSuffix: "" intervalSeconds: 15 +# Container-mode workspace relays register their own Keycloak clients with a +# registrar credential (Secret saw-relay-provisioner) that this keeps in place. +# Enable wherever container workspaces may be created. +relayProvisioner: + enabled: false + image: registry.access.redhat.com/ubi9/python-311@sha256:a0bdb55576fc5b8d6704279307817828ef027e1065533ceba133fe9516003a6c + # The OpenShell audience relay tokens carry (the gateway's OIDC client). + audience: openshell-cli + # Empty: discover the operator's -ingress HTTPS Route. + keycloakUrl: "" + # Optional PEM CA for an external/private issuer. + caBundle: "" + # Empty: -initial-admin (the operator's). + adminSecret: "" + intervalSeconds: 300 + # Resolve Pattern user-list owners without placing Keycloak admin credentials # in tenant namespaces. The user-list chart grants this service account patch # access only to each tenant's saw-owner-subject ConfigMap. diff --git a/charts/openshell-rhdh/files/portal.py b/charts/openshell-rhdh/files/portal.py index 5e8c5232a..83ebed6c9 100644 --- a/charts/openshell-rhdh/files/portal.py +++ b/charts/openshell-rhdh/files/portal.py @@ -116,8 +116,8 @@ def public_model_inputs(profile, secrets): return _project(_workspace.public_model_inputs, profile, secrets) -def approved_endpoint(profile, secrets, boundary): - return _project(_workspace.approved_endpoint, profile, secrets, boundary) +def approved_endpoint(profile, secrets): + return _project(_workspace.approved_endpoint, profile, secrets) def enrolled_site(site, workspace, read): @@ -394,17 +394,84 @@ def check_user(user): PROVISIONABLE_MODES = ("vm",) -def container_site(user): - """Trusted site inventory, never names/URLs supplied by the request.""" +def _deep_merge(base, over): + out = json.loads(json.dumps(base)) + for key, value in over.items(): + out[key] = (_deep_merge(out[key], value) if isinstance(value, dict) and isinstance(out.get(key), dict) + else json.loads(json.dumps(value))) + return out + + +def container_defaults(): + """Operator-owned shared site (saw-users containerDefaults); empty when unset.""" + defaults = json.loads(os.environ.get("SAW_CONTAINER_DEFAULTS") or "{}") + return defaults if isinstance(defaults, dict) else {} + + +_OWNER_SUBJECTS = {} + + +def owner_subject(user): + """The owner's enabled Keycloak id from the owner directory, or "" when unavailable.""" + if user not in _OWNER_SUBJECTS: + url = os.environ.get("KEYCLOAK_URL", "") + try: + with open(env("KEYCLOAK_SECRET_FILE"), encoding="utf-8") as credential: + ids = keycloak_user_ids(url.rstrip("/"), env("KEYCLOAK_REALM"), env("KEYCLOAK_CLIENT_ID"), + credential.read().strip(), [user], + os.environ.get("KEYCLOAK_SKIP_VERIFY") == "true") if url else {} + except (PortalError, OSError, ValueError, KeyError) as exc: + log(f"WARN: owner lookup for {user} failed ({exc})") + return "" + if not ids.get(user): + return "" # not cached: the account may be created later + _OWNER_SUBJECTS[user] = ids[user] + return _OWNER_SUBJECTS[user] + + +def container_site(user, subject=None): + """Trusted site inventory, never names/URLs supplied by the request. + + An owner's own containerSites entry is layered over the shared + containerDefaults. A site from the defaults takes the owner's subject from + the registry entry or the owner directory, and unset chart revisions follow + the pattern branch, as for saw-users entries.""" sites = json.loads(os.environ.get("SAW_CONTAINER_SITES", "{}")) site = sites.get(user) + defaults = container_defaults() + if defaults and (site is None or isinstance(site, dict)): + site = _deep_merge(defaults, site or {}) + if not site.get("subject"): + site["subject"] = subject or owner_subject(user) + # Only an autoApprove site follows the pattern branch; a reviewed site + # pins commit SHAs, and preflight rejects any it leaves unset. + revision = os.environ.get("SAW_TARGET_REVISION", "") if auto_approved(site) else "" + if revision: + stack = site.setdefault("stack", {}) + for key in ("identity", "policy", "gateway", "audit"): + item = stack.setdefault(key, {}) + if isinstance(item, dict) and not item.get("revision"): + item["revision"] = revision + automatic = site.get("automaticEnrollment") + if isinstance(automatic, dict): + automatic.setdefault("revision", revision) + if isinstance(automatic.get("relay"), dict): + automatic["relay"].setdefault("revision", revision) if not isinstance(site, dict) or not re.fullmatch( r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", str(site.get("subject", ""))): return None return site -def container_profiles(site): +def auto_approved(site): + automatic = (site or {}).get("automaticEnrollment", {}) + return isinstance(automatic, dict) and automatic.get("autoApprove") is True + + +def container_profiles(site, catalog=None): + """Profiles an owner may request: every catalog profile on an autoApprove site.""" + if auto_approved(site): + return {profile: "" for profile in (catalog or {})} automatic = site.get("automaticEnrollment", {}) return automatic.get("approvedProfiles", {}) @@ -428,7 +495,8 @@ def read(path): if exc.code == 403: return {} raise - return _workspace.container_status(read, normalized, container_site(user), argo_ns, domain, ping, catalog) + return _workspace.container_status(read, normalized, container_site(user, entry.get("ownerSubject")), + argo_ns, domain, ping, catalog) def installation_id(user, registration): @@ -744,8 +812,9 @@ def _approved_profile_reference(site, profile): def check_live_boundary_approval(k8s, user, site, mode, profile, catalog): """Check the existing namespace policy against the owner-approved hash.""" automatic = site.get("automaticEnrollment", {}) if isinstance(site, dict) else {} - if not isinstance(automatic, dict) or not automatic or automatic.get("enabled") is False: - return + if (not isinstance(automatic, dict) or not automatic or automatic.get("enabled") is False + or automatic.get("autoApprove") is True): + return # autoApprove: enrollment publishes the first observed boundary reference = _approved_profile_reference(site, profile) try: _preflight.verify_boundary_reference(reference, mode) @@ -815,8 +884,41 @@ def resource(path, key, normalize=False): "sandboxPlacementBinding") +def credential_bindings(entry): + """Which Secret key backs which OpenShell provider type for one profile. + + Mirrors the saw-users.credentialBindings helper, which renders the same + list into the site once the workspace is created. + """ + keys = {} + for name, spec in (entry.get("secrets") or {}).items(): + fields = list(spec.get("fields") or []) + refresh = spec.get("refresh") or {} + if refresh: + fields.append({"key": refresh.get("credentialKey"), "kind": "secret", "refresh": True}) + for field in fields: + if field.get("kind") != "secret" or field.get("refreshMaterial"): + continue + binding = keys.setdefault((name, field["key"]), {"providers": [], "refresh": False}) + for provider in spec.get("providers") or []: + for kind in [provider] + (["build"] if provider == "nvidia" else []): + if kind not in binding["providers"]: + binding["providers"].append(kind) + binding["refresh"] = binding["refresh"] or bool(field.get("refresh")) + bindings = [] + for (name, key), binding in sorted(keys.items()): + for kind in binding["providers"]: + item = {"secret": name, "key": key, "type": kind} + if binding["refresh"]: + item["refresh"] = "oauth2_refresh_token" + bindings.append(item) + return bindings + + def check_workspace_preflight(k8s, user, site, mode, profile, catalog): """Run read-only platform gates before reserving or writing keys.""" + if "credentialBindings" not in site: + site = {**site, "credentialBindings": credential_bindings(catalog[profile])} observations = _preflight.configuration_facts(site) observations["api"] = True try: @@ -1327,7 +1429,7 @@ def workspace_status(k8s, user, catalog, ns, argo_ns, domain, ping=None): "title": message, "text": message, "message": message, "ready": False, "failed": state != "running", "steps": [], "links": []} mode = entry_deployment_mode(entry) - if mode in KUBERNETES_MODES and container_site(user): + if mode in KUBERNETES_MODES and container_site(user, entry.get("ownerSubject")): return container_status(k8s, user, entry, argo_ns, domain, ping or owner_route_available, catalog) if mode not in PROVISIONABLE_MODES: message = f"{mode} workspace lifecycle and readiness are not qualified in this release" @@ -1674,7 +1776,7 @@ def handle(action, request_name): _workspace.validate_runtime_placement(mode, site) except _workspace.WorkspaceError as exc: raise PortalError(str(exc)) from exc - approved = container_profiles(site) + approved = container_profiles(site, catalog) if data.get("profile") not in approved: raise PortalError("selected profile is not approved for your container workspace; " "approved profiles: " + (", ".join(sorted(approved)) or "none") + @@ -1693,8 +1795,7 @@ def handle(action, request_name): if mode in KUBERNETES_MODES: if cm and read_entry(cm)["profiles"] != [profile]: raise PortalError("changing the profile requires a new container registration") - endpoint = approved_endpoint(catalog[profile], secrets, - site.get("profileBoundaries", {}).get(profile, {})) + endpoint = approved_endpoint(catalog[profile], secrets) if cm and endpoint != read_entry(cm).get("customInferenceURL"): raise PortalError("changing the endpoint requires a new registration") models = public_model_inputs(catalog[profile], secrets) @@ -1723,7 +1824,7 @@ def handle(action, request_name): entry["webSearch"] = {"enabled": False} if models: entry["modelInputs"] = models - if "approvedProfiles" in site.get("automaticEnrollment",{}): + if "approvedProfiles" in site.get("automaticEnrollment",{}) or auto_approved(site): slots=sandbox_targets(user,generation,catalog[profile]) entry["uiNamespaces"]=sorted({"saw-ui-"+slot["relayID"] for slot in slots.values() if slot["ui"]}) entry["intentGeneration"] = previous.get("intentGeneration", 0) + 1 @@ -1900,7 +2001,8 @@ def generator_params(workspaces, defaults, read=None, catalog=None, previous=Non for entry in workspaces: ws = {**entry, "values": {**entry.get("values", {}), "deployment": {"mode": entry_deployment_mode(entry)}}} - site = container_site(ws["name"]) if entry_deployment_mode(ws) in KUBERNETES_MODES else {} + site = (container_site(ws["name"], ws.get("ownerSubject")) + if entry_deployment_mode(ws) in KUBERNETES_MODES else {}) if site: if not ws.get("ownerSubject") or ws["ownerSubject"] != site["subject"]: continue diff --git a/charts/openshell-rhdh/files/preflight.py b/charts/openshell-rhdh/files/preflight.py index c32862180..dc499183c 100644 --- a/charts/openshell-rhdh/files/preflight.py +++ b/charts/openshell-rhdh/files/preflight.py @@ -196,24 +196,33 @@ def check_observations(mode, observations): return tuple(required) +# Reviewed sites pin every chart to a full commit SHA. An autoApprove +# (development) site may follow a branch instead: saw-users and portal defaults +# use global.targetRevision when a site sets no revision. +PINNED_REVISION = r"[a-f0-9]{40}" +BRANCH_REVISION = r"[a-f0-9]{40}|[A-Za-z0-9][A-Za-z0-9._/-]*" + + def configuration_facts(site): """Check site-owned inputs that do not require cluster access.""" if not isinstance(site, dict): return {key: False for key in ("network", "storage", "secrets", "registry", "providerEgress", "revisions")} stack = site.get("stack") if isinstance(site.get("stack"), dict) else {} + enrollment = site.get("automaticEnrollment") or {} + revision_pattern = BRANCH_REVISION if isinstance(enrollment, dict) and enrollment.get( + "autoApprove") is True else PINNED_REVISION revisions = [item.get("revision") for item in stack.values() if isinstance(item, dict)] - required_components = ("identity", "policy", "proxy", "gateway", "audit") + required_components = ("identity", "policy", "gateway", "audit") revision_pin = all(isinstance(stack.get(name), dict) for name in required_components) and all( isinstance(stack[name].get("revision"), str) - and re.fullmatch(r"[a-f0-9]{40}", stack[name]["revision"]) + and re.fullmatch(revision_pattern, stack[name]["revision"]) for name in required_components) and bool(revisions) and len(revisions) == len(stack) and all( - isinstance(value, str) and re.fullmatch(r"[a-f0-9]{40}", value) for value in revisions) - enrollment = site.get("automaticEnrollment") or {} + isinstance(value, str) and re.fullmatch(revision_pattern, value) for value in revisions) if enrollment and not isinstance(enrollment, dict): revision_pin = False elif enrollment: - revision_pin = revision_pin and bool(re.fullmatch(r"[a-f0-9]{40}", str(enrollment.get("revision", "")))) + revision_pin = revision_pin and bool(re.fullmatch(revision_pattern, str(enrollment.get("revision", "")))) image_values = [] storage_values = [] @@ -233,28 +242,20 @@ def walk(value, path=()): walk(child, path) walk(site) - declared_hosts = site.get("providerAllowHosts") - policy = site.get("providerPolicy") - clean_hosts = (isinstance(declared_hosts, list) and bool(declared_hosts) - and all(isinstance(host, str) and host and "*" not in host - for host in declared_hosts) - and (policy is None or (isinstance(policy, dict) - and isinstance(policy.get("allowHosts"), list) - and all(isinstance(host, str) for host in policy["allowHosts"]) - and set(policy["allowHosts"]) == set(declared_hosts)))) - proxy = stack.get("proxy") or {} - proxy_values = proxy.get("values") or {} if isinstance(proxy, dict) else {} - bootstrap_egress = ((proxy_values.get("network") or {}).get("bootstrapEgress") - if isinstance(proxy_values, dict) else None) + # OpenShell decides where each credential may go (provider profiles); the + # site only lists which Secret backs which provider type. + bindings = site.get("credentialBindings") + clean_bindings = (isinstance(bindings, list) and all( + isinstance(b, dict) and {"secret", "key", "type"} <= set(b) <= {"secret", "key", "type", "refresh"} + and all(isinstance(v, str) and v for v in b.values()) for b in bindings)) storage_ok = bool(storage_values) and all(value.strip() for value in storage_values) return { - "network": bool(stack.get("policy")) and isinstance(bootstrap_egress, list) - and bool(bootstrap_egress), + "network": bool(stack.get("policy")), "storage": storage_ok, "secrets": isinstance(site.get("secretStore", "vault-backend"), str) and bool(site.get("secretStore", "vault-backend")), "registry": bool(image_values) and all("@sha256:" in image for image in image_values), - "providerEgress": clean_hosts, + "providerEgress": clean_bindings, "revisions": revision_pin, } diff --git a/charts/openshell-rhdh/files/workspace.py b/charts/openshell-rhdh/files/workspace.py index bc86b4d01..1addd71e3 100644 --- a/charts/openshell-rhdh/files/workspace.py +++ b/charts/openshell-rhdh/files/workspace.py @@ -5,6 +5,7 @@ resource application. This module never discovers or changes cluster state. """ import hashlib +import ipaddress import json import re import urllib.parse @@ -18,9 +19,9 @@ class WorkspaceError(ValueError): SAFE_FAILURE_REASONS = frozenset({ "ProfileRejected", "InvalidPlan", "PlacementRejected", "IdentityConflict", "InvalidIntent", "StaleIntent", "ReconcilerStateRejected", "GatewayMismatch", - "ProviderProfileMismatch", "WorkspaceRejected", "ProviderRejected", + "ProviderProfileMismatch", "ProviderRefreshFailed", "WorkspaceRejected", "ProviderRejected", "SandboxRejected", "SandboxStateMismatch", "SandboxDrift", "CoreRejected", - "CoreFailure", + "CoreFailure", "ReenrollRequired", }) SAFE_RPC_CODES = frozenset({ "NOT_FOUND", "ALREADY_EXISTS", "UNAVAILABLE", "DEADLINE_EXCEEDED", "ABORTED", @@ -82,24 +83,40 @@ def public_model_inputs(profile, secrets): return values -def approved_endpoint(profile, secrets, boundary): +CUSTOM_INFERENCE_URL = re.compile(r"https://[a-z0-9-]+(?:\.[a-z0-9-]+)+(?::443)?(?:/[A-Za-z0-9_-]+)*/v1") + + +def custom_inference_url(endpoint): + """The workspace's own OpenAI-compatible base URL: HTTPS, a DNS name, port 443, ending /v1. + + Which host may receive the API key is not decided here: the custom-inference + governance profile names it, and the runtime controller refuses a workspace + whose URL host is not that profile's only endpoint (ProviderProfileMismatch). + """ + if not isinstance(endpoint, str) or not CUSTOM_INFERENCE_URL.fullmatch(endpoint): + raise WorkspaceError("custom inference needs an HTTPS base URL ending in /v1") + try: + ipaddress.ip_address(urllib.parse.urlsplit(endpoint).hostname) + except ValueError: + return endpoint + raise WorkspaceError("custom inference needs an HTTPS base URL ending in /v1, with a DNS name") + + +def approved_endpoint(profile, secrets): + """The endpoint URL the owner entered (public metadata), if the profile takes one.""" refs = {sb["endpointInput"] for _, sb in enabled_catalog_sandboxes(profile) if sb.get("endpointInput")} if not refs: return None - endpoint = boundary.get("inferenceBaseURL", "") - if not isinstance(endpoint, str) or not re.fullmatch( - r"https://[a-z0-9-]+(?:\.[a-z0-9-]+)+(?::443)?(?:/[A-Za-z0-9_-]+)*/v1", endpoint): - raise WorkspaceError("site has no approved custom inference endpoint") - if boundary.get("allowHosts") != [urllib.parse.urlsplit(endpoint).hostname]: - raise WorkspaceError("custom inference requires a dedicated broker host") + endpoints = set() for ref in refs: secret, key = ref.split(".", 1) fields = profile["secrets"][secret]["fields"] if not any(f["key"] == key and f["kind"] == "url" for f in fields): raise WorkspaceError("endpoint input must be public URL metadata") - if secrets.get(secret, {}).get(key, "").rstrip("/") != endpoint: - raise WorkspaceError("endpoint differs from the site-approved custom inference URL") - return endpoint + endpoints.add(secrets.get(secret, {}).get(key, "").rstrip("/")) + if len(endpoints) != 1: + raise WorkspaceError("custom inference endpoint inputs disagree") + return custom_inference_url(endpoints.pop()) def enrolled_site(site, ws, read): @@ -123,17 +140,18 @@ def publication(name): if data: raise WorkspaceError("cannot disable enrollment of a bound workspace; use desiredState") return fresh - for key, kind in (("reference", dict), ("relay", dict), ("revision", str), - ("image", str), ("buildNamespace", str)): + auto = a.get("autoApprove") is True + for key, kind in ((() if auto else (("reference", dict),)) + (("relay", dict), ("revision", str), + ("image", str), ("buildNamespace", str))): if not isinstance(a.get(key), kind) or not a[key]: raise WorkspaceError(f"container site for {ws['name']} requires automaticEnrollment.{key}") if not data: return fresh bound=json.loads(data["binding.json"]) - if set(bound)!={"registration","intent","approved","gatewayCA"} or bound["registration"]!=reg or set(bound["approved"])!=set(a["reference"]): + if set(bound)!={"registration","intent","approved","gatewayCA"} or bound["registration"]!=reg or (not auto and set(bound["approved"])!=set(a["reference"])): raise WorkspaceError("invalid published enrollment") intent=bound["intent"] - if intent["bindings"]["ownerID"]!=install or intent["bindings"]["namespace"]!="saw-"+ws["name"] or intent["bindings"]["ownerSubject"]!=ws["ownerSubject"] or intent["profileRef"]["sha256"]!=site.get("selectedDigest",a.get("profileSHA256")): + if intent["bindings"]["ownerID"]!=install or intent["bindings"]["namespace"]!="saw-"+ws["name"] or intent["bindings"]["ownerSubject"]!=ws["ownerSubject"] or (not auto and intent["profileRef"]["sha256"]!=site.get("selectedDigest",a.get("profileSHA256"))): raise WorkspaceError("published intent does not belong to this workspace") subjects = {target["subjectMap"]:publication(target["subjectMap"]).get("subject", "") for target in site.get("targets",{}).values() if target["ui"]} @@ -204,7 +222,7 @@ def project_workspace(workspace, defaults, site, catalog, read=None, previous=No # Inputs include operator configuration and immutable API publications. # Do not include arbitrary values (especially JSON bodies) in diagnostics. detail = f"missing {exc.args[0]}" if isinstance(exc, KeyError) and exc.args[0] in { - "subject", "registration", "installationID", "reference", "allowHosts", "bindings", + "subject", "registration", "installationID", "reference", "bindings", "binding.json", "profileRef", "sha256", "initialModelInputs"} else "invalid site or publication" raise WorkspaceError(f"workspace {workspace.get('name', '?')}: {detail}") from None @@ -241,11 +259,26 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): validate_runtime_placement(mode, site) automatic = site.get("automaticEnrollment", {}) selected, *extra = ws.get("profiles", []) or [None] - foundation = automatic.get("enabled") is False + foundation = automatic.get("enabled") is False or automatic.get("autoApprove") is True if extra or selected not in catalog or not foundation and selected not in automatic.get("approvedProfiles", {}): raise WorkspaceError("container requires one approved BOM profile") if not ws.get("registration") or not ws.get("installationID"): raise WorkspaceError("container requires a registration and installation identity") + # As the portal does at registration: a dedicated-endpoint profile (such as + # custom-inference) has no web-search credential unless the entry asks for it. + if "dedicatedEndpointSecrets" in catalog[selected] and "webSearch" not in ws: + ws["webSearch"] = {"enabled": False} + # The runtime compiles the model from public inputs, never from the Secret. + # The portal reads it from the form; a static entry must name it. + given = ws.get("initialModelInputs") if ws.get("lifecycleVersion") == 1 else ws.get("modelInputs") + for _, sandbox in enabled_catalog_sandboxes(catalog[selected]): + key = sandbox.get("modelInput") + if not key: + continue + secret, field = key.split(".", 1) + definition = next((f for f in catalog[selected]["secrets"][secret]["fields"] if f["key"] == field), {}) + if definition.get("required") and not definition.get("default") and not (given or {}).get(key): + raise WorkspaceError(f"{ws['name']}: set modelInputs.{key} (the model this profile requires)") overrides = site.get("profileImageOverrides", {}).get(selected, {}) if overrides: ws["imageOverrides"] = overrides @@ -259,12 +292,19 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): target["image"] = overrides.get(target["sandbox"], target["image"]) boundary = site.get("profileBoundaries", {}).get(selected) if boundary: - site = {**site, "providerAllowHosts": boundary["allowHosts"], - "automaticEnrollment": {**automatic, "reference": boundary["reference"]}} - if ws.get("customInferenceURL"): - if not boundary or boundary.get("inferenceBaseURL") != ws["customInferenceURL"]: - raise WorkspaceError("endpoint differs from the site-approved custom inference URL") - site["customInferenceURL"] = ws["customInferenceURL"] + # autoApprove sites have no operator-reviewed reference to pin. + reviewed = {"reference": boundary["reference"]} if "reference" in boundary or \ + automatic.get("autoApprove") is not True else {} + site = {**site, "automaticEnrollment": {**automatic, **reviewed}} + # A profile with an endpoint input (custom-inference) uses the owner's own + # URL: the portal form value, or customInferenceURL in a static entry. The + # custom-inference governance profile approves its host at run time. + if any(sb.get("endpointInput") for _, sb in enabled_catalog_sandboxes(catalog[selected])): + if not ws.get("customInferenceURL"): + raise WorkspaceError(f"{ws['name']}: set customInferenceURL (the inference server's base URL)") + site["customInferenceURL"] = custom_inference_url(ws["customInferenceURL"]) + elif ws.get("customInferenceURL"): + raise WorkspaceError("only a profile with an endpoint input takes customInferenceURL") if managed: site.update(lifecycleVersion=1, modelInputs=ws["initialModelInputs"], requestedModels=ws.get("modelInputs", {}), desiredState=ws["desiredState"], diff --git a/charts/openshell-rhdh/templates/_helpers.tpl b/charts/openshell-rhdh/templates/_helpers.tpl index 985206768..621c6823d 100644 --- a/charts/openshell-rhdh/templates/_helpers.tpl +++ b/charts/openshell-rhdh/templates/_helpers.tpl @@ -170,7 +170,7 @@ from the release is enough and keeps renders stable. {{- if and .Values.portal.containerSites .Values.portal.containerSitesSecretName -}} {{- fail "set only one of portal.containerSites and portal.containerSitesSecretName" -}} {{- end -}} -{{- if or .Values.portal.containerSites .Values.portal.containerSitesSecretName -}}true{{- else -}}false{{- end -}} +{{- if or .Values.portal.containerSites .Values.portal.containerSitesSecretName .Values.containerDefaults -}}true{{- else -}}false{{- end -}} {{- end -}} {{- define "openshell-rhdh.containerSitesEnv" -}} @@ -183,6 +183,13 @@ from the release is enough and keeps renders stable. {{- else }} value: {{ .Values.portal.containerSites | default dict | toJson | quote }} {{- end }} +{{- /* Shared site for every owner without their own entry (saw-users' +containerDefaults, from overrides/saw-container-defaults.yaml). Subjects come +from the owner directory; unset chart revisions follow the pattern branch. */}} +- name: SAW_CONTAINER_DEFAULTS + value: {{ .Values.containerDefaults | default dict | toJson | quote }} +- name: SAW_TARGET_REVISION + value: {{ .Values.global.targetRevision | default "" | quote }} {{- end -}} {{/* Generated forms have vm as their safe default; project the administrator's @@ -221,6 +228,18 @@ The server still verifies the authenticated owner's exact profile approval. */ - {{- end -}} {{- end -}} {{- end -}} +{{- with $root.Values.containerDefaults -}} +{{- /* The shared site serves every owner: autoApprove offers each catalog +profile, otherwise its approvedProfiles. */ -}} +{{- $a := .automaticEnrollment | default dict -}} +{{- if has "container" $modes -}} +{{- range $id := $step.properties.profile.enum -}} +{{- if or (eq (toString ($a.autoApprove | default false)) "true") (hasKey ($a.approvedProfiles | default dict) $id) -}} +{{- $_ := set (index $approved "container") $id true -}} +{{- end -}} +{{- end -}} +{{- end -}} +{{- end -}} {{- $profilesByMode := dict -}} {{- range $mode := list "container" "kata" -}} {{- $ids := list -}}{{- $names := list -}} diff --git a/charts/openshell-saw-kubernetes/templates/_helpers.tpl b/charts/openshell-saw-kubernetes/templates/_helpers.tpl index cccd7beed..b501606b0 100644 --- a/charts/openshell-saw-kubernetes/templates/_helpers.tpl +++ b/charts/openshell-saw-kubernetes/templates/_helpers.tpl @@ -26,7 +26,7 @@ app.kubernetes.io/part-of: secure-agent-workspace {{- if and (eq .Values.deployment.mode "kata") (not (regexMatch "^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$" $k.workload.runtimeClassName)) -}}{{- fail "kata requires an approved workload RuntimeClass name" -}}{{- end -}} {{- if not (regexMatch "^https://[^/?#@[:space:]]+(/[^?#[:space:]]*)?$" .Values.oidc.issuerUrl) -}}{{- fail "oidc.issuerUrl must be explicit HTTPS without userinfo, query or fragment" -}}{{- end -}} {{- if not (or (regexMatch "^https://[^/?#@[:space:]]+/?$" $k.governance.endpoint) (regexMatch "^http://[a-z0-9-]+\\.[a-z0-9-]+\\.svc(\\.cluster\\.local)?:[0-9]+$" $k.governance.endpoint)) -}}{{- fail "governance endpoint must be HTTPS without userinfo or the explicitly selected in-cluster HTTP gRPC Service" -}}{{- end -}} -{{- if or (not (regexMatch "^https?://[^/?#@[:space:]]+:[0-9]+$" $k.proxy.url)) (not $k.proxy.caConfigMap) -}}{{- fail "configure the trusted credential proxy URL without userinfo and public CA ConfigMap" -}}{{- end -}} +{{- if and $k.proxy.url (or (not (regexMatch "^https?://[^/?#@[:space:]]+:[0-9]+$" $k.proxy.url)) (not $k.proxy.caConfigMap)) -}}{{- fail "an upstream proxy needs a URL without userinfo and a public CA ConfigMap" -}}{{- end -}} {{- if or (not $k.network.reconcilerNamespace) (not $k.network.reconcilerLabels) -}}{{- fail "trusted reconciler namespace and exact Pod labels are required" -}}{{- end -}} {{- if eq $k.network.reconcilerNamespace .Release.Namespace -}}{{- fail "trusted reconciler identity must be outside the runtime namespace" -}}{{- end -}} {{- if not $k.network.gatewayEgress -}}{{- fail "explicit gateway API/DNS/OIDC/governance/proxy egress rules are required" -}}{{- end -}} diff --git a/charts/openshell-saw-kubernetes/templates/gateway-config.yaml b/charts/openshell-saw-kubernetes/templates/gateway-config.yaml index b0143a11c..96c690444 100644 --- a/charts/openshell-saw-kubernetes/templates/gateway-config.yaml +++ b/charts/openshell-saw-kubernetes/templates/gateway-config.yaml @@ -62,10 +62,12 @@ data: supervisor_image_pull_policy = "IfNotPresent" sandbox_runtime_image_pull_policy = "IfNotPresent" image_pull_secrets = {{ .Values.kubernetes.imagePullSecrets | toJson }} +{{- if .Values.kubernetes.proxy.url }} https_proxy = {{ .Values.kubernetes.proxy.url | quote }} # Stock SAW proxy accepts DNS:443 CONNECT targets, never literal IPs. proxy_connect_by_hostname = true proxy_ca_bundle = "/etc/openshell-tls/proxy-ca/ca.crt" +{{- end }} [openshell.drivers.kubernetes.resource_admission] enabled = true [openshell.drivers.kubernetes.resource_admission.required_labels] diff --git a/charts/openshell-saw-kubernetes/templates/gateway.yaml b/charts/openshell-saw-kubernetes/templates/gateway.yaml index d56efaebb..30a3fe0bb 100644 --- a/charts/openshell-saw-kubernetes/templates/gateway.yaml +++ b/charts/openshell-saw-kubernetes/templates/gateway.yaml @@ -88,7 +88,9 @@ spec: - {name: client-ca, mountPath: /etc/openshell-tls/client-ca, readOnly: true} - {name: jwt, mountPath: /etc/openshell-jwt, readOnly: true} - {name: peer-token, mountPath: /var/run/secrets/openshell-peer, readOnly: true} +{{- if $k.proxy.url }} - {name: proxy-ca, mountPath: /etc/openshell-tls/proxy-ca, readOnly: true} +{{- end }} - {name: tmp, mountPath: /tmp} {{- if .Values.oidc.caConfigMap }} - {name: oidc-ca, mountPath: /etc/openshell-tls/oidc-ca, readOnly: true} @@ -104,7 +106,9 @@ spec: secretName: {{ $k.identity.clientCaSecret | quote }} items: [{key: ca.crt, path: ca.crt}] - {name: jwt, secret: {secretName: {{ $k.identity.jwtSecret | quote }}, defaultMode: 0440}} +{{- if $k.proxy.url }} - {name: proxy-ca, configMap: {name: {{ $k.proxy.caConfigMap | quote }}}} +{{- end }} - {name: tmp, emptyDir: {}} {{- if .Values.oidc.caConfigMap }} - {name: oidc-ca, configMap: {name: {{ .Values.oidc.caConfigMap | quote }}}} diff --git a/charts/openshell-saw/files/installer/apply_bom.py b/charts/openshell-saw/files/installer/apply_bom.py index 35d8b0ad7..130cac5ac 100644 --- a/charts/openshell-saw/files/installer/apply_bom.py +++ b/charts/openshell-saw/files/installer/apply_bom.py @@ -3976,7 +3976,11 @@ def start_openclaw(self, ws, sb, provider): raise ValueError("expected a list of model IDs") except ValueError as exc: raise InstallerError(f"cannot read OpenClaw managed models: {exc}") from None - if (sb.inference_values or {}).get("models") or previous: + thinking = (sb.inference_values or {}).get("thinking", "") + if thinking: + self.mark_reasoning_model(exec_cmd, oc_env, provider.type, model_id, + reasoning=thinking != "off") + if (sb.inference_values or {}).get("models") or previous or thinking: current_models = self.cli(*exec_cmd, "sh", "-c", f"{oc_env} openclaw config get agents.defaults --json", quiet=True) @@ -3989,7 +3993,9 @@ def start_openclaw(self, ws, sb, provider): raise ValueError("expected a mapping") except ValueError as exc: raise InstallerError(f"cannot read OpenClaw model choices: {exc}") from None - desired = {model_id: {}} + # The profile's thinking level is this model's default; /think in a + # chat still overrides it for that session. + desired = {model_id: {"params": {"thinking": thinking}} if thinking else {}} for name, selected_model in (sb.inference_values or {}).get("models", {}).items(): kind = next(p.type for p in ws.providers if p.name == name) selected_id = (selected_model if selected_model.startswith(f"{kind}/") @@ -4001,6 +4007,11 @@ def start_openclaw(self, ws, sb, provider): choices.pop(name, None) for name, settings in desired.items(): choices.setdefault(name, {}).update(settings) + if not thinking and isinstance(choices[model_id].get("params"), dict): + # A thinking level removed from the profile stops applying. + choices[model_id]["params"].pop("thinking", None) + if not choices[model_id]["params"]: + choices[model_id].pop("params") self.cli(*exec_cmd, "sh", "-c", f"{oc_env} openclaw config set agents.defaults.models " + shlex.quote(json.dumps(choices)) @@ -4057,6 +4068,42 @@ def launch_openclaw(self, ws, sb, exec_cmd, oc_env): self.clear_confinement_stop(ws, sb) self.install_keepalive(ws, sb) + def mark_reasoning_model(self, exec_cmd, oc_env, provider_type, model_id, reasoning=True): + """Set whether OpenClaw treats a custom provider's model as reasoning. + + OpenClaw knows which of its own models reason; a custom model offers + only default and off unless its entry says reasoning: true and lists + the efforts the endpoint accepts (sent as reasoning_effort). Thinking + off marks it reasoning: false, so no effort is sent.""" + key = f"models.providers.{shlex.quote(provider_type)}.models" + found = self.cli(*exec_cmd, "sh", "-c", f"{oc_env} openclaw config get {key} --json", + check=False, quiet=True) + if self.sh.dry_run: + return + try: + models = json.loads(found.out) if found.ok else None + except ValueError: + models = None + bare = model_id.removeprefix(f"{provider_type}/") + entry = next((m for m in models or [] if isinstance(m, dict) and m.get("id") in (bare, model_id)), None) + if entry is None: + log(f"WARN: {provider_type} has no model entry for '{bare}'; its thinking level " + "applies only if OpenClaw already treats it as a reasoning model") + return + compat = entry.setdefault("compat", {}) + efforts = REASONING_EFFORTS if reasoning else None + if entry.get("reasoning") is reasoning and compat.get("supportedReasoningEfforts") == efforts: + return + entry["reasoning"] = reasoning + if reasoning: + compat["supportedReasoningEfforts"] = REASONING_EFFORTS + else: + compat.pop("supportedReasoningEfforts", None) + if not compat: + entry.pop("compat") + self.cli(*exec_cmd, "sh", "-c", + f"{oc_env} openclaw config set {key} {shlex.quote(json.dumps(models))}") + def disable_provider_channels(self, ws, sb, exec_cmd, oc_env): """Keep OpenClaw's own chat channel off for a provider that shares its name (slack). The provider is for governed reads (the harness's diff --git a/charts/openshell-saw/files/installer/saw_admin.py b/charts/openshell-saw/files/installer/saw_admin.py index 0a5a986fb..3dbc9eb27 100644 --- a/charts/openshell-saw/files/installer/saw_admin.py +++ b/charts/openshell-saw/files/installer/saw_admin.py @@ -64,7 +64,7 @@ def issue(authority, client, *, subject, crypto=openssl, erase=erase_ca_key): try: crypto("req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes", "-keyout", ca_key, "-out", ca, "-days", "1", - "-subj", "/O=openshell/OU=SAW-apply/CN=saw-apply-ca", + "-subj", "/O=openshell/OU=SAW-apply/CN=saw-apply-ca-" + secrets.token_hex(8), "-addext", "basicConstraints=critical,CA:TRUE", "-addext", "keyUsage=critical,keyCertSign") crypto("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes", "-keyout", key, "-subj", subject, "-out", csr) diff --git a/charts/openshell-saw/files/installer/saw_core.py b/charts/openshell-saw/files/installer/saw_core.py index c74428747..5138cd96e 100644 --- a/charts/openshell-saw/files/installer/saw_core.py +++ b/charts/openshell-saw/files/installer/saw_core.py @@ -200,7 +200,7 @@ class Sandbox: # (the agent, and argv, can read these): those stay on providers. env: dict = field(default_factory=dict) # `inference:` -- how the agent reaches its model: {providerRef, protocol, - # baseUrl?, model, models?, timeoutSeconds?}. models maps optional native + # baseUrl?, model, models?, timeoutSeconds?, thinking?}. models maps optional native # provider names to additional chat model inputs. baseUrl/model/timeoutSeconds # is a literal or an input ({secretKeyRef: {name, key}, default?, # required?, title?}); inference_values is it resolved. The installer onboards the @@ -418,6 +418,10 @@ def validate_profile_document(doc, kind, where="profile"): raise InstallerError(f"{where}: inference.providerRef must be a string") if "protocol" in inference and not isinstance(inference["protocol"], str): raise InstallerError(f"{where}: inference.protocol must be a string") + inference = _thinking_off(inference) + if "thinking" in inference and inference["thinking"] not in THINKING_LEVELS: + raise InstallerError(f"{where}: inference.thinking must be one of " + + ", ".join(THINKING_LEVELS)) for field_name in ("model", "baseUrl", "timeoutSeconds"): kinds = (str, int) if field_name == "timeoutSeconds" else (str,) if field_name in inference: @@ -511,7 +515,7 @@ def parse_profiles(files, *, strict=False, document_check=None): harness_ref=dict(s.get("harnessRef") or {}), ui=dict(s.get("ui") or {}), env=s.get("env") if s.get("env") is not None else {}, - inference=s.get("inference") if s.get("inference") is not None else {}, + inference=_thinking_off(s.get("inference") if s.get("inference") is not None else {}), gpu_enabled=gpu_enabled, gpu_count=gpu_count)) profile.workspaces.append(ws) profiles.append(profile) @@ -721,7 +725,19 @@ def secret_ref_problems(src): return out -INFERENCE_KEYS = {"providerRef", "protocol", "baseUrl", "model", "models", "timeoutSeconds"} +def _thinking_off(inference): + """YAML reads an unquoted `thinking: off` as false; it means off.""" + if isinstance(inference, dict) and inference.get("thinking") is False: + return {**inference, "thinking": "off"} + return inference + + +INFERENCE_KEYS = {"providerRef", "protocol", "baseUrl", "model", "models", "timeoutSeconds", "thinking"} +# OpenClaw thinking levels a profile may make the model's default. A level +# other than off also marks the model as a reasoning model that accepts +# these efforts, which OpenClaw only assumes for its own known models. +THINKING_LEVELS = ("off", "minimal", "low", "medium", "high") +REASONING_EFFORTS = ["low", "medium", "high"] # A profile controls allowed credential destinations; the protocol controls @@ -948,6 +964,8 @@ def resolve_inference(ws, sb, read_value, validate_endpoint, forbidden=()): if timeout and (not str(timeout).isdigit() or int(timeout) < 0): raise InstallerError(f"{where}: inference timeoutSeconds must be a non-negative integer") out["timeoutSeconds"] = int(timeout) if timeout else 0 + if spec.get("thinking"): + out["thinking"] = spec["thinking"] if "models" in spec: out["models"] = {} for name, src in spec["models"].items(): @@ -1007,6 +1025,11 @@ def sandbox_inference_problems(sb, provider_types, declared_provider_types=None) for key in ("baseUrl", "model"): if key in spec: out += [f"inference {key} {p}" for p in input_problems(spec[key])] + if "thinking" in spec: + if spec["thinking"] not in THINKING_LEVELS: + out.append(f"inference thinking must be one of {', '.join(THINKING_LEVELS)}") + elif sb.type != "openclaw": + out.append("inference thinking is supported only for openclaw sandboxes") models = spec.get("models", {}) if not isinstance(models, dict): out.append("inference models must be a mapping of provider names to model inputs") @@ -1058,7 +1081,7 @@ def profiles_from_plan(data): 'SANDBOX_TYPES', 'BASE_URL_CONFIG_KEYS', 'InstallerError', 'Provider', 'Sandbox', 'Workspace', 'Profile', 'HarnessBundle', 'read_profile_files', '_yaml', 'parse_profiles', 'enabled_workspaces', 'validate_profiles', 'ENV_NAME_RE', 'CREDENTIAL_NAME_RE', 'ENV_VALUE_LIMIT', 'SANDBOX_ENV_KEYS', - 'INPUT_KEYS', 'secret_ref', 'secret_ref_problems', 'INFERENCE_KEYS', 'INFERENCE_PROTOCOLS', + 'INPUT_KEYS', 'secret_ref', 'secret_ref_problems', 'INFERENCE_KEYS', 'INFERENCE_PROTOCOLS', 'THINKING_LEVELS', 'REASONING_EFFORTS', 'PROVIDER_PROTOCOLS', 'check_env_value', 'sandbox_env_problems', 'input_problems', 'check_base_url', 'resolve_bom_input', 'resolve_inference', 'inference_protocol', 'sandbox_inference_problems', 'harness_from_plan', 'profiles_from_plan', 'validate_profile_document', 'apply_workspace_sequence', 'select_inference_provider', @@ -1113,13 +1136,33 @@ def tool_gate_identity(owner, subject, workspace, sandbox): "sandbox": sandbox, "workspace": workspace} -def tool_gate_bundle(here, identity, receipt_key=None): - """Build the identical policy, identity and OpenClaw extension for both runtimes.""" +def tool_gate_bundle(here, identity, receipt_key=None, harness_rules=()): + """Build the identical policy, identity and OpenClaw extension for both runtimes. + + `harness_rules` are the enrolled harness's own tool rules + (harness_tool_rules). They follow the base rules, so where both name a + tool the base rule decides, and the pinned policy hash covers them. + """ names = ("tool-actions.yaml", "tool-gate.mjs", "tool-gate-plugin.mjs") missing = [name for name in names if not (here / name).is_file()] if missing: raise InstallerError("tool gate files missing from the installer disk: " + ", ".join(missing)) policy = (here / "tool-actions.yaml").read_bytes() + if harness_rules: + lines = [b"", b" # From the enrolled harness bundle (its own MCP tools only)."] + for rule in harness_rules: + # Written into policy text, so check every field here as well as + # where the rules are built: only a __ rule with a + # harness action, in a charset the policy reads verbatim. + if (not isinstance(rule, dict) or set(rule) != {"id", "tool", "action"} + or not all(isinstance(v, str) for v in rule.values()) + or not HARNESS_RULE_ID_RE.fullmatch(rule["id"]) + or not HARNESS_TOOL_RE.fullmatch(rule["tool"]) + or rule["action"] not in HARNESS_TOOL_ACTIONS): + raise InstallerError(f"invalid harness tool rule {rule!r}") + lines += [f" - id: {rule['id']}".encode(), f" tool: {rule['tool']}".encode(), + f" action: {rule['action']}".encode()] + policy = policy.rstrip(b"\n") + b"\n".join(lines) + b"\n" policy_hash = "sha256:" + hashlib.sha256(policy).hexdigest() plugin = (here / "tool-gate-plugin.mjs").read_bytes().replace( b"__SAW_POLICY_HASH__", policy_hash.encode()) @@ -1142,6 +1185,20 @@ def tool_gate_bundle(here, identity, receipt_key=None): # Inline harness parsing and OpenClaw registration are shared by both installers. HARNESS_MOUNT = "/sandbox/harness" +# A bundle can allow its own MCP tools or ask for approval; refusing is the +# default, and the site's tool-actions.yaml can still deny or require approval. +HARNESS_TOOL_ACTIONS = ("allow", "approval") +# A harness rule names only __ of its own MCP servers; both +# parts are letters, digits, '_' or '-' (MCP_SERVER_NAME_RE), never a +# newline or YAML syntax, and never a bare tool such as exec. +HARNESS_PART = r"[A-Za-z0-9_-]{1,64}" +HARNESS_TOOL_RE = re.compile(rf"{HARNESS_PART}__{HARNESS_PART}") +HARNESS_RULE_ID_RE = re.compile(rf"harness-{HARNESS_PART}-{HARNESS_PART}") + + +def harness_tool_rules(info): + """The tool-gate rules a described harness declares for its own MCP tools.""" + return list(info.get("toolRules", [])) # mcp.json env/header value: exactly ${VAR}, or Authorization-style @@ -1286,6 +1343,33 @@ def describe_harness_tree(files, inline=False, *, warn=lambda _: None): "governanceProfile in harness.yaml spec.mcpServers") governance.append({"kind": "MCP server", "name": server, "governanceProfile": profile, "hosts": [host]}) + tool_rules = [] + for server, decl in sorted(declared.items()): + tools = decl.get("tools") + if tools is None: + continue + if not isinstance(server, str) or not re.fullmatch(HARNESS_PART, server): + raise InstallerError( + f"harness '{name}': mcp server name {server!r} must be 1-64 letters, digits, " + "'_' or '-' to declare tool actions") + if server not in mcp_server_names: + raise InstallerError( + f"harness '{name}': tools are declared for '{server}', which mcp.json does not " + "define; a bundle may only set actions for its own MCP servers' tools") + if not isinstance(tools, list): + raise InstallerError(f"harness '{name}': mcp server '{server}' tools must be a list") + for item in tools: + if (not isinstance(item, dict) or set(item) != {"name", "action"} + or not isinstance(item["name"], str) + or not re.fullmatch(HARNESS_PART, item["name"]) + or item["action"] not in HARNESS_TOOL_ACTIONS): + raise InstallerError( + f"harness '{name}': mcp server '{server}' tools entries need exactly a name " + "(letters, digits, '_' or '-') and an action of allow or approval") + tool_rules.append({"id": f"harness-{server}-{item['name']}", + "tool": f"{server}__{item['name']}", "action": item["action"]}) + if len({r["id"] for r in tool_rules}) != len(tool_rules): + raise InstallerError(f"harness '{name}': a tool is declared twice") bundle_id = name if "plugin.json" in files: try: @@ -1303,6 +1387,7 @@ def describe_harness_tree(files, inline=False, *, warn=lambda _: None): "mcpConfigs": mcp_configs, "pluginDirs": plugin_dirs, "governance": governance, + "toolRules": tool_rules, } diff --git a/charts/openshell-saw/files/installer/tool-actions.yaml b/charts/openshell-saw/files/installer/tool-actions.yaml index 3becbac16..029dc993c 100644 --- a/charts/openshell-saw/files/installer/tool-actions.yaml +++ b/charts/openshell-saw/files/installer/tool-actions.yaml @@ -42,24 +42,53 @@ rules: - openclaw cron get - openclaw cron show - openclaw cron runs + - openclaw cron --help + - openclaw cron add --help + - openclaw cron create --help + - openclaw cron edit --help + - openclaw cron rm --help + - openclaw cron remove --help + - openclaw cron delete --help + - openclaw cron enable --help + - openclaw cron disable --help + - openclaw cron run --help - openclaw automations list - openclaw automations status - openclaw automations get - openclaw automations show - openclaw automations runs + - openclaw automations --help + - openclaw automations add --help + - openclaw automations create --help + - openclaw automations edit --help + - openclaw automations rm --help + - openclaw automations remove --help + - openclaw automations delete --help + - openclaw automations enable --help + - openclaw automations disable --help + - openclaw automations run --help + # "Allow always" skips the card for later automation changes until the + # gateway restarts; each call is still audited. - id: exec-openclaw-automation-change tool: exec action: approval + allowAlways: true whenCommandMatches: - openclaw cron add + - openclaw cron create - openclaw cron edit - openclaw cron rm + - openclaw cron remove + - openclaw cron delete - openclaw cron enable - openclaw cron disable - openclaw cron run - openclaw automations add + - openclaw automations create - openclaw automations edit - openclaw automations rm + - openclaw automations remove + - openclaw automations delete - openclaw automations enable - openclaw automations disable - openclaw automations run diff --git a/charts/openshell-saw/files/installer/tool-gate.mjs b/charts/openshell-saw/files/installer/tool-gate.mjs index 3429a31ee..22a029999 100644 --- a/charts/openshell-saw/files/installer/tool-gate.mjs +++ b/charts/openshell-saw/files/installer/tool-gate.mjs @@ -102,6 +102,12 @@ export function parsePolicy(text) { ids.add(rule.id); if (typeof rule.tool !== "string" || !rule.tool) throw new Error(`rule ${rule.id} needs a tool`); if (!ACTIONS.has(rule.action)) throw new Error(`rule ${rule.id} has an unknown action`); + if (rule.allowAlways !== undefined) { + if (rule.allowAlways !== "true" || rule.action !== "approval") { + throw new Error(`rule ${rule.id}: allowAlways must be true on an approval rule`); + } + rule.allowAlways = true; + } if (rule.whenCommandMatches !== undefined) { if (!Array.isArray(rule.whenCommandMatches) || rule.whenCommandMatches.length === 0) { throw new Error(`rule ${rule.id} has an empty whenCommandMatches`); @@ -147,6 +153,8 @@ export function commandText(params) { function normalizedExec(command) { if (!command.trim()) return { error: "exec-unreadable" }; + // A trailing 2>&1 only merges stderr into stdout; agents add it out of habit. + command = command.replace(/(?:[ \t]+2>&1)+[ \t]*$/, ""); if (/[;&|`\n\r<>]|\$\(|\$\{/.test(command)) return { error: "exec-opaque" }; const words = command.trim().split(/\s+/); const assignments = []; @@ -206,11 +214,43 @@ function baseRecord(input, extras) { }; } -function effectFor(action, tool, ruleId) { +// Said back to the agent with a denial so it can retry in an accepted form +// instead of guessing. +const EXEC_HINTS = { + "exec-unreadable": "Send the command as one plain string.", + "exec-opaque": "Run one command per exec call, with no ;, &&, |, backticks, $(...), " + + "redirects or shell wrappers such as sh -c (a trailing 2>&1 is fine). " + + "Each command is checked on its own.", +}; + +// For an unlisted exec command, the accepted commands that start with the +// same two words (such as `openclaw automations`), so the agent can use the +// right spelling instead of giving up or guessing. +function sameFamily(policy, command) { + const words = command.split(" ").slice(0, 2); + if (words.length < 2) return ""; + const prefix = `${words.join(" ")} `; + const found = { allow: [], approval: [] }; + for (const rule of policy.rules) { + if (rule.tool !== "exec" || !found[rule.action]) continue; + for (const needle of rule.whenCommandMatches || []) { + const normalized = needle.toLowerCase().replace(/\s+/g, " ").trim(); + const verb = normalized.startsWith(prefix) ? normalized.slice(prefix.length) : ""; + if (verb && !verb.includes(" ") && !found[rule.action].includes(verb)) found[rule.action].push(verb); + } + } + const parts = []; + if (found.allow.length) parts.push(`${found.allow.join(", ")} (run directly)`); + if (found.approval.length) parts.push(`${found.approval.join(", ")} (ask the user for approval)`); + return parts.length ? `. Accepted \`${words.join(" ")}\` commands: ${parts.join("; ")}` : ""; +} + +function effectFor(action, tool, ruleId, allowAlways = false, hint = "") { if (action === "allow") return { kind: "allow" }; if (action === "deny") { const why = ruleId === "default" - ? `Tool ${tool} is denied by the default action` + ? `Tool ${tool} is denied by the default action${tool === "exec" + ? `: this command is not on the allowed list, so do not retry it in another form${hint}` : ""}` : `Tool ${tool} is denied by rule ${ruleId}`; return { kind: "deny", blockReason: why }; } @@ -221,7 +261,7 @@ function effectFor(action, tool, ruleId) { description: `Tool ${tool} matches ${ruleId} and needs approval before it runs.`, severity: "warning", timeoutMs: 120000, - allowedDecisions: ["allow-once", "deny"], + allowedDecisions: allowAlways ? ["allow-once", "allow-always", "deny"] : ["allow-once", "deny"], }, }; } @@ -280,14 +320,27 @@ export function decide(input) { const task = { id: session, title }; const rawCommand = commandText(input.params); const exec = tool === "exec" ? normalizedExec(rawCommand) : null; - if (exec?.error) return blocked(input, exec.error, `Tool call blocked: ${exec.error}`, task); + if (exec?.error) return blocked(input, exec.error, `Tool call blocked: ${exec.error}. ${EXEC_HINTS[exec.error]}`, task); const command = exec ? exec.command : rawCommand; const rule = policy.rules.find((item) => ruleMatches(item, tool, command)); const action = rule ? rule.action : policy.defaultAction; const ruleId = rule ? rule.id : "default"; + // "Allow always" on an allowAlways rule lets later matching calls run + // without asking while this gateway runs. Keyed by the policy hash, so a + // policy change asks again. Every call is still audited. + const rememberKey = rule && rule.allowAlways ? `${policyHash}:${ruleId}` : null; + if (rememberKey && input.remembered && input.remembered.has(rememberKey)) { + return { + record: { ...baseRecord(input, { task, rule: ruleId, policyHash, decision: "allow" }), + approval: { mode: "remembered", resolution: "allow-always" } }, + effect: { kind: "allow" }, + }; + } return { record: baseRecord(input, { task, rule: ruleId, policyHash, decision: decisionName(action) }), - effect: effectFor(action, tool, ruleId), + effect: effectFor(action, tool, ruleId, Boolean(rememberKey), + exec && !rule ? sameFamily(policy, command) : ""), + rememberKey, }; } @@ -354,9 +407,13 @@ export function parseIdentity(text) { } } +// Rules the signed-in user answered "Allow always" for, for this gateway process. +const REMEMBERED = new Set(); + // The before_tool_call hook without the OpenClaw import. A thrown audit write // blocks the call. onResolution appends a second line and does not execute. export function evaluateToolCall(input) { + const remembered = input.remembered || REMEMBERED; const identity = input.identityText !== undefined ? parseIdentity(input.identityText) : input.identity; const decided = decide({ policyText: input.policyText, @@ -368,6 +425,7 @@ export function evaluateToolCall(input) { sessionKey: input.sessionKey, sessionId: input.sessionId, now: input.now, + remembered, }); const append = input.appendRecord || (input.auditFile && (record => appendAudit(input.auditFile, record))); if (append) { @@ -383,9 +441,16 @@ export function evaluateToolCall(input) { } } const hook = hookResult(decided, (resolution) => { - if (!append) return; + const remember = () => { + if (resolution === "allow-always" && decided.rememberKey) remembered.add(decided.rememberKey); + }; + if (!append) { + remember(); + return; + } try { append(resolutionRecord(decided.record, resolution)); + remember(); } catch { const record = { ...resolutionRecord(decided.record, resolution), auditWriteFailed: true }; process.stderr.write(`${JSON.stringify(record)}\n`); diff --git a/charts/openshell-saw/files/installer/tool-gate.test.mjs b/charts/openshell-saw/files/installer/tool-gate.test.mjs index 1721d8e49..fec32941b 100644 --- a/charts/openshell-saw/files/installer/tool-gate.test.mjs +++ b/charts/openshell-saw/files/installer/tool-gate.test.mjs @@ -159,12 +159,12 @@ test("identity configuration always requires approval, including file and avatar test("both automation aliases allow only inspection and hold mutations for approval", () => { for (const group of ["cron", "automations"]) { - for (const verb of ["list", "status", "get", "show", "runs"]) { + for (const verb of ["list", "status", "get", "show", "runs", "--help", "edit --help", "rm --help"]) { const result = call({ params: { command: `openclaw ${group} ${verb} --json` } }); assert.equal(result.effect.kind, "allow"); assert.equal(result.record.rule, "exec-openclaw-automation-inspect"); } - for (const verb of ["add", "edit", "rm", "enable", "disable", "run"]) { + for (const verb of ["add", "create", "edit", "rm", "remove", "delete", "enable", "disable", "run"]) { const result = call({ params: { command: `openclaw ${group} ${verb} job-id` } }); assert.equal(result.effect.kind, "approval"); assert.equal(result.record.rule, "exec-openclaw-automation-change"); @@ -175,7 +175,7 @@ test("both automation aliases allow only inspection and hold mutations for appro } } // Unsupported aliases, mixed read/write surfaces and unknown verbs stay denied. - for (const verb of ["", "create", "remove", "delete", "scratch", "listx", "runsx", "run-all"]) { + for (const verb of ["", "scratch", "bind", "listx", "runsx", "run-all", "removex"]) { assert.equal(call({ params: { command: `openclaw ${group} ${verb}` } }).effect.kind, "deny"); } for (const command of [ @@ -520,3 +520,80 @@ test("an unavailable audit file blocks an otherwise allowed call", () => { assert.equal(result.record.rule, "audit-unwritable"); assert.equal(result.hook.block, true); }); + +test("allow always skips later automation approvals but never other rules", () => { + const remembered = new Set(); + const records = []; + const run = (command) => evaluateToolCall({ + policyText, identity, toolName: "exec", params: { command }, sessionKey: "session-1", + appendRecord: (record) => records.push(record), remembered, + }); + const first = run("openclaw cron rm job-1"); + assert.deepEqual(first.hook.requireApproval.allowedDecisions, ["allow-once", "allow-always", "deny"]); + // Allow once remembers nothing. + first.hook.requireApproval.onResolution("allow-once"); + assert.ok(run("openclaw cron edit job-1").hook.requireApproval); + run("openclaw cron add --name x").hook.requireApproval.onResolution("allow-always"); + // Later automation changes run, in any session, and are still audited. + for (const command of ["openclaw cron rm job-1", "openclaw automations edit job-2"]) { + records.length = 0; + assert.equal(run(command).hook, undefined); + assert.equal(records[0].decision, "allow"); + assert.equal(records[0].rule, "exec-openclaw-automation-change"); + assert.deepEqual(records[0].approval, { mode: "remembered", resolution: "allow-always" }); + } + // Other approval rules still ask, and offer no allow always. + const push = run("git push"); + assert.deepEqual(push.hook.requireApproval.allowedDecisions, ["allow-once", "deny"]); + push.hook.requireApproval.onResolution("allow-always"); + assert.ok(run("git push").hook.requireApproval); + // Unmatched commands are still denied. + assert.equal(run("openclaw cron update job-1").hook.block, true); +}); + +test("allow always is forgotten when the policy changes or the answer is not recorded", () => { + const remembered = new Set(); + const changed = policyText.replace("defaultAction: deny", "defaultAction: deny\n# changed"); + const run = (text, append) => evaluateToolCall({ + policyText: text, identity, toolName: "exec", params: { command: "openclaw cron rm job-1" }, + sessionKey: "session-1", appendRecord: append, remembered, + }); + run(policyText, () => {}).hook.requireApproval.onResolution("allow-always"); + assert.equal(run(policyText, () => {}).hook, undefined); + assert.ok(run(changed, () => {}).hook.requireApproval); + const unrecorded = new Set(); + const failing = evaluateToolCall({ + policyText, identity, toolName: "exec", params: { command: "openclaw cron rm job-1" }, + sessionKey: "session-1", remembered: unrecorded, + appendRecord: (record) => { if (record.approval) throw new Error("down"); }, + }); + failing.hook.requireApproval.onResolution("allow-always"); + assert.equal(unrecorded.size, 0); +}); + +test("allowAlways is only valid as true on an approval rule", () => { + const rule = (action, value) => `version: 1\ndefaultAction: deny\nrules:\n - id: r\n tool: exec\n action: ${action}\n allowAlways: ${value}\n`; + assert.equal(parsePolicy(rule("approval", "true")).rules[0].allowAlways, true); + assert.throws(() => parsePolicy(rule("allow", "true")), /allowAlways/); + assert.throws(() => parsePolicy(rule("approval", "yes")), /allowAlways/); +}); + +test("a trailing 2>&1 is accepted, and blocked exec calls say how to retry", () => { + for (const command of ["openclaw automations list --all 2>&1", "git status 2>&1 2>&1", "git status\t2>&1 "]) { + assert.equal(call({ params: { command } }).effect.kind, "allow", command); + } + // Only a trailing stderr merge: any other redirect or chain is still opaque. + for (const command of ["git status 2>&1 | head", "git status > /tmp/x 2>&1", "git status 2>&1; rm -rf /", + "git status 2>/tmp/x", "git status 2>&1\nrm -rf /", "git status &>/tmp/x"]) { + assert.equal(call({ params: { command } }).record.rule, "exec-opaque", command); + } + const opaque = call({ params: { command: "openclaw automations show a; openclaw automations show b" } }); + assert.match(opaque.effect.blockReason, /exec-opaque\. Run one command per exec call/); + const unlisted = call({ params: { command: "openclaw automations scratch" } }); + assert.match(unlisted.effect.blockReason, /not on the allowed list/); + // A wrong spelling learns the accepted ones for the same command family. + const remove = call({ params: { command: "openclaw automations update 69f1c7c1" } }).effect.blockReason; + assert.match(remove, /Accepted `openclaw automations` commands: list, status, get, show, runs, --help \(run directly\); add, create, edit, rm, remove, delete, enable, disable, run \(ask the user for approval\)$/); + assert.doesNotMatch(call({ params: { command: "curl https://x" } }).effect.blockReason, /Accepted/); + assert.match(call({ toolName: "web_fetch", params: {} }).effect.blockReason, /^Tool web_fetch is denied by the default action$/); +}); diff --git a/charts/saw-kubernetes-controller/templates/controller.yaml b/charts/saw-kubernetes-controller/templates/controller.yaml index 029a0b1ab..e1fbe039a 100644 --- a/charts/saw-kubernetes-controller/templates/controller.yaml +++ b/charts/saw-kubernetes-controller/templates/controller.yaml @@ -55,7 +55,7 @@ rules: - {apiGroups: [rbac.authorization.k8s.io], resources: [roles], resourceNames: [{{ $g }}-gateway], verbs: [get]} # Public trust only; no private administrator identity is stored in this Secret. - {apiGroups: [""], resources: [secrets], resourceNames: [{{ $g }}-client-ca], verbs: [get, update]} - - {apiGroups: [""], resources: [configmaps], resourceNames: [{{ $c.profile }}, {{ $c.intent }}, {{ $g }}-gateway-config, {{ $g }}-proxy-ca], verbs: [get]} + - {apiGroups: [""], resources: [configmaps], resourceNames: [{{ $c.profile }}, {{ $c.intent }}, {{ $g }}-gateway-config], verbs: [get]} - {apiGroups: [""], resources: [configmaps], resourceNames: [{{ $c.intent }}], verbs: [watch]} - {apiGroups: [""], resources: [configmaps], resourceNames: [{{ $c.status }}], verbs: [get, update]} - {apiGroups: [""], resources: [persistentvolumeclaims], resourceNames: {{ $.Values.claimNames | toJson }}, verbs: [get]} @@ -64,9 +64,11 @@ rules: - {apiGroups: [networking.k8s.io], resources: [networkpolicies], resourceNames: [{{ $g }}-gateway, {{ $g }}-default-deny, openshell-sandbox-workloads, openshell-sandbox-supervisors], verbs: [get]} {{- else if eq $ns $t }} - {apiGroups: [""], resources: [pods], verbs: [get]} - - {apiGroups: [apps], resources: [deployments], resourceNames: [{{ $g }}-credential-proxy], verbs: [get]} - - {apiGroups: [networking.k8s.io], resources: [networkpolicies], resourceNames: [{{ $g }}-credential-proxy], verbs: [get]} - - {apiGroups: [""], resources: [configmaps], resourceNames: [{{ $c.proxyPolicy }}, {{ $g }}-gateway-ca], verbs: [get]} + - {apiGroups: [""], resources: [configmaps], resourceNames: [{{ $g }}-gateway-ca], verbs: [get]} +{{- with $c.credentialSecrets }} + # Read only to hand each value to OpenShell when a provider is created or rotated. + - {apiGroups: [""], resources: [secrets], resourceNames: {{ toJson . }}, verbs: [get]} +{{- end }} {{- else }} - {apiGroups: [apps], resources: [deployments], resourceNames: [governance-interceptor], verbs: [get]} - {apiGroups: [""], resources: [services], resourceNames: [governance-interceptor], verbs: [get]} diff --git a/charts/saw-kubernetes-identity/values.schema.json b/charts/saw-kubernetes-identity/values.schema.json index 4454aa255..1a36dbd2a 100644 --- a/charts/saw-kubernetes-identity/values.schema.json +++ b/charts/saw-kubernetes-identity/values.schema.json @@ -33,6 +33,46 @@ }, "helperImage": { "type": "string" + }, + "network": { + "type": "object", + "additionalProperties": false, + "required": [ + "bootstrapEgress" + ], + "properties": { + "bootstrapEgress": { + "type": "array", + "items": { + "type": "object", + "required": [ + "to", + "ports" + ], + "additionalProperties": false, + "properties": { + "to": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "minProperties": 1 + } + }, + "ports": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": [ + "port" + ] + } + } + } + } + } + } } } } diff --git a/charts/saw-kubernetes-proxy/Chart.yaml b/charts/saw-kubernetes-proxy/Chart.yaml deleted file mode 100644 index cee97f759..000000000 --- a/charts/saw-kubernetes-proxy/Chart.yaml +++ /dev/null @@ -1,5 +0,0 @@ -apiVersion: v2 -name: saw-kubernetes-proxy -description: Existing SAW credential proxy in a separate trusted namespace -type: application -version: 0.1.0 diff --git a/charts/saw-kubernetes-proxy/files/project_ca.py b/charts/saw-kubernetes-proxy/files/project_ca.py deleted file mode 100644 index 814e982b0..000000000 --- a/charts/saw-kubernetes-proxy/files/project_ca.py +++ /dev/null @@ -1,145 +0,0 @@ -"""Project only the stock proxy's public CA; refuse replacement or adoption. - -The preceding init container runs the unchanged SAW proxy init-ca command. -This helper never reads a Secret, returns credential data or rotates trust. -""" -import json -from pathlib import Path -import re -import ssl -import sys -from urllib.error import HTTPError, URLError -from urllib.request import Request, HTTPSHandler, HTTPRedirectHandler, build_opener -import uuid - -OWNER = "saw.redhat.com/runtime-owner" -KEEP = "Prune=false,Delete=false" -NAME = re.compile(r"[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\Z") -LIMIT = 128 * 1024 - - -class Failure(Exception): - pass - - -class NoRedirect(HTTPRedirectHandler): - def redirect_request(self, req, fp, code, msg, headers, newurl): - return None - - -class Api: - def __init__(self): - root = Path('/var/run/secrets/kubernetes.io/serviceaccount') - self.token = root / 'token' - self.opener = build_opener(NoRedirect(), HTTPSHandler( - context=ssl.create_default_context(cafile=str(root / 'ca.crt')))) - - def call(self, method, path, body=None): - try: - token = self.token.read_text().strip() - if not token or any(c.isspace() for c in token): - raise ValueError() - data = None if body is None else json.dumps(body).encode() - request = Request('https://kubernetes.default.svc' + path, data=data, - headers={'Authorization': 'Bearer ' + token, - 'Content-Type': 'application/json'}, method=method) - with self.opener.open(request, timeout=20) as response: - raw = response.read(LIMIT + 1) - if len(raw) > LIMIT: - raise ValueError() - result = json.loads(raw) - if not isinstance(result, dict): - raise ValueError() - return result - except HTTPError as exc: - status = exc.code - exc.close() - if (method == 'GET' and status == 404) or (method == 'POST' and status == 409): - return None - raise Failure(f'projection API failed ({status})') from None - except (OSError, ValueError, URLError): - raise Failure('projection API unavailable') from None - - -def validate(config): - if not isinstance(config, dict) or set(config) != {'ownerID', 'namespace', 'targetNamespace', 'name'}: - raise Failure('invalid projection fields') - for key in ('namespace', 'targetNamespace', 'name'): - name = config[key] - if (not isinstance(name, str) or len(name) > 63 or not NAME.fullmatch(name) - or name == 'default' or name.startswith(('openshift', 'kube-'))): - raise Failure('dedicated projection names required') - if config['namespace'] == config['targetNamespace']: - raise Failure('proxy and runtime namespaces must differ') - try: - identity = uuid.UUID(config['ownerID']) - if str(identity) != config['ownerID'] or identity.int == 0: - raise ValueError() - except (ValueError, TypeError, AttributeError): - raise Failure('canonical nonzero installation UUID required') from None - - -def mapping(value): - if not isinstance(value, dict): - raise Failure('invalid projection object') - return value - - -def metadata(obj): - meta = mapping(mapping(obj or {}).get('metadata', {})) - mapping(meta.get('labels', {})) - mapping(meta.get('annotations', {})) - return meta - - -def project(api, config): - validate(config) - owner = config['ownerID'] - for namespace in (config['namespace'], config['targetNamespace']): - obj = api.call('GET', '/api/v1/namespaces/' + namespace) - meta = metadata(obj) - if (meta.get('name') != namespace or meta.get('deletionTimestamp') - or meta.get('labels', {}).get(OWNER) != owner): - raise Failure('namespace ownership mismatch') - name = config['name'] - source = api.call('GET', f"/api/v1/namespaces/{config['namespace']}/configmaps/{name}") - meta = metadata(source) - data = mapping((source or {}).get('data', {})) - if (meta.get('name') != name or meta.get('namespace') != config['namespace'] - or meta.get('deletionTimestamp') or set(data) != {'ca.crt'} - or (source or {}).get('binaryData')): - raise Failure('invalid public CA source') - cert = data['ca.crt'] - if (not isinstance(cert, str) or len(cert) > 32768 or 'PRIVATE KEY' in cert - or not re.fullmatch(r'-----BEGIN CERTIFICATE-----\s+[A-Za-z0-9+/=\s]+-----END CERTIFICATE-----\s*', cert)): - raise Failure('public certificate only') - try: - ssl.create_default_context().load_verify_locations(cadata=cert) - except (ValueError, ssl.SSLError): - raise Failure('invalid public certificate') from None - base = f"/api/v1/namespaces/{config['targetNamespace']}/configmaps" - existing = api.call('GET', base + '/' + name) - if existing is None: - api.call('POST', base, {'apiVersion': 'v1', 'kind': 'ConfigMap', - 'metadata': {'name': name, 'namespace': config['targetNamespace'], - 'labels': {OWNER: owner}, - 'annotations': {'argocd.argoproj.io/sync-options': KEEP}}, - 'immutable': True, 'data': {'ca.crt': cert}}) - existing = api.call('GET', base + '/' + name) - meta = metadata(existing) - if (meta.get('name') != name or meta.get('namespace') != config['targetNamespace'] - or meta.get('deletionTimestamp') or meta.get('ownerReferences') - or meta.get('labels', {}).get(OWNER) != owner - or meta.get('annotations', {}).get('argocd.argoproj.io/sync-options') != KEEP - or (existing or {}).get('immutable') is not True - or (existing or {}).get('binaryData') or (existing or {}).get('data') != {'ca.crt': cert}): - raise Failure('public projection differs; explicit trust recovery required') - - -if __name__ == '__main__': - try: - project(Api(), json.loads(Path('/config/config.json').read_text())) - print('Public proxy CA projection verified') - except (Failure, OSError, ValueError) as exc: - print(str(exc) if isinstance(exc, Failure) else 'projection configuration unavailable', file=sys.stderr) - sys.exit(1) diff --git a/charts/saw-kubernetes-proxy/templates/proxy.yaml b/charts/saw-kubernetes-proxy/templates/proxy.yaml deleted file mode 100644 index ac074fa66..000000000 --- a/charts/saw-kubernetes-proxy/templates/proxy.yaml +++ /dev/null @@ -1,226 +0,0 @@ -{{- if .Values.enabled }} -{{- $v := .Values -}} -{{- range $name := list .Release.Namespace $v.targetNamespace $v.gateway }} -{{- if or (gt (len $name) 40) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $name)) (eq $name "default") (hasPrefix "openshift" $name) (hasPrefix "kube-" $name) }}{{- fail "dedicated DNS-label names of at most 40 characters required" }}{{- end }}{{- end }} -{{- if eq .Release.Namespace $v.targetNamespace }}{{- fail "trusted and runtime namespaces must differ" }}{{- end }} -{{- if or (eq $v.ownerID "00000000-0000-0000-0000-000000000000") (not (regexMatch "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" $v.ownerID)) }}{{- fail "installation UUID required" }}{{- end }} -{{- range $image := list $v.image $v.helperImage }}{{- if not (regexMatch "^.+@sha256:[0-9a-f]{64}$" $image) }}{{- fail "digest-pinned images required" }}{{- end }}{{- end }} -{{- if or (not $v.policyConfigMap) (not $v.credentialSecretNames) (not $v.network.bootstrapEgress) (not $v.network.proxyEgress) }}{{- fail "existing policy, credential references and explicit egress required" }}{{- end }} -{{- range $name := append (deepCopy $v.credentialSecretNames) $v.policyConfigMap }}{{- if or (gt (len $name) 63) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $name)) }}{{- fail "policy and credential references must be DNS labels" }}{{- end }}{{- end }} -{{- if ne (len (uniq $v.credentialSecretNames)) (len $v.credentialSecretNames) }}{{- fail "duplicate credential reference" }}{{- end }} -{{- if not (regexMatch "^[0-9a-f]{64}$" $v.policyDigest) }}{{- fail "SHA256 of policy config.json required for explicit rollout" }}{{- end }} -{{- $name := printf "%s-credential-proxy" $v.gateway }} -{{- $job := printf "%s-proxy-bootstrap" $v.gateway }} -{{- $ca := printf "%s-proxy-ca" $v.gateway }} -apiVersion: v1 -kind: ConfigMap -metadata: - name: {{ $job }} - annotations: {argocd.argoproj.io/sync-wave: "-20"} -data: - config.json: {{ dict "ownerID" $v.ownerID "namespace" .Release.Namespace "targetNamespace" $v.targetNamespace "name" $ca | toJson | quote }} - project_ca.py: | -{{ .Files.Get "files/project_ca.py" | indent 4 }} ---- -apiVersion: v1 -kind: ServiceAccount -metadata: - name: {{ $job }} - annotations: {argocd.argoproj.io/sync-wave: "-20"} -automountServiceAccountToken: false -{{- range $ns := list .Release.Namespace $v.targetNamespace }} ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: - name: {{ $job }} - namespace: {{ $ns }} - annotations: {argocd.argoproj.io/sync-wave: "-20"} -rules: - - apiGroups: [""] - resources: [configmaps] - verbs: [create] - - apiGroups: [""] - resources: [configmaps] - resourceNames: [{{ $ca }}] - verbs: [get{{ if eq $ns $.Release.Namespace }}, update{{ end }}] -{{- if eq $ns $.Release.Namespace }} - - apiGroups: [""] - resources: [secrets] - verbs: [create] - - apiGroups: [""] - resources: [secrets] - resourceNames: [{{ $ca }}] - verbs: [get] -{{- end }} ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - name: {{ $job }} - namespace: {{ $ns }} - annotations: {argocd.argoproj.io/sync-wave: "-20"} -roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: {{ $job }}} -subjects: - - {kind: ServiceAccount, name: {{ $job }}, namespace: {{ $.Release.Namespace }}} -{{- end }} ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - name: {{ .Release.Namespace }}-{{ $job }} - annotations: {argocd.argoproj.io/sync-wave: "-20"} -rules: - - apiGroups: [""] - resources: [namespaces] - resourceNames: [{{ .Release.Namespace }}, {{ $v.targetNamespace }}] - verbs: [get] ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - name: {{ .Release.Namespace }}-{{ $job }} - annotations: {argocd.argoproj.io/sync-wave: "-20"} -roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: {{ .Release.Namespace }}-{{ $job }}} -subjects: - - {kind: ServiceAccount, name: {{ $job }}, namespace: {{ .Release.Namespace }}} ---- -apiVersion: networking.k8s.io/v1 -kind: NetworkPolicy -metadata: - name: {{ $job }} - annotations: {argocd.argoproj.io/sync-wave: "-20"} -spec: - podSelector: - matchLabels: {app.kubernetes.io/instance: {{ $v.gateway }}, openshell.pattern/role: proxy-bootstrap} - policyTypes: [Ingress, Egress] - ingress: [] - egress: -{{ toYaml $v.network.bootstrapEgress | indent 4 }} ---- -apiVersion: batch/v1 -kind: Job -metadata: - name: {{ $job }} - annotations: - argocd.argoproj.io/hook: Sync - argocd.argoproj.io/hook-delete-policy: BeforeHookCreation,HookSucceeded - argocd.argoproj.io/sync-wave: "-10" -spec: - backoffLimit: 2 - activeDeadlineSeconds: 300 - template: - metadata: - labels: {app.kubernetes.io/instance: {{ $v.gateway }}, openshell.pattern/role: proxy-bootstrap} - spec: - serviceAccountName: {{ $job }} - automountServiceAccountToken: false - restartPolicy: Never - securityContext: {runAsNonRoot: true, seccompProfile: {type: RuntimeDefault}} - initContainers: - - name: stock-ca - image: {{ $v.image }} - args: [init-ca] - env: - - {name: POD_NAMESPACE, value: {{ .Release.Namespace }}} - - {name: SAW_CA_SECRET_NAME, value: {{ $ca }}} - - {name: SAW_CA_CONFIGMAP_NAME, value: {{ $ca }}} - securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}} - resources: {requests: {cpu: 50m, memory: 64Mi}, limits: {memory: 256Mi}} - volumeMounts: - - {name: api, mountPath: /var/run/secrets/kubernetes.io/serviceaccount, readOnly: true} - containers: - - name: public-projection - image: {{ $v.helperImage }} - command: [python3, /config/project_ca.py] - env: [{name: PYTHONDONTWRITEBYTECODE, value: "1"}] - securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}} - resources: {requests: {cpu: 50m, memory: 64Mi}, limits: {memory: 256Mi}} - volumeMounts: - - {name: api, mountPath: /var/run/secrets/kubernetes.io/serviceaccount, readOnly: true} - - {name: config, mountPath: /config, readOnly: true} - volumes: - - name: config - configMap: {name: {{ $job }}} - - name: api - projected: - defaultMode: 0440 - sources: - - serviceAccountToken: {path: token, expirationSeconds: 600} - - configMap: {name: kube-root-ca.crt, items: [{key: ca.crt, path: ca.crt}]} ---- -apiVersion: v1 -kind: ServiceAccount -metadata: {name: {{ $name }}} -automountServiceAccountToken: false ---- -apiVersion: apps/v1 -kind: Deployment -metadata: {name: {{ $name }}} -spec: - replicas: 1 - selector: - matchLabels: {app.kubernetes.io/instance: {{ $v.gateway }}, openshell.pattern/role: credential-proxy} - template: - metadata: - annotations: {checksum/policy: {{ $v.policyDigest | quote }}} - labels: {app.kubernetes.io/instance: {{ $v.gateway }}, openshell.pattern/role: credential-proxy} - spec: - serviceAccountName: {{ $name }} - automountServiceAccountToken: false - securityContext: {runAsNonRoot: true, seccompProfile: {type: RuntimeDefault}} - containers: - - name: proxy - image: {{ $v.image }} - args: [serve] - securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}} - resources: {requests: {cpu: 50m, memory: 64Mi}, limits: {memory: 256Mi}} - ports: [{name: connect, containerPort: 3128}, {name: health, containerPort: 8081}] - readinessProbe: {httpGet: {path: /healthz, port: health}, periodSeconds: 5} - livenessProbe: {tcpSocket: {port: connect}, periodSeconds: 30} - volumeMounts: - - {name: policy, mountPath: /etc/saw-proxy, readOnly: true} - - {name: ca, mountPath: /var/run/saw/ca, readOnly: true} -{{- range $i, $secret := $v.credentialSecretNames }} - - {name: credential-{{ $i }}, mountPath: /var/run/saw/secrets/{{ $secret }}, readOnly: true} -{{- end }} - volumes: - - name: policy - configMap: {name: {{ $v.policyConfigMap }}} - - name: ca - secret: {secretName: {{ $ca }}, defaultMode: 0440} -{{- range $i, $secret := $v.credentialSecretNames }} - - name: credential-{{ $i }} - secret: {secretName: {{ $secret }}, defaultMode: 0440} -{{- end }} ---- -apiVersion: v1 -kind: Service -metadata: {name: {{ $name }}} -spec: - selector: - app.kubernetes.io/instance: {{ $v.gateway }} - openshell.pattern/role: credential-proxy - ports: [{name: connect, port: 3128, targetPort: connect}] ---- -apiVersion: networking.k8s.io/v1 -kind: NetworkPolicy -metadata: {name: {{ $name }}} -spec: - podSelector: - matchLabels: {app.kubernetes.io/instance: {{ $v.gateway }}, openshell.pattern/role: credential-proxy} - policyTypes: [Ingress, Egress] - ingress: - - from: - - namespaceSelector: - matchLabels: {kubernetes.io/metadata.name: {{ $v.targetNamespace }}} - podSelector: - matchLabels: {app.kubernetes.io/instance: {{ $v.gateway }}, openshell.pattern/role: gateway} - - namespaceSelector: - matchLabels: {kubernetes.io/metadata.name: {{ $v.targetNamespace }}} - podSelector: - matchLabels: {openshell.ai/gateway-id: {{ $v.gateway }}, openshell.ai/boundary-role: supervisor} - ports: [{protocol: TCP, port: 3128}] - egress: -{{ toYaml $v.network.proxyEgress | indent 4 }} -{{- end }} diff --git a/charts/saw-kubernetes-proxy/values.schema.json b/charts/saw-kubernetes-proxy/values.schema.json deleted file mode 100644 index daa6b9bd3..000000000 --- a/charts/saw-kubernetes-proxy/values.schema.json +++ /dev/null @@ -1,111 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "type": "object", - "additionalProperties": false, - "properties": { - "ownerID": { - "type": "string" - }, - "targetNamespace": { - "type": "string" - }, - "gateway": { - "type": "string" - }, - "policyConfigMap": { - "type": "string" - }, - "policyDigest": { - "type": "string" - }, - "image": { - "type": "string" - }, - "helperImage": { - "type": "string" - }, - "enabled": { - "type": "boolean" - }, - "credentialSecretNames": { - "type": "array", - "uniqueItems": true, - "maxItems": 16, - "items": { - "type": "string" - } - }, - "network": { - "type": "object", - "additionalProperties": false, - "required": [ - "bootstrapEgress", - "proxyEgress" - ], - "properties": { - "bootstrapEgress": { - "type": "array", - "items": { - "type": "object", - "required": [ - "to", - "ports" - ], - "additionalProperties": false, - "properties": { - "to": { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "minProperties": 1 - } - }, - "ports": { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "required": [ - "port" - ] - } - } - } - } - }, - "proxyEgress": { - "type": "array", - "items": { - "type": "object", - "required": [ - "to", - "ports" - ], - "additionalProperties": false, - "properties": { - "to": { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "minProperties": 1 - } - }, - "ports": { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "required": [ - "port" - ] - } - } - } - } - } - } - } - } -} diff --git a/charts/saw-kubernetes-proxy/values.yaml b/charts/saw-kubernetes-proxy/values.yaml deleted file mode 100644 index 499e458b2..000000000 --- a/charts/saw-kubernetes-proxy/values.yaml +++ /dev/null @@ -1,17 +0,0 @@ -enabled: false -ownerID: "" -targetNamespace: "" -gateway: "" -# Administrator-owned policy and ESO-created credentials in the release namespace. -# No credential values are accepted by this chart. -policyConfigMap: "" -# SHA256 of config.json; changing policy must roll the stock proxy. -policyDigest: "" -credentialSecretNames: [] -image: ghcr.io/validatedpatterns-sandbox/saw-credential-proxy@sha256:73f271de2eb6166315603fbb72c800b939a14770a69c86debaabbd29a46a0f93 -helperImage: registry.access.redhat.com/ubi9/python-311@sha256:a0bdb55576fc5b8d6704279307817828ef027e1065533ceba133fe9516003a6c -network: - # Standard NetworkPolicy egress rules. Bootstrap needs only API access. - bootstrapEgress: [] - # Explicit DNS and approved upstream paths; the proxy also checks host policy. - proxyEgress: [] diff --git a/charts/saw-portal-container/files/enroll.py b/charts/saw-portal-container/files/enroll.py index 9780d7ad0..0179ffb97 100644 --- a/charts/saw-portal-container/files/enroll.py +++ b/charts/saw-portal-container/files/enroll.py @@ -39,6 +39,16 @@ def obj(kind,name,namespace=ns): return api("/api/v1/namespaces/"+namespace+"/"+plural+"/"+name) nsobj=obj("namespace",ns)["metadata"] if nsobj["labels"].get("saw.redhat.com/runtime-owner")!=ident or nsobj.get("deletionTimestamp"):raise ValueError("namespace ownership") + if x.get("autoApprove"): + # autoApprove publishes the first observation once. A rerun (new chart + # inputs) must not compare it with today's, which includes the running + # workspace; the reconciler still rejects later boundary changes. + published=api(f"/api/v1/namespaces/{t}/configmaps/saw-portal-enrollment") + binding=(published.get("data") or {}).get("binding.json") + if ((published["metadata"].get("labels") or {}).get("saw.redhat.com/runtime-owner")==ident + and binding and json.loads(binding).get("registration")==r): + print("Registration "+r+" is already enrolled",flush=True) + return if runtime: try: runtime_class=obj("runtimeclass",runtime["name"]) @@ -74,16 +84,20 @@ def obj(kind,name,namespace=ns): ("validatingadmissionpolicies", "validatingadmissionpolicybindings")) verify_kata_platform(x, runtime_class, configs, nodes, api_readiness, cluster_version) cfg=dict(namespace=ns,namespaceUID=nsobj["uid"],ownerID=ident,mode=mode,trustedNamespace=t, - governanceNamespace=x["governance"],gateway=u,proxyPolicy=u+"-proxy-policy",slotKeys=sorted(x["targets"])) + governanceNamespace=x["governance"],gateway=u,slotKeys=sorted(x["targets"])) if runtime: cfg["workloadRuntimeClass"]=runtime["name"] cache={} def get(p): if p not in cache:cache[p]=api(p) return cache[p] - approved=capture(cfg,get)["approved"] - verify_contract(cfg,get,x["reference"]) + approved=capture(cfg,get)["approved"] # health, admission and network checks always run profile=obj("configmap","saw-bom-profiles") - if digest(profile["data"])!=x["profileSHA256"]:raise ValueError("unapproved BOM") + if not x.get("autoApprove"): + # Reviewed sites compare the live boundary and BOM with the operator's approval. + # autoApprove (an explicit cluster setting) publishes this first observation instead; + # later changes to the enrolled boundary still fail closed. + verify_contract(cfg,get,x["reference"]) + if digest(profile["data"])!=x["profileSHA256"]:raise ValueError("unapproved BOM") def pvc(name,ro): return dict(claimName=name,uid=obj("persistentvolumeclaim",name)["metadata"]["uid"],readOnly=ro) harnesses = {} @@ -115,10 +129,8 @@ def pvc(name,ro): if runtime: bindings.update(workloadRuntimeClass=runtime["name"],workloadRuntimeClassUID=runtime["uid"], workloadRuntimeClassDigest=runtime["sha256"]) - if x.get("providerPolicy"): - bindings["proxyBindings"] = [{"secret": b["secret"], "key": b["key"], "type": typ, - "refresh": bool(b.get("refresh"))} - for b in x["providerPolicy"]["bindings"] for typ in b["providers"]] + if x.get("credentialBindings"): + bindings["credentialBindings"] = x["credentialBindings"] if x.get("customInferenceURL"): bindings["customInferenceURL"] = x["customInferenceURL"] if x.get("modelInputs"): diff --git a/charts/saw-portal-container/files/portal_contract.py b/charts/saw-portal-container/files/portal_contract.py index 94cd4e791..9257a94d0 100644 --- a/charts/saw-portal-container/files/portal_contract.py +++ b/charts/saw-portal-container/files/portal_contract.py @@ -9,7 +9,6 @@ import ipaddress import json import re -import ssl from saw_kubernetes.boundary import BoundaryError, fingerprint, objects @@ -25,19 +24,6 @@ def contract(config, get): # Cluster installation is shared across registrations. Keep both UID and hash. output[key]={"uid":obj["metadata"]["uid"],"sha256":fingerprint(value)} continue - if key=="publicCA": - source=get(f"/api/v1/namespaces/{trusted}/configmaps/{config['gateway']}-proxy-ca") - if obj.get("metadata",{}).get("labels",{}).get("saw.redhat.com/runtime-owner")!=owner or set(value)!={"ca.crt"} or value!=source.get("data") or source["metadata"].get("deletionTimestamp"): - raise BoundaryError("UntrustedProxyCA") - cert=value["ca.crt"] - if not re.fullmatch(r"-----BEGIN CERTIFICATE-----\s+[A-Za-z0-9+/=\s]+-----END CERTIFICATE-----\s*",cert): - raise BoundaryError("InvalidProxyCA") - try: - ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT).load_verify_locations(cadata=cert) - except (ssl.SSLError,ValueError) as exc: - raise BoundaryError("InvalidProxyCA") from exc - output[key]="equals independent trusted proxy public CA" - continue if key=="gatewayService": ips=value.get("clusterIPs") if (value.get("type")!="ClusterIP" or not isinstance(ips,list) or not ips or value.get("clusterIP")!=ips[0] diff --git a/charts/saw-portal-container/files/preflight.py b/charts/saw-portal-container/files/preflight.py index c32862180..dc499183c 100644 --- a/charts/saw-portal-container/files/preflight.py +++ b/charts/saw-portal-container/files/preflight.py @@ -196,24 +196,33 @@ def check_observations(mode, observations): return tuple(required) +# Reviewed sites pin every chart to a full commit SHA. An autoApprove +# (development) site may follow a branch instead: saw-users and portal defaults +# use global.targetRevision when a site sets no revision. +PINNED_REVISION = r"[a-f0-9]{40}" +BRANCH_REVISION = r"[a-f0-9]{40}|[A-Za-z0-9][A-Za-z0-9._/-]*" + + def configuration_facts(site): """Check site-owned inputs that do not require cluster access.""" if not isinstance(site, dict): return {key: False for key in ("network", "storage", "secrets", "registry", "providerEgress", "revisions")} stack = site.get("stack") if isinstance(site.get("stack"), dict) else {} + enrollment = site.get("automaticEnrollment") or {} + revision_pattern = BRANCH_REVISION if isinstance(enrollment, dict) and enrollment.get( + "autoApprove") is True else PINNED_REVISION revisions = [item.get("revision") for item in stack.values() if isinstance(item, dict)] - required_components = ("identity", "policy", "proxy", "gateway", "audit") + required_components = ("identity", "policy", "gateway", "audit") revision_pin = all(isinstance(stack.get(name), dict) for name in required_components) and all( isinstance(stack[name].get("revision"), str) - and re.fullmatch(r"[a-f0-9]{40}", stack[name]["revision"]) + and re.fullmatch(revision_pattern, stack[name]["revision"]) for name in required_components) and bool(revisions) and len(revisions) == len(stack) and all( - isinstance(value, str) and re.fullmatch(r"[a-f0-9]{40}", value) for value in revisions) - enrollment = site.get("automaticEnrollment") or {} + isinstance(value, str) and re.fullmatch(revision_pattern, value) for value in revisions) if enrollment and not isinstance(enrollment, dict): revision_pin = False elif enrollment: - revision_pin = revision_pin and bool(re.fullmatch(r"[a-f0-9]{40}", str(enrollment.get("revision", "")))) + revision_pin = revision_pin and bool(re.fullmatch(revision_pattern, str(enrollment.get("revision", "")))) image_values = [] storage_values = [] @@ -233,28 +242,20 @@ def walk(value, path=()): walk(child, path) walk(site) - declared_hosts = site.get("providerAllowHosts") - policy = site.get("providerPolicy") - clean_hosts = (isinstance(declared_hosts, list) and bool(declared_hosts) - and all(isinstance(host, str) and host and "*" not in host - for host in declared_hosts) - and (policy is None or (isinstance(policy, dict) - and isinstance(policy.get("allowHosts"), list) - and all(isinstance(host, str) for host in policy["allowHosts"]) - and set(policy["allowHosts"]) == set(declared_hosts)))) - proxy = stack.get("proxy") or {} - proxy_values = proxy.get("values") or {} if isinstance(proxy, dict) else {} - bootstrap_egress = ((proxy_values.get("network") or {}).get("bootstrapEgress") - if isinstance(proxy_values, dict) else None) + # OpenShell decides where each credential may go (provider profiles); the + # site only lists which Secret backs which provider type. + bindings = site.get("credentialBindings") + clean_bindings = (isinstance(bindings, list) and all( + isinstance(b, dict) and {"secret", "key", "type"} <= set(b) <= {"secret", "key", "type", "refresh"} + and all(isinstance(v, str) and v for v in b.values()) for b in bindings)) storage_ok = bool(storage_values) and all(value.strip() for value in storage_values) return { - "network": bool(stack.get("policy")) and isinstance(bootstrap_egress, list) - and bool(bootstrap_egress), + "network": bool(stack.get("policy")), "storage": storage_ok, "secrets": isinstance(site.get("secretStore", "vault-backend"), str) and bool(site.get("secretStore", "vault-backend")), "registry": bool(image_values) and all("@sha256:" in image for image in image_values), - "providerEgress": clean_hosts, + "providerEgress": clean_bindings, "revisions": revision_pin, } diff --git a/charts/saw-portal-container/templates/_helpers.tpl b/charts/saw-portal-container/templates/_helpers.tpl index a6ad840c2..195f01797 100644 --- a/charts/saw-portal-container/templates/_helpers.tpl +++ b/charts/saw-portal-container/templates/_helpers.tpl @@ -1,6 +1,6 @@ {{/* Targets are derived from the selected BOM, never a fixed profile. */}} {{- define "portal.targets" -}} -{{- $s := .Values.site | default dict -}} +{{- $s := include "portal.site" . | fromJson -}} {{ required "BOM-derived sandbox targets are required" $s.targets | toJson }} {{- end -}} {{- define "portal.claims" -}} @@ -11,3 +11,49 @@ {{- end -}}{{- end -}} {{ $claims | toJson }} {{- end -}} + +{{/* The namespace whose ImageStreams the runtime image is pulled from: the +site's buildNamespace when the image is in the OpenShift internal registry, +else "" (a published image needs no pull grant, and the namespace need not +exist). Takes the enrollment or automaticEnrollment dict. */}} +{{- define "portal.pullNamespace" -}} +{{- if hasPrefix "image-registry.openshift-image-registry.svc:5000/" (.image | default "") -}}{{ .buildNamespace }}{{- end -}} +{{- end -}} + +{{/* Chart revisions a site may use. Reviewed sites pin every chart to a full +commit SHA; an autoApprove (development) site may follow a branch. The +portal and installer preflight apply the same rule (preflight.py). */}} +{{- define "portal.revisionPattern" -}} +{{- $a := (include "portal.site" . | fromJson).automaticEnrollment | default dict -}} +{{- if eq (toString ($a.autoApprove | default false)) "true" -}}^[A-Za-z0-9][A-Za-z0-9._/-]*${{- else -}}^[a-f0-9]{40}${{- end -}} +{{- end -}} + +{{/* Recursive merge of .over into .base by key presence (as saw-users.deepMerge): +a false, 0 or "" in .over replaces the base value. Maps merge; every other +value (lists included) is replaced. Returns JSON. */}} +{{- define "portal.deepMerge" -}} +{{- $out := deepCopy (.base | default dict) -}} +{{- range $key, $value := (.over | default dict) -}} +{{- $current := index $out $key -}} +{{- if and (kindIs "map" $value) (kindIs "map" $current) -}} +{{- $_ := set $out $key (include "portal.deepMerge" (dict "base" $current "over" $value) | fromJson) -}} +{{- else -}} +{{- $_ := set $out $key $value -}} +{{- end -}} +{{- end -}} +{{- toJson $out -}} +{{- end -}} + +{{/* The site layered over siteDefaults. A published enrollment carries the +site's relay settings and build namespace; fill what the site left to the +defaults, and let the relay follow the enrollment revision. Returns JSON. */}} +{{- define "portal.site" -}} +{{- $site := include "portal.deepMerge" (dict "base" .Values.siteDefaults "over" (.Values.site | default dict)) | fromJson -}} +{{- with $site.enrollment -}} +{{- $a := $site.automaticEnrollment -}} +{{- $_ := set . "relay" (include "portal.deepMerge" (dict "base" ($a.relay | default dict) "over" (.relay | default dict)) | fromJson) -}} +{{- if not .relay.revision }}{{ $_ := set .relay "revision" .revision }}{{ end -}} +{{- if not .buildNamespace }}{{ $_ := set . "buildNamespace" $a.buildNamespace }}{{ end -}} +{{- end -}} +{{- toJson $site -}} +{{- end -}} diff --git a/charts/saw-portal-container/templates/auto-enroll.yaml b/charts/saw-portal-container/templates/auto-enroll.yaml index 47853e0fc..a39dbe2ed 100644 --- a/charts/saw-portal-container/templates/auto-enroll.yaml +++ b/charts/saw-portal-container/templates/auto-enroll.yaml @@ -1,6 +1,7 @@ -{{- $s := .Values.site | default dict }}{{- $a := $s.automaticEnrollment | default dict }} -{{- if and $a (ne (get $a "enabled" | toString) "false") }} -{{- if or (not (regexMatch "^.+@sha256:[a-f0-9]{64}$" $a.image)) (not (regexMatch "^[a-f0-9]{40}$" $a.revision)) (ne (len $a.reference) (ternary 27 25 (not (empty $s.kataRuntimeClass)))) }}{{ fail "automatic enrollment requires pinned code and a reviewed boundary" }}{{- end }} +{{- $s := include "portal.site" . | fromJson }}{{- $a := $s.automaticEnrollment | default dict }} +{{- if and (.Values.site | default dict).automaticEnrollment (ne (get $a "enabled" | toString) "false") }} +{{- $autoApprove := eq (toString ($a.autoApprove | default false)) "true" }} +{{- if or (not (regexMatch "^.+@sha256:[a-f0-9]{64}$" $a.image)) (not (regexMatch (include "portal.revisionPattern" $) ($a.revision | default ""))) (and (not $autoApprove) (ne (len ($a.reference | default dict)) (ternary 23 21 (not (empty $s.kataRuntimeClass))))) }}{{ fail "automatic enrollment requires a pinned image, a full Git commit SHA revision and a reviewed boundary (or autoApprove, which may follow a branch)" }}{{- end }} {{- $observer := $s.observer | default dict }} {{- $r := .Values.registration }}{{- $g := .Values.owner }}{{- $n := .Release.Namespace }} {{- $t := printf "saw-ctl-%s" $r }}{{- $archive := printf "saw-history-%s" $r }} @@ -8,7 +9,7 @@ {{- $bases := list }}{{- range $slot := $targets }}{{- $bases = append $bases $slot.base }}{{- end }} {{- $gov := $s.governanceNamespace }}{{- $name := printf "enroll-%s" $r }}{{- $policy := printf "saw-%s-runtime" $n }} {{- $gatewayVersion := dig "stack" "gateway" "values" "kubernetes" "gateway" "version" .Values.driverDefaults.gatewayVersion $s -}} -{{- $bootstrap := dict "registration" $r "installation" .Values.installationID "user" $g "subject" .Values.ownerSubject "governance" $gov "reference" $a.reference "profileSHA256" ($s.selectedDigest | default $a.profileSHA256) "targets" $targets "gatewayVersion" $gatewayVersion "customInferenceURL" ($s.customInferenceURL | default "") "providerPolicy" ($s.providerPolicy | default dict) "lifecycleVersion" ($s.lifecycleVersion | default 0) "modelInputs" ($s.modelInputs | default dict) "resources" $a.resources "domain" .Values.global.clusterDomain -}} +{{- $bootstrap := dict "registration" $r "installation" .Values.installationID "user" $g "subject" .Values.ownerSubject "governance" $gov "reference" ($a.reference | default dict) "autoApprove" $autoApprove "profileSHA256" ($s.selectedDigest | default $a.profileSHA256) "targets" $targets "gatewayVersion" $gatewayVersion "customInferenceURL" ($s.customInferenceURL | default "") "credentialBindings" ($s.credentialBindings | default list) "lifecycleVersion" ($s.lifecycleVersion | default 0) "modelInputs" ($s.modelInputs | default dict) "resources" $a.resources "domain" .Values.global.clusterDomain -}} {{- $scripts := (.Files.Glob "files/*.py").AsConfig -}} {{- with $s.kataRuntimeClass }}{{- $_ := set $bootstrap "kataRuntimeClass" . }}{{- end }} {{- $revision := dict "chartVersion" .Chart.Version "image" $a.image "config" $bootstrap "scripts" $scripts | toJson | sha256sum | trunc 12 -}} @@ -48,15 +49,13 @@ metadata: {name: {{ $name }}, namespace: {{ $ns }}} rules: {{- if eq $ns $n }} - {apiGroups: [rbac.authorization.k8s.io], resources: [roles], resourceNames: [{{ $g }}-gateway], verbs: [get]} - - {apiGroups: [""], resources: [configmaps], resourceNames: [saw-bom-profiles, {{ $g }}-gateway-config, {{ $g }}-proxy-ca], verbs: [get]} + - {apiGroups: [""], resources: [configmaps], resourceNames: [saw-bom-profiles, {{ $g }}-gateway-config], verbs: [get]} - {apiGroups: [""], resources: [persistentvolumeclaims], resourceNames: {{ include "portal.claims" $ }}, verbs: [get]} - {apiGroups: [apps], resources: [statefulsets], resourceNames: [{{ $g }}-gateway], verbs: [get]} - {apiGroups: [""], resources: [services], resourceNames: [{{ $g }}-gateway], verbs: [get]} - {apiGroups: [networking.k8s.io], resources: [networkpolicies], resourceNames: [{{ $g }}-gateway, {{ $g }}-default-deny, openshell-sandbox-workloads, openshell-sandbox-supervisors], verbs: [get]} {{- else if eq $ns $t }} - - {apiGroups: [apps], resources: [deployments], resourceNames: [{{ $g }}-credential-proxy], verbs: [get]} - - {apiGroups: [networking.k8s.io], resources: [networkpolicies], resourceNames: [{{ $g }}-credential-proxy], verbs: [get]} - - {apiGroups: [""], resources: [configmaps], resourceNames: [{{ $g }}-proxy-policy, {{ $g }}-proxy-ca, {{ $g }}-gateway-ca], verbs: [get]} + - {apiGroups: [""], resources: [configmaps], resourceNames: [{{ $g }}-gateway-ca], verbs: [get]} - {apiGroups: [""], resources: [configmaps], resourceNames: [saw-portal-enrollment], verbs: [get, patch]} {{- else }} - {apiGroups: [apps], resources: [deployments], resourceNames: [governance-interceptor], verbs: [get]} @@ -71,17 +70,19 @@ roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: {{ $name }}} subjects: [{kind: ServiceAccount, name: {{ $name }}, namespace: {{ $t }}}] {{- end }} +{{- with include "portal.pullNamespace" $a }} --- apiVersion: rbac.authorization.k8s.io/v1 kind: Role -metadata: {name: {{ $name }}-pull, namespace: {{ $a.buildNamespace }}} +metadata: {name: {{ $name }}-pull, namespace: {{ . }}} rules: [{apiGroups: [image.openshift.io], resources: [imagestreams/layers], resourceNames: [{{ base (index (splitList "@" $a.image) 0) | quote }}], verbs: [get]}] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding -metadata: {name: {{ $name }}-pull, namespace: {{ $a.buildNamespace }}} +metadata: {name: {{ $name }}-pull, namespace: {{ . }}} roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: {{ $name }}-pull} subjects: [{kind: ServiceAccount, name: {{ $name }}, namespace: {{ $t }}}] +{{- end }} --- apiVersion: v1 kind: ConfigMap @@ -110,7 +111,7 @@ spec: podSelector: {matchLabels: {app: {{ $name }}}} policyTypes: [Egress] egress: -{{ toYaml $s.stack.proxy.values.network.bootstrapEgress | indent 4 }} +{{ toYaml $s.stack.identity.values.network.bootstrapEgress | indent 4 }} - to: - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: {{ $archive }}}} podSelector: {matchExpressions: [{key: saw-audit-writer, operator: In, values: {{ $bases | toJson }}}]} diff --git a/charts/saw-portal-container/templates/enrolled-runtime.yaml b/charts/saw-portal-container/templates/enrolled-runtime.yaml index c82c2714d..1f81eaddf 100644 --- a/charts/saw-portal-container/templates/enrolled-runtime.yaml +++ b/charts/saw-portal-container/templates/enrolled-runtime.yaml @@ -1,4 +1,4 @@ -{{- $site := .Values.site | default dict }} +{{- $site := include "portal.site" . | fromJson }} {{- $e := $site.enrollment | default dict }} {{- if and $e (eq $e.registration .Values.registration) }} {{- $reg := .Values.registration }} @@ -32,17 +32,19 @@ apiVersion: v1 kind: ServiceAccount metadata: {name: saw-gate-preparation, namespace: {{ $ns }}} automountServiceAccountToken: false +{{- with include "portal.pullNamespace" $e }} --- apiVersion: rbac.authorization.k8s.io/v1 kind: Role -metadata: {name: {{ printf "portal-gate-%s" $reg }}, namespace: {{ $e.buildNamespace }}} +metadata: {name: {{ printf "portal-gate-%s" $reg }}, namespace: {{ . }}} rules: [{apiGroups: [image.openshift.io], resources: [imagestreams/layers], resourceNames: [{{ base (index (splitList "@" $e.image) 0) | quote }}], verbs: [get]}] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding -metadata: {name: {{ printf "portal-gate-%s" $reg }}, namespace: {{ $e.buildNamespace }}} +metadata: {name: {{ printf "portal-gate-%s" $reg }}, namespace: {{ . }}} roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: {{ printf "portal-gate-%s" $reg }}} subjects: [{kind: ServiceAccount, name: saw-gate-preparation, namespace: {{ $ns }}}] +{{- end }} {{- range $key,$target := $targets }} {{- $slot := index $b.bindings $key }} {{- $gate := $slot.toolGate }} @@ -68,7 +70,9 @@ kind: Job metadata: {name: {{ $job }}, namespace: {{ $ns }}, annotations: {argocd.argoproj.io/sync-wave: '2'}} spec: backoffLimit: 2 - activeDeadlineSeconds: 360 + # Waits in ContainerCreating until the relay's identity Job projects the + # browser proof; Argo never recreates a failed Job, so allow for that. + activeDeadlineSeconds: 1800 template: spec: serviceAccountName: saw-gate-preparation @@ -83,6 +87,8 @@ spec: volumeMounts: [{name: gate, mountPath: /volume}{{ if $target.ui }}, {name: proof, mountPath: /proof, readOnly: true}{{ end }}{{ if $gate.harness }}, {name: bom, mountPath: /bom, readOnly: true}{{ end }}] volumes: [{name: gate, persistentVolumeClaim: {claimName: {{ $gate.trusted.claimName }}}}{{ if $target.ui }}, {name: proof, secret: {secretName: ui-{{ $target.relayID }}-browser-proof, items: [{key: relay-proof, path: relay-proof}]}}{{ end }}{{ if $gate.harness }}, {name: bom, configMap: {name: saw-bom-profiles}}{{ end }}] {{- end }} +{{- $credentialSecrets := list }} +{{- range ($site.credentialBindings | default list) }}{{- $credentialSecrets = append $credentialSecrets .secret }}{{- end }} --- apiVersion: argoproj.io/v1alpha1 kind: Application @@ -105,14 +111,15 @@ spec: enabled: true image: {{ $e.image | quote }} stateClaim: portal-ledger - imageBuildNamespace: {{ $e.buildNamespace }} + imageBuildNamespace: {{ include "portal.pullNamespace" $e | quote }} claimNames: {{ $claims | toJson }} configuration: gateway: {{ $u }} namespace: {{ $ns }} trustedNamespace: {{ $ctl }} governanceNamespace: {{ $site.governanceNamespace }} - proxyPolicy: {{ $u }}-proxy-policy + # The Secrets this workspace's providers read from (External Secrets copies). + credentialSecrets: {{ $credentialSecrets | uniq | sortAlpha | toJson }} ownerID: {{ $b.ownerID }} namespaceUID: {{ $b.namespaceUID }} mode: {{ $b.mode }} @@ -124,7 +131,7 @@ spec: status: saw-runtime-status approved: {{ $e.approved | toJson }} trustedEgress: -{{ toYaml $site.stack.proxy.values.network.bootstrapEgress | indent 10 }} +{{ toYaml $site.stack.identity.values.network.bootstrapEgress | indent 10 }} - to: - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: {{ $ns }}}} podSelector: {matchLabels: {app.kubernetes.io/instance: {{ $u }}, openshell.pattern/role: gateway}} diff --git a/charts/saw-portal-container/templates/foundation.yaml b/charts/saw-portal-container/templates/foundation.yaml index 92a22d8c3..6c89277d4 100644 --- a/charts/saw-portal-container/templates/foundation.yaml +++ b/charts/saw-portal-container/templates/foundation.yaml @@ -31,17 +31,15 @@ metadata: {name: default-deny, namespace: {{ $runtime }}, annotations: {argocd.a spec: {podSelector: {}, policyTypes: [Ingress, Egress], ingress: [], egress: []} {{- $customSecret := "" }} {{- $sources := dict }} -{{- with required "explicit governed provider policy required" (.Values.site | default dict).providerPolicy }} -{{- $sources = dict }} -{{- range .bindings }} +{{- /* helm lint turns required into a warning and yields "", which range cannot iterate. */}} +{{- $bindings := required "explicit credential bindings required" (.Values.site | default dict).credentialBindings }} +{{- range ($bindings | default list) }} +{{- if eq .type "custom-inference" }}{{- $customSecret = .secret }}{{- end }} {{- $fields := get $sources .secret | default list }} -{{- if .refresh }} -{{- range .refresh.material }}{{- $fields = append $fields . }}{{- end }} -{{- else }}{{- $fields = append $fields .key }}{{- end }} -{{- if has "custom-inference" .providers }}{{- $customSecret = .secret }}{{- end }} +{{- /* A refreshable credential's Secret holds only the refresh material; OpenShell mints the token. */}} +{{- if .refresh }}{{- $fields = concat $fields (list "client_id" "client_secret" "refresh_token") }}{{- else }}{{- $fields = append $fields .key }}{{- end }} {{- $_ := set $sources .secret ($fields | uniq | sortAlpha) }} {{- end }} -{{- end }} {{- range $secret, $fields := $sources }} --- apiVersion: external-secrets.io/v1 diff --git a/charts/saw-portal-container/templates/publications.yaml b/charts/saw-portal-container/templates/publications.yaml index a39f271b2..bbbc02cd1 100644 --- a/charts/saw-portal-container/templates/publications.yaml +++ b/charts/saw-portal-container/templates/publications.yaml @@ -1,5 +1,5 @@ -{{- $s := .Values.site | default dict }} -{{- if $s.automaticEnrollment }} +{{- $s := include "portal.site" . | fromJson }} +{{- if (.Values.site | default dict).automaticEnrollment }} {{- $observer := $s.observer | default dict }} {{- $t := printf "saw-ctl-%s" .Values.registration }} {{- $targets := include "portal.targets" . | fromJson }} diff --git a/charts/saw-portal-container/templates/relay.yaml b/charts/saw-portal-container/templates/relay.yaml index 5ac8ecea6..59b65b019 100644 --- a/charts/saw-portal-container/templates/relay.yaml +++ b/charts/saw-portal-container/templates/relay.yaml @@ -1,8 +1,8 @@ -{{- $site := .Values.site | default dict }} +{{- $site := include "portal.site" . | fromJson }} {{- $e := $site.enrollment | default dict }} {{- if and $e (eq $e.registration .Values.registration) $e.relay }} {{- $r := $e.relay }} -{{- if not (regexMatch "^[a-f0-9]{40}$" ($r.revision | default "")) }}{{ fail "relay revision must be a full Git commit SHA" }}{{ end }} +{{- if not (regexMatch (include "portal.revisionPattern" $) ($r.revision | default "")) }}{{ fail "relay revision must be a full Git commit SHA (only autoApprove sites may follow a branch)" }}{{ end }} {{- $u := .Values.owner }} {{- $reg := .Values.registration }} {{- $ctl := printf "saw-ctl-%s" $reg }} @@ -54,7 +54,7 @@ spec: installationID: {{ $.Values.installationID }} host: {{ $u }}-{{ $target.workspace }}-{{ $target.sandbox }}-ui.apps.{{ $.Values.global.clusterDomain }} sdkImage: {{ $e.image }} - imageBuildNamespace: {{ $e.buildNamespace }} + imageBuildNamespace: {{ include "portal.pullNamespace" $e | quote }} egress: {{ $r.egress | toJson }} ignoreDifferences: - {group: "", kind: Secret, name: ui-{{ $rid }}-registration-state, namespace: {{ $r.keycloakNamespace }}, jsonPointers: [/data]} diff --git a/charts/saw-portal-container/templates/stack.yaml b/charts/saw-portal-container/templates/stack.yaml index a0a540369..1865e04ef 100644 --- a/charts/saw-portal-container/templates/stack.yaml +++ b/charts/saw-portal-container/templates/stack.yaml @@ -1,8 +1,8 @@ {{- /* The site supplies reviewed values for the stock charts. No tpl: owner input must never become a Helm program or choose a source, namespace or chart. */ -}} -{{- $site := .Values.site | default dict }} +{{- $site := include "portal.site" . | fromJson }} {{- $stack := $site.stack | default dict }} -{{- if $stack }} +{{- if .Values.site }} {{- $u := .Values.owner }} {{- $reg := .Values.registration }} {{- $runtime := .Release.Namespace }} @@ -47,7 +47,7 @@ metadata: {name: identity-api, namespace: {{ $trusted }}} spec: podSelector: {matchLabels: {openshell.pattern/role: identity-bootstrap}} policyTypes: [Egress] - egress: {{ $stack.proxy.values.network.bootstrapEgress | toJson }} + egress: {{ required "site.stack.identity.values.network.bootstrapEgress is required" (dig "identity" "values" "network" "bootstrapEgress" nil $stack) | toJson }} --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy @@ -60,22 +60,35 @@ spec: - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: {{ $runtime }}}} podSelector: {matchLabels: {app.kubernetes.io/instance: {{ $u }}, openshell.pattern/role: gateway}} ports: [{port: 18081, protocol: TCP}] ---- -apiVersion: v1 -kind: ConfigMap -metadata: {name: {{ $u }}-proxy-policy, namespace: {{ $trusted }}} -data: - config.json: | - {{ required "explicit governed provider policy required" $site.providerPolicy | toJson }} -{{- $charts := dict "identity" (list "saw-kubernetes-identity" $trusted) "policy" (list "saw-runtime-policies" $runtime) "proxy" (list "saw-kubernetes-proxy" $trusted) "gateway" (list "openshell-saw-kubernetes" $runtime) }} + +{{- $charts := dict "identity" (list "saw-kubernetes-identity" $trusted) "policy" (list "saw-runtime-policies" $runtime) "gateway" (list "openshell-saw-kubernetes" $runtime) }} {{- range $slot := $targets }}{{- $key := ternary "audit" (printf "audit-%s" $slot.relayID) (eq (len $targets) 1) }}{{- $_ := set $charts $key (list "saw-audit-writer" $archive $slot) }}{{- end }} {{- range $key, $c := $charts }} {{- $item := required (printf "missing site.stack.%s" $key) (get $stack (ternary "audit" $key (eq (len $c) 3))) }} -{{- if not (regexMatch "^[a-f0-9]{40}$" ($item.revision | default "")) }}{{ fail "each infrastructure chart must be pinned to a Git commit" }}{{ end }} +{{- if not (regexMatch (include "portal.revisionPattern" $) ($item.revision | default "")) }}{{ fail "each infrastructure chart must be pinned to a full Git commit SHA (only autoApprove sites may follow a branch)" }}{{ end }} {{- $values := $item.values | toJson }} {{- range $k, $v := $map }} {{- $values = replace (printf "@%s@" $k) $v $values }} {{- end }} +{{- if eq $key "gateway" }} +{{- /* The interceptor endpoint and the egress to reach it follow the site's + governance namespace; the default sandbox image is the first target's. */}} +{{- $gateway := fromJson $values }} +{{- $k := $gateway.kubernetes }} +{{- $gov := $site.governanceNamespace }} +{{- $_ := set $k "governance" (dict "endpoint" (printf "http://governance-interceptor.%s.svc:18081" $gov)) }} +{{- $interceptor := dict "to" (list (dict "namespaceSelector" (dict "matchLabels" (dict "kubernetes.io/metadata.name" $gov)) "podSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" "governance-interceptor")))) "ports" (list (dict "protocol" "TCP" "port" 18081)) }} +{{- $network := $k.network | default dict }} +{{- $_ := set $network "gatewayEgress" (prepend ($network.gatewayEgress | default list) $interceptor) }} +{{- $_ := set $k "network" $network }} +{{- $workload := $k.workload | default dict }} +{{- if not $workload.image }} +{{- $first := index $targets (first (keys $targets | sortAlpha)) }} +{{- $_ := set $workload "image" (required "sandbox targets must name an image" $first.image) }} +{{- end }} +{{- $_ := set $k "workload" $workload }} +{{- $values = toJson $gateway }} +{{- end }} {{- if and (eq $key "gateway") $site.kataRuntimeClass }} {{- $gateway := fromJson $values }} {{- $_ := set $gateway "deployment" (dict "mode" "kata") }} @@ -99,19 +112,11 @@ data: {{- $_ := set $policy "forwarderImage" $stack.audit.values.image }} {{- $_ := set $policy "serverTLSSecret" (replace "@OWNER@" $u $gw.identity.serverTlsSecret) }} {{- $_ := set $policy "supervisorImage" (dig "supervisor" "image" $.Values.driverDefaults.supervisorImage $gw) }} -{{- $_ := set $policy "runtimeImage" ($gw.workload.runtimeImage | default $.Values.driverDefaults.runtimeImage) }} -{{- $proxyURL := replace "@TRUSTED@" $trusted (replace "@OWNER@" $u $gw.proxy.url) }} -{{- $_ := set $policy "supervisorCommand" (list "/openshell-supervisor" "--backend-descriptor-file" "/.openshell/supervisor/runtime-descriptor.json" "--auth-bundle-file" "/.openshell/supervisor/auth.json" "--workdir" "/sandbox" "--health-socket-path" "/run/openshell/health.sock" "--health-port" "5501" "--upstream-proxy" $proxyURL "--upstream-proxy-connect-by-hostname" "--upstream-proxy-ca-bundle" "/.openshell/supervisor/upstream-proxy-ca.pem") }} +{{- $_ := set $policy "runtimeImage" (dig "workload" "runtimeImage" "" $gw | default $.Values.driverDefaults.runtimeImage) }} +{{- $_ := set $policy "supervisorCommand" (list "/openshell-supervisor" "--backend-descriptor-file" "/.openshell/supervisor/runtime-descriptor.json" "--auth-bundle-file" "/.openshell/supervisor/auth.json" "--workdir" "/sandbox" "--health-socket-path" "/run/openshell/health.sock" "--health-port" "5501") }} +{{- $_ := set $policy.network "publicHTTPS" true }} {{- $values = toJson $policy }} {{- end }} -{{- if and (eq $key "proxy") $site.providerPolicy }} -{{- $proxy := fromJson $values }} -{{- $secrets := list }} -{{- range $site.providerPolicy.bindings }}{{- $secrets = append $secrets .secret }}{{- end }} -{{- $_ := set $proxy "credentialSecretNames" ($secrets | uniq | sortAlpha) }} -{{- $_ := set $proxy "policyDigest" ($site.providerPolicy | toJson | sha256sum) }} -{{- $values = toJson $proxy }} -{{- end }} {{- $release := $u }} {{- if eq (len $c) 3 }} {{- $slot := index $c 2 }} diff --git a/charts/saw-portal-container/values.yaml b/charts/saw-portal-container/values.yaml index ec815deab..77aa73997 100644 --- a/charts/saw-portal-container/values.yaml +++ b/charts/saw-portal-container/values.yaml @@ -8,3 +8,99 @@ driverDefaults: gatewayVersion: 0.1.6-rhaiv.4 supervisorImage: quay.io/opendatahub/odh-openshell-supervisor@sha256:626b91a0f53393dac0d591c142b81100916aa66b4e65444b5527672b5533fe86 runtimeImage: quay.io/opendatahub/odh-openshell-sandbox@sha256:0cde11346e68485907c22d3c9b30802e52cf16e3853720a864ac8347bb68f6ef + +# The wiring every container site shares. A site (saw-users containerDefaults +# and containerSites, or the portal's) sets only what differs per cluster and +# wins: maps merge, other values (lists included) replace. +siteDefaults: + governanceNamespace: openshell-agents + automaticEnrollment: + # Enrollment policy (enabled, autoApprove), the runtime image, build + # namespace and relay Keycloak settings come from the site itself + # (saw-users containerDefaults), because the workspace projector reads and + # checks them before this chart's defaults are merged. Only the compute + # request for the enrollment Job defaults here. + resources: + requests: {cpu: 500m, memory: 1Gi} + limits: {cpu: "2", memory: 4Gi} + stack: + identity: + values: + enabled: true + ownerID: '@INSTALLATION@' + targetNamespace: '@RUNTIME@' + gateway: '@OWNER@' + serverSans: + - '@OWNER@-gateway.@RUNTIME@.svc' + - '@OWNER@-gateway.@RUNTIME@.svc.cluster.local' + policy: + values: + enabled: true + targetNamespace: '@RUNTIME@' + gatewayId: '@OWNER@' + gatewayServiceAccount: '@OWNER@-gateway' + sandboxServiceAccount: '@OWNER@-sandbox' + mode: container + network: + # Each workspace policy selects only its own namespace, so workspaces + # can share a priority. The runtime refuses to start if any other + # policy covering the namespace comes at or before it. + priority: 51 + egress: + - name: dns + to: + - pods: + namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: openshift-dns}} + podSelector: {matchLabels: {dns.operator.openshift.io/daemonset-dns: default}} + ports: + - portNumber: {protocol: UDP, port: 53} + - portNumber: {protocol: TCP, port: 53} + - portNumber: {protocol: UDP, port: 5353} + - portNumber: {protocol: TCP, port: 5353} + - name: gateway + to: + - pods: + namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: '@RUNTIME@'}} + podSelector: {matchLabels: {app.kubernetes.io/instance: '@OWNER@', openshell.pattern/role: gateway}} + ports: + - portNumber: {protocol: TCP, port: 17670} + - name: workload-boundary + to: + - pods: + namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: '@RUNTIME@'}} + podSelector: {matchLabels: {openshell.ai/boundary-role: workload}} + ports: + - portNumber: {protocol: TCP, port: 5500} + gateway: + values: + deployment: {mode: container} + kubernetes: + experimental: true + # workload.image defaults to the first sandbox's image (stack.yaml). + identity: + serverTlsSecret: '@OWNER@-server' + clientCaSecret: '@OWNER@-client-ca' + jwtSecret: '@OWNER@-jwt' + credentialKeySecret: '@OWNER@-kek' + storage: + gatewaySize: 1Gi + workspaceSize: 10Gi + network: + reconcilerNamespace: '@TRUSTED@' + reconcilerLabels: + app.kubernetes.io/instance: '@OWNER@' + openshell.pattern/role: reconciler + route: {enabled: false} + audit: + values: + enabled: true + trustedNamespace: '@ARCHIVE@' + runtimeNamespace: '@RUNTIME@' + ownerID: '@INSTALLATION@' + # The audit writer needs a pinned Node 24 runtime; the OpenClaw image has one. + image: ghcr.io/openclaw/openclaw@sha256:0a5ff5e682e62afa19149df126aa50063bf65ef885b5c94713ce32dc0eb12e15 + identity: + subject: '@SUBJECT@' + username: '@OWNER@' + workspace: agent + sandbox: audited diff --git a/charts/saw-runtime-policies/templates/admin-network-policy.yaml b/charts/saw-runtime-policies/templates/admin-network-policy.yaml index 48694cfc2..2b50d2dce 100644 --- a/charts/saw-runtime-policies/templates/admin-network-policy.yaml +++ b/charts/saw-runtime-policies/templates/admin-network-policy.yaml @@ -24,6 +24,22 @@ spec: action: Pass to: {{ .to | toYaml | nindent 8 }} ports: {{ .ports | toYaml | nindent 8 }} +{{- end }} +{{- if .Values.network.publicHTTPS }} + # The supervisor reaches providers itself and OpenShell enforces which + # hosts each sandbox may use (as OpenShell's own supervisor fence leaves + # egress open). Private ranges stay closed unless passed above. + - name: deny-private-networks + action: Deny + to: + - networks: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10", + "169.254.0.0/16", "127.0.0.0/8", "0.0.0.0/8", "fc00::/7", "fe80::/10", "::1/128"] + - name: public-https + action: Pass + to: + - networks: ["0.0.0.0/0", "::/0"] + ports: + - portNumber: {protocol: TCP, port: 443} {{- end }} - name: deny-other-egress action: Deny diff --git a/charts/saw-runtime-policies/values.schema.json b/charts/saw-runtime-policies/values.schema.json index a8834a079..74712edcf 100644 --- a/charts/saw-runtime-policies/values.schema.json +++ b/charts/saw-runtime-policies/values.schema.json @@ -42,6 +42,9 @@ "items": { "$ref": "#/definitions/egressRule" } + }, + "publicHTTPS": { + "type": "boolean" } }, "required": [ diff --git a/charts/saw-runtime-policies/values.yaml b/charts/saw-runtime-policies/values.yaml index 6ee07a152..c09b0b989 100644 --- a/charts/saw-runtime-policies/values.yaml +++ b/charts/saw-runtime-policies/values.yaml @@ -10,9 +10,14 @@ network: # Required administrator allocation, unique among overlapping ANPs (0..99). priority: null # ANP egress peers/ports. The chart fixes each action to Pass, then denies - # all remaining IPv4/IPv6. Populate actual DNS, gateway, workload-boundary, - # credential-proxy and approved external destinations before enabling. + # all remaining IPv4/IPv6. Populate actual DNS, gateway, workload-boundary + # and approved in-cluster destinations before enabling. egress: [] + # Let supervisors reach public HTTPS (provider APIs). Credentials go only to + # their provider profile's endpoints, and the runtime controller refuses a + # credentialed profile whose endpoints are not the approved set (the shipped + # governed profile, or the site's custom inference host). + publicHTTPS: false # Filled by the shared composition from the approved BOM and gateway configuration. sandboxControllerUsername: system:serviceaccount:agent-sandbox-system:agent-sandbox-controller diff --git a/charts/saw-users/files/governed-profiles.json b/charts/saw-users/files/governed-profiles.json deleted file mode 100644 index 6819eb497..000000000 --- a/charts/saw-users/files/governed-profiles.json +++ /dev/null @@ -1,550 +0,0 @@ -{ - "anthropic": { - "binaries": [ - "/usr/bin/curl", - "/usr/local/bin/curl", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "inference", - "credentials": [ - { - "auth_style": "header", - "description": "Anthropic API key", - "env_vars": [ - "ANTHROPIC_API_KEY" - ], - "header_name": "x-api-key", - "name": "api_key", - "required": true - } - ], - "description": "Anthropic inference API", - "discovery": { - "credentials": [ - "api_key" - ] - }, - "display_name": "Anthropic", - "endpoints": [ - { - "access": "read-write", - "enforcement": "enforce", - "host": "api.anthropic.com", - "port": 443, - "protocol": "rest" - } - ], - "id": "anthropic", - "inference_capable": true - }, - "brave": { - "binaries": [ - "/usr/bin/curl", - "/usr/local/bin/curl", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "other", - "credentials": [ - { - "auth_style": "header", - "description": "Brave Search API key", - "env_vars": [ - "BRAVE_API_KEY" - ], - "header_name": "X-Subscription-Token", - "name": "api_key", - "required": true - } - ], - "description": "Brave Search API access for governed sandbox agents", - "discovery": { - "credentials": [ - "api_key" - ] - }, - "display_name": "Brave Search", - "endpoints": [ - { - "access": "read-only", - "enforcement": "enforce", - "host": "api.search.brave.com", - "port": 443, - "protocol": "rest" - } - ], - "id": "brave" - }, - "gemini": { - "binaries": [ - "/usr/bin/gemini", - "/usr/lib/node_modules/@google/gemini-cli/dist/index.js", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "other", - "credentials": [ - { - "auth_style": "query", - "description": "Google Gemini API key", - "env_vars": [ - "GEMINI_API_KEY" - ], - "name": "api_key", - "query_param": "key", - "required": true - } - ], - "description": "Google Gemini AI and Vertex AI API access", - "discovery": { - "credentials": [ - "api_key" - ] - }, - "display_name": "Google Gemini", - "endpoints": [ - { - "access": "read-write", - "enforcement": "enforce", - "host": "generativelanguage.googleapis.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-write", - "enforcement": "enforce", - "host": "*-aiplatform.googleapis.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-write", - "enforcement": "enforce", - "host": "cloudcode-pa.googleapis.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "accounts.google.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "oauth2.googleapis.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "www.googleapis.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "iamcredentials.googleapis.com", - "port": 443, - "protocol": "rest" - } - ], - "id": "gemini" - }, - "github": { - "binaries": [ - "/usr/bin/gh", - "/usr/local/bin/gh", - "/usr/bin/git", - "/usr/local/bin/git", - "/usr/bin/curl", - "/usr/local/bin/curl" - ], - "category": "source_control", - "credentials": [ - { - "auth_style": "bearer", - "description": "GitHub token", - "env_vars": [ - "GITHUB_TOKEN", - "GH_TOKEN" - ], - "header_name": "authorization", - "name": "api_token", - "required": true - } - ], - "description": "GitHub API and Git operations", - "discovery": { - "credentials": [ - "api_token" - ] - }, - "display_name": "GitHub", - "endpoints": [ - { - "access": "read-only", - "enforcement": "enforce", - "host": "api-1.github.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "api.github.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "api.github.com", - "path": "/graphql", - "port": 443, - "protocol": "graphql" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "github.com", - "port": 443, - "protocol": "rest" - } - ], - "id": "github" - }, - "gmail": { - "binaries": [ - "/usr/bin/curl", - "/usr/local/bin/curl", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "messaging", - "credentials": [ - { - "auth_style": "bearer", - "description": "Gmail OAuth access token (gmail.readonly)", - "env_vars": [ - "GMAIL_ACCESS_TOKEN" - ], - "header_name": "authorization", - "name": "access_token", - "refresh": { - "material": [ - { - "description": "Google OAuth client ID", - "name": "client_id", - "required": true - }, - { - "description": "Google OAuth client secret", - "name": "client_secret", - "required": true, - "secret": true - }, - { - "description": "Google OAuth refresh token (scope gmail.readonly)", - "name": "refresh_token", - "required": true, - "secret": true - } - ], - "max_lifetime_seconds": 3600, - "refresh_before_seconds": 300, - "strategy": "oauth2_refresh_token", - "token_url": "https://oauth2.googleapis.com/token" - }, - "required": true - } - ], - "description": "Read-only Gmail API access for governed sandbox agents", - "discovery": { - "credentials": [ - "access_token" - ] - }, - "display_name": "Gmail", - "endpoints": [ - { - "enforcement": "enforce", - "host": "gmail.googleapis.com", - "port": 443, - "protocol": "rest", - "rules": [ - { - "allow": { - "method": "GET", - "path": "/gmail/v1/users/me/profile" - } - }, - { - "allow": { - "method": "GET", - "path": "/gmail/v1/users/me/labels" - } - }, - { - "allow": { - "method": "GET", - "path": "/gmail/v1/users/me/messages" - } - }, - { - "allow": { - "method": "GET", - "path": "/gmail/v1/users/me/messages/*" - } - }, - { - "allow": { - "method": "GET", - "path": "/gmail/v1/users/me/threads" - } - }, - { - "allow": { - "method": "GET", - "path": "/gmail/v1/users/me/threads/*" - } - } - ] - } - ], - "id": "gmail" - }, - "nvidia": { - "binaries": [ - "/usr/bin/curl", - "/usr/local/bin/curl", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "inference", - "credentials": [ - { - "auth_style": "bearer", - "description": "NVIDIA API key", - "env_vars": [ - "NVIDIA_API_KEY" - ], - "header_name": "authorization", - "name": "api_key", - "required": true - } - ], - "description": "NVIDIA API inference endpoints", - "discovery": { - "credentials": [ - "api_key" - ] - }, - "display_name": "NVIDIA Endpoints", - "endpoints": [ - { - "access": "read-write", - "enforcement": "enforce", - "host": "integrate.api.nvidia.com", - "port": 443, - "protocol": "rest" - } - ], - "id": "nvidia", - "inference_capable": true - }, - "openai": { - "binaries": [ - "/usr/bin/curl", - "/usr/local/bin/curl", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "inference", - "credentials": [ - { - "auth_style": "bearer", - "description": "OpenAI API key", - "env_vars": [ - "OPENAI_API_KEY" - ], - "header_name": "authorization", - "name": "api_key", - "required": true - } - ], - "description": "OpenAI inference API", - "discovery": { - "credentials": [ - "api_key" - ] - }, - "display_name": "OpenAI", - "endpoints": [ - { - "access": "read-write", - "enforcement": "enforce", - "host": "api.openai.com", - "port": 443, - "protocol": "rest" - } - ], - "id": "openai", - "inference_capable": true - }, - "slack": { - "binaries": [ - "/usr/bin/curl", - "/usr/local/bin/curl", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "messaging", - "credentials": [ - { - "auth_style": "bearer", - "description": "Slack bot or user token", - "env_vars": [ - "SLACK_BOT_TOKEN", - "SLACK_TOKEN" - ], - "header_name": "authorization", - "name": "api_token", - "refresh": { - "material": [ - { - "description": "Slack app client ID", - "name": "client_id", - "required": true - }, - { - "description": "Slack app client secret", - "name": "client_secret", - "required": true, - "secret": true - }, - { - "description": "Slack refresh token (xoxe-...)", - "name": "refresh_token", - "required": true, - "secret": true - } - ], - "max_lifetime_seconds": 43200, - "refresh_before_seconds": 600, - "strategy": "oauth2_refresh_token", - "token_url": "https://slack.com/api/oauth.v2.access" - }, - "required": true - } - ], - "description": "Read-only Slack Web API access for governed sandbox agents", - "discovery": { - "credentials": [ - "api_token" - ] - }, - "display_name": "Slack", - "endpoints": [ - { - "enforcement": "enforce", - "host": "slack.com", - "port": 443, - "protocol": "rest", - "rules": [ - { - "allow": { - "method": "GET", - "path": "/api/auth.test" - } - }, - { - "allow": { - "method": "GET", - "path": "/api/team.info" - } - }, - { - "allow": { - "method": "GET", - "path": "/api/users.info" - } - }, - { - "allow": { - "method": "GET", - "path": "/api/conversations.list" - } - }, - { - "allow": { - "method": "GET", - "path": "/api/conversations.info" - } - }, - { - "allow": { - "method": "GET", - "path": "/api/conversations.history" - } - }, - { - "allow": { - "method": "GET", - "path": "/api/conversations.replies" - } - } - ] - } - ], - "id": "slack" - }, - "web-search": { - "binaries": [ - "/usr/bin/curl", - "/usr/local/bin/curl", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "other", - "description": "Tavily and Brave Search API endpoints and plugin registry", - "display_name": "Web Search", - "endpoints": [ - { - "access": "read-only", - "enforcement": "enforce", - "host": "api.tavily.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "api.search.brave.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "registry.npmjs.org", - "port": 443, - "protocol": "rest" - } - ], - "id": "web-search" - } -} diff --git a/charts/saw-users/files/preflight.py b/charts/saw-users/files/preflight.py index c32862180..dc499183c 100644 --- a/charts/saw-users/files/preflight.py +++ b/charts/saw-users/files/preflight.py @@ -196,24 +196,33 @@ def check_observations(mode, observations): return tuple(required) +# Reviewed sites pin every chart to a full commit SHA. An autoApprove +# (development) site may follow a branch instead: saw-users and portal defaults +# use global.targetRevision when a site sets no revision. +PINNED_REVISION = r"[a-f0-9]{40}" +BRANCH_REVISION = r"[a-f0-9]{40}|[A-Za-z0-9][A-Za-z0-9._/-]*" + + def configuration_facts(site): """Check site-owned inputs that do not require cluster access.""" if not isinstance(site, dict): return {key: False for key in ("network", "storage", "secrets", "registry", "providerEgress", "revisions")} stack = site.get("stack") if isinstance(site.get("stack"), dict) else {} + enrollment = site.get("automaticEnrollment") or {} + revision_pattern = BRANCH_REVISION if isinstance(enrollment, dict) and enrollment.get( + "autoApprove") is True else PINNED_REVISION revisions = [item.get("revision") for item in stack.values() if isinstance(item, dict)] - required_components = ("identity", "policy", "proxy", "gateway", "audit") + required_components = ("identity", "policy", "gateway", "audit") revision_pin = all(isinstance(stack.get(name), dict) for name in required_components) and all( isinstance(stack[name].get("revision"), str) - and re.fullmatch(r"[a-f0-9]{40}", stack[name]["revision"]) + and re.fullmatch(revision_pattern, stack[name]["revision"]) for name in required_components) and bool(revisions) and len(revisions) == len(stack) and all( - isinstance(value, str) and re.fullmatch(r"[a-f0-9]{40}", value) for value in revisions) - enrollment = site.get("automaticEnrollment") or {} + isinstance(value, str) and re.fullmatch(revision_pattern, value) for value in revisions) if enrollment and not isinstance(enrollment, dict): revision_pin = False elif enrollment: - revision_pin = revision_pin and bool(re.fullmatch(r"[a-f0-9]{40}", str(enrollment.get("revision", "")))) + revision_pin = revision_pin and bool(re.fullmatch(revision_pattern, str(enrollment.get("revision", "")))) image_values = [] storage_values = [] @@ -233,28 +242,20 @@ def walk(value, path=()): walk(child, path) walk(site) - declared_hosts = site.get("providerAllowHosts") - policy = site.get("providerPolicy") - clean_hosts = (isinstance(declared_hosts, list) and bool(declared_hosts) - and all(isinstance(host, str) and host and "*" not in host - for host in declared_hosts) - and (policy is None or (isinstance(policy, dict) - and isinstance(policy.get("allowHosts"), list) - and all(isinstance(host, str) for host in policy["allowHosts"]) - and set(policy["allowHosts"]) == set(declared_hosts)))) - proxy = stack.get("proxy") or {} - proxy_values = proxy.get("values") or {} if isinstance(proxy, dict) else {} - bootstrap_egress = ((proxy_values.get("network") or {}).get("bootstrapEgress") - if isinstance(proxy_values, dict) else None) + # OpenShell decides where each credential may go (provider profiles); the + # site only lists which Secret backs which provider type. + bindings = site.get("credentialBindings") + clean_bindings = (isinstance(bindings, list) and all( + isinstance(b, dict) and {"secret", "key", "type"} <= set(b) <= {"secret", "key", "type", "refresh"} + and all(isinstance(v, str) and v for v in b.values()) for b in bindings)) storage_ok = bool(storage_values) and all(value.strip() for value in storage_values) return { - "network": bool(stack.get("policy")) and isinstance(bootstrap_egress, list) - and bool(bootstrap_egress), + "network": bool(stack.get("policy")), "storage": storage_ok, "secrets": isinstance(site.get("secretStore", "vault-backend"), str) and bool(site.get("secretStore", "vault-backend")), "registry": bool(image_values) and all("@sha256:" in image for image in image_values), - "providerEgress": clean_hosts, + "providerEgress": clean_bindings, "revisions": revision_pin, } diff --git a/charts/saw-users/files/projector.py b/charts/saw-users/files/projector.py index 23282e0eb..fb05ae669 100644 --- a/charts/saw-users/files/projector.py +++ b/charts/saw-users/files/projector.py @@ -88,8 +88,8 @@ def previous(self, owner): def verify_gitops_preflight(owner, site, mode, read): """Stop ApplicationSet generation on a changed live Kata boundary.""" automatic = site.get("automaticEnrollment", {}) - if not automatic or automatic.get("enabled") is False: - return + if not automatic or automatic.get("enabled") is False or automatic.get("autoApprove") is True: + return # autoApprove has no operator reference; enrollment checks the live boundary reference = automatic.get("reference") preflight.verify_boundary_reference(reference, mode) if mode == "kata": diff --git a/charts/saw-users/files/workspace.py b/charts/saw-users/files/workspace.py index bc86b4d01..1addd71e3 100644 --- a/charts/saw-users/files/workspace.py +++ b/charts/saw-users/files/workspace.py @@ -5,6 +5,7 @@ resource application. This module never discovers or changes cluster state. """ import hashlib +import ipaddress import json import re import urllib.parse @@ -18,9 +19,9 @@ class WorkspaceError(ValueError): SAFE_FAILURE_REASONS = frozenset({ "ProfileRejected", "InvalidPlan", "PlacementRejected", "IdentityConflict", "InvalidIntent", "StaleIntent", "ReconcilerStateRejected", "GatewayMismatch", - "ProviderProfileMismatch", "WorkspaceRejected", "ProviderRejected", + "ProviderProfileMismatch", "ProviderRefreshFailed", "WorkspaceRejected", "ProviderRejected", "SandboxRejected", "SandboxStateMismatch", "SandboxDrift", "CoreRejected", - "CoreFailure", + "CoreFailure", "ReenrollRequired", }) SAFE_RPC_CODES = frozenset({ "NOT_FOUND", "ALREADY_EXISTS", "UNAVAILABLE", "DEADLINE_EXCEEDED", "ABORTED", @@ -82,24 +83,40 @@ def public_model_inputs(profile, secrets): return values -def approved_endpoint(profile, secrets, boundary): +CUSTOM_INFERENCE_URL = re.compile(r"https://[a-z0-9-]+(?:\.[a-z0-9-]+)+(?::443)?(?:/[A-Za-z0-9_-]+)*/v1") + + +def custom_inference_url(endpoint): + """The workspace's own OpenAI-compatible base URL: HTTPS, a DNS name, port 443, ending /v1. + + Which host may receive the API key is not decided here: the custom-inference + governance profile names it, and the runtime controller refuses a workspace + whose URL host is not that profile's only endpoint (ProviderProfileMismatch). + """ + if not isinstance(endpoint, str) or not CUSTOM_INFERENCE_URL.fullmatch(endpoint): + raise WorkspaceError("custom inference needs an HTTPS base URL ending in /v1") + try: + ipaddress.ip_address(urllib.parse.urlsplit(endpoint).hostname) + except ValueError: + return endpoint + raise WorkspaceError("custom inference needs an HTTPS base URL ending in /v1, with a DNS name") + + +def approved_endpoint(profile, secrets): + """The endpoint URL the owner entered (public metadata), if the profile takes one.""" refs = {sb["endpointInput"] for _, sb in enabled_catalog_sandboxes(profile) if sb.get("endpointInput")} if not refs: return None - endpoint = boundary.get("inferenceBaseURL", "") - if not isinstance(endpoint, str) or not re.fullmatch( - r"https://[a-z0-9-]+(?:\.[a-z0-9-]+)+(?::443)?(?:/[A-Za-z0-9_-]+)*/v1", endpoint): - raise WorkspaceError("site has no approved custom inference endpoint") - if boundary.get("allowHosts") != [urllib.parse.urlsplit(endpoint).hostname]: - raise WorkspaceError("custom inference requires a dedicated broker host") + endpoints = set() for ref in refs: secret, key = ref.split(".", 1) fields = profile["secrets"][secret]["fields"] if not any(f["key"] == key and f["kind"] == "url" for f in fields): raise WorkspaceError("endpoint input must be public URL metadata") - if secrets.get(secret, {}).get(key, "").rstrip("/") != endpoint: - raise WorkspaceError("endpoint differs from the site-approved custom inference URL") - return endpoint + endpoints.add(secrets.get(secret, {}).get(key, "").rstrip("/")) + if len(endpoints) != 1: + raise WorkspaceError("custom inference endpoint inputs disagree") + return custom_inference_url(endpoints.pop()) def enrolled_site(site, ws, read): @@ -123,17 +140,18 @@ def publication(name): if data: raise WorkspaceError("cannot disable enrollment of a bound workspace; use desiredState") return fresh - for key, kind in (("reference", dict), ("relay", dict), ("revision", str), - ("image", str), ("buildNamespace", str)): + auto = a.get("autoApprove") is True + for key, kind in ((() if auto else (("reference", dict),)) + (("relay", dict), ("revision", str), + ("image", str), ("buildNamespace", str))): if not isinstance(a.get(key), kind) or not a[key]: raise WorkspaceError(f"container site for {ws['name']} requires automaticEnrollment.{key}") if not data: return fresh bound=json.loads(data["binding.json"]) - if set(bound)!={"registration","intent","approved","gatewayCA"} or bound["registration"]!=reg or set(bound["approved"])!=set(a["reference"]): + if set(bound)!={"registration","intent","approved","gatewayCA"} or bound["registration"]!=reg or (not auto and set(bound["approved"])!=set(a["reference"])): raise WorkspaceError("invalid published enrollment") intent=bound["intent"] - if intent["bindings"]["ownerID"]!=install or intent["bindings"]["namespace"]!="saw-"+ws["name"] or intent["bindings"]["ownerSubject"]!=ws["ownerSubject"] or intent["profileRef"]["sha256"]!=site.get("selectedDigest",a.get("profileSHA256")): + if intent["bindings"]["ownerID"]!=install or intent["bindings"]["namespace"]!="saw-"+ws["name"] or intent["bindings"]["ownerSubject"]!=ws["ownerSubject"] or (not auto and intent["profileRef"]["sha256"]!=site.get("selectedDigest",a.get("profileSHA256"))): raise WorkspaceError("published intent does not belong to this workspace") subjects = {target["subjectMap"]:publication(target["subjectMap"]).get("subject", "") for target in site.get("targets",{}).values() if target["ui"]} @@ -204,7 +222,7 @@ def project_workspace(workspace, defaults, site, catalog, read=None, previous=No # Inputs include operator configuration and immutable API publications. # Do not include arbitrary values (especially JSON bodies) in diagnostics. detail = f"missing {exc.args[0]}" if isinstance(exc, KeyError) and exc.args[0] in { - "subject", "registration", "installationID", "reference", "allowHosts", "bindings", + "subject", "registration", "installationID", "reference", "bindings", "binding.json", "profileRef", "sha256", "initialModelInputs"} else "invalid site or publication" raise WorkspaceError(f"workspace {workspace.get('name', '?')}: {detail}") from None @@ -241,11 +259,26 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): validate_runtime_placement(mode, site) automatic = site.get("automaticEnrollment", {}) selected, *extra = ws.get("profiles", []) or [None] - foundation = automatic.get("enabled") is False + foundation = automatic.get("enabled") is False or automatic.get("autoApprove") is True if extra or selected not in catalog or not foundation and selected not in automatic.get("approvedProfiles", {}): raise WorkspaceError("container requires one approved BOM profile") if not ws.get("registration") or not ws.get("installationID"): raise WorkspaceError("container requires a registration and installation identity") + # As the portal does at registration: a dedicated-endpoint profile (such as + # custom-inference) has no web-search credential unless the entry asks for it. + if "dedicatedEndpointSecrets" in catalog[selected] and "webSearch" not in ws: + ws["webSearch"] = {"enabled": False} + # The runtime compiles the model from public inputs, never from the Secret. + # The portal reads it from the form; a static entry must name it. + given = ws.get("initialModelInputs") if ws.get("lifecycleVersion") == 1 else ws.get("modelInputs") + for _, sandbox in enabled_catalog_sandboxes(catalog[selected]): + key = sandbox.get("modelInput") + if not key: + continue + secret, field = key.split(".", 1) + definition = next((f for f in catalog[selected]["secrets"][secret]["fields"] if f["key"] == field), {}) + if definition.get("required") and not definition.get("default") and not (given or {}).get(key): + raise WorkspaceError(f"{ws['name']}: set modelInputs.{key} (the model this profile requires)") overrides = site.get("profileImageOverrides", {}).get(selected, {}) if overrides: ws["imageOverrides"] = overrides @@ -259,12 +292,19 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): target["image"] = overrides.get(target["sandbox"], target["image"]) boundary = site.get("profileBoundaries", {}).get(selected) if boundary: - site = {**site, "providerAllowHosts": boundary["allowHosts"], - "automaticEnrollment": {**automatic, "reference": boundary["reference"]}} - if ws.get("customInferenceURL"): - if not boundary or boundary.get("inferenceBaseURL") != ws["customInferenceURL"]: - raise WorkspaceError("endpoint differs from the site-approved custom inference URL") - site["customInferenceURL"] = ws["customInferenceURL"] + # autoApprove sites have no operator-reviewed reference to pin. + reviewed = {"reference": boundary["reference"]} if "reference" in boundary or \ + automatic.get("autoApprove") is not True else {} + site = {**site, "automaticEnrollment": {**automatic, **reviewed}} + # A profile with an endpoint input (custom-inference) uses the owner's own + # URL: the portal form value, or customInferenceURL in a static entry. The + # custom-inference governance profile approves its host at run time. + if any(sb.get("endpointInput") for _, sb in enabled_catalog_sandboxes(catalog[selected])): + if not ws.get("customInferenceURL"): + raise WorkspaceError(f"{ws['name']}: set customInferenceURL (the inference server's base URL)") + site["customInferenceURL"] = custom_inference_url(ws["customInferenceURL"]) + elif ws.get("customInferenceURL"): + raise WorkspaceError("only a profile with an endpoint input takes customInferenceURL") if managed: site.update(lifecycleVersion=1, modelInputs=ws["initialModelInputs"], requestedModels=ws.get("modelInputs", {}), desiredState=ws["desiredState"], diff --git a/charts/saw-users/templates/_governed-proxy-policy.tpl b/charts/saw-users/templates/_governed-proxy-policy.tpl deleted file mode 100644 index 39b52d032..000000000 --- a/charts/saw-users/templates/_governed-proxy-policy.tpl +++ /dev/null @@ -1,52 +0,0 @@ -{{/* Shared broker config for VM and container. The catalog generator mirrors this template into saw-users. */}} -{{- define "saw.governedProxyPolicy" -}} -{{- $profiles := dict -}} -{{- $refresh := dict -}} -{{- range $profile := .catalog -}} - {{- range $credential := $profile.credentials | default list -}} - {{- $spec := $credential.refresh | default dict -}} - {{- if eq ($spec.strategy | default "") "oauth2_refresh_token" -}} - {{- $keys := list -}} - {{- range $spec.material -}}{{- $keys = append $keys .name -}}{{- end -}} - {{- range list "client_id" "client_secret" "refresh_token" -}} - {{- if not (has . $keys) -}}{{- fail "OAuth refresh requires client_id, client_secret and refresh_token material" -}}{{- end -}} - {{- end -}} - {{- $_ := set $refresh $profile.id (dict "credential" $credential.name "spec" (dict "strategy" $spec.strategy "tokenURL" $spec.token_url "refreshBeforeSeconds" $spec.refresh_before_seconds "maxLifetimeSeconds" $spec.max_lifetime_seconds "material" (dict "clientID" "client_id" "clientSecret" "client_secret" "refreshToken" "refresh_token"))) -}} - {{- end -}} - {{- end -}} - {{- if $profile.credentials -}} - {{- $hosts := list -}} - {{- range $profile.endpoints -}} - {{- if and .host (not (has .host $hosts)) -}}{{- $hosts = append $hosts .host -}}{{- end -}} - {{- end -}} - {{- $_ := set $profiles $profile.id $hosts -}} - {{- end -}} -{{- end -}} -{{- if hasKey $profiles "nvidia" -}}{{- $_ := set $profiles "build" (index $profiles "nvidia") -}}{{- end -}} -{{- $bindings := list -}} -{{- $attached := .attached -}} -{{- range .bindings -}} - {{- if has .name $attached -}} - {{- if and .name (not (regexMatch "^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$" .name)) -}}{{ fail (printf "invalid secret name %q" .name) }}{{- end -}} - {{- if not (regexMatch "^[A-Za-z0-9_.-]+$" (.key | default "")) -}} - {{- fail (printf "credentialProxy.secrets[%s].key is invalid" .name) -}} - {{- end -}} - {{- if not .providers -}}{{- fail (printf "credentialProxy.secrets[%s].providers is required" .name) -}}{{- end -}} - {{- if and (hasKey . "refresh") (not (kindIs "bool" .refresh)) -}} - {{- fail "credentialProxy.secrets[].refresh must be a boolean" -}} - {{- end -}} - {{- $binding := dict "secret" .name "key" .key "providers" .providers -}} - {{- if .refresh -}} - {{- if ne (len .providers) 1 -}}{{- fail "refresh binding requires exactly one provider type" -}}{{- end -}} - {{- $type := first .providers -}} - {{- if not (hasKey $refresh $type) -}}{{- fail (printf "provider %s has no OAuth refresh spec" $type) -}}{{- end -}} - {{- $entry := index $refresh $type -}} - {{- if ne .key $entry.credential -}}{{- fail "refresh binding key must match the profile credential" -}}{{- end -}} - {{- $_ := set $binding "refresh" $entry.spec -}} - {{- end -}} - {{- $bindings = append $bindings $binding -}} - {{- end -}} -{{- end -}} -{{- $policy := dict "markerPrefix" "saw-cred" "allowHosts" .allowHosts "profiles" $profiles "bindings" $bindings -}} -{{ $policy | toJson }} -{{- end -}} diff --git a/charts/saw-users/templates/_helpers.tpl b/charts/saw-users/templates/_helpers.tpl index b3a987fa3..8a5e703de 100644 --- a/charts/saw-users/templates/_helpers.tpl +++ b/charts/saw-users/templates/_helpers.tpl @@ -23,7 +23,9 @@ watches, not in whatever namespace this chart happens to be released into. {{- $seen := dict -}} {{- range .Values.users | default list -}} {{- $name := .name | default "" | toString -}} +{{- if not (include "saw-users.awaitingOwner" (dict "root" $ "user" .)) -}} {{- include "saw-users.validateDeploymentMode" (dict "root" $ "user" .) -}} +{{- end -}} {{- if and $.Values.ownerResolution.enabled (not (has (dig "deployment" "mode" "vm" (.values | default dict)) (list "container" "kata"))) -}} {{- $entryValues := .values | default dict -}} {{- $entryAccess := index $entryValues "accessControl" | default dict -}} @@ -459,11 +461,11 @@ openshellValues. Keep omission as vm without changing existing rendered values. {{- if not (has $mode (list "vm" "container" "kata")) -}} {{- fail "deployment.mode must be one of vm, container, kata" -}} {{- end -}} -{{- if and (has $mode (list "container" "kata")) (hasKey (.root.Values.containerSites | default dict) .user.name) -}} -{{- $u := .user -}} -{{- $site := index .root.Values.containerSites $u.name -}} +{{- if and (has $mode (list "container" "kata")) (or (hasKey (.root.Values.containerSites | default dict) .user.name) .root.Values.containerDefaults) -}} +{{- $u := include "saw-users.containerUser" (dict "root" .root "user" .user) | fromJson -}} +{{- $site := include "saw-users.containerSite" (dict "root" .root "user" $u) | fromJson -}} {{- if not (has (dig "deployment" "mode" "vm" ($u.values | default dict)) (list "container" "kata")) -}}{{- fail "deployment.mode=container must be explicit on each user" -}}{{- end -}} -{{- $foundation := eq (dig "automaticEnrollment" "enabled" true $site | toString) "false" -}} +{{- $foundation := or (eq (dig "automaticEnrollment" "enabled" true $site | toString) "false") (eq (dig "automaticEnrollment" "autoApprove" false $site | toString) "true") -}} {{- $catalog := (.root.Files.Get "files/profile-catalog.json" | fromJson).profiles -}} {{- $profile := first ($u.profiles | default list) | default "" -}} {{- $approved := or $foundation (hasKey (dig "automaticEnrollment" "approvedProfiles" dict $site) $profile) -}} @@ -471,6 +473,100 @@ openshellValues. Keep omission as vm without changing existing rendered values. {{- fail "container requires verified owner subject, scoped registration, approved BOM profile and foreground cleanup" -}} {{- end -}} {{- else if has $mode (list "container" "kata") -}} -{{- fail (printf "user %q: deployment.mode=container requires a containerSites entry" .user.name) -}} +{{- fail (printf "user %q: deployment.mode=container requires containerDefaults or a containerSites entry" .user.name) -}} +{{- end -}} +{{- end -}} + +{{/* installationID for a container user. An explicit value wins; otherwise +it is uuid5(NAMESPACE_URL, "urn:saw:portal::"), the same +ID the portal and inspect-boundary.py derive. Empty without a valid registration. */}} +{{- define "saw-users.installationID" -}} +{{- if .installationID -}} +{{- .installationID -}} +{{- else if regexMatch "^[0-9a-f]{16}$" (toString (.registration | default "")) -}} +{{- $h := printf "%s%s" ("a6e4EZ2tEdGAtADAT9QwyA==" | b64dec) (printf "urn:saw:portal:%s:%s" .name .registration) | sha1sum -}} +{{- $variant := index (dict "0" "8" "1" "9" "2" "a" "3" "b" "4" "8" "5" "9" "6" "a" "7" "b" "8" "8" "9" "9" "a" "a" "b" "b" "c" "8" "d" "9" "e" "a" "f" "b") (substr 16 17 $h) -}} +{{- printf "%s-%s-5%s-%s%s-%s" (substr 0 8 $h) (substr 8 12 $h) (substr 13 16 $h) $variant (substr 17 20 $h) (substr 20 32 $h) -}} +{{- end -}} +{{- end -}} + +{{/* A container user with defaults filled in, so an entry needs only name, +ownerSubject, profiles, vaultPrefix and values.deployment.mode: +- registration: sha256(":")[:16]; bump generation (default 1) + for a fresh workspace instead of reusing an old one's storage. +- vaultPrefix: a base path (default defaults.vaultPrefix) gets + /saw-/ appended; a full owner-scoped path is kept. +- pruneOnRemove: true, intentGeneration: 1, installationID: derived. +Explicit values always win. Returns JSON. */}} +{{- define "saw-users.containerUser" -}} +{{- $u := deepCopy .user -}} +{{- if not $u.registration -}} +{{- $_ := set $u "registration" (printf "%s:%v" $u.name ($u.generation | default 1) | sha256sum | trunc 16) -}} +{{- end -}} +{{- $base := $u.vaultPrefix | default .root.Values.defaults.vaultPrefix | default "secret/data/hub" | trimSuffix "/" -}} +{{- if not (regexMatch (printf "/saw-%s/%s$" $u.name $u.registration) $base) -}} +{{- $base = printf "%s/saw-%s/%s" $base $u.name $u.registration -}} +{{- end -}} +{{- $_ := set $u "vaultPrefix" $base -}} +{{- if not (hasKey $u "pruneOnRemove") }}{{ $_ := set $u "pruneOnRemove" true }}{{ end -}} +{{- if not (hasKey $u "intentGeneration") }}{{ $_ := set $u "intentGeneration" 1 }}{{ end -}} +{{- with include "saw-users.installationID" $u }}{{ $_ := set $u "installationID" . }}{{ end -}} +{{- toJson $u -}} +{{- end -}} + +{{/* Recursive merge of .over into .base by key presence: unlike Sprig's +mergeOverwrite, a false, 0 or "" in .over replaces the base value. Maps merge; +every other value (lists included) is replaced. Returns JSON. */}} +{{- define "saw-users.deepMerge" -}} +{{- $out := deepCopy (.base | default dict) -}} +{{- range $key, $value := (.over | default dict) -}} +{{- $current := index $out $key -}} +{{- if and (kindIs "map" $value) (kindIs "map" $current) -}} +{{- $_ := set $out $key (include "saw-users.deepMerge" (dict "base" $current "over" $value) | fromJson) -}} +{{- else -}} +{{- $_ := set $out $key $value -}} +{{- end -}} +{{- end -}} +{{- toJson $out -}} {{- end -}} + +{{/* A container user's site: containerSites. layered over the shared +containerDefaults (site values win). subject defaults to the user's +ownerSubject. On an autoApprove site every unset chart revision defaults to +global.targetRevision, so the workspace follows the pattern's branch like VM +users; reviewed sites must pin each revision to a commit SHA and are left +unset so the chart and preflight fail instead. Merged by key presence +(saw-users.deepMerge), so a per-user false or "" overrides a default, as in +the portal. Returns JSON. */}} +{{- define "saw-users.containerSite" -}} +{{- $root := .root -}}{{- $u := .user -}} +{{- $site := include "saw-users.deepMerge" (dict "base" ($root.Values.containerDefaults | default dict) "over" (index ($root.Values.containerSites | default dict) $u.name | default dict)) | fromJson -}} +{{- if and $site (not $site.subject) }}{{ $_ := set $site "subject" $u.ownerSubject }}{{ end -}} +{{- $rev := $root.Values.global.targetRevision -}} +{{- if eq (toString (dig "automaticEnrollment" "autoApprove" false $site)) "true" -}} +{{- $stack := $site.stack | default dict -}} +{{- range $key := list "identity" "policy" "gateway" "audit" -}} +{{- $item := index $stack $key | default dict -}} +{{- if and (kindIs "map" $item) (not $item.revision) }}{{ $_ := set $item "revision" $rev }}{{ end -}} +{{- $_ := set $stack $key $item -}} +{{- end -}} +{{- $_ := set $site "stack" $stack -}} +{{- with $site.automaticEnrollment -}} +{{- if not .revision }}{{ $_ := set . "revision" $rev }}{{ end -}} +{{- if and .relay (not .relay.revision) }}{{ $_ := set .relay "revision" $rev }}{{ end -}} +{{- end -}} +{{- end -}} +{{- toJson $site -}} +{{- end -}} + +{{/* "true" for a container or Kata user whose ownerSubject is not known yet +(typically before the Keycloak account exists) on an installation configured +for containers (containerDefaults or the user's containerSites entry). Such a +user is left out of every rendered resource and listed in the +saw-users-awaiting-owner ConfigMap, so VM users and the rest of the install +still sync. Without any container configuration the entry still fails. */}} +{{- define "saw-users.awaitingOwner" -}} +{{- $u := .user -}} +{{- $configured := or .root.Values.containerDefaults (hasKey (.root.Values.containerSites | default dict) ($u.name | default "")) -}} +{{- if and $configured (has (dig "deployment" "mode" "vm" ($u.values | default dict)) (list "container" "kata")) (not $u.ownerSubject) -}}true{{- end -}} {{- end -}} diff --git a/charts/saw-users/templates/applications.yaml b/charts/saw-users/templates/applications.yaml index 96905913b..e3323bd5a 100644 --- a/charts/saw-users/templates/applications.yaml +++ b/charts/saw-users/templates/applications.yaml @@ -1,7 +1,8 @@ {{- include "saw-users.validate" . -}} {{- range $user := .Values.users | default list }} -{{- if not (and $.Values.projection.enabled (has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata"))) }} +{{- if and (not (include "saw-users.awaitingOwner" (dict "root" $ "user" $user))) (not (and $.Values.projection.enabled (has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata")))) }} {{- $container := has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata") }} +{{- if $container }}{{- $user = include "saw-users.containerUser" (dict "root" $ "user" $user) | fromJson }}{{- end }} {{- if not $container }} --- {{ include "saw-users.application" (dict @@ -26,14 +27,24 @@ ) }} --- {{- if $container }} -{{- $site := deepCopy (index $.Values.containerSites $user.name | default dict) }} +{{- $site := include "saw-users.containerSite" (dict "root" $ "user" $user) | fromJson }} {{- $mode := dig "deployment" "mode" "vm" ($user.values | default dict) }} {{- if ne (eq $mode "kata") (not (empty $site.kataRuntimeClass)) }}{{ fail "registration placement differs from the site RuntimeClass approval" }}{{- end }} -{{- with $site.providerAllowHosts }} +{{- /* Which Secret backs which provider type; OpenShell's provider profiles + decide where each credential may be used. */}} {{- $scope := dict "root" $ "user" $user }} -{{- $policy := include "saw.governedProxyPolicy" (dict "catalog" ($.Files.Get "files/governed-profiles.json" | fromJson) "bindings" (include "saw-users.credentialBindings" $scope | fromJsonArray) "attached" (include "saw-users.secretNames" $scope | fromJsonArray) "allowHosts" .) | fromJson }} -{{- $_ := set $site "providerPolicy" $policy }} +{{- $attached := include "saw-users.secretNames" $scope | fromJsonArray }} +{{- $credentials := list }} +{{- range $binding := include "saw-users.credentialBindings" $scope | fromJsonArray }} +{{- if has $binding.name $attached }} +{{- range $type := $binding.providers }} +{{- $credential := dict "secret" $binding.name "key" $binding.key "type" $type }} +{{- if $binding.refresh }}{{- $_ := set $credential "refresh" "oauth2_refresh_token" }}{{- end }} +{{- $credentials = append $credentials $credential }} {{- end }} +{{- end }} +{{- end }} +{{- $_ := set $site "credentialBindings" $credentials }} {{ $values := dict "owner" $user.name "ownerSubject" $user.ownerSubject "registration" $user.registration "vaultPrefix" $user.vaultPrefix "installationID" $user.installationID "intentGeneration" $user.intentGeneration "site" $site "global" $.Values.global }} {{ include "saw-users.application" (dict "root" $ "user" $user "appName" (printf "saw-%s" $user.name) "wave" $.Values.syncWave.sandbox "path" "charts/saw-portal-container" "release" $user.name "values" (toYaml $values)) }} {{- else }} diff --git a/charts/saw-users/templates/awaiting-owner.yaml b/charts/saw-users/templates/awaiting-owner.yaml new file mode 100644 index 000000000..8d834cb7c --- /dev/null +++ b/charts/saw-users/templates/awaiting-owner.yaml @@ -0,0 +1,15 @@ +{{- /* Container/Kata users left out until their ownerSubject is set; see +saw-users.awaitingOwner. `oc get cm saw-users-awaiting-owner -o yaml` lists them. */ -}} +{{- $waiting := list }} +{{- range $user := .Values.users | default list }} +{{- if include "saw-users.awaitingOwner" (dict "root" $ "user" $user) }}{{- $waiting = append $waiting $user.name }}{{- end }} +{{- end }} +{{- if $waiting }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: saw-users-awaiting-owner +data: + users: {{ join "," $waiting | quote }} + next: "Create the Keycloak account (make keycloak-add-user KC_USER=), read its subject (make keycloak-user-info KC_USER=), set ownerSubject on the entry in overrides/saw-users.yaml and push." +{{- end }} diff --git a/charts/saw-users/templates/namespaces.yaml b/charts/saw-users/templates/namespaces.yaml index dce93a39f..6e8ca308e 100644 --- a/charts/saw-users/templates/namespaces.yaml +++ b/charts/saw-users/templates/namespaces.yaml @@ -1,6 +1,7 @@ {{- include "saw-users.validate" . -}} {{- range $user := .Values.users | default list }} -{{- if not (and $.Values.projection.enabled (has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata"))) }} +{{- if and (not (include "saw-users.awaitingOwner" (dict "root" $ "user" $user))) (not (and $.Values.projection.enabled (has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata")))) }} +{{- if has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata") }}{{- $user = include "saw-users.containerUser" (dict "root" $ "user" $user) | fromJson }}{{- end }} --- apiVersion: v1 kind: Namespace diff --git a/charts/saw-users/templates/projector.yaml b/charts/saw-users/templates/projector.yaml index 0ef7fd960..36c1b623a 100644 --- a/charts/saw-users/templates/projector.yaml +++ b/charts/saw-users/templates/projector.yaml @@ -1,14 +1,23 @@ {{- if .Values.projection.enabled }} {{- $users := list }} {{- range $user := .Values.users }} -{{- if has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata") }} -{{- $users = append $users $user }} +{{- if and (has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata")) $user.ownerSubject }} +{{- $users = append $users (include "saw-users.containerUser" (dict "root" $ "user" $user) | fromJson) }} {{- end }}{{- end }} {{- $owner := printf "%s/%s" .Release.Namespace .Release.Name | sha256sum | trunc 20 }} {{- $name := printf "saw-projector-%s" $owner }} {{- $config := dict }} {{- if $users }}{{- $config = deepCopy .Values }}{{- end }} {{- $_ := set $config "users" $users }} +{{- if $users }} +{{- $sites := dict }} +{{- range $user := $users }} +{{- $resolved := include "saw-users.containerSite" (dict "root" $ "user" $user) | fromJson }} +{{- if $resolved }}{{- $_ := set $sites $user.name $resolved }}{{- end }} +{{- end }} +{{- $_ := set $config "containerSites" $sites }} +{{- $_ := unset $config "containerDefaults" }} +{{- end }} {{- range $user := $users }} {{- $site := index $config.containerSites $user.name }} {{- if not $site }}{{ fail (printf "user %q: deployment.mode=container requires a containerSites entry" $user.name) }}{{ end }} @@ -94,7 +103,7 @@ subjects: [{kind: ServiceAccount, name: {{ $name }}-identity, namespace: {{ .Rel {{- $classes := list }} {{- range $user := $users }} {{- if eq (dig "deployment" "mode" "vm" ($user.values | default dict)) "kata" }} -{{- $classes = append $classes (dig "kataRuntimeClass" "name" "" (index $.Values.containerSites $user.name)) }} +{{- $classes = append $classes (dig "kataRuntimeClass" "name" "" (index $config.containerSites $user.name)) }} {{- end }} {{- end }} apiVersion: rbac.authorization.k8s.io/v1 @@ -273,6 +282,9 @@ metadata: name: {{ $name }} namespace: {{ $argo }} labels: {saw.redhat.com/projector-owner: {{ $owner | quote }}} + # After wave 0: the identity Job must have created the plugin token Secret, + # or the ApplicationSet controller fails to fetch it and waits to retry. + annotations: {argocd.argoproj.io/sync-wave: "1"} spec: goTemplate: true goTemplateOptions: [missingkey=error] diff --git a/charts/saw-users/values.yaml b/charts/saw-users/values.yaml index c863a7f3c..5c4537f03 100644 --- a/charts/saw-users/values.yaml +++ b/charts/saw-users/values.yaml @@ -138,6 +138,20 @@ global: pattern: secure-agent-workspace vpArgoNamespace: vp-gitops +# Container and Kata users (values.deployment.mode). A user entry needs only +# name, ownerSubject, profiles and vaultPrefix (the credential base path); +# registration, installationID, pruneOnRemove and intentGeneration have defaults +# (see saw-users.containerUser in _helpers.tpl). +# +# containerDefaults: the cluster-wide site every container user gets, with +# @OWNER@/@RUNTIME@/... placeholders. subject defaults to the user's +# ownerSubject and every chart revision to global.targetRevision. +# automaticEnrollment.autoApprove: true enrolls on first observation instead of +# an operator-reviewed reference/approvedProfiles (dev and demo clusters). +containerDefaults: {} +# containerSites.: per-user overrides layered over containerDefaults. +containerSites: {} + # Static container entries use the same workspace projector as the portal. # RHDH supplies already-projected values and leaves this disabled. projection: diff --git a/charts/saw-workspace-relay/templates/access.yaml b/charts/saw-workspace-relay/templates/access.yaml index 2bf81382f..f6a242d72 100644 --- a/charts/saw-workspace-relay/templates/access.yaml +++ b/charts/saw-workspace-relay/templates/access.yaml @@ -34,6 +34,7 @@ apiVersion: v1 kind: ServiceAccount metadata: {name: {{ $n }}} automountServiceAccountToken: false +{{- if $v.imageBuildNamespace }} --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding @@ -42,6 +43,7 @@ roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: system:i subjects: - {kind: ServiceAccount, name: {{ $n }}, namespace: {{ $ui }}} - {kind: ServiceAccount, name: {{ $n }}, namespace: {{ $v.trustedNamespace }}} +{{- end }} --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy diff --git a/charts/saw-workspace-relay/templates/identity.yaml b/charts/saw-workspace-relay/templates/identity.yaml index 36eb66abd..e489d10f7 100644 --- a/charts/saw-workspace-relay/templates/identity.yaml +++ b/charts/saw-workspace-relay/templates/identity.yaml @@ -107,7 +107,10 @@ metadata: {{- end }} spec: backoffLimit: 2 - activeDeadlineSeconds: 300 + # Creation waits in ContainerCreating until the Keycloak chart's + # saw-relay-provisioner Secret exists; Argo never recreates a failed Job, + # so a short deadline turned a slow dependency into a manual cleanup. + activeDeadlineSeconds: {{ if eq $action "delete" }}300{{ else }}1800{{ end }} template: spec: restartPolicy: Never diff --git a/docs/container-images.md b/docs/container-images.md index ca73cae31..bbb2f29d9 100644 --- a/docs/container-images.md +++ b/docs/container-images.md @@ -254,7 +254,18 @@ published image blobs while any site references their digests. The shipped notebook image sets `WORKDIR /sandbox` with mode `0770` and ownership `1000:0`. Container workspaces run with the OpenShift namespace UID and group. They need search permission on this directory to start the sandbox -entrypoint. Prepare the image once in the same build namespace as the runtime: +entrypoint. + +CI publishes the prepared image: `.github/workflows/build-openclaw-image.yml` +builds `images/saw-openclaw/Containerfile` from the notebook BOM's pinned +image and pushes `ghcr.io//saw-openclaw` (linux/amd64 and +linux/arm64), tagged +`src-`. Pin that tag's digest in +`containerDefaults.profileImageOverrides` (public, so no `imagePull` is +needed). A changed source digest in the BOM publishes a new tag. + +Disconnected clusters can prepare the image once in the same build namespace +as the runtime instead: ```sh make container-notebook-image BUILD_NS="$BUILD_NS" BUILD_ARCH=amd64 > notebook-site.yaml diff --git a/docs/container-installation.md b/docs/container-installation.md index ff5ed7b3c..e36e3ce6d 100644 --- a/docs/container-installation.md +++ b/docs/container-installation.md @@ -43,7 +43,9 @@ Additional requirements: - Reachable DNS, Kubernetes API, trusted OIDC issuer, governance, registry and approved provider endpoints. Use the [container topology preflight](#discover-and-review-container-egress) to derive API, DNS and issuer rules, or supply those rules explicitly. - Allocate a distinct AdminNetworkPolicy priority for each workspace. + Workspaces share one AdminNetworkPolicy priority (each policy selects only + its own namespace); enrollment refuses a workspace if any other policy + covering its namespace comes at or before it. - `oc`, Helm 3 and `uv` on the installation machine. Provider credentials stay in Vault; local files and Git contain references and public configuration. @@ -86,21 +88,26 @@ For Kata workload placement, follow the [Kata installation and Developer Hub gui The same site object is used as `containerSites.` for static installs or `portal.containerSites.` for RHDH. It is administrator-owned, not a form -field. Start from the component charts' values and schemas: +field. The component wiring (namespaces, service accounts, SANs, the +workspace egress policy, governance endpoint, enrollment build namespace, +resources and relay Keycloak settings) defaults in +[`siteDefaults`](../charts/saw-portal-container/values.yaml); a site sets only +what differs, and its values win (maps merge, lists replace). Start from the +component charts' values and schemas: | Site input | Contents / source | |---|---| | `subject` | Resolved Keycloak subject UUID matching the owner. Static inputs supply it explicitly; RHDH resolves the authenticated owner and requires a matching site. | -| `stack.identity` | Pinned revision and [identity chart values](../charts/saw-kubernetes-identity/values.yaml): installation identity, gateway SANs and stock generator/helper images. Administrator sessions use the VM's shared temporary-identity mechanism; no administrator certificate or renewal input is supplied. | -| `stack.policy` | Pinned revision and [admission/network values](../charts/saw-runtime-policies/values.yaml): runtime namespace, service accounts, explicit egress and unique priority. | -| `stack.proxy` | Pinned revision and [credential-proxy values](../charts/saw-kubernetes-proxy/values.yaml): trusted namespace and egress. Provider bindings/digest derive from the shared catalog. | +| `stack.identity` | Pinned revision and [identity chart values](../charts/saw-kubernetes-identity/values.yaml): installation identity, gateway SANs, stock generator/helper images and the bootstrap's API/DNS egress (`network.bootstrapEgress`). Administrator sessions use the VM's shared temporary-identity mechanism; no administrator certificate or renewal input is supplied. | +| `stack.policy` | Pinned revision and [admission/network values](../charts/saw-runtime-policies/values.yaml): runtime namespace, service accounts, explicit egress and priority. | | `stack.gateway` | Pinned revision and [gateway values](../charts/openshell-saw-kubernetes/values.yaml): stock gateway/driver images, storage, OIDC and network configuration. | | `stack.audit` | Pinned revision and [audit values](../charts/saw-audit-writer/values.yaml): history/exchange storage classes, image and owner identity. Targets derive from the BOM. | -| `governanceNamespace`, `providerAllowHosts` | Shared governance location and permitted provider destinations. | -| `automaticEnrollment` | `enabled`, pinned helper image/revision, build namespace, resource limits, approved profile digests and reviewed boundary reference. | +| `governanceNamespace` | Shared governance location (default `openshell-agents`); the gateway's interceptor endpoint and egress follow it. | +| `automaticEnrollment` | `enabled` (enrollment runs only when `true`), pinned helper image/revision, build namespace, resource limits, approved profile digests and reviewed boundary reference. | | `automaticEnrollment.relay` | Pinned relay chart revision, issuer, Keycloak namespace and realm registrar Secret **name**, and explicit DNS, OIDC and Kubernetes API egress. See [relay values](../charts/saw-workspace-relay/values.yaml). | -| `profileImageOverrides`, `profileBoundaries` | Optional per-profile pinned image overrides and explicit provider/boundary approval. Changing the profile requires its own approval. | +| `profileImageOverrides`, `profileBoundaries` | Optional per-profile pinned image overrides and reviewed boundary `reference`. Changing the profile requires its own approval. | | `imagePull` | Optional namespace and ImageStream names for access to an OpenShift internal registry. | +| `customInferenceURL` (per user) | `custom-inference` only: the owner's OpenAI-compatible base URL (HTTPS, port 443, ending `/v1`), from the portal form or the user's entry in `overrides/saw-users.yaml`. Its host must be the only endpoint in `overrides/governance-profiles/custom-inference.yaml`, where OpenShell sends the API key; the runtime controller otherwise refuses the provider (`ProviderProfileMismatch`). | RHDH offers **Container** on the create form when `portal.deploymentModes` includes `container` and at least one configured owner site has a catalog profile @@ -172,29 +179,20 @@ Match workload selectors and tolerations, and recheck after adding nodes or changing digests. Each node needs space for the selected images. Keep the holder running while the profile is in use. -### One-time Keycloak registration setup +### Keycloak registration setup -Use a dedicated Keycloak realm. Run this once from the checkout with an -explicit kubeconfig for the intended cluster. The bootstrap Job needs the -existing master bootstrap Secret only during setup. If the issuer requires -a private CA, supply `--ca-configmap NAME` with key `ca-bundle.crt`. - -```sh -python3 scripts/portal-container/setup-relay-provisioner.py \ - --namespace "$KEYCLOAK_NAMESPACE" --issuer "$KEYCLOAK_ISSUER" \ - --bootstrap-secret "$PLATFORM_BOOTSTRAP_SECRET" | - oc --kubeconfig="$KUBECONFIG" apply --server-side -f - -oc --kubeconfig="$KUBECONFIG" -n "$KEYCLOAK_NAMESPACE" wait \ - --for=condition=Complete job/saw-relay-provisioner --timeout=4m -``` - -Setup creates a confidential service account with only the realm-management -`create-client` permission. It registers an administrator-defined client scope +No manual step. With `relayProvisioner.enabled` (on in `values-prod.yaml`), +the `openshell-keycloak` chart runs a `saw-relay-provisioner` Deployment in the +Keycloak namespace. It uses the operator's `-initial-admin` Secret to +create a confidential service account with only the realm-management +`create-client` permission, registers an administrator-defined client scope `saw-workspace-relay` for the OpenShell audience and user role, and allows that -scope for authenticated dynamic registration. Its credential is stored in -`saw-relay-provisioner` in the Keycloak namespace. Set +scope for authenticated dynamic registration. It keeps the credential in the +`saw-relay-provisioner` Secret, which it creates itself so a GitOps self-heal +cannot clear it, and re-verifies every five minutes. Set `automaticEnrollment.relay.keycloakProvisionerSecret: saw-relay-provisioner` -and use a full Git commit for `automaticEnrollment.relay.revision`. +and use a full Git commit for `automaticEnrollment.relay.revision`. For an +issuer with a private CA, set `relayProvisioner.caBundle`. The registrar can create clients in the workspace realm. The Job enforces the registration-specific client name. Protect the registrar Secret and restrict who @@ -282,7 +280,8 @@ users: - name: alice ownerSubject: registration: <16-lowercase-hex-characters> - installationID: + # installationID: optional; defaults to the portal's + # uuid5(NAMESPACE_URL, "urn:saw:portal::") vaultPrefix: secret/data/hub/saw-alice/ profiles: [data-science] pruneOnRemove: true @@ -308,7 +307,8 @@ containerSites: ``` This shows the input contract, not a runnable site with omitted fields. Generate -unique registration/installation IDs and keep them stable for the installation. +a unique registration and keep it stable for the installation. Omit +`installationID` to use the derived value; set it only to keep an existing one. Never reuse an old registration to adopt retained storage or credentials. Enrollment also pins the initial compiled plan. A runtime/compiler change that @@ -496,6 +496,87 @@ operator-owned; deleting the standalone Helm release does not erase it. ## Pattern and RHDH enablement +### Minimal static entries + +The pattern reads two files for `saw-users`. The platform admin sets the +cluster-wide container settings once in `overrides/saw-container-defaults.yaml` +(`projection` and `containerDefaults`, the site every container user gets). +Users only add an entry to `overrides/saw-users.yaml`: + +```yaml +users: + - name: alice + ownerSubject: # make keycloak-user-info KC_USER=alice + profiles: [custom-inference] + vaultPrefix: secret/data/hub # credential base path + values: + deployment: {mode: container} +``` + +The chart fills in the rest; an explicit value always wins: + +| Field | Default | +|---|---| +| `registration` | `sha256(":")[:16]`; set `generation: 2` (default 1) for a fresh workspace instead of reusing an old one | +| `installationID` | `uuid5(NAMESPACE_URL, "urn:saw:portal::")` | +| `vaultPrefix` | base path + `/saw-/`; credentials go under it (for example `.../inference`) | +| `pruneOnRemove`, `intentGeneration` | `true`, `1` | +| site | `containerDefaults`, overlaid by `containerSites.`; `subject` is the user's `ownerSubject` | +| chart revisions | Reviewed sites: none. Set `stack.*.revision`, `automaticEnrollment.revision` and `relay.revision` to full commit SHAs; the workspace chart and preflight reject a branch or a missing revision. `autoApprove` sites: `global.targetRevision`, so they follow the pattern's branch like VM users. | + +Enrollment stays off unless a site sets `automaticEnrollment.enabled: true` +(and `autoApprove` defaults to `false`): a new workspace deploys its foundation and waits for +the reviewed flow below. After the review, set `enabled: true`, the reviewed +`reference` and the `approvedProfiles` digest under +`containerSites..automaticEnrollment`, and pin its chart revisions to +full SHAs. + +Development and demo clusters can skip the review by listing +`overrides/saw-container-demo.yaml` after `saw-container-defaults.yaml` in the +`saw-users` and `openshell-rhdh` `extraValueFiles`. It sets `autoApprove: true`: +the enrollment Job still runs its health, admission and network checks, then +publishes the boundary and BOM it observes instead of comparing them with a +reviewed `reference` and `approvedProfiles` digest. Later changes to an +enrolled boundary still fail closed; start a new `generation` to re-enroll. +`containerSites..automaticEnrollment.autoApprove: false` puts one user +back on the reviewed flow. Never list the demo file in production values. + +**Upgrading from the credential-proxy controller.** Container workspaces +enrolled before OpenShell-native providers cannot be upgraded in place: their +approved boundary lists the removed proxy objects, and their controller state +records proxy-era providers. They report `ReenrollRequired` and make no +changes. Re-enroll each one by starting a new generation (`generation: ` +in `overrides/saw-users.yaml`, or a new request in the portal), copying its +credentials to the new registration's Vault path first. With +`pruneOnRemove` (the default) the old registration's namespaces are removed. + +Generate the network overlay from both files with `make container-topology`; +it covers `containerDefaults` as well as individual sites. + +Before install, `make saw-init` checks the cluster for these entries: OVN-Kubernetes, +AdminNetworkPolicy and ValidatingAdmissionPolicy, a shared-filesystem +(ReadWriteMany) StorageClass for the audit exchange volume, and an +anonymous pull of the runtime image from inside the cluster. `pattern-install` +and `make saw-create DEPLOYMENT_MODE=container|kata` run it first. + +Without a ReadWriteMany class, `saw-init` stops and lists the options; it +creates nothing unless asked. Install a real shared filesystem first (ODF +CephFS, EFS, vendor NFS) and `saw-init` leaves storage alone. Two opt-ins: + +- `SAW_SHARED_STORAGE=efs` offers to create EFS on AWS (filesystem, mount + targets, security group, the AWS EFS CSI Driver Operator and StorageClass + `saw-efs`) with working `aws` credentials. +- `SAW_SHARED_STORAGE=nfs`, for development and demo clusters only, creates a + privileged NFS server Pod on a default-class volume in namespace `saw-nfs`, + the upstream NFS subdirectory provisioner (with a cluster-scoped role) and + StorageClass `saw-nfs`, then verifies a read/write mount. It is a single Pod + with no replication. + +A container entry without `ownerSubject` waits: it renders nothing and is listed +in the `saw-users-awaiting-owner` ConfigMap, so other users still sync. Set it +from `make keycloak-user-info KC_USER=` once the account exists. With +`make saw-create`, an omitted `ownerSubject` is resolved from Keycloak. + For static pattern users, put the same values under `overrides/saw-users.yaml`, enable `projection`, commit them and let the existing `saw-users` Application reconcile. Its namespace must be separate from Argo CD. VM users keep their diff --git a/docs/container-workspaces.md b/docs/container-workspaces.md index d6d5bfb18..4c49c355a 100644 --- a/docs/container-workspaces.md +++ b/docs/container-workspaces.md @@ -44,13 +44,13 @@ flowchart TD | Common `workspace.py` | Projects a registration and catalog into `saw-users` values: sandbox topology, image overrides, approved profile digest, model inputs and public enrollment. Also implements shared readiness: matching BOM/intent generation, healthy Argo application and owner login challenge. It performs no credential storage or resource mutation. | | RHDH adapter | Authenticates requests, resolves owners, stores provider inputs, maintains registration and drives the existing Tekton/ApplicationSet flow. Its forms come from the shared catalog. | | Standalone projector | An ApplicationSet plugin installed by `saw-users` when `projection.enabled`. Uses the same `workspace.py` as RHDH, with operator-owned YAML instead of portal registrations. Reads named public enrollment ConfigMaps and its own named child Applications. It has no Kubernetes write or Secret-read permission. | -| Container composition | Creates per-registration identity, network policy, credential proxy, gateway, PVCs, audit services, preparation Jobs, reconciler and browser relay through Argo CD. | +| Container composition | Creates per-registration identity, network policy, gateway, PVCs, audit services, preparation Jobs, reconciler and browser relay through Argo CD. | | Enrollment Job | Compares deployed resources against an administrator-approved boundary; records actual resource UIDs and hashes, PVC identities and public trust material in an immutable publication. It cannot approve an arbitrary observed configuration. | | Kubernetes reconciler | Reads BOM + intent, checks the approved boundary and attachment identities, compiles stock OpenShell RPCs, and reconciles owned objects using a retained ledger. It does not create application Pods directly. | | Stock gateway / driver | Implements workspace/provider/sandbox APIs and creates supervisor Pods and agent-sandbox resources. Gateway state has its own PVC. | | Stock agent-sandbox controller | Reconciles the workload resource into the application Pod. Its CRD/controller is a separate prerequisite, not a SAW API. | | Governance interceptor | Supplies signed provider profiles and policy. SAW's extension restricts Kubernetes driver configuration to an approved PVC/resource envelope submitted by a platform mTLS operator. | -| Credential proxy | Resolves opaque credential markers using trusted-namespace Secrets and the shared provider policy. It supplies credentials only for approved destinations. | +| Provider credentials | OpenShell providers. The reconciler hands OpenShell each value from the trusted-namespace Secret when it creates a provider or the Secret rotates (and configures OAuth refresh); the plan and its state hold only references. OpenShell's supervisor, in its own Pod, puts placeholders in the agent's environment and substitutes the real value only for the endpoints in that provider's profile. | | Audit writer | Owns retained history outside the application namespace and signs acknowledgements after append. The application mounts an exchange volume, not the history PVC. | | Browser relay | Combines owner-only login, a dedicated nonadmin Keycloak client, shared connection limiter and stock OpenShell forwarding. Its membership is scoped to the intended workspace. Only its membership Job opens a temporary gateway operator session; the UI has no operator identity or trust-write permission. | @@ -103,8 +103,8 @@ not mean that a container runs the VM installer. 4. Argo creates the foundation. Enrollment verifies the approved configuration and publishes the registration binding. The generator reads only the named public publications and reprojects the values to enable runtime resources. - A new site can set `automaticEnrollment.enabled: false` to deploy its - foundation for review. Enabling enrollment requires approved reference + A new site deploys only its foundation for review until it sets + `automaticEnrollment.enabled: true`. Enabling enrollment requires approved reference hashes; discovery is not approval. 5. The reconciler requires a coherent BOM digest and intent generation, checks namespace/PVC UIDs and the live boundary, and then calls the gateway. It @@ -121,7 +121,7 @@ sequenceDiagram participant Gateway as OpenShell gateway participant Pod as Workload Git->>Argo: Approved profile + site + desired registration - Argo->>Argo: Identity, network, proxy, gateway, PVCs, BOM + Argo->>Argo: Identity, network, gateway, PVCs, BOM Argo->>Enroll: Pinned bootstrap inputs Enroll->>Enroll: Check approved boundary and ownership Enroll->>Project: Immutable binding: UIDs, hashes, public keys @@ -144,8 +144,16 @@ Policies protect different boundaries: - **OpenShift admission and network policy** constrain Pod roles, service accounts, placement and network reachability. A reconciler's permission to call the gateway does not bypass these controls. -- **Credential-proxy policy** derives from the same provider catalog and Helm - helper used by VM mode; credentials are not copied into application Pods. +- **Provider credentials** follow OpenShell's provider model: the platform + provider profiles the gateway serves (shipped or published by the governance + interceptor) decide where each credential may be used, and the supervisor + enforces it. The agent Pod never receives a credential, only a placeholder. + Supervisors may reach public HTTPS (`network.publicHTTPS`). Before creating a + credentialed provider, the runtime controller requires the live profile's + endpoints to be exactly the approved set, all in enforce mode: the governed + profile shipped with the runtime image, or for `custom-inference` only the + workspace's `customInferenceURL` host on 443. Otherwise it stops with + `ProviderProfileMismatch`. - **Tool-action policy** uses the same `tool-actions.yaml`, decision engine and OpenClaw hook as VM mode. The Kubernetes adapter changes storage and audit transport, not the decision rules. @@ -224,11 +232,12 @@ flowchart LR Login --> Relay[Scoped relay / OpenShell forward] Relay --> Gateway[Gateway and supervisor] Gateway --> Agent[Agent / OpenClaw] - Agent -->|Provider marker| Proxy[Trusted credential proxy] + Agent -->|Placeholder| Supervisor[OpenShell supervisor Pod] Vault[Vault] --> ESO[External Secrets] ESO --> Secrets[Trusted-namespace Secrets] - Secrets --> Proxy - Proxy -->|Real credential| Provider[Approved inference / tool API] + Secrets -->|Reconciler, on create or rotation| Gateway[OpenShell gateway credential store] + Gateway --> Supervisor + Supervisor -->|Real credential, profile endpoints only| Provider[Approved inference / tool API] Agent --> Gate[Shared tool gate] Gate --> Exchange[Audit exchange PVC] Exchange --> Writer[Restricted forwarder and writer] @@ -252,8 +261,8 @@ replaced together so removed permissions or providers do not survive an update. An explicit container model uses an internal OpenClaw provider ID such as `saw-openai/gpt-4.1`. This prevents the stock built-in model catalog from rewriting a requested model to a different release. The BOM still names -`openai`; its approved OpenAI endpoint, protocol, credential marker and proxy -authorization are unchanged. Chat transcripts therefore identify the internal +`openai`; its approved OpenAI endpoint, protocol and OpenShell provider are +unchanged. Chat transcripts therefore identify the internal provider alias and the exact requested model. VM native onboarding remains unchanged. The native writer regression can run against a stock binary with `node tests/openclaw-config-publication.mjs`; add `--expect-restore` on versions diff --git a/docs/custom-inference.md b/docs/custom-inference.md index 049ab7d47..696436dc1 100644 --- a/docs/custom-inference.md +++ b/docs/custom-inference.md @@ -146,6 +146,14 @@ stated (`openai`): the installer cannot infer it for a profile of your own. Custom keyed ports and in-cluster service-CA trust are follow-up work. - `inferenceTimeout` on a provider is no longer used: there is no gateway router to time out. Use the sandbox's `inference.timeoutSeconds`. +- OpenClaw offers only `default` and `off` thinking for a custom model. Set + the sandbox's `inference.thinking` (`off`, `minimal`, `low`, `medium` or + `high`) to make that level the model's default. Any level but `off` also + marks the model as a reasoning model accepting `low`, `medium` and `high`, + which OpenClaw sends as `reasoning_effort`; the endpoint may ignore it. + `off` marks it `reasoning: false` instead (like `MODEL_REASONING=false`); an + unquoted YAML `off` (read as `false`) also means off. A + chat's `/think` still overrides the default. VM workspaces only for now. ### Keycloak compatibility diff --git a/docs/governance-interceptor.md b/docs/governance-interceptor.md index f2df6a303..9cd9f1f30 100644 --- a/docs/governance-interceptor.md +++ b/docs/governance-interceptor.md @@ -199,10 +199,10 @@ The interceptor above does not see a tool call. OpenShell 0.1.6 only forwards al OpenClaw loads `saw-tool-gate` from `/sandbox/.saw/trusted/plugin` through `plugins.load.paths`. The installer appends it to a restrictive `plugins.allow`, enables it, and verifies that OpenClaw reports it loaded from the trusted mount. Each policy read is hashed against a SHA-256 constant embedded in the mounted plugin. A mismatch denies the call with rule `policy-hash`. - The default action is `deny`. The explicit read-only allowlist covers `read`, memory reads, session inspection, and `exec` for `git status`, `git diff`, `git log`, and `git show`. `message`, `git push`, `gh pr merge`, `rm`, `kubectl delete`, and `oc delete` require approval. Unknown tools deny. -- The daily briefing allows exactly `slack-reader__new_messages`, `slack-reader__channels`, `gmail-reader__new_messages`, and `briefing-writer__save_briefing`. The writer saves only today's briefing; generic `write` stays denied. `exec` for `openclaw cron list` is allowed, while `openclaw cron add` and `openclaw cron rm` require approval. Scheduled updates use only the allowed readers and writer. +- The daily briefing allows exactly `slack-reader__new_messages`, `slack-reader__channels`, `gmail-reader__new_messages`, and `briefing-writer__save_briefing`. The writer saves only today's briefing; generic `write` stays denied. `exec` for `openclaw cron list` is allowed, as are `--help` and ` --help`, while `openclaw cron add`/`create`, `edit`, `rm`/`remove`/`delete`, `enable`, `disable` and `run` require approval (`openclaw automations` is the same). That card also offers **Allow always**: later automation changes then run without asking until the gateway restarts or the policy changes, and each is still audited (`approval.mode: remembered`). No other approval rule offers it. Scheduled updates use only the allowed readers and writer. - `openclaw agents set-identity` always requires approval. Its identity-file and avatar arguments can read outside the workspace or fetch remote content, and it rewrites `openclaw.json`; `tools.fs.workspaceOnly` does not constrain this CLI command. Denial, cancellation and timeout block execution. - `tool_search` and `tool_call` are allowed for discovery and dispatch. Live testing on OpenClaw 2026.9.2 (`3928bad`) with only these dispatcher rules produced separate `default`/`deny` audit records for `slack-reader__new_messages` and `gmail-reader__new_messages`. Every dispatched target therefore still needs its own rule. Recheck that behavior when upgrading OpenClaw; do not allow a dispatcher that bypasses target hooks. -- `exec` matches the command at its start after normalizing whitespace, leading assignments, and the executable basename. Empty commands deny as `exec-unreadable`; shell operators and opaque wrappers such as `sh -c` deny as `exec-opaque`. +- `exec` matches the command at its start after normalizing whitespace, leading assignments, and the executable basename. Empty commands deny as `exec-unreadable`; shell operators and opaque wrappers such as `sh -c` deny as `exec-opaque`. A trailing `2>&1` is ignored. Each denial tells the agent how to retry (one command per call), or that an unlisted command should not be retried in another form; an unlisted command also lists the accepted commands that start with the same two words, such as `openclaw automations`. - Every call appends one JSON line to `/sandbox/.saw/audit/tool-actions.jsonl`, a separate `saw-audit-*` volume. The directory is not writable by the sandbox user, and the log file is append-only (`chattr +a`). The same line goes to gateway stderr for `podman logs`. Each line includes the user, OpenClaw session task id, `policyHash`, rule, and decision. An optional `/sandbox/.saw/current-task.json` `title` is copied onto that record. - `allow` runs the tool after the audit append succeeds. - `deny` blocks it. diff --git a/docs/harness-bundles.md b/docs/harness-bundles.md index 09565e5e9..aa27b908a 100644 --- a/docs/harness-bundles.md +++ b/docs/harness-bundles.md @@ -191,6 +191,33 @@ in-cluster MCP services should use `credentialFree: true`, or expose keyed services through an HTTPS Route on port 443. HTTPS to a `.svc` host on another port is refused. Add any in-cluster peer to the proxy's NetworkPolicy too. +#### Tool actions for the bundle's MCP tools + +SAW's tool gate refuses any tool its policy does not name. A bundle names +what the gate may do with its own MCP tools, next to the server that +provides them: + +```yaml +spec: + mcpServers: + - name: mailpit_reader + governanceProfile: mailpit + tools: + - {name: saw_read_email, action: allow} # or approval +``` + +Each entry becomes a gate rule for `__`, the name OpenClaw +gives an MCP tool, and OpenClaw's tool allowlist gets the same tools. A +bundle can only name tools of servers in its own `mcp.json`, and only +`allow` or `approval`; it cannot change built-in tools such as `exec` or +another bundle's tools. The rules follow the base `tool-actions.yaml`, so +where the base policy names the same tool, the base rule decides. They are +part of the gate policy whose hash the gate checks, so changing them changes +the bundle digest and the gate, like any other edit to the bundle. + +Container workspaces apply these rules today. VM workspaces still take their +tool actions from the base `tool-actions.yaml` only. + ### Tool plugins (`plugins//`) Plain ES modules (`.mjs`, or `.js` with `"type": "module"`), self-contained: diff --git a/docs/openshell-016-release.md b/docs/openshell-016-release.md index 9a7c52d9e..09e3745bd 100644 --- a/docs/openshell-016-release.md +++ b/docs/openshell-016-release.md @@ -81,8 +81,9 @@ remove it to bypass recovery. A configured agent can resume without a usable provider while retaining its model/credentials; unchanged reapply leaves it running. In OpenClaw 2026.9.6, `automations` aliases `cron`. Only `list`, `status`, `get`, -`show` and `runs` need no approval; `add`, `edit`, `rm`, `enable`, `disable` and -`run` require it. Unsupported aliases, mixed read/write `scratch`, unknown +`show` and `runs` need no approval; `add`/`create`, `edit`, `rm`, `enable`, +`disable` and `run` require it. Unsupported aliases (`remove`, `delete`), mixed +read/write `scratch`, unknown commands and shell wrappers remain denied. Every `agents set-identity` call requires approval: its file/avatar inputs can reach outside the workspace and it rewrites configuration, beyond filesystem-tool confinement. Denial, diff --git a/docs/personal-assistant.md b/docs/personal-assistant.md index 881c84250..c74fe4ef9 100644 --- a/docs/personal-assistant.md +++ b/docs/personal-assistant.md @@ -65,6 +65,12 @@ Slack remains a static bot token. Check: openshell provider refresh status gmail --workspace personal-assistant ``` +Container workspaces sync only the Gmail OAuth material (client ID, client +secret, refresh token) from Vault; no access token is stored. The runtime +controller creates the OpenShell provider without a credential value and +configures refresh, and OpenShell mints and rotates the access token. Check it +with the same `openshell provider refresh status` command. + The token URL host must stay in `egress.allow`. A token-only Gmail Secret is accepted with a warning and needs manual renewal. Mode switches preserve `/sandbox/briefing`; see [switching modes](credential-isolation.md#switching-modes) diff --git a/images/saw-openclaw/Containerfile b/images/saw-openclaw/Containerfile new file mode 100644 index 000000000..5d3df5321 --- /dev/null +++ b/images/saw-openclaw/Containerfile @@ -0,0 +1,15 @@ +# The stock OpenClaw image with /sandbox searchable by any UID. +# +# Its /sandbox is 0770 and owned by 1000:0, but OpenShift runs each workspace +# as its namespace's UID, which then cannot reach the volumes SAW mounts under +# /sandbox. This adds only the search bit (o+x); nothing else changes. The same +# steps as make container-notebook-image, built in CI instead of in-cluster. +# +# SOURCE_IMAGE: the digest-pinned stock image (the notebook BOM's image). +# IMAGE_USER: the stock image's own USER, restored after the change. +ARG SOURCE_IMAGE +FROM ${SOURCE_IMAGE} +ARG IMAGE_USER +USER 0 +RUN test -d /sandbox && chmod o+x /sandbox +USER ${IMAGE_USER} diff --git a/kubernetes-runtime/Containerfile b/kubernetes-runtime/Containerfile index e50b368da..1edc3542b 100644 --- a/kubernetes-runtime/Containerfile +++ b/kubernetes-runtime/Containerfile @@ -17,6 +17,8 @@ COPY charts/openshell-saw/files/provider-profiles/ charts/openshell-saw/files/pr COPY charts/saw-users/files/workspace.py /opt/saw/kubernetes-runtime/saw_workspace.py COPY kubernetes-runtime/saw_kubernetes kubernetes-runtime/saw_kubernetes ENV PYTHONPATH=/opt/saw/kubernetes-runtime:/opt/saw/sdk PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 -RUN python3 -c 'from openshell._proto import openshell_pb2_grpc; from saw_kubernetes import serve' +# COPY keeps the builder's file modes; the runtime runs as a non-root UID. +RUN chmod -R a+rX,go-w /opt/saw USER 1001 +RUN python3 -c 'from openshell._proto import openshell_pb2_grpc; from saw_kubernetes import serve' ENTRYPOINT ["python3", "-m", "saw_kubernetes.serve"] diff --git a/kubernetes-runtime/saw_kubernetes/adapters.py b/kubernetes-runtime/saw_kubernetes/adapters.py index 11535a3ed..406aa0e5b 100644 --- a/kubernetes-runtime/saw_kubernetes/adapters.py +++ b/kubernetes-runtime/saw_kubernetes/adapters.py @@ -12,8 +12,9 @@ RPC_METHODS = { "GetGatewayInfo", "GetWorkspace", "CreateWorkspace", "ListWorkspaceMembers", - "AddWorkspaceMember", "GetProviderProfile", "GetProvider", "CreateProvider", "GetSandbox", - "CreateSandbox", "StartSandbox", "StopSandbox", + "AddWorkspaceMember", "GetProviderProfile", "ListProviderProfiles", "GetProvider", + "CreateProvider", "UpdateProvider", "ConfigureProviderRefresh", "RotateProviderCredential", + "GetProviderRefreshStatus", "GetSandbox", "CreateSandbox", "StartSandbox", "StopSandbox", } diff --git a/kubernetes-runtime/saw_kubernetes/admin_session.py b/kubernetes-runtime/saw_kubernetes/admin_session.py index d34d71cb9..2a2757c93 100644 --- a/kubernetes-runtime/saw_kubernetes/admin_session.py +++ b/kubernetes-runtime/saw_kubernetes/admin_session.py @@ -26,6 +26,8 @@ OWNER = "saw.redhat.com/runtime-owner" NAME = re.compile(r"[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?\Z") OPERATOR_SUBJECT = "/O=openshell/OU=operator/CN=saw-installer" +# Codes a probe sees while the gateway does not trust the session CA yet. +TRUST_PENDING = frozenset({"UNAVAILABLE", "UNAUTHENTICATED", "DEADLINE_EXCEEDED", "UNKNOWN", "INTERNAL"}) def encoded(raw): @@ -200,7 +202,13 @@ def accepted(): gateway.call("GetGatewayInfo", {}) return True except RpcError as exc: - if exc.code not in {"UNAVAILABLE", "UNAUTHENTICATED"}: raise + # Under TLS 1.3 the gateway rejects a not-yet-trusted + # client certificate after the handshake, so the probe + # sees a broken read (UNKNOWN/INTERNAL/DEADLINE_EXCEEDED) + # rather than UNAUTHENTICATED. Re-raising here ended the + # session and minted a fresh CA every cycle, which never + # outran the kubelet's Secret propagation. + if exc.code not in TRUST_PENDING: raise return False admin.wait_for_trust(accepted) gateway.timeout = 20 diff --git a/kubernetes-runtime/saw_kubernetes/boundary.py b/kubernetes-runtime/saw_kubernetes/boundary.py index ea2c1c667..9501ddf9c 100644 --- a/kubernetes-runtime/saw_kubernetes/boundary.py +++ b/kubernetes-runtime/saw_kubernetes/boundary.py @@ -4,7 +4,6 @@ import yaml -from . import provider as governed class BoundaryError(ValueError): @@ -55,10 +54,6 @@ def objects(config): "governanceService": (f"{core}/{governance}/services/governance-interceptor", "spec"), "governancePolicy": (f"{core}/{governance}/configmaps/governance-interceptor-policy", "data"), "governanceProfiles": (f"{core}/{governance}/configmaps/governance-interceptor-profiles", "data"), - "proxy": (f"{apps}/{trusted}/deployments/{gateway}-credential-proxy", "spec"), - "proxyNetwork": (f"{net}/{trusted}/networkpolicies/{gateway}-credential-proxy", "spec"), - "proxyPolicy": (f"{core}/{trusted}/configmaps/{config['proxyPolicy']}", "data"), - "publicCA": (f"{core}/{ns}/configmaps/{gateway}-proxy-ca", "data"), } @@ -89,10 +84,18 @@ def excludes_namespace(policy, namespace): return isinstance(name, str) and bool(name) and name != namespace +# Objects of the removed SAW credential proxy. An approval that still lists +# them was published by the proxy-era controller; it cannot be upgraded in +# place, only re-enrolled (a new generation). +PROXY_ERA_OBJECTS = frozenset({"proxy", "proxyNetwork", "proxyPolicy", "publicCA"}) + + def verify(config, plan, get): if (config["namespace"], config["namespaceUID"], config["ownerID"], config["mode"]) != ( plan["namespace"], plan["namespaceUID"], plan["ownerID"], plan["mode"]): raise BoundaryError("WrongInstallation") + if PROXY_ERA_OBJECTS & set(config["approved"]): + raise BoundaryError("ReenrollRequired") refs = objects(config) if set(config["approved"]) != set(refs): raise BoundaryError("IncompleteApproval") @@ -105,19 +108,6 @@ def verify(config, plan, get): or fingerprint(obj[field]) != expected["sha256"]): raise BoundaryError("ChangedBoundary:" + key) observed[key] = obj - for workspace in plan.get("workspaces", []): - for provider in workspace["providers"]: - credentials = provider.get("credentials") - if credentials: - policy = json.loads(observed["proxyPolicy"]["data"]["config.json"]) - kind = provider.get("type", "openai") - if kind not in {"openai", "custom-inference"}: - live = observed["governanceProfiles"]["data"].get(kind + ".yaml", "") - if yaml.safe_load(live) != governed.document(kind): - raise BoundaryError("ProviderGovernanceMismatch") - if not governed.check_policy(kind, credentials, policy, plan.get("customInferenceURL")): - raise BoundaryError("OpenAIProxyBindingMismatch" if kind == "openai" - else "ProviderProxyBindingMismatch") checks = ["validation", "secretGuard", "serviceGuard", "podDeleteGuard"] if config["mode"] == "kata": import tomllib @@ -148,7 +138,7 @@ def verify(config, plan, get): and c.get("reason") == "SetupSucceeded"} if not zones or not zones <= realized: raise BoundaryError("NetworkNotRealized") - for key in ("gateway", "governance", "proxy"): + for key in ("gateway", "governance"): obj = observed[key] status = obj.get("status", {}) if (status.get("observedGeneration") != obj["metadata"]["generation"] diff --git a/kubernetes-runtime/saw_kubernetes/compiler.py b/kubernetes-runtime/saw_kubernetes/compiler.py index 6f7f493c1..cc31c39fe 100644 --- a/kubernetes-runtime/saw_kubernetes/compiler.py +++ b/kubernetes-runtime/saw_kubernetes/compiler.py @@ -28,9 +28,9 @@ SAFE_FAILURE_REASONS = frozenset({ "ProfileRejected", "InvalidPlan", "PlacementRejected", "IdentityConflict", "InvalidIntent", "StaleIntent", "ReconcilerStateRejected", "GatewayMismatch", - "ProviderProfileMismatch", + "ProviderProfileMismatch", "ProviderRefreshFailed", "WorkspaceRejected", "ProviderRejected", "SandboxRejected", - "SandboxStateMismatch", "SandboxDrift", + "SandboxStateMismatch", "SandboxDrift", "ReenrollRequired", }) @@ -167,7 +167,7 @@ def compile_profile(profile_dir, config): def _openclaw_startup(kind, info): - slot, _ = governed.requirements(kind, info.get("baseUrl")) + key_env = governed.inference_key_env(kind) endpoint = info.get("baseUrl") or shared.NATIVE_BASE_URLS[kind] provider_id = shared.openclaw_managed_provider_id(kind) timeout = info.get("timeoutSeconds", 0) @@ -176,7 +176,7 @@ def _openclaw_startup(kind, info): .replace("@SAW_BASE_URL@", json.dumps(endpoint)) .replace("@SAW_TIMEOUT@", f"timeoutSeconds: {timeout}, " if timeout else "") .replace("@SAW_API@", "anthropic-messages" if info["protocol"] == "anthropic" else "openai-completions") - .replace("@SAW_KEY_ENV@", slot["env_vars"][0]) + .replace("@SAW_KEY_ENV@", key_env) .replace("@SAW_PROVIDER_ID@", provider_id)) @@ -197,7 +197,7 @@ def _compatible_inference(workspace, sandbox, config): except (ValueError, TypeError) as exc: raise ContractError("custom inference endpoint is not approved") from exc inputs = config.get("modelInputs", {}) - credentials = {(b["secret"], b["key"]) for b in config.get("proxyBindings", [])} + credentials = {(b["secret"], b["key"]) for b in config.get("credentialBindings", [])} def read_model(secret, key): if secret != provider.credential_secret or (secret, key) in credentials: raise ContractError("model input is outside the public inference binding") @@ -225,7 +225,10 @@ def read_model(secret, key): return provider, info -def compile_profile_files(files, config): +REFRESH_MATERIAL = ("client_id", "client_secret", "refresh_token") + + +def compile_profile_files(files, config, gateway_profiles=None): """Compile stock SAW ConfigMap data with administrator-approved bindings. The shared VM/Kubernetes core owns document parsing, models and semantic @@ -246,7 +249,7 @@ def compile_profile_files(files, config): raise ContractError("profile documents fail shared SAW schema or semantic validation") from None mapping(config, {"ownerID", "namespace", "namespaceUID", "ownerSubject", "mode", "workloadRuntimeClass", "workloadRuntimeClassUID", "workloadRuntimeClassDigest", "bindings", - "approvedCredentialFreeProviders", "gatewayVersion", "retiredSandboxes", "modelInputs", "proxyBindings", "customInferenceURL"}, + "approvedCredentialFreeProviders", "gatewayVersion", "retiredSandboxes", "modelInputs", "credentialBindings", "customInferenceURL"}, {"ownerID", "namespace", "namespaceUID", "ownerSubject", "mode", "bindings", "approvedCredentialFreeProviders", "gatewayVersion"}, "administrator configuration") try: @@ -295,23 +298,29 @@ def compile_profile_files(files, config): name(provider.name, "provider") name(provider.type, "provider type") # All semantic checks (references, credentialFree, governed names) - # live in the common core. The trusted proxy owns private credentials and refresh. + # live in the common core. OpenShell owns the credential once the + # reconciler hands it over; the plan only names where it comes from. entry = {"metadata": {"name": provider.name, "labels": { MANAGED: "kubernetes-runtime", OWNER: owner}}, "type": provider.type} - if not config.get("proxyBindings") and (provider.refresh_strategy or provider.credentials_spec or provider.credential_secret_key != "api_key"): + if provider.credentials_spec or provider.refresh_strategy not in ("", "oauth2_refresh_token"): raise ContractError("provider requires an unported credential/refresh capability or approval") if provider.credential_free: if provider.type == "custom-inference": raise ContractError("custom inference requires a bound credential") if provider.type not in approved: raise ContractError("credential-free provider requires administrator approval") - elif config.get("proxyBindings"): - try: - entry["credentials"] = governed.checked_marker(provider, config["proxyBindings"], config.get("customInferenceURL")) - except ValueError as exc: - raise ContractError(str(exc)) from exc else: - raise ContractError("provider requires an unported credential/refresh capability or approval") + ref = {"secret": provider.credential_secret, "key": provider.credential_secret_key, + "type": provider.type} + if provider.refresh_strategy: + ref["refresh"] = provider.refresh_strategy + if ref not in config.get("credentialBindings", []): + raise ContractError("provider credential is not one the site approved") + entry["credentialRef"] = {"secret": ref["secret"], "key": ref["key"]} + if provider.refresh_strategy: + # OpenShell refreshes the access token from this material + # (in the same Secret) once the reconciler configures it. + entry["refresh"] = {"strategy": provider.refresh_strategy, "material": list(REFRESH_MATERIAL)} providers.append(entry) sandboxes = [] for sandbox in workspace.sandboxes: @@ -328,7 +337,7 @@ def compile_profile_files(files, config): raise ContractError("UI route capability requires the matching approved OpenClaw browser binding") if sandbox.type in ("openclaw", "nemoclaw"): inference_provider, info = _compatible_inference(workspace, sandbox, config) - if not any(p["metadata"]["name"] == inference_provider.name and p.get("credentials") + if not any(p["metadata"]["name"] == inference_provider.name and p.get("credentialRef") for p in providers): raise ContractError("agent requires an explicitly bound inference credential") kind = inference_provider.type @@ -377,7 +386,9 @@ def compile_profile_files(files, config): assets = Path(shared.__file__).parent receipt_key = bindings[key]["toolGate"].get("receiptKey") try: - _, _, gate_digest, _ = shared.tool_gate_bundle(assets, identity, receipt_key) + enrolled = harness.binding_for(sandbox, bundles) + rules = harness.tool_rules(bundles[enrolled["name"]] if enrolled else None) + _, _, gate_digest, _ = shared.tool_gate_bundle(assets, identity, receipt_key, rules) except shared.InstallerError as exc: raise ContractError(str(exc)) from exc script = Path(__file__).with_name("tool_gate_preflight.js").read_text() @@ -425,7 +436,10 @@ def compile_profile_files(files, config): if not gate.get("receiptKey") or sandbox.type not in ("openclaw", "nemoclaw"): raise ContractError("harness requires an enrolled agent and signed tool gate") provider_types = {p.type for p in workspace.providers if p.enabled and p.name in sandbox.providers} - catalog = {t: governed.requirements(t)[1] for t in provider_types if t in governed.SUPPORTED} + # The providers the gateway serves, as in VM mode; enrollment has + # no gateway yet and leaves this check to the controller. + catalog = (None if gateway_profiles is None else + {t: gateway_profiles[t] for t in provider_types if t in gateway_profiles}) harness.configure(command, driver, bundles[expected_harness["name"]], workspace, sandbox, catalog) except shared.InstallerError as exc: raise ContractError(str(exc)) from exc diff --git a/kubernetes-runtime/saw_kubernetes/controller.py b/kubernetes-runtime/saw_kubernetes/controller.py index de1a8b5df..f092c2be9 100644 --- a/kubernetes-runtime/saw_kubernetes/controller.py +++ b/kubernetes-runtime/saw_kubernetes/controller.py @@ -358,8 +358,10 @@ def _once(self): if intent["desiredState"] == "Running": try: self.verify_boundary(plan) - except Exception: - raise InputError("BoundaryRejected") from None + except Exception as exc: + # Only the proxy-era approval gets its own reason: the fix is a re-enrollment. + reason = "ReenrollRequired" if str(exc) == "ReenrollRequired" else "BoundaryRejected" + raise InputError(reason) from None # Stopped delegates to the core's identity-checked shutdown path. # Renewed network/attachment approval must not prevent stopping an # already recorded sandbox. Input fencing above remains mandatory. diff --git a/kubernetes-runtime/saw_kubernetes/harness.py b/kubernetes-runtime/saw_kubernetes/harness.py index eadc2a73d..56bdfdd41 100644 --- a/kubernetes-runtime/saw_kubernetes/harness.py +++ b/kubernetes-runtime/saw_kubernetes/harness.py @@ -32,17 +32,28 @@ def binding_for(sandbox, bundles): return {"name": bundle.name, "digest": bundle.digest} +def tool_rules(bundle): + """The enrolled bundle's own tool rules, for the gate policy and the allowlist.""" + if bundle is None: + return [] + return shared.harness_tool_rules(shared.describe_harness_tree(bundle_tree(bundle), inline=True)) + + def configure(command, driver, bundle, workspace, sandbox, catalog): """Add only the approved RO tree and retain the existing signed tool gate.""" info = shared.describe_harness_tree(bundle_tree(bundle), inline=True) attached = {p.type for p in workspace.providers if p.enabled and p.name in sandbox.providers} - shared.check_harness_governance(workspace, sandbox, info, catalog, attached) + if catalog is not None: # None: checked later against the gateway's profiles + shared.check_harness_governance(workspace, sandbox, info, catalog, attached) config = shared.openclaw_harness_config(info) ids = shared.harness_plugin_ids(info) if any(not re.fullmatch(r"[a-zA-Z0-9_-]+", name) or name == "saw-tool-gate" for name in ids): raise shared.InstallerError("invalid or reserved harness plugin ID") policy = yaml.safe_load((Path(shared.__file__).parent / "tool-actions.yaml").read_text()) tools = {r["tool"] for r in policy["rules"] if r["action"] in ("allow", "approval")} + # The bundle's own tools, unless the base policy already decides them (as in the gate). + named = {r["tool"] for r in policy["rules"]} + tools |= {r["tool"] for r in shared.harness_tool_rules(info) if r["tool"] not in named} discovery = {"tool_search", "tool_call"} mcp_tools = sorted(t for t in tools if t in discovery or t.partition("__")[0] in info["mcpServers"]) spec = {"trustEnv": shared.MCP_TRUST_ENV, "tools": mcp_tools, "digest": bundle.digest, "paths": config.get("plugins.load.paths", []), diff --git a/kubernetes-runtime/saw_kubernetes/portal_contract.py b/kubernetes-runtime/saw_kubernetes/portal_contract.py index 76dbf3f8e..8f54163ab 100644 --- a/kubernetes-runtime/saw_kubernetes/portal_contract.py +++ b/kubernetes-runtime/saw_kubernetes/portal_contract.py @@ -9,7 +9,6 @@ import ipaddress import json import re -import ssl from .boundary import BoundaryError, fingerprint, objects @@ -25,19 +24,6 @@ def contract(config, get): # Cluster installation is shared across registrations. Keep both UID and hash. output[key]={"uid":obj["metadata"]["uid"],"sha256":fingerprint(value)} continue - if key=="publicCA": - source=get(f"/api/v1/namespaces/{trusted}/configmaps/{config['gateway']}-proxy-ca") - if obj.get("metadata",{}).get("labels",{}).get("saw.redhat.com/runtime-owner")!=owner or set(value)!={"ca.crt"} or value!=source.get("data") or source["metadata"].get("deletionTimestamp"): - raise BoundaryError("UntrustedProxyCA") - cert=value["ca.crt"] - if not re.fullmatch(r"-----BEGIN CERTIFICATE-----\s+[A-Za-z0-9+/=\s]+-----END CERTIFICATE-----\s*",cert): - raise BoundaryError("InvalidProxyCA") - try: - ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT).load_verify_locations(cadata=cert) - except (ssl.SSLError,ValueError) as exc: - raise BoundaryError("InvalidProxyCA") from exc - output[key]="equals independent trusted proxy public CA" - continue if key=="gatewayService": ips=value.get("clusterIPs") if (value.get("type")!="ClusterIP" or not isinstance(ips,list) or not ips or value.get("clusterIP")!=ips[0] diff --git a/kubernetes-runtime/saw_kubernetes/prepare_gate.py b/kubernetes-runtime/saw_kubernetes/prepare_gate.py index 5d382c89c..f57566bc7 100644 --- a/kubernetes-runtime/saw_kubernetes/prepare_gate.py +++ b/kubernetes-runtime/saw_kubernetes/prepare_gate.py @@ -28,9 +28,9 @@ def verify(directory, files, model_selector=False, browser=False): raise ValueError("existing gate differs from the requested policy or owner") -def publish(root, identity, receipt_key=None, *, model=None, generation=None, browser=False): +def publish(root, identity, receipt_key=None, *, model=None, generation=None, browser=False, harness_rules=()): assets = Path(shared.__file__).parent - files, _, digest, _ = shared.tool_gate_bundle(assets, identity, receipt_key) + files, _, digest, _ = shared.tool_gate_bundle(assets, identity, receipt_key, harness_rules) target = root / "bundle" publish_tree(root, target, files, model_selector=model is not None, browser=browser) if model is not None: @@ -66,6 +66,7 @@ def publish_harness(root, bom, name, expected_digest): if not bundle or bundle.name != name or bundle.digest != expected_digest: raise ValueError("mounted BOM does not match enrolled harness") publish_tree(root, root / ("harness-" + bundle.digest.removeprefix("sha256:")), bundle_tree(bundle)) + return bundle def publish_model(root, target, model, generation): @@ -132,9 +133,11 @@ def publish_browser_proof(directory, proof): from .receipt import receipt_key args.receipt_key = receipt_key(args.writer_service, args.writer_namespace, args.writer_ca) os.umask(0o022) + rules = [] if args.harness: - publish_harness(Path("/volume"), Path("/bom"), *args.harness) - result = publish(Path("/volume"), shared.tool_gate_identity(args.owner, args.subject, args.workspace, args.sandbox), args.receipt_key, model=args.model, generation=args.model_generation, browser=bool(args.browser_proof)) + from .harness import tool_rules + rules = tool_rules(publish_harness(Path("/volume"), Path("/bom"), *args.harness)) + result = publish(Path("/volume"), shared.tool_gate_identity(args.owner, args.subject, args.workspace, args.sandbox), args.receipt_key, model=args.model, generation=args.model_generation, browser=bool(args.browser_proof), harness_rules=rules) if args.browser_proof: publish_browser_proof(Path("/volume/bundle"), Path(args.browser_proof).read_bytes()) print(result) diff --git a/kubernetes-runtime/saw_kubernetes/provider.py b/kubernetes-runtime/saw_kubernetes/provider.py index c917691b6..7c8680d91 100644 --- a/kubernetes-runtime/saw_kubernetes/provider.py +++ b/kubernetes-runtime/saw_kubernetes/provider.py @@ -1,4 +1,12 @@ -"""Verify Kubernetes proxy bindings against the same shipped governance profiles as the VM.""" +"""Provider helpers for configuring the agent. + +OpenShell owns provider security: profiles decide which endpoints a credential +may reach, and the supervisor substitutes the real value only for those. This +module tells the agent which environment variable holds its inference key, +checks the site's custom inference URL, and names the endpoints each +credentialed provider's profile must list (approved_endpoints), which the +reconciler compares with the live profile. +""" import re import ipaddress from functools import lru_cache @@ -10,18 +18,16 @@ from .core import shared PROFILES = Path(shared.__file__).resolve().parents[1] / "provider-profiles" -SUPPORTED = {"openai", "anthropic", "nvidia", "slack", "gmail", "brave"} +INFERENCE = {"openai", "anthropic", "nvidia"} -@lru_cache(maxsize=5) -def document(kind): - if kind not in SUPPORTED: - raise ValueError("unsupported governed provider") +@lru_cache(maxsize=4) +def _shipped(kind): return yaml.safe_load((PROFILES / (kind + ".yaml")).read_text()) def custom_host(url): - """The namespace credential broker intercepts only HTTPS on port 443.""" + """Custom inference must be an HTTPS v1 endpoint on port 443 with a DNS name.""" if not isinstance(url, str) or shared.check_base_url(url) != url: raise ValueError("invalid custom inference base URL") parsed = urlsplit(url) @@ -31,7 +37,7 @@ def custom_host(url): except ValueError: pass else: - raise ValueError("credential broker requires a DNS hostname") + raise ValueError("custom inference requires a DNS hostname") label = r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?" if (parsed.scheme != "https" or parsed.port not in (None, 443) or len(hostname) > 253 or not re.fullmatch(rf"{label}(?:\.{label})+", hostname) @@ -40,62 +46,26 @@ def custom_host(url): return parsed.hostname -def requirements(kind, custom_url=None): - if kind == "custom-inference" and custom_url: - return {"name":"api_key", "env_vars":["CUSTOM_INFERENCE_API_KEY"]}, [custom_host(custom_url)] - doc = document(kind) - slot, = doc["credentials"] - hosts = sorted({e["host"] for e in doc["endpoints"]}) - return slot, hosts - +def inference_key_env(kind): + """The env var the agent reads its inference key from (an OpenShell placeholder).""" + if kind == "custom-inference": + return "CUSTOM_INFERENCE_API_KEY" + if kind not in INFERENCE: + raise ValueError("not an inference provider") + slot, = _shipped(kind)["credentials"] + return slot["env_vars"][0] -def checked_marker(provider, bindings, custom_url=None): - """The plan carries only the public routing marker; keys remain in the proxy.""" - slot, _ = requirements(provider.type, custom_url) - expected = {"secret": provider.credential_secret, "key": provider.credential_secret_key, - "type": provider.type, "refresh": bool(provider.refresh_strategy)} - if (expected not in bindings or provider.credentials_spec or provider.base_url or provider.base_url_secret_key - or provider.refresh_strategy not in ("", "oauth2_refresh_token") or provider.inference_timeout - or (provider.type != "nvidia" and (provider.model or provider.nemoclaw_provider)) - or provider.model_secret_key): - raise ValueError("provider configuration differs from enrolled proxy binding") - if expected["refresh"] and (slot.get("refresh") or {}).get("strategy") != provider.refresh_strategy: - raise ValueError("provider refresh is not supported by its governance profile") - if not re.fullmatch(r"[a-z0-9-]+", expected["secret"]) or not re.fullmatch(r"[a-zA-Z0-9_-]+", expected["key"]): - raise ValueError("invalid proxy marker reference") - return {slot["env_vars"][0]: shared.credential_marker("saw-cred", expected["secret"], expected["key"])} +def approved_endpoints(kind, custom_url=None): + """The (host, port) pairs a credentialed provider's key may be sent to. -def check_policy(kind, credentials, policy, custom_url=None): - slot, hosts = requirements(kind, custom_url) + Stock providers: the governed profile shipped with this runtime (the same + files as the governance policy). Custom inference: only the site's + approved URL host, so one workspace's key never reaches another's server. + """ if kind == "custom-inference": - # Same contract as the VM: the trusted Secret's url supplies the marker - # host. No static profile may add hosts, even under another binding. - return (policy.get("markerPrefix") == "saw-cred" - and not policy["profiles"].get(kind) - and policy["allowHosts"] == hosts - and len(policy["bindings"]) == 1 - and any(b.get("providers") == [kind] and b.get("key") == "api_key" - and not b.get("refresh") and credentials == {slot["env_vars"][0]: - shared.credential_marker("saw-cred", b["secret"], b["key"])} for b in policy["bindings"])) - - if (policy.get("markerPrefix") != "saw-cred" or sorted(policy["profiles"].get(kind, [])) != hosts or - not set(hosts) <= set(policy["allowHosts"])): - return False - for binding in policy["bindings"]: - if kind not in binding["providers"]: - continue - if set(binding["providers"]) - ({kind, "build"} if kind=="nvidia" else {kind}): - continue - marker = shared.credential_marker("saw-cred", binding["secret"], binding["key"]) - if credentials != {slot["env_vars"][0]: marker}: - continue - refresh = binding.get("refresh") - if refresh: - contract = slot.get("refresh", {}) - if (refresh.get("strategy") != contract.get("strategy") or - refresh.get("tokenURL") != contract.get("token_url") or - refresh.get("material") != {"clientID":"client_id", "clientSecret":"client_secret", "refreshToken":"refresh_token"}): - return False - return True - return False + return {(custom_host(custom_url), 443)} + path = PROFILES / (kind + ".yaml") + if not re.fullmatch(r"[a-z0-9-]+", kind or "") or not path.is_file(): + raise ValueError("no governed profile ships for this provider type") + return {(e["host"], int(e.get("port", 443))) for e in _shipped(kind).get("endpoints", [])} diff --git a/kubernetes-runtime/saw_kubernetes/reconcile.py b/kubernetes-runtime/saw_kubernetes/reconcile.py index 04bcbd073..b48fc206e 100644 --- a/kubernetes-runtime/saw_kubernetes/reconcile.py +++ b/kubernetes-runtime/saw_kubernetes/reconcile.py @@ -15,8 +15,8 @@ import tempfile from types import SimpleNamespace -from .core import shared from . import provider as governed +from .core import shared from .compiler import ContractError, MANAGED, OWNER, REVISION, SOURCE_REVISION, digest, request_id @@ -102,8 +102,12 @@ class Reconciler: providing a no-op in a deployment is not qualification. """ - def __init__(self, rpc, state_directory, verify_resources, *, verify_shutdown=None): + def __init__(self, rpc, state_directory, verify_resources, *, verify_shutdown=None, read_credential=None): self.rpc = rpc + # read_credential(secret, key) -> (value, revision) from the trusted + # namespace; called only when a value is handed to OpenShell. + self.read_credential = read_credential + self.credential_env = {} self.store = StateStore(state_directory) if not callable(verify_resources): raise ContractError("resource verifier is required", safe_reason="InvalidPlan") @@ -124,10 +128,13 @@ def _get(self, method, request, field): raise ContractError("gateway returned an invalid object", safe_reason="GatewayMismatch") return response[field] - def _mutate(self, method, request, plan, generation): + def _mutate(self, method, request, plan, generation, identity=None): body = copy.deepcopy(request) + # `identity` replaces a request that carries a credential value, so the + # idempotency key never depends on the secret itself. body["request_id"] = request_id(plan["ownerID"], method, - {"request": request, "generation": generation}) + {"request": request if identity is None else identity, + "generation": generation}) try: return self.rpc.call(method, body) except RpcError as exc: @@ -194,6 +201,11 @@ def reconcile(self, plan, *, generation, desired_state="Running"): if state and state.get("identity") != identity: raise ContractError("workspace identity, owner and deployment mode are immutable", safe_reason="IdentityConflict") + if state.get("pendingProxyProviders") or state.get("proxyProviderRevisions"): + # Providers created through the removed credential proxy cannot + # be adopted: their revisions and credentials are not ours. + raise ContractError("workspace was enrolled with the SAW credential proxy; " + "start a new generation to re-enroll it", safe_reason="ReenrollRequired") previous = state.get("intent", {}) intent = {"generation": generation, "revision": plan["revision"], "desiredState": desired_state} if previous.get("generation", 0) > generation or (previous.get("generation") == generation and previous != intent): @@ -238,19 +250,18 @@ def _pass(self, plan, state, generation, desired_state): # Resolve platform scope explicitly (workspace_scope omitted). A # workspace administrator's same-name custom profile is not enough. profile = self.rpc.call("GetProviderProfile", {"id": provider_type}).get("profile", {}) - marker_provider = any(p.get("credentials") for w in plan["workspaces"] for p in w["providers"] - if p["type"] == provider_type) - if marker_provider: + credentialed = any(p.get("credentialRef") for w in plan["workspaces"] for p in w["providers"] + if p["type"] == provider_type) + if credentialed: + # OpenShell attaches this credential only to the profile's + # endpoints, so those must be exactly the approved ones. slots = profile.get("credentials", []) - endpoints = profile.get("endpoints", []) - slot, hosts = governed.requirements(provider_type, plan.get("customInferenceURL")) - if (profile.get("id") != provider_type - or profile.get("source") != "interceptor/governance" or len(slots) != 1 - or slots[0].get("env_vars") != slot["env_vars"] or slots[0].get("name") != slot["name"] - or sorted(e.get("host") for e in endpoints) != hosts - or any(e.get("port") != 443 or e.get("enforcement") != "NETWORK_ENFORCEMENT_MODE_ENFORCE" for e in endpoints)): - raise ContractError("provider profile differs from the approved inference boundary", + if (profile.get("id") != provider_type or len(slots) != 1 + or not slots[0].get("env_vars")): + raise ContractError("provider profile must declare exactly one credential", safe_reason="ProviderProfileMismatch") + self._verify_profile_endpoints(plan, provider_type, profile) + self.credential_env[provider_type] = slots[0]["env_vars"][0] continue if (profile.get("id") != provider_type or profile.get("credentials") or not profile.get("source", "").startswith("interceptor/")): @@ -270,6 +281,25 @@ def _pass(self, plan, state, generation, desired_state): ("GenericReady" if desired_state == "Running" else "Stopped"), pending=pending, retry_after_seconds=5 if pending else 0) + @staticmethod + def _verify_profile_endpoints(plan, provider_type, profile): + """A credentialed profile may list only the approved endpoints, all enforced.""" + try: + approved = governed.approved_endpoints(provider_type, plan.get("customInferenceURL")) + except (ValueError, TypeError): + approved = None + live = set() + for endpoint in profile.get("endpoints", []): + if (endpoint.get("enforcement") != "NETWORK_ENFORCEMENT_MODE_ENFORCE" + or endpoint.get("allowed_ips") or not endpoint.get("host")): + approved = None + break + for port in endpoint.get("ports") or [endpoint.get("port", 443)]: + live.add((endpoint["host"], int(port))) + if not approved or live != approved: + raise ContractError("provider profile endpoints differ from the approved ones", + safe_reason="ProviderProfileMismatch") + def _stop_pass(self, plan, state, generation): """Only stop previously observed IDs; never create or repair dependencies. @@ -357,34 +387,48 @@ def _apply_provider(self, ws, provider, plan, state, generation, pending): scope = {"workspace_scope": {"workspace": ws["name"]}} pname = provider["metadata"]["name"] reference = f"{ws['name']}/{pname}" + ref = provider.get("credentialRef") + refresh = provider.get("refresh") + # Only OpenShell Provider fields go to the gateway; it rejects unknown ones. + request = {k: v for k, v in provider.items() if k not in ("credentialRef", "refresh")} + source = None + if ref: + if not callable(self.read_credential): + raise ContractError("no credential source configured", safe_reason="ProviderRejected") + if refresh: + # The Secret holds only refresh material; OpenShell mints the + # access token, so the provider starts without a value and the + # material's Secret revision is the source. + _, source = self.read_credential(ref["secret"], refresh["material"][0]) + else: + value, source = self.read_credential(ref["secret"], ref["key"]) + request["credentials"] = {self.credential_env[provider["type"]]: value} + # What we record and key requests on: the plan entry (a reference, never + # the value) plus the Secret revision the value came from. + identity = {"provider": provider, "source": source} existing = self._get("GetProvider", {**scope, "name": pname}, "provider") # Persist intent before the RPC: a committed create can outlive the # connection (or this process). The pinned gateway durably replays the # same caller/request ID/payload and checks the recorded object revision. # A subsequent GetProvider, even with our labels, is not a create receipt. - creations = state.setdefault("pendingProxyProviders", {}) + creations = state.setdefault("pendingProviders", {}) intent = creations.get(reference) if intent is not None and (not isinstance(intent, dict) - or intent.get("request") != digest(provider) + or intent.get("request") != digest(identity) or type(intent.get("generation")) is not int or intent["generation"] < 1): raise ContractError("pending provider creation changed; explicit recovery is required", safe_reason="ProviderRejected") + revisions = state.setdefault("providerRevisions", {}) if existing is None or intent is not None: - if provider.get("credentials") and intent is None: - intent = {"request": digest(provider), "generation": generation} + if ref and intent is None: + intent = {"request": digest(identity), "generation": generation} creations[reference] = intent self.store.save(state) - reply = self._mutate("CreateProvider", {**scope, "provider": provider}, plan, - intent["generation"] if intent else generation) - if provider.get("credentials") and reply: - created = reply.get("provider", {}) - self._identity("provider", ws["name"], pname, created, plan, state) - meta = created["metadata"] - version = meta.get("resource_version") - if not version: - raise ContractError("missing provider revision", safe_reason="ProviderRejected") - state.setdefault("proxyProviderRevisions", {})[reference] = { - "version": version, "request": digest(provider)} + reply = self._mutate("CreateProvider", {**scope, "provider": request}, plan, + intent["generation"] if intent else generation, + identity=identity if ref else None) + if ref and reply: + self._record_provider(ws, pname, reply, plan, state, identity) creations.pop(reference, None) self.store.save(state) elif existing is not None: @@ -395,18 +439,126 @@ def _apply_provider(self, ws, provider, plan, state, generation, pending): return False self._identity("provider", ws["name"], pname, existing, plan, state) expected_credentials = {} - if provider.get("credentials"): - recorded = state.get("proxyProviderRevisions", {}).get(f"{ws['name']}/{pname}") - if recorded != {"version": existing["metadata"].get("resource_version"), "request": digest(provider)}: - raise ContractError("proxy provider ownership or credential revision requires explicit recovery", + updates = state.setdefault("pendingProviderUpdates", {}) + update = updates.get(reference) + if ref and update is not None: + # A credential update was sent but its reply was lost. If the + # provider moved on from the version we updated, that update (or + # its replay) applied: record it, as long as the provider still has + # exactly our credential slot. Otherwise it is resent below. + current = existing["metadata"].get("resource_version") + if current != update.get("from"): + if (existing.get("type") != provider["type"] or existing.get("config") + or existing.get("credentials", {}) != dict.fromkeys(request.get("credentials", {}), "REDACTED") + or update.get("provider") != digest(provider)): + raise ContractError("provider changed during a credential update; explicit recovery is required", + safe_reason="ProviderRejected") + revisions[reference] = {"version": current, "provider": digest(provider), + "source": update.get("source")} + updates.pop(reference) + self.store.save(state) + if ref: + recorded = revisions.get(reference, {}) + # OpenShell rewrites a refreshed provider (each minted token bumps + # its version), so only a static credential pins the version. + if (recorded.get("provider") != digest(provider) + or (not refresh and recorded.get("version") != existing["metadata"].get("resource_version"))): + raise ContractError("provider ownership or credential revision requires explicit recovery", safe_reason="ProviderRejected") - expected_credentials = dict.fromkeys(provider["credentials"], "REDACTED") + if recorded.get("source") != source and not refresh: + # The Secret rotated: hand OpenShell the new value. Persist the + # intent first, as for creates; a lost reply is resolved above. + updates[reference] = {"provider": digest(provider), "source": source, + "from": existing["metadata"].get("resource_version")} + self.store.save(state) + reply = self._mutate("UpdateProvider", {**scope, "provider": request}, plan, generation, + identity=identity) + if reply: + self._record_provider(ws, pname, reply, plan, state, identity) + updates.pop(reference, None) + self.store.save(state) + pending.append(f"provider/{reference}") + return False + if refresh: + if not self._apply_refresh(ws, provider, plan, state, generation, source, pending): + return False + # Either nothing yet or the one token OpenShell minted. + minted = {self.credential_env[provider["type"]]: "REDACTED"} + expected_credentials = minted if existing.get("credentials") else {} + else: + expected_credentials = dict.fromkeys(request["credentials"], "REDACTED") if (existing.get("type") != provider["type"] or existing.get("config") or existing.get("profile_workspace") - or existing.get("credentials", {}) != expected_credentials or existing.get("credential_handles")): + or existing.get("credentials", {}) != expected_credentials): raise ContractError("provider drift or unexpected credential state requires explicit recovery", safe_reason="ProviderRejected") return True + def _apply_refresh(self, ws, provider, plan, state, generation, source, pending): + """Hand OpenShell the refresh material once per Secret revision. + + OpenShell then refreshes the access token itself and keeps any rotated + refresh token; re-sending the Secret's original one would undo that. + A revision counts as configured only once the gateway's refresh status + shows the credential without an error. Until then a missing status + entry is pending, and a configure whose reply was lost is sent again + (same request ID, so the gateway replays rather than repeats it). + """ + scope = {"workspace_scope": {"workspace": ws["name"]}} + pname = provider["metadata"]["name"] + reference = f"{ws['name']}/{pname}" + key = self.credential_env[provider["type"]] + configured = state.setdefault("refreshConfigured", {}) + sent = state.setdefault("refreshSent", {}) + if configured.get(reference) != source: + attempt = sent.get(reference) or {} + if attempt.get("source") != source or not attempt.get("acknowledged"): + ref, refresh = provider["credentialRef"], provider["refresh"] + material = {} + for name in refresh["material"]: + value, revision = self.read_credential(ref["secret"], name) + if revision != source: + pending.append(f"provider/{reference}") + return False # the Secret changed while reading; next pass + material[name] = value + request = {**scope, "provider": pname, "credential_key": key, + "strategy": "PROVIDER_CREDENTIAL_REFRESH_STRATEGY_" + refresh["strategy"].upper(), + "material": material, "secret_material_keys": sorted(material)} + identity = {"refresh": provider, "source": source} + configure = self._mutate("ConfigureProviderRefresh", request, plan, generation, identity=identity) + rotate = self._mutate("RotateProviderCredential", + {**scope, "provider": pname, "credential_key": key}, + plan, generation, identity=identity) + sent[reference] = {"source": source, "acknowledged": bool(configure and rotate)} + self.store.save(state) + pending.append(f"provider/{reference}") + return False + status = self.rpc.call("GetProviderRefreshStatus", {**scope, "provider": pname, "credential_key": key}) + entries = [c for c in status.get("credentials", []) if c.get("credential_key") == key] + if any(c.get("last_error") or c.get("failure_code") for c in entries): + raise ContractError("provider credential refresh is failing; see the gateway's refresh status", + safe_reason="ProviderRefreshFailed") + if not entries: + if configured.get(reference) == source: + # It was working and the gateway no longer has it: refreshing stopped. + raise ContractError("provider credential refresh is no longer configured at the gateway", + safe_reason="ProviderRefreshFailed") + pending.append(f"provider/{reference}") # status not populated yet + return False + if configured.get(reference) != source: + configured[reference] = source + sent.pop(reference, None) + self.store.save(state) + return True + + def _record_provider(self, ws, pname, reply, plan, state, identity): + created = reply.get("provider", {}) + self._identity("provider", ws["name"], pname, created, plan, state) + version = created.get("metadata", {}).get("resource_version") + if not version: + raise ContractError("missing provider revision", safe_reason="ProviderRejected") + state.setdefault("providerRevisions", {})[f"{ws['name']}/{pname}"] = { + "version": version, "provider": digest(identity["provider"]), "source": identity["source"]} + def _apply_sandbox(self, ws, sandbox, plan, state, generation, desired_state, pending): scope = {"workspace_scope": {"workspace": ws["name"]}} sname = sandbox["name"] diff --git a/kubernetes-runtime/saw_kubernetes/serve.py b/kubernetes-runtime/saw_kubernetes/serve.py index 2e6e562b9..91f166be5 100644 --- a/kubernetes-runtime/saw_kubernetes/serve.py +++ b/kubernetes-runtime/saw_kubernetes/serve.py @@ -1,4 +1,5 @@ """Run one retained controller for an administrator-defined workspace.""" +import base64 import json import os from pathlib import Path @@ -37,6 +38,17 @@ def read(kind, name, namespace=None): def boundary(plan): verify(config, plan, get) + + allowed = set(config.get("credentialSecrets", [])) + def read_credential(secret, key): + """A provider credential for OpenShell, from this workspace's own Secrets only.""" + if secret not in allowed or not NAME.fullmatch(secret): + raise ContractError("credential outside controller scope") + obj = get(f"/api/v1/namespaces/{config['trustedNamespace']}/secrets/{secret}") + data = obj.get("data") or {} + if key not in data: + raise ContractError("credential is not available yet", safe_reason="ProviderRejected") + return base64.b64decode(data[key]).decode(), obj["metadata"]["resourceVersion"] resources = KubernetesResourceVerifier(read, boundary) endpoint = f"https://{config['gateway']}-gateway.{scope.namespace}.svc:17670" public_ca = read_public_ca(config["trustedNamespace"], config["gateway"], scope.owner_id, get) @@ -45,11 +57,35 @@ def boundary(plan): os.environ["POD_NAME"], os.environ["POD_UID"]) sessions = GatewaySessions(trust, endpoint) state = Path("/state") + catalog = {} + + def list_profiles(gateway): + """Platform provider profiles the gateway serves: type -> endpoint hosts.""" + profiles, token = {}, "" + while True: + page = gateway.call("ListProviderProfiles", {"page_size": 1000, "page_token": token}) + for profile in page.get("profiles", []): + profiles[profile["id"]] = [e["host"] for e in profile.get("endpoints", [])] + token = page.get("next_page_token", "") + if not token: + return profiles + def reconcile(plan, **kwargs): with sessions.open() as gateway: + # Refresh the catalog in the session we already hold: every session + # mints a client identity the gateway must first trust, so a second + # session per cycle keeps losing that race. + catalog["profiles"] = list_profiles(gateway) return Reconciler(gateway, state / "core", resources.verify_attachments, - verify_shutdown=resources.verify_shutdown).reconcile(plan, **kwargs) - frontend = Controller(api, scope, state, compile_profile_files, reconcile, boundary) + verify_shutdown=resources.verify_shutdown, + read_credential=read_credential).reconcile(plan, **kwargs) + + def compile_files(files, bindings): + if "profiles" not in catalog: # first cycle only + with sessions.open() as gateway: + catalog["profiles"] = list_profiles(gateway) + return compile_profile_files(files, bindings, catalog["profiles"]) + frontend = Controller(api, scope, state, compile_files, reconcile, boundary) stopped = False def stop(signum, frame): nonlocal stopped diff --git a/overrides/container-network.yaml b/overrides/container-network.yaml new file mode 100644 index 000000000..501f69414 --- /dev/null +++ b/overrides/container-network.yaml @@ -0,0 +1,235 @@ +containerDefaults: + stack: + gateway: + values: + oidc: + issuerUrl: https://openshell-keycloak-ingress-saw-keycloak.apps.vvkp4siy.westus.aroapp.io/realms/openshell + kubernetes: + network: + gatewayEgress: + - to: + - ipBlock: + cidr: 10.0.0.10/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.0.7/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.0.9/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 172.30.0.1/32 + ports: + - protocol: TCP + port: 443 + - to: + - ipBlock: + cidr: 172.30.0.10/32 + ports: + - protocol: TCP + port: 53 + - protocol: UDP + port: 53 + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: openshift-dns + podSelector: + matchLabels: + dns.operator.openshift.io/daemonset-dns: default + ports: + - protocol: TCP + port: 5353 + - protocol: UDP + port: 5353 + - to: + - ipBlock: + cidr: 52.234.29.158/32 + ports: + - protocol: TCP + port: 443 + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: openshift-ingress + podSelector: + matchLabels: + ingresscontroller.operator.openshift.io/deployment-ingresscontroller: default + ports: + - protocol: TCP + port: https + storage: + className: managed-csi + identity: + values: + network: + bootstrapEgress: + - to: + - ipBlock: + cidr: 10.0.0.10/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.0.7/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.0.9/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 172.30.0.1/32 + ports: + - protocol: TCP + port: 443 + - to: + - ipBlock: + cidr: 172.30.0.10/32 + ports: + - protocol: TCP + port: 53 + - protocol: UDP + port: 53 + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: openshift-dns + podSelector: + matchLabels: + dns.operator.openshift.io/daemonset-dns: default + ports: + - protocol: TCP + port: 5353 + - protocol: UDP + port: 5353 + audit: + values: + storageClass: managed-csi + exchangeStorageClass: azurefile-csi + automaticEnrollment: + relay: + issuer: https://openshell-keycloak-ingress-saw-keycloak.apps.vvkp4siy.westus.aroapp.io/realms/openshell + egress: + - to: + - ipBlock: + cidr: 10.0.0.10/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.0.7/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.0.9/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 172.30.0.1/32 + ports: + - protocol: TCP + port: 443 + - to: + - ipBlock: + cidr: 172.30.0.10/32 + ports: + - protocol: TCP + port: 53 + - protocol: UDP + port: 53 + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: openshift-dns + podSelector: + matchLabels: + dns.operator.openshift.io/daemonset-dns: default + ports: + - protocol: TCP + port: 5353 + - protocol: UDP + port: 5353 + - to: + - ipBlock: + cidr: 52.234.29.158/32 + ports: + - protocol: TCP + port: 443 + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: openshift-ingress + podSelector: + matchLabels: + ingresscontroller.operator.openshift.io/deployment-ingresscontroller: default + ports: + - protocol: TCP + port: https +projection: + egress: + - to: + - ipBlock: + cidr: 10.0.0.10/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.0.7/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.0.9/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 172.30.0.1/32 + ports: + - protocol: TCP + port: 443 + - to: + - ipBlock: + cidr: 172.30.0.10/32 + ports: + - protocol: TCP + port: 53 + - protocol: UDP + port: 53 + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: openshift-dns + podSelector: + matchLabels: + dns.operator.openshift.io/daemonset-dns: default + ports: + - protocol: TCP + port: 5353 + - protocol: UDP + port: 5353 + applicationSetControllerLabels: + app.kubernetes.io/name: vp-gitops-applicationset-controller diff --git a/overrides/governance-profiles/custom-inference.yaml b/overrides/governance-profiles/custom-inference.yaml index 08bcbf272..a941b95b8 100644 --- a/overrides/governance-profiles/custom-inference.yaml +++ b/overrides/governance-profiles/custom-inference.yaml @@ -18,7 +18,7 @@ credentials: discovery: credentials: [api_key] endpoints: - - host: api.inference.example.com # the host of the `url` in the inference Secret + - host: api.enmaas.devshift.net # TEMPORARY (vvkp4siy test): restore api.inference.example.com before merge port: 443 # its port (443 for https without one, 8000 for a vLLM Service) protocol: rest enforcement: enforce diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml new file mode 100644 index 000000000..8817457bd --- /dev/null +++ b/overrides/saw-container-defaults.yaml @@ -0,0 +1,40 @@ +# Cluster-wide settings for container and Kata workspaces, set once by the +# platform admin; saw-users and the portal (openshell-rhdh) both read it. Users +# only add an entry to overrides/saw-users.yaml; per-user changes go under +# containerSites.. Everything else a site needs is a default in +# charts/saw-portal-container (siteDefaults). +# +# `make container-topology` writes this cluster's API, DNS and Keycloak egress, +# issuer URLs and storage classes to overrides/container-network.yaml. Commit +# it on your fork and list it after /overrides/saw-users.yaml in saw-users' +# extraValueFiles. +projection: + enabled: true + +containerDefaults: + # OpenClaw with /sandbox searchable by OpenShift namespace UIDs, published by + # .github/workflows/build-openclaw-image.yml. Pin the src-<12 hex> tag that + # matches the BOM's source image (for now the amd64 build of 896d1526ee29). + # Disconnected clusters can build it in-cluster (make container-notebook-image). + profileImageOverrides: + data-science: + notebook: "ghcr.io/sauagarwa/saw-openclaw@sha256:05f17f3872f864e44231fb3cea30cd4dd2ba9887b382a67b261f068a234b79a2" + custom-inference: + notebook: "ghcr.io/sauagarwa/saw-openclaw@sha256:05f17f3872f864e44231fb3cea30cd4dd2ba9887b382a67b261f068a234b79a2" + automaticEnrollment: + # Enrollment stays off until an operator reviews a workspace's boundary; + # then set enabled: true, the reviewed reference and approvedProfiles + # digest under containerSites..automaticEnrollment, and pin chart + # revisions to commit SHAs (docs/container-installation.md). Demo clusters + # list overrides/saw-container-demo.yaml after this file instead. + enabled: false + autoApprove: false + # The saw-kubernetes-runtime image, pinned by digest and pullable + # anonymously from inside the cluster (make saw-init checks this). + # For now an amd64 build of this branch (tag fe412b28ed73-amd64), until + # .github/workflows/build-kubernetes-runtime.yml publishes it from main. + image: ghcr.io/sauagarwa/saw-kubernetes-runtime@sha256:86ab0fca61a1728952b036240653e9167cb677d7a7cb0e7d43f7378de425f923 + buildNamespace: saw-component-builds + relay: + keycloakNamespace: saw-keycloak + keycloakProvisionerSecret: saw-relay-provisioner diff --git a/overrides/saw-container-demo.yaml b/overrides/saw-container-demo.yaml new file mode 100644 index 000000000..d53d5eeeb --- /dev/null +++ b/overrides/saw-container-demo.yaml @@ -0,0 +1,20 @@ +# Development and demo clusters only. Never list this file in production +# values: it skips the operator boundary review. +# +# List it after /overrides/saw-container-defaults.yaml in the saw-users and +# openshell-rhdh extraValueFiles. Enrollment then publishes the first boundary +# and BOM it observes instead of comparing them with a reviewed reference and +# approvedProfiles digest, the portal offers Container and every catalog +# profile, and chart revisions may follow the pattern's branch. Later boundary +# changes still fail closed; start a new generation to re-enroll. A user can +# opt back into review with +# containerSites..automaticEnrollment.autoApprove: false. +containerDefaults: + automaticEnrollment: + enabled: true + autoApprove: true + +# The self-service portal offers Container next to VM; any Keycloak user may +# request it, and their site is containerDefaults. +portal: + deploymentModes: [vm, container, kata] diff --git a/overrides/saw-users.yaml b/overrides/saw-users.yaml index 03b297a07..6fed5d7da 100644 --- a/overrides/saw-users.yaml +++ b/overrides/saw-users.yaml @@ -1,6 +1,31 @@ # Add real account names here after creating them with keycloak-add-users. # Each entry creates saw-. Demo entries are in saw-users-demo.yaml. -users: [] +# +# Container workspaces: set the mode, the Keycloak subject +# (make keycloak-user-info KC_USER=) and the credential base path. +# Credentials are read from /saw-//inference. +# Bump generation to start over with a fresh workspace. +# - name: alice +# ownerSubject: +# profiles: [custom-inference] +# vaultPrefix: secret/data/hub +# customInferenceURL: https:///v1 # custom-inference only +# modelInputs: +# inference.model: +# values: +# deployment: {mode: container} +#users: [] +users: + - name: alice + generation: 2 # registration d2565216ccf6a6c0 + ownerSubject: 73f456ac-0377-48a6-8fa8-40a1f94fe291 + profiles: [custom-inference] + vaultPrefix: secret/data/hub # saw-users appends saw-alice/d2565216ccf6a6c0 + customInferenceURL: https://api.enmaas.devshift.net/v1 + modelInputs: + inference.model: rits/zai-org/glm-5-3 + values: + deployment: {mode: container} # Opt in only for users of a configured custom-inference endpoint. Match # the hostname in overrides/governance-profiles/custom-inference.yaml. diff --git a/scripts/ci/deployment_validation.py b/scripts/ci/deployment_validation.py index 4d7f83ecf..193b63f5e 100644 --- a/scripts/ci/deployment_validation.py +++ b/scripts/ci/deployment_validation.py @@ -33,7 +33,7 @@ } CONTAINER_CHILD_CHARTS = { "openshell-saw-kubernetes", "saw-audit-writer", "saw-kubernetes-identity", - "saw-kubernetes-proxy", "saw-runtime-policies", + "saw-runtime-policies", } CONTAINER_APIS = ( "agents.x-k8s.io/v1beta1/Sandbox", diff --git a/scripts/container-workspace.py b/scripts/container-workspace.py index 36e876024..bc4dfba9a 100644 --- a/scripts/container-workspace.py +++ b/scripts/container-workspace.py @@ -7,6 +7,7 @@ """ import argparse import copy +import hashlib import importlib.util import json import os @@ -17,6 +18,7 @@ import sys import tempfile import time +import uuid from urllib.request import HTTPRedirectHandler, build_opener import yaml @@ -64,6 +66,48 @@ def get(kind, name, namespace=None): return json.loads(raw) if raw.strip() else None +def deep_merge(base, over): + out = copy.deepcopy(base) + for key, value in over.items(): + out[key] = deep_merge(out[key], value) if isinstance(value, dict) and isinstance(out.get(key), dict) \ + else copy.deepcopy(value) + return out + + +def apply_container_defaults(config, user): + """Same defaults as saw-users.containerUser in charts/saw-users/templates/_helpers.tpl.""" + name = user["name"] + if not user.get("registration"): + user["registration"] = hashlib.sha256(f"{name}:{user.get('generation') or 1}".encode()).hexdigest()[:16] + base = (user.get("vaultPrefix") or config.get("defaults", {}).get("vaultPrefix") or "secret/data/hub").rstrip("/") + if not re.search(f"/saw-{re.escape(name)}/{re.escape(str(user['registration']))}$", base): + base = f"{base}/saw-{name}/{user['registration']}" + user["vaultPrefix"] = base + user.setdefault("pruneOnRemove", True) + user.setdefault("intentGeneration", 1) + if not user.get("installationID") and re.fullmatch(r"[a-f0-9]{16}", str(user["registration"])): + user["installationID"] = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:saw:portal:{name}:{user['registration']}")) + + +def container_site(config, user): + """Same layering as saw-users.containerSite: containerDefaults under containerSites..""" + site = deep_merge(config.get("containerDefaults") or {}, config.get("containerSites", {}).get(user["name"]) or {}) + if site and not site.get("subject"): + site["subject"] = user.get("ownerSubject") + return site + + +def resolve_subject(name): + """The enabled Keycloak account's subject, as `make keycloak-user-info` prints it.""" + try: + subject = subprocess.run([str(Path(__file__).with_name("keycloak-users.sh")), "resolve-subject", name], + capture_output=True, text=True, timeout=90, check=True).stdout.strip() + except (OSError, subprocess.SubprocessError): + raise InstallError(f"set ownerSubject for {name}, or create the Keycloak account first " + f"(make keycloak-add-user KC_USER={name})") from None + return subject + + def select(values, name): """The operator supplies the same public saw-users/site configuration as GitOps.""" if not isinstance(values, dict): @@ -82,12 +126,15 @@ def select(values, name): if mode not in {"container", "kata"} or mode != os.environ.get("DEPLOYMENT_MODE", "container"): raise InstallError("the selected user must explicitly select the requested Kubernetes deployment mode") config["ownerResolution"] = {**config.get("ownerResolution", {}), "enabled": False} + if not user.get("ownerSubject"): + user["ownerSubject"] = resolve_subject(name) + apply_container_defaults(config, user) for field, pattern in [("registration", r"[a-f0-9]{16}"), ("installationID", r"[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}"), ("ownerSubject", r"[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}")]: if not re.fullmatch(pattern, str(user.get(field, ""))): raise InstallError("container inputs require a valid "+field) - site = config.get("containerSites", {}).get(name) + site = container_site(config, user) if not site or site.get("subject") != user["ownerSubject"] or user.get("pruneOnRemove") is not True: raise InstallError("container inputs require the matching site identity and foreground cleanup") if type(user.get("intentGeneration")) is not int or user["intentGeneration"] < 1: diff --git a/scripts/container_topology.py b/scripts/container_topology.py index 7fd342686..d86baa7b7 100644 --- a/scripts/container_topology.py +++ b/scripts/container_topology.py @@ -16,10 +16,28 @@ SCRIPTS = Path(__file__).resolve().parent DNS_LABEL = re.compile(r"[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?") GATEWAY = ("stack", "gateway", "values") -BOOTSTRAP = ("stack", "proxy", "values", "network", "bootstrapEgress") +BOOTSTRAP = ("stack", "identity", "values", "network", "bootstrapEgress") RELAY = ("automaticEnrollment", "relay") +class PlainDumper(yaml.SafeDumper): + """Write shared rules out in full: reviewers read the overlay, not anchors.""" + def ignore_aliases(self, data): + return True + + +def dump(data, stream=None): + return yaml.dump(data, stream, Dumper=PlainDumper, sort_keys=False) +AUDIT = ("stack", "audit", "values") +GATEWAY_STORAGE = GATEWAY + ("kubernetes", "storage", "className") +# CSI provisioners that serve ReadWriteMany filesystems. +SHARED_FILESYSTEM_PROVISIONERS = ( + "openshift-storage.cephfs.csi.ceph.com", "cephfs.csi.ceph.com", "nfs.csi.k8s.io", + "efs.csi.aws.com", "file.csi.azure.com", "filestore.csi.storage.gke.io", + "csi.trident.netapp.io", "spectrumscale.csi.ibm.com", "k8s-sigs.io/nfs-subdir-external-provisioner") +# Keep in sync with SHARED in scripts/shared-storage.sh. + + def command(*args): result = subprocess.run(args, capture_output=True, text=True, timeout=90) if result.returncode: @@ -93,6 +111,97 @@ def discover_issuer(issuer, probe, container): return [host_rule(ip, port) for ip in sorted(set(answers), key=ipaddress.IPv4Address)] +def load_balancer_backends(rules): + """Rules for the pods behind a LoadBalancer Service whose external IP the + issuer resolves to (the OpenShift router on Azure, for example). + + OVN-Kubernetes sends pod traffic for a LoadBalancer Service's external IP + straight to the Service's pods before network policy is checked, so an + ipBlock rule for that IP never matches. Allow those pods, on the Service's + target port, as well.""" + wanted = {} + for rule in rules: + cidr = rule["to"][0].get("ipBlock", {}).get("cidr", "") + if cidr.endswith("/32"): + wanted.setdefault(cidr[:-3], set()).update(p["port"] for p in rule["ports"]) + if not wanted: + return [] + services = json.loads(command("oc", "get", "service", "-A", "-o", "json")).get("items", []) + out = [] + for svc in services: + spec, meta = svc.get("spec") or {}, svc.get("metadata") or {} + if spec.get("type") != "LoadBalancer": + continue + ingress = ((svc.get("status") or {}).get("loadBalancer") or {}).get("ingress") or [] + ports = set() + for entry in ingress: + ports |= wanted.get(entry.get("ip"), set()) + if not ports: + continue + namespace, selector = meta.get("namespace", ""), spec.get("selector") + if (not DNS_LABEL.fullmatch(namespace) or not isinstance(selector, dict) or not selector + or not all(isinstance(k, str) and isinstance(v, str) for k, v in selector.items())): + raise ValueError("the issuer's LoadBalancer Service has no usable namespace or pod selector") + for port in spec.get("ports") or []: + if port.get("port") in ports and port.get("protocol", "TCP") == "TCP": + target = port.get("targetPort", port["port"]) + rule = {"to": [{"namespaceSelector": {"matchLabels": {"kubernetes.io/metadata.name": namespace}}, + "podSelector": {"matchLabels": dict(sorted(selector.items()))}}], + "ports": [{"protocol": "TCP", "port": target}]} + if rule not in out: + out.append(rule) + return out + + +def appset_controller_labels(values): + """Pod labels of the GitOps ApplicationSet controller the projector serves.""" + namespace = (path_value(values, ("global", "vpArgoNamespace")) + or path_value(values, ("argo", "namespace")) or "vp-gitops") + if not isinstance(namespace, str) or not DNS_LABEL.fullmatch(namespace): + raise ValueError("invalid Argo CD namespace") + # Operator-managed instances label the pod app.kubernetes.io/name=-applicationset-controller; + # some also set app.kubernetes.io/component=applicationset-controller. + pods = json.loads(command("oc", "get", "pods", "-n", namespace, "-o", "json")) + names = set() + for pod in pods.get("items", []): + meta = pod.get("metadata", {}) + labels = meta.get("labels", {}) + name = labels.get("app.kubernetes.io/name", "") + if not meta.get("deletionTimestamp") and (name.endswith("-applicationset-controller") or + labels.get("app.kubernetes.io/component") == "applicationset-controller"): + names.add(name) + if len(names) != 1 or not DNS_LABEL.fullmatch(next(iter(names))): + raise ValueError(f"expected one ApplicationSet controller in {namespace}; " + "set projection.applicationSetControllerLabels in the base file") + return {"app.kubernetes.io/name": names.pop()} + + +def storage_classes(): + """The cluster's default class (RWO volumes) and a shared-filesystem class (RWX).""" + items = json.loads(command("oc", "get", "storageclass", "-o", "json")).get("items", []) + def is_default(item): + notes = item.get("metadata", {}).get("annotations", {}) + return "true" in (notes.get("storageclass.kubernetes.io/is-default-class"), + notes.get("storageclass.beta.kubernetes.io/is-default-class")) + defaults = sorted(i["metadata"]["name"] for i in items if is_default(i)) + shared = sorted((not is_default(i), i["metadata"]["name"]) for i in items + if i.get("provisioner") in SHARED_FILESYSTEM_PROVISIONERS) + return (defaults[0] if len(defaults) == 1 else None), (shared[0][1] if shared else None) + + +def storage_overlay(site, out, discover): + """Fill only storage classes the base leaves empty; explicit choices win.""" + wanted = [(GATEWAY_STORAGE, 0), (AUDIT + ("storageClass",), 0), (AUDIT + ("exchangeStorageClass",), 1)] + for path, kind in wanted: + if path_value(site, path): + continue + name = discover()[kind] + if not name: + raise ValueError("no " + ("default" if kind == 0 else "shared-filesystem (ReadWriteMany)") + + " storage class found; set " + ".".join(path) + " in the base file") + put(out, path, name) + + def container_overlay(values, probe, container=None): topology = json.loads(command(sys.executable, str(SCRIPTS / "network-topology.py"), "print-json")) api = topology["cleanupApi"] @@ -125,13 +234,24 @@ def container_overlay(values, probe, container=None): raise ValueError("clusterDomain differs from the current cluster ingress domain") overlay = {} checked = {} + found = [] + def discover(): + if not found: + found.append(storage_classes()) + return found[0] for scope in [(), ("portal",)]: sites = path_value(values, scope + ("containerSites",), {}) if not isinstance(sites, dict): raise ValueError("containerSites must be a mapping") - for owner, site in sites.items(): - if not isinstance(site, dict) or not path_value(site, GATEWAY) or not path_value(site, RELAY): - raise ValueError("expected gateway and automatic enrollment relay site inputs") + # saw-users' shared containerDefaults get the same generated rules as a site. + entries = [(scope + ("containerSites", owner), site) for owner, site in sites.items() + if not (scope == () and path_value(values, ("containerDefaults",)) and not + (path_value(site, GATEWAY) and path_value(site, RELAY)))] + if not scope and path_value(values, ("containerDefaults",)): + entries.insert(0, (("containerDefaults",), path_value(values, ("containerDefaults",)))) + for target, site in entries: + if not isinstance(site, dict): + raise ValueError("expected a container site mapping") raw = [path_value(site, GATEWAY + ("oidc", "issuerUrl")), path_value(site, RELAY + ("issuer",))] issuers = {v.replace("@DOMAIN@", domain[5:]) for v in raw if isinstance(v, str) and v} if len(issuers) > 1 or any(v is not None and not isinstance(v, str) for v in raw): @@ -139,22 +259,28 @@ def container_overlay(values, probe, container=None): if issuers: issuer = issuers.pop() else: - namespace = path_value(site, RELAY + ("keycloakNamespace",)) + # The saw-portal-container default unless the site names one. + namespace = path_value(site, RELAY + ("keycloakNamespace",), "saw-keycloak") if not isinstance(namespace, str) or not DNS_LABEL.fullmatch(namespace): raise ValueError("expected relay Keycloak namespace") host = command(str(SCRIPTS / "keycloak-host.sh"), namespace) issuer = f"https://{host}/realms/{os.environ.get('KEYCLOAK_REALM', 'openshell')}" if issuer not in checked: - checked[issuer] = discover_issuer(issuer, probe, container) + rules = discover_issuer(issuer, probe, container) + checked[issuer] = rules + load_balancer_backends(rules) out = {} for path in [GATEWAY + ("oidc", "issuerUrl"), RELAY + ("issuer",)]: put(out, path, issuer) for path in [GATEWAY + ("kubernetes", "network", "gatewayEgress"), RELAY + ("egress",)]: put(out, path, egress(site, path, common + checked[issuer])) put(out, BOOTSTRAP, egress(site, BOOTSTRAP, common)) - put(overlay, scope + ("containerSites", owner), out) - if not scope and sites: + storage_overlay(site, out, discover) + put(overlay, target, out) + if not scope and entries: put(overlay, ("projection", "egress"), egress(values, ("projection", "egress"), common)) + # An operator-chosen selector in the base file wins; Helm merges maps. + if not path_value(values, ("projection", "applicationSetControllerLabels")): + put(overlay, ("projection", "applicationSetControllerLabels"), appset_controller_labels(values)) if not overlay: raise ValueError("no containerSites in site values") return overlay @@ -179,7 +305,7 @@ def install_values(config, owner, overlay_file, probe, container, verify): raise ValueError("review the generated topology overlay before enabling enrollment") # Link a complete file without overwriting another concurrent install's review. with tempfile.NamedTemporaryFile(dir=path_on_disk.parent, mode="w") as tmp: - yaml.safe_dump(expected, tmp, sort_keys=False) + dump(expected, tmp) tmp.flush() try: os.link(tmp.name, path_on_disk) @@ -215,7 +341,7 @@ def main(): if yaml.safe_load(args.check.read_text()) != found: raise ValueError("container topology drift; regenerate the overlay from the base file and review the diff") else: - sys.stdout.write(yaml.safe_dump(found, sort_keys=False)) + sys.stdout.write(dump(found)) except yaml.YAMLError: p.exit(1, "Container topology check failed: invalid YAML input\n") except (ValueError, OSError, KeyError, TypeError, subprocess.SubprocessError) as exc: diff --git a/scripts/keycloak-users.sh b/scripts/keycloak-users.sh index fc3e8503a..af9e5200b 100755 --- a/scripts/keycloak-users.sh +++ b/scripts/keycloak-users.sh @@ -10,6 +10,8 @@ # Secret; --show prints the value (never printed otherwise). # reset-password USER Give USER a new generated password in the Secret. # resolve-subject USER Return the exact enabled user's Keycloak subject. +# user-info USER Show USER's subject (ownerSubject), enabled flag and +# email, or say why there is no usable account. # show List users that have stored passwords. # ensure Create or complete Secret $SECRET: a generated # password per test user in the chart's values (the @@ -333,6 +335,41 @@ resolve_subject() { printf '%s\n' "${subject}" } +user_info() { + local user="${1:-}" response count + [[ "${user}" =~ ^[a-z0-9][-a-z0-9]*$ ]] || { + echo "usage: $0 user-info USER (a plain Keycloak username)" >&2 + return 2 + } + admin_login + response="$(api_get "/users?exact=true&username=${user}")" + count="$(jq -r 'if type == "array" then length else -1 end' <<<"${response}" 2>/dev/null || echo -1)" + if [[ "${count}" == -1 ]]; then + echo "Error: Keycloak user lookup failed in realm ${REALM} (namespace ${NS})." >&2 + return 1 + fi + if [[ "${count}" == 0 ]]; then + echo "${user} is not in realm ${REALM} (namespace ${NS})." >&2 + echo "Create it with: make keycloak-add-user KC_USER=${user}" >&2 + echo "or set KEYCLOAK_REALM / KEYCLOAK_NS if it lives elsewhere." >&2 + return 1 + fi + jq -r --arg realm "${REALM}" '.[] | + "realm: \($realm)", + "username: \(.username)", + "subject: \(.id)", + "enabled: \(.enabled)", + "email: \(.email // "-")", + "name: \([.firstName, .lastName] | map(select(. != null)) | join(" ") | if . == "" then "-" else . end)", + ""' <<<"${response}" + if [[ "${count}" == 1 ]] && [[ "$(jq -r '.[0].enabled' <<<"${response}")" == true ]]; then + echo "ownerSubject: $(jq -r '.[0].id' <<<"${response}")" + else + echo "Warning: no single enabled account; resolve-subject and container registration will refuse it." >&2 + return 1 + fi +} + set_password() { # user id, password, temporary (true|false) api_code PUT "/users/$1/reset-password" \ "$(jq -n --arg pw "$2" --argjson t "$3" '{type: "password", value: $pw, temporary: $t}')" @@ -502,5 +539,6 @@ case "${1:-}" in password) password "${@:2}" ;; reset-password) reset_password "${2:-}" ;; resolve-subject) resolve_subject "${2:-}" ;; - *) echo "usage: $0 add-users [FILE]|password USER|reset-password USER|show|ensure|harden|session-max" >&2; exit 2 ;; + user-info) user_info "${2:-}" ;; + *) echo "usage: $0 add-users [FILE]|password USER|reset-password USER|resolve-subject USER|user-info USER|show|ensure|harden|session-max" >&2; exit 2 ;; esac diff --git a/scripts/portal-container/setup-relay-provisioner.py b/scripts/portal-container/setup-relay-provisioner.py deleted file mode 100644 index 9517e6b75..000000000 --- a/scripts/portal-container/setup-relay-provisioner.py +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env python3 -"""Render or run the one-time, platform-owned Keycloak relay registrar setup.""" -import argparse -import base64 -import json -import os -from pathlib import Path -import secrets -import ssl -import sys -from urllib.error import HTTPError -from urllib.parse import urlencode, urlsplit -from urllib.request import build_opener, HTTPRedirectHandler, HTTPSHandler, Request - -NAME = "saw-relay-provisioner" -SCOPE = "saw-workspace-relay" -IMAGE = "registry.access.redhat.com/ubi9/python-311@sha256:a0bdb55576fc5b8d6704279307817828ef027e1065533ceba133fe9516003a6c" - - -class NoRedirect(HTTPRedirectHandler): - def redirect_request(self, *args): - return None - - -def call(url, method="GET", *, token=None, body=None, form=None, ca=None, patch=False): - headers = {} - data = None - if form is not None: - headers["Content-Type"] = "application/x-www-form-urlencoded" - data = urlencode(form).encode() - if body is not None: - headers["Content-Type"] = "application/merge-patch+json" if patch else "application/json" - data = json.dumps(body).encode() - if token: - headers["Authorization"] = "Bearer " + token - client = build_opener(NoRedirect(), HTTPSHandler(context=ssl.create_default_context(cafile=ca))) - with client.open(Request(url, data=data, method=method, headers=headers), timeout=20) as response: - raw = response.read() - return json.loads(raw) if raw else None - - -def setup(): - issuer = os.environ["ISSUER"].rstrip("/") - base, realm = issuer.rsplit("/realms/", 1) - if urlsplit(issuer).scheme != "https" or not realm or realm == "master": - raise ValueError("expected a dedicated HTTPS realm") - admin = Path("/bootstrap") - token = call(base + "/realms/master/protocol/openid-connect/token", "POST", - form={"client_id":"admin-cli", "grant_type":"password", - "username":(admin/"username").read_text().strip(), - "password":(admin/"password").read_text().strip()})["access_token"] - def kc(path, method="GET", body=None): - return call(base + "/admin/realms/" + realm + path, method, token=token, body=body) - - sa = Path("/var/run/secrets/kubernetes.io/serviceaccount") - secret_url = ("https://kubernetes.default.svc/api/v1/namespaces/" + os.environ["NAMESPACE"] - + "/secrets/" + NAME) - opts = dict(ca=str(sa/"ca.crt"), token=(sa/"token").read_text().strip()) - state = call(secret_url, **opts) - if state["metadata"]["labels"].get("saw.redhat.com/component") != NAME: - raise ValueError("unexpected destination Secret") - if not state.get("data"): - state = call(secret_url, "PATCH", patch=True, **opts, body={ - "metadata":{"resourceVersion":state["metadata"]["resourceVersion"]}, - "stringData":{"client-id":NAME, "client-secret":secrets.token_urlsafe(40), "issuer":issuer}}) - values = {k:base64.b64decode(v,validate=True).decode() for k,v in state["data"].items()} - if set(values) != {"issuer","client-id","client-secret"} or values["issuer"] != issuer or values["client-id"] != NAME: - raise ValueError("incompatible provisioner Secret") - audience = os.environ["AUDIENCE"] - mappers = [ - {"name":"relay-audience", "protocol":"openid-connect", "protocolMapper":"oidc-audience-mapper", - "config":{"included.client.audience":audience, "access.token.claim":"true"}}, - {"name":"relay-user", "protocol":"openid-connect", "protocolMapper":"oidc-hardcoded-claim-mapper", - "config":{"claim.name":"realm_access.roles","claim.value":'["openshell-user"]', - "jsonType.label":"JSON","access.token.claim":"true"}}] - scopes = {s["name"]:s for s in kc("/client-scopes")} - if SCOPE not in scopes: - kc("/client-scopes","POST",{"name":SCOPE, "protocol":"openid-connect", - "description":"SAW registration-scoped workspace relay", "protocolMappers":mappers}) - scope = next(s for s in kc("/client-scopes") if s["name"]==SCOPE) - actual = kc("/client-scopes/"+scope["id"]+"/protocol-mappers/models") - if {m["name"] for m in actual} != {m["name"] for m in mappers}: - raise ValueError("unexpected relay scope mappers") - for desired in mappers: - found=next(m for m in actual if m["name"]==desired["name"]) - if found["protocolMapper"]!=desired["protocolMapper"] or any(found["config"].get(k)!=v for k,v in desired["config"].items()): - raise ValueError("foreign relay scope configuration") - # Add this specific pre-approved scope to authenticated DCR. Never allow - # clients to author their own role or audience mappers. - policies=kc("/components?"+urlencode({"type":"org.keycloak.services.clientregistration.policy.ClientRegistrationPolicy"})) - allowed=[p for p in policies if p.get("providerId")=="allowed-client-templates" and p.get("subType")=="authenticated"] - if len(allowed)!=1: - raise ValueError("expected one authenticated client-scope registration policy") - policy=allowed[0] - config=policy.setdefault("config",{}) - permitted=config.setdefault("allowed-client-scopes",[]) - if SCOPE not in permitted: - permitted.append(SCOPE) - kc("/components/"+policy["id"],"PUT",policy) - - def lookup(client_id): - return next((c for c in kc("/clients?"+urlencode({"clientId":client_id})) if c["clientId"]==client_id), None) - settings=dict(clientId=NAME, enabled=True, protocol="openid-connect", publicClient=False, - serviceAccountsEnabled=True,standardFlowEnabled=False,implicitFlowEnabled=False, - directAccessGrantsEnabled=False,fullScopeAllowed=False) - if not lookup(NAME): - kc("/clients","POST",{**settings,"secret":values["client-secret"],"attributes":{"saw.component":NAME}, - "defaultClientScopes":["basic","roles"],"optionalClientScopes":[]}) - client=kc("/clients/"+lookup(NAME)["id"]) - if client.get("attributes",{}).get("saw.component")!=NAME or any(client.get(k)!=v for k,v in settings.items()): - raise ValueError("refusing to adopt a foreign provisioning client") - prefix="/clients/"+client["id"] - management=lookup("realm-management")["id"] - role=kc("/clients/"+management+"/roles/create-client") - user=kc(prefix+"/service-account-user")["id"] - for path in [prefix+"/scope-mappings/clients/"+management, - "/users/"+user+"/role-mappings/clients/"+management]: - current=kc(path) - if {r["name"] for r in current} - {"create-client"}: - raise ValueError("provisioner has unexpected realm-management privileges") - if not current: - kc(path,"POST",[role]) - result=call(issuer+"/protocol/openid-connect/token","POST",form={ - "client_id":NAME,"client_secret":values["client-secret"],"grant_type":"client_credentials"}) - part=result["access_token"].split(".")[1] - claim=json.loads(base64.urlsafe_b64decode(part+"="*(-len(part)%4))) - if set(claim.get("resource_access",{}).get("realm-management",{}).get("roles",[]))!={"create-client"}: - raise ValueError("unexpected effective registrar privilege") - print("Realm registrar verified: create-client in the workspace realm.") - - -def render(args): - ns=args.namespace - metadata={"name":NAME,"namespace":ns} - subject={"kind":"ServiceAccount","name":NAME,"namespace":ns} - objects=[ - {"apiVersion":"v1","kind":"Secret","metadata":{**metadata,"labels":{"saw.redhat.com/component":NAME}},"type":"Opaque"}, - {"apiVersion":"v1","kind":"ServiceAccount","metadata":metadata}, - {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"Role","metadata":metadata,"rules":[ - {"apiGroups":[""],"resources":["secrets"],"verbs":["get","patch"],"resourceNames":[NAME]}]}, - {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"RoleBinding","metadata":metadata,"subjects":[subject], - "roleRef":{"apiGroup":"rbac.authorization.k8s.io","kind":"Role","name":NAME}}, - {"apiVersion":"v1","kind":"ConfigMap","metadata":metadata,"data":{"setup.py":Path(__file__).read_text()}}] - volumes=[{"name":"script","configMap":{"name":NAME}},{"name":"bootstrap","secret":{ - "secretName":args.bootstrap_secret,"items":[{"key":k,"path":k} for k in ("username","password")]}}] - mounts=[{"name":v["name"],"mountPath":"/"+v["name"],"readOnly":True} for v in volumes] - env={"ISSUER":args.issuer,"NAMESPACE":ns,"AUDIENCE":args.audience} - if args.ca_configmap: - volumes.append({"name":"trust","configMap":{"name":args.ca_configmap}}) - mounts.append({"name":"trust","mountPath":"/trust","readOnly":True}) - env["SSL_CERT_FILE"]="/trust/ca-bundle.crt" - objects.append({"apiVersion":"batch/v1","kind":"Job","metadata":metadata,"spec":{ - "activeDeadlineSeconds":180,"backoffLimit":1,"ttlSecondsAfterFinished":900, - "template":{"spec":{"serviceAccountName":NAME,"restartPolicy":"Never","volumes":volumes, - "securityContext":{"runAsNonRoot":True,"seccompProfile":{"type":"RuntimeDefault"}}, - "containers":[{"name":"setup","image":IMAGE,"command":["python3","/script/setup.py","run"], - "volumeMounts":mounts,"env":[{"name":k,"value":v} for k,v in env.items()], - "securityContext":{"readOnlyRootFilesystem":True,"allowPrivilegeEscalation":False,"capabilities":{"drop":["ALL"]}}}]}}}}) - print(json.dumps({"apiVersion":"v1","kind":"List","items":objects})) - - -if __name__=="__main__": - if sys.argv[1:]==["run"]: - try: - setup() - except HTTPError as exc: - sys.exit(f"Setup API failed: HTTP {exc.code} at {urlsplit(exc.url).path}") - else: - parser=argparse.ArgumentParser(description=__doc__) - for flag in ("namespace","issuer","bootstrap-secret"): - parser.add_argument("--"+flag,required=True) - parser.add_argument("--audience",default="openshell-cli") - parser.add_argument("--ca-configmap") - render(parser.parse_args()) diff --git a/scripts/saw-init.sh b/scripts/saw-init.sh new file mode 100755 index 000000000..8c0cd40d5 --- /dev/null +++ b/scripts/saw-init.sh @@ -0,0 +1,121 @@ +#!/usr/bin/env bash +# Prepare a cluster for SAW before `./pattern.sh make install` or `make saw-create`. +# +# Runs only what the configured users need. VM-only configurations stop after +# the default StorageClass check (storage-class-check, a make prerequisite). +# When any user in the saw-users values selects deployment.mode container or +# kata, it also checks: +# - OVN-Kubernetes, AdminNetworkPolicy and ValidatingAdmissionPolicy; +# - a shared-filesystem (ReadWriteMany) StorageClass, offering to create one +# (scripts/shared-storage.sh); +# - that the runtime image in containerDefaults can be pulled anonymously +# from inside the cluster. +# Steps that need a running Keycloak (the relay registrar, the network overlay) +# come after install; see docs/container-installation.md. +# +# Env: SAW_USERS_VALUES_FILE (default overrides/saw-users.yaml), +# SAW_CONTAINER_DEFAULTS_FILE (default overrides/saw-container-defaults.yaml), +# SAW_INIT_NAMESPACE (namespace for the short-lived image check Pod, default), +# SAW_INIT_SKIP_IMAGE_CHECK=1, SAW_STORAGE_ASSUME_YES=1 (unattended). +set -euo pipefail + +script_dir="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "${script_dir}/.." && pwd)" +users_file="${SAW_USERS_VALUES_FILE:-${root}/overrides/saw-users.yaml}" +defaults_file="${SAW_CONTAINER_DEFAULTS_FILE:-${root}/overrides/saw-container-defaults.yaml}" +failed=0 + +ok() { echo " ok $*"; } +warn() { echo " warn $*" >&2; } +fail() { echo " FAIL $*" >&2; failed=1; } + +# Users and the runtime image from the same files the pattern reads. +# SAW_USERS_VALUES_FILE may name either file (make container-topology reads the +# defaults file through it), so read users and defaults from all of them. +read -r container_users image < <(python3 - "$users_file" "${root}/overrides/saw-users.yaml" "$defaults_file" <<'EOF' +import sys, yaml +names, image, seen = [], "", set() +for path in sys.argv[1:]: + if path in seen: + continue + seen.add(path) + try: + doc = yaml.safe_load(open(path)) or {} + except FileNotFoundError: + continue + for u in doc.get("users") or []: + mode = ((u.get("values") or {}).get("deployment") or {}).get("mode") + if mode in ("container", "kata") and u.get("name") not in names: + names.append(u.get("name", "?")) + image = image or ((doc.get("containerDefaults") or {}).get("automaticEnrollment") or {}).get("image", "") +print(",".join(names) or "-", image or "-") +EOF +) + +if [ "$container_users" = "-" ]; then + echo "SAW init: no container or Kata users; nothing more to prepare." + exit 0 +fi +echo "SAW init: container workspaces for ${container_users//,/, }" + +network="$(oc get network.config.openshift.io cluster -o jsonpath='{.status.networkType}' 2>/dev/null || true)" +[ "$network" = OVNKubernetes ] && ok "network: OVN-Kubernetes" \ + || fail "network type is '${network:-unknown}'; container mode needs OVN-Kubernetes" + +version="$(oc get clusterversion version -o jsonpath='{.status.desired.version}' 2>/dev/null || true)" +if [ -n "$version" ] && printf '4.22\n%s\n' "${version%%-*}" | sort -V -C; then + ok "OpenShift ${version}" +else + warn "OpenShift ${version:-unknown}; container mode is qualified on 4.22 and later" +fi + +oc get crd adminnetworkpolicies.policy.networking.k8s.io >/dev/null 2>&1 \ + && ok "AdminNetworkPolicy API" || fail "AdminNetworkPolicy API is missing (OVN-Kubernetes on OpenShift 4.14+)" +oc api-resources --api-group=admissionregistration.k8s.io -o name 2>/dev/null \ + | grep -q '^validatingadmissionpolicies' \ + && ok "ValidatingAdmissionPolicy API" || fail "ValidatingAdmissionPolicy API is missing" + +if "${script_dir}/shared-storage.sh"; then :; else failed=1; fi + +if [ "${SAW_INIT_SKIP_IMAGE_CHECK:-0}" = 1 ]; then + warn "runtime image check skipped" +elif [ "$image" = "-" ] || [[ "$image" != *@sha256:* ]]; then + fail "containerDefaults.automaticEnrollment.image must be a pinned image (…@sha256:…) in ${defaults_file#${root}/}" +else + # Anonymous registry v2 handshake from a short-lived Pod: what the nodes see + # without a pull secret for that registry. + probe='img=$1; host=${img%%/*}; rest=${img#*/}; repo=${rest%@*}; ref=${rest#*@} +url="https://$host/v2/$repo/manifests/$ref" +A="Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json" +code=$(curl -s -o /dev/null -w "%{http_code}" -H "$A" "$url") +if [ "$code" = 401 ]; then + h=$(curl -sI -H "$A" "$url" | tr -d "\r" | grep -i "^www-authenticate:") + realm=$(echo "$h" | sed -n "s/.*realm=\"\([^\"]*\)\".*/\1/p") + service=$(echo "$h" | sed -n "s/.*service=\"\([^\"]*\)\".*/\1/p") + scope=$(echo "$h" | sed -n "s/.*scope=\"\([^\"]*\)\".*/\1/p") + tok=$(curl -s "$realm?service=$service&scope=$scope" | sed -n "s/.*\"token\":\"\([^\"]*\)\".*/\1/p") + code=$(curl -s -o /dev/null -w "%{http_code}" -H "$A" -H "Authorization: Bearer $tok" "$url") +fi +echo "image-check:$code"' + result="$(oc run "saw-init-image-check-$$" -n "${SAW_INIT_NAMESPACE:-default}" --rm -i --restart=Never \ + --image=registry.access.redhat.com/ubi9/ubi-minimal --command -- sh -c "$probe" sh "$image" 2>/dev/null \ + | sed -n 's/^image-check://p' | tail -n1)" + case "$result" in + 200) ok "runtime image pullable from the cluster" ;; + 401|403) fail "runtime image is not anonymously pullable (HTTP ${result}): make the package public or add a pull secret: ${image}" ;; + 404) fail "runtime image not found: ${image}" ;; + *) warn "could not check the runtime image from inside the cluster (${result:-no result}); set SAW_INIT_SKIP_IMAGE_CHECK=1 to skip" ;; + esac +fi + +echo +if [ "$failed" != 0 ]; then + echo "SAW init: fix the items above, then run make saw-init again." >&2 + exit 1 +fi +cat <<'EOF' +SAW init: the cluster is ready for container workspaces. After install, once Keycloak is up: + - make keycloak-add-user KC_USER=; make keycloak-user-info KC_USER= (ownerSubject) + - make container-topology > overrides/container-network.yaml (network overlay; commit it on + your fork and list it after /overrides/saw-users.yaml in saw-users' extraValueFiles) +EOF diff --git a/scripts/saw-profile-catalog.py b/scripts/saw-profile-catalog.py index d6d6c7d29..789e30b61 100644 --- a/scripts/saw-profile-catalog.py +++ b/scripts/saw-profile-catalog.py @@ -570,18 +570,13 @@ def main(argv=None): for src in sorted(GOVERNANCE_PROFILES.glob("*.yaml"))} extra = [p for p in sorted(INSTALLER_PROFILES.glob("*.yaml")) if p not in mirror] lifecycle = TEMPLATE_OUTPUT.with_name("set-workspace-state.yaml") - # Independent Helm charts package the same reviewed broker renderer. - policy_template = ROOT / "charts/openshell-saw/templates/_governed-proxy-policy.tpl" policy_outputs = [ (ROOT / "charts/openshell-rhdh/files/saw_keycloak_admin.py", (ROOT / "charts/openshell-keycloak/files/saw_keycloak_admin.py").read_text()), (ROOT / "charts/saw-workspace-relay/files/saw_ui_limit.py", (ROOT / "charts/openshell-saw/files/installer/saw_ui_limit.py").read_text()), (ROOT / "charts/openshell-rhdh/files/workspace.py", - (ROOT / "charts/saw-users/files/workspace.py").read_text()), - (ROOT / "charts/saw-users/templates/_governed-proxy-policy.tpl", policy_template.read_text()), - (ROOT / "charts/saw-users/files/governed-profiles.json", json.dumps( - {p.stem: load(p) for p in sorted(GOVERNANCE_PROFILES.glob("*.yaml"))}, sort_keys=True, indent=2) + "\n")] + (ROOT / "charts/saw-users/files/workspace.py").read_text())] if args.list: # Every path this script owns: the generated files, each mirror, and # the mirror directory itself, so `git add -A -- ` (the hook, diff --git a/scripts/shared-storage.sh b/scripts/shared-storage.sh new file mode 100755 index 000000000..efee3535a --- /dev/null +++ b/scripts/shared-storage.sh @@ -0,0 +1,344 @@ +#!/usr/bin/env bash +# Ensure a shared-filesystem (ReadWriteMany) StorageClass for container workspaces. +# +# The audit exchange volume is mounted by several Pods at once, so it needs a +# ReadWriteMany class (CephFS, NFS, EFS, ...). Block classes such as EBS +# (gp3-csi) cannot serve it. This script: +# - a known shared-filesystem class exists -> continue +# - otherwise, by SAW_SHARED_STORAGE: +# unset / none -> print the options and fail (nothing is created) +# nfs -> dev/demo only, explicit opt-in: create a small in-cluster +# NFS server (privileged SCC) and provisioner (cluster-scoped +# role, StorageClass `saw-nfs`) and verify it. One Pod, no +# replication: not for production. +# efs -> on AWS with working `aws` credentials, offer to create EFS +# (filesystem, mount targets, NFS security group), the AWS +# EFS CSI Driver Operator and StorageClass `saw-efs`. EFS is +# billed per GB; it is tagged kubernetes.io/cluster/. +# For production, provide a real RWX class (ODF CephFS, EFS, vendor NFS) first; +# this script then leaves storage alone. +# +# Env: SAW_SHARED_STORAGE, SAW_EFS_STORAGECLASS (saw-efs), SAW_NFS_STORAGECLASS +# (saw-nfs), SAW_NFS_NAMESPACE (saw-nfs), SAW_NFS_SIZE (20Gi), +# SAW_STORAGE_ASSUME_YES=1 (accept the EFS prompt unattended) +set -euo pipefail + +CLASS="${SAW_EFS_STORAGECLASS:-saw-efs}" +# Keep in sync with SHARED_FILESYSTEM_PROVISIONERS in scripts/container_topology.py. +SHARED='["openshift-storage.cephfs.csi.ceph.com","cephfs.csi.ceph.com","nfs.csi.k8s.io", + "efs.csi.aws.com","file.csi.azure.com","filestore.csi.storage.gke.io","csi.trident.netapp.io", + "spectrumscale.csi.ibm.com","k8s-sigs.io/nfs-subdir-external-provisioner"]' +CSI_NS=openshift-cluster-csi-drivers + +err() { echo "$@" >&2; } +interactive() { [ -t 0 ] && [ -t 1 ]; } +ask_yes() { + [ "${SAW_STORAGE_ASSUME_YES:-0}" = 1 ] && return 0 + interactive || return 1 + local ans + read -r -p "$1 [y/N] " ans || return 1 + [[ "$ans" =~ ^[Yy]([Ee][Ss])?$ ]] +} +guidance() { + err "Container workspaces need a ReadWriteMany (shared filesystem) StorageClass." + err "Options, then run make saw-init again:" + err " - AWS: EFS with the AWS EFS CSI Driver Operator (this script automates it" + err " when 'aws sts get-caller-identity' works for the cluster's account)" + err " - OpenShift Data Foundation (CephFS: ocs-storagecluster-cephfs)" + err " - an NFS server with the NFS CSI driver (nfs.csi.k8s.io)" + err " - dev/demo only: SAW_SHARED_STORAGE=nfs make saw-init creates a small in-cluster NFS" + err " server (privileged SCC, cluster-scoped provisioner role; one Pod, no replication)" + err " - or name an existing RWX class in containerDefaults.stack.audit.values.exchangeStorageClass" + err "See docs/container-installation.md." +} + +# A Pod writes and reads through a ReadWriteMany claim of the class. +verify_rwx() { + local ns="$1" class="$2" + oc apply -n "$ns" -f - >/dev/null </dev/null 2>&1 + oc apply -n "$ns" -f - >/dev/null < /data/check && cat /data/check"] + securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, runAsNonRoot: true, seccompProfile: {type: RuntimeDefault}} + volumeMounts: [{name: data, mountPath: /data}] + volumes: [{name: data, persistentVolumeClaim: {claimName: rwx-check}}] +EOF + local phase="" + for _ in $(seq 60); do + phase="$(oc get pod rwx-check -n "$ns" -o jsonpath='{.status.phase}' 2>/dev/null)" + case "$phase" in Succeeded|Failed) break ;; esac + sleep 5 + done + if [ "$phase" = Succeeded ] && [ "$(oc logs rwx-check -n "$ns" 2>/dev/null)" = saw ]; then + echo " ok shared-filesystem StorageClass: ${class} (demo NFS, verified read/write)" + else + err " FAIL ${class} did not serve a ReadWriteMany volume (check Pod: ${phase:-not started})" + err " oc -n ${ns} get pvc,pods; oc -n ${ns} describe pod rwx-check; oc -n ${ns} logs deploy/nfs-provisioner" + exit 1 + fi + oc delete pod rwx-check -n "$ns" --wait=false >/dev/null 2>&1 || true + oc delete pvc rwx-check -n "$ns" --wait=false >/dev/null 2>&1 || true +} + +existing="$(oc get storageclass -o json | jq -r --argjson p "$SHARED" \ + '[.items[] | select(.provisioner as $x | $p | index($x))] | sort_by(.metadata.name) | .[0].metadata.name // empty')" +if [ -n "$existing" ]; then + nfs_class="${SAW_NFS_STORAGECLASS:-saw-nfs}" + if [ "$existing" = "$nfs_class" ]; then + verify_rwx "${SAW_NFS_NAMESPACE:-saw-nfs}" "$nfs_class" # our demo server: prove it still works + else + echo " ok shared-filesystem StorageClass: ${existing}" + fi + exit 0 +fi + +# SAW_SHARED_STORAGE=nfs (explicit opt-in): a small NFS server inside the cluster. +# One server Pod on a default-class (RWO) volume, exported to a dynamic +# provisioner; not replicated and a single point of failure. +setup_demo_nfs() { + local ns="${SAW_NFS_NAMESPACE:-saw-nfs}" class="${SAW_NFS_STORAGECLASS:-saw-nfs}" size="${SAW_NFS_SIZE:-20Gi}" + # Upstream Kubernetes images: the e2e NFS server (kernel nfsd, exports /exports + # as the NFSv4 root) and the sig-storage subdirectory provisioner. + local server_image="${SAW_NFS_SERVER_IMAGE:-registry.k8s.io/e2e-test-images/volume/nfs:1.4}" + local provisioner_image="${SAW_NFS_PROVISIONER_IMAGE:-registry.k8s.io/sig-storage/nfs-subdir-external-provisioner:v4.0.2}" + echo " info no shared-filesystem StorageClass: creating an in-cluster NFS server in ${ns}" + echo " (privileged Pod on a ${size} default-class volume, provisioner, StorageClass ${class})." + echo " Dev/demo only: one Pod, no replication." + + oc create namespace "$ns" --dry-run=client -o yaml | oc apply -f - >/dev/null + oc create serviceaccount nfs-server -n "$ns" --dry-run=client -o yaml | oc apply -f - >/dev/null + oc create serviceaccount nfs-provisioner -n "$ns" --dry-run=client -o yaml | oc apply -f - >/dev/null + oc adm policy add-scc-to-user privileged -z nfs-server -n "$ns" >/dev/null + # Pods with nfs volumes need an SCC that allows them. + oc adm policy add-scc-to-user hostmount-anyuid -z nfs-provisioner -n "$ns" >/dev/null + oc apply -n "$ns" -f - >/dev/null </dev/null \ + || { err " FAIL demo NFS server did not start (oc -n ${ns} describe deployment/nfs-server)"; exit 1; } + # Nodes mount NFS from the host network, which reaches the Service IP but not cluster DNS. + local server_ip + server_ip="$(oc get service nfs-server -n "$ns" -o jsonpath='{.spec.clusterIP}')" + echo " ok demo NFS server at ${server_ip}" + + oc apply -f - >/dev/null </dev/null \ + || { err " FAIL demo NFS provisioner did not start (oc -n ${ns} describe deployment/nfs-provisioner)"; exit 1; } + + verify_rwx "$ns" "$class" +} + +case "${SAW_SHARED_STORAGE:-}" in + nfs) setup_demo_nfs; exit 0 ;; + efs) ;; # below + *) err " FAIL no shared-filesystem (ReadWriteMany) StorageClass"; guidance; exit 1 ;; +esac + +infra="$(oc get infrastructure cluster -o json)" +platform="$(jq -r '.status.platformStatus.type // ""' <<<"$infra")" +if [ "$platform" != AWS ] || ! command -v aws >/dev/null || ! aws sts get-caller-identity >/dev/null 2>&1; then + err " FAIL no shared-filesystem (ReadWriteMany) StorageClass" + [ "$platform" = AWS ] && err " (AWS: install the aws CLI and log in to the cluster's account to automate EFS)" + guidance + exit 1 +fi +if [ "$(oc get cloudcredential cluster -o jsonpath='{.spec.credentialsMode}' 2>/dev/null)" = Manual ]; then + err " FAIL no shared-filesystem StorageClass; this cluster uses short-term AWS credentials (STS)," + err " which the EFS operator needs an IAM role for. Follow the OpenShift 'AWS EFS CSI Driver" + err " Operator' documentation for STS, then run make saw-init again." + exit 1 +fi + +region="$(jq -r '.status.platformStatus.aws.region' <<<"$infra")" +infra_id="$(jq -r '.status.infrastructureName' <<<"$infra")" +export AWS_REGION="$region" +err "" +err "No shared-filesystem StorageClass. On AWS this script can create, in ${region}:" +err " - an encrypted EFS filesystem saw-${infra_id} with a mount target per worker subnet," +err " - a security group allowing NFS (TCP 2049) from the cluster VPC," +err " - the AWS EFS CSI Driver Operator and StorageClass ${CLASS}." +err "EFS is billed per GB stored. It is tagged kubernetes.io/cluster/${infra_id}." +if ! ask_yes "Create it now?"; then + guidance + exit 1 +fi + +# Worker instances -> subnets and VPC. +mapfile -t instances < <(oc get nodes -l node-role.kubernetes.io/worker \ + -o jsonpath='{range .items[*]}{.spec.providerID}{"\n"}{end}' | sed 's#.*/##' | grep '^i-' | sort -u) +[ "${#instances[@]}" -gt 0 ] || { err "no AWS worker instances found"; exit 1; } +read -r -a subnets <<<"$(aws ec2 describe-instances --instance-ids "${instances[@]}" \ + --query 'Reservations[].Instances[].SubnetId' --output text | tr '\t' '\n' | sort -u | tr '\n' ' ')" +vpc="$(aws ec2 describe-instances --instance-ids "${instances[0]}" --query 'Reservations[0].Instances[0].VpcId' --output text)" +cidr="$(aws ec2 describe-vpcs --vpc-ids "$vpc" --query 'Vpcs[0].CidrBlock' --output text)" + +sg="$(aws ec2 describe-security-groups --filters "Name=vpc-id,Values=${vpc}" "Name=group-name,Values=saw-efs-${infra_id}" \ + --query 'SecurityGroups[0].GroupId' --output text)" +if [ "$sg" = None ] || [ -z "$sg" ]; then + sg="$(aws ec2 create-security-group --group-name "saw-efs-${infra_id}" --vpc-id "$vpc" \ + --description "SAW EFS: NFS from the ${infra_id} cluster VPC" \ + --tag-specifications "ResourceType=security-group,Tags=[{Key=kubernetes.io/cluster/${infra_id},Value=owned}]" \ + --query GroupId --output text)" + aws ec2 authorize-security-group-ingress --group-id "$sg" --protocol tcp --port 2049 --cidr "$cidr" >/dev/null +fi +echo " ok security group ${sg} (NFS from ${cidr})" + +fs="$(aws efs describe-file-systems --creation-token "saw-${infra_id}" --query 'FileSystems[0].FileSystemId' --output text)" +if [ "$fs" = None ] || [ -z "$fs" ]; then + fs="$(aws efs create-file-system --creation-token "saw-${infra_id}" --encrypted \ + --performance-mode generalPurpose --throughput-mode elastic \ + --tags "Key=Name,Value=saw-${infra_id}" "Key=kubernetes.io/cluster/${infra_id},Value=owned" \ + --query FileSystemId --output text)" +fi +for _ in $(seq 60); do + [ "$(aws efs describe-file-systems --file-system-id "$fs" --query 'FileSystems[0].LifeCycleState' --output text)" = available ] && break + sleep 5 +done +echo " ok EFS ${fs}" +have="$(aws efs describe-mount-targets --file-system-id "$fs" --query 'MountTargets[].SubnetId' --output text)" +for s in "${subnets[@]}"; do + [[ " $have " == *" $s "* ]] && continue + aws efs create-mount-target --file-system-id "$fs" --subnet-id "$s" --security-groups "$sg" >/dev/null \ + || err " warn mount target in ${s} not created (one per availability zone)" +done +echo " ok mount targets in ${#subnets[@]} worker subnet(s)" + +# AWS EFS CSI Driver Operator in openshift-cluster-csi-drivers. +if [ -z "$(oc get operatorgroup -n "$CSI_NS" -o name 2>/dev/null)" ]; then + oc apply -f - </dev/null +apiVersion: operators.coreos.com/v1 +kind: OperatorGroup +metadata: {name: openshift-cluster-csi-drivers, namespace: ${CSI_NS}} +spec: {upgradeStrategy: Default} +EOF +fi +oc apply -f - </dev/null +apiVersion: operators.coreos.com/v1alpha1 +kind: Subscription +metadata: {name: aws-efs-csi-driver-operator, namespace: ${CSI_NS}} +spec: {channel: stable, name: aws-efs-csi-driver-operator, source: redhat-operators, sourceNamespace: openshift-marketplace} +EOF +for _ in $(seq 60); do + oc get crd clustercsidrivers.operator.openshift.io >/dev/null 2>&1 \ + && [ "$(oc get csv -n "$CSI_NS" -o json | jq -r '[.items[] | select(.metadata.name | startswith("aws-efs-csi-driver-operator")) | .status.phase][0] // ""')" = Succeeded ] && break + sleep 10 +done +oc apply -f - </dev/null +apiVersion: operator.openshift.io/v1 +kind: ClusterCSIDriver +metadata: {name: efs.csi.aws.com} +spec: {managementState: Managed} +EOF +for _ in $(seq 60); do oc get csidriver efs.csi.aws.com >/dev/null 2>&1 && break; sleep 10; done +oc get csidriver efs.csi.aws.com >/dev/null || { err "EFS CSI driver did not become available"; exit 1; } +echo " ok AWS EFS CSI driver" +oc apply -f - </dev/null +apiVersion: storage.k8s.io/v1 +kind: StorageClass +metadata: {name: ${CLASS}} +provisioner: efs.csi.aws.com +parameters: {provisioningMode: efs-ap, fileSystemId: ${fs}, directoryPerms: "700"} +reclaimPolicy: Delete +volumeBindingMode: Immediate +EOF +echo " ok shared-filesystem StorageClass: ${CLASS} (EFS ${fs})" diff --git a/tests/charts/test_governance_interceptor_image.py b/tests/charts/test_governance_interceptor_image.py index b270c13d7..1e9b2ab43 100644 --- a/tests/charts/test_governance_interceptor_image.py +++ b/tests/charts/test_governance_interceptor_image.py @@ -222,17 +222,60 @@ def test_default_build_output_is_internal_and_push_requires_explicit_destination assert build["spec"]["output"]["to"]["name"] == "ghcr.io/example/governance-interceptor:v0.1.6" -@pytest.mark.parametrize("filename", ["build-governance-interceptor.yml", "build-kubernetes-runtime.yml"]) +@pytest.mark.parametrize("filename", ["build-governance-interceptor.yml", "build-kubernetes-runtime.yml", + "build-openclaw-image.yml"]) def test_pr_image_jobs_cannot_publish(filename): workflow = yaml.safe_load((ROOT / ".github/workflows" / filename).read_text()) assert workflow["permissions"] == {"contents": "read"} jobs = workflow["jobs"] assert "permissions" not in jobs["build"] - assert jobs["build"]["if"] == "github.event_name == 'pull_request' || github.ref != 'refs/heads/main'" + main = "github.event_name != 'pull_request' && github.ref == 'refs/heads/main'" + if "publish" in (workflow[True].get("workflow_dispatch") or {}).get("inputs", {}): + # A maintainer's manual run may publish a branch; pull_request events + # carry no dispatch inputs, so a PR still never publishes. + assert workflow[True]["workflow_dispatch"]["inputs"]["publish"]["default"] is False + assert jobs["build"]["if"] == ("github.event_name == 'pull_request' || " + "(github.ref != 'refs/heads/main' && !inputs.publish)") + publish_if = f"({main}) || inputs.publish" + else: + assert jobs["build"]["if"] == "github.event_name == 'pull_request' || github.ref != 'refs/heads/main'" + publish_if = main for job in ("publish", "merge"): - assert jobs[job]["if"] == "github.event_name != 'pull_request' && github.ref == 'refs/heads/main'" + assert jobs[job]["if"] == publish_if assert jobs[job]["permissions"] == {"contents": "read", "packages": "write"} assert jobs["merge"]["needs"] == "publish" assert jobs["build"]["steps"] == jobs["publish"]["steps"] image = next(s for s in jobs["build"]["steps"] if s.get("uses") == "./.github/actions/build-push-image") assert "github.event_name != 'pull_request' && github.ref == 'refs/heads/main'" in image["with"]["registry_token"] + + +def test_a_branch_publish_never_moves_shared_tags(): + """Manual branch publishes are addressed by commit; :latest and the + OpenShell release tag move only from main.""" + for action in ("build-push-image", "merge-image"): + text = (ROOT / ".github/actions" / action / "action.yml").read_text() + main_block = text[text.index('if [ "$REF" = refs/heads/main ]'):] + assert ":latest" in main_block and "EXTRA_TAG" in main_block + before = text[:text.index('if [ "$REF" = refs/heads/main ]')] + assert ":latest" not in before.split("tags")[-1] + + +def test_every_pinned_personal_image_has_a_publishing_workflow(): + """An image pinned from a fork owner's ghcr namespace must be rebuildable + by CI from this branch, not only from a laptop.""" + import re + pinned = set() + for path in [*(ROOT / "charts").rglob("values*.yaml"), *(ROOT / "overrides").glob("*.yaml")]: + for owner, image in re.findall(r"ghcr\.io/([a-z0-9-]+)/([a-z0-9-]+)@sha256:", path.read_text()): + # The project's own namespace publishes from main; upstream + # vendors' images are not built here. + if owner not in {"validatedpatterns-sandbox", "openclaw", "nvidia"}: + pinned.add(image) + publishable = set() + for wf in (ROOT / ".github/workflows").glob("*.yml"): + workflow = yaml.safe_load(wf.read_text()) + dispatch = (workflow.get(True) or {}).get("workflow_dispatch") or {} + if "publish" not in (dispatch.get("inputs") or {}): + continue + publishable |= set(re.findall(r"image_name: ([a-z0-9-]+)", wf.read_text())) + assert pinned <= publishable, sorted(pinned - publishable) diff --git a/tests/charts/test_openshell_keycloak_chart.py b/tests/charts/test_openshell_keycloak_chart.py index db788385c..a0984a8d7 100644 --- a/tests/charts/test_openshell_keycloak_chart.py +++ b/tests/charts/test_openshell_keycloak_chart.py @@ -358,3 +358,30 @@ def test_shared_admin_scope_helper_is_mounted_and_rolls_bootstraps(tmp_path): for name in names: dep = next(d for d in changed if d["kind"] == "Deployment" and d["metadata"]["name"] == name) assert dep["spec"]["template"]["metadata"]["annotations"]["checksum/script"] != checksums[name] + + +def test_the_relay_provisioner_is_off_unless_container_workspaces_need_it(): + assert not [d for d in render() if "relay-provisioner" in d["metadata"]["name"]] + + +def test_the_relay_provisioner_runs_as_a_self_healing_deployment(): + docs = render("--set", "relayProvisioner.enabled=true") + mine = [d for d in docs if "relay-provisioner" in d["metadata"]["name"]] + (deploy,) = [d for d in mine if d["kind"] == "Deployment"] + # The generated credential lives in a Secret Helm does not own, so a + # GitOps self-heal cannot clear it, and nothing runs against a deadline. + assert not [d for d in mine if d["kind"] == "Secret"] + assert not [d for d in mine if d["kind"] == "Job"] + spec = deploy["spec"]["template"]["spec"] + (admin,) = [v for v in spec["volumes"] if v["name"] == "admin"] + assert admin["secret"]["secretName"] == "openshell-keycloak-initial-admin" + (role,) = [d for d in mine if d["kind"] == "Role" and d["metadata"]["name"] == "saw-relay-provisioner"] + named = [r for r in role["rules"] if r.get("resourceNames")] + assert named == [{"apiGroups": [""], "resources": ["secrets"], + "resourceNames": ["saw-relay-provisioner"], "verbs": ["get", "patch"]}] + + +def test_the_pattern_enables_the_relay_provisioner(): + values = yaml.safe_load((ROOT / "values-prod.yaml").read_text()) + overrides = values["clusterGroup"]["applications"]["openshell-keycloak"]["overrides"] + assert {"name": "relayProvisioner.enabled", "value": "true"} in overrides diff --git a/tests/charts/test_openshell_saw_chart.py b/tests/charts/test_openshell_saw_chart.py index f5354222e..ef55e8d8e 100644 --- a/tests/charts/test_openshell_saw_chart.py +++ b/tests/charts/test_openshell_saw_chart.py @@ -1030,7 +1030,14 @@ def test_pattern_puts_keycloak_and_each_saw_in_their_own_namespaces(): users_app = apps["saw-users"] assert users_app["namespace"] == "openshell-agents" assert users_app["path"] == "charts/saw-users" - assert users_app["extraValueFiles"] == ["/overrides/saw-users.yaml"] + # Shared container defaults first, then the users; never the demo-only file. + assert users_app["extraValueFiles"] == ["/overrides/saw-container-defaults.yaml", + "/overrides/saw-users.yaml"] + for app in apps.values(): + assert "/overrides/saw-container-demo.yaml" not in (app or {}).get("extraValueFiles", []) + defaults = yaml.safe_load((ROOT / "overrides/saw-container-defaults.yaml").read_text()) + enrollment = defaults["containerDefaults"]["automaticEnrollment"] + assert enrollment["autoApprove"] is False and enrollment["enabled"] is False assert users_app["syncPolicy"]["automated"]["prune"] is True listed = yaml.safe_load((ROOT / "overrides/saw-users.yaml").read_text())["users"] assert listed == [] diff --git a/tests/charts/test_portal_container.py b/tests/charts/test_portal_container.py index 6ffeb3a1f..df9d759b6 100644 --- a/tests/charts/test_portal_container.py +++ b/tests/charts/test_portal_container.py @@ -1,4 +1,5 @@ """Render the same owner request through both Helm levels and the stock component charts.""" +import copy import importlib.util from pathlib import Path import json @@ -180,6 +181,26 @@ def test_gateway_api_versions_require_the_same_reviewed_identity_revision(older_ assert "apiVersions" not in helm +@pytest.mark.parametrize("auto_approve,revision,renders", [ + (False, "a" * 40, True), (False, "main", False), (True, "main", True), (True, "a" * 40, True)]) +def test_only_auto_approve_sites_may_follow_a_branch(auto_approve, revision, renders): + # The same rule as preflight.configuration_facts (the portal and installer). + site = json.loads(json.dumps(SITE)) + for item in site["stack"].values(): + item["revision"] = revision + site["automaticEnrollment"]["revision"] = revision + site["automaticEnrollment"]["relay"]["revision"] = revision + site["automaticEnrollment"]["autoApprove"] = auto_approve + values = dict(site=site, owner=U, registration=REG, installationID=user()["installationID"], + ownerSubject=SITE["subject"], vaultPrefix=user()["vaultPrefix"], **{"global": GLOBAL}) + result = subprocess.run(["helm", "template", U, str(ROOT / "charts/saw-portal-container"), "--namespace", "saw-" + U, + "--api-versions", "agents.x-k8s.io/v1beta1", "-f", "-"], + input=json.dumps(values), text=True, capture_output=True) + assert (result.returncode == 0) == renders, result.stderr + if not renders: + assert "full Git commit SHA" in result.stderr + + def test_model_gate_claim_is_shared_only_for_the_publisher_and_agent(): audit = SITE["stack"]["audit"]["values"] # Use the same per-registration Helm values projection as the nested Applications. @@ -196,40 +217,47 @@ def test_model_gate_claim_is_shared_only_for_the_publisher_and_agent(): assert claims["workspace-"+U]["accessModes"] == claims[U+"-history"]["accessModes"] == ["ReadWriteOnce"] -def test_personal_assistant_uses_the_vm_proxy_policy_and_trusted_secret_projection(): +def app_values(application): + source = application["spec"]["source"]["helm"] + return source.get("valuesObject") or yaml.safe_load(source["values"]) + + +def test_personal_assistant_credentials_are_projected_for_openshell(): owner = {**user(), "profiles":["personal-assistant"]} - site = {**SITE, "providerAllowHosts":["integrate.api.nvidia.com","slack.com","gmail.googleapis.com","oauth2.googleapis.com"]} + site = {**SITE} site["automaticEnrollment"]={**SITE["automaticEnrollment"],"approvedProfiles":{"personal-assistant":"a"*64}} parent = render("saw-users","portal-ws-"+U,"saw-portal",{"global":GLOBAL,"users":[owner],"containerSites":{U:site}}) app, = [a for a in parent if a.get("spec",{}).get("source",{}).get("path")=="charts/saw-portal-container"] - resources=child(app) - broker,=[r for r in resources if r["kind"]=="ConfigMap" and r["metadata"]["name"].endswith("-proxy-policy")] - policy=json.loads(broker["data"]["config.json"]) - bindings={b["secret"]:b for b in policy["bindings"]} + bindings = {b["secret"]: b for b in app_values(app)["site"]["credentialBindings"]} assert set(bindings)=={"gmail","slack","inference"} - assert bindings["gmail"]["refresh"]["tokenURL"]=="https://oauth2.googleapis.com/token" - assert bindings["slack"]=={"secret":"slack","key":"bot_token","providers":["slack"]} + assert bindings["gmail"]=={"secret":"gmail","key":"access_token","type":"gmail","refresh":"oauth2_refresh_token"} + assert bindings["slack"]=={"secret":"slack","key":"bot_token","type":"slack"} + resources=child(app) secrets={r["metadata"]["name"]:r for r in resources if r["kind"]=="ExternalSecret"} + # Gmail's Secret holds only the refresh material; OpenShell mints the access token. for name,keys in {"gmail":{"refresh_token","client_id","client_secret"},"slack":{"bot_token"},"inference":{"api_key"}}.items(): assert secrets[name]["metadata"]["namespace"]=="saw-ctl-"+REG assert {e["secretKey"] for e in secrets[name]["spec"]["data"]}==keys - proxy,=[r for r in resources if r["kind"]=="Application" and r["spec"]["source"]["path"]=="charts/saw-kubernetes-proxy"] - assert proxy["spec"]["source"]["helm"]["valuesObject"]["credentialSecretNames"]==sorted(secrets) - - -def test_custom_inference_projection_pins_broker_url_and_keeps_key_private(): + # Every Vault property synced is one the profile collects (what the portal writes). + catalog = json.loads((ROOT/"charts/saw-users/files/profile-catalog.json").read_text())["profiles"] + for name, spec in catalog["personal-assistant"]["secrets"].items(): + collected = {f["key"] for f in spec.get("fields", [])} + assert {e["remoteRef"]["property"] for e in secrets[name]["spec"]["data"]} <= collected, name + # No SAW credential proxy: OpenShell's supervisor injects the credentials. + assert not [r for r in resources if "proxy" in r["metadata"]["name"]] + assert not [r for r in resources if r["kind"]=="Application" + and r["spec"]["source"]["path"].endswith("saw-kubernetes-proxy")] + + +def test_custom_inference_secret_carries_the_site_url(): url="https://models.fixture.test/v1" owner={**user(),"profiles":["custom-inference"],"webSearch":{"enabled":False}} - site={**SITE,"providerAllowHosts":["models.fixture.test"],"customInferenceURL":url, + site={**SITE,"customInferenceURL":url, "automaticEnrollment":{**SITE["automaticEnrollment"],"approvedProfiles":{"custom-inference":"a"*64}}} root=render("saw-users","portal-ws-"+U,"saw-portal",{"global":GLOBAL,"users":[owner],"containerSites":{U:site}}) app,=[a for a in root if a.get("spec",{}).get("source",{}).get("path")=="charts/saw-portal-container"] - resources=child(app) - broker,=[r for r in resources if r["kind"]=="ConfigMap" and r["metadata"]["name"].endswith("-proxy-policy")] - policy=json.loads(broker["data"]["config.json"]) - assert policy["allowHosts"]==["models.fixture.test"] and not policy["profiles"].get("custom-inference") - assert policy["bindings"]==[{"providers":["custom-inference"],"key":"api_key","secret":"inference"}] - es,=[r for r in resources if r["kind"]=="ExternalSecret"] + assert app_values(app)["site"]["credentialBindings"]==[{"secret":"inference","key":"api_key","type":"custom-inference"}] + es,=[r for r in child(app) if r["kind"]=="ExternalSecret"] assert es["metadata"]["namespace"]=="saw-ctl-"+REG assert es["spec"]["target"]["template"]=={"engineVersion":"v2","mergePolicy":"Merge","data":{"url":url}} assert [e["secretKey"] for e in es["spec"]["data"]]==["api_key"] @@ -380,11 +408,49 @@ def test_foundation_can_be_reviewed_without_placeholder_approval_or_workload(): assert any(o.get("spec", {}).get("source", {}).get("path") == "charts/openshell-saw-kubernetes" for o in docs) +def pull_grant_render(image): + site = copy.deepcopy(SITE) + site["automaticEnrollment"]["image"] = image + site["enrollment"] = dict( + registration=REG, image=image, buildNamespace="builds", revision="1" * 40, + approved={}, intent={"profileRef": {"name": "saw-bom-profiles"}, "bindings": { + "ownerID": user()["installationID"], "ownerSubject": SITE["subject"], + "namespace": "saw-" + U, "namespaceUID": "fixture-uid", "mode": "container", + "bindings": {"default/notebook": { + "workspace": {"claimName": "workspace-" + U}, + "toolGate": {"trusted": {"claimName": "saw-gate-" + U}, + "audit": {"claimName": "saw-audit-" + U}, + "ownerLogin": U, "receiptKey": "fixture-public-key"}, + "browser": {"ownerLogin": U, "origin": "https://alice-default-notebook-ui.apps.cluster.example.com"}}}}}) + return render("saw-portal-container", U, "saw-" + U, dict( + site=site, owner=U, ownerSubject=SITE["subject"], registration=REG, + installationID=user()["installationID"], intentGeneration=1, + vaultPrefix=user()["vaultPrefix"], **{"global": GLOBAL})) + + +def test_gate_preparation_waits_for_the_relay_browser_proof(): + """Argo never recreates a failed Job, so preparation must outlast the + relay identity Job that projects the proof it mounts.""" + resources = pull_grant_render("ghcr.io/example/saw-kubernetes-runtime@sha256:" + "b" * 64) + jobs = [r for r in resources if r["kind"] == "Job" and r["metadata"]["name"].startswith("saw-gate-preparation")] + assert jobs and all(j["spec"]["activeDeadlineSeconds"] == 1800 for j in jobs) + + +def test_a_published_runtime_image_needs_no_build_namespace(): + """A registry image needs no ImageStream pull grant, so nothing is created + in buildNamespace (which need not exist) and the charts are told none.""" + resources = pull_grant_render("ghcr.io/example/saw-kubernetes-runtime@sha256:" + "b" * 64) + assert not [r for r in resources if r["metadata"].get("namespace") == "builds"] + for app in (r for r in resources if r["kind"] == "Application"): + values = app_values(app) + assert values.get("imageBuildNamespace", "") == "", app["metadata"]["name"] + + @pytest.mark.parametrize("stream", ["saw-kubernetes-runtime", "custom-runtime"]) def test_runtime_pull_grants_follow_the_configured_image(stream): from copy import deepcopy site = deepcopy(SITE) - image = "image-registry.example.test/builds/" + stream + "@sha256:" + "b" * 64 + image = "image-registry.openshift-image-registry.svc:5000/builds/" + stream + "@sha256:" + "b" * 64 site["automaticEnrollment"]["image"] = image site["enrollment"] = dict( registration=REG, image=image, buildNamespace="builds", revision="1" * 40, @@ -414,3 +480,21 @@ def test_removing_last_static_owner_keeps_only_empty_registration_config(): assert docs[0]["kind"] == "ConfigMap" assert docs[0]["metadata"]["name"].endswith("-configuration") assert json.loads(docs[0]["data"]["workspaces.json"]) == {"users": []} + + +def test_a_site_without_workload_settings_uses_the_driver_defaults(): + """Regression: the shipped defaults set no gateway workload block (its image + comes from the first sandbox target), so the policy's runtime image must + fall back to driverDefaults instead of failing on a nil lookup.""" + site = copy.deepcopy(SITE) + del site["stack"]["gateway"]["values"]["kubernetes"]["workload"] + image = "registry.example.test/agent@sha256:" + "c"*64 + site["targets"]["default/notebook"]["image"] = image # the projector sets it from the BOM + top = render("saw-users","portal-ws-"+U,"saw-portal",{"global":GLOBAL,"users":[user()],"containerSites":{U:site}}) + portal, = [a for a in top if a["kind"]=="Application" and a["spec"]["source"]["path"]=="charts/saw-portal-container"] + apps = [r for r in child(portal) if r["kind"]=="Application"] + defaults = yaml.safe_load((ROOT/"charts/saw-portal-container/values.yaml").read_text())["driverDefaults"] + policy, = [a for a in apps if a["metadata"]["name"].endswith("-policy")] + assert app_values(policy)["runtimeImage"] == defaults["runtimeImage"] + gateway, = [a for a in apps if a["metadata"]["name"].endswith("-gateway")] + assert app_values(gateway)["kubernetes"]["workload"]["image"] == image diff --git a/tests/charts/test_saw_kubernetes_chart.py b/tests/charts/test_saw_kubernetes_chart.py index 1d5e918fa..55a96455c 100644 --- a/tests/charts/test_saw_kubernetes_chart.py +++ b/tests/charts/test_saw_kubernetes_chart.py @@ -267,3 +267,12 @@ def test_openshell_startup_timeouts_must_be_in_supported_range(assignment): result = template('--set', assignment) assert result.returncode != 0 assert not result.stdout.strip() + + +def test_native_providers_need_no_upstream_proxy(): + docs = render('--set', 'kubernetes.proxy.url=', '--set', 'kubernetes.proxy.caConfigMap=') + driver = config(docs)['drivers']['kubernetes'] + for key in ('https_proxy', 'proxy_connect_by_hostname', 'proxy_ca_bundle'): + assert key not in driver + sts = next(v for (kind, _), v in docs.items() if kind == 'StatefulSet') + assert 'proxy-ca' not in {v['name'] for v in sts['spec']['template']['spec']['volumes']} diff --git a/tests/charts/test_saw_kubernetes_proxy_chart.py b/tests/charts/test_saw_kubernetes_proxy_chart.py deleted file mode 100644 index 178176eaa..000000000 --- a/tests/charts/test_saw_kubernetes_proxy_chart.py +++ /dev/null @@ -1,67 +0,0 @@ -import json -from pathlib import Path -import shutil -import pytest -import yaml -from helm_cache import run_helm - -ROOT = Path(__file__).resolve().parents[2] -HELM = shutil.which('helm') -pytestmark = [pytest.mark.ci_external, pytest.mark.skipif(not HELM, reason='Helm required')] - - -def render(*args, enabled=True): - return run_helm([HELM, 'template', 'proxy', str(ROOT / 'charts/saw-kubernetes-proxy'), - '-n', 'saw-test-trusted', '--set', 'enabled=' + str(enabled).lower(), - '--set', 'gateway=saw-test,targetNamespace=saw-test,ownerID=67a9891d-e281-442f-86c3-41771f5ce049', - '--set', 'policyConfigMap=approved-policy,credentialSecretNames[0]=inference', - '--set-string', 'policyDigest=' + 'a'*64, - '--set-json', 'network.bootstrapEgress=[{"to":[{"ipBlock":{"cidr":"10.0.0.1/32"}}],"ports":[{"port":443}]}]', - '--set-json', 'network.proxyEgress=[{"to":[{"ipBlock":{"cidr":"0.0.0.0/0"}}],"ports":[{"port":443}]}]', - *args], capture_output=True, text=True) - - -def test_isolation_and_retained_public_projection(): - result = render() - assert result.returncode == 0, result.stderr - docs = list(yaml.safe_load_all(result.stdout)) - assert not any(d['kind'] == 'Secret' for d in docs) - deployment = next(d for d in docs if d['kind'] == 'Deployment') - pod = deployment['spec']['template']['spec'] - assert pod['automountServiceAccountToken'] is False - assert not any(v.get('projected') for v in pod['volumes']) - assert pod['containers'][0]['args'] == ['serve'] - job = next(d for d in docs if d['kind'] == 'Job')['spec']['template']['spec'] - assert job['initContainers'][0]['args'] == ['init-ca'] - assert job['automountServiceAccountToken'] is False - for c in [*job['initContainers'], *job['containers'], *pod['containers']]: - assert '@sha256:' in c['image'] - assert c['securityContext'] == dict(allowPrivilegeEscalation=False, - readOnlyRootFilesystem=True, capabilities={'drop': ['ALL']}) - runtime = next(d for d in docs if d['kind'] == 'Role' and d['metadata']['namespace']=='saw-test') - assert all(r['resources'] == ['configmaps'] and set(r['verbs']) <= {'get','create'} for r in runtime['rules']) - trusted = next(d for d in docs if d['kind']=='Role' and d['metadata']['namespace']=='saw-test-trusted') - assert not any('update' in r['verbs'] for r in trusted['rules'] if 'secrets' in r['resources']) - assert not any(d['kind']=='RoleBinding' and d['subjects'][0]['name']=='saw-test-credential-proxy' for d in docs) - cm = next(d for d in docs if d['kind']=='ConfigMap') - assert json.loads(cm['data']['config.json'])['name']=='saw-test-proxy-ca' - assert cm['data']['project_ca.py'].rstrip()==(ROOT/'charts/saw-kubernetes-proxy/files/project_ca.py').read_text().rstrip() - np = next(d for d in docs if d['kind']=='NetworkPolicy' and d['metadata']['name']=='saw-test-credential-proxy') - peers = np['spec']['ingress'][0]['from'] - assert all(set(peer)=={'namespaceSelector','podSelector'} for peer in peers) - assert peers[1]['podSelector']['matchLabels']=={'openshell.ai/gateway-id':'saw-test','openshell.ai/boundary-role':'supervisor'} - service = next(d for d in docs if d['kind']=='Service') - assert [p['port'] for p in service['spec']['ports']]==[3128] - - -def test_opt_in(): - result=render(enabled=False) - assert result.returncode==0 and not result.stdout.strip() - - -@pytest.mark.parametrize('value', ['targetNamespace=saw-test-trusted','gateway=kube-system', - 'ownerID=00000000-0000-0000-0000-000000000000','image=repo:latest','helperImage=repo:latest', - 'policyConfigMap=','policyDigest=','credentialSecretNames[1]=inference']) -def test_fail_closed(value): - result=render('--set-string',value) - assert result.returncode != 0 and not result.stdout.strip() diff --git a/tests/charts/test_saw_runtime_policies.py b/tests/charts/test_saw_runtime_policies.py index 8b0bfa237..6b01caad7 100644 --- a/tests/charts/test_saw_runtime_policies.py +++ b/tests/charts/test_saw_runtime_policies.py @@ -257,3 +257,21 @@ def test_kata_enforces_reviewed_runtime_at_sandbox_and_pod(): assert any('object.spec.runtimeClassName == "saw-kata"' in check for check in checks) assert any("variables.role != 'supervisor' || !has(object.spec.runtimeClassName)" in check for check in checks) + + +@pytest.mark.parametrize("packet,expected", [ + ({"ip": "203.0.113.7"}, "Pass"), # a public provider API on 443 + ({"ip": "203.0.113.7", "port": 80}, "Deny"), + ({"ip": "10.20.30.40"}, "Deny"), # private ranges stay closed + ({"ip": "172.16.0.9"}, "Deny"), + ({"ip": "192.168.1.1"}, "Deny"), + ({"ip": "169.254.169.254"}, "Deny"), # cloud metadata + ({"ip": "192.0.2.10"}, "Pass"), # explicit rules still apply first +]) +def test_public_https_lets_supervisors_reach_providers_but_not_private_networks(packet, expected): + anp = render("--set", "network.publicHTTPS=true")["AdminNetworkPolicy"] + assert packet_action(anp, **packet) == expected + + +def test_public_https_is_off_by_default(): + assert packet_action(render()["AdminNetworkPolicy"], ip="203.0.113.7") == "Deny" diff --git a/tests/charts/test_saw_users_chart.py b/tests/charts/test_saw_users_chart.py index 32d18e428..6a5d5bac6 100644 --- a/tests/charts/test_saw_users_chart.py +++ b/tests/charts/test_saw_users_chart.py @@ -69,9 +69,9 @@ def helm_values(application): return yaml.safe_load(application["spec"]["source"]["helm"]["values"]) -def test_container_policy_is_derived_from_documented_hosts(tmp_path): +def test_container_credentials_are_bound_by_secret_and_type(tmp_path): site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] - del site["providerPolicy"] + site.pop("credentialBindings", None) user = { "name": "alice", "registration": "a" * 16, "installationID": "22222222-2222-4222-8222-222222222222", @@ -81,7 +81,139 @@ def test_container_policy_is_derived_from_documented_hosts(tmp_path): } docs = docs_from(render_file(tmp_path, [user], {"containerSites": {"alice": site}})) rendered_site = helm_values(app(docs, "saw-alice"))["site"] - assert rendered_site["providerPolicy"]["allowHosts"] == site["providerAllowHosts"] + assert "providerPolicy" not in rendered_site and "providerAllowHosts" not in rendered_site + assert {b["secret"] for b in rendered_site["credentialBindings"]} >= {"inference"} + assert all(set(b) >= {"secret", "key", "type"} for b in rendered_site["credentialBindings"]) + + +def container_alice(**extra): + site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] + user = {"name": "alice", "registration": "3f9a1c0e7b2d4a68", "ownerSubject": site["subject"], + "profiles": ["data-science"], "intentGeneration": 1, "pruneOnRemove": True, + "vaultPrefix": "secret/data/hub/saw-alice/3f9a1c0e7b2d4a68", + "values": {"deployment": {"mode": "container"}}, **extra} + return user, {"containerSites": {"alice": site}} + + +@pytest.mark.parametrize(("given", "expected"), [ + (None, "c4d7d813-fd00-5645-b4b9-7b73e372d0dd"), # uuid5 of urn:saw:portal:alice:3f9a1c0e7b2d4a68 + ("22222222-2222-4222-8222-222222222222", "22222222-2222-4222-8222-222222222222"), +]) +def test_container_installation_id_defaults_to_portal_uuid5(tmp_path, given, expected): + user, extra = container_alice(**({"installationID": given} if given else {})) + docs = docs_from(render_file(tmp_path, [user], extra)) + namespace = [d for d in by_kind(docs, "Namespace") if d["metadata"]["name"] == "saw-alice"][0] + assert namespace["metadata"]["labels"]["saw.redhat.com/runtime-owner"] == expected + assert helm_values(app(docs, "saw-alice"))["installationID"] == expected + + +@pytest.mark.parametrize("auto_approve", [True, False]) +def test_minimal_container_entry_uses_cluster_defaults(tmp_path, auto_approve): + site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] + subject = site.pop("subject") + for item in site["stack"].values(): + item.pop("revision") + site["automaticEnrollment"].pop("revision") + site["automaticEnrollment"]["relay"].pop("revision") + site["automaticEnrollment"]["autoApprove"] = auto_approve + user = {"name": "alice", "ownerSubject": subject, "profiles": ["data-science"], + "vaultPrefix": "secret/data/hub", "values": {"deployment": {"mode": "container"}}} + docs = docs_from(render_file(tmp_path, [user], {"containerDefaults": site})) + values = helm_values(app(docs, "saw-alice")) + registration = "1f732dc2bd1766a0" # sha256("alice:1")[:16] + assert values["registration"] == registration + assert values["installationID"] == "a4300afa-4ae4-5da1-a5b1-44e50a34eb59" + assert values["vaultPrefix"] == "secret/data/hub/saw-alice/" + registration + assert values["site"]["subject"] == subject + # Only an autoApprove site follows the pattern branch; a reviewed site must + # pin commit SHAs itself, so its revisions stay unset and the workspace + # chart and preflight reject it. + expected = {"main"} if auto_approve else {None} + assert {item.get("revision") for item in values["site"]["stack"].values()} == expected + assert values["site"]["automaticEnrollment"].get("revision") == next(iter(expected)) + assert values["site"]["automaticEnrollment"]["relay"].get("revision") == next(iter(expected)) + + +def test_per_user_auto_approve_false_overrides_the_default(tmp_path): + # Sprig's mergeOverwrite would drop the false; the portal's merge keeps it + # (tests/portal/test_portal.py), so both paths must agree. + site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] + subject = site.pop("subject") + site["automaticEnrollment"]["autoApprove"] = True + alice = {"name": "alice", "ownerSubject": subject, "profiles": ["data-science"], + "vaultPrefix": "secret/data/hub", "values": {"deployment": {"mode": "container"}}} + override = {"alice": {"automaticEnrollment": {"autoApprove": False}}} + values = helm_values(app(docs_from(render_file( + tmp_path, [alice], {"containerDefaults": site, "containerSites": override})), "saw-alice")) + enrollment = values["site"]["automaticEnrollment"] + assert enrollment["autoApprove"] is False + assert enrollment["image"] == site["automaticEnrollment"]["image"] # siblings still come from the defaults + + projection = {"enabled": True, "applicationSetControllerLabels": { + "app.kubernetes.io/name": "vp-gitops-applicationset-controller"}, + "egress": [{"to": [{"ipBlock": {"cidr": "10.0.0.3/32"}}], + "ports": [{"protocol": "TCP", "port": 6443}]}]} + (tmp_path / "projected").mkdir() + docs = docs_from(render_file(tmp_path / "projected", [alice], { + "containerDefaults": site, "containerSites": override, "projection": projection, + "ownerResolution": {"enabled": True}})) + config = [d for d in by_kind(docs, "ConfigMap") if d["metadata"]["name"].endswith("-configuration")] + projected = json.loads(config[0]["data"]["workspaces.json"])["containerSites"]["alice"] + assert projected["automaticEnrollment"]["autoApprove"] is False + + +def test_vm_and_container_users_coexist(tmp_path): + site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] + subject = site.pop("subject") + alice = {"name": "alice", "ownerSubject": subject, "profiles": ["data-science"], + "vaultPrefix": "secret/data/hub", "values": {"deployment": {"mode": "container"}}} + bob = {"name": "bob"} + projection = {"enabled": True, "applicationSetControllerLabels": { + "app.kubernetes.io/name": "vp-gitops-applicationset-controller"}, + "egress": [{"to": [{"ipBlock": {"cidr": "10.0.0.3/32"}}], + "ports": [{"protocol": "TCP", "port": 6443}]}]} + extra = {"containerDefaults": site, "projection": projection, "ownerResolution": {"enabled": True}} + mixed = docs_from(render_file(tmp_path, [alice, bob], extra)) + (tmp_path / "vm").mkdir() + alone = docs_from(render_file(tmp_path / "vm", [bob], {"ownerResolution": {"enabled": True}})) + + # Bob's VM resources are exactly what a VM-only list renders. + def bobs(docs): + return sorted((d["kind"], d["metadata"]["name"], json.dumps(d, sort_keys=True)) for d in docs + if d["metadata"].get("labels", {}).get("openshell.pattern/owner") == "bob" + or d["metadata"].get("namespace") == "saw-bob" or d["metadata"]["name"] == "saw-bob") + assert bobs(mixed) and bobs(mixed) == bobs(alone) + assert {"saw-bob", "saw-bob-secrets", "saw-bob-bom"} <= {d["metadata"]["name"] for d in by_kind(mixed, "Application")} + + # Alice goes through the projector only: no direct Application or Namespace. + names = {(d["kind"], d["metadata"]["name"]) for d in mixed} + assert ("Application", "saw-alice") not in names and ("Namespace", "saw-alice") not in names + config = [d for d in by_kind(mixed, "ConfigMap") if d["metadata"]["name"].endswith("-configuration")] + workspaces = json.loads(config[0]["data"]["workspaces.json"]) + assert [u["name"] for u in workspaces["users"]] == ["alice"] + assert list(workspaces["containerSites"]) == ["alice"] + assert workspaces["containerSites"]["alice"]["subject"] == subject + assert workspaces["users"][0]["registration"] == "1f732dc2bd1766a0" + assert "containerDefaults" not in workspaces + + +def test_container_user_without_subject_waits_without_blocking_others(tmp_path): + site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] + site.pop("subject") + alice = {"name": "alice", "profiles": ["data-science"], "values": {"deployment": {"mode": "container"}}} + docs = docs_from(render_file(tmp_path, [alice, {"name": "bob"}], {"containerDefaults": site})) + names = {(d["kind"], d["metadata"]["name"]) for d in docs} + assert ("Application", "saw-bob") in names + assert not any(n == "saw-alice" or n.startswith("saw-alice-") for _, n in names) + waiting = [d for d in by_kind(docs, "ConfigMap") if d["metadata"]["name"] == "saw-users-awaiting-owner"] + assert waiting[0]["data"]["users"] == "alice" + + +def test_container_entry_without_defaults_or_site_fails(tmp_path): + user = {"name": "alice", "ownerSubject": "11111111-1111-4111-8111-111111111111", + "profiles": ["data-science"], "values": {"deployment": {"mode": "container"}}} + result = render_file(tmp_path, [user]) + assert result.returncode != 0 and "requires containerDefaults or a containerSites entry" in result.stderr def test_static_owner_revision_pin_selects_all_children_and_preserves_sibling(tmp_path): diff --git a/tests/charts/test_workspace_relay.py b/tests/charts/test_workspace_relay.py index 71e8fadb4..6016491f8 100644 --- a/tests/charts/test_workspace_relay.py +++ b/tests/charts/test_workspace_relay.py @@ -152,3 +152,12 @@ async def request(headers): for headers in [b"X-Forwarded-Email: reused-login", b"X-Forwarded-Email: owner-sub\r\nX-Forwarded-Email: foreign"]: with pytest.raises(ValueError): asyncio.run(request(headers)) + + +def test_identity_creation_waits_for_its_registrar_secret(): + """A failed Job is never recreated by Argo; creation must outlast a + Keycloak chart that is still bringing up the registrar credential.""" + import re + from pathlib import Path + source = (Path(__file__).resolve().parents[2] / "charts/saw-workspace-relay/templates/identity.yaml").read_text() + assert re.search(r'activeDeadlineSeconds: \{\{ if eq \$action "delete" \}\}300\{\{ else \}\}1800\{\{ end \}\}', source) diff --git a/tests/fixtures/container-site.yaml b/tests/fixtures/container-site.yaml index 65331a2b3..c1d328e09 100644 --- a/tests/fixtures/container-site.yaml +++ b/tests/fixtures/container-site.yaml @@ -19,6 +19,38 @@ portal: serverSans: - '@OWNER@-gateway.@RUNTIME@.svc' - '@OWNER@-gateway.@RUNTIME@.svc.cluster.local' + network: + bootstrapEgress: + - to: + - ipBlock: + cidr: 192.0.2.10/32 + - ipBlock: + cidr: 192.0.2.10/32 + - ipBlock: + cidr: 192.0.2.10/32 + - ipBlock: + cidr: 192.0.2.10/32 + ports: + - protocol: TCP + port: 443 + - protocol: TCP + port: 6443 + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: openshift-dns + podSelector: + matchLabels: + dns.operator.openshift.io/daemonset-dns: default + ports: + - protocol: UDP + port: 53 + - protocol: UDP + port: 5353 + - protocol: TCP + port: 53 + - protocol: TCP + port: 5353 policy: revision: '1111111111111111111111111111111111111111' values: @@ -80,97 +112,6 @@ portal: - portNumber: protocol: TCP port: 5500 - - name: credential-proxy - to: - - pods: - namespaceSelector: - matchLabels: - kubernetes.io/metadata.name: '@TRUSTED@' - podSelector: - matchLabels: - app.kubernetes.io/instance: '@OWNER@' - openshell.pattern/role: credential-proxy - ports: - - portNumber: - protocol: TCP - port: 3128 - proxy: - revision: '1111111111111111111111111111111111111111' - values: - enabled: true - ownerID: '@INSTALLATION@' - gateway: '@OWNER@' - targetNamespace: '@RUNTIME@' - policyConfigMap: '@OWNER@-proxy-policy' - policyDigest: 3601c933b11c60e7d693c4635ed14c626e32c29c9a9e8920a144f852dcba184d - credentialSecretNames: - - inference - network: - bootstrapEgress: - - to: - - ipBlock: - cidr: 192.0.2.10/32 - - ipBlock: - cidr: 192.0.2.10/32 - - ipBlock: - cidr: 192.0.2.10/32 - - ipBlock: - cidr: 192.0.2.10/32 - ports: - - protocol: TCP - port: 443 - - protocol: TCP - port: 6443 - - to: - - namespaceSelector: - matchLabels: - kubernetes.io/metadata.name: openshift-dns - podSelector: - matchLabels: - dns.operator.openshift.io/daemonset-dns: default - ports: - - protocol: UDP - port: 53 - - protocol: UDP - port: 5353 - - protocol: TCP - port: 53 - - protocol: TCP - port: 5353 - proxyEgress: - - to: - - namespaceSelector: - matchLabels: - kubernetes.io/metadata.name: openshift-dns - podSelector: - matchLabels: - dns.operator.openshift.io/daemonset-dns: default - ports: - - protocol: UDP - port: 53 - - protocol: UDP - port: 5353 - - protocol: TCP - port: 53 - - protocol: TCP - port: 5353 - - to: - - ipBlock: - cidr: 0.0.0.0/0 - except: - - 0.0.0.0/8 - - 10.0.0.0/8 - - 100.64.0.0/10 - - 127.0.0.0/8 - - 169.254.0.0/16 - - 172.16.0.0/12 - - 192.168.0.0/16 - - 224.0.0.0/4 - - 240.0.0.0/4 - - 192.0.2.0/24 - ports: - - protocol: TCP - port: 443 gateway: revision: '1111111111111111111111111111111111111111' values: @@ -189,9 +130,6 @@ portal: className: block gatewaySize: 1Gi workspaceSize: 1Gi - proxy: - url: http://@OWNER@-credential-proxy.@TRUSTED@.svc:3128 - caConfigMap: '@OWNER@-proxy-ca' governance: endpoint: http://governance-interceptor.saw-builds.svc:18081 network: @@ -256,17 +194,6 @@ portal: ports: - protocol: TCP port: 18081 - - to: - - namespaceSelector: - matchLabels: - kubernetes.io/metadata.name: '@TRUSTED@' - podSelector: - matchLabels: - app.kubernetes.io/instance: '@OWNER@' - openshell.pattern/role: credential-proxy - ports: - - protocol: TCP - port: 3128 oidc: issuerUrl: https://openshell-keycloak-ingress-saw-keycloak.apps.@DOMAIN@/realms/openshell route: @@ -327,10 +254,6 @@ portal: governanceProfiles: uid: 22222222-2222-4222-8222-222222222222 sha256: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - proxy: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - proxyNetwork: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - proxyPolicy: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - publicCA: equals independent trusted proxy public CA relay: keycloakNamespace: saw-keycloak keycloakProvisionerSecret: saw-relay-provisioner @@ -388,17 +311,7 @@ portal: relayID: a8cb6cbd0eb62f31 subjectMap: saw-portal-relay-subject selectedDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - providerAllowHosts: - - api.openai.com - providerPolicy: - allowHosts: - - api.openai.com - bindings: - - secret: inference - key: api_key - providers: - - openai - markerPrefix: saw-cred - profiles: - openai: - - api.openai.com + credentialBindings: + - secret: inference + key: api_key + type: openai diff --git a/tests/installer/test_custom_endpoint.py b/tests/installer/test_custom_endpoint.py index acacf09bc..b139c6351 100644 --- a/tests/installer/test_custom_endpoint.py +++ b/tests/installer/test_custom_endpoint.py @@ -384,3 +384,54 @@ def test_reference_plan_shell_validates_regular_file_and_cleans_up(ab, tmp_path, assert [c['dryRun'] for c in calls] == ([True] if preflight_fails else [True, False]) assert all(t['ref']['id'] == 'CUSTOM_INFERENCE_API_KEY' for t in calls[0]['plan']['targets']) assert not list(tmp_path.glob('saw-credential-ref.*')) + + +def test_a_thinking_level_marks_the_model_as_reasoning_and_sets_its_default( + ab, fake_env, config, profiles, custom_secrets, governed_catalog): + """OpenClaw offers only default/off for a custom model unless its entry + says reasoning: true and lists the efforts; the level is then the model's + default (a chat's /think still overrides it).""" + notebook(profiles).inference["thinking"] = "medium" + creds = resolve(ab, profiles, custom_secrets) + ab.ProfileApplier(ab.Shell(), config, creds).apply(profiles) + state = fake_env.openshell_state() + sb = state["sandboxes"]["default/notebook"] + model_id = f"custom-inference/{MODEL}" + assert sb["openclawConfig"]["agents.defaults.models"][model_id] == {"params": {"thinking": "medium"}} + # Onboarding wrote the model entry; a rerun marks it as a reasoning model. + sb["openclawConfig"]["models.providers.custom-inference.models"] = [ + {"id": MODEL, "name": MODEL, "contextWindow": 128000}, {"id": "other"}] + fake_env.set_openshell_state(state) + ab.ProfileApplier(ab.Shell(), config, creds).apply(profiles) + models = fake_env.openshell_state()["sandboxes"]["default/notebook"]["openclawConfig"][ + "models.providers.custom-inference.models"] + assert models == [{"id": MODEL, "name": MODEL, "contextWindow": 128000, "reasoning": True, + "compat": {"supportedReasoningEfforts": ["low", "medium", "high"]}}, + {"id": "other"}] + # off marks the model as not reasoning, so no reasoning_effort is sent. + notebook(profiles).inference["thinking"] = "off" + ab.ProfileApplier(ab.Shell(), config, resolve(ab, profiles, custom_secrets)).apply(profiles) + cfg = fake_env.openshell_state()["sandboxes"]["default/notebook"]["openclawConfig"] + assert cfg["models.providers.custom-inference.models"][0] == { + "id": MODEL, "name": MODEL, "contextWindow": 128000, "reasoning": False} + assert cfg["agents.defaults.models"][model_id] == {"params": {"thinking": "off"}} + # Removing the level stops it applying. + del notebook(profiles).inference["thinking"] + ab.ProfileApplier(ab.Shell(), config, resolve(ab, profiles, custom_secrets)).apply(profiles) + assert fake_env.openshell_state()["sandboxes"]["default/notebook"]["openclawConfig"][ + "agents.defaults.models"][model_id] == {} + + +@pytest.mark.parametrize("level", ["max", "Medium", 1]) +def test_an_unknown_thinking_level_is_refused(ab, profiles, level): + sb = notebook(profiles) + sb.inference["thinking"] = level + assert any("thinking must be one of" in p for p in ab.sandbox_inference_problems(sb, {"custom-inference": "custom-inference"})) + + +def test_an_unquoted_yaml_off_means_off(ab): + """YAML 1.1 reads `thinking: off` as false; it still means off.""" + files = profile_files("custom-inference") + key = next(k for k in files if k.endswith("__sandbox.yaml")) + files[key] = files[key].replace('timeoutSeconds: "300"', 'timeoutSeconds: "300"\n thinking: off') + assert notebook(ab.parse_profiles(files)).inference["thinking"] == "off" diff --git a/tests/kubernetes_runtime/profile_fixtures.py b/tests/kubernetes_runtime/profile_fixtures.py index a41be17bd..56180915f 100644 --- a/tests/kubernetes_runtime/profile_fixtures.py +++ b/tests/kubernetes_runtime/profile_fixtures.py @@ -41,10 +41,11 @@ def briefing_inputs(image=IMAGE): slot["toolGate"]["harness"] = {"name": bundle.name, "digest": bundle.digest} ws, = shared.parse_profiles(docs)[0].workspaces bindings = [{"secret":p.credential_secret,"key":p.credential_secret_key,"type":p.type, - "refresh": bool(p.refresh_strategy)} for p in ws.providers if p.enabled] + **({"refresh":p.refresh_strategy} if p.refresh_strategy else {})} + for p in ws.providers if p.enabled and not p.credential_free] cfg = dict(ownerID="b032b2e4-2cd5-47a7-8ef8-ac73e15700b1",namespace="saw-fixture", namespaceUID="fixture-ns",ownerSubject="fixture-subject",mode="container",gatewayVersion="0.1.2-rhaiv.6", - approvedCredentialFreeProviders=[],proxyBindings=bindings,bindings={"personal-assistant/assistant":slot}) + approvedCredentialFreeProviders=[],credentialBindings=bindings,bindings={"personal-assistant/assistant":slot}) return files, cfg @@ -58,7 +59,7 @@ def fixture_inputs(): cfg = dict(namespace="saw-fixture", namespaceUID="fixture", ownerSubject="fixture-owner", mode="container", ownerID="b032b2e4-2cd5-47a7-8ef8-ac73e15700b1", gatewayVersion="0.1.2-rhaiv.6", approvedCredentialFreeProviders=[], - proxyBindings=[{"type":"custom-inference","secret":"inference","key":"api_key","refresh":False}], + credentialBindings=[{"type":"custom-inference","secret":"inference","key":"api_key"}], customInferenceURL="https://models.fixture.test/v1", modelInputs={"inference.model":"fixture/model"}, bindings={"default/notebook":browser_slot()}) return yaml.safe_load(rendered)["data"], cfg diff --git a/tests/kubernetes_runtime/test_admin_session.py b/tests/kubernetes_runtime/test_admin_session.py index 30f3a4d8e..b39e38809 100644 --- a/tests/kubernetes_runtime/test_admin_session.py +++ b/tests/kubernetes_runtime/test_admin_session.py @@ -387,3 +387,41 @@ def test_abandoned_cleanup_does_not_follow_authority_symlink(tmp_path): with pytest.raises(sessions.admin.AdminSessionError, match="symlink"): sessions.admin.remove_abandoned(root) assert (outside/"session.keep").exists() + + +@pytest.mark.parametrize("code", ["UNKNOWN", "INTERNAL", "DEADLINE_EXCEEDED", "UNAVAILABLE"]) +def test_probe_keeps_one_session_until_the_gateway_trusts_it(ca, tmp_path, monkeypatch, code): + """TLS 1.3 rejects an untrusted client after the handshake, so the probe + sees a transport code; the session must survive until the CA propagates.""" + api = Api(ca) + identity_factory = sessions.admin.identity + def identity(base, runtime, **kwargs): + return identity_factory(base, runtime, require_tmpfs=False, erase=lambda p: p.unlink(), **kwargs) + monkeypatch.setattr(sessions.admin, "identity", identity) + monkeypatch.setattr(sessions.admin, "require_memory", lambda _: None) + monkeypatch.setattr(sessions.admin.time, "sleep", lambda _: None) + attempts, seen = [], set() + class Gateway: + def __init__(self, *args, **kwargs): pass + def call(self, method, body): + seen.update(published(api)) + attempts.append(method) + if len(attempts) < 4: raise sessions.RpcError(code) + def close(self): pass + with sessions.GatewaySessions(api.trust(ca), "https://gateway:17670", tmp_path, gateway_factory=Gateway).open(): + assert len(attempts) == 4 + assert len(seen) == 1 and not published(api) + + +def test_each_session_ca_has_a_distinct_name(tmp_path): + names = set() + for n in range(2): + runtime = tmp_path/str(n) + runtime.mkdir() + with sessions.admin.identity(b"server-ca\n", runtime, require_tmpfs=False, + erase=lambda p: p.unlink()) as one: + names.add(one["ca"]) + import subprocess + subjects = {subprocess.run(["openssl", "x509", "-noout", "-subject"], input=pem.encode(), + capture_output=True, check=True).stdout for pem in names} + assert len(subjects) == 2 diff --git a/tests/kubernetes_runtime/test_boundary.py b/tests/kubernetes_runtime/test_boundary.py index ca29e3bd0..d7d646860 100644 --- a/tests/kubernetes_runtime/test_boundary.py +++ b/tests/kubernetes_runtime/test_boundary.py @@ -8,7 +8,7 @@ def installation(): config = dict(namespace="runtime", namespaceUID="ns-uid", ownerID="owner", mode="container", trustedNamespace="trusted", governanceNamespace="gov", - gateway="gateway", proxyPolicy="proxy") + gateway="gateway") resources = {} for key, (path, field) in objects(config).items(): resources[path] = {"metadata": {"uid": key, "generation": 1}, field: {}} @@ -16,7 +16,7 @@ def obj(key): return resources[objects(config)[key][0]] for key in ("validation", "secretGuard", "serviceGuard", "podDeleteGuard"): obj(key)["status"] = {"observedGeneration": 1, "typeChecking": {}} - for key in ("gateway", "governance", "proxy"): + for key in ("gateway", "governance"): obj(key)["spec"]["replicas"] = 1 obj(key)["status"] = {"observedGeneration": 1, "readyReplicas": 1, "updatedReplicas": 1} obj("network")["spec"]["priority"] = 50 @@ -30,16 +30,16 @@ def obj(key): @pytest.mark.parametrize("case,reason", [ - ("replaced", "ChangedBoundary:proxy"), ("drift", "ChangedBoundary:publicCA"), + ("replaced", "ChangedBoundary:governance"), ("drift", "ChangedBoundary:gatewayConfig"), ("new-zone", "NetworkNotRealized"), ("precedence", "EarlierNetworkPolicy"), ("warning", "AdmissionUnavailable"), ("rollout", "RolloutIncomplete:gateway"), ]) def test_changed_or_unrealized_boundary_blocks(installation, case, reason): config, resources, obj, listing = installation if case == "replaced": - obj("proxy")["metadata"]["uid"] = "replacement" + obj("governance")["metadata"]["uid"] = "replacement" elif case == "drift": - obj("publicCA")["data"]["ca.crt"] = "new" + obj("gatewayConfig")["data"]["gateway.toml"] = "new" elif case == "new-zone": resources["/api/v1/nodes"]["items"].append({"metadata": {"name": "new"}}) elif case == "precedence": diff --git a/tests/kubernetes_runtime/test_briefing.py b/tests/kubernetes_runtime/test_briefing.py index 3c4a2947a..9c5d575c7 100644 --- a/tests/kubernetes_runtime/test_briefing.py +++ b/tests/kubernetes_runtime/test_briefing.py @@ -18,10 +18,10 @@ def test_briefing_plan_and_volume(tmp_path): ws, = plan["workspaces"] sb, = ws["sandboxes"] spec = sb["spec"] - assert {p["type"]:p["credentials"] for p in ws["providers"]} == { - "gmail":{"GMAIL_ACCESS_TOKEN":"saw-cred.gmail.access_token"}, - "slack":{"SLACK_BOT_TOKEN":"saw-cred.slack.bot_token"}, - "nvidia":{"NVIDIA_API_KEY":"saw-cred.inference.api_key"}} + assert {p["type"]:p["credentialRef"] for p in ws["providers"]} == { + "gmail":{"secret":"gmail","key":"access_token"}, + "slack":{"secret":"slack","key":"bot_token"}, + "nvidia":{"secret":"inference","key":"api_key"}} mount, = [m for m in spec["template"]["driver_config"]["kubernetes"]["containers"]["agent"]["volume_mounts"] if m["mount_path"]=="/sandbox/harness"] assert mount["read_only"] and mount["name"]=="saw-gate" @@ -43,5 +43,5 @@ def test_untrusted_briefing_is_rejected(fault): if fault=="edited": files[ks[0]]=base64.b64encode(b"tampered").decode() if fault=="no-index": del files["harness-index.yaml"] if fault=="no-approval": del cfg["bindings"]["personal-assistant/assistant"]["toolGate"]["harness"] - if fault=="missing-provider": cfg["proxyBindings"]=[b for b in cfg["proxyBindings"] if b["type"]!="gmail"] + if fault=="missing-provider": cfg["credentialBindings"]=[b for b in cfg["credentialBindings"] if b["type"]!="gmail"] with pytest.raises(ContractError): compile_profile_files(files,cfg) diff --git a/tests/kubernetes_runtime/test_controller.py b/tests/kubernetes_runtime/test_controller.py index d48657961..197c30033 100644 --- a/tests/kubernetes_runtime/test_controller.py +++ b/tests/kubernetes_runtime/test_controller.py @@ -263,6 +263,14 @@ def test_boundary_failure_is_sanitized_and_prevents_core(setup): assert not calls and "secret-token" not in canonical(api.objects[c.scope.status_name]) +def test_proxy_era_approval_asks_for_reenrollment(setup): + from saw_kubernetes.boundary import BoundaryError + c, api, _, _, calls, _ = setup + c.verify_boundary = lambda _: (_ for _ in ()).throw(BoundaryError("ReenrollRequired")) + assert c.reconcile_once()["reason"] == "ReenrollRequired" + assert not calls + + def test_ambiguous_core_failure_retains_intent_and_does_not_publish_exception(setup): c, api, *_ = setup c.core_pass = lambda *a, **k: (_ for _ in ()).throw(RuntimeError("private-request-body")) diff --git a/tests/kubernetes_runtime/test_custom_inference.py b/tests/kubernetes_runtime/test_custom_inference.py index 5236a670a..184cabed8 100644 --- a/tests/kubernetes_runtime/test_custom_inference.py +++ b/tests/kubernetes_runtime/test_custom_inference.py @@ -3,14 +3,13 @@ from .profile_fixtures import fixture_inputs from saw_kubernetes import compile_profile_files, ContractError -from saw_kubernetes import provider def test_custom_bom_uses_bound_model_endpoint_timeout_and_marker(): files,cfg=fixture_inputs() plan=compile_profile_files(files,cfg) w,=plan["workspaces"] - assert w["providers"][0]["credentials"]=={"CUSTOM_INFERENCE_API_KEY":"saw-cred.inference.api_key"} + assert w["providers"][0]["credentialRef"]=={"secret":"inference","key":"api_key"} spec=w["sandboxes"][0]["spec"] assert spec["command"][-1]=="fixture/model" assert plan["customInferenceURL"]=='https://models.fixture.test/v1' @@ -39,34 +38,10 @@ def test_bom_cannot_override_site_approved_destination(bad): with pytest.raises((ContractError, ValueError)): compile_profile_files(files,cfg) -def test_missing_approval_and_widened_proxy_policy_are_rejected(): +def test_custom_inference_requires_site_approval(): files,cfg=fixture_inputs() cfg.pop("customInferenceURL") with pytest.raises(ContractError): compile_profile_files(files,cfg) - url="https://models.fixture.test/v1" - creds={"CUSTOM_INFERENCE_API_KEY":"saw-cred.inference.api_key"} - policy={"allowHosts":["models.fixture.test"],"profiles":{},"markerPrefix":"saw-cred", - "bindings":[{"providers":["custom-inference"],"key":"api_key","secret":"inference"}]} - assert provider.check_policy("custom-inference",creds,policy,url) - for patch in ({"profiles":{"custom-inference":["elsewhere.example"]}}, - {"allowHosts":["models.fixture.test","elsewhere.example"]},{"bindings":[]}): - assert not provider.check_policy("custom-inference",creds,{**policy,**patch},url) - - -def test_gateway_profile_must_match_the_pinned_destination(tmp_path): - from saw_kubernetes import Reconciler - from .test_runtime import FakeGateway files,cfg=fixture_inputs() - plan=compile_profile_files(files,cfg) - gateway=FakeGateway() - old=gateway.call - def call(method, request): - if method=="GetProviderProfile": - return {"profile":{"id":"custom-inference","source":"interceptor/governance", - "credentials":[{"env_vars":["CUSTOM_INFERENCE_API_KEY"],"name":"api_key"}], - "endpoints":[{"host":"foreign.example","port":443,"enforcement":"NETWORK_ENFORCEMENT_MODE_ENFORCE"}]}} - return old(method,request) - gateway.call=call - with pytest.raises(ContractError,match="approved inference boundary"): - Reconciler(gateway,tmp_path,lambda _:None).reconcile(plan,generation=1) - assert not gateway.sandboxes and not gateway.providers + cfg["credentialBindings"]=[] + with pytest.raises(ContractError): compile_profile_files(files,cfg) diff --git a/tests/kubernetes_runtime/test_harness_tool_rules.py b/tests/kubernetes_runtime/test_harness_tool_rules.py new file mode 100644 index 000000000..c0592a135 --- /dev/null +++ b/tests/kubernetes_runtime/test_harness_tool_rules.py @@ -0,0 +1,115 @@ +"""A harness bundle sets the tool-gate actions for its own MCP tools, and only those.""" +import base64 +import json +import subprocess +import shutil +from pathlib import Path +from types import SimpleNamespace + +import pytest +import yaml + +from saw_kubernetes import harness +from saw_kubernetes.core import shared + +ASSETS = Path(shared.__file__).parent +IDENTITY = shared.tool_gate_identity("alice", "subject-1", "default", "notebook") + + +def tree(servers, mcp=("reader", "writer")): + doc = {"apiVersion": "saw.redhat.com/v1alpha1", "kind": "HarnessBundle", + "metadata": {"name": "demo"}, "spec": {"agent": "openclaw", "mcpServers": servers}} + config = {"mcpServers": {name: {"type": "stdio", "command": "node", "args": ["${PLUGIN_ROOT}/mcp/x.mjs"]} + for name in mcp}} + return {"harness.yaml": (yaml.safe_dump(doc).encode(), False), + "plugin.json": (b'{"name": "demo"}', False), + "mcp.json": (json.dumps(config).encode(), False)} + + +def rules(servers, **kwargs): + return shared.harness_tool_rules(shared.describe_harness_tree(tree(servers, **kwargs), inline=True)) + + +def test_declared_tools_become_rules_named_after_their_server(): + assert rules([{"name": "reader", "tools": [{"name": "read_mail", "action": "allow"}]}, + {"name": "writer", "tools": [{"name": "save", "action": "approval"}]}]) == [ + {"id": "harness-reader-read_mail", "tool": "reader__read_mail", "action": "allow"}, + {"id": "harness-writer-save", "tool": "writer__save", "action": "approval"}] + assert rules([{"name": "reader"}]) == [] + + +@pytest.mark.parametrize("servers", [ + [{"name": "other", "tools": [{"name": "x", "action": "allow"}]}], # not this bundle's server + [{"name": "reader", "tools": [{"name": "x", "action": "deny"}]}], # only allow or approval + [{"name": "reader", "tools": [{"name": "../exec", "action": "allow"}]}], + [{"name": "reader", "tools": [{"name": "x", "action": "allow", "when": "always"}]}], + [{"name": "reader", "tools": {"name": "x", "action": "allow"}}], + [{"name": "reader", "tools": [{"name": "x", "action": "allow"}, {"name": "x", "action": "allow"}]}], +]) +def test_a_bundle_cannot_claim_other_tools_or_actions(servers): + with pytest.raises(shared.InstallerError): + rules(servers) + + +def test_gate_policy_appends_harness_rules_after_the_base_and_pins_them(): + base, _, base_digest, base_hash = shared.tool_gate_bundle(ASSETS, IDENTITY) + extra = [{"id": "harness-reader-read_mail", "tool": "reader__read_mail", "action": "allow"}] + merged, _, digest, policy_hash = shared.tool_gate_bundle(ASSETS, IDENTITY, None, extra) + text = merged["tool-actions.yaml"][0] + assert text.startswith(base["tool-actions.yaml"][0].rstrip(b"\n")) + assert b"tool: reader__read_mail" in text + assert (digest, policy_hash) != (base_digest, base_hash) + assert policy_hash.encode() in merged["plugin/index.js"][0] + assert shared.tool_gate_bundle(ASSETS, IDENTITY, None, extra)[2] == digest + + +def test_an_injected_server_name_cannot_add_policy_rules(): + """Regression: a server name with a newline could append `tool: exec` / + `action: allow` to the policy text and bypass default-deny.""" + evil = "reader\n - id: pwn\n tool: exec\n action: allow\n - id: x" + with pytest.raises(shared.InstallerError, match="mcp server name"): + rules([{"name": evil, "tools": [{"name": "x", "action": "allow"}]}], mcp=(evil,)) + + +@pytest.mark.parametrize("rule", [ + {"id": "harness-reader-x", "tool": "exec", "action": "allow"}, # a bare base tool + {"id": "harness-reader-x", "tool": "reader__x\n - id: pwn", "action": "allow"}, + {"id": "pwn\n tool: exec", "tool": "reader__x", "action": "allow"}, + {"id": "harness-reader-x", "tool": "reader__x", "action": "deny"}, + {"id": "harness-reader-x", "tool": "reader__x", "action": "allow", "whenCommandMatches": "rm"}, +]) +def test_the_gate_policy_refuses_rules_it_cannot_write_safely(rule): + with pytest.raises(shared.InstallerError, match="invalid harness tool rule"): + shared.tool_gate_bundle(ASSETS, IDENTITY, None, [rule]) + + +@pytest.mark.skipif(not shutil.which("node"), reason="node is required") +def test_the_gate_allows_the_harness_tool_and_the_base_rule_wins(tmp_path): + # A harness rule cannot name a base tool at all, and its own tools are allowed. + base = yaml.safe_load((ASSETS / "tool-actions.yaml").read_text()) + denied = next(r["tool"] for r in base["rules"] if r["action"] == "approval" and "whenCommandMatches" not in r) + with pytest.raises(shared.InstallerError): + shared.tool_gate_bundle(ASSETS, IDENTITY, None, [{"id": "harness-x-override", "tool": denied, "action": "allow"}]) + extra = [{"id": "harness-reader-read_mail", "tool": "reader__read_mail", "action": "allow"}] + policy = shared.tool_gate_bundle(ASSETS, IDENTITY, None, extra)[0]["tool-actions.yaml"][0].decode() + script = f""" +import {{ decide }} from {json.dumps(str(ASSETS / "tool-gate.mjs"))}; +const input = (tool) => ({{ policyText: {json.dumps(policy)}, identity: {{username: "alice", subject: "s"}}, + toolName: tool, sessionKey: "s1", params: {{}} }}); +console.log(JSON.stringify(["reader__read_mail", {json.dumps(denied)}, "reader__other"].map(t => decide(input(t)).record.decision))); +""" + out = subprocess.run(["node", "--input-type=module", "-e", script], capture_output=True, text=True, check=True) + assert json.loads(out.stdout) == ["allow", "approval_required", "deny"] + + +def test_openclaw_allowlist_gets_the_bundle_tools_but_not_base_decided_ones(): + files = tree([{"name": "reader", "tools": [{"name": "read_mail", "action": "allow"}]}]) + bundle = SimpleNamespace(files={k: base64.b64encode(v).decode() for k, (v, _) in files.items()}, + digest="sha256:" + "a" * 64) + command = ["sh", "-c", "const target = process.env.OPENCLAW_CONFIG_PATH;\nexec openclaw gateway run"] + driver = {"containers": {"agent": {"volume_mounts": []}}} + workspace = SimpleNamespace(providers=[]) + harness.configure(command, driver, bundle, workspace, SimpleNamespace(providers=[]), None) + spec = json.loads(command[2].split("const harness = ", 1)[1].split(";\n", 1)[0]) + assert "reader__read_mail" in spec["tools"] + assert "reader__other" not in spec["tools"] diff --git a/tests/kubernetes_runtime/test_inference_providers.py b/tests/kubernetes_runtime/test_inference_providers.py index f082cf30d..1f8699575 100644 --- a/tests/kubernetes_runtime/test_inference_providers.py +++ b/tests/kubernetes_runtime/test_inference_providers.py @@ -1,4 +1,4 @@ -"""All inference providers share BOM resolution and the VM's proxy profiles.""" +"""All inference providers share BOM resolution; OpenShell holds their keys.""" import json import shutil import subprocess @@ -25,7 +25,7 @@ def test_provider_compiles_native_protocol_and_placeholder_config(source, kind, if native: sandbox(source, lambda s: s["inference"].pop("baseUrl")) workspace = compile_profile(*source)["workspaces"][0] - assert workspace["providers"][0]["credentials"] == {env:"saw-cred.inference.api_key"} + assert workspace["providers"][0]["credentialRef"] == {"secret": "inference", "key": "api_key"} command = workspace["sandboxes"][0]["spec"]["command"] assert "@SAW_" not in command[2] if not shutil.which("node"): @@ -61,16 +61,9 @@ def test_provider_compiles_native_protocol_and_placeholder_config(source, kind, @pytest.mark.parametrize("kind,model,url,api,env", CASES) -def test_provider_uses_shipped_host_and_credential_policy(source, kind, model, url, api, env): +def test_provider_reads_its_placeholder_and_keeps_its_native_endpoint(source, kind, model, url, api, env): agent(source, kind, model) - credentials = compile_profile(*source)["workspaces"][0]["providers"][0]["credentials"] - slot, hosts = governed.requirements(kind) - assert slot["env_vars"] == [env] - policy = {"markerPrefix":"saw-cred", "profiles":{kind:hosts}, "allowHosts":hosts, - "bindings":[{"providers":[kind],"secret":"inference","key":"api_key"}]} - assert governed.check_policy(kind, credentials, policy) - assert not governed.check_policy(kind, credentials, {**policy,"allowHosts":[]}) - assert not governed.check_policy(kind, {env:"saw-cred.foreign.api_key"}, policy) + assert governed.inference_key_env(kind) == env sandbox(source, lambda s: s["inference"].update(baseUrl="https://foreign.example/v1")) with pytest.raises(ContractError): compile_profile(*source) diff --git a/tests/kubernetes_runtime/test_openclaw.py b/tests/kubernetes_runtime/test_openclaw.py index dff64aeda..c59b7cfcc 100644 --- a/tests/kubernetes_runtime/test_openclaw.py +++ b/tests/kubernetes_runtime/test_openclaw.py @@ -13,7 +13,7 @@ def agent(source, kind="openai", model="gpt-4.1-mini-2025-04-14"): shared.NATIVE_BASE_URLS.get(kind) or shared.PROTOCOL_NATIVE_BASE_URLS[protocol]) if kind == "custom-inference": source[1]["customInferenceURL"] = endpoint - source[1]["proxyBindings"] = [{"type":kind, "secret":"inference", "key":"api_key", "refresh":False}] + source[1]["credentialBindings"] = [{"type":kind, "secret":"inference", "key":"api_key"}] mutate(source, "providers.yaml", lambda d: d["spec"]["providers"].append( {"name": kind, "type": kind, "credentialSecret": "inference"})) sandbox(source, lambda s: s.update(type="openclaw", providers=[kind], inference={ @@ -48,13 +48,14 @@ def test_mutable_model_compiles_and_startup_accepts_published_selection(source, assert result.stdout.strip() == model -def test_openclaw_pinned_proxy_contract(source): +def test_openclaw_reads_its_key_from_the_openshell_placeholder(source): agent(source) ws = compile_profile(*source)["workspaces"][0] - assert ws["providers"][0]["credentials"] == {"OPENAI_API_KEY": "saw-cred.inference.api_key"} + assert ws["providers"][0]["credentialRef"] == {"secret": "inference", "key": "api_key"} + assert "credentials" not in ws["providers"][0] command = ws["sandboxes"][0]["spec"]["command"] assert command[-1] == "gpt-4.1-mini-2025-04-14" - assert "saw-cred" not in json.dumps(command) + assert "OPENAI_API_KEY" in command[2] assert "loopback" in command[2] @@ -62,7 +63,7 @@ def test_openclaw_pinned_proxy_contract(source): def test_openclaw_rejects_unapproved_bindings(source, change): agent(source) if change == "absent": - source[1].pop("proxyBindings") + source[1].pop("credentialBindings") else: update = {"alternative-url": {"baseUrl": "https://example.com/v1"}, "shell": {"model": "$(id)"}, "unknown-input": {"model": {"secretKeyRef": {"name":"private","key":"key"}}}} @@ -77,7 +78,9 @@ def test_redacted_provider_refuses_changed_revision(source, tmp_path): ws = plan["workspaces"][0] provider = ws["providers"][0] gateway = FakeGateway() - core = Reconciler(gateway, tmp_path / "ledger", lambda plan: None) + core = Reconciler(gateway, tmp_path / "ledger", lambda plan: None, + read_credential=lambda secret, key: ("real-key", "1")) + core.credential_env["openai"] = "OPENAI_API_KEY" real_call = gateway.call def call(method, body): result = real_call(method, body) diff --git a/tests/kubernetes_runtime/test_portal_contract.py b/tests/kubernetes_runtime/test_portal_contract.py index 5b7eff77c..25a943fba 100644 --- a/tests/kubernetes_runtime/test_portal_contract.py +++ b/tests/kubernetes_runtime/test_portal_contract.py @@ -13,17 +13,13 @@ def public_test_ca(): def resources(reg="0123456789abcdef", owner="12345678-1234-4123-a123-123456789012", address="10.0.0.18"): - cfg=dict(namespace="runtime",trustedNamespace="saw-ctl-"+reg,ownerID=owner,governanceNamespace="gov",gateway="gw",proxyPolicy="proxy") + cfg=dict(namespace="runtime",trustedNamespace="saw-ctl-"+reg,ownerID=owner,governanceNamespace="gov",gateway="gw") refs=objects(cfg) data={p:{"metadata":{"uid":key},"spec":{},"data":{}} for key,(p,_) in refs.items()} data[refs["gatewayRole"][0]]["rules"] = [] def obj(k):return data[refs[k][0]] - obj("proxy")["spec"]={"namespace":cfg["trustedNamespace"],"owner":owner,"image":"locked"} obj("gateway")["spec"]={"template":{"metadata":{"annotations":{"checksum/config":"c"*64}}}} obj("gatewayService")["spec"]={"type":"ClusterIP","clusterIP":address,"clusterIPs":[address],"ipFamilies":["IPv4"],"ports":[{"port":17670}]} - pem=public_test_ca() - obj("publicCA").update(data={"ca.crt":pem},metadata={"labels":{"saw.redhat.com/runtime-owner":owner}}) - data["/api/v1/namespaces/"+cfg["trustedNamespace"]+"/configmaps/gw-proxy-ca"]={"metadata":{},"data":{"ca.crt":pem}} return cfg,data,obj @@ -33,14 +29,13 @@ def test_rebind_only_per_registration_identifiers(): verify_contract(second,new.__getitem__,contract(first,old.__getitem__)) -@pytest.mark.parametrize("change",["proxyImage","servicePort","governanceUID","fakeCA","replacementIssuer","extra"]) +@pytest.mark.parametrize("change",["gatewayImage","servicePort","governanceUID","replacementIssuer","extra"]) def test_unreviewed_differences_rejected(change): cfg,live,obj=resources() expected=copy.deepcopy(contract(cfg,live.__getitem__)) - if change=="proxyImage":obj("proxy")["spec"]["image"]="foreign" + if change=="gatewayImage":obj("gateway")["spec"]["image"]="foreign" if change=="servicePort":obj("gatewayService")["spec"]["ports"][0]["port"]=80 if change=="governanceUID":obj("governance")["metadata"]["uid"]="foreign" - if change=="fakeCA":obj("publicCA")["data"]["ca.crt"]="-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----" if change=="replacementIssuer":obj("gatewayConfig")["data"]["issuer"]="foreign" if change=="extra":expected["newKey"]="injected" with pytest.raises(BoundaryError):verify_contract(cfg,live.__getitem__,expected) diff --git a/tests/kubernetes_runtime/test_portal_profile.py b/tests/kubernetes_runtime/test_portal_profile.py index d00003610..26fa7e127 100644 --- a/tests/kubernetes_runtime/test_portal_profile.py +++ b/tests/kubernetes_runtime/test_portal_profile.py @@ -21,7 +21,7 @@ def test_portal_bom_route_requires_same_sandboxes_browser_binding(): profile=ROOT/"tests/fixtures/profiles/audited-openclaw" cfg={"namespace":"saw-owner","namespaceUID":"ns","ownerID":"76c95ca5-b9bc-4be7-b764-bc028087ae28", "ownerSubject":"owner","mode":"container","gatewayVersion":"0.1.2-rhaiv.6", - "approvedCredentialFreeProviders":[],"proxyBindings":[{"type":"openai", "secret":"inference", "key":"api_key", "refresh":False}],"bindings":{"agent/audited":{ + "approvedCredentialFreeProviders":[],"credentialBindings":[{"type":"openai", "secret":"inference", "key":"api_key"}],"bindings":{"agent/audited":{ "workspace":{"claimName":"tenant-data","uid":"claim","readOnly":False}, "toolGate":{"ownerLogin":"owner", "trusted":{"claimName":"saw-gate-fixture","uid":"gate","readOnly":True}, "audit":{"claimName":"saw-audit-fixture","uid":"audit","readOnly":False}}, diff --git a/tests/kubernetes_runtime/test_provider_endpoints.py b/tests/kubernetes_runtime/test_provider_endpoints.py new file mode 100644 index 000000000..c9214efbc --- /dev/null +++ b/tests/kubernetes_runtime/test_provider_endpoints.py @@ -0,0 +1,93 @@ +"""A credentialed provider's profile may list only the approved endpoints. + +OpenShell attaches a provider's credential to the endpoints in its profile, and +container supervisors may open public TCP/443, so the reconciler must refuse a +profile that would send the key anywhere else. +""" +import pytest + +from saw_kubernetes import ContractError, Reconciler, compile_profile_files +from .profile_fixtures import fixture_inputs +from .test_runtime import FakeGateway + +ENFORCE = "NETWORK_ENFORCEMENT_MODE_ENFORCE" +SITE_URL = "https://models.fixture.test/v1" + + +def endpoint(host, port=443, **extra): + return {"host": host, "port": port, "protocol": "rest", "enforcement": ENFORCE, **extra} + + +def check(kind, endpoints, url=SITE_URL): + Reconciler._verify_profile_endpoints({"customInferenceURL": url}, kind, {"endpoints": endpoints}) + + +def test_custom_inference_host_must_be_the_site_url_host(): + check("custom-inference", [endpoint("models.fixture.test")]) + with pytest.raises(ContractError, match="endpoints differ") as error: + check("custom-inference", [endpoint("api.inference.example.com")]) + assert error.value.safe_reason == "ProviderProfileMismatch" + # One shared profile cannot list several tenants' hosts either. + with pytest.raises(ContractError, match="endpoints differ"): + check("custom-inference", [endpoint("models.fixture.test"), endpoint("api.inference.example.com")]) + + +def test_stock_profile_must_match_the_shipped_governed_profile(): + check("nvidia", [endpoint("integrate.api.nvidia.com")]) + with pytest.raises(ContractError, match="endpoints differ"): + check("nvidia", [endpoint("integrate.api.nvidia.com"), endpoint("evil.example")]) + with pytest.raises(ContractError, match="endpoints differ"): + check("no-such-provider", [endpoint("integrate.api.nvidia.com")]) + + +@pytest.mark.parametrize("bad", [ + endpoint("models.fixture.test", enforcement="NETWORK_ENFORCEMENT_MODE_AUDIT"), + {"host": "models.fixture.test", "port": 443}, # unspecified = audit + endpoint("models.fixture.test", allowed_ips=["203.0.113.7"]), + endpoint("models.fixture.test", ports=[443, 8443]), +]) +def test_every_endpoint_is_enforced_without_extra_destinations(bad): + with pytest.raises(ContractError, match="endpoints differ"): + check("custom-inference", [bad]) + + +class ProfileGateway(FakeGateway): + def __init__(self, endpoints): + super().__init__() + self.endpoints = endpoints + + def call(self, method, request): + if method == "GetProviderProfile" and request["id"] == "custom-inference": + self.calls.append((method, request)) + return {"profile": {"id": "custom-inference", "endpoints": self.endpoints, + "credentials": [{"env_vars": ["CUSTOM_INFERENCE_API_KEY"]}]}} + return super().call(method, request) + + +def test_mismatched_profile_stops_the_reconciler_before_create_provider(tmp_path): + files, config = fixture_inputs() + plan = compile_profile_files(files, config) + gateway = ProfileGateway([endpoint("api.inference.example.com")]) + reconciler = Reconciler(gateway, tmp_path / "state", lambda _: None, + read_credential=lambda secret, key: ("value", "1")) + with pytest.raises(ContractError) as error: + reconciler.reconcile(plan, generation=1) + assert error.value.safe_reason == "ProviderProfileMismatch" + assert not [m for m, _ in gateway.calls if m == "CreateProvider"] + + +def test_matching_profile_lets_the_reconciler_create_the_provider(tmp_path): + files, config = fixture_inputs() + plan = compile_profile_files(files, config) + gateway = ProfileGateway([endpoint("models.fixture.test")]) + reconciler = Reconciler(gateway, tmp_path / "state", lambda _: None, + read_credential=lambda secret, key: ("value", "1")) + created = lambda: [m for m, _ in gateway.calls if m == "CreateProvider"] + for _ in range(4): # workspace and membership come first + try: + reconciler.reconcile(plan, generation=1) + except ContractError: + pass # the bare fake returns no provider revision; the create is what counts + if created(): + break + assert created() diff --git a/tests/kubernetes_runtime/test_provider_governance.py b/tests/kubernetes_runtime/test_provider_governance.py deleted file mode 100644 index 7d78a1f99..000000000 --- a/tests/kubernetes_runtime/test_provider_governance.py +++ /dev/null @@ -1,20 +0,0 @@ -from saw_kubernetes import provider as governed - - -def test_brave_search_uses_shipped_governance_profile(): - slot, hosts = governed.requirements("brave") - - assert slot["name"] == "api_key" - assert slot["env_vars"] == ["BRAVE_API_KEY"] - assert hosts == ["api.search.brave.com"] - - credentials = {"BRAVE_API_KEY": "saw-cred.web-search.api_key"} - policy = { - "markerPrefix": "saw-cred", - "profiles": {"brave": hosts}, - "allowHosts": hosts, - "bindings": [{"providers": ["brave"], "secret": "web-search", "key": "api_key"}], - } - - assert governed.check_policy("brave", credentials, policy) - assert not governed.check_policy("brave", credentials, {**policy, "allowHosts": []}) diff --git a/tests/kubernetes_runtime/test_provider_recovery.py b/tests/kubernetes_runtime/test_provider_recovery.py index 9208df716..05c35e9f6 100644 --- a/tests/kubernetes_runtime/test_provider_recovery.py +++ b/tests/kubernetes_runtime/test_provider_recovery.py @@ -1,5 +1,6 @@ """CreateProvider ambiguity must use a replay receipt, never redacted Get data.""" import copy +import json import pytest @@ -46,22 +47,30 @@ def interrupted(source, tmp_path): ws = plan["workspaces"][0] provider = ws["providers"][0] gateway = LostProviderResponse() - core = Reconciler(gateway, tmp_path / "ledger", lambda _: None) + secrets = {"revision": "1"} + def read_credential(secret, key): + return "real-" + secret + "-" + secrets["revision"], secrets["revision"] + def reconciler(): + core = Reconciler(gateway, tmp_path / "ledger", lambda _: None, read_credential=read_credential) + core.credential_env[provider["type"]] = "OPENAI_API_KEY" + return core + core = reconciler() with pytest.raises(RpcError, match="DEADLINE_EXCEEDED"): core._apply_provider(ws, provider, plan, {}, 1, []) # Reconstruct the process from durable state; changing intent generation # must not change the original CreateProvider request ID. - core = Reconciler(gateway, tmp_path / "ledger", lambda _: None) + core = reconciler() + core.secrets = secrets return core, gateway, ws, provider, plan def test_lost_provider_response_recovers_across_process_and_generation(interrupted): core, gateway, ws, provider, plan = interrupted state = core.store.load() - assert state["pendingProxyProviders"] and not state.get("proxyProviderRevisions") + assert state["pendingProviders"] and not state.get("providerRevisions") assert core._apply_provider(ws, provider, plan, state, 2, []) assert gateway.creations == 1 and gateway.replays == 1 - assert not core.store.load()["pendingProxyProviders"] + assert not core.store.load()["pendingProviders"] assert core._apply_provider(ws, provider, plan, core.store.load(), 2, []) assert gateway.replays == 1 @@ -78,13 +87,13 @@ def test_recovery_refuses_changed_gateway_resource(interrupted, change): meta["labels"] = {} with pytest.raises(RpcError, match="FAILED_PRECONDITION"): core._apply_provider(ws, provider, plan, core.store.load(), 2, []) - assert not core.store.load().get("proxyProviderRevisions") + assert not core.store.load().get("providerRevisions") -def test_recovery_refuses_changed_marker_or_missing_receipt(interrupted): +def test_recovery_refuses_changed_reference_or_missing_receipt(interrupted): core, gateway, ws, provider, plan = interrupted changed = copy.deepcopy(provider) - changed["credentials"]["OPENAI_API_KEY"] = "saw-cred.other.api_key" + changed["credentialRef"]["secret"] = "other" with pytest.raises(ContractError, match="pending provider creation changed"): core._apply_provider(ws, changed, plan, core.store.load(), 2, []) assert gateway.replays == 0 @@ -94,3 +103,102 @@ def test_recovery_refuses_changed_marker_or_missing_receipt(interrupted): # Losing the local intent must not allow adoption based on labels alone. with pytest.raises(ContractError, match="credential revision"): core._apply_provider(ws, provider, plan, {}, 2, []) + + +def test_credential_value_stays_out_of_the_plan_state_and_request_id(interrupted): + core, gateway, ws, provider, plan = interrupted + assert "credentials" not in provider and provider["credentialRef"] + request, _ = gateway.receipt + assert request["provider"]["credentials"] == {"OPENAI_API_KEY": "real-" + provider["credentialRef"]["secret"] + "-1"} + assert "real-" not in json.dumps(plan) + json.dumps(core.store.load()) + request["request_id"] + + +def test_rotated_secret_updates_the_openshell_provider(interrupted): + core, gateway, ws, provider, plan = interrupted + assert core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + updates = [] + original = gateway.call + def call(method, request): + if method == "UpdateProvider": + updates.append(request) + key = (ws["name"], provider["metadata"]["name"]) + gateway.providers[key]["metadata"]["resource_version"] = "2" + return {"provider": copy.deepcopy(gateway.providers[key])} + return original(method, request) + gateway.call = call + core.secrets["revision"] = "2" + pending = [] + assert not core._apply_provider(ws, provider, plan, core.store.load(), 2, pending) + assert pending and updates[0]["provider"]["credentials"] == { + "OPENAI_API_KEY": "real-" + provider["credentialRef"]["secret"] + "-2"} + assert core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + + + +class LostUpdateResponse: + """UpdateProvider whose reply is lost; it may or may not have applied.""" + + def __init__(self, gateway, key, *, apply, error): + self.gateway, self.key, self.apply, self.error = gateway, key, apply, error + self.original, self.sent = gateway.call, [] + gateway.call = self.call + + def call(self, method, request): + if method != "UpdateProvider": + return self.original(method, request) + self.sent.append(request["request_id"]) + provider = self.gateway.providers[self.key] + if self.apply: + provider["metadata"]["resource_version"] = str(int(provider["metadata"]["resource_version"]) + 1) + self.apply = False # a replay of the same request does not apply twice + if self.error: + error, self.error = self.error, "ALREADY_EXISTS" # replays answer with no body + raise RpcError(error) + return {"provider": copy.deepcopy(provider)} + + +def converged(interrupted): + core, gateway, ws, provider, plan = interrupted + assert core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + core.secrets["revision"] = "2" + return core, gateway, ws, provider, plan, (ws["name"], provider["metadata"]["name"]) + + +def test_applied_update_with_a_lost_reply_is_recorded_not_resent(interrupted): + core, gateway, ws, provider, plan, key = converged(interrupted) + lost = LostUpdateResponse(gateway, key, apply=True, error="DEADLINE_EXCEEDED") + with pytest.raises(RpcError, match="DEADLINE_EXCEEDED"): + core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + assert core.store.load()["pendingProviderUpdates"] + # The next pass sees the provider moved on and records the new source. + assert core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + state = core.store.load() + assert not state["pendingProviderUpdates"] + recorded = next(iter(state["providerRevisions"].values())) + assert recorded["source"] == "2" and recorded["version"] == "2" + assert core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + assert len(lost.sent) == 1 + + +def test_update_replay_without_a_body_converges(interrupted): + core, gateway, ws, provider, plan, key = converged(interrupted) + # First attempt never applied; its replay applies and answers ALREADY_EXISTS. + lost = LostUpdateResponse(gateway, key, apply=False, error="DEADLINE_EXCEEDED") + with pytest.raises(RpcError, match="DEADLINE_EXCEEDED"): + core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + lost.apply = True + pending = [] + assert not core._apply_provider(ws, provider, plan, core.store.load(), 2, pending) and pending + assert lost.sent[0] == lost.sent[1] # same request ID: the gateway replays it + assert core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + assert len(lost.sent) == 2 + + +def test_provider_changed_during_an_update_fails_closed(interrupted): + core, gateway, ws, provider, plan, key = converged(interrupted) + LostUpdateResponse(gateway, key, apply=True, error="DEADLINE_EXCEEDED") + with pytest.raises(RpcError, match="DEADLINE_EXCEEDED"): + core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + gateway.providers[key]["credentials"] = {"OTHER_KEY": "REDACTED"} + with pytest.raises(ContractError, match="changed during a credential update"): + core._apply_provider(ws, provider, plan, core.store.load(), 2, []) diff --git a/tests/kubernetes_runtime/test_provider_refresh.py b/tests/kubernetes_runtime/test_provider_refresh.py new file mode 100644 index 000000000..386215fc5 --- /dev/null +++ b/tests/kubernetes_runtime/test_provider_refresh.py @@ -0,0 +1,155 @@ +"""OpenShell refreshes OAuth access tokens; the runtime only hands it the material.""" +import copy +import json + +from saw_kubernetes import Reconciler +from saw_kubernetes.compiler import MANAGED, OWNER +from .test_runtime import FakeGateway + +OWNER_ID = "b032b2e4-2cd5-47a7-8ef8-ac73e15700b1" +PLAN = {"ownerID": OWNER_ID} +WS = {"name": "default"} +GMAIL = {"metadata": {"name": "gmail", "labels": {OWNER: OWNER_ID, MANAGED: "kubernetes-runtime"}}, + "type": "gmail", "credentialRef": {"secret": "gmail", "key": "access_token"}, + "refresh": {"strategy": "oauth2_refresh_token", + "material": ["client_id", "client_secret", "refresh_token"]}} + + +class RefreshGateway(FakeGateway): + def __init__(self): + super().__init__() + self.refresh_ok = True + self.status_ready = True # False: the gateway has not populated refresh status yet + self.lose_replies = False # True: configure/rotate replies come back without a body + + def call(self, method, request): + if method in ("ConfigureProviderRefresh", "RotateProviderCredential"): + self.calls.append((method, copy.deepcopy(request))) + if self.lose_replies: + from saw_kubernetes import RpcError + raise RpcError("ALREADY_EXISTS") + if method == "RotateProviderCredential": + # As the gateway does: store the minted token, bumping the version. + provider = self.providers[(request["workspace_scope"]["workspace"], request["provider"])] + provider["credentials"] = {request["credential_key"]: "REDACTED"} + provider["metadata"]["resource_version"] = str(int(provider["metadata"]["resource_version"]) + 1) + return {"status": {}} + if method == "GetProviderRefreshStatus": + if not self.status_ready: + return {"credentials": []} + status = {"credential_key": request["credential_key"]} + if not self.refresh_ok: + status["last_error"] = "invalid_grant" + return {"credentials": [status]} + response = super().call(method, request) + if method == "CreateProvider": + obj = response["provider"] + obj["metadata"]["resource_version"] = "1" + obj["credentials"] = {k: "REDACTED" for k in obj.get("credentials", {})} + return response + + +def setup(tmp_path): + gateway = RefreshGateway() + secret = {"revision": "1"} + def read_credential(name, key): + # Like the portal's Vault object: refresh material only, no access_token. + assert key in GMAIL["refresh"]["material"], key + return f"{key}-{secret['revision']}", secret["revision"] + core = Reconciler(gateway, tmp_path / "ledger", lambda _: None, read_credential=read_credential) + core.credential_env["gmail"] = "GMAIL_ACCESS_TOKEN" + return core, gateway, secret + + +def run(core, state): + pending = [] + return core._apply_provider(WS, GMAIL, PLAN, state, 1, pending), pending + + +def methods(gateway, name): + return [r for m, r in gateway.calls if m == name] + + +def test_refresh_is_configured_once_per_secret_revision(tmp_path): + core, gateway, secret = setup(tmp_path) + state = {} + assert run(core, state) == (False, ["provider/default/gmail"]) # created + assert run(core, state) == (False, ["provider/default/gmail"]) # refresh configured + configure, = methods(gateway, "ConfigureProviderRefresh") + assert configure["credential_key"] == "GMAIL_ACCESS_TOKEN" + assert configure["strategy"] == "PROVIDER_CREDENTIAL_REFRESH_STRATEGY_OAUTH2_REFRESH_TOKEN" + assert configure["material"] == {"client_id": "client_id-1", "client_secret": "client_secret-1", + "refresh_token": "refresh_token-1"} + assert set(configure["secret_material_keys"]) == {"client_id", "client_secret", "refresh_token"} + assert len(methods(gateway, "RotateProviderCredential")) == 1 + assert run(core, state) == (True, []) + assert len(methods(gateway, "ConfigureProviderRefresh")) == 1 # unchanged Secret: not re-sent + + secret["revision"] = "2" + assert run(core, state)[0] is False + assert len(methods(gateway, "ConfigureProviderRefresh")) == 2 + assert not methods(gateway, "UpdateProvider") # OpenShell owns the refreshed token + assert run(core, state) == (True, []) + + stored = json.dumps(core.store.load()) + json.dumps(state) + ids = json.dumps([r.get("request_id") for _, r in gateway.calls]) + assert "refresh_token-" not in stored + ids and "client_secret-" not in stored + ids + + +def test_failing_refresh_is_reported(tmp_path): + core, gateway, _ = setup(tmp_path) + state = {} + run(core, state); run(core, state) + gateway.refresh_ok = False + import pytest + from saw_kubernetes import ContractError + with pytest.raises(ContractError, match="refresh is failing"): + run(core, state) + + +def test_provider_is_created_from_material_without_an_access_token(tmp_path): + core, gateway, _ = setup(tmp_path) + state = {} + run(core, state) + create, = methods(gateway, "CreateProvider") + # OpenShell mints the token: no credential value, and only Provider fields. + assert "credentials" not in create["provider"] and "refresh" not in create["provider"] + run(core, state) + assert len(methods(gateway, "RotateProviderCredential")) == 1 + # The rotation rewrote the provider (new version, minted token); still converged. + assert run(core, state) == (True, []) + assert run(core, state) == (True, []) + + +def test_unpopulated_status_is_pending_and_a_lost_configure_is_resent(tmp_path): + core, gateway, _ = setup(tmp_path) + state = {} + run(core, state) # create + gateway.status_ready, gateway.lose_replies = False, True + assert run(core, state) == (False, ["provider/default/gmail"]) # configure: no reply body + assert run(core, state) == (False, ["provider/default/gmail"]) # sent again, same request + first, second = methods(gateway, "ConfigureProviderRefresh") + assert first["request_id"] == second["request_id"] + assert not core.store.load().get("refreshConfigured") # nothing recorded yet + + gateway.lose_replies = False + assert run(core, state)[0] is False # acknowledged; status still empty + assert run(core, state) == (False, ["provider/default/gmail"]) # empty status: pending + assert len(methods(gateway, "ConfigureProviderRefresh")) == 3 # not re-sent once acknowledged + assert not core.store.load().get("refreshConfigured") + gateway.status_ready = True + assert run(core, state) == (True, []) + assert core.store.load()["refreshConfigured"] == {"default/gmail": "1"} + + +def test_refresh_that_disappears_after_working_is_reported(tmp_path): + core, gateway, _ = setup(tmp_path) + state = {} + run(core, state); run(core, state) + assert run(core, state) == (True, []) + gateway.status_ready = False + import pytest + from saw_kubernetes import ContractError + with pytest.raises(ContractError, match="no longer configured") as error: + run(core, state) + assert error.value.safe_reason == "ProviderRefreshFailed" diff --git a/tests/kubernetes_runtime/test_proxy_ca_projection.py b/tests/kubernetes_runtime/test_proxy_ca_projection.py deleted file mode 100644 index 1efae4a43..000000000 --- a/tests/kubernetes_runtime/test_proxy_ca_projection.py +++ /dev/null @@ -1,126 +0,0 @@ -"""Public trust projection: no Secret reads, adoption, replacement or rotation.""" -import copy -import importlib.util -from pathlib import Path -import subprocess -import pytest - -ROOT=Path(__file__).resolve().parents[2] -SPEC=importlib.util.spec_from_file_location('project_ca',ROOT/'charts/saw-kubernetes-proxy/files/project_ca.py') -mod=importlib.util.module_from_spec(SPEC) -SPEC.loader.exec_module(mod) - - -@pytest.fixture(scope='module') -def cert(tmp_path_factory): - root=tmp_path_factory.mktemp('proxy-ca-test') - subprocess.run(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-days','1', - '-subj','/CN=Public test CA','-keyout',str(root/'key.pem'),'-out',str(root/'ca.pem')], - check=True,capture_output=True) - value=(root/'ca.pem').read_text() - (root/'key.pem').unlink() - return value - - -@pytest.fixture -def config(): - return dict(ownerID='67a9891d-e281-442f-86c3-41771f5ce049',namespace='saw-test-trusted', - targetNamespace='saw-test',name='saw-test-proxy-ca') - - -class Api: - def __init__(self,config,cert): - self.objects={f'/api/v1/namespaces/{ns}':{'metadata':{'name':ns,'labels':{mod.OWNER:config['ownerID']}}} - for ns in [config['namespace'],config['targetNamespace']]} - self.source=f"/api/v1/namespaces/{config['namespace']}/configmaps/{config['name']}" - self.target=f"/api/v1/namespaces/{config['targetNamespace']}/configmaps/{config['name']}" - self.objects[self.source]={'metadata':{'name':config['name'],'namespace':config['namespace']},'data':{'ca.crt':cert}} - self.calls=[] - self.race=None - - def call(self,method,path,body=None): - self.calls.append((method,path)) - assert '/secrets' not in path - assert method in ['GET','POST'] - if method=='POST': - target=path+'/'+body['metadata']['name'] - if self.race: - body=self.race(copy.deepcopy(body)) - self.objects.setdefault(target,copy.deepcopy(body)) - return copy.deepcopy(self.objects.get(path)) - - -def test_repeat_sync_and_only_public_material(config,cert): - api=Api(config,cert) - mod.project(api,config) - before=copy.deepcopy(api.objects) - mod.project(api,config) - assert api.objects==before - assert sum(m=='POST' for m,p in api.calls)==1 - target=api.objects[api.target] - assert target['immutable'] is True and target['data']=={'ca.crt':cert} - assert target['metadata']['annotations']['argocd.argoproj.io/sync-options']==mod.KEEP - - -@pytest.mark.parametrize('mutation',[ - lambda b: b.update(immutable=False), - lambda b: b.update(data={'ca.crt':'different'}), - lambda b: b.update(binaryData={'private':'data'}), - lambda b: b['metadata'].update(ownerReferences=[{'name':'foreign'}]), - lambda b: b['metadata'].update(deletionTimestamp='now'), - lambda b: b['metadata'].update(labels={mod.OWNER:'foreign'}), - lambda b: b['metadata'].update(annotations={}), - lambda b: b.update(metadata=None), -]) -def test_refuses_foreign_changed_or_malformed_target(config,cert,mutation): - api=Api(config,cert) - mod.project(api,config) - mutation(api.objects[api.target]) - before=copy.deepcopy(api.objects) - with pytest.raises(mod.Failure):mod.project(api,config) - assert api.objects==before - - -def test_conflicting_create_race_is_not_adopted(config,cert): - api=Api(config,cert) - def race(body): - body['metadata']['labels'][mod.OWNER]='foreign' - return body - api.race=race - with pytest.raises(mod.Failure,match='explicit trust recovery'):mod.project(api,config) - - -def test_matching_create_race_is_safe(config,cert): - api=Api(config,cert) - api.race=lambda body:body - mod.project(api,config) - - -@pytest.mark.parametrize('value',['secret','-----BEGIN PRIVATE KEY-----','not a certificate',None]) -def test_invalid_source_rejected_before_any_write(config,cert,value): - api=Api(config,cert) - api.objects[api.source]['data']={'ca.crt':value} - with pytest.raises(mod.Failure):mod.project(api,config) - assert not any(m=='POST' for m,p in api.calls) - - -def test_extra_text_cannot_be_projected(config,cert): - api=Api(config,cert) - api.objects[api.source]['data']['ca.crt']=cert+'secret trailing text' - with pytest.raises(mod.Failure):mod.project(api,config) - - -def test_namespace_ownership_required_before_reading_ca(config,cert): - api=Api(config,cert) - api.objects['/api/v1/namespaces/saw-test']['metadata']['labels']={} - with pytest.raises(mod.Failure,match='ownership'):mod.project(api,config) - assert all('/configmaps' not in p for m,p in api.calls) - - -@pytest.mark.parametrize('patch',[{'ownerID':'0'*32},{'targetNamespace':'saw-test-trusted'}, - {'name':'../secrets'},{'targetNamespace':'kube-system'},{'extra':'field'}]) -def test_bad_config_never_calls_api(config,cert,patch): - api=Api(config,cert) - config.update(patch) - with pytest.raises(mod.Failure):mod.project(api,config) - assert not api.calls diff --git a/tests/kubernetes_runtime/test_proxy_era_upgrade.py b/tests/kubernetes_runtime/test_proxy_era_upgrade.py new file mode 100644 index 000000000..a241052b4 --- /dev/null +++ b/tests/kubernetes_runtime/test_proxy_era_upgrade.py @@ -0,0 +1,30 @@ +"""Workspaces enrolled by the removed credential-proxy controller must re-enroll.""" +import pytest + +from saw_kubernetes import ContractError, Reconciler, compile_profile +from saw_kubernetes.boundary import PROXY_ERA_OBJECTS, BoundaryError, verify +from .test_openclaw import agent +from .test_runtime import FakeGateway, source # noqa: F401 (fixture) + + +@pytest.mark.parametrize("key", ["proxyProviderRevisions", "pendingProxyProviders"]) +def test_proxy_era_controller_state_is_not_adopted(source, tmp_path, key): + agent(source) + plan = compile_profile(*source) + gateway = FakeGateway() + reconciler = Reconciler(gateway, tmp_path / "state", lambda _: None, + read_credential=lambda secret, name: ("value", "1")) + identity = {k: plan[k] for k in ["ownerID", "namespaceUID", "ownerSubject", "mode"]} + reference = plan["workspaces"][0]["name"] + "/" + plan["workspaces"][0]["providers"][0]["metadata"]["name"] + reconciler.store.save({"identity": identity, key: {reference: {"version": "7"}}}) + with pytest.raises(ContractError, match="re-enroll") as error: + reconciler.reconcile(plan, generation=1) + assert error.value.safe_reason == "ReenrollRequired" + assert not gateway.calls # nothing adopted, nothing created + + +def test_proxy_era_approval_requires_reenrollment(): + plan = {"namespace": "saw-alice", "namespaceUID": "u", "ownerID": "o", "mode": "container"} + config = {**plan, "approved": dict.fromkeys(PROXY_ERA_OBJECTS | {"gateway"}, {})} + with pytest.raises(BoundaryError, match="ReenrollRequired"): + verify(config, plan, lambda path: pytest.fail("no object is read before the check")) diff --git a/tests/kubernetes_runtime/test_rpc_allowlist.py b/tests/kubernetes_runtime/test_rpc_allowlist.py new file mode 100644 index 000000000..949b1dca0 --- /dev/null +++ b/tests/kubernetes_runtime/test_rpc_allowlist.py @@ -0,0 +1,15 @@ +"""The gateway adapter refuses RPCs it does not list; test fakes accept any.""" +import re +from pathlib import Path + +import saw_kubernetes +from saw_kubernetes.adapters import RPC_METHODS + + +def test_every_rpc_the_runtime_calls_is_allowed(): + called = set() + for source in Path(saw_kubernetes.__file__).parent.glob("*.py"): + called |= set(re.findall(r'(?:\.call|_mutate)\(\s*"([A-Z][A-Za-z]+)"', source.read_text())) + assert {"ListProviderProfiles", "UpdateProvider", "ConfigureProviderRefresh", + "RotateProviderCredential", "GetProviderRefreshStatus"} <= called + assert called <= RPC_METHODS diff --git a/tests/portal/test_portal.py b/tests/portal/test_portal.py index 3dc99b405..38c417a93 100644 --- a/tests/portal/test_portal.py +++ b/tests/portal/test_portal.py @@ -17,6 +17,7 @@ from urllib.parse import parse_qs, urlsplit import pytest +import yaml ROOT = Path(__file__).resolve().parents[2] PORTAL = ROOT / "charts" / "openshell-rhdh" / "files" / "portal.py" @@ -242,6 +243,52 @@ def catalog(portal): return portal.load_catalog(CATALOG) +def test_per_user_auto_approve_false_overrides_the_default(portal, monkeypatch): + # Same override as tests/charts/test_saw_users_chart.py: the portal and the + # saw-users chart must agree that a per-user false wins. + defaults = {"automaticEnrollment": {"autoApprove": True, "image": "runtime@sha256:" + "a" * 64}} + monkeypatch.setenv("SAW_CONTAINER_DEFAULTS", json.dumps(defaults)) + monkeypatch.setenv("SAW_CONTAINER_SITES", json.dumps( + {"alice": {"automaticEnrollment": {"autoApprove": False}}})) + monkeypatch.delenv("SAW_TARGET_REVISION", raising=False) + alice = portal.container_site("alice", subject="11111111-1111-4111-8111-111111111111") + assert alice["automaticEnrollment"] == {"autoApprove": False, "image": "runtime@sha256:" + "a" * 64} + assert portal.auto_approved(alice) is False + assert portal.auto_approved(portal.container_site( + "bob", subject="22222222-2222-4222-8222-222222222222")) is True + + +@pytest.mark.parametrize("auto_approve", [True, False]) +def test_only_auto_approve_sites_follow_the_pattern_branch(portal, monkeypatch, auto_approve): + # Same rule as the saw-portal-container chart (tests/charts/test_portal_container.py). + site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] + for item in site["stack"].values(): + item.pop("revision") + site["automaticEnrollment"].pop("revision") + site["automaticEnrollment"]["relay"].pop("revision") + site["automaticEnrollment"]["autoApprove"] = auto_approve + site["credentialBindings"] = [] + monkeypatch.setenv("SAW_CONTAINER_DEFAULTS", json.dumps(site)) + monkeypatch.setenv("SAW_CONTAINER_SITES", "{}") + monkeypatch.setenv("SAW_TARGET_REVISION", "main") + resolved = portal.container_site("alice", subject=site["subject"]) + revisions = {item.get("revision") for item in resolved["stack"].values()} + assert revisions == ({"main"} if auto_approve else {None}) + assert portal._preflight.configuration_facts(resolved)["revisions"] is auto_approve + + +def test_preflight_gets_the_bindings_the_chart_renders(portal, catalog): + # Same list as saw-users.credentialBindings: nvidia also serves build, + # and a refreshable credential is marked for OpenShell's refresh flow. + assert portal.credential_bindings(catalog["personal-assistant"]) == [ + {"secret": "gmail", "key": "access_token", "type": "gmail", "refresh": "oauth2_refresh_token"}, + {"secret": "inference", "key": "api_key", "type": "nvidia"}, + {"secret": "inference", "key": "api_key", "type": "build"}, + {"secret": "slack", "key": "bot_token", "type": "slack"}, + ] + assert portal.credential_bindings({}) == [] + + def test_a_request_gets_the_profiles_secrets(portal, catalog): profile, secrets = portal.parse_request({ "profile": "data-science", "inference.api_key": " nvapi-1 ", "web-search.api_key": "brave-1", @@ -2254,13 +2301,11 @@ def state(name, operation, generation, **extra): assert json.dumps(fake.vault, sort_keys=True) == vault_before -def test_custom_endpoint_is_approved_before_writing_vault(portal, world, monkeypatch): +def test_custom_endpoint_is_validated_before_writing_vault(portal, world, monkeypatch): fake, signer = world url="https://models.fixture.test/v1" - boundary={"allowHosts":["models.fixture.test"],"inferenceBaseURL":url} site=synthetic_preflight_site(portal, { "subject":"478fdd1f-8db9-41e8-97ad-b563215c89e9", - "profileBoundaries":{"custom-inference":boundary}, "automaticEnrollment":{"approvedProfiles":{"custom-inference":"a"*64}}, }) monkeypatch.setenv("SAW_DEPLOYMENT_MODES",'["vm","container"]') @@ -2271,7 +2316,10 @@ def submit(name,endpoint): request.pop("web-search.api_key") fake.request(name,request) return portal.main(["create",name]) - assert submit("saw-req-bad","https://elsewhere.example/v1") != 0 + # A malformed URL is refused before any key reaches Vault. Which host may + # receive the key is the custom-inference governance profile's call, checked + # by the runtime controller (tests/kubernetes_runtime/test_provider_endpoints.py). + assert submit("saw-req-bad","http://models.fixture.test/v1") != 0 assert not fake.vault and REGISTRY not in fake.objects assert submit("saw-req-good",url) == 0 entry=portal.read_entry(fake.objects[REGISTRY]) diff --git a/tests/scripts/test_container_installation.py b/tests/scripts/test_container_installation.py index 31e55ec10..48ac97403 100644 --- a/tests/scripts/test_container_installation.py +++ b/tests/scripts/test_container_installation.py @@ -42,6 +42,39 @@ def test_select_isolates_container_without_modifying_vm_or_input(): assert selected["projection"]["enabled"] is True +def test_select_accepts_the_minimal_entry_with_container_defaults(monkeypatch): + values = inputs() + site = values.pop("containerSites")["alice"] + subject = site.pop("subject") + values["containerDefaults"] = site + values["users"][0] = {"name": "alice", "profiles": ["data-science"], "vaultPrefix": "secret/data/hub", + "values": {"deployment": {"mode": "container"}}} + monkeypatch.setattr(install, "resolve_subject", lambda name: subject) + selected, user = install.select(values, "alice") + assert user["registration"] == "1f732dc2bd1766a0" # sha256("alice:1")[:16], as the chart derives + assert user["installationID"] == "a4300afa-4ae4-5da1-a5b1-44e50a34eb59" + assert user["vaultPrefix"] == "secret/data/hub/saw-alice/1f732dc2bd1766a0" + assert user["ownerSubject"] == subject and user["pruneOnRemove"] is True and user["intentGeneration"] == 1 + assert selected["containerSites"]["alice"]["subject"] == subject + + +def test_select_without_subject_or_keycloak_account_explains(monkeypatch): + values = inputs() + del values["users"][0]["ownerSubject"] + def missing(name): + raise install.InstallError("set ownerSubject for alice, or create the Keycloak account first") + monkeypatch.setattr(install, "resolve_subject", missing) + with pytest.raises(install.InstallError, match="Keycloak account"): + install.select(values, "alice") + + +def test_select_derives_installation_id_like_the_portal(): + values = inputs() + del values["users"][0]["installationID"] + _, user = install.select(values, "alice") + assert user["installationID"] == "12305846-148f-5386-9827-819d16cda0e1" # uuid5 of urn:saw:portal:alice:aaaa... + + @pytest.mark.parametrize(("requested", "declared"), [ ("container", "kata"), ("kata", "container"), ("vm", "container"), ]) @@ -79,7 +112,6 @@ def test_update_cannot_adopt_another_registration(field): def test_make_preflight_accepts_a_first_registration_with_complete_approval(monkeypatch): values, user = install.select(inputs(), "alice") - del values["containerSites"]["alice"]["providerPolicy"] assert install.preflight_checks.configuration_facts(values["containerSites"]["alice"])["providerEgress"] calls = [] monkeypatch.setattr(install, "get", lambda kind, name, namespace=None: diff --git a/tests/scripts/test_container_topology.py b/tests/scripts/test_container_topology.py index 60dc3985d..c355f3cee 100644 --- a/tests/scripts/test_container_topology.py +++ b/tests/scripts/test_container_topology.py @@ -22,12 +22,18 @@ def module(name): probe = module("oidc_topology_probe") +SERVICES = [] + + @pytest.fixture def cluster(monkeypatch): calls = [] addresses = ["10.10.10.101", "10.10.10.102"] + SERVICES.clear() def command(*args): calls.append(args) + if args[:4] == ("oc", "get", "service", "-A"): + return json.dumps({"items": SERVICES}) if "print-json" in args: return json.dumps({"cleanupApi": {"serviceIP": "172.30.0.1", "endpoints": [ {"ip": "10.10.1.2", "port": 6443}]}}) @@ -40,6 +46,15 @@ def command(*args): {"name": p.lower(), "port": 5353, "protocol": p} for p in ["UDP", "TCP"]]}]}) if "ingress.config.openshift.io" in args: return '{"spec":{"domain":"apps.cluster.example.test"}}' + if "storageclass" in args: + return json.dumps({"items": [ + {"metadata": {"name": "gp3-csi", "annotations": { + "storageclass.kubernetes.io/is-default-class": "true"}}, "provisioner": "ebs.csi.aws.com"}, + {"metadata": {"name": "ocs-cephfs"}, "provisioner": "openshift-storage.cephfs.csi.ceph.com"}]}) + if "pods" in args and "vp-gitops" in args: + return json.dumps({"items": [ + {"metadata": {"labels": {"app.kubernetes.io/name": "vp-gitops-applicationset-controller"}}}, + {"metadata": {"labels": {"app.kubernetes.io/name": "vp-gitops-server"}}}]}) if args[0].endswith("keycloak-host.sh"): return "keycloak.apps.cluster.example.test" if "exec" in args: @@ -84,8 +99,53 @@ def test_overlay_uses_one_probe_and_preserves_separation(base, cluster): assert topo.host_rule("10.10.1.2", 443) not in bootstrap assert {"to": [{"ipBlock": {"cidr": "172.30.0.10/32"}}], "ports": [{"protocol": "TCP", "port": 53}, {"protocol": "UDP", "port": 53}]} in bootstrap - assert set(result["stack"]) == {"gateway", "proxy"} - assert set(result["stack"]["proxy"]["values"]["network"]) == {"bootstrapEgress"} + assert set(result["stack"]) == {"gateway", "identity"} + assert set(result["stack"]["identity"]["values"]["network"]) == {"bootstrapEgress"} + + +def test_overlay_discovers_appset_controller_unless_operator_set(base, cluster): + overlay = topo.container_overlay(copy.deepcopy(base), "trusted-tools/network-probe") + assert overlay["projection"]["applicationSetControllerLabels"] == { + "app.kubernetes.io/name": "vp-gitops-applicationset-controller"} + base["projection"] = {"applicationSetControllerLabels": {"app.kubernetes.io/name": "mine"}} + calls = len(cluster[1]) + overlay = topo.container_overlay(base, "trusted-tools/network-probe") + assert "applicationSetControllerLabels" not in overlay["projection"] + assert not any("pods" in c for c in cluster[1][calls:]) + + +def test_overlay_covers_shared_container_defaults(base, cluster): + values = {"global": base["global"], "containerDefaults": base["containerSites"]["alice"], + "containerSites": {"alice": {"automaticEnrollment": {"autoApprove": True}}}} + overlay = topo.container_overlay(values, "trusted-tools/network-probe") + assert "containerSites" not in overlay # a bare per-user override inherits the defaults' rules + defaults = overlay["containerDefaults"] + assert topo.path_value(defaults, topo.RELAY + ("issuer",)).startswith("https://") + assert topo.path_value(defaults, topo.BOOTSTRAP) == overlay["projection"]["egress"] + + +def test_overlay_fills_only_missing_storage_classes(base, cluster): + site = base["containerSites"]["alice"] + topo.path_value(site, topo.GATEWAY + ("kubernetes", "storage"))["className"] = "" + del site["stack"]["audit"]["values"]["storageClass"] + overlay = topo.container_overlay(base, "trusted-tools/network-probe")["containerSites"]["alice"] + assert topo.path_value(overlay, topo.GATEWAY_STORAGE) == "gp3-csi" + assert overlay["stack"]["audit"]["values"] == {"storageClass": "gp3-csi"} # explicit exchange class kept + assert sum("storageclass" in c for c in cluster[1]) == 1 + + +def test_missing_shared_filesystem_class_is_reported(base, monkeypatch): + del base["containerSites"]["alice"]["stack"]["audit"]["values"]["exchangeStorageClass"] + monkeypatch.setattr(topo, "storage_classes", lambda: ("gp3-csi", None)) + with pytest.raises(ValueError, match="shared-filesystem"): + topo.storage_overlay(base["containerSites"]["alice"], {}, topo.storage_classes) + + +def test_appset_controller_must_be_unique(monkeypatch): + monkeypatch.setattr(topo, "command", lambda *a: json.dumps({"items": [ + {"metadata": {"labels": {"app.kubernetes.io/name": n}}} for n in ("a-applicationset-controller", "b-applicationset-controller")]})) + with pytest.raises(ValueError, match="expected one ApplicationSet controller in vp-gitops"): + topo.appset_controller_labels({}) def test_make_bootstrap_saves_once_enrolled_apply_rechecks_and_delete_works_offline(base, cluster, tmp_path): @@ -232,6 +292,10 @@ def test_make_commands_and_helm_gateway_policy(tmp_path, monkeypatch, base): data = {"status":{"clusterNetwork":[{"cidr":"10.128.0.0/14"}],"serviceNetwork":["172.30.0.0/16"]}} elif "ingress.config.openshift.io" in args: data = {"spec":{"domain":"apps.cluster.example.test"}} +elif "pods" in args: + data = {"items":[{"metadata":{"labels":{"app.kubernetes.io/name":"vp-gitops-applicationset-controller"}}}]} +elif "service" in args and "-A" in args: + data = {"items":[]} elif "service" in args and "kubernetes" in args: data = {"spec":{"clusterIP":"172.30.0.1","ports":[{"port":443}]}} elif "endpointslice" in args and "default" in args: @@ -268,3 +332,33 @@ def test_make_commands_and_helm_gateway_policy(tmp_path, monkeypatch, base): monkeypatch.setenv("MOCK_ISSUER_IP", "10.10.10.111") drift = subprocess.run([*make, "check-container-topology"], text=True, cwd=ROOT, capture_output=True) assert drift.returncode and "topology drift" in drift.stderr + + +def test_issuer_behind_a_load_balancer_also_allows_its_pods(base, cluster): + """On Azure the router is a LoadBalancer Service; OVN-Kubernetes delivers + pod traffic for its external IP straight to the router pods, so the + overlay must allow those pods as well as the IP.""" + addresses, _ = cluster + router = {"metadata": {"name": "router-default", "namespace": "openshift-ingress"}, + "spec": {"type": "LoadBalancer", + "selector": {"ingresscontroller.operator.openshift.io/deployment-ingresscontroller": "default"}, + "ports": [{"name": "http", "port": 80, "protocol": "TCP", "targetPort": "http"}, + {"name": "https", "port": 443, "protocol": "TCP", "targetPort": "https"}]}, + "status": {"loadBalancer": {"ingress": [{"ip": addresses[0]}]}}} + unrelated = {"metadata": {"name": "other", "namespace": "apps"}, + "spec": {"type": "LoadBalancer", "selector": {"app": "x"}, "ports": [{"port": 443}]}, + "status": {"loadBalancer": {"ingress": [{"ip": "203.0.113.9"}]}}} + SERVICES.extend([router, unrelated, {**router, "spec": {**router["spec"], "type": "ClusterIP"}}]) + overlay = topo.container_overlay(base, "trusted-tools/network-probe", None) + relay = topo.path_value(overlay["containerSites"]["alice"], topo.RELAY + ("egress",)) + backend = {"to": [{"namespaceSelector": {"matchLabels": {"kubernetes.io/metadata.name": "openshift-ingress"}}, + "podSelector": {"matchLabels": router["spec"]["selector"]}}], + "ports": [{"protocol": "TCP", "port": "https"}]} + assert backend in relay and topo.host_rule(addresses[0], 443) in relay + assert relay.count(backend) == 1 and not any("apps" in json.dumps(r) for r in relay if r is not backend) + + +def test_issuer_not_behind_a_load_balancer_adds_no_pod_rule(base, cluster): + overlay = topo.container_overlay(base, "trusted-tools/network-probe", None) + relay = topo.path_value(overlay["containerSites"]["alice"], topo.RELAY + ("egress",)) + assert not any("namespaceSelector" in json.dumps(r) and "openshift-ingress" in json.dumps(r) for r in relay) diff --git a/tests/scripts/test_make_interface.py b/tests/scripts/test_make_interface.py index f9c01723e..035fc3367 100644 --- a/tests/scripts/test_make_interface.py +++ b/tests/scripts/test_make_interface.py @@ -34,10 +34,13 @@ def test_container_make_dispatch_never_calls_vm_operations(tmp_path, target, act 'import os,sys\nfrom pathlib import Path\nPath(os.environ["MARKER"]).write_text(sys.argv[1])\n') for filename in ("sandbox-pre-delete.sh", "openshell-saw-create.sh", "saw-delete.sh"): executable(scripts / filename, "exit 99\n") + # saw-create checks the cluster first; the real saw-init.sh needs one. + executable(scripts / "saw-init.sh", 'touch "$MARKER.init"\n') result = run_make(target, "OPENSHELL_SAW_NAME=alice", "DEPLOYMENT_MODE=container", "PYTHON=python3", f"SCRIPTS_DIR={scripts}", env=dict(os.environ, MARKER=str(marker))) assert result.returncode == 0, result.stderr assert marker.read_text() == action + assert (tmp_path / "called.init").exists() == (target == "saw-create") @pytest.mark.parametrize("target", ["saw-logs", "saw-vm-ssh", "saw-restart", "saw-restart-pending"]) diff --git a/tests/scripts/test_profile_catalog_automation.py b/tests/scripts/test_profile_catalog_automation.py index a6943b46b..9a392123d 100644 --- a/tests/scripts/test_profile_catalog_automation.py +++ b/tests/scripts/test_profile_catalog_automation.py @@ -69,13 +69,14 @@ def test_list_names_every_generated_file(): mirrored = [p for p in listed if p.startswith("charts/openshell-saw/files/provider-profiles/")] shipped = sorted(p.name for p in (ROOT / "charts/governance-policy/profiles").glob("*.yaml")) # ... plus the mirror directory itself (so a removed mirror is staged too). - assert "charts/saw-users/templates/_governed-proxy-policy.tpl" in listed - assert "charts/saw-users/files/governed-profiles.json" in listed + for unused in ("charts/saw-users/templates/_governed-proxy-policy.tpl", + "charts/saw-users/files/governed-profiles.json"): + assert unused not in listed assert "charts/openshell-rhdh/files/set-workspace-state.yaml" in listed assert "charts/openshell-rhdh/files/workspace.py" in listed assert "charts/openshell-rhdh/files/saw_keycloak_admin.py" in listed assert UI_MIRROR in listed - assert len(listed) == 12 + len(shipped) + 1 + assert len(listed) == 10 + len(shipped) + 1 assert sorted(p.rsplit("/", 1)[1] for p in mirrored) == shipped assert "charts/openshell-saw/files/provider-profiles" in listed assert "charts/openshell-rhdh/files/create-workspace.yaml" in listed diff --git a/tests/scripts/test_relay_provisioner.py b/tests/scripts/test_relay_provisioner.py new file mode 100644 index 000000000..37c3a7561 --- /dev/null +++ b/tests/scripts/test_relay_provisioner.py @@ -0,0 +1,116 @@ +"""The relay registrar: created without a manual step, never adopts foreign state.""" +import base64 +import importlib.util +import json +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "charts/openshell-keycloak/files")) +SCRIPT = ROOT / "charts/openshell-keycloak/files/relay-provisioner.py" +SPEC = importlib.util.spec_from_file_location("relay_provisioner", SCRIPT) +prov = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(prov) + +ISSUER = "https://keycloak.apps.example.test/realms/openshell" + + +class FakeKube: + """One Secret, with the API's create/get/merge-patch behaviour.""" + + def get(self, path): + return self(path) + + def __init__(self, secret=None): + self.secret, self.writes = secret, [] + + def __call__(self, path, method="GET", body=None, patch=False): + if method == "GET": + if self.secret is None: + raise prov.HttpError(404, "not found") + return json.loads(json.dumps(self.secret)) + self.writes.append(method) + if method == "POST": + assert path.endswith("/secrets") and self.secret is None + self.secret = {"metadata": {**body["metadata"], "resourceVersion": "1"}, + "data": {k: base64.b64encode(v.encode()).decode() + for k, v in body["stringData"].items()}} + else: + assert patch + self.secret["data"] = {k: base64.b64encode(v.encode()).decode() + for k, v in body["stringData"].items()} + return json.loads(json.dumps(self.secret)) + + +def secret(labels, data=None): + return {"metadata": {"name": prov.NAME, "labels": labels, "resourceVersion": "7"}, + "data": {k: base64.b64encode(v.encode()).decode() for k, v in (data or {}).items()}} + + +def test_a_new_cluster_gets_its_credential_without_a_manual_step(): + kube = FakeKube() + values = prov.credential(kube, "saw-keycloak", ISSUER) + assert kube.writes == ["POST"] + assert values["client-id"] == prov.NAME and values["issuer"] == ISSUER + assert len(values["client-secret"]) >= 40 + assert kube.secret["metadata"]["labels"] == {prov.LABEL: prov.NAME} + + +def test_the_credential_is_kept_across_runs(): + kube = FakeKube() + first = prov.credential(kube, "saw-keycloak", ISSUER) + assert prov.credential(kube, "saw-keycloak", ISSUER) == first + assert kube.writes == ["POST"] + + +def test_a_secret_from_the_old_setup_script_is_adopted(): + """Clusters set up by hand with the retired script keep their client.""" + data = {"client-id": prov.NAME, "client-secret": "s" * 54, "issuer": ISSUER} + kube = FakeKube(secret({prov.LABEL: prov.NAME}, data)) + assert prov.credential(kube, "saw-keycloak", ISSUER) == data and kube.writes == [] + + +def test_an_empty_owned_secret_is_filled(): + kube = FakeKube(secret({prov.LABEL: prov.NAME})) + assert prov.credential(kube, "saw-keycloak", ISSUER)["client-id"] == prov.NAME + assert kube.writes == ["PATCH"] + + +@pytest.mark.parametrize("labels,data,message", [ + ({}, {"client-id": prov.NAME, "client-secret": "x", "issuer": ISSUER}, "not this helper's"), + ({prov.LABEL: prov.NAME}, {"client-id": prov.NAME, "client-secret": "x", "issuer": "https://other/realms/x"}, + "issuer"), + ({prov.LABEL: prov.NAME}, {"client-id": "other", "client-secret": "x", "issuer": ISSUER}, "unexpected"), +]) +def test_foreign_or_mismatched_secrets_are_refused(labels, data, message): + kube = FakeKube(secret(labels, data)) + with pytest.raises(ValueError, match=message): + prov.credential(kube, "saw-keycloak", ISSUER) + assert kube.writes == [] + + +def test_errors_are_retried_rather_than_crashing(monkeypatch): + class Stop(Exception): + pass + monkeypatch.setenv("KEYCLOAK_NAMESPACE", "saw-keycloak") + monkeypatch.setenv("KEYCLOAK_NAME", "openshell-keycloak") + monkeypatch.setenv("REALM", "openshell") + monkeypatch.setenv("KC_URL", "https://keycloak.apps.example.test") + monkeypatch.setattr(prov, "Kube", lambda: FakeKube()) + monkeypatch.setattr(prov.saw_tls, "tls_context", lambda *a: None) + calls, sleeps = [], [] + def setup(*args): + calls.append(args) + if len(calls) == 1: + raise prov.HttpError(503, "keycloak starting") + def sleep(seconds): + sleeps.append(seconds) + if len(sleeps) == 2: + raise Stop + monkeypatch.setattr(prov, "setup", setup) + monkeypatch.setattr(prov.time, "sleep", sleep) + with pytest.raises(Stop): + prov.main(["relay-provisioner.py"]) + assert sleeps == [15, 300] and calls[1][2] == ISSUER diff --git a/tests/scripts/test_saw_preflight.py b/tests/scripts/test_saw_preflight.py index c8a288b3f..1952e8213 100644 --- a/tests/scripts/test_saw_preflight.py +++ b/tests/scripts/test_saw_preflight.py @@ -187,15 +187,10 @@ def site_config(): pin = "a" * 40 image = "registry.example.invalid/worker@sha256:" + "b" * 64 return { - "providerAllowHosts": ["api.example.invalid"], - "providerPolicy": {"allowHosts": ["api.example.invalid"]}, + "credentialBindings": [{"secret": "inference", "key": "api_key", "type": "openai"}], "automaticEnrollment": {"revision": pin, "image": image}, "stack": { "policy": {"revision": pin}, - "proxy": {"revision": pin, "values": { - "image": image, - "network": {"bootstrapEgress": [{"to": ["api.example.invalid"]}]}, - }}, "gateway": {"revision": pin, "values": { "kubernetes": {"storage": {"className": "workspace-rwx"}, "image": image}, }}, @@ -216,33 +211,39 @@ def test_site_configuration_requires_pinned_sources_and_scoped_egress(): "revisions": True, } changed = site_config() - changed["providerPolicy"]["allowHosts"] = ["*"] + changed["credentialBindings"] = [{"secret": "inference", "key": "api_key"}] changed["stack"]["gateway"]["revision"] = "main" changed["stack"]["audit"]["values"]["image"] = "image:latest" facts = preflight.configuration_facts(changed) assert facts["providerEgress"] is False assert facts["revisions"] is False assert facts["registry"] is False + development = site_config() + development["automaticEnrollment"]["autoApprove"] = True + for component in development["stack"].values(): + component["revision"] = "configure-alice-custom-inference" + development["automaticEnrollment"]["revision"] = "main" + assert preflight.configuration_facts(development)["revisions"] is True + development["stack"]["gateway"]["revision"] = "-not-a-branch" + assert preflight.configuration_facts(development)["revisions"] is False missing_component = site_config() del missing_component["stack"]["audit"] assert preflight.configuration_facts(missing_component)["revisions"] is False invalid_network = site_config() - invalid_network["stack"]["proxy"]["values"]["network"]["bootstrapEgress"] = "all" + del invalid_network["stack"]["policy"] assert preflight.configuration_facts(invalid_network)["network"] is False -def test_documented_provider_hosts_do_not_need_generated_policy(): +def test_credential_bindings_name_a_secret_key_and_provider_type(): site = site_config() - del site["providerPolicy"] assert preflight.configuration_facts(site)["providerEgress"] is True - for hosts in ([], ["*"], ["api.example.invalid", "*.example.invalid"]): - site["providerAllowHosts"] = hosts + site["credentialBindings"].append({"secret": "gmail", "key": "access_token", "type": "gmail", + "refresh": "oauth2_refresh_token"}) + assert preflight.configuration_facts(site)["providerEgress"] is True + for bad in ({"secret": "", "key": "k", "type": "t"}, {"secret": "s", "key": "k"}, + {"secret": "s", "key": "k", "type": "t", "allowHosts": ["*"]}): + site["credentialBindings"] = [bad] assert preflight.configuration_facts(site)["providerEgress"] is False - site["providerAllowHosts"] = ["api.example.invalid"] - site["providerPolicy"] = {"allowHosts": ["other.example.invalid"]} - assert preflight.configuration_facts(site)["providerEgress"] is False - site["providerPolicy"] = {"allowHosts": [{}]} - assert preflight.configuration_facts(site)["providerEgress"] is False def test_storage_preflight_rejects_missing_class_and_accepts_default_class(): diff --git a/tests/scripts/test_shared_storage.py b/tests/scripts/test_shared_storage.py new file mode 100644 index 000000000..f31a1742a --- /dev/null +++ b/tests/scripts/test_shared_storage.py @@ -0,0 +1,59 @@ +"""scripts/shared-storage.sh: the privileged demo NFS server is opt-in only.""" +import json +import os +import shutil +import subprocess +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = ROOT / "scripts" / "shared-storage.sh" +BLOCK_ONLY = {"items": [{"metadata": {"name": "gp3-csi"}, "provisioner": "ebs.csi.aws.com"}]} + +pytestmark = pytest.mark.skipif(shutil.which("jq") is None, reason="shared-storage.sh needs jq") + + +def run(tmp_path, storage=None): + """Run the script against a fake oc that records every call.""" + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + calls = tmp_path / "calls" + classes = tmp_path / "classes.json" + classes.write_text(json.dumps(BLOCK_ONLY)) + oc = bin_dir / "oc" + oc.write_text(f"""#!/usr/bin/env bash +echo "$*" >> {calls} +case "$*" in + *"-f -"*) cat >/dev/null ;; + "get storageclass -o json") cat {classes} ;; + "get pod rwx-check"*) echo Succeeded ;; + "logs rwx-check"*) echo saw ;; + "create "*"--dry-run=client -o yaml") echo "kind: Namespace" ;; +esac +exit 0 +""") + oc.chmod(0o755) + env = dict(os.environ, PATH=f"{bin_dir}:{os.environ['PATH']}") + env.pop("SAW_SHARED_STORAGE", None) + if storage is not None: + env["SAW_SHARED_STORAGE"] = storage + result = subprocess.run(["bash", str(SCRIPT)], env=env, stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=60, check=False) + return result, calls.read_text().splitlines() + + +@pytest.mark.parametrize("storage", [None, "none"]) +def test_without_a_shared_class_it_fails_with_guidance_and_creates_nothing(tmp_path, storage): + result, calls = run(tmp_path, storage) + assert result.returncode == 1 + assert "no shared-filesystem (ReadWriteMany) StorageClass" in result.stderr + assert "SAW_SHARED_STORAGE=nfs" in result.stderr + assert calls == ["get storageclass -o json"] + + +def test_the_demo_nfs_server_needs_an_explicit_choice(tmp_path): + result, calls = run(tmp_path, "nfs") + assert result.returncode == 0, result.stderr + assert "adm policy add-scc-to-user privileged -z nfs-server -n saw-nfs" in calls + assert "verified read/write" in result.stdout diff --git a/tests/scripts/test_workspace_projection.py b/tests/scripts/test_workspace_projection.py index 5e5dbbe01..c7f5fbf5c 100644 --- a/tests/scripts/test_workspace_projection.py +++ b/tests/scripts/test_workspace_projection.py @@ -83,6 +83,84 @@ def test_foundation_requires_no_synthetic_approval_hash(): workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) +def auto_site(owner): + return dict(subject=owner["ownerSubject"], automaticEnrollment={ + "autoApprove": True, "revision": "main", "image": "example/runtime@sha256:" + "d"*64, + "buildNamespace": "saw-builds", "relay": {"revision": "main"}}) + + +def published(owner, subject=None): + intent = {"bindings": {"ownerID": owner["installationID"], "namespace": "saw-" + owner["name"], + "ownerSubject": subject or owner["ownerSubject"]}, + "profileRef": {"name": "saw-bom-profiles", "sha256": "e"*64}} + binding = {"registration": owner["registration"], "intent": intent, + "approved": {"observed": "f"*64}, "gatewayCA": "ca"} + return {"immutable": True, "metadata": {"labels": {"saw.redhat.com/runtime-owner": owner["installationID"]}}, + "data": {"binding.json": json.dumps(binding)}} + + +def test_auto_approve_needs_no_reference_or_profile_digest(): + owner, _ = inputs() + result = workspace.project_workspace(owner, {}, auto_site(owner), CATALOG, lambda _: {}) + projected = result["containerSites"]["alice"] + assert not projected["selectedDigest"] and "enrollment" not in projected + + +def test_auto_approve_accepts_the_observed_enrollment_but_still_binds_the_owner(): + owner, _ = inputs() + projected = workspace.project_workspace(owner, {}, auto_site(owner), CATALOG, + lambda _: published(owner))["containerSites"]["alice"] + assert projected["enrollment"]["approved"] == {"observed": "f"*64} + assert projected["enrollment"]["revision"] == "main" + with pytest.raises(workspace.WorkspaceError, match="does not belong"): + workspace.project_workspace(owner, {}, auto_site(owner), CATALOG, + lambda _: published(owner, subject="33333333-3333-4333-8333-333333333333")) + + +def test_custom_inference_uses_the_owners_own_url(): + owner, _ = inputs() + owner.update(profiles=["custom-inference"]) + for key in ("lifecycleVersion", "initialModelInputs", "modelInputs", "desiredState", "restartGeneration"): + owner.pop(key) + owner["modelInputs"] = {"inference.model": "org/model"} + site = auto_site(owner) + # No site-level URL: the entry names its own; the governance profile approves the host at run time. + with pytest.raises(workspace.WorkspaceError, match="set customInferenceURL"): + workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) + owner["customInferenceURL"] = "https://api.inference.example/v1" + result = workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) + projected = result["containerSites"]["alice"] + assert projected["customInferenceURL"] == "https://api.inference.example/v1" + assert "profileBoundaries" not in projected or "custom-inference" not in projected["profileBoundaries"] + assert "reference" not in projected["automaticEnrollment"] + assert result["users"][0]["webSearch"] == {"enabled": False} # dedicated endpoint, as in the portal + for bad in ("http://api.inference.example/v1", "https://api.inference.example/v2", + "https://api.inference.example:8443/v1", "https://10.0.0.1/v1"): + owner["customInferenceURL"] = bad + with pytest.raises(workspace.WorkspaceError, match="HTTPS base URL ending in /v1"): + workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) + owner["customInferenceURL"] = "https://api.inference.example/v1" + del owner["modelInputs"] + with pytest.raises(workspace.WorkspaceError, match="set modelInputs.inference.model"): + workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) + + +def test_only_an_endpoint_profile_takes_a_custom_inference_url(): + owner, _ = inputs() + owner["customInferenceURL"] = "https://api.inference.example/v1" + with pytest.raises(workspace.WorkspaceError, match="only a profile with an endpoint input"): + workspace.project_workspace(owner, {}, auto_site(owner), CATALOG, lambda _: {}) + + +def test_reviewed_site_still_rejects_an_unreviewed_enrollment(): + owner, _ = inputs() + site = auto_site(owner) + site["automaticEnrollment"].update(autoApprove=False, reference={"other": "0"*64}, + approvedProfiles={"data-science": "e"*64}) + with pytest.raises(workspace.WorkspaceError, match="invalid published enrollment"): + workspace.project_workspace(owner, {}, site, CATALOG, lambda _: published(owner)) + + @pytest.mark.parametrize("mode", ["vm", "container"]) def test_operator_revision_pin_is_shared_and_does_not_change_repository(mode): owner, site = inputs() diff --git a/values-prod.yaml b/values-prod.yaml index 96722476b..4f32e677d 100644 --- a/values-prod.yaml +++ b/values-prod.yaml @@ -35,6 +35,8 @@ clusterGroup: # the namespace with the workspace registry and its pipelines. rhdh: saw-portal: + # Agent Sandbox controller for container and Kata workspaces (cluster-wide). + agent-sandbox-system: redhat-ods-operator: operatorGroup: true targetNamespaces: [] @@ -90,6 +92,18 @@ clusterGroup: value: "true" - name: ownerResolver.enabled value: "true" + # Registrar for container workspaces' browser relays. + - name: relayProvisioner.enabled + value: "true" + # Stock upstream Agent Sandbox controller (CRDs + controller), required by + # container and Kata workspaces. Remove if the platform already provides it. + agent-sandbox: + name: agent-sandbox + namespace: agent-sandbox-system + path: charts/agent-sandbox + overrides: + - name: enabled + value: "true" # One namespace and three apps (secrets, bill of materials, VM) per user, # from overrides/saw-users.yaml. The chart release is tracked here; the # Application objects it creates live in the Argo CD namespace. @@ -100,7 +114,10 @@ clusterGroup: namespace: openshell-agents path: charts/saw-users extraValueFiles: + - /overrides/saw-container-defaults.yaml + - /overrides/saw-container-demo.yaml # TEMPORARY (vvkp4siy test): remove before merge - /overrides/saw-users.yaml + - /overrides/container-network.yaml # TEMPORARY (vvkp4siy test): remove before merge overrides: - name: ownerResolution.enabled value: "true" @@ -124,6 +141,10 @@ clusterGroup: namespace: rhdh path: charts/openshell-rhdh extraValueFiles: + # containerDefaults (the shared site for portal container requests) + # and portal.deploymentModes come from the same files as saw-users, + # including the site's container-network overlay where it has one. + - /overrides/saw-container-defaults.yaml - /overrides/saw-users.yaml governance-policy: name: governance-policy