From 1d909d2bab9c0caa3327419b3f36f400709cc8dd Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 12 Nov 2026 10:50:42 -0500 Subject: [PATCH 01/69] Configure Alice custom inference workspace --- .../governance-profiles/custom-inference.yaml | 2 +- overrides/saw-users.yaml | 16 ++++++++++------ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/overrides/governance-profiles/custom-inference.yaml b/overrides/governance-profiles/custom-inference.yaml index 08bcbf272..ba03baf29 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.inference.example.com # the host of the `url` in the inference Secret port: 443 # its port (443 for https without one, 8000 for a vLLM Service) protocol: rest enforcement: enforce diff --git a/overrides/saw-users.yaml b/overrides/saw-users.yaml index 03b297a07..ad9f63e22 100644 --- a/overrides/saw-users.yaml +++ b/overrides/saw-users.yaml @@ -1,11 +1,15 @@ # 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: [] +users: + - name: alice + profiles: + - custom-inference + # Opt in only for users of a configured custom-inference endpoint. Match # the hostname in overrides/governance-profiles/custom-inference.yaml. -# defaults: -# openshellSaw: -# egress: -# extraAllow: -# - api.inference.example.com +defaults: + openshellSaw: + egress: + extraAllow: + - api.inference.example.com From 6aaefefc166ce8e1f9afe922277baba5070ac67c Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 16 Nov 2026 12:59:41 -0500 Subject: [PATCH 02/69] Allow OpenClaw automation create commands --- charts/governance-policy/tool-actions.yaml | 2 ++ .../files/installer/tool-actions.yaml | 2 ++ .../files/installer/tool-gate.test.mjs | 4 ++-- docs/governance-interceptor.md | 2 +- docs/openshell-016-release.md | 21 +++++++++++++++++++ .../governance-profiles/custom-inference.yaml | 2 +- 6 files changed, 29 insertions(+), 4 deletions(-) diff --git a/charts/governance-policy/tool-actions.yaml b/charts/governance-policy/tool-actions.yaml index 3becbac16..7f7650989 100644 --- a/charts/governance-policy/tool-actions.yaml +++ b/charts/governance-policy/tool-actions.yaml @@ -52,12 +52,14 @@ rules: action: approval whenCommandMatches: - openclaw cron add + - openclaw cron create - openclaw cron edit - openclaw cron rm - openclaw cron enable - openclaw cron disable - openclaw cron run - openclaw automations add + - openclaw automations create - openclaw automations edit - openclaw automations rm - openclaw automations enable diff --git a/charts/openshell-saw/files/installer/tool-actions.yaml b/charts/openshell-saw/files/installer/tool-actions.yaml index 3becbac16..7f7650989 100644 --- a/charts/openshell-saw/files/installer/tool-actions.yaml +++ b/charts/openshell-saw/files/installer/tool-actions.yaml @@ -52,12 +52,14 @@ rules: action: approval whenCommandMatches: - openclaw cron add + - openclaw cron create - openclaw cron edit - openclaw cron rm - openclaw cron enable - openclaw cron disable - openclaw cron run - openclaw automations add + - openclaw automations create - openclaw automations edit - openclaw automations rm - openclaw automations enable diff --git a/charts/openshell-saw/files/installer/tool-gate.test.mjs b/charts/openshell-saw/files/installer/tool-gate.test.mjs index 1721d8e49..290fd655f 100644 --- a/charts/openshell-saw/files/installer/tool-gate.test.mjs +++ b/charts/openshell-saw/files/installer/tool-gate.test.mjs @@ -164,7 +164,7 @@ test("both automation aliases allow only inspection and hold mutations for appro 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", "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 ["", "remove", "delete", "scratch", "listx", "runsx", "run-all"]) { assert.equal(call({ params: { command: `openclaw ${group} ${verb}` } }).effect.kind, "deny"); } for (const command of [ diff --git a/docs/governance-interceptor.md b/docs/governance-interceptor.md index f2df6a303..7e3b9ad72 100644 --- a/docs/governance-interceptor.md +++ b/docs/governance-interceptor.md @@ -199,7 +199,7 @@ 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, while `openclaw cron add`/`create` and `openclaw cron rm` require approval. 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`. diff --git a/docs/openshell-016-release.md b/docs/openshell-016-release.md index 9a7c52d9e..47165f0a2 100644 --- a/docs/openshell-016-release.md +++ b/docs/openshell-016-release.md @@ -80,6 +80,7 @@ or `~/.local/state/openshell/confinement-stops.json` without a ledger. Do not remove it to bypass recovery. A configured agent can resume without a usable provider while retaining its model/credentials; unchanged reapply leaves it running. +<<<<<<< HEAD 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 @@ -87,3 +88,23 @@ 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, cancellation or timeout prevents execution. See the [governance guide](governance-interceptor.md). +======= +OpenClaw `automations` aliases `cron` in the pinned 2026.9.6 release. Both +allow only `list`, `status`, `get`, `show`, and `runs` without approval. +`add`/`create`, `edit`, `rm`, `enable`, `disable`, and `run` require approval. Unsupported +aliases (`remove`, `delete`), the mixed read/write `scratch` interface +and unknown commands stay denied. Shell wrappers, chaining, substitutions +and conflicting command representations remain denied. Command registration +was verified against the upstream release's +[`register.ts`](https://github.com/openclaw/openclaw/blob/v2026.9.6/src/cli/cron-cli/register.ts), +[`register.cron-add.ts`](https://github.com/openclaw/openclaw/blob/v2026.9.6/src/cli/cron-cli/register.cron-add.ts), +[`register.cron-simple.ts`](https://github.com/openclaw/openclaw/blob/v2026.9.6/src/cli/cron-cli/register.cron-simple.ts) +and [`register.cron-edit.ts`](https://github.com/openclaw/openclaw/blob/v2026.9.6/src/cli/cron-cli/register.cron-edit.ts). + +`openclaw agents set-identity` requires approval for every invocation, including +ordinary name changes. In the pinned OpenClaw version, `--identity-file` can +read arbitrary paths and `--avatar` accepts HTTP(S) and data URIs; the command +also rewrites `openclaw.json`. Filesystem-tool workspace confinement does not +limit this CLI command. Cancelled, denied or timed-out approvals do not run it; +shell wrappers, chaining and substitutions remain denied. +>>>>>>> 552a620f (Allow OpenClaw automation create commands) diff --git a/overrides/governance-profiles/custom-inference.yaml b/overrides/governance-profiles/custom-inference.yaml index ba03baf29..a58dfd7ee 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.inference.example.com # the host of the `url` in the inference Secret port: 443 # its port (443 for https without one, 8000 for a vLLM Service) protocol: rest enforcement: enforce From e41ed1588b14286ab4daf72cc03ae9c37bb1b5f2 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Wed, 18 Nov 2026 15:09:36 -0500 Subject: [PATCH 03/69] Update custom inference server --- overrides/governance-profiles/custom-inference.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/overrides/governance-profiles/custom-inference.yaml b/overrides/governance-profiles/custom-inference.yaml index a58dfd7ee..ba03baf29 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.inference.example.com # the host of the `url` in the inference Secret port: 443 # its port (443 for https without one, 8000 for a vLLM Service) protocol: rest enforcement: enforce From d41bc5f98aa5b9025bef2a714579827255131c1e Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Wed, 18 Nov 2026 23:02:06 +0000 Subject: [PATCH 04/69] Simplify container-mode saw-users entries for static GitOps A container user now needs only name, ownerSubject, profiles, vaultPrefix and values.deployment.mode, like a VM entry. saw-users: - Derive registration (sha256 of name:generation), installationID (the portal's uuid5), the owner-scoped vaultPrefix, pruneOnRemove and intentGeneration; explicit values still win. - Build each container site from a cluster-wide containerDefaults, overlaid by containerSites.; subject defaults to the user's ownerSubject. - Default every component revision to global.targetRevision so container workspaces follow the pattern branch like VM users. saw-portal-container / projector: - Accept a Git branch as well as a full SHA for stack, relay and enrollment revisions. - Add automaticEnrollment.autoApprove for dev/demo clusters: enrollment still runs its health, admission and network checks, then publishes the observed boundary instead of comparing it with a reviewed reference. Pattern and tooling: - overrides/saw-container-defaults.yaml holds projection and containerDefaults; Alice's entry is reduced to the essentials. - values-prod installs the Agent Sandbox controller. - make container-topology also discovers the ApplicationSet controller labels, storage classes and containerDefaults egress. - make keycloak-user-info KC_USER= prints a user's subject. Tests cover the derived fields, minimal entries, mixed VM and container users, autoApprove and the topology discovery. Assisted-By: Claude --- Makefile-quickstart | 6 +- charts/openshell-rhdh/files/workspace.py | 11 +- charts/saw-portal-container/files/enroll.py | 10 +- .../templates/auto-enroll.yaml | 5 +- .../saw-portal-container/templates/relay.yaml | 2 +- .../saw-portal-container/templates/stack.yaml | 2 +- charts/saw-users/files/projector.py | 4 +- charts/saw-users/files/workspace.py | 11 +- charts/saw-users/templates/_helpers.tpl | 67 +++++++- charts/saw-users/templates/applications.yaml | 3 +- charts/saw-users/templates/namespaces.yaml | 1 + charts/saw-users/templates/projector.yaml | 13 +- charts/saw-users/values.yaml | 14 ++ docs/container-installation.md | 44 ++++- overrides/saw-container-defaults.yaml | 158 ++++++++++++++++++ overrides/saw-users.yaml | 12 +- scripts/container-workspace.py | 4 + scripts/container_topology.py | 71 +++++++- scripts/keycloak-users.sh | 40 ++++- tests/charts/test_saw_users_chart.py | 83 +++++++++ tests/scripts/test_container_installation.py | 7 + tests/scripts/test_container_topology.py | 56 +++++++ tests/scripts/test_workspace_projection.py | 43 +++++ values-prod.yaml | 12 ++ 24 files changed, 643 insertions(+), 36 deletions(-) create mode 100644 overrides/saw-container-defaults.yaml diff --git a/Makefile-quickstart b/Makefile-quickstart index df2eb1e81..b309fc743 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 \ 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 \ @@ -372,6 +372,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)" diff --git a/charts/openshell-rhdh/files/workspace.py b/charts/openshell-rhdh/files/workspace.py index bc86b4d01..114dcd614 100644 --- a/charts/openshell-rhdh/files/workspace.py +++ b/charts/openshell-rhdh/files/workspace.py @@ -123,17 +123,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"]} @@ -241,7 +242,7 @@ 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"): diff --git a/charts/saw-portal-container/files/enroll.py b/charts/saw-portal-container/files/enroll.py index 9780d7ad0..918a3da0e 100644 --- a/charts/saw-portal-container/files/enroll.py +++ b/charts/saw-portal-container/files/enroll.py @@ -80,10 +80,14 @@ def obj(kind,name,namespace=ns): 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 = {} diff --git a/charts/saw-portal-container/templates/auto-enroll.yaml b/charts/saw-portal-container/templates/auto-enroll.yaml index 47853e0fc..16a3ef028 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 }} +{{- $autoApprove := eq (toString ($a.autoApprove | default false)) "true" }} +{{- if or (not (regexMatch "^.+@sha256:[a-f0-9]{64}$" $a.image)) (not (regexMatch "^[A-Za-z0-9][A-Za-z0-9._/-]*$" ($a.revision | default ""))) (and (not $autoApprove) (ne (len ($a.reference | default dict)) (ternary 27 25 (not (empty $s.kataRuntimeClass))))) }}{{ fail "automatic enrollment requires a pinned image, a Git revision and a reviewed boundary (or autoApprove)" }}{{- 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 "") "providerPolicy" ($s.providerPolicy | default dict) "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 -}} diff --git a/charts/saw-portal-container/templates/relay.yaml b/charts/saw-portal-container/templates/relay.yaml index 5ac8ecea6..ee41ca894 100644 --- a/charts/saw-portal-container/templates/relay.yaml +++ b/charts/saw-portal-container/templates/relay.yaml @@ -2,7 +2,7 @@ {{- $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 "^[A-Za-z0-9][A-Za-z0-9._/-]*$" ($r.revision | default "")) }}{{ fail "relay revision must be a Git commit or branch" }}{{ end }} {{- $u := .Values.owner }} {{- $reg := .Values.registration }} {{- $ctl := printf "saw-ctl-%s" $reg }} diff --git a/charts/saw-portal-container/templates/stack.yaml b/charts/saw-portal-container/templates/stack.yaml index a0a540369..6f61d9ca9 100644 --- a/charts/saw-portal-container/templates/stack.yaml +++ b/charts/saw-portal-container/templates/stack.yaml @@ -71,7 +71,7 @@ data: {{- 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 "^[A-Za-z0-9][A-Za-z0-9._/-]*$" ($item.revision | default "")) }}{{ fail "each infrastructure chart needs a Git commit or branch revision" }}{{ end }} {{- $values := $item.values | toJson }} {{- range $k, $v := $map }} {{- $values = replace (printf "@%s@" $k) $v $values }} 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..114dcd614 100644 --- a/charts/saw-users/files/workspace.py +++ b/charts/saw-users/files/workspace.py @@ -123,17 +123,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"]} @@ -241,7 +242,7 @@ 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"): diff --git a/charts/saw-users/templates/_helpers.tpl b/charts/saw-users/templates/_helpers.tpl index b3a987fa3..c0f8fc6c8 100644 --- a/charts/saw-users/templates/_helpers.tpl +++ b/charts/saw-users/templates/_helpers.tpl @@ -459,11 +459,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 +471,63 @@ 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 -}} + +{{/* A container user's site: containerSites. layered over the shared +containerDefaults (site values win). subject defaults to the user's +ownerSubject; every chart revision defaults to global.targetRevision, so the +workspace follows the pattern's branch like VM users. Note: mergeOverwrite +skips empty values, so a per-user false/"" cannot unset a default. Returns JSON. */}} +{{- define "saw-users.containerSite" -}} +{{- $root := .root -}}{{- $u := .user -}} +{{- $site := mergeOverwrite (deepCopy ($root.Values.containerDefaults | default dict)) (deepCopy (index ($root.Values.containerSites | default dict) $u.name | default dict)) -}} +{{- if and $site (not $site.subject) }}{{ $_ := set $site "subject" $u.ownerSubject }}{{ end -}} +{{- $rev := $root.Values.global.targetRevision -}} +{{- range $key, $item := ($site.stack | default dict) -}} +{{- if and (kindIs "map" $item) (not $item.revision) }}{{ $_ := set $item "revision" $rev }}{{ end -}} +{{- end -}} +{{- with $site.automaticEnrollment -}} +{{- if not .revision }}{{ $_ := set . "revision" $rev }}{{ end -}} +{{- if and .relay (not .relay.revision) }}{{ $_ := set .relay "revision" $rev }}{{ end -}} +{{- end -}} +{{- toJson $site -}} +{{- end -}} diff --git a/charts/saw-users/templates/applications.yaml b/charts/saw-users/templates/applications.yaml index 96905913b..ba309846e 100644 --- a/charts/saw-users/templates/applications.yaml +++ b/charts/saw-users/templates/applications.yaml @@ -2,6 +2,7 @@ {{- range $user := .Values.users | default list }} {{- if 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,7 +27,7 @@ ) }} --- {{- 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 }} diff --git a/charts/saw-users/templates/namespaces.yaml b/charts/saw-users/templates/namespaces.yaml index dce93a39f..eee2b9049 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 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..07f9cf399 100644 --- a/charts/saw-users/templates/projector.yaml +++ b/charts/saw-users/templates/projector.yaml @@ -2,13 +2,22 @@ {{- $users := list }} {{- range $user := .Values.users }} {{- if has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata") }} -{{- $users = append $users $user }} +{{- $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 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/docs/container-installation.md b/docs/container-installation.md index ff5ed7b3c..9d61bb790 100644 --- a/docs/container-installation.md +++ b/docs/container-installation.md @@ -282,7 +282,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 +309,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 +498,44 @@ 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 | `global.targetRevision`: workspaces follow the pattern's branch like VM users. Pin a site's `stack.*.revision`, `automaticEnrollment.revision` and `relay.revision` to full SHAs to stop that. | + +`containerDefaults.automaticEnrollment.autoApprove: true` is for development and +demo clusters. The enrollment Job still runs its health, admission and network +checks, then publishes the boundary and BOM it observes instead of comparing +them with an operator-reviewed `reference` and `approvedProfiles` digest. Later +changes to an enrolled boundary still fail closed; start a new `generation` +to re-enroll. Keep the reviewed flow below for production clusters. + +Generate the network overlay from both files with `make container-topology`; +it covers `containerDefaults` as well as individual sites. + 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/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml new file mode 100644 index 000000000..2c74fd65d --- /dev/null +++ b/overrides/saw-container-defaults.yaml @@ -0,0 +1,158 @@ +# Cluster-wide settings for container/kata workspaces in saw-users, set once by +# the platform admin. Users only add an entry to overrides/saw-users.yaml. +# Every container user's site is built from containerDefaults; per-user +# overrides go under containerSites.. subject comes from the user's +# ownerSubject and chart revisions follow the pattern's targetRevision. +# <...> values are cluster-specific. Egress to the API server, DNS and Keycloak, +# the issuer URLs and projection.applicationSetControllerLabels are generated +# by `make container-topology` into overrides/container-network.yaml, as are +# storage classes left unset here (the cluster default for single-node volumes, +# a shared-filesystem class such as CephFS for the audit exchange volume). +projection: + enabled: true + +containerDefaults: + governanceNamespace: openshell-agents + providerAllowHosts: + - api.inference.example.com + automaticEnrollment: + enabled: true + autoApprove: true # dev/demo cluster: enroll on first observation, no manual review + # CI build of main f582a118 in the sauagarwa fork (public, multi-arch); + # tag sha-f582a1183dc13ee15f8df4349e8467c981a39250. Switch to the + # validatedpatterns-sandbox package once it is public. + image: ghcr.io/sauagarwa/saw-kubernetes-runtime@sha256:78ea2cf9eebdbf6b350fff43175e034724f22def60bdf03b4fb014f54430221d + buildNamespace: saw-component-builds + resources: + requests: {cpu: 500m, memory: 1Gi} + limits: {cpu: "2", memory: 4Gi} + relay: + keycloakNamespace: saw-keycloak + keycloakProvisionerSecret: saw-relay-provisioner + egress: [] # generated + 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: + priority: 51 # must be unique per workspace: oc get adminnetworkpolicy + 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} + - 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: + values: + enabled: true + ownerID: '@INSTALLATION@' + gateway: '@OWNER@' + targetNamespace: '@RUNTIME@' + policyConfigMap: '@OWNER@-proxy-policy' + # credentialSecretNames and policyDigest are derived from the profile catalog. + network: + bootstrapEgress: [] # generated + 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: # public HTTPS only; the proxy policy narrows it to providerAllowHosts + - 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] + ports: + - {protocol: TCP, port: 443} + gateway: + values: + deployment: {mode: container} + kubernetes: + experimental: true + workload: + image: quay.io/aipcc/base-images/agentic/openclaw@sha256:896d1526ee29b53167034ba65d1c758c8da777f441ed094e19f3bcf6d7445c61 + identity: + serverTlsSecret: '@OWNER@-server' + clientCaSecret: '@OWNER@-client-ca' + jwtSecret: '@OWNER@-jwt' + credentialKeySecret: '@OWNER@-kek' + storage: + gatewaySize: 1Gi + workspaceSize: 10Gi + proxy: + url: http://@OWNER@-credential-proxy.@TRUSTED@.svc:3128 + caConfigMap: '@OWNER@-proxy-ca' + governance: + endpoint: http://governance-interceptor.openshell-agents.svc:18081 + network: + reconcilerNamespace: '@TRUSTED@' + reconcilerLabels: + app.kubernetes.io/instance: '@OWNER@' + openshell.pattern/role: reconciler + gatewayEgress: # operator rules; API/DNS/issuer rules are generated + - to: + - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: openshell-agents}} + podSelector: {matchLabels: {app.kubernetes.io/name: governance-interceptor}} + 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} + route: {enabled: false} + audit: + values: + enabled: true + trustedNamespace: '@ARCHIVE@' + runtimeNamespace: '@RUNTIME@' + ownerID: '@INSTALLATION@' + image: ghcr.io/openclaw/openclaw@sha256:0a5ff5e682e62afa19149df126aa50063bf65ef885b5c94713ce32dc0eb12e15 + identity: + username: '@OWNER@' + workspace: agent + sandbox: audited diff --git a/overrides/saw-users.yaml b/overrides/saw-users.yaml index ad9f63e22..f335db396 100644 --- a/overrides/saw-users.yaml +++ b/overrides/saw-users.yaml @@ -1,9 +1,17 @@ # Add real account names here after creating them with keycloak-add-users. # Each entry creates saw-. Demo entries are in saw-users-demo.yaml. +# +# 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. users: - name: alice - profiles: - - custom-inference + ownerSubject: 9a30e84e-2a47-4b88-a2c2-7ba2bddc6dbf + profiles: [custom-inference] + vaultPrefix: secret/data/hub + values: + deployment: {mode: container} # Opt in only for users of a configured custom-inference endpoint. Match diff --git a/scripts/container-workspace.py b/scripts/container-workspace.py index 36e876024..92409beb4 100644 --- a/scripts/container-workspace.py +++ b/scripts/container-workspace.py @@ -17,6 +17,7 @@ import sys import tempfile import time +import uuid from urllib.request import HTTPRedirectHandler, build_opener import yaml @@ -82,6 +83,9 @@ 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} + # Same derivation as the chart and portal when installationID is omitted. + if not user.get("installationID") and re.fullmatch(r"[a-f0-9]{16}", str(user.get("registration", ""))): + user["installationID"] = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:saw:portal:{name}:{user['registration']}")) 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}")]: diff --git a/scripts/container_topology.py b/scripts/container_topology.py index 7fd342686..fc58e6637 100644 --- a/scripts/container_topology.py +++ b/scripts/container_topology.py @@ -18,6 +18,13 @@ GATEWAY = ("stack", "gateway", "values") BOOTSTRAP = ("stack", "proxy", "values", "network", "bootstrapEgress") RELAY = ("automaticEnrollment", "relay") +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") def command(*args): @@ -93,6 +100,49 @@ def discover_issuer(issuer, probe, container): return [host_rule(ip, port) for ip in sorted(set(answers), key=ipaddress.IPv4Address)] +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") + pods = json.loads(command("oc", "get", "pods", "-n", namespace, "-l", + "app.kubernetes.io/component=applicationset-controller", "-o", "json")) + names = {p.get("metadata", {}).get("labels", {}).get("app.kubernetes.io/name") + for p in pods.get("items", []) if not p.get("metadata", {}).get("deletionTimestamp")} + names.discard(None) + 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[:-1]) is None or 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,11 +175,22 @@ 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(): + # 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) or not path_value(site, GATEWAY) or not path_value(site, RELAY): raise ValueError("expected gateway and automatic enrollment relay site inputs") raw = [path_value(site, GATEWAY + ("oidc", "issuerUrl")), path_value(site, RELAY + ("issuer",))] @@ -152,9 +213,13 @@ def container_overlay(values, probe, container=None): 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 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/tests/charts/test_saw_users_chart.py b/tests/charts/test_saw_users_chart.py index 32d18e428..52452fbc9 100644 --- a/tests/charts/test_saw_users_chart.py +++ b/tests/charts/test_saw_users_chart.py @@ -84,6 +84,89 @@ def test_container_policy_is_derived_from_documented_hosts(tmp_path): assert rendered_site["providerPolicy"]["allowHosts"] == site["providerAllowHosts"] +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 + + +def test_minimal_container_entry_uses_cluster_defaults(tmp_path): + 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") + 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 + assert {item["revision"] for item in values["site"]["stack"].values()} == {"main"} + assert values["site"]["automaticEnrollment"]["relay"]["revision"] == "main" + + +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_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): docs = docs_from(render_file(tmp_path, [ALICE, {"name": "bob"}], {"workspaceRevisions": {"alice": "a"*40}})) diff --git a/tests/scripts/test_container_installation.py b/tests/scripts/test_container_installation.py index 31e55ec10..f63e31bc0 100644 --- a/tests/scripts/test_container_installation.py +++ b/tests/scripts/test_container_installation.py @@ -42,6 +42,13 @@ def test_select_isolates_container_without_modifying_vm_or_input(): assert selected["projection"]["enabled"] is True +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"), ]) diff --git a/tests/scripts/test_container_topology.py b/tests/scripts/test_container_topology.py index 60dc3985d..9ec576d84 100644 --- a/tests/scripts/test_container_topology.py +++ b/tests/scripts/test_container_topology.py @@ -40,6 +40,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", + "app.kubernetes.io/component": "applicationset-controller"}}}]}) if args[0].endswith("keycloak-host.sh"): return "keycloak.apps.cluster.example.test" if "exec" in args: @@ -88,6 +97,51 @@ def test_overlay_uses_one_probe_and_preserves_separation(base, cluster): assert set(result["stack"]["proxy"]["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): values = copy.deepcopy(base) file = tmp_path / "net.yaml" @@ -232,6 +286,8 @@ 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 "kubernetes" in args: data = {"spec":{"clusterIP":"172.30.0.1","ports":[{"port":443}]}} elif "endpointslice" in args and "default" in args: diff --git a/tests/scripts/test_workspace_projection.py b/tests/scripts/test_workspace_projection.py index 5e5dbbe01..70b4fd7cf 100644 --- a/tests/scripts/test_workspace_projection.py +++ b/tests/scripts/test_workspace_projection.py @@ -83,6 +83,49 @@ 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_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..ee80f778e 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,15 @@ clusterGroup: value: "true" - name: ownerResolver.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,6 +111,7 @@ clusterGroup: namespace: openshell-agents path: charts/saw-users extraValueFiles: + - /overrides/saw-container-defaults.yaml - /overrides/saw-users.yaml overrides: - name: ownerResolution.enabled From c6aa881e116077e850ca7318c0c7fb352140d00d Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Wed, 18 Nov 2026 23:03:18 +0000 Subject: [PATCH 05/69] Resolve leftover rebase conflict in OpenShell 0.1.6 release notes Keep main's wording and add the create alias from the automation commands change. Assisted-By: Claude --- docs/openshell-016-release.md | 26 +++----------------------- 1 file changed, 3 insertions(+), 23 deletions(-) diff --git a/docs/openshell-016-release.md b/docs/openshell-016-release.md index 47165f0a2..09e3745bd 100644 --- a/docs/openshell-016-release.md +++ b/docs/openshell-016-release.md @@ -80,31 +80,11 @@ or `~/.local/state/openshell/confinement-stops.json` without a ledger. Do not remove it to bypass recovery. A configured agent can resume without a usable provider while retaining its model/credentials; unchanged reapply leaves it running. -<<<<<<< HEAD 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, cancellation or timeout prevents execution. See the [governance guide](governance-interceptor.md). -======= -OpenClaw `automations` aliases `cron` in the pinned 2026.9.6 release. Both -allow only `list`, `status`, `get`, `show`, and `runs` without approval. -`add`/`create`, `edit`, `rm`, `enable`, `disable`, and `run` require approval. Unsupported -aliases (`remove`, `delete`), the mixed read/write `scratch` interface -and unknown commands stay denied. Shell wrappers, chaining, substitutions -and conflicting command representations remain denied. Command registration -was verified against the upstream release's -[`register.ts`](https://github.com/openclaw/openclaw/blob/v2026.9.6/src/cli/cron-cli/register.ts), -[`register.cron-add.ts`](https://github.com/openclaw/openclaw/blob/v2026.9.6/src/cli/cron-cli/register.cron-add.ts), -[`register.cron-simple.ts`](https://github.com/openclaw/openclaw/blob/v2026.9.6/src/cli/cron-cli/register.cron-simple.ts) -and [`register.cron-edit.ts`](https://github.com/openclaw/openclaw/blob/v2026.9.6/src/cli/cron-cli/register.cron-edit.ts). - -`openclaw agents set-identity` requires approval for every invocation, including -ordinary name changes. In the pinned OpenClaw version, `--identity-file` can -read arbitrary paths and `--avatar` accepts HTTP(S) and data URIs; the command -also rewrites `openclaw.json`. Filesystem-tool workspace confinement does not -limit this CLI command. Cancelled, denied or timed-out approvals do not run it; -shell wrappers, chaining and substitutions remain denied. ->>>>>>> 552a620f (Allow OpenClaw automation create commands) From 2dadb18361e4ba30cbec682264886caabc183e9d Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 00:15:25 +0000 Subject: [PATCH 06/69] Add make saw-init and prepare this cluster for container workspaces make saw-init (scripts/saw-init.sh) prepares a cluster before ./pattern.sh make install or make saw-create. pattern-install and saw-create for container/kata run it first. With container or kata users it checks OVN-Kubernetes, AdminNetworkPolicy, ValidatingAdmissionPolicy and an anonymous pull of the runtime image from inside the cluster, and ensures a ReadWriteMany StorageClass for the audit exchange volume (scripts/shared-storage.sh): without one it creates a small in-cluster NFS server and provisioner (StorageClass saw-nfs, dev/demo) and verifies a read/write mount; SAW_SHARED_STORAGE=efs offers EFS on AWS, none reports. saw-users: a container user without ownerSubject on an installation configured for containers waits (ConfigMap saw-users-awaiting-owner) instead of failing the whole render. make saw-create accepts the minimal entry with the chart's defaults and resolves an omitted subject from Keycloak. make container-topology finds the ApplicationSet controller by its app.kubernetes.io/name label, fills missing storage classes and writes plain YAML. Add the generated overrides/container-network.yaml for this cluster to the saw-users value files. README (both install options) and docs/container-installation.md describe the flow. Assisted-By: Claude --- Makefile | 4 +- Makefile-quickstart | 6 +- README.md | 21 ++ charts/saw-users/templates/_helpers.tpl | 14 + charts/saw-users/templates/applications.yaml | 2 +- .../saw-users/templates/awaiting-owner.yaml | 15 + charts/saw-users/templates/namespaces.yaml | 2 +- charts/saw-users/templates/projector.yaml | 2 +- docs/container-installation.md | 21 ++ overrides/container-network.yaml | 250 +++++++++++++ scripts/container-workspace.py | 51 ++- scripts/container_topology.py | 33 +- scripts/saw-init.sh | 120 ++++++ scripts/shared-storage.sh | 342 ++++++++++++++++++ tests/charts/test_saw_users_chart.py | 12 + tests/scripts/test_container_installation.py | 26 ++ tests/scripts/test_container_topology.py | 6 +- values-prod.yaml | 2 + 18 files changed, 909 insertions(+), 20 deletions(-) create mode 100644 charts/saw-users/templates/awaiting-owner.yaml create mode 100644 overrides/container-network.yaml create mode 100755 scripts/saw-init.sh create mode 100755 scripts/shared-storage.sh 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 b309fc743..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-user-info \ + 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 @@ -439,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..a535466a7 100644 --- a/README.md +++ b/README.md @@ -284,6 +284,14 @@ 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 creates a +# small in-cluster NFS server for dev/demo; SAW_SHARED_STORAGE=efs offers EFS on +# AWS, =none only reports) 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. @@ -304,6 +312,15 @@ 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" +# Container workspace instead of a VM: add the Keycloak subject and mode, e.g. +# - name: alice +# ownerSubject: +# profiles: [custom-inference] +# values: {deployment: {mode: container}} +# Until ownerSubject is set the entry waits (ConfigMap saw-users-awaiting-owner) +# without blocking other users. Once, after Keycloak is up, generate the network +# overlay: make container-topology > overrides/container-network.yaml, then +# commit it. See docs/container-installation.md#minimal-static-entries. # 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). @@ -351,6 +368,10 @@ export OPENSHELL_SAW_NAME=alice # the user VM, deployed into namespace saw-a # 4. Verify prerequisites after CNV and RHBK are installed make quickstart-prereqs-check +# Container or kata workspaces (DEPLOYMENT_MODE=container|kata) also need +# OpenShift GitOps installed: their components are Argo CD Applications even +# here. `make saw-create` runs `make saw-init` first for those modes; run it +# now: without a shared-filesystem StorageClass it creates a small in-cluster NFS server. # This check does not change the cluster. It can save ingress-ca.pem here. # make images-mirror enables the registry route. diff --git a/charts/saw-users/templates/_helpers.tpl b/charts/saw-users/templates/_helpers.tpl index c0f8fc6c8..253313450 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 -}} @@ -531,3 +533,15 @@ skips empty values, so a per-user false/"" cannot unset a default. Returns JSON. {{- 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 ba309846e..659e0ef61 100644 --- a/charts/saw-users/templates/applications.yaml +++ b/charts/saw-users/templates/applications.yaml @@ -1,6 +1,6 @@ {{- 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 }} 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 eee2b9049..6e8ca308e 100644 --- a/charts/saw-users/templates/namespaces.yaml +++ b/charts/saw-users/templates/namespaces.yaml @@ -1,6 +1,6 @@ {{- 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 diff --git a/charts/saw-users/templates/projector.yaml b/charts/saw-users/templates/projector.yaml index 07f9cf399..de67c8591 100644 --- a/charts/saw-users/templates/projector.yaml +++ b/charts/saw-users/templates/projector.yaml @@ -1,7 +1,7 @@ {{- if .Values.projection.enabled }} {{- $users := list }} {{- range $user := .Values.users }} -{{- if has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata") }} +{{- 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 }} diff --git a/docs/container-installation.md b/docs/container-installation.md index 9d61bb790..5f4906034 100644 --- a/docs/container-installation.md +++ b/docs/container-installation.md @@ -536,6 +536,27 @@ to re-enroll. Keep the reviewed flow below for production clusters. 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` creates one for development and demo +clusters: a privileged NFS server Pod on a default-class volume in namespace +`saw-nfs`, the upstream NFS subdirectory provisioner and StorageClass `saw-nfs`, +then verifies a read/write mount. It is a single Pod with no replication. For +production, install a real shared filesystem first (ODF CephFS, EFS, vendor NFS); +`saw-init` then leaves storage alone. `SAW_SHARED_STORAGE=efs` instead 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, and +`SAW_SHARED_STORAGE=none` only reports. + +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/overrides/container-network.yaml b/overrides/container-network.yaml new file mode 100644 index 000000000..bbc0362c3 --- /dev/null +++ b/overrides/container-network.yaml @@ -0,0 +1,250 @@ +# Generated by `make container-topology` from overrides/saw-container-defaults.yaml. +# Re-run it (or `make check-container-topology`) when API, DNS or Keycloak addresses change. +containerDefaults: + stack: + gateway: + values: + oidc: + issuerUrl: https://openshell-keycloak-ingress-saw-keycloak.apps.ocp.qv4zq.sandbox5540.opentlc.com/realms/openshell + kubernetes: + network: + gatewayEgress: + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: openshell-agents + podSelector: + matchLabels: + app.kubernetes.io/name: governance-interceptor + 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 + - to: + - ipBlock: + cidr: 10.0.24.185/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.54.171/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.83.113/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: 3.133.196.240/32 + ports: + - protocol: TCP + port: 443 + - to: + - ipBlock: + cidr: 18.118.63.102/32 + ports: + - protocol: TCP + port: 443 + storage: + className: gp3-csi + proxy: + values: + network: + bootstrapEgress: + - to: + - ipBlock: + cidr: 10.0.24.185/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.54.171/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.83.113/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: gp3-csi + exchangeStorageClass: saw-nfs + automaticEnrollment: + relay: + issuer: https://openshell-keycloak-ingress-saw-keycloak.apps.ocp.qv4zq.sandbox5540.opentlc.com/realms/openshell + egress: + - to: + - ipBlock: + cidr: 10.0.24.185/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.54.171/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.83.113/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: 3.133.196.240/32 + ports: + - protocol: TCP + port: 443 + - to: + - ipBlock: + cidr: 18.118.63.102/32 + ports: + - protocol: TCP + port: 443 +projection: + egress: + - to: + - ipBlock: + cidr: 10.0.24.185/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.54.171/32 + ports: + - protocol: TCP + port: 6443 + - to: + - ipBlock: + cidr: 10.0.83.113/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/scripts/container-workspace.py b/scripts/container-workspace.py index 92409beb4..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 @@ -65,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): @@ -83,15 +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} - # Same derivation as the chart and portal when installationID is omitted. - if not user.get("installationID") and re.fullmatch(r"[a-f0-9]{16}", str(user.get("registration", ""))): - user["installationID"] = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:saw:portal:{name}:{user['registration']}")) + 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 fc58e6637..ea1771ab1 100644 --- a/scripts/container_topology.py +++ b/scripts/container_topology.py @@ -18,13 +18,24 @@ GATEWAY = ("stack", "gateway", "values") BOOTSTRAP = ("stack", "proxy", "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") + "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): @@ -106,11 +117,17 @@ def appset_controller_labels(values): 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") - pods = json.loads(command("oc", "get", "pods", "-n", namespace, "-l", - "app.kubernetes.io/component=applicationset-controller", "-o", "json")) - names = {p.get("metadata", {}).get("labels", {}).get("app.kubernetes.io/name") - for p in pods.get("items", []) if not p.get("metadata", {}).get("deletionTimestamp")} - names.discard(None) + # 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") @@ -244,7 +261,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) @@ -280,7 +297,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/saw-init.sh b/scripts/saw-init.sh new file mode 100755 index 000000000..34075b3ce --- /dev/null +++ b/scripts/saw-init.sh @@ -0,0 +1,120 @@ +#!/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) +EOF diff --git a/scripts/shared-storage.sh b/scripts/shared-storage.sh new file mode 100755 index 000000000..f158c4d42 --- /dev/null +++ b/scripts/shared-storage.sh @@ -0,0 +1,342 @@ +#!/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: +# nfs (default) -> create a small in-cluster NFS server and provisioner +# (StorageClass `saw-nfs`) and verify it. One Pod, no +# replication: fine for dev/demo, 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/. +# none -> print the options and fail +# 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 " - SAW_SHARED_STORAGE=nfs (default) sets up a small in-cluster NFS server (dev/demo)" + 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 + +# Default: a small NFS server inside the cluster, needing only cluster-admin. +# 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. Set SAW_SHARED_STORAGE=none or efs to change." + + 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:-nfs}" 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_saw_users_chart.py b/tests/charts/test_saw_users_chart.py index 52452fbc9..d41950af1 100644 --- a/tests/charts/test_saw_users_chart.py +++ b/tests/charts/test_saw_users_chart.py @@ -160,6 +160,18 @@ def bobs(docs): 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"}}} diff --git a/tests/scripts/test_container_installation.py b/tests/scripts/test_container_installation.py index f63e31bc0..fb95eb00f 100644 --- a/tests/scripts/test_container_installation.py +++ b/tests/scripts/test_container_installation.py @@ -42,6 +42,32 @@ 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"] diff --git a/tests/scripts/test_container_topology.py b/tests/scripts/test_container_topology.py index 9ec576d84..4e70b9887 100644 --- a/tests/scripts/test_container_topology.py +++ b/tests/scripts/test_container_topology.py @@ -46,9 +46,9 @@ def command(*args): "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", - "app.kubernetes.io/component": "applicationset-controller"}}}]}) + 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: diff --git a/values-prod.yaml b/values-prod.yaml index ee80f778e..260481206 100644 --- a/values-prod.yaml +++ b/values-prod.yaml @@ -113,6 +113,8 @@ clusterGroup: extraValueFiles: - /overrides/saw-container-defaults.yaml - /overrides/saw-users.yaml + # Generated by make container-topology; after the files it completes. + - /overrides/container-network.yaml overrides: - name: ownerResolution.enabled value: "true" From e3dab4e2cc96f5fb083fb65dbe3bf0ed81081e96 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 00:45:57 +0000 Subject: [PATCH 07/69] Use the OpenShift-ready OpenClaw image for container workspaces The stock OpenClaw image's /sandbox (0770, 1000:0) is not searchable by OpenShift namespace UIDs, so the projector preflight refused alice (WorkloadImageNotNamespaceAccessible). Point the data-science and custom-inference notebooks at the in-cluster rebuild from make container-notebook-image and grant pull access to its ImageStream. Assisted-By: Claude --- overrides/saw-container-defaults.yaml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml index 2c74fd65d..ddec72093 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -12,6 +12,17 @@ projection: enabled: true containerDefaults: + # Stock OpenClaw image rebuilt so OpenShift namespace UIDs can enter /sandbox + # (make container-notebook-image BUILD_NS=saw-component-builds BUILD_ARCH=amd64). + # Both profiles use the same source image. + profileImageOverrides: + data-science: + notebook: "image-registry.openshift-image-registry.svc:5000/saw-component-builds/saw-openclaw-896d1526ee29-amd64@sha256:5c923bbb2f244f0818e57c041370d10eea697204b4b63f558b7e907fb657f8e1" + custom-inference: + notebook: "image-registry.openshift-image-registry.svc:5000/saw-component-builds/saw-openclaw-896d1526ee29-amd64@sha256:5c923bbb2f244f0818e57c041370d10eea697204b4b63f558b7e907fb657f8e1" + imagePull: + namespace: saw-component-builds + streams: [saw-openclaw-896d1526ee29-amd64] governanceNamespace: openshell-agents providerAllowHosts: - api.inference.example.com From 1fd2a3e0e99e905f72e963c5639e5bc082700082 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 00:55:33 +0000 Subject: [PATCH 08/69] Approve the custom inference endpoint once for container workspaces The custom-inference workspace chart needs the endpoint URL itself (site.customInferenceURL), which comes from a site's profileBoundaries. Declare it in containerDefaults and let a static entry take the site-approved endpoint unless it names one; an autoApprove site needs no reviewed boundary reference. Assisted-By: Claude --- charts/openshell-rhdh/files/workspace.py | 9 ++++++++- charts/saw-users/files/workspace.py | 9 ++++++++- overrides/saw-container-defaults.yaml | 6 ++++++ tests/scripts/test_workspace_projection.py | 19 +++++++++++++++++++ 4 files changed, 41 insertions(+), 2 deletions(-) diff --git a/charts/openshell-rhdh/files/workspace.py b/charts/openshell-rhdh/files/workspace.py index 114dcd614..a5224307e 100644 --- a/charts/openshell-rhdh/files/workspace.py +++ b/charts/openshell-rhdh/files/workspace.py @@ -260,8 +260,15 @@ 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: + # 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, "providerAllowHosts": boundary["allowHosts"], - "automaticEnrollment": {**automatic, "reference": boundary["reference"]}} + "automaticEnrollment": {**automatic, **reviewed}} + # A static entry takes the site-approved endpoint unless it names one. + if (not ws.get("customInferenceURL") and boundary.get("inferenceBaseURL") + and any(sb.get("endpointInput") for _, sb in enabled_catalog_sandboxes(catalog[selected]))): + ws["customInferenceURL"] = boundary["inferenceBaseURL"] if ws.get("customInferenceURL"): if not boundary or boundary.get("inferenceBaseURL") != ws["customInferenceURL"]: raise WorkspaceError("endpoint differs from the site-approved custom inference URL") diff --git a/charts/saw-users/files/workspace.py b/charts/saw-users/files/workspace.py index 114dcd614..a5224307e 100644 --- a/charts/saw-users/files/workspace.py +++ b/charts/saw-users/files/workspace.py @@ -260,8 +260,15 @@ 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: + # 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, "providerAllowHosts": boundary["allowHosts"], - "automaticEnrollment": {**automatic, "reference": boundary["reference"]}} + "automaticEnrollment": {**automatic, **reviewed}} + # A static entry takes the site-approved endpoint unless it names one. + if (not ws.get("customInferenceURL") and boundary.get("inferenceBaseURL") + and any(sb.get("endpointInput") for _, sb in enabled_catalog_sandboxes(catalog[selected]))): + ws["customInferenceURL"] = boundary["inferenceBaseURL"] if ws.get("customInferenceURL"): if not boundary or boundary.get("inferenceBaseURL") != ws["customInferenceURL"]: raise WorkspaceError("endpoint differs from the site-approved custom inference URL") diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml index ddec72093..d7692a3a6 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -12,6 +12,12 @@ projection: enabled: true containerDefaults: + # The custom inference endpoint approved for custom-inference workspaces; + # its host must be the only allowed provider host for that profile. + profileBoundaries: + custom-inference: + inferenceBaseURL: https://api.inference.example.com/v1 + allowHosts: [api.inference.example.com] # Stock OpenClaw image rebuilt so OpenShift namespace UIDs can enter /sandbox # (make container-notebook-image BUILD_NS=saw-component-builds BUILD_ARCH=amd64). # Both profiles use the same source image. diff --git a/tests/scripts/test_workspace_projection.py b/tests/scripts/test_workspace_projection.py index 70b4fd7cf..56f9f6500 100644 --- a/tests/scripts/test_workspace_projection.py +++ b/tests/scripts/test_workspace_projection.py @@ -117,6 +117,25 @@ def test_auto_approve_accepts_the_observed_enrollment_but_still_binds_the_owner( lambda _: published(owner, subject="33333333-3333-4333-8333-333333333333")) +def test_auto_approve_site_endpoint_defaults_custom_inference_url(): + owner, _ = inputs() + owner.update(profiles=["custom-inference"]) + for key in ("lifecycleVersion", "initialModelInputs", "modelInputs", "desiredState", "restartGeneration"): + owner.pop(key) + site = auto_site(owner) + site["profileBoundaries"] = {"custom-inference": { + "inferenceBaseURL": "https://api.inference.example/v1", "allowHosts": ["api.inference.example"]}} + result = workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) + projected = result["containerSites"]["alice"] + assert projected["customInferenceURL"] == "https://api.inference.example/v1" + assert projected["providerAllowHosts"] == ["api.inference.example"] + assert "reference" not in projected["automaticEnrollment"] + assert result["users"][0]["customInferenceURL"] == "https://api.inference.example/v1" + owner["customInferenceURL"] = "https://elsewhere.example/v1" + with pytest.raises(workspace.WorkspaceError, match="endpoint differs"): + workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) + + def test_reviewed_site_still_rejects_an_unreviewed_enrollment(): owner, _ = inputs() site = auto_site(owner) From 6b175afdf2744b7d5172d90ad0586b2ffb5664df Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 01:05:31 +0000 Subject: [PATCH 09/69] Fix alice's audit identity and web-search secret Restore the audit writer's identity.subject ('@SUBJECT@'), lost when the site became containerDefaults; the audit Application failed to render. A dedicated-endpoint profile such as custom-inference gets no web-search credential unless the entry asks for one, as the portal does at registration; alice's web-search ExternalSecret had no Vault data. Assisted-By: Claude --- charts/openshell-rhdh/files/workspace.py | 4 ++++ charts/saw-users/files/workspace.py | 4 ++++ overrides/saw-container-defaults.yaml | 1 + tests/scripts/test_workspace_projection.py | 1 + 4 files changed, 10 insertions(+) diff --git a/charts/openshell-rhdh/files/workspace.py b/charts/openshell-rhdh/files/workspace.py index a5224307e..f2ad7a8f1 100644 --- a/charts/openshell-rhdh/files/workspace.py +++ b/charts/openshell-rhdh/files/workspace.py @@ -247,6 +247,10 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): 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} overrides = site.get("profileImageOverrides", {}).get(selected, {}) if overrides: ws["imageOverrides"] = overrides diff --git a/charts/saw-users/files/workspace.py b/charts/saw-users/files/workspace.py index a5224307e..f2ad7a8f1 100644 --- a/charts/saw-users/files/workspace.py +++ b/charts/saw-users/files/workspace.py @@ -247,6 +247,10 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): 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} overrides = site.get("profileImageOverrides", {}).get(selected, {}) if overrides: ws["imageOverrides"] = overrides diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml index d7692a3a6..79554980b 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -170,6 +170,7 @@ containerDefaults: ownerID: '@INSTALLATION@' image: ghcr.io/openclaw/openclaw@sha256:0a5ff5e682e62afa19149df126aa50063bf65ef885b5c94713ce32dc0eb12e15 identity: + subject: '@SUBJECT@' username: '@OWNER@' workspace: agent sandbox: audited diff --git a/tests/scripts/test_workspace_projection.py b/tests/scripts/test_workspace_projection.py index 56f9f6500..99277ab4a 100644 --- a/tests/scripts/test_workspace_projection.py +++ b/tests/scripts/test_workspace_projection.py @@ -131,6 +131,7 @@ def test_auto_approve_site_endpoint_defaults_custom_inference_url(): assert projected["providerAllowHosts"] == ["api.inference.example"] assert "reference" not in projected["automaticEnrollment"] assert result["users"][0]["customInferenceURL"] == "https://api.inference.example/v1" + assert result["users"][0]["webSearch"] == {"enabled": False} # dedicated endpoint, as in the portal owner["customInferenceURL"] = "https://elsewhere.example/v1" with pytest.raises(workspace.WorkspaceError, match="endpoint differs"): workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) From 02145fdaf7296f37a8288e52103921efa4022ef3 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 01:23:22 +0000 Subject: [PATCH 10/69] Name alice's model and require it for custom-inference entries The runtime compiles a sandbox's model from public model inputs, never from the credential Secret. Without one, alice's enrollment looped on ContractError (invalid sandbox inference inputs). Set modelInputs.inference.model on alice, and have the projector refuse a static entry whose profile requires a model it does not name, instead of an enrollment that never finishes. Assisted-By: Claude --- charts/openshell-rhdh/files/workspace.py | 11 +++++++++++ charts/saw-users/files/workspace.py | 11 +++++++++++ overrides/saw-users.yaml | 2 ++ tests/scripts/test_workspace_projection.py | 5 +++++ 4 files changed, 29 insertions(+) diff --git a/charts/openshell-rhdh/files/workspace.py b/charts/openshell-rhdh/files/workspace.py index f2ad7a8f1..21230e793 100644 --- a/charts/openshell-rhdh/files/workspace.py +++ b/charts/openshell-rhdh/files/workspace.py @@ -251,6 +251,17 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): # 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 diff --git a/charts/saw-users/files/workspace.py b/charts/saw-users/files/workspace.py index f2ad7a8f1..21230e793 100644 --- a/charts/saw-users/files/workspace.py +++ b/charts/saw-users/files/workspace.py @@ -251,6 +251,17 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): # 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 diff --git a/overrides/saw-users.yaml b/overrides/saw-users.yaml index f335db396..17cd449f4 100644 --- a/overrides/saw-users.yaml +++ b/overrides/saw-users.yaml @@ -10,6 +10,8 @@ users: ownerSubject: 9a30e84e-2a47-4b88-a2c2-7ba2bddc6dbf profiles: [custom-inference] vaultPrefix: secret/data/hub + modelInputs: + inference.model: rits/zai-org/glm-5-3 # public model name; the key stays in Vault values: deployment: {mode: container} diff --git a/tests/scripts/test_workspace_projection.py b/tests/scripts/test_workspace_projection.py index 99277ab4a..16e17fe21 100644 --- a/tests/scripts/test_workspace_projection.py +++ b/tests/scripts/test_workspace_projection.py @@ -122,6 +122,7 @@ def test_auto_approve_site_endpoint_defaults_custom_inference_url(): 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) site["profileBoundaries"] = {"custom-inference": { "inferenceBaseURL": "https://api.inference.example/v1", "allowHosts": ["api.inference.example"]}} @@ -132,6 +133,10 @@ def test_auto_approve_site_endpoint_defaults_custom_inference_url(): assert "reference" not in projected["automaticEnrollment"] assert result["users"][0]["customInferenceURL"] == "https://api.inference.example/v1" assert result["users"][0]["webSearch"] == {"enabled": False} # dedicated endpoint, as in the portal + del owner["modelInputs"] + with pytest.raises(workspace.WorkspaceError, match="set modelInputs.inference.model"): + workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) + owner["modelInputs"] = {"inference.model": "org/model"} owner["customInferenceURL"] = "https://elsewhere.example/v1" with pytest.raises(workspace.WorkspaceError, match="endpoint differs"): workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) From b82caead3ce044d05c0a04c1c1375844783a74ad Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 02:20:03 +0000 Subject: [PATCH 11/69] Remove alice's first container registration Its enrollment recorded the alice-gateway Service while it still carried the VM workspace's selector, so the reconciler rejects the boundary (BoundaryRejected) and cannot be repaired in place. Remove the registration; alice comes back as generation 2. Assisted-By: Claude --- overrides/saw-users.yaml | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/overrides/saw-users.yaml b/overrides/saw-users.yaml index 17cd449f4..e1bac0e2c 100644 --- a/overrides/saw-users.yaml +++ b/overrides/saw-users.yaml @@ -5,15 +5,10 @@ # (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. -users: - - name: alice - ownerSubject: 9a30e84e-2a47-4b88-a2c2-7ba2bddc6dbf - profiles: [custom-inference] - vaultPrefix: secret/data/hub - modelInputs: - inference.model: rits/zai-org/glm-5-3 # public model name; the key stays in Vault - values: - deployment: {mode: container} +# alice is re-registered as generation 2 (registration d2565216ccf6a6c0) once +# generation 1 (1f732dc2bd1766a0) has been removed; its enrollment approved a +# gateway Service left over from her VM workspace. +users: [] # Opt in only for users of a configured custom-inference endpoint. Match From e416694f954116d5c27fb809f9193964499c3138 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 03:11:01 +0000 Subject: [PATCH 12/69] Re-register alice as generation 2 A fresh container registration (d2565216ccf6a6c0) on the fixed defaults: rebuilt OpenClaw image, approved custom inference endpoint, model input, no web search, restored audit identity. Assisted-By: Claude --- overrides/saw-users.yaml | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/overrides/saw-users.yaml b/overrides/saw-users.yaml index e1bac0e2c..bb51828e5 100644 --- a/overrides/saw-users.yaml +++ b/overrides/saw-users.yaml @@ -5,10 +5,20 @@ # (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. -# alice is re-registered as generation 2 (registration d2565216ccf6a6c0) once -# generation 1 (1f732dc2bd1766a0) has been removed; its enrollment approved a -# gateway Service left over from her VM workspace. -users: [] +users: + - name: alice + # generation 2 = registration d2565216ccf6a6c0 (credentials at + # secret/data/hub/saw-alice/d2565216ccf6a6c0/inference). Generation 1 + # (1f732dc2bd1766a0) was removed: its enrollment approved a gateway + # Service left over from her VM workspace. + generation: 2 + ownerSubject: 9a30e84e-2a47-4b88-a2c2-7ba2bddc6dbf + profiles: [custom-inference] + vaultPrefix: secret/data/hub + modelInputs: + inference.model: rits/zai-org/glm-5-3 # public model name; the key stays in Vault + values: + deployment: {mode: container} # Opt in only for users of a configured custom-inference endpoint. Match From bfeb8fe704002ea7df6cee8fbf8bcc2b8ce25bce Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 03:58:12 +0000 Subject: [PATCH 13/69] Use the in-cluster governance interceptor build The published interceptor image predates mTLS operator access (118b4cfa), so it denies the container reconciler's CreateSandbox driver config. Assisted-By: Claude --- values-prod.yaml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/values-prod.yaml b/values-prod.yaml index 260481206..2b3fbd239 100644 --- a/values-prod.yaml +++ b/values-prod.yaml @@ -162,6 +162,13 @@ clusterGroup: name: governance-interceptor namespace: openshell-agents path: charts/governance-interceptor + # Built in-cluster (make governance-interceptor-build-local): the published + # image predates mTLS operator access (118b4cfa), which container + # reconcilers use to create sandboxes. + overrides: + - name: image + value: image-registry.openshift-image-registry.svc:5000/openshell-agents/governance-interceptor@sha256:2a1421a4b1960ef499ef9cb02f77bd49d78aa7a9081981877f2a93d5b205408e + forceString: true syncPolicy: automated: prune: true From 3c267af62ca324ff649bf6703306854937ad0048 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 04:36:27 +0000 Subject: [PATCH 14/69] Keep cluster-specific values out of the shared configuration Remove the generated network overlay (this cluster's API, DNS and Keycloak addresses), alice's entry, and images built in this cluster's registry or a fork. Each site generates and lists its own overlay, as docs/container-installation.md describes; image digests are placeholders. Assisted-By: Claude --- README.md | 6 +- overrides/container-network.yaml | 250 ------------------ .../governance-profiles/custom-inference.yaml | 2 +- overrides/saw-container-defaults.yaml | 13 +- overrides/saw-users.yaml | 34 +-- scripts/saw-init.sh | 3 +- values-prod.yaml | 9 - 7 files changed, 28 insertions(+), 289 deletions(-) delete mode 100644 overrides/container-network.yaml diff --git a/README.md b/README.md index a535466a7..40188e8d5 100644 --- a/README.md +++ b/README.md @@ -319,8 +319,10 @@ make saw-logs OPENSHELL_SAW_NAME=alice # until "apply: Done" # values: {deployment: {mode: container}} # Until ownerSubject is set the entry waits (ConfigMap saw-users-awaiting-owner) # without blocking other users. Once, after Keycloak is up, generate the network -# overlay: make container-topology > overrides/container-network.yaml, then -# commit it. See docs/container-installation.md#minimal-static-entries. +# overlay: make container-topology > overrides/container-network.yaml, commit +# it on your fork and list it after saw-users.yaml in saw-users' +# extraValueFiles (it holds this cluster's addresses, so it is not in this +# repository). See docs/container-installation.md#minimal-static-entries. # 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). diff --git a/overrides/container-network.yaml b/overrides/container-network.yaml deleted file mode 100644 index bbc0362c3..000000000 --- a/overrides/container-network.yaml +++ /dev/null @@ -1,250 +0,0 @@ -# Generated by `make container-topology` from overrides/saw-container-defaults.yaml. -# Re-run it (or `make check-container-topology`) when API, DNS or Keycloak addresses change. -containerDefaults: - stack: - gateway: - values: - oidc: - issuerUrl: https://openshell-keycloak-ingress-saw-keycloak.apps.ocp.qv4zq.sandbox5540.opentlc.com/realms/openshell - kubernetes: - network: - gatewayEgress: - - to: - - namespaceSelector: - matchLabels: - kubernetes.io/metadata.name: openshell-agents - podSelector: - matchLabels: - app.kubernetes.io/name: governance-interceptor - 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 - - to: - - ipBlock: - cidr: 10.0.24.185/32 - ports: - - protocol: TCP - port: 6443 - - to: - - ipBlock: - cidr: 10.0.54.171/32 - ports: - - protocol: TCP - port: 6443 - - to: - - ipBlock: - cidr: 10.0.83.113/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: 3.133.196.240/32 - ports: - - protocol: TCP - port: 443 - - to: - - ipBlock: - cidr: 18.118.63.102/32 - ports: - - protocol: TCP - port: 443 - storage: - className: gp3-csi - proxy: - values: - network: - bootstrapEgress: - - to: - - ipBlock: - cidr: 10.0.24.185/32 - ports: - - protocol: TCP - port: 6443 - - to: - - ipBlock: - cidr: 10.0.54.171/32 - ports: - - protocol: TCP - port: 6443 - - to: - - ipBlock: - cidr: 10.0.83.113/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: gp3-csi - exchangeStorageClass: saw-nfs - automaticEnrollment: - relay: - issuer: https://openshell-keycloak-ingress-saw-keycloak.apps.ocp.qv4zq.sandbox5540.opentlc.com/realms/openshell - egress: - - to: - - ipBlock: - cidr: 10.0.24.185/32 - ports: - - protocol: TCP - port: 6443 - - to: - - ipBlock: - cidr: 10.0.54.171/32 - ports: - - protocol: TCP - port: 6443 - - to: - - ipBlock: - cidr: 10.0.83.113/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: 3.133.196.240/32 - ports: - - protocol: TCP - port: 443 - - to: - - ipBlock: - cidr: 18.118.63.102/32 - ports: - - protocol: TCP - port: 443 -projection: - egress: - - to: - - ipBlock: - cidr: 10.0.24.185/32 - ports: - - protocol: TCP - port: 6443 - - to: - - ipBlock: - cidr: 10.0.54.171/32 - ports: - - protocol: TCP - port: 6443 - - to: - - ipBlock: - cidr: 10.0.83.113/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 ba03baf29..08bcbf272 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.inference.example.com # the host of the `url` in the inference Secret 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 index 79554980b..ccaabc9ac 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -8,6 +8,8 @@ # by `make container-topology` into overrides/container-network.yaml, as are # storage classes left unset here (the cluster default for single-node volumes, # a shared-filesystem class such as CephFS for the audit exchange volume). +# That overlay holds one cluster's addresses: commit it on your fork and list +# it after /overrides/saw-users.yaml in saw-users' extraValueFiles. projection: enabled: true @@ -23,9 +25,9 @@ containerDefaults: # Both profiles use the same source image. profileImageOverrides: data-science: - notebook: "image-registry.openshift-image-registry.svc:5000/saw-component-builds/saw-openclaw-896d1526ee29-amd64@sha256:5c923bbb2f244f0818e57c041370d10eea697204b4b63f558b7e907fb657f8e1" + notebook: "image-registry.openshift-image-registry.svc:5000/saw-component-builds/saw-openclaw-896d1526ee29-amd64@sha256:" custom-inference: - notebook: "image-registry.openshift-image-registry.svc:5000/saw-component-builds/saw-openclaw-896d1526ee29-amd64@sha256:5c923bbb2f244f0818e57c041370d10eea697204b4b63f558b7e907fb657f8e1" + notebook: "image-registry.openshift-image-registry.svc:5000/saw-component-builds/saw-openclaw-896d1526ee29-amd64@sha256:" imagePull: namespace: saw-component-builds streams: [saw-openclaw-896d1526ee29-amd64] @@ -35,10 +37,9 @@ containerDefaults: automaticEnrollment: enabled: true autoApprove: true # dev/demo cluster: enroll on first observation, no manual review - # CI build of main f582a118 in the sauagarwa fork (public, multi-arch); - # tag sha-f582a1183dc13ee15f8df4349e8467c981a39250. Switch to the - # validatedpatterns-sandbox package once it is public. - image: ghcr.io/sauagarwa/saw-kubernetes-runtime@sha256:78ea2cf9eebdbf6b350fff43175e034724f22def60bdf03b4fb014f54430221d + # The saw-kubernetes-runtime image, pinned by digest and pullable + # anonymously from inside the cluster (make saw-init checks this). + image: ghcr.io/validatedpatterns-sandbox/saw-kubernetes-runtime@sha256: buildNamespace: saw-component-builds resources: requests: {cpu: 500m, memory: 1Gi} diff --git a/overrides/saw-users.yaml b/overrides/saw-users.yaml index bb51828e5..f84ad89e6 100644 --- a/overrides/saw-users.yaml +++ b/overrides/saw-users.yaml @@ -5,26 +5,20 @@ # (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. -users: - - name: alice - # generation 2 = registration d2565216ccf6a6c0 (credentials at - # secret/data/hub/saw-alice/d2565216ccf6a6c0/inference). Generation 1 - # (1f732dc2bd1766a0) was removed: its enrollment approved a gateway - # Service left over from her VM workspace. - generation: 2 - ownerSubject: 9a30e84e-2a47-4b88-a2c2-7ba2bddc6dbf - profiles: [custom-inference] - vaultPrefix: secret/data/hub - modelInputs: - inference.model: rits/zai-org/glm-5-3 # public model name; the key stays in Vault - values: - deployment: {mode: container} - +# - name: alice +# ownerSubject: +# profiles: [custom-inference] +# vaultPrefix: secret/data/hub +# modelInputs: +# inference.model: +# values: +# deployment: {mode: container} +users: [] # Opt in only for users of a configured custom-inference endpoint. Match # the hostname in overrides/governance-profiles/custom-inference.yaml. -defaults: - openshellSaw: - egress: - extraAllow: - - api.inference.example.com +# defaults: +# openshellSaw: +# egress: +# extraAllow: +# - api.inference.example.com diff --git a/scripts/saw-init.sh b/scripts/saw-init.sh index 34075b3ce..8c0cd40d5 100755 --- a/scripts/saw-init.sh +++ b/scripts/saw-init.sh @@ -116,5 +116,6 @@ 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) + - 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/values-prod.yaml b/values-prod.yaml index 2b3fbd239..ee80f778e 100644 --- a/values-prod.yaml +++ b/values-prod.yaml @@ -113,8 +113,6 @@ clusterGroup: extraValueFiles: - /overrides/saw-container-defaults.yaml - /overrides/saw-users.yaml - # Generated by make container-topology; after the files it completes. - - /overrides/container-network.yaml overrides: - name: ownerResolution.enabled value: "true" @@ -162,13 +160,6 @@ clusterGroup: name: governance-interceptor namespace: openshell-agents path: charts/governance-interceptor - # Built in-cluster (make governance-interceptor-build-local): the published - # image predates mTLS operator access (118b4cfa), which container - # reconcilers use to create sandboxes. - overrides: - - name: image - value: image-registry.openshift-image-registry.svc:5000/openshell-agents/governance-interceptor@sha256:2a1421a4b1960ef499ef9cb02f77bd49d78aa7a9081981877f2a93d5b205408e - forceString: true syncPolicy: automated: prune: true From d3f7d722805f8ba565643c3cf38f8f9b6f54bbcc Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 04:53:19 +0000 Subject: [PATCH 15/69] Let the RHDH portal create container workspaces from containerDefaults The portal layers containerDefaults under each user's site, looks up the owner's Keycloak subject, follows the branch revision and honours autoApprove, so the create form offers container mode without per-user containerSites. Preflight accepts branch revisions as well as commit SHAs. Assisted-By: Claude --- charts/openshell-rhdh/files/portal.py | 86 ++++++++++++++++--- charts/openshell-rhdh/files/preflight.py | 11 ++- charts/openshell-rhdh/templates/_helpers.tpl | 21 ++++- .../saw-portal-container/files/preflight.py | 11 ++- charts/saw-users/files/preflight.py | 11 ++- overrides/saw-container-defaults.yaml | 5 ++ values-prod.yaml | 4 + 7 files changed, 129 insertions(+), 20 deletions(-) diff --git a/charts/openshell-rhdh/files/portal.py b/charts/openshell-rhdh/files/portal.py index 5e8c5232a..43a188ca8 100644 --- a/charts/openshell-rhdh/files/portal.py +++ b/charts/openshell-rhdh/files/portal.py @@ -394,17 +394,80 @@ 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) + revision = os.environ.get("SAW_TARGET_REVISION", "") + if revision: + for item in (site.get("stack") or {}).values(): + 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 +491,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 +808,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) @@ -1327,7 +1392,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 +1739,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") + @@ -1723,7 +1788,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 +1965,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..df8b13303 100644 --- a/charts/openshell-rhdh/files/preflight.py +++ b/charts/openshell-rhdh/files/preflight.py @@ -196,6 +196,11 @@ def check_observations(mode, observations): return tuple(required) +# A full commit SHA pins the charts; a branch follows the pattern (saw-users and +# portal defaults use global.targetRevision when a site sets no revision). +GIT_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): @@ -206,14 +211,14 @@ def configuration_facts(site): required_components = ("identity", "policy", "proxy", "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(GIT_REVISION, 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) + isinstance(value, str) and re.fullmatch(GIT_REVISION, value) for value in revisions) enrollment = site.get("automaticEnrollment") or {} 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(GIT_REVISION, str(enrollment.get("revision", "")))) image_values = [] storage_values = [] 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/saw-portal-container/files/preflight.py b/charts/saw-portal-container/files/preflight.py index c32862180..df8b13303 100644 --- a/charts/saw-portal-container/files/preflight.py +++ b/charts/saw-portal-container/files/preflight.py @@ -196,6 +196,11 @@ def check_observations(mode, observations): return tuple(required) +# A full commit SHA pins the charts; a branch follows the pattern (saw-users and +# portal defaults use global.targetRevision when a site sets no revision). +GIT_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): @@ -206,14 +211,14 @@ def configuration_facts(site): required_components = ("identity", "policy", "proxy", "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(GIT_REVISION, 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) + isinstance(value, str) and re.fullmatch(GIT_REVISION, value) for value in revisions) enrollment = site.get("automaticEnrollment") or {} 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(GIT_REVISION, str(enrollment.get("revision", "")))) image_values = [] storage_values = [] diff --git a/charts/saw-users/files/preflight.py b/charts/saw-users/files/preflight.py index c32862180..df8b13303 100644 --- a/charts/saw-users/files/preflight.py +++ b/charts/saw-users/files/preflight.py @@ -196,6 +196,11 @@ def check_observations(mode, observations): return tuple(required) +# A full commit SHA pins the charts; a branch follows the pattern (saw-users and +# portal defaults use global.targetRevision when a site sets no revision). +GIT_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): @@ -206,14 +211,14 @@ def configuration_facts(site): required_components = ("identity", "policy", "proxy", "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(GIT_REVISION, 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) + isinstance(value, str) and re.fullmatch(GIT_REVISION, value) for value in revisions) enrollment = site.get("automaticEnrollment") or {} 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(GIT_REVISION, str(enrollment.get("revision", "")))) image_values = [] storage_values = [] diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml index ccaabc9ac..7027c70e5 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -13,6 +13,11 @@ projection: enabled: true +# Self-service portal (openshell-rhdh reads this file too): offer Container next +# to VM. Any Keycloak user may request it; their site is containerDefaults. +portal: + deploymentModes: [vm, container, kata] + containerDefaults: # The custom inference endpoint approved for custom-inference workspaces; # its host must be the only allowed provider host for that profile. diff --git a/values-prod.yaml b/values-prod.yaml index ee80f778e..9bf24733c 100644 --- a/values-prod.yaml +++ b/values-prod.yaml @@ -136,6 +136,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 From 806545259d6bfa77c68667a1a3c2faec71bbe0a7 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 04:58:07 +0000 Subject: [PATCH 16/69] Allow branch revisions only for autoApprove sites Reviewed sites keep the full commit SHA pin on every chart; development sites with automaticEnrollment.autoApprove may follow a branch, as saw-users and the portal defaults do through global.targetRevision. Assisted-By: Claude --- charts/openshell-rhdh/files/preflight.py | 18 +++++++++++------- charts/saw-portal-container/files/preflight.py | 18 +++++++++++------- charts/saw-users/files/preflight.py | 18 +++++++++++------- tests/scripts/test_saw_preflight.py | 8 ++++++++ 4 files changed, 41 insertions(+), 21 deletions(-) diff --git a/charts/openshell-rhdh/files/preflight.py b/charts/openshell-rhdh/files/preflight.py index df8b13303..fbcdf03ba 100644 --- a/charts/openshell-rhdh/files/preflight.py +++ b/charts/openshell-rhdh/files/preflight.py @@ -196,9 +196,11 @@ def check_observations(mode, observations): return tuple(required) -# A full commit SHA pins the charts; a branch follows the pattern (saw-users and -# portal defaults use global.targetRevision when a site sets no revision). -GIT_REVISION = r"[a-f0-9]{40}|[A-Za-z0-9][A-Za-z0-9._/-]*" +# 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): @@ -207,18 +209,20 @@ def configuration_facts(site): 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") revision_pin = all(isinstance(stack.get(name), dict) for name in required_components) and all( isinstance(stack[name].get("revision"), str) - and re.fullmatch(GIT_REVISION, 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(GIT_REVISION, 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(GIT_REVISION, str(enrollment.get("revision", "")))) + revision_pin = revision_pin and bool(re.fullmatch(revision_pattern, str(enrollment.get("revision", "")))) image_values = [] storage_values = [] diff --git a/charts/saw-portal-container/files/preflight.py b/charts/saw-portal-container/files/preflight.py index df8b13303..fbcdf03ba 100644 --- a/charts/saw-portal-container/files/preflight.py +++ b/charts/saw-portal-container/files/preflight.py @@ -196,9 +196,11 @@ def check_observations(mode, observations): return tuple(required) -# A full commit SHA pins the charts; a branch follows the pattern (saw-users and -# portal defaults use global.targetRevision when a site sets no revision). -GIT_REVISION = r"[a-f0-9]{40}|[A-Za-z0-9][A-Za-z0-9._/-]*" +# 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): @@ -207,18 +209,20 @@ def configuration_facts(site): 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") revision_pin = all(isinstance(stack.get(name), dict) for name in required_components) and all( isinstance(stack[name].get("revision"), str) - and re.fullmatch(GIT_REVISION, 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(GIT_REVISION, 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(GIT_REVISION, str(enrollment.get("revision", "")))) + revision_pin = revision_pin and bool(re.fullmatch(revision_pattern, str(enrollment.get("revision", "")))) image_values = [] storage_values = [] diff --git a/charts/saw-users/files/preflight.py b/charts/saw-users/files/preflight.py index df8b13303..fbcdf03ba 100644 --- a/charts/saw-users/files/preflight.py +++ b/charts/saw-users/files/preflight.py @@ -196,9 +196,11 @@ def check_observations(mode, observations): return tuple(required) -# A full commit SHA pins the charts; a branch follows the pattern (saw-users and -# portal defaults use global.targetRevision when a site sets no revision). -GIT_REVISION = r"[a-f0-9]{40}|[A-Za-z0-9][A-Za-z0-9._/-]*" +# 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): @@ -207,18 +209,20 @@ def configuration_facts(site): 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") revision_pin = all(isinstance(stack.get(name), dict) for name in required_components) and all( isinstance(stack[name].get("revision"), str) - and re.fullmatch(GIT_REVISION, 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(GIT_REVISION, 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(GIT_REVISION, str(enrollment.get("revision", "")))) + revision_pin = revision_pin and bool(re.fullmatch(revision_pattern, str(enrollment.get("revision", "")))) image_values = [] storage_values = [] diff --git a/tests/scripts/test_saw_preflight.py b/tests/scripts/test_saw_preflight.py index c8a288b3f..885814d88 100644 --- a/tests/scripts/test_saw_preflight.py +++ b/tests/scripts/test_saw_preflight.py @@ -223,6 +223,14 @@ def test_site_configuration_requires_pinned_sources_and_scoped_egress(): 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 From 1bef65b7a63d54f521b41a39dc6a049701f2cf6d Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 04:59:01 +0000 Subject: [PATCH 17/69] Treat a repeat autoApprove enrollment as already done A chart change starts a new enrollment Job. Under autoApprove it observed the boundary again, now including the running workspace, and failed against the immutable first publication. If this registration already published, report it and exit; reviewed sites keep the strict comparison. Assisted-By: Claude --- charts/saw-portal-container/files/enroll.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/charts/saw-portal-container/files/enroll.py b/charts/saw-portal-container/files/enroll.py index 918a3da0e..227171b2f 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"]) From d1d6319073aeb6740db7d0c64b24873957adecff Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 22:21:23 -0500 Subject: [PATCH 18/69] Use OpenShell's native providers in container mode Container workspaces now hand credentials to OpenShell providers and drop SAW's credential proxy, its hard-coded provider list, and the boundary checks that mirrored the proxy policy. The runtime controller reads each site-approved Secret just in time and submits it with CreateProvider or UpdateProvider. OpenShell's provider profiles decide which endpoints the supervisor may substitute the credential for. Providers with oauth2_refresh_token (Gmail) are configured through ConfigureProviderRefresh and RotateProviderCredential. - credentialBindings replaces proxyBindings throughout the site config - saw-kubernetes-proxy chart removed; identity owns bootstrapEgress - saw-runtime-policies: optional publicHTTPS lets supervisors reach public 443 while private ranges stay denied - VM mode is unchanged Assisted-By: Claude --- charts/openshell-rhdh/files/preflight.py | 26 +- charts/openshell-rhdh/files/workspace.py | 3 +- .../templates/_helpers.tpl | 2 +- .../templates/gateway-config.yaml | 2 + .../templates/gateway.yaml | 4 + .../templates/controller.yaml | 10 +- .../values.schema.json | 40 ++++ charts/saw-kubernetes-proxy/Chart.yaml | 5 - .../saw-kubernetes-proxy/files/project_ca.py | 145 ----------- .../saw-kubernetes-proxy/templates/proxy.yaml | 226 ------------------ .../saw-kubernetes-proxy/values.schema.json | 111 --------- charts/saw-kubernetes-proxy/values.yaml | 17 -- charts/saw-portal-container/files/enroll.py | 8 +- .../files/portal_contract.py | 14 -- .../saw-portal-container/files/preflight.py | 26 +- .../templates/auto-enroll.yaml | 12 +- .../templates/enrolled-runtime.yaml | 7 +- .../templates/foundation.yaml | 13 +- .../saw-portal-container/templates/stack.yaml | 24 +- .../templates/admin-network-policy.yaml | 16 ++ .../saw-runtime-policies/values.schema.json | 3 + charts/saw-runtime-policies/values.yaml | 7 +- charts/saw-users/files/preflight.py | 26 +- charts/saw-users/files/workspace.py | 3 +- charts/saw-users/templates/applications.yaml | 16 +- docs/container-installation.md | 3 +- docs/container-workspaces.md | 25 +- kubernetes-runtime/saw_kubernetes/boundary.py | 20 +- kubernetes-runtime/saw_kubernetes/compiler.py | 42 ++-- kubernetes-runtime/saw_kubernetes/harness.py | 3 +- .../saw_kubernetes/portal_contract.py | 14 -- kubernetes-runtime/saw_kubernetes/provider.py | 85 ++----- .../saw_kubernetes/reconcile.py | 143 ++++++++--- kubernetes-runtime/saw_kubernetes/serve.py | 32 ++- overrides/saw-container-defaults.yaml | 45 +--- scripts/ci/deployment_validation.py | 2 +- scripts/container_topology.py | 2 +- tests/charts/test_portal_container.py | 39 +-- tests/charts/test_saw_kubernetes_chart.py | 9 + .../charts/test_saw_kubernetes_proxy_chart.py | 67 ------ tests/charts/test_saw_runtime_policies.py | 18 ++ tests/charts/test_saw_users_chart.py | 8 +- tests/fixtures/container-site.yaml | 159 +++--------- tests/kubernetes_runtime/profile_fixtures.py | 7 +- tests/kubernetes_runtime/test_boundary.py | 10 +- tests/kubernetes_runtime/test_briefing.py | 10 +- .../test_custom_inference.py | 33 +-- .../test_inference_providers.py | 15 +- tests/kubernetes_runtime/test_openclaw.py | 15 +- .../test_portal_contract.py | 11 +- .../kubernetes_runtime/test_portal_profile.py | 2 +- .../test_provider_governance.py | 20 -- .../test_provider_recovery.py | 52 +++- .../test_provider_refresh.py | 93 +++++++ .../test_proxy_ca_projection.py | 126 ---------- tests/scripts/test_container_installation.py | 1 - tests/scripts/test_container_topology.py | 4 +- tests/scripts/test_saw_preflight.py | 27 +-- tests/scripts/test_workspace_projection.py | 2 +- 59 files changed, 621 insertions(+), 1289 deletions(-) delete mode 100644 charts/saw-kubernetes-proxy/Chart.yaml delete mode 100644 charts/saw-kubernetes-proxy/files/project_ca.py delete mode 100644 charts/saw-kubernetes-proxy/templates/proxy.yaml delete mode 100644 charts/saw-kubernetes-proxy/values.schema.json delete mode 100644 charts/saw-kubernetes-proxy/values.yaml delete mode 100644 tests/charts/test_saw_kubernetes_proxy_chart.py delete mode 100644 tests/kubernetes_runtime/test_provider_governance.py create mode 100644 tests/kubernetes_runtime/test_provider_refresh.py delete mode 100644 tests/kubernetes_runtime/test_proxy_ca_projection.py diff --git a/charts/openshell-rhdh/files/preflight.py b/charts/openshell-rhdh/files/preflight.py index fbcdf03ba..dc499183c 100644 --- a/charts/openshell-rhdh/files/preflight.py +++ b/charts/openshell-rhdh/files/preflight.py @@ -213,7 +213,7 @@ def configuration_facts(site): 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(revision_pattern, stack[name]["revision"]) @@ -242,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 21230e793..30161a0fe 100644 --- a/charts/openshell-rhdh/files/workspace.py +++ b/charts/openshell-rhdh/files/workspace.py @@ -278,8 +278,7 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): # 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, "providerAllowHosts": boundary["allowHosts"], - "automaticEnrollment": {**automatic, **reviewed}} + site = {**site, "automaticEnrollment": {**automatic, **reviewed}} # A static entry takes the site-approved endpoint unless it names one. if (not ws.get("customInferenceURL") and boundary.get("inferenceBaseURL") and any(sb.get("endpointInput") for _, sb in enabled_catalog_sandboxes(catalog[selected]))): 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/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 227171b2f..0179ffb97 100644 --- a/charts/saw-portal-container/files/enroll.py +++ b/charts/saw-portal-container/files/enroll.py @@ -84,7 +84,7 @@ 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): @@ -129,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 fbcdf03ba..dc499183c 100644 --- a/charts/saw-portal-container/files/preflight.py +++ b/charts/saw-portal-container/files/preflight.py @@ -213,7 +213,7 @@ def configuration_facts(site): 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(revision_pattern, stack[name]["revision"]) @@ -242,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/auto-enroll.yaml b/charts/saw-portal-container/templates/auto-enroll.yaml index 16a3ef028..3aceaf174 100644 --- a/charts/saw-portal-container/templates/auto-enroll.yaml +++ b/charts/saw-portal-container/templates/auto-enroll.yaml @@ -1,7 +1,7 @@ {{- $s := .Values.site | default dict }}{{- $a := $s.automaticEnrollment | default dict }} {{- if and $a (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 "^[A-Za-z0-9][A-Za-z0-9._/-]*$" ($a.revision | default ""))) (and (not $autoApprove) (ne (len ($a.reference | default dict)) (ternary 27 25 (not (empty $s.kataRuntimeClass))))) }}{{ fail "automatic enrollment requires a pinned image, a Git revision and a reviewed boundary (or autoApprove)" }}{{- end }} +{{- if or (not (regexMatch "^.+@sha256:[a-f0-9]{64}$" $a.image)) (not (regexMatch "^[A-Za-z0-9][A-Za-z0-9._/-]*$" ($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 Git revision and a reviewed boundary (or autoApprove)" }}{{- 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 }} @@ -9,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 | default dict) "autoApprove" $autoApprove "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 -}} @@ -49,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]} @@ -111,7 +109,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..f1621368c 100644 --- a/charts/saw-portal-container/templates/enrolled-runtime.yaml +++ b/charts/saw-portal-container/templates/enrolled-runtime.yaml @@ -83,6 +83,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 @@ -112,7 +114,8 @@ spec: 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 +127,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..acd47782a 100644 --- a/charts/saw-portal-container/templates/foundation.yaml +++ b/charts/saw-portal-container/templates/foundation.yaml @@ -31,17 +31,12 @@ 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 }} -{{- $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 }} +{{- range required "explicit credential bindings required" (.Values.site | default dict).credentialBindings }} +{{- if eq .type "custom-inference" }}{{- $customSecret = .secret }}{{- end }} +{{- $fields := append (get $sources .secret | default list) .key }} +{{- if .refresh }}{{- $fields = concat $fields (list "client_id" "client_secret" "refresh_token") }}{{- 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/stack.yaml b/charts/saw-portal-container/templates/stack.yaml index 6f61d9ca9..4219a3df0 100644 --- a/charts/saw-portal-container/templates/stack.yaml +++ b/charts/saw-portal-container/templates/stack.yaml @@ -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,14 +60,8 @@ 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))) }} @@ -100,18 +94,10 @@ data: {{- $_ := 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 "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-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..1356e4c80 100644 --- a/charts/saw-runtime-policies/values.yaml +++ b/charts/saw-runtime-policies/values.yaml @@ -10,9 +10,12 @@ 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); OpenShell's network + # policy then decides which hosts each sandbox may actually use. + 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/preflight.py b/charts/saw-users/files/preflight.py index fbcdf03ba..dc499183c 100644 --- a/charts/saw-users/files/preflight.py +++ b/charts/saw-users/files/preflight.py @@ -213,7 +213,7 @@ def configuration_facts(site): 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(revision_pattern, stack[name]["revision"]) @@ -242,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/workspace.py b/charts/saw-users/files/workspace.py index 21230e793..30161a0fe 100644 --- a/charts/saw-users/files/workspace.py +++ b/charts/saw-users/files/workspace.py @@ -278,8 +278,7 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): # 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, "providerAllowHosts": boundary["allowHosts"], - "automaticEnrollment": {**automatic, **reviewed}} + site = {**site, "automaticEnrollment": {**automatic, **reviewed}} # A static entry takes the site-approved endpoint unless it names one. if (not ws.get("customInferenceURL") and boundary.get("inferenceBaseURL") and any(sb.get("endpointInput") for _, sb in enabled_catalog_sandboxes(catalog[selected]))): diff --git a/charts/saw-users/templates/applications.yaml b/charts/saw-users/templates/applications.yaml index 659e0ef61..e3323bd5a 100644 --- a/charts/saw-users/templates/applications.yaml +++ b/charts/saw-users/templates/applications.yaml @@ -30,11 +30,21 @@ {{- $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/docs/container-installation.md b/docs/container-installation.md index 5f4906034..96a212ebd 100644 --- a/docs/container-installation.md +++ b/docs/container-installation.md @@ -91,9 +91,8 @@ field. 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.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 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.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. | diff --git a/docs/container-workspaces.md b/docs/container-workspaces.md index d6d5bfb18..04374f302 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. | @@ -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,12 @@ 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`); OpenShell's + network policy decides which hosts each sandbox may actually use. - **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 +228,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 +257,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/kubernetes-runtime/saw_kubernetes/boundary.py b/kubernetes-runtime/saw_kubernetes/boundary.py index ea2c1c667..9bce4f676 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"), } @@ -105,19 +100,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 +130,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..bb692cc22 100644 --- a/kubernetes-runtime/saw_kubernetes/compiler.py +++ b/kubernetes-runtime/saw_kubernetes/compiler.py @@ -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 @@ -425,7 +434,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/harness.py b/kubernetes-runtime/saw_kubernetes/harness.py index eadc2a73d..308a13fea 100644 --- a/kubernetes-runtime/saw_kubernetes/harness.py +++ b/kubernetes-runtime/saw_kubernetes/harness.py @@ -36,7 +36,8 @@ 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): 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/provider.py b/kubernetes-runtime/saw_kubernetes/provider.py index c917691b6..141f2205f 100644 --- a/kubernetes-runtime/saw_kubernetes/provider.py +++ b/kubernetes-runtime/saw_kubernetes/provider.py @@ -1,4 +1,10 @@ -"""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 only tells the agent which environment variable holds its inference key +and checks the site's custom inference URL. +""" import re import ipaddress from functools import lru_cache @@ -10,18 +16,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 +35,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 +44,11 @@ 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 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 check_policy(kind, credentials, policy, custom_url=None): - slot, hosts = requirements(kind, custom_url) +def inference_key_env(kind): + """The env var the agent reads its inference key from (an OpenShell placeholder).""" 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_INFERENCE_API_KEY" + if kind not in INFERENCE: + raise ValueError("not an inference provider") + slot, = _shipped(kind)["credentials"] + return slot["env_vars"][0] diff --git a/kubernetes-runtime/saw_kubernetes/reconcile.py b/kubernetes-runtime/saw_kubernetes/reconcile.py index 04bcbd073..ecf988fca 100644 --- a/kubernetes-runtime/saw_kubernetes/reconcile.py +++ b/kubernetes-runtime/saw_kubernetes/reconcile.py @@ -16,7 +16,6 @@ from types import SimpleNamespace from .core import shared -from . import provider as governed from .compiler import ContractError, MANAGED, OWNER, REVISION, SOURCE_REVISION, digest, request_id @@ -102,8 +101,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 +127,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: @@ -238,19 +244,17 @@ 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 enforces where this credential may go (the profile's + # endpoints); we only need the variable the sandbox reads it from. 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.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/")): @@ -357,34 +361,40 @@ 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") + request = {k: v for k, v in provider.items() if k != "credentialRef"} + source = None + if ref: + if not callable(self.read_credential): + raise ContractError("no credential source configured", safe_reason="ProviderRejected") + 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 +405,79 @@ 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", + if ref: + recorded = revisions.get(reference, {}) + if (recorded.get("version") != existing["metadata"].get("resource_version") + or recorded.get("provider") != digest(provider)): + 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 provider.get("refresh"): + # The Secret rotated: hand OpenShell the new value. + reply = self._mutate("UpdateProvider", {**scope, "provider": request}, plan, generation, + identity=identity) + if reply: + self._record_provider(ws, pname, reply, plan, state, identity) + self.store.save(state) + pending.append(f"provider/{reference}") + return False + expected_credentials = dict.fromkeys(request["credentials"], "REDACTED") + if provider.get("refresh") and not self._apply_refresh(ws, provider, plan, state, generation, + source, pending): + return False 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. + """ + 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", {}) + if configured.get(reference) != source: + 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} + self._mutate("ConfigureProviderRefresh", request, plan, generation, identity=identity) + self._mutate("RotateProviderCredential", {**scope, "provider": pname, "credential_key": key}, + plan, generation, identity=identity) + configured[reference] = source + self.store.save(state) + pending.append(f"provider/{reference}") + return False + status = self.rpc.call("GetProviderRefreshStatus", {**scope, "provider": pname, "credential_key": key}) + ok = any(c.get("credential_key") == key and not c.get("last_error") and not c.get("failure_code") + for c in status.get("credentials", [])) + if not ok: + raise ContractError("provider credential refresh is failing; see the gateway's refresh status", + safe_reason="ProviderRefreshFailed") + 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..19e74b84f 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) @@ -48,8 +60,24 @@ def boundary(plan): def reconcile(plan, **kwargs): with sessions.open() as 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 gateway_profiles(): + """Platform provider profiles the gateway serves: type -> endpoint hosts.""" + profiles, token = {}, "" + with sessions.open() as gateway: + 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 compile_files(files, bindings): + return compile_profile_files(files, bindings, gateway_profiles()) + frontend = Controller(api, scope, state, compile_files, reconcile, boundary) stopped = False def stop(signum, frame): nonlocal stopped diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml index 7027c70e5..6fc909e42 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -37,8 +37,6 @@ containerDefaults: namespace: saw-component-builds streams: [saw-openclaw-896d1526ee29-amd64] governanceNamespace: openshell-agents - providerAllowHosts: - - api.inference.example.com automaticEnrollment: enabled: true autoApprove: true # dev/demo cluster: enroll on first observation, no manual review @@ -57,6 +55,8 @@ containerDefaults: identity: values: enabled: true + network: + bootstrapEgress: [] # generated (API and DNS) ownerID: '@INSTALLATION@' targetNamespace: '@RUNTIME@' gateway: '@OWNER@' @@ -98,39 +98,6 @@ containerDefaults: podSelector: {matchLabels: {openshell.ai/boundary-role: workload}} ports: - 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: - values: - enabled: true - ownerID: '@INSTALLATION@' - gateway: '@OWNER@' - targetNamespace: '@RUNTIME@' - policyConfigMap: '@OWNER@-proxy-policy' - # credentialSecretNames and policyDigest are derived from the profile catalog. - network: - bootstrapEgress: [] # generated - 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: # public HTTPS only; the proxy policy narrows it to providerAllowHosts - - 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] - ports: - - {protocol: TCP, port: 443} gateway: values: deployment: {mode: container} @@ -146,9 +113,6 @@ containerDefaults: storage: gatewaySize: 1Gi workspaceSize: 10Gi - proxy: - url: http://@OWNER@-credential-proxy.@TRUSTED@.svc:3128 - caConfigMap: '@OWNER@-proxy-ca' governance: endpoint: http://governance-interceptor.openshell-agents.svc:18081 network: @@ -162,11 +126,6 @@ containerDefaults: podSelector: {matchLabels: {app.kubernetes.io/name: governance-interceptor}} 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} route: {enabled: false} audit: values: 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_topology.py b/scripts/container_topology.py index ea1771ab1..d3634dc7d 100644 --- a/scripts/container_topology.py +++ b/scripts/container_topology.py @@ -16,7 +16,7 @@ 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") diff --git a/tests/charts/test_portal_container.py b/tests/charts/test_portal_container.py index 6ffeb3a1f..c9b5a6022 100644 --- a/tests/charts/test_portal_container.py +++ b/tests/charts/test_portal_container.py @@ -196,40 +196,41 @@ 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"} - for name,keys in {"gmail":{"refresh_token","client_id","client_secret"},"slack":{"bot_token"},"inference":{"api_key"}}.items(): + for name,keys in {"gmail":{"access_token","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) + # 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_projection_pins_broker_url_and_keeps_key_private(): +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"] 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 d41950af1..72e46f191 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,9 @@ 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): 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/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_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_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_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_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..1ff2632fc 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,32 @@ 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, []) diff --git a/tests/kubernetes_runtime/test_provider_refresh.py b/tests/kubernetes_runtime/test_provider_refresh.py new file mode 100644 index 000000000..f67776f44 --- /dev/null +++ b/tests/kubernetes_runtime/test_provider_refresh.py @@ -0,0 +1,93 @@ +"""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 + + def call(self, method, request): + if method in ("ConfigureProviderRefresh", "RotateProviderCredential"): + self.calls.append((method, copy.deepcopy(request))) + return {"status": {}} + if method == "GetProviderRefreshStatus": + 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): + 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) 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/scripts/test_container_installation.py b/tests/scripts/test_container_installation.py index fb95eb00f..48ac97403 100644 --- a/tests/scripts/test_container_installation.py +++ b/tests/scripts/test_container_installation.py @@ -112,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 4e70b9887..abe13da15 100644 --- a/tests/scripts/test_container_topology.py +++ b/tests/scripts/test_container_topology.py @@ -93,8 +93,8 @@ 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): diff --git a/tests/scripts/test_saw_preflight.py b/tests/scripts/test_saw_preflight.py index 885814d88..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,7 +211,7 @@ 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) @@ -235,22 +230,20 @@ def test_site_configuration_requires_pinned_sources_and_scoped_egress(): 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_workspace_projection.py b/tests/scripts/test_workspace_projection.py index 16e17fe21..a22b2b05b 100644 --- a/tests/scripts/test_workspace_projection.py +++ b/tests/scripts/test_workspace_projection.py @@ -129,7 +129,7 @@ def test_auto_approve_site_endpoint_defaults_custom_inference_url(): result = workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) projected = result["containerSites"]["alice"] assert projected["customInferenceURL"] == "https://api.inference.example/v1" - assert projected["providerAllowHosts"] == ["api.inference.example"] + assert "providerAllowHosts" not in projected # OpenShell's profiles decide hosts assert "reference" not in projected["automaticEnrollment"] assert result["users"][0]["customInferenceURL"] == "https://api.inference.example/v1" assert result["users"][0]["webSearch"] == {"enabled": False} # dedicated endpoint, as in the portal From 4bac60f66ad4b476d59ca7e04ff115cd6274eeb0 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 23:31:26 -0500 Subject: [PATCH 19/69] Allow the provider RPCs and reuse the reconcile session for the profile catalog The gateway adapter refused ListProviderProfiles, UpdateProvider and the refresh RPCs, which test fakes accepted. A test now checks every RPC the runtime calls against the allowlist. The controller fetched the provider profile catalog in a second gateway session per cycle; each session waits for the gateway to trust a fresh admin CA, so the catalog now comes from the reconcile session. Assisted-By: Claude --- kubernetes-runtime/saw_kubernetes/adapters.py | 5 +-- kubernetes-runtime/saw_kubernetes/serve.py | 34 ++++++++++++------- .../kubernetes_runtime/test_rpc_allowlist.py | 15 ++++++++ 3 files changed, 39 insertions(+), 15 deletions(-) create mode 100644 tests/kubernetes_runtime/test_rpc_allowlist.py 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/serve.py b/kubernetes-runtime/saw_kubernetes/serve.py index 19e74b84f..91f166be5 100644 --- a/kubernetes-runtime/saw_kubernetes/serve.py +++ b/kubernetes-runtime/saw_kubernetes/serve.py @@ -57,26 +57,34 @@ def read_credential(secret, key): 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, read_credential=read_credential).reconcile(plan, **kwargs) - def gateway_profiles(): - """Platform provider profiles the gateway serves: type -> endpoint hosts.""" - profiles, token = {}, "" - with sessions.open() as gateway: - 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 compile_files(files, bindings): - return compile_profile_files(files, bindings, gateway_profiles()) + 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): 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 From 4c2a2aa9e3ee97e9a467b0f4b57709ed6bc01cae Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Thu, 19 Nov 2026 23:55:06 -0500 Subject: [PATCH 20/69] Make the runtime image readable by its non-root user COPY keeps the builder's file modes, so a checkout with a private umask produced an image UID 1001 could not import. Normalize the modes and run the import check as the runtime user so the build fails instead. Assisted-By: Claude --- kubernetes-runtime/Containerfile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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"] From 7a710b79e5c63d9f1be1a86b485395ddca9516ab Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Fri, 20 Nov 2026 01:01:14 -0500 Subject: [PATCH 21/69] Let a harness bundle set the tool-gate actions for its own MCP tools harness.yaml lists tools per MCP server with allow or approval. The rules follow the base tool-actions.yaml in the gate policy, so the pinned policy hash and gate digest cover them and a base rule for the same tool still decides. A bundle can only name its own servers' tools. Container workspaces apply them; VM workspaces keep the base policy. Assisted-By: Claude --- .../openshell-saw/files/installer/saw_core.py | 47 +++++++++- docs/harness-bundles.md | 27 ++++++ kubernetes-runtime/saw_kubernetes/compiler.py | 4 +- kubernetes-runtime/saw_kubernetes/harness.py | 10 ++ .../saw_kubernetes/prepare_gate.py | 11 ++- .../test_harness_tool_rules.py | 94 +++++++++++++++++++ 6 files changed, 186 insertions(+), 7 deletions(-) create mode 100644 tests/kubernetes_runtime/test_harness_tool_rules.py diff --git a/charts/openshell-saw/files/installer/saw_core.py b/charts/openshell-saw/files/installer/saw_core.py index c74428747..101958654 100644 --- a/charts/openshell-saw/files/installer/saw_core.py +++ b/charts/openshell-saw/files/installer/saw_core.py @@ -1113,13 +1113,24 @@ 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: + 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 +1153,14 @@ 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") + + +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 +1305,29 @@ 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 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(r"[A-Za-z0-9_-]{1,64}", 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 +1345,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/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/kubernetes-runtime/saw_kubernetes/compiler.py b/kubernetes-runtime/saw_kubernetes/compiler.py index bb692cc22..88aa78b07 100644 --- a/kubernetes-runtime/saw_kubernetes/compiler.py +++ b/kubernetes-runtime/saw_kubernetes/compiler.py @@ -386,7 +386,9 @@ def compile_profile_files(files, config, gateway_profiles=None): 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() diff --git a/kubernetes-runtime/saw_kubernetes/harness.py b/kubernetes-runtime/saw_kubernetes/harness.py index 308a13fea..56bdfdd41 100644 --- a/kubernetes-runtime/saw_kubernetes/harness.py +++ b/kubernetes-runtime/saw_kubernetes/harness.py @@ -32,6 +32,13 @@ 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) @@ -44,6 +51,9 @@ def configure(command, driver, bundle, workspace, sandbox, catalog): 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/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/tests/kubernetes_runtime/test_harness_tool_rules.py b/tests/kubernetes_runtime/test_harness_tool_rules.py new file mode 100644 index 000000000..550b9f21f --- /dev/null +++ b/tests/kubernetes_runtime/test_harness_tool_rules.py @@ -0,0 +1,94 @@ +"""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 + + +@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 "allow" for a tool the base policy already names does not change it. + 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) + extra = [{"id": "harness-reader-read_mail", "tool": "reader__read_mail", "action": "allow"}, + {"id": "harness-x-override", "tool": denied, "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"] From 64770a85ae9d0b51b0f4d279c6cafd774c811da6 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 14:32:41 +0000 Subject: [PATCH 22/69] Give the portal's container preflight its credential bindings Native providers made preflight require site.credentialBindings, which saw-users renders into the site from the profile's secrets. The portal runs preflight before anything renders, so every container request failed with ProviderEgressRejected. Derive the same list from the catalog entry. Assisted-By: Claude --- charts/openshell-rhdh/files/portal.py | 33 +++++++++++++++++++++++++++ tests/portal/test_portal.py | 12 ++++++++++ 2 files changed, 45 insertions(+) diff --git a/charts/openshell-rhdh/files/portal.py b/charts/openshell-rhdh/files/portal.py index 43a188ca8..33c38dbf5 100644 --- a/charts/openshell-rhdh/files/portal.py +++ b/charts/openshell-rhdh/files/portal.py @@ -880,8 +880,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: diff --git a/tests/portal/test_portal.py b/tests/portal/test_portal.py index 3dc99b405..27117baa3 100644 --- a/tests/portal/test_portal.py +++ b/tests/portal/test_portal.py @@ -242,6 +242,18 @@ def catalog(portal): return portal.load_catalog(CATALOG) +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", From 93897a35f2ae34fe1ccde3a22de748eba943d7a3 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 15:07:48 +0000 Subject: [PATCH 23/69] Merge container sites by key presence so a per-user false wins Sprig's mergeOverwrite skips empty values, so containerSites. could not set automaticEnrollment.autoApprove (or any key) to false over a shared true, while the portal's Python merge could. saw-users.deepMerge merges maps by key presence and replaces every other value, matching the portal. Tests cover the same override on the static, projected and portal paths. Assisted-By: Claude --- charts/saw-users/templates/_helpers.tpl | 23 +++++++++++++++++--- tests/charts/test_saw_users_chart.py | 28 +++++++++++++++++++++++++ tests/portal/test_portal.py | 15 +++++++++++++ 3 files changed, 63 insertions(+), 3 deletions(-) diff --git a/charts/saw-users/templates/_helpers.tpl b/charts/saw-users/templates/_helpers.tpl index 253313450..38efc139c 100644 --- a/charts/saw-users/templates/_helpers.tpl +++ b/charts/saw-users/templates/_helpers.tpl @@ -514,14 +514,31 @@ Explicit values always win. Returns JSON. */}} {{- 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; every chart revision defaults to global.targetRevision, so the -workspace follows the pattern's branch like VM users. Note: mergeOverwrite -skips empty values, so a per-user false/"" cannot unset a default. Returns JSON. */}} +workspace follows the pattern's branch like VM users. 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 := mergeOverwrite (deepCopy ($root.Values.containerDefaults | default dict)) (deepCopy (index ($root.Values.containerSites | default dict) $u.name | default dict)) -}} +{{- $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 -}} {{- range $key, $item := ($site.stack | default dict) -}} diff --git a/tests/charts/test_saw_users_chart.py b/tests/charts/test_saw_users_chart.py index 72e46f191..84198b6d5 100644 --- a/tests/charts/test_saw_users_chart.py +++ b/tests/charts/test_saw_users_chart.py @@ -127,6 +127,34 @@ def test_minimal_container_entry_uses_cluster_defaults(tmp_path): assert values["site"]["automaticEnrollment"]["relay"]["revision"] == "main" +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") diff --git a/tests/portal/test_portal.py b/tests/portal/test_portal.py index 27117baa3..cac8c886d 100644 --- a/tests/portal/test_portal.py +++ b/tests/portal/test_portal.py @@ -242,6 +242,21 @@ 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 + + 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. From f4521a98e865ea983fa0b830da952c2c45c40abd Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 15:08:51 +0000 Subject: [PATCH 24/69] Keep auto-approval out of production container defaults values-prod.yaml loads saw-container-defaults.yaml for saw-users and the portal, and it enabled autoApprove. Production defaults now keep enrollment off until an operator reviews the boundary and sets the reference, approvedProfiles and pinned revisions per user. Auto-approval moves to overrides/saw-container-demo.yaml, which demo clusters list explicitly. Assisted-By: Claude --- docs/container-installation.md | 22 ++++++++++++++++------ overrides/saw-container-defaults.yaml | 11 +++++++++-- overrides/saw-container-demo.yaml | 14 ++++++++++++++ 3 files changed, 39 insertions(+), 8 deletions(-) create mode 100644 overrides/saw-container-demo.yaml diff --git a/docs/container-installation.md b/docs/container-installation.md index 96a212ebd..8aa5344ae 100644 --- a/docs/container-installation.md +++ b/docs/container-installation.md @@ -525,12 +525,22 @@ The chart fills in the rest; an explicit value always wins: | site | `containerDefaults`, overlaid by `containerSites.`; `subject` is the user's `ownerSubject` | | chart revisions | `global.targetRevision`: workspaces follow the pattern's branch like VM users. Pin a site's `stack.*.revision`, `automaticEnrollment.revision` and `relay.revision` to full SHAs to stop that. | -`containerDefaults.automaticEnrollment.autoApprove: true` is for development and -demo clusters. The enrollment Job still runs its health, admission and network -checks, then publishes the boundary and BOM it observes instead of comparing -them with an operator-reviewed `reference` and `approvedProfiles` digest. Later -changes to an enrolled boundary still fail closed; start a new `generation` -to re-enroll. Keep the reviewed flow below for production clusters. +The defaults keep enrollment off (`automaticEnrollment.enabled: false`, +`autoApprove: 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. Generate the network overlay from both files with `make container-topology`; it covers `containerDefaults` as well as individual sites. diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml index 6fc909e42..0d6fbf713 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -38,8 +38,15 @@ containerDefaults: streams: [saw-openclaw-896d1526ee29-amd64] governanceNamespace: openshell-agents automaticEnrollment: - enabled: true - autoApprove: true # dev/demo cluster: enroll on first observation, no manual review + # Reviewed flow: a new container workspace deploys without enrollment + # until an operator has reviewed its boundary. Then, per user under + # containerSites..automaticEnrollment, set enabled: true with the + # reviewed reference and approvedProfiles digest, and pin chart revisions + # to commit SHAs (docs/container-installation.md). Development and demo + # clusters can list overrides/saw-container-demo.yaml after this file to + # auto-approve instead; never list it in production values. + enabled: false + autoApprove: false # The saw-kubernetes-runtime image, pinned by digest and pullable # anonymously from inside the cluster (make saw-init checks this). image: ghcr.io/validatedpatterns-sandbox/saw-kubernetes-runtime@sha256: diff --git a/overrides/saw-container-demo.yaml b/overrides/saw-container-demo.yaml new file mode 100644 index 000000000..1a76fc3ee --- /dev/null +++ b/overrides/saw-container-demo.yaml @@ -0,0 +1,14 @@ +# 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 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 From c3eb26241c798ac7197aecc5ccc467a92c0882e8 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 15:09:40 +0000 Subject: [PATCH 25/69] Make the privileged demo NFS server an explicit opt-in saw-init runs shared-storage.sh during pattern-install and make saw-create. With no shared-filesystem class and SAW_SHARED_STORAGE unset, it created a privileged NFS server and a cluster-scoped provisioner role without asking. It now fails with the options; SAW_SHARED_STORAGE=nfs creates the demo server. Tests drive the script with a fake oc. Assisted-By: Claude --- README.md | 7 ++-- docs/container-installation.md | 21 +++++----- scripts/shared-storage.sh | 18 +++++---- tests/scripts/test_shared_storage.py | 59 ++++++++++++++++++++++++++++ 4 files changed, 85 insertions(+), 20 deletions(-) create mode 100644 tests/scripts/test_shared_storage.py diff --git a/README.md b/README.md index 40188e8d5..be86a0371 100644 --- a/README.md +++ b/README.md @@ -286,9 +286,10 @@ make check-oidc-ca # 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 creates a -# small in-cluster NFS server for dev/demo; SAW_SHARED_STORAGE=efs offers EFS on -# AWS, =none only reports) and the runtime image in overrides/saw-container-defaults.yaml. +# 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 diff --git a/docs/container-installation.md b/docs/container-installation.md index 8aa5344ae..e953d8554 100644 --- a/docs/container-installation.md +++ b/docs/container-installation.md @@ -551,15 +551,18 @@ AdminNetworkPolicy and ValidatingAdmissionPolicy, a shared-filesystem 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` creates one for development and demo -clusters: a privileged NFS server Pod on a default-class volume in namespace -`saw-nfs`, the upstream NFS subdirectory provisioner and StorageClass `saw-nfs`, -then verifies a read/write mount. It is a single Pod with no replication. For -production, install a real shared filesystem first (ODF CephFS, EFS, vendor NFS); -`saw-init` then leaves storage alone. `SAW_SHARED_STORAGE=efs` instead 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, and -`SAW_SHARED_STORAGE=none` only reports. +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 diff --git a/scripts/shared-storage.sh b/scripts/shared-storage.sh index f158c4d42..efee3535a 100755 --- a/scripts/shared-storage.sh +++ b/scripts/shared-storage.sh @@ -6,14 +6,15 @@ # (gp3-csi) cannot serve it. This script: # - a known shared-filesystem class exists -> continue # - otherwise, by SAW_SHARED_STORAGE: -# nfs (default) -> create a small in-cluster NFS server and provisioner -# (StorageClass `saw-nfs`) and verify it. One Pod, no -# replication: fine for dev/demo, not for production. +# 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/. -# none -> print the options and fail # For production, provide a real RWX class (ODF CephFS, EFS, vendor NFS) first; # this script then leaves storage alone. # @@ -45,7 +46,8 @@ guidance() { 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 " - SAW_SHARED_STORAGE=nfs (default) sets up a small in-cluster NFS server (dev/demo)" + 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." } @@ -103,7 +105,7 @@ if [ -n "$existing" ]; then exit 0 fi -# Default: a small NFS server inside the cluster, needing only cluster-admin. +# 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() { @@ -114,7 +116,7 @@ setup_demo_nfs() { 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. Set SAW_SHARED_STORAGE=none or efs to change." + 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 @@ -226,7 +228,7 @@ EOF verify_rwx "$ns" "$class" } -case "${SAW_SHARED_STORAGE:-nfs}" in +case "${SAW_SHARED_STORAGE:-}" in nfs) setup_demo_nfs; exit 0 ;; efs) ;; # below *) err " FAIL no shared-filesystem (ReadWriteMany) StorageClass"; guidance; exit 1 ;; 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 From ca5c8ec6d3bda23a208836106228f4ca44217e45 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 15:53:23 +0000 Subject: [PATCH 26/69] Let helm lint render saw-portal-container without credential bindings helm lint reports a missing required value as a warning and returns "", so ranging over required ... credentialBindings failed the chart with "range can't iterate over". Default the result to an empty list; real installs still fail when the bindings are missing. Assisted-By: Claude --- charts/saw-portal-container/templates/foundation.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/charts/saw-portal-container/templates/foundation.yaml b/charts/saw-portal-container/templates/foundation.yaml index acd47782a..14f7f9f9f 100644 --- a/charts/saw-portal-container/templates/foundation.yaml +++ b/charts/saw-portal-container/templates/foundation.yaml @@ -31,7 +31,9 @@ metadata: {name: default-deny, namespace: {{ $runtime }}, annotations: {argocd.a spec: {podSelector: {}, policyTypes: [Ingress, Egress], ingress: [], egress: []} {{- $customSecret := "" }} {{- $sources := dict }} -{{- range required "explicit credential bindings required" (.Values.site | default dict).credentialBindings }} +{{- /* 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 := append (get $sources .secret | default list) .key }} {{- if .refresh }}{{- $fields = concat $fields (list "client_id" "client_secret" "refresh_token") }}{{- end }} From 2008e89574f3176a34b6aba0126907d2177782df Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 16:07:07 +0000 Subject: [PATCH 27/69] Expect the shared container defaults in saw-users' value files values-prod.yaml now lists saw-container-defaults.yaml before saw-users.yaml. The test also checks that no application lists the demo-only file and that the defaults keep enrollment and auto-approval off. Assisted-By: Claude --- tests/charts/test_openshell_saw_chart.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) 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 == [] From 3cec20f1e8768969b28b838c33c7f40dbb6354ed Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 16:15:00 +0000 Subject: [PATCH 28/69] Stub saw-init in the container make-dispatch test make saw-create now runs scripts/saw-init.sh before the container apply, so the test's scripts directory needs it. The stub also checks that only saw-create runs it. Assisted-By: Claude --- tests/scripts/test_make_interface.py | 3 +++ 1 file changed, 3 insertions(+) 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"]) From edf780316577bb689031d1194c20aefc557467b7 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 17:18:36 +0000 Subject: [PATCH 29/69] Require pinned chart revisions on reviewed container sites Preflight demanded commit SHAs for reviewed sites, but the saw-users chart and the portal filled every unset revision with global.targetRevision, and the workspace chart accepted any branch. Only autoApprove sites now follow the branch; a reviewed site keeps its revisions unset until the operator pins them, and the workspace chart fails on a branch or a missing revision, as preflight does. Production values no longer advertise Container in the portal; the demo file does. Assisted-By: Claude --- charts/openshell-rhdh/files/portal.py | 4 +++- .../templates/_helpers.tpl | 8 ++++++++ .../templates/auto-enroll.yaml | 2 +- .../saw-portal-container/templates/relay.yaml | 2 +- .../saw-portal-container/templates/stack.yaml | 2 +- charts/saw-users/templates/_helpers.tpl | 8 ++++++-- docs/container-installation.md | 2 +- overrides/saw-container-defaults.yaml | 8 ++++---- overrides/saw-container-demo.yaml | 14 +++++++++---- tests/charts/test_portal_container.py | 20 +++++++++++++++++++ tests/charts/test_saw_users_chart.py | 13 +++++++++--- tests/portal/test_portal.py | 20 +++++++++++++++++++ 12 files changed, 85 insertions(+), 18 deletions(-) diff --git a/charts/openshell-rhdh/files/portal.py b/charts/openshell-rhdh/files/portal.py index 33c38dbf5..a1ec407d7 100644 --- a/charts/openshell-rhdh/files/portal.py +++ b/charts/openshell-rhdh/files/portal.py @@ -443,7 +443,9 @@ def container_site(user, subject=None): site = _deep_merge(defaults, site or {}) if not site.get("subject"): site["subject"] = subject or owner_subject(user) - revision = os.environ.get("SAW_TARGET_REVISION", "") + # 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: for item in (site.get("stack") or {}).values(): if isinstance(item, dict) and not item.get("revision"): diff --git a/charts/saw-portal-container/templates/_helpers.tpl b/charts/saw-portal-container/templates/_helpers.tpl index a6ad840c2..5472c0813 100644 --- a/charts/saw-portal-container/templates/_helpers.tpl +++ b/charts/saw-portal-container/templates/_helpers.tpl @@ -11,3 +11,11 @@ {{- end -}}{{- end -}} {{ $claims | toJson }} {{- 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 := (.Values.site | default dict).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 -}} diff --git a/charts/saw-portal-container/templates/auto-enroll.yaml b/charts/saw-portal-container/templates/auto-enroll.yaml index 3aceaf174..c545ee211 100644 --- a/charts/saw-portal-container/templates/auto-enroll.yaml +++ b/charts/saw-portal-container/templates/auto-enroll.yaml @@ -1,7 +1,7 @@ {{- $s := .Values.site | default dict }}{{- $a := $s.automaticEnrollment | default dict }} {{- if and $a (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 "^[A-Za-z0-9][A-Za-z0-9._/-]*$" ($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 Git revision and a reviewed boundary (or autoApprove)" }}{{- end }} +{{- 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 }} diff --git a/charts/saw-portal-container/templates/relay.yaml b/charts/saw-portal-container/templates/relay.yaml index ee41ca894..48d9dce72 100644 --- a/charts/saw-portal-container/templates/relay.yaml +++ b/charts/saw-portal-container/templates/relay.yaml @@ -2,7 +2,7 @@ {{- $e := $site.enrollment | default dict }} {{- if and $e (eq $e.registration .Values.registration) $e.relay }} {{- $r := $e.relay }} -{{- if not (regexMatch "^[A-Za-z0-9][A-Za-z0-9._/-]*$" ($r.revision | default "")) }}{{ fail "relay revision must be a Git commit or branch" }}{{ 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 }} diff --git a/charts/saw-portal-container/templates/stack.yaml b/charts/saw-portal-container/templates/stack.yaml index 4219a3df0..cf04318bf 100644 --- a/charts/saw-portal-container/templates/stack.yaml +++ b/charts/saw-portal-container/templates/stack.yaml @@ -65,7 +65,7 @@ spec: {{- 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-Za-z0-9][A-Za-z0-9._/-]*$" ($item.revision | default "")) }}{{ fail "each infrastructure chart needs a Git commit or branch revision" }}{{ 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 }} diff --git a/charts/saw-users/templates/_helpers.tpl b/charts/saw-users/templates/_helpers.tpl index 38efc139c..536d542c1 100644 --- a/charts/saw-users/templates/_helpers.tpl +++ b/charts/saw-users/templates/_helpers.tpl @@ -532,8 +532,10 @@ every other value (lists included) is replaced. Returns JSON. */}} {{/* A container user's site: containerSites. layered over the shared containerDefaults (site values win). subject defaults to the user's -ownerSubject; every chart revision defaults to global.targetRevision, so the -workspace follows the pattern's branch like VM users. Merged by key presence +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" -}} @@ -541,6 +543,7 @@ the portal. Returns JSON. */}} {{- $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" -}} {{- range $key, $item := ($site.stack | default dict) -}} {{- if and (kindIs "map" $item) (not $item.revision) }}{{ $_ := set $item "revision" $rev }}{{ end -}} {{- end -}} @@ -548,6 +551,7 @@ the portal. Returns JSON. */}} {{- if not .revision }}{{ $_ := set . "revision" $rev }}{{ end -}} {{- if and .relay (not .relay.revision) }}{{ $_ := set .relay "revision" $rev }}{{ end -}} {{- end -}} +{{- end -}} {{- toJson $site -}} {{- end -}} diff --git a/docs/container-installation.md b/docs/container-installation.md index e953d8554..b4f7d8227 100644 --- a/docs/container-installation.md +++ b/docs/container-installation.md @@ -523,7 +523,7 @@ The chart fills in the rest; an explicit value always wins: | `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 | `global.targetRevision`: workspaces follow the pattern's branch like VM users. Pin a site's `stack.*.revision`, `automaticEnrollment.revision` and `relay.revision` to full SHAs to stop that. | +| 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. | The defaults keep enrollment off (`automaticEnrollment.enabled: false`, `autoApprove: false`): a new workspace deploys its foundation and waits for diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml index 0d6fbf713..e42aa8c84 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -13,10 +13,10 @@ projection: enabled: true -# Self-service portal (openshell-rhdh reads this file too): offer Container next -# to VM. Any Keycloak user may request it; their site is containerDefaults. -portal: - deploymentModes: [vm, container, kata] +# The self-service portal (openshell-rhdh reads this file too) keeps its +# default modes here. Offer Container (portal.deploymentModes) only once a +# reviewed site is configured, or on a demo cluster through +# overrides/saw-container-demo.yaml. containerDefaults: # The custom inference endpoint approved for custom-inference workspaces; diff --git a/overrides/saw-container-demo.yaml b/overrides/saw-container-demo.yaml index 1a76fc3ee..d53d5eeeb 100644 --- a/overrides/saw-container-demo.yaml +++ b/overrides/saw-container-demo.yaml @@ -4,11 +4,17 @@ # 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 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. +# 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/tests/charts/test_portal_container.py b/tests/charts/test_portal_container.py index c9b5a6022..d360661b3 100644 --- a/tests/charts/test_portal_container.py +++ b/tests/charts/test_portal_container.py @@ -180,6 +180,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. diff --git a/tests/charts/test_saw_users_chart.py b/tests/charts/test_saw_users_chart.py index 84198b6d5..6a5d5bac6 100644 --- a/tests/charts/test_saw_users_chart.py +++ b/tests/charts/test_saw_users_chart.py @@ -107,13 +107,15 @@ def test_container_installation_id_defaults_to_portal_uuid5(tmp_path, given, exp assert helm_values(app(docs, "saw-alice"))["installationID"] == expected -def test_minimal_container_entry_uses_cluster_defaults(tmp_path): +@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})) @@ -123,8 +125,13 @@ def test_minimal_container_entry_uses_cluster_defaults(tmp_path): assert values["installationID"] == "a4300afa-4ae4-5da1-a5b1-44e50a34eb59" assert values["vaultPrefix"] == "secret/data/hub/saw-alice/" + registration assert values["site"]["subject"] == subject - assert {item["revision"] for item in values["site"]["stack"].values()} == {"main"} - assert values["site"]["automaticEnrollment"]["relay"]["revision"] == "main" + # 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): diff --git a/tests/portal/test_portal.py b/tests/portal/test_portal.py index cac8c886d..69a097315 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" @@ -257,6 +258,25 @@ def test_per_user_auto_approve_false_overrides_the_default(portal, monkeypatch): "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. From 0e446ed85a68b4b74f72f410d10842b2d864e013 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 17:21:50 +0000 Subject: [PATCH 30/69] Start OAuth refresh providers from material, not a stored access token The portal writes only Gmail's client_id, client_secret and refresh_token to Vault, but the ExternalSecret also synced access_token and the reconciler read it to create the provider, so Gmail never started. The ExternalSecret now syncs only the refresh material, and the reconciler creates the provider without a credential value (the profile's oauth2_refresh_token strategy lets OpenShell mint it), sends only OpenShell Provider fields (the gateway rejects the plan's refresh field), and accepts the version bumps each minted token causes. Tests check that every synced Vault property is one the profile collects, and that refresh converges after OpenShell rewrites the provider. Assisted-By: Claude --- .../templates/foundation.yaml | 5 +-- docs/personal-assistant.md | 6 ++++ .../saw_kubernetes/reconcile.py | 32 +++++++++++++------ tests/charts/test_portal_container.py | 8 ++++- .../test_provider_refresh.py | 21 ++++++++++++ 5 files changed, 60 insertions(+), 12 deletions(-) diff --git a/charts/saw-portal-container/templates/foundation.yaml b/charts/saw-portal-container/templates/foundation.yaml index 14f7f9f9f..6c89277d4 100644 --- a/charts/saw-portal-container/templates/foundation.yaml +++ b/charts/saw-portal-container/templates/foundation.yaml @@ -35,8 +35,9 @@ spec: {podSelector: {}, policyTypes: [Ingress, Egress], ingress: [], egress: []} {{- $bindings := required "explicit credential bindings required" (.Values.site | default dict).credentialBindings }} {{- range ($bindings | default list) }} {{- if eq .type "custom-inference" }}{{- $customSecret = .secret }}{{- end }} -{{- $fields := append (get $sources .secret | default list) .key }} -{{- if .refresh }}{{- $fields = concat $fields (list "client_id" "client_secret" "refresh_token") }}{{- end }} +{{- $fields := get $sources .secret | default list }} +{{- /* 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 }} {{- range $secret, $fields := $sources }} 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/kubernetes-runtime/saw_kubernetes/reconcile.py b/kubernetes-runtime/saw_kubernetes/reconcile.py index ecf988fca..dffa9046a 100644 --- a/kubernetes-runtime/saw_kubernetes/reconcile.py +++ b/kubernetes-runtime/saw_kubernetes/reconcile.py @@ -362,13 +362,21 @@ def _apply_provider(self, ws, provider, plan, state, generation, pending): pname = provider["metadata"]["name"] reference = f"{ws['name']}/{pname}" ref = provider.get("credentialRef") - request = {k: v for k, v in provider.items() if k != "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") - value, source = self.read_credential(ref["secret"], ref["key"]) - request["credentials"] = {self.credential_env[provider["type"]]: value} + 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} @@ -407,8 +415,10 @@ def _apply_provider(self, ws, provider, plan, state, generation, pending): expected_credentials = {} if ref: recorded = revisions.get(reference, {}) - if (recorded.get("version") != existing["metadata"].get("resource_version") - or recorded.get("provider") != digest(provider)): + # 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") if recorded.get("source") != source and not provider.get("refresh"): @@ -420,10 +430,14 @@ def _apply_provider(self, ws, provider, plan, state, generation, pending): self.store.save(state) pending.append(f"provider/{reference}") return False - expected_credentials = dict.fromkeys(request["credentials"], "REDACTED") - if provider.get("refresh") and not self._apply_refresh(ws, provider, plan, state, generation, - source, pending): - 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): raise ContractError("provider drift or unexpected credential state requires explicit recovery", diff --git a/tests/charts/test_portal_container.py b/tests/charts/test_portal_container.py index d360661b3..b8f9383f7 100644 --- a/tests/charts/test_portal_container.py +++ b/tests/charts/test_portal_container.py @@ -233,9 +233,15 @@ def test_personal_assistant_credentials_are_projected_for_openshell(): 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"} - for name,keys in {"gmail":{"access_token","refresh_token","client_id","client_secret"},"slack":{"bot_token"},"inference":{"api_key"}}.items(): + # 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 + # 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" diff --git a/tests/kubernetes_runtime/test_provider_refresh.py b/tests/kubernetes_runtime/test_provider_refresh.py index f67776f44..cf7e44ac1 100644 --- a/tests/kubernetes_runtime/test_provider_refresh.py +++ b/tests/kubernetes_runtime/test_provider_refresh.py @@ -23,6 +23,11 @@ def __init__(self): def call(self, method, request): if method in ("ConfigureProviderRefresh", "RotateProviderCredential"): self.calls.append((method, copy.deepcopy(request))) + 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": status = {"credential_key": request["credential_key"]} @@ -41,6 +46,8 @@ 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" @@ -91,3 +98,17 @@ def test_failing_refresh_is_reported(tmp_path): 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, []) From 89e63739c3b8a8b454df505047adbbded4e4f786 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 17:24:59 +0000 Subject: [PATCH 31/69] Refuse credentialed provider profiles with unapproved endpoints OpenShell attaches a provider's credential to its profile's endpoints, and container supervisors may open public TCP/443, but nothing checked those endpoints once the credential proxy was removed. Before creating a provider, the reconciler now requires the live profile's endpoints to be exactly the approved set, all enforced and without raw IP allowances: the governed profile shipped with the runtime image, or for custom-inference only the site URL's host on 443. Anything else stops with ProviderProfileMismatch. Assisted-By: Claude --- charts/saw-runtime-policies/values.yaml | 6 +- docs/container-installation.md | 4 +- docs/container-workspaces.md | 8 +- kubernetes-runtime/saw_kubernetes/provider.py | 21 ++++- .../saw_kubernetes/reconcile.py | 25 ++++- .../test_provider_endpoints.py | 93 +++++++++++++++++++ 6 files changed, 147 insertions(+), 10 deletions(-) create mode 100644 tests/kubernetes_runtime/test_provider_endpoints.py diff --git a/charts/saw-runtime-policies/values.yaml b/charts/saw-runtime-policies/values.yaml index 1356e4c80..c09b0b989 100644 --- a/charts/saw-runtime-policies/values.yaml +++ b/charts/saw-runtime-policies/values.yaml @@ -13,8 +13,10 @@ network: # 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); OpenShell's network - # policy then decides which hosts each sandbox may actually use. + # 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. diff --git a/docs/container-installation.md b/docs/container-installation.md index b4f7d8227..4277eaf04 100644 --- a/docs/container-installation.md +++ b/docs/container-installation.md @@ -95,10 +95,10 @@ field. Start from the component charts' values and schemas: | `stack.policy` | Pinned revision and [admission/network values](../charts/saw-runtime-policies/values.yaml): runtime namespace, service accounts, explicit egress and unique 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. | +| `governanceNamespace` | Shared governance location. | | `automaticEnrollment` | `enabled`, 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 explicit provider/boundary approval. Changing the profile requires its own approval. The `custom-inference` governance profile must list exactly the `inferenceBaseURL` host on port 443; the runtime controller otherwise refuses the provider (`ProviderProfileMismatch`). | | `imagePull` | Optional namespace and ImageStream names for access to an OpenShift internal registry. | RHDH offers **Container** on the create form when `portal.deploymentModes` diff --git a/docs/container-workspaces.md b/docs/container-workspaces.md index 04374f302..3cd8912ca 100644 --- a/docs/container-workspaces.md +++ b/docs/container-workspaces.md @@ -148,8 +148,12 @@ Policies protect different boundaries: 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`); OpenShell's - network policy decides which hosts each sandbox may actually use. + 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 + site's `inferenceBaseURL` 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. diff --git a/kubernetes-runtime/saw_kubernetes/provider.py b/kubernetes-runtime/saw_kubernetes/provider.py index 141f2205f..7c8680d91 100644 --- a/kubernetes-runtime/saw_kubernetes/provider.py +++ b/kubernetes-runtime/saw_kubernetes/provider.py @@ -2,8 +2,10 @@ OpenShell owns provider security: profiles decide which endpoints a credential may reach, and the supervisor substitutes the real value only for those. This -module only tells the agent which environment variable holds its inference key -and checks the site's custom inference URL. +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 @@ -52,3 +54,18 @@ def inference_key_env(kind): raise ValueError("not an inference provider") slot, = _shipped(kind)["credentials"] return slot["env_vars"][0] + + +def approved_endpoints(kind, custom_url=None): + """The (host, port) pairs a credentialed provider's key may be sent to. + + 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": + 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 dffa9046a..ed0bd3af3 100644 --- a/kubernetes-runtime/saw_kubernetes/reconcile.py +++ b/kubernetes-runtime/saw_kubernetes/reconcile.py @@ -15,6 +15,7 @@ import tempfile from types import SimpleNamespace +from . import provider as governed from .core import shared from .compiler import ContractError, MANAGED, OWNER, REVISION, SOURCE_REVISION, digest, request_id @@ -247,13 +248,14 @@ def _pass(self, plan, state, generation, desired_state): credentialed = any(p.get("credentialRef") for w in plan["workspaces"] for p in w["providers"] if p["type"] == provider_type) if credentialed: - # OpenShell enforces where this credential may go (the profile's - # endpoints); we only need the variable the sandbox reads it from. + # OpenShell attaches this credential only to the profile's + # endpoints, so those must be exactly the approved ones. slots = profile.get("credentials", []) 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") @@ -274,6 +276,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. 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() From 158ce82d510cb42e58c6acb35786fcfbb35d38ef Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 17:26:00 +0000 Subject: [PATCH 32/69] Converge credential updates whose reply was lost A rotated Secret's UpdateProvider recorded the new source only when the reply had a body. After a lost reply, or a replay answering ALREADY_EXISTS, the provider's version no longer matched and the update never converged. The reconciler now persists the update intent before the RPC, as creates do. On the next pass, if the provider moved on from the version it updated and still holds exactly its credential slot, it records that; if not applied, it resends the same request ID; if the provider changed shape, it fails closed. Assisted-By: Claude --- .../saw_kubernetes/reconcile.py | 27 ++++++- .../test_provider_recovery.py | 70 +++++++++++++++++++ 2 files changed, 95 insertions(+), 2 deletions(-) diff --git a/kubernetes-runtime/saw_kubernetes/reconcile.py b/kubernetes-runtime/saw_kubernetes/reconcile.py index ed0bd3af3..86762fa94 100644 --- a/kubernetes-runtime/saw_kubernetes/reconcile.py +++ b/kubernetes-runtime/saw_kubernetes/reconcile.py @@ -434,6 +434,24 @@ def _apply_provider(self, ws, provider, plan, state, generation, pending): return False self._identity("provider", ws["name"], pname, existing, plan, state) expected_credentials = {} + 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 @@ -442,12 +460,17 @@ def _apply_provider(self, ws, provider, plan, state, generation, pending): 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") - if recorded.get("source") != source and not provider.get("refresh"): - # The Secret rotated: hand OpenShell the new value. + 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 diff --git a/tests/kubernetes_runtime/test_provider_recovery.py b/tests/kubernetes_runtime/test_provider_recovery.py index 1ff2632fc..05c35e9f6 100644 --- a/tests/kubernetes_runtime/test_provider_recovery.py +++ b/tests/kubernetes_runtime/test_provider_recovery.py @@ -132,3 +132,73 @@ def call(method, request): 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, []) From d88d861c4ce45d33ad9c7f2e4efc2552b5f2bb18 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 17:27:19 +0000 Subject: [PATCH 33/69] Mark provider refresh configured only after a clean status The reconciler recorded a refresh as configured right after sending the material, even when both RPC replies were lost, so a lost configure was never retried; and an empty refresh status failed the workspace. Sent and confirmed are now separate: a revision counts as configured only once the gateway's status shows the credential without an error, an empty status is pending, and a configure without an acknowledged reply is sent again with the same request ID. A refresh that disappears after working is reported. ProviderRefreshFailed is now an allowed status reason, so it is published. Assisted-By: Claude --- charts/openshell-rhdh/files/workspace.py | 2 +- charts/saw-users/files/workspace.py | 2 +- kubernetes-runtime/saw_kubernetes/compiler.py | 2 +- .../saw_kubernetes/reconcile.py | 62 ++++++++++++------- .../test_provider_refresh.py | 41 ++++++++++++ 5 files changed, 84 insertions(+), 25 deletions(-) diff --git a/charts/openshell-rhdh/files/workspace.py b/charts/openshell-rhdh/files/workspace.py index 30161a0fe..3ece1c68c 100644 --- a/charts/openshell-rhdh/files/workspace.py +++ b/charts/openshell-rhdh/files/workspace.py @@ -18,7 +18,7 @@ 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", }) diff --git a/charts/saw-users/files/workspace.py b/charts/saw-users/files/workspace.py index 30161a0fe..3ece1c68c 100644 --- a/charts/saw-users/files/workspace.py +++ b/charts/saw-users/files/workspace.py @@ -18,7 +18,7 @@ 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", }) diff --git a/kubernetes-runtime/saw_kubernetes/compiler.py b/kubernetes-runtime/saw_kubernetes/compiler.py index 88aa78b07..330f4b830 100644 --- a/kubernetes-runtime/saw_kubernetes/compiler.py +++ b/kubernetes-runtime/saw_kubernetes/compiler.py @@ -28,7 +28,7 @@ SAFE_FAILURE_REASONS = frozenset({ "ProfileRejected", "InvalidPlan", "PlacementRejected", "IdentityConflict", "InvalidIntent", "StaleIntent", "ReconcilerStateRejected", "GatewayMismatch", - "ProviderProfileMismatch", + "ProviderProfileMismatch", "ProviderRefreshFailed", "WorkspaceRejected", "ProviderRejected", "SandboxRejected", "SandboxStateMismatch", "SandboxDrift", }) diff --git a/kubernetes-runtime/saw_kubernetes/reconcile.py b/kubernetes-runtime/saw_kubernetes/reconcile.py index 86762fa94..41121d0e1 100644 --- a/kubernetes-runtime/saw_kubernetes/reconcile.py +++ b/kubernetes-runtime/saw_kubernetes/reconcile.py @@ -493,38 +493,56 @@ def _apply_refresh(self, ws, provider, plan, state, generation, source, pending) 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: - 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} - self._mutate("ConfigureProviderRefresh", request, plan, generation, identity=identity) - self._mutate("RotateProviderCredential", {**scope, "provider": pname, "credential_key": key}, - plan, generation, identity=identity) - configured[reference] = source - self.store.save(state) - pending.append(f"provider/{reference}") - return False + 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}) - ok = any(c.get("credential_key") == key and not c.get("last_error") and not c.get("failure_code") - for c in status.get("credentials", [])) - if not ok: + 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): diff --git a/tests/kubernetes_runtime/test_provider_refresh.py b/tests/kubernetes_runtime/test_provider_refresh.py index cf7e44ac1..386215fc5 100644 --- a/tests/kubernetes_runtime/test_provider_refresh.py +++ b/tests/kubernetes_runtime/test_provider_refresh.py @@ -19,10 +19,15 @@ 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"])] @@ -30,6 +35,8 @@ def call(self, method, request): 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" @@ -112,3 +119,37 @@ def test_provider_is_created_from_material_without_an_access_token(tmp_path): # 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" From 6592ac2cb9c768528fb7d7fc7a328f80576bf124 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 17:28:58 +0000 Subject: [PATCH 34/69] Ask proxy-era container workspaces to re-enroll explicitly Workspaces enrolled by the credential-proxy controller failed after upgrade with a generic BoundaryRejected or ProviderRejected. An approval that still lists the removed proxy objects now fails with ReenrollRequired, and controller state holding proxy-era provider records stops with the same reason before any gateway call, so old providers are never adopted. The reason is published to the portal; the docs describe re-enrolling with a new generation. Assisted-By: Claude --- charts/openshell-rhdh/files/workspace.py | 2 +- charts/saw-users/files/workspace.py | 2 +- docs/container-installation.md | 9 ++++++ kubernetes-runtime/saw_kubernetes/boundary.py | 8 +++++ kubernetes-runtime/saw_kubernetes/compiler.py | 2 +- .../saw_kubernetes/controller.py | 6 ++-- .../saw_kubernetes/reconcile.py | 5 ++++ tests/kubernetes_runtime/test_controller.py | 8 +++++ .../test_proxy_era_upgrade.py | 30 +++++++++++++++++++ 9 files changed, 67 insertions(+), 5 deletions(-) create mode 100644 tests/kubernetes_runtime/test_proxy_era_upgrade.py diff --git a/charts/openshell-rhdh/files/workspace.py b/charts/openshell-rhdh/files/workspace.py index 3ece1c68c..980a104df 100644 --- a/charts/openshell-rhdh/files/workspace.py +++ b/charts/openshell-rhdh/files/workspace.py @@ -20,7 +20,7 @@ class WorkspaceError(ValueError): "InvalidIntent", "StaleIntent", "ReconcilerStateRejected", "GatewayMismatch", "ProviderProfileMismatch", "ProviderRefreshFailed", "WorkspaceRejected", "ProviderRejected", "SandboxRejected", "SandboxStateMismatch", "SandboxDrift", "CoreRejected", - "CoreFailure", + "CoreFailure", "ReenrollRequired", }) SAFE_RPC_CODES = frozenset({ "NOT_FOUND", "ALREADY_EXISTS", "UNAVAILABLE", "DEADLINE_EXCEEDED", "ABORTED", diff --git a/charts/saw-users/files/workspace.py b/charts/saw-users/files/workspace.py index 3ece1c68c..980a104df 100644 --- a/charts/saw-users/files/workspace.py +++ b/charts/saw-users/files/workspace.py @@ -20,7 +20,7 @@ class WorkspaceError(ValueError): "InvalidIntent", "StaleIntent", "ReconcilerStateRejected", "GatewayMismatch", "ProviderProfileMismatch", "ProviderRefreshFailed", "WorkspaceRejected", "ProviderRejected", "SandboxRejected", "SandboxStateMismatch", "SandboxDrift", "CoreRejected", - "CoreFailure", + "CoreFailure", "ReenrollRequired", }) SAFE_RPC_CODES = frozenset({ "NOT_FOUND", "ALREADY_EXISTS", "UNAVAILABLE", "DEADLINE_EXCEEDED", "ABORTED", diff --git a/docs/container-installation.md b/docs/container-installation.md index 4277eaf04..d7d7561a1 100644 --- a/docs/container-installation.md +++ b/docs/container-installation.md @@ -542,6 +542,15 @@ 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. diff --git a/kubernetes-runtime/saw_kubernetes/boundary.py b/kubernetes-runtime/saw_kubernetes/boundary.py index 9bce4f676..9501ddf9c 100644 --- a/kubernetes-runtime/saw_kubernetes/boundary.py +++ b/kubernetes-runtime/saw_kubernetes/boundary.py @@ -84,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") diff --git a/kubernetes-runtime/saw_kubernetes/compiler.py b/kubernetes-runtime/saw_kubernetes/compiler.py index 330f4b830..cc31c39fe 100644 --- a/kubernetes-runtime/saw_kubernetes/compiler.py +++ b/kubernetes-runtime/saw_kubernetes/compiler.py @@ -30,7 +30,7 @@ "InvalidIntent", "StaleIntent", "ReconcilerStateRejected", "GatewayMismatch", "ProviderProfileMismatch", "ProviderRefreshFailed", "WorkspaceRejected", "ProviderRejected", "SandboxRejected", - "SandboxStateMismatch", "SandboxDrift", + "SandboxStateMismatch", "SandboxDrift", "ReenrollRequired", }) 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/reconcile.py b/kubernetes-runtime/saw_kubernetes/reconcile.py index 41121d0e1..b48fc206e 100644 --- a/kubernetes-runtime/saw_kubernetes/reconcile.py +++ b/kubernetes-runtime/saw_kubernetes/reconcile.py @@ -201,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): 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_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")) From ac7ddeb573117ffe5c3bfba4ce3c98d02fe69fbd Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 18:01:06 +0000 Subject: [PATCH 35/69] Publish the OpenShift-ready OpenClaw image from CI The stock OpenClaw image's /sandbox (0770, 1000:0) cannot be searched by OpenShift namespace UIDs, and OpenShell cannot fix it either: its own workspace seeding reads that directory as the same UID. Clusters built the one-line fix in-cluster (make container-notebook-image). A workflow now builds images/saw-openclaw/Containerfile from the notebook BOM's pinned image on main and publishes ghcr.io//saw-openclaw for linux/amd64 and linux/arm64, tagged src-. Assisted-By: Claude --- .github/workflows/build-openclaw-image.yml | 100 +++++++++++++++++++++ images/saw-openclaw/Containerfile | 15 ++++ 2 files changed, 115 insertions(+) create mode 100644 .github/workflows/build-openclaw-image.yml create mode 100644 images/saw-openclaw/Containerfile diff --git a/.github/workflows/build-openclaw-image.yml b/.github/workflows/build-openclaw-image.yml new file mode 100644 index 000000000..5d20dc3e2 --- /dev/null +++ b/.github/workflows/build-openclaw-image.yml @@ -0,0 +1,100 @@ +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: + +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' + 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 }} + 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' && secrets.GITHUB_TOKEN || '' }} + + publish: + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + 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' + 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/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} From 1b2e18dca476baba0bd98cb8a35dc6b6896fc6d0 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 18:01:06 +0000 Subject: [PATCH 36/69] Use the CI-published OpenClaw image in container defaults The defaults pinned an image each cluster had to build into its internal registry, plus imagePull access to it. They now name the public image the build-openclaw-image workflow publishes; the digest is filled in after its first build. In-cluster builds remain for disconnected clusters. Assisted-By: Claude --- docs/container-images.md | 13 ++++++++++++- overrides/saw-container-defaults.yaml | 16 ++++++++-------- 2 files changed, 20 insertions(+), 9 deletions(-) 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/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml index e42aa8c84..169e450f3 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -25,17 +25,17 @@ containerDefaults: custom-inference: inferenceBaseURL: https://api.inference.example.com/v1 allowHosts: [api.inference.example.com] - # Stock OpenClaw image rebuilt so OpenShift namespace UIDs can enter /sandbox - # (make container-notebook-image BUILD_NS=saw-component-builds BUILD_ARCH=amd64). - # Both profiles use the same source image. + # The stock OpenClaw image with /sandbox searchable by OpenShift namespace + # UIDs, published by .github/workflows/build-openclaw-image.yml + # (images/saw-openclaw/Containerfile). Pin the digest of the src-<12 hex> + # tag that matches the notebook BOM's source image. Both profiles use it. + # Disconnected clusters can build it in-cluster instead (make + # container-notebook-image) and add the imagePull it prints. profileImageOverrides: data-science: - notebook: "image-registry.openshift-image-registry.svc:5000/saw-component-builds/saw-openclaw-896d1526ee29-amd64@sha256:" + notebook: "ghcr.io/sauagarwa/saw-openclaw@sha256:" custom-inference: - notebook: "image-registry.openshift-image-registry.svc:5000/saw-component-builds/saw-openclaw-896d1526ee29-amd64@sha256:" - imagePull: - namespace: saw-component-builds - streams: [saw-openclaw-896d1526ee29-amd64] + notebook: "ghcr.io/sauagarwa/saw-openclaw@sha256:" governanceNamespace: openshell-agents automaticEnrollment: # Reviewed flow: a new container workspace deploys without enrollment From 5af093506afca7f83dbf631650fef026d8d8eeef Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 18:08:53 +0000 Subject: [PATCH 37/69] Pin the published OpenShift-ready OpenClaw image MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ghcr.io/sauagarwa/saw-openclaw@sha256:05f17f38… is the amd64 build of the notebook BOM's source image (tag 896d1526ee29-amd64). Switch to the workflow's multi-arch src-896d1526ee29 digest once it publishes. Assisted-By: Claude --- overrides/saw-container-defaults.yaml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml index 169e450f3..4cf02281d 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -29,13 +29,15 @@ containerDefaults: # UIDs, published by .github/workflows/build-openclaw-image.yml # (images/saw-openclaw/Containerfile). Pin the digest of the src-<12 hex> # tag that matches the notebook BOM's source image. Both profiles use it. + # For now: the amd64 build of source 896d1526ee29 (tag 896d1526ee29-amd64), + # until the workflow's multi-arch src-896d1526ee29 tag is published. # Disconnected clusters can build it in-cluster instead (make # container-notebook-image) and add the imagePull it prints. profileImageOverrides: data-science: - notebook: "ghcr.io/sauagarwa/saw-openclaw@sha256:" + notebook: "ghcr.io/sauagarwa/saw-openclaw@sha256:05f17f3872f864e44231fb3cea30cd4dd2ba9887b382a67b261f068a234b79a2" custom-inference: - notebook: "ghcr.io/sauagarwa/saw-openclaw@sha256:" + notebook: "ghcr.io/sauagarwa/saw-openclaw@sha256:05f17f3872f864e44231fb3cea30cd4dd2ba9887b382a67b261f068a234b79a2" governanceNamespace: openshell-agents automaticEnrollment: # Reviewed flow: a new container workspace deploys without enrollment From d4f7b75e849999d62ae55fc9e3637c842a8aceed Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 18:20:19 +0000 Subject: [PATCH 38/69] Take the custom inference URL from its owner, approved by the governance profile The URL lived in four places: the owner's Vault entry, a site-level profileBoundaries.custom-inference (inferenceBaseURL and allowHosts), the site copy compiled into the agent, and the custom-inference governance profile's host. The site-level copies only restated the other two. A workspace now uses its owner's own URL (the portal form, or customInferenceURL in a saw-users entry), checked for an HTTPS /v1 DNS URL; the governance profile remains the approval, enforced by the runtime controller before the key is handed to OpenShell. profileBoundaries keeps its per-profile reviewed reference. Assisted-By: Claude --- charts/openshell-rhdh/files/portal.py | 7 ++- charts/openshell-rhdh/files/workspace.py | 56 ++++++++++++++-------- charts/saw-users/files/workspace.py | 56 ++++++++++++++-------- docs/container-installation.md | 3 +- docs/container-workspaces.md | 2 +- overrides/saw-container-defaults.yaml | 10 ++-- overrides/saw-users.yaml | 1 + tests/portal/test_portal.py | 9 ++-- tests/scripts/test_workspace_projection.py | 28 +++++++---- 9 files changed, 109 insertions(+), 63 deletions(-) diff --git a/charts/openshell-rhdh/files/portal.py b/charts/openshell-rhdh/files/portal.py index a1ec407d7..01c4f9e2b 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): @@ -1793,8 +1793,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) diff --git a/charts/openshell-rhdh/files/workspace.py b/charts/openshell-rhdh/files/workspace.py index 980a104df..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 @@ -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): @@ -205,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 @@ -279,14 +296,15 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): reviewed = {"reference": boundary["reference"]} if "reference" in boundary or \ automatic.get("autoApprove") is not True else {} site = {**site, "automaticEnrollment": {**automatic, **reviewed}} - # A static entry takes the site-approved endpoint unless it names one. - if (not ws.get("customInferenceURL") and boundary.get("inferenceBaseURL") - and any(sb.get("endpointInput") for _, sb in enabled_catalog_sandboxes(catalog[selected]))): - ws["customInferenceURL"] = boundary["inferenceBaseURL"] - 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"] + # 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/files/workspace.py b/charts/saw-users/files/workspace.py index 980a104df..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 @@ -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): @@ -205,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 @@ -279,14 +296,15 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): reviewed = {"reference": boundary["reference"]} if "reference" in boundary or \ automatic.get("autoApprove") is not True else {} site = {**site, "automaticEnrollment": {**automatic, **reviewed}} - # A static entry takes the site-approved endpoint unless it names one. - if (not ws.get("customInferenceURL") and boundary.get("inferenceBaseURL") - and any(sb.get("endpointInput") for _, sb in enabled_catalog_sandboxes(catalog[selected]))): - ws["customInferenceURL"] = boundary["inferenceBaseURL"] - 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"] + # 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/docs/container-installation.md b/docs/container-installation.md index d7d7561a1..2184024cb 100644 --- a/docs/container-installation.md +++ b/docs/container-installation.md @@ -98,8 +98,9 @@ field. Start from the component charts' values and schemas: | `governanceNamespace` | Shared governance location. | | `automaticEnrollment` | `enabled`, 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. The `custom-inference` governance profile must list exactly the `inferenceBaseURL` host on port 443; the runtime controller otherwise refuses the provider (`ProviderProfileMismatch`). | +| `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 diff --git a/docs/container-workspaces.md b/docs/container-workspaces.md index 3cd8912ca..8dea79a00 100644 --- a/docs/container-workspaces.md +++ b/docs/container-workspaces.md @@ -152,7 +152,7 @@ Policies protect different boundaries: 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 - site's `inferenceBaseURL` host on 443. Otherwise it stops with + 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 diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml index 4cf02281d..e4c7db5c0 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -19,12 +19,10 @@ projection: # overrides/saw-container-demo.yaml. containerDefaults: - # The custom inference endpoint approved for custom-inference workspaces; - # its host must be the only allowed provider host for that profile. - profileBoundaries: - custom-inference: - inferenceBaseURL: https://api.inference.example.com/v1 - allowHosts: [api.inference.example.com] + # custom-inference workspaces use their owner's own base URL (the portal form, + # or customInferenceURL in overrides/saw-users.yaml). Its host must be the one + # endpoint in overrides/governance-profiles/custom-inference.yaml, where + # OpenShell sends the API key; the runtime refuses any other host. # The stock OpenClaw image with /sandbox searchable by OpenShift namespace # UIDs, published by .github/workflows/build-openclaw-image.yml # (images/saw-openclaw/Containerfile). Pin the digest of the src-<12 hex> diff --git a/overrides/saw-users.yaml b/overrides/saw-users.yaml index f84ad89e6..e6174da35 100644 --- a/overrides/saw-users.yaml +++ b/overrides/saw-users.yaml @@ -9,6 +9,7 @@ # ownerSubject: # profiles: [custom-inference] # vaultPrefix: secret/data/hub +# customInferenceURL: https:///v1 # custom-inference only # modelInputs: # inference.model: # values: diff --git a/tests/portal/test_portal.py b/tests/portal/test_portal.py index 69a097315..38c417a93 100644 --- a/tests/portal/test_portal.py +++ b/tests/portal/test_portal.py @@ -2301,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"]') @@ -2318,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_workspace_projection.py b/tests/scripts/test_workspace_projection.py index a22b2b05b..c7f5fbf5c 100644 --- a/tests/scripts/test_workspace_projection.py +++ b/tests/scripts/test_workspace_projection.py @@ -117,29 +117,39 @@ def test_auto_approve_accepts_the_observed_enrollment_but_still_binds_the_owner( lambda _: published(owner, subject="33333333-3333-4333-8333-333333333333")) -def test_auto_approve_site_endpoint_defaults_custom_inference_url(): +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) - site["profileBoundaries"] = {"custom-inference": { - "inferenceBaseURL": "https://api.inference.example/v1", "allowHosts": ["api.inference.example"]}} + # 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 "providerAllowHosts" not in projected # OpenShell's profiles decide hosts + assert "profileBoundaries" not in projected or "custom-inference" not in projected["profileBoundaries"] assert "reference" not in projected["automaticEnrollment"] - assert result["users"][0]["customInferenceURL"] == "https://api.inference.example/v1" 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 _: {}) - owner["modelInputs"] = {"inference.model": "org/model"} - owner["customInferenceURL"] = "https://elsewhere.example/v1" - with pytest.raises(workspace.WorkspaceError, match="endpoint differs"): - 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(): From fe412b28ed737646c309a48411a06b7d15c6200f Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 18:53:16 +0000 Subject: [PATCH 39/69] Default the fixed container site wiring in saw-portal-container overrides/saw-container-defaults.yaml repeated wiring that is the same on every cluster: namespaces, service accounts, SANs, the workspace egress policy, the governance endpoint and its egress, the enrollment build namespace, resources and relay Keycloak settings. These now live in saw-portal-container's siteDefaults, and a site sets only what differs. The defaults file keeps the image pins and the runtime image. - The gateway's default sandbox image is the first target's image, and its interceptor endpoint and egress follow governanceNamespace. - Workspaces share one AdminNetworkPolicy priority: each policy selects only its own namespace, and enrollment already refuses an earlier overlapping policy. - Enrollment runs only when a site sets automaticEnrollment.enabled: true. - autoApprove sites get a revision for every stack component, even one the site does not list. - make container-topology no longer needs gateway and relay blocks in the base file. Assisted-By: Claude --- charts/openshell-rhdh/files/portal.py | 6 +- charts/openshell-rhdh/files/workspace.py | 12 +- .../templates/_helpers.tpl | 34 +++- .../templates/auto-enroll.yaml | 4 +- .../templates/enrolled-runtime.yaml | 2 +- .../templates/publications.yaml | 4 +- .../saw-portal-container/templates/relay.yaml | 2 +- .../saw-portal-container/templates/stack.yaml | 23 ++- charts/saw-portal-container/values.yaml | 98 +++++++++++ charts/saw-users/files/projector.py | 2 +- charts/saw-users/files/workspace.py | 12 +- charts/saw-users/templates/_helpers.tpl | 6 +- docs/container-installation.md | 21 ++- docs/container-workspaces.md | 4 +- overrides/saw-container-defaults.yaml | 154 +++--------------- scripts/container_topology.py | 9 +- tests/charts/test_openshell_saw_chart.py | 3 +- tests/fixtures/container-site.yaml | 1 + tests/portal/test_portal.py | 2 +- 19 files changed, 223 insertions(+), 176 deletions(-) diff --git a/charts/openshell-rhdh/files/portal.py b/charts/openshell-rhdh/files/portal.py index 01c4f9e2b..400d80de6 100644 --- a/charts/openshell-rhdh/files/portal.py +++ b/charts/openshell-rhdh/files/portal.py @@ -447,7 +447,9 @@ def container_site(user, subject=None): # pins commit SHAs, and preflight rejects any it leaves unset. revision = os.environ.get("SAW_TARGET_REVISION", "") if auto_approved(site) else "" if revision: - for item in (site.get("stack") or {}).values(): + 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") @@ -810,7 +812,7 @@ 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 + if (not isinstance(automatic, dict) or not automatic or automatic.get("enabled") is not True or automatic.get("autoApprove") is True): return # autoApprove: enrollment publishes the first observed boundary reference = _approved_profile_reference(site, profile) diff --git a/charts/openshell-rhdh/files/workspace.py b/charts/openshell-rhdh/files/workspace.py index 1addd71e3..e1b942677 100644 --- a/charts/openshell-rhdh/files/workspace.py +++ b/charts/openshell-rhdh/files/workspace.py @@ -136,13 +136,13 @@ def publication(name): return obj["data"] fresh = {k:v for k,v in site.items() if k!="enrollment"} data=publication("saw-portal-enrollment") - if a.get("enabled") is False: + if a.get("enabled") is not True: if data: raise WorkspaceError("cannot disable enrollment of a bound workspace; use desiredState") return fresh auto = a.get("autoApprove") is True - for key, kind in ((() if auto else (("reference", dict),)) + (("relay", dict), ("revision", str), - ("image", str), ("buildNamespace", str))): + # Relay settings and the build namespace default in saw-portal-container. + for key, kind in ((() if auto else (("reference", dict),)) + (("revision", str), ("image", 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: @@ -159,8 +159,8 @@ def publication(name): sub=subjects.get("saw-portal-relay-subject","") if site.get("targets") else publication("saw-portal-relay-subject").get("subject","") if sub and (not re.fullmatch(r"[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}",sub) or sub==ws["ownerSubject"]): raise WorkspaceError("invalid relay subject") - relay={**a["relay"],"gatewayCA":bound["gatewayCA"],"subject":sub,"workspaceID":""} - fresh["enrollment"]={**{k:a[k] for k in ("revision","image","buildNamespace")},"registration":reg,"intent":intent,"approved":bound["approved"],"relay":relay} + relay={**(a.get("relay") or {}),"gatewayCA":bound["gatewayCA"],"subject":sub,"workspaceID":""} + fresh["enrollment"]={**{k:a[k] for k in ("revision","image","buildNamespace") if k in a},"registration":reg,"intent":intent,"approved":bound["approved"],"relay":relay} return fresh @@ -259,7 +259,7 @@ 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 or automatic.get("autoApprove") is True + foundation = automatic.get("enabled") is not True 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"): diff --git a/charts/saw-portal-container/templates/_helpers.tpl b/charts/saw-portal-container/templates/_helpers.tpl index 5472c0813..87b047597 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" -}} @@ -16,6 +16,36 @@ 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 := (.Values.site | default dict).automaticEnrollment | default dict -}} +{{- $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 c545ee211..ab046d3dc 100644 --- a/charts/saw-portal-container/templates/auto-enroll.yaml +++ b/charts/saw-portal-container/templates/auto-enroll.yaml @@ -1,5 +1,5 @@ -{{- $s := .Values.site | default dict }}{{- $a := $s.automaticEnrollment | default dict }} -{{- if and $a (ne (get $a "enabled" | toString) "false") }} +{{- $s := include "portal.site" . | fromJson }}{{- $a := $s.automaticEnrollment | default dict }} +{{- if eq (toString $a.enabled) "true" }} {{- $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 }} diff --git a/charts/saw-portal-container/templates/enrolled-runtime.yaml b/charts/saw-portal-container/templates/enrolled-runtime.yaml index f1621368c..4154562cb 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 }} 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 48d9dce72..4eaa4c9e7 100644 --- a/charts/saw-portal-container/templates/relay.yaml +++ b/charts/saw-portal-container/templates/relay.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) $e.relay }} {{- $r := $e.relay }} diff --git a/charts/saw-portal-container/templates/stack.yaml b/charts/saw-portal-container/templates/stack.yaml index cf04318bf..e3aca72d3 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 }} @@ -70,6 +70,25 @@ spec: {{- 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") }} diff --git a/charts/saw-portal-container/values.yaml b/charts/saw-portal-container/values.yaml index ec815deab..02057a6a5 100644 --- a/charts/saw-portal-container/values.yaml +++ b/charts/saw-portal-container/values.yaml @@ -8,3 +8,101 @@ 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 runs only when a site sets enabled: true. + enabled: false + autoApprove: false + buildNamespace: saw-component-builds + resources: + requests: {cpu: 500m, memory: 1Gi} + limits: {cpu: "2", memory: 4Gi} + relay: + keycloakNamespace: saw-keycloak + keycloakProvisionerSecret: saw-relay-provisioner + 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-users/files/projector.py b/charts/saw-users/files/projector.py index fb05ae669..ecc873dca 100644 --- a/charts/saw-users/files/projector.py +++ b/charts/saw-users/files/projector.py @@ -88,7 +88,7 @@ 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 or automatic.get("autoApprove") is True: + if not automatic or automatic.get("enabled") is not True 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) diff --git a/charts/saw-users/files/workspace.py b/charts/saw-users/files/workspace.py index 1addd71e3..e1b942677 100644 --- a/charts/saw-users/files/workspace.py +++ b/charts/saw-users/files/workspace.py @@ -136,13 +136,13 @@ def publication(name): return obj["data"] fresh = {k:v for k,v in site.items() if k!="enrollment"} data=publication("saw-portal-enrollment") - if a.get("enabled") is False: + if a.get("enabled") is not True: if data: raise WorkspaceError("cannot disable enrollment of a bound workspace; use desiredState") return fresh auto = a.get("autoApprove") is True - for key, kind in ((() if auto else (("reference", dict),)) + (("relay", dict), ("revision", str), - ("image", str), ("buildNamespace", str))): + # Relay settings and the build namespace default in saw-portal-container. + for key, kind in ((() if auto else (("reference", dict),)) + (("revision", str), ("image", 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: @@ -159,8 +159,8 @@ def publication(name): sub=subjects.get("saw-portal-relay-subject","") if site.get("targets") else publication("saw-portal-relay-subject").get("subject","") if sub and (not re.fullmatch(r"[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}",sub) or sub==ws["ownerSubject"]): raise WorkspaceError("invalid relay subject") - relay={**a["relay"],"gatewayCA":bound["gatewayCA"],"subject":sub,"workspaceID":""} - fresh["enrollment"]={**{k:a[k] for k in ("revision","image","buildNamespace")},"registration":reg,"intent":intent,"approved":bound["approved"],"relay":relay} + relay={**(a.get("relay") or {}),"gatewayCA":bound["gatewayCA"],"subject":sub,"workspaceID":""} + fresh["enrollment"]={**{k:a[k] for k in ("revision","image","buildNamespace") if k in a},"registration":reg,"intent":intent,"approved":bound["approved"],"relay":relay} return fresh @@ -259,7 +259,7 @@ 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 or automatic.get("autoApprove") is True + foundation = automatic.get("enabled") is not True 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"): diff --git a/charts/saw-users/templates/_helpers.tpl b/charts/saw-users/templates/_helpers.tpl index 536d542c1..8a5e703de 100644 --- a/charts/saw-users/templates/_helpers.tpl +++ b/charts/saw-users/templates/_helpers.tpl @@ -544,9 +544,13 @@ the portal. Returns JSON. */}} {{- 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" -}} -{{- range $key, $item := ($site.stack | default dict) -}} +{{- $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 -}} diff --git a/docs/container-installation.md b/docs/container-installation.md index 2184024cb..86bcd635a 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,17 +88,22 @@ 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, 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 unique priority. | +| `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` | Shared governance location. | -| `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 reviewed boundary `reference`. Changing the profile requires its own approval. | | `imagePull` | Optional namespace and ImageStream names for access to an OpenShift internal registry. | @@ -526,8 +533,8 @@ The chart fills in the rest; an explicit value always wins: | 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. | -The defaults keep enrollment off (`automaticEnrollment.enabled: false`, -`autoApprove: false`): a new workspace deploys its foundation and waits for +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 diff --git a/docs/container-workspaces.md b/docs/container-workspaces.md index 8dea79a00..4c49c355a 100644 --- a/docs/container-workspaces.md +++ b/docs/container-workspaces.md @@ -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 diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml index e4c7db5c0..7db0af813 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -1,148 +1,32 @@ -# Cluster-wide settings for container/kata workspaces in saw-users, set once by -# the platform admin. Users only add an entry to overrides/saw-users.yaml. -# Every container user's site is built from containerDefaults; per-user -# overrides go under containerSites.. subject comes from the user's -# ownerSubject and chart revisions follow the pattern's targetRevision. -# <...> values are cluster-specific. Egress to the API server, DNS and Keycloak, -# the issuer URLs and projection.applicationSetControllerLabels are generated -# by `make container-topology` into overrides/container-network.yaml, as are -# storage classes left unset here (the cluster default for single-node volumes, -# a shared-filesystem class such as CephFS for the audit exchange volume). -# That overlay holds one cluster's addresses: commit it on your fork and list -# it after /overrides/saw-users.yaml in saw-users' extraValueFiles. +# 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 -# The self-service portal (openshell-rhdh reads this file too) keeps its -# default modes here. Offer Container (portal.deploymentModes) only once a -# reviewed site is configured, or on a demo cluster through -# overrides/saw-container-demo.yaml. - containerDefaults: - # custom-inference workspaces use their owner's own base URL (the portal form, - # or customInferenceURL in overrides/saw-users.yaml). Its host must be the one - # endpoint in overrides/governance-profiles/custom-inference.yaml, where - # OpenShell sends the API key; the runtime refuses any other host. - # The stock OpenClaw image with /sandbox searchable by OpenShift namespace - # UIDs, published by .github/workflows/build-openclaw-image.yml - # (images/saw-openclaw/Containerfile). Pin the digest of the src-<12 hex> - # tag that matches the notebook BOM's source image. Both profiles use it. - # For now: the amd64 build of source 896d1526ee29 (tag 896d1526ee29-amd64), - # until the workflow's multi-arch src-896d1526ee29 tag is published. - # Disconnected clusters can build it in-cluster instead (make - # container-notebook-image) and add the imagePull it prints. + # 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" - governanceNamespace: openshell-agents automaticEnrollment: - # Reviewed flow: a new container workspace deploys without enrollment - # until an operator has reviewed its boundary. Then, per user under - # containerSites..automaticEnrollment, set enabled: true with the - # reviewed reference and approvedProfiles digest, and pin chart revisions - # to commit SHAs (docs/container-installation.md). Development and demo - # clusters can list overrides/saw-container-demo.yaml after this file to - # auto-approve instead; never list it in production values. - enabled: false - autoApprove: false # The saw-kubernetes-runtime image, pinned by digest and pullable # anonymously from inside the cluster (make saw-init checks this). image: ghcr.io/validatedpatterns-sandbox/saw-kubernetes-runtime@sha256: - buildNamespace: saw-component-builds - resources: - requests: {cpu: 500m, memory: 1Gi} - limits: {cpu: "2", memory: 4Gi} - relay: - keycloakNamespace: saw-keycloak - keycloakProvisionerSecret: saw-relay-provisioner - egress: [] # generated - stack: - identity: - values: - enabled: true - network: - bootstrapEgress: [] # generated (API and DNS) - 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: - priority: 51 # must be unique per workspace: oc get adminnetworkpolicy - 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: quay.io/aipcc/base-images/agentic/openclaw@sha256:896d1526ee29b53167034ba65d1c758c8da777f441ed094e19f3bcf6d7445c61 - identity: - serverTlsSecret: '@OWNER@-server' - clientCaSecret: '@OWNER@-client-ca' - jwtSecret: '@OWNER@-jwt' - credentialKeySecret: '@OWNER@-kek' - storage: - gatewaySize: 1Gi - workspaceSize: 10Gi - governance: - endpoint: http://governance-interceptor.openshell-agents.svc:18081 - network: - reconcilerNamespace: '@TRUSTED@' - reconcilerLabels: - app.kubernetes.io/instance: '@OWNER@' - openshell.pattern/role: reconciler - gatewayEgress: # operator rules; API/DNS/issuer rules are generated - - to: - - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: openshell-agents}} - podSelector: {matchLabels: {app.kubernetes.io/name: governance-interceptor}} - ports: - - {protocol: TCP, port: 18081} - route: {enabled: false} - audit: - values: - enabled: true - trustedNamespace: '@ARCHIVE@' - runtimeNamespace: '@RUNTIME@' - ownerID: '@INSTALLATION@' - image: ghcr.io/openclaw/openclaw@sha256:0a5ff5e682e62afa19149df126aa50063bf65ef885b5c94713ce32dc0eb12e15 - identity: - subject: '@SUBJECT@' - username: '@OWNER@' - workspace: agent - sandbox: audited + # 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. diff --git a/scripts/container_topology.py b/scripts/container_topology.py index d3634dc7d..41ced3e9b 100644 --- a/scripts/container_topology.py +++ b/scripts/container_topology.py @@ -151,7 +151,7 @@ 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[:-1]) is None or path_value(site, path): + if path_value(site, path): continue name = discover()[kind] if not name: @@ -208,8 +208,8 @@ def discover(): 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) or not path_value(site, GATEWAY) or not path_value(site, RELAY): - raise ValueError("expected gateway and automatic enrollment relay site inputs") + 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): @@ -217,7 +217,8 @@ def discover(): 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) diff --git a/tests/charts/test_openshell_saw_chart.py b/tests/charts/test_openshell_saw_chart.py index ef55e8d8e..e03097ecd 100644 --- a/tests/charts/test_openshell_saw_chart.py +++ b/tests/charts/test_openshell_saw_chart.py @@ -1037,7 +1037,8 @@ def test_pattern_puts_keycloak_and_each_saw_in_their_own_namespaces(): 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 + # Enrollment and autoApprove stay off (the saw-portal-container defaults). + assert "enabled" not in enrollment and "autoApprove" not in enrollment 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/fixtures/container-site.yaml b/tests/fixtures/container-site.yaml index c1d328e09..e3c5960ee 100644 --- a/tests/fixtures/container-site.yaml +++ b/tests/fixtures/container-site.yaml @@ -214,6 +214,7 @@ portal: workspace: agent sandbox: audited automaticEnrollment: + enabled: true image: registry.example.test/saw-runtime-controller@sha256:966c76c969f074ea088e1499d40fd8d993ecb4df527239736df554d9d726c6d0 revision: '1111111111111111111111111111111111111111' buildNamespace: saw-builds diff --git a/tests/portal/test_portal.py b/tests/portal/test_portal.py index 38c417a93..554b767f4 100644 --- a/tests/portal/test_portal.py +++ b/tests/portal/test_portal.py @@ -2227,7 +2227,7 @@ def test_generator_publishes_only_immutable_owner_bound_data(portal): reg="a"*16; owner="9aaea20f-245f-407a-a0c3-fbd894615b90" sub="e05c1559-5009-4663-81fb-3c5facb5ced8" ws=dict(name="ada",registration=reg,installationID=owner,ownerSubject=sub) - a=dict(image="pinned@sha256:abc",revision="fixed",buildNamespace="trust",profileSHA256="bom", + a=dict(enabled=True,image="pinned@sha256:abc",revision="fixed",buildNamespace="trust",profileSHA256="bom", reference={"gateway":{}},relay={"issuer":"https://issuer","revision":"fixed"}) site={"automaticEnrollment":a} intent=dict(bindings=dict(ownerID=owner,namespace="saw-ada",ownerSubject=sub),profileRef=dict(sha256="bom")) From dbd7bbe953b55419e62c89a35334633a4025dcf5 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 19:02:13 +0000 Subject: [PATCH 40/69] Pin a test build of the Kubernetes runtime image in container defaults An amd64 build of this branch (fe412b28ed73), published to ghcr.io/sauagarwa until the build-kubernetes-runtime workflow publishes the image from main. Assisted-By: Claude --- overrides/saw-container-defaults.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml index 7db0af813..611ea8d3f 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -24,7 +24,9 @@ containerDefaults: automaticEnrollment: # The saw-kubernetes-runtime image, pinned by digest and pullable # anonymously from inside the cluster (make saw-init checks this). - image: ghcr.io/validatedpatterns-sandbox/saw-kubernetes-runtime@sha256: + # 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:b37bc7e89b44331c6204e19b592b064277a5c865a01388a924762ff6fc6b2f33 # 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 From 61062c39381965ed8b59bc1b91e5ecf571627963 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 19:28:51 +0000 Subject: [PATCH 41/69] Validate harness tool rules before writing them into the gate policy A harness bundle's MCP server name went into tool-actions.yaml unchecked. A name with newlines could add an unconditional allow rule for exec and get past the tool gate's default deny. - Reject a server name that is not 1-64 letters, digits, '_' or '-' before building its tool rules. - Check every rule again when writing the policy: exactly id, tool and action; a __ name, never a bare tool such as exec; an allow or approval action; and only characters the policy reads verbatim. - Add regression tests for the newline injection and each invalid rule shape. Assisted-By: Claude --- .../openshell-saw/files/installer/saw_core.py | 21 ++++++++++++++- .../test_harness_tool_rules.py | 27 ++++++++++++++++--- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/charts/openshell-saw/files/installer/saw_core.py b/charts/openshell-saw/files/installer/saw_core.py index 101958654..21e1bbefb 100644 --- a/charts/openshell-saw/files/installer/saw_core.py +++ b/charts/openshell-saw/files/installer/saw_core.py @@ -1128,6 +1128,15 @@ def tool_gate_bundle(here, identity, receipt_key=None, harness_rules=()): 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" @@ -1156,6 +1165,12 @@ def tool_gate_bundle(here, identity, receipt_key=None, harness_rules=()): # 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): @@ -1310,6 +1325,10 @@ def describe_harness_tree(files, inline=False, *, warn=lambda _: None): 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 " @@ -1319,7 +1338,7 @@ def describe_harness_tree(files, inline=False, *, warn=lambda _: None): for item in tools: if (not isinstance(item, dict) or set(item) != {"name", "action"} or not isinstance(item["name"], str) - or not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", item["name"]) + 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 " diff --git a/tests/kubernetes_runtime/test_harness_tool_rules.py b/tests/kubernetes_runtime/test_harness_tool_rules.py index 550b9f21f..c0592a135 100644 --- a/tests/kubernetes_runtime/test_harness_tool_rules.py +++ b/tests/kubernetes_runtime/test_harness_tool_rules.py @@ -63,13 +63,34 @@ def test_gate_policy_appends_harness_rules_after_the_base_and_pins_them(): 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 "allow" for a tool the base policy already names does not change it. + # 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) - extra = [{"id": "harness-reader-read_mail", "tool": "reader__read_mail", "action": "allow"}, - {"id": "harness-x-override", "tool": denied, "action": "allow"}] + 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"))}; From 146882f80cf4c774e49146973b4586999382a2fb Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 19:38:55 +0000 Subject: [PATCH 42/69] Offer "Allow always" for OpenClaw automation changes Every automation change (create, edit, rm, enable, disable, run) asked for approval, which is tiring when an agent reworks a schedule. Its approval card now also offers "Allow always". Later automation changes then run without asking until the gateway restarts or the policy changes. - A rule opts in with allowAlways: true, which is valid only on an approval rule. Only exec-openclaw-automation-change sets it; git push, rm, set-identity and every other approval rule still ask each time. - The approval is remembered only once its resolution is in the audit trail. Each later call is still audited, with approval.mode "remembered". - Commands that match no rule are still denied. Assisted-By: Claude --- charts/governance-policy/tool-actions.yaml | 3 + .../files/installer/tool-actions.yaml | 3 + .../files/installer/tool-gate.mjs | 38 +++++++++++-- .../files/installer/tool-gate.test.mjs | 57 +++++++++++++++++++ docs/governance-interceptor.md | 2 +- 5 files changed, 98 insertions(+), 5 deletions(-) diff --git a/charts/governance-policy/tool-actions.yaml b/charts/governance-policy/tool-actions.yaml index 7f7650989..4468d482b 100644 --- a/charts/governance-policy/tool-actions.yaml +++ b/charts/governance-policy/tool-actions.yaml @@ -47,9 +47,12 @@ rules: - openclaw automations get - openclaw automations show - openclaw automations runs + # "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 diff --git a/charts/openshell-saw/files/installer/tool-actions.yaml b/charts/openshell-saw/files/installer/tool-actions.yaml index 7f7650989..4468d482b 100644 --- a/charts/openshell-saw/files/installer/tool-actions.yaml +++ b/charts/openshell-saw/files/installer/tool-actions.yaml @@ -47,9 +47,12 @@ rules: - openclaw automations get - openclaw automations show - openclaw automations runs + # "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 diff --git a/charts/openshell-saw/files/installer/tool-gate.mjs b/charts/openshell-saw/files/installer/tool-gate.mjs index 3429a31ee..18c9a9962 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`); @@ -206,7 +212,7 @@ function baseRecord(input, extras) { }; } -function effectFor(action, tool, ruleId) { +function effectFor(action, tool, ruleId, allowAlways = false) { if (action === "allow") return { kind: "allow" }; if (action === "deny") { const why = ruleId === "default" @@ -221,7 +227,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"], }, }; } @@ -285,9 +291,21 @@ export function decide(input) { 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)), + rememberKey, }; } @@ -354,9 +372,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 +390,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 +406,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 290fd655f..486ca19c2 100644 --- a/charts/openshell-saw/files/installer/tool-gate.test.mjs +++ b/charts/openshell-saw/files/installer/tool-gate.test.mjs @@ -520,3 +520,60 @@ 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 remove 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/); +}); diff --git a/docs/governance-interceptor.md b/docs/governance-interceptor.md index 7e3b9ad72..fb6030f86 100644 --- a/docs/governance-interceptor.md +++ b/docs/governance-interceptor.md @@ -199,7 +199,7 @@ 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`/`create` 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, while `openclaw cron add`/`create`, `edit`, `rm`, `enable`, `disable` and `run` require approval. 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`. From 1b861b3222a3ca67e237d7dfb1ed1d7b84d6ba71 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 20:15:21 +0000 Subject: [PATCH 43/69] Tell the agent how to retry an exec call the tool gate blocks The gate log showed agents losing time on blocked calls: `openclaw automations list --all 2>&1`, two `show` calls chained with `;`, and `--help` piped to `head`. Each got only "exec-opaque", so the agent guessed at variants until one passed. - Ignore a trailing 2>&1, which only merges stderr into stdout. Any other redirect, chain or wrapper is still opaque. - Allow `openclaw cron --help` and `openclaw automations --help` as read-only inspection. - Say how to retry: an opaque call gets "run one command per exec call...", and an unlisted command gets "not on the allowed list, so do not retry it in another form". Assisted-By: Claude --- charts/governance-policy/tool-actions.yaml | 2 ++ .../files/installer/tool-actions.yaml | 2 ++ .../files/installer/tool-gate.mjs | 16 ++++++++++++++-- .../files/installer/tool-gate.test.mjs | 18 +++++++++++++++++- docs/governance-interceptor.md | 2 +- 5 files changed, 36 insertions(+), 4 deletions(-) diff --git a/charts/governance-policy/tool-actions.yaml b/charts/governance-policy/tool-actions.yaml index 4468d482b..2d028b41f 100644 --- a/charts/governance-policy/tool-actions.yaml +++ b/charts/governance-policy/tool-actions.yaml @@ -42,11 +42,13 @@ rules: - openclaw cron get - openclaw cron show - openclaw cron runs + - openclaw cron --help - openclaw automations list - openclaw automations status - openclaw automations get - openclaw automations show - openclaw automations runs + - openclaw automations --help # "Allow always" skips the card for later automation changes until the # gateway restarts; each call is still audited. - id: exec-openclaw-automation-change diff --git a/charts/openshell-saw/files/installer/tool-actions.yaml b/charts/openshell-saw/files/installer/tool-actions.yaml index 4468d482b..2d028b41f 100644 --- a/charts/openshell-saw/files/installer/tool-actions.yaml +++ b/charts/openshell-saw/files/installer/tool-actions.yaml @@ -42,11 +42,13 @@ rules: - openclaw cron get - openclaw cron show - openclaw cron runs + - openclaw cron --help - openclaw automations list - openclaw automations status - openclaw automations get - openclaw automations show - openclaw automations runs + - openclaw automations --help # "Allow always" skips the card for later automation changes until the # gateway restarts; each call is still audited. - id: exec-openclaw-automation-change diff --git a/charts/openshell-saw/files/installer/tool-gate.mjs b/charts/openshell-saw/files/installer/tool-gate.mjs index 18c9a9962..ca6c70923 100644 --- a/charts/openshell-saw/files/installer/tool-gate.mjs +++ b/charts/openshell-saw/files/installer/tool-gate.mjs @@ -153,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 = []; @@ -212,11 +214,21 @@ function baseRecord(input, extras) { }; } +// 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.", +}; + function effectFor(action, tool, ruleId, allowAlways = false) { 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" : ""}` : `Tool ${tool} is denied by rule ${ruleId}`; return { kind: "deny", blockReason: why }; } @@ -286,7 +298,7 @@ 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; diff --git a/charts/openshell-saw/files/installer/tool-gate.test.mjs b/charts/openshell-saw/files/installer/tool-gate.test.mjs index 486ca19c2..864cb908c 100644 --- a/charts/openshell-saw/files/installer/tool-gate.test.mjs +++ b/charts/openshell-saw/files/installer/tool-gate.test.mjs @@ -159,7 +159,7 @@ 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"]) { const result = call({ params: { command: `openclaw ${group} ${verb} --json` } }); assert.equal(result.effect.kind, "allow"); assert.equal(result.record.rule, "exec-openclaw-automation-inspect"); @@ -577,3 +577,19 @@ test("allowAlways is only valid as true on an approval rule", () => { 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/); + assert.match(call({ toolName: "web_fetch", params: {} }).effect.blockReason, /^Tool web_fetch is denied by the default action$/); +}); diff --git a/docs/governance-interceptor.md b/docs/governance-interceptor.md index fb6030f86..40ad8ceb4 100644 --- a/docs/governance-interceptor.md +++ b/docs/governance-interceptor.md @@ -202,7 +202,7 @@ OpenClaw loads `saw-tool-gate` from `/sandbox/.saw/trusted/plugin` through `plug - 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`/`create`, `edit`, `rm`, `enable`, `disable` and `run` require approval. 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. - 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. From 981a52ad18f68ceeece646e05623054b458531f2 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 20:32:06 +0000 Subject: [PATCH 44/69] Accept every spelling of automation removal and its help pages Agents reach for `openclaw automations remove` and `--help` on change commands. remove was denied with no way forward, and `edit --help` asked for approval like a real edit. - rm, remove and delete all ask for approval, with Allow always as for the other automation changes. - ` --help` for every automation command runs directly. - An unlisted command lists the accepted commands that share its first two words, split into those that run directly and those that ask for approval, so the agent can use a working spelling. Assisted-By: Claude --- charts/governance-policy/tool-actions.yaml | 22 ++++++++++++++ .../files/installer/tool-actions.yaml | 22 ++++++++++++++ .../files/installer/tool-gate.mjs | 29 +++++++++++++++++-- .../files/installer/tool-gate.test.mjs | 12 +++++--- docs/governance-interceptor.md | 4 +-- 5 files changed, 80 insertions(+), 9 deletions(-) diff --git a/charts/governance-policy/tool-actions.yaml b/charts/governance-policy/tool-actions.yaml index 2d028b41f..029dc993c 100644 --- a/charts/governance-policy/tool-actions.yaml +++ b/charts/governance-policy/tool-actions.yaml @@ -43,12 +43,30 @@ rules: - 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 @@ -60,6 +78,8 @@ rules: - openclaw cron create - openclaw cron edit - openclaw cron rm + - openclaw cron remove + - openclaw cron delete - openclaw cron enable - openclaw cron disable - openclaw cron run @@ -67,6 +87,8 @@ rules: - 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-actions.yaml b/charts/openshell-saw/files/installer/tool-actions.yaml index 2d028b41f..029dc993c 100644 --- a/charts/openshell-saw/files/installer/tool-actions.yaml +++ b/charts/openshell-saw/files/installer/tool-actions.yaml @@ -43,12 +43,30 @@ rules: - 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 @@ -60,6 +78,8 @@ rules: - openclaw cron create - openclaw cron edit - openclaw cron rm + - openclaw cron remove + - openclaw cron delete - openclaw cron enable - openclaw cron disable - openclaw cron run @@ -67,6 +87,8 @@ rules: - 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 ca6c70923..22a029999 100644 --- a/charts/openshell-saw/files/installer/tool-gate.mjs +++ b/charts/openshell-saw/files/installer/tool-gate.mjs @@ -223,12 +223,34 @@ const EXEC_HINTS = { + "Each command is checked on its own.", }; -function effectFor(action, tool, ruleId, allowAlways = false) { +// 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 === "exec" - ? ": this command is not on the allowed list, so do not retry it in another form" : ""}` + ? `: 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 }; } @@ -316,7 +338,8 @@ export function decide(input) { } return { record: baseRecord(input, { task, rule: ruleId, policyHash, decision: decisionName(action) }), - effect: effectFor(action, tool, ruleId, Boolean(rememberKey)), + effect: effectFor(action, tool, ruleId, Boolean(rememberKey), + exec && !rule ? sameFamily(policy, command) : ""), rememberKey, }; } diff --git a/charts/openshell-saw/files/installer/tool-gate.test.mjs b/charts/openshell-saw/files/installer/tool-gate.test.mjs index 864cb908c..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", "--help"]) { + 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", "create", "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 ["", "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 [ @@ -548,7 +548,7 @@ test("allow always skips later automation approvals but never other rules", () = push.hook.requireApproval.onResolution("allow-always"); assert.ok(run("git push").hook.requireApproval); // Unmatched commands are still denied. - assert.equal(run("openclaw cron remove job-1").hook.block, true); + 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", () => { @@ -591,5 +591,9 @@ test("a trailing 2>&1 is accepted, and blocked exec calls say how to retry", () 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/docs/governance-interceptor.md b/docs/governance-interceptor.md index 40ad8ceb4..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`/`create`, `edit`, `rm`, `enable`, `disable` and `run` require approval. 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. +- 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`. 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. +- `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. From 1bd11d8290ebb4a21d4696e5c2b819f1f22e1e63 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 20:49:56 +0000 Subject: [PATCH 45/69] Let a profile set the custom model's thinking level OpenClaw offers only "default" and "off" thinking for a custom provider's model, so `/think medium` was refused for the custom-inference model. - A sandbox's `inference.thinking` (off, minimal, low, medium or high) becomes that model's default thinking level (agents.defaults.models[""].params.thinking). A chat's /think still overrides it. - Any level other than off also marks the model's entry reasoning: true, with compat.supportedReasoningEfforts [low, medium, high]. OpenClaw then offers those levels and sends reasoning_effort. - Removing the setting removes the default it set. - VM workspaces only for now; the container runtime builds the OpenClaw config separately. Assisted-By: Claude --- .../files/installer/apply_bom.py | 43 ++++++++++++++++++- .../openshell-saw/files/installer/saw_core.py | 21 +++++++-- docs/custom-inference.md | 6 +++ tests/installer/test_custom_endpoint.py | 36 ++++++++++++++++ 4 files changed, 101 insertions(+), 5 deletions(-) diff --git a/charts/openshell-saw/files/installer/apply_bom.py b/charts/openshell-saw/files/installer/apply_bom.py index 35d8b0ad7..93304c215 100644 --- a/charts/openshell-saw/files/installer/apply_bom.py +++ b/charts/openshell-saw/files/installer/apply_bom.py @@ -3976,7 +3976,10 @@ 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 and thinking != "off": + self.mark_reasoning_model(exec_cmd, oc_env, provider.type, model_id) + 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 +3992,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 +4006,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 +4067,35 @@ 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): + """Let OpenClaw offer thinking levels for a custom provider's model. + + 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).""" + 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", {}) + if entry.get("reasoning") is True and compat.get("supportedReasoningEfforts") == REASONING_EFFORTS: + return + entry["reasoning"] = True + compat["supportedReasoningEfforts"] = REASONING_EFFORTS + 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_core.py b/charts/openshell-saw/files/installer/saw_core.py index 21e1bbefb..7499cde79 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,9 @@ 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") + 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: @@ -721,7 +724,12 @@ def secret_ref_problems(src): return out -INFERENCE_KEYS = {"providerRef", "protocol", "baseUrl", "model", "models", "timeoutSeconds"} +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 +956,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 +1017,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 +1073,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', diff --git a/docs/custom-inference.md b/docs/custom-inference.md index 049ab7d47..1352fcab7 100644 --- a/docs/custom-inference.md +++ b/docs/custom-inference.md @@ -146,6 +146,12 @@ 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. A + chat's `/think` still overrides the default. VM workspaces only for now. ### Keycloak compatibility diff --git a/tests/installer/test_custom_endpoint.py b/tests/installer/test_custom_endpoint.py index acacf09bc..2abd9f2f0 100644 --- a/tests/installer/test_custom_endpoint.py +++ b/tests/installer/test_custom_endpoint.py @@ -384,3 +384,39 @@ 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"}] + # 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"})) From 7191dddc8b009bd1f605a32d46383ca3368e6bc0 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 21:00:33 +0000 Subject: [PATCH 46/69] Mark a custom model not reasoning when its thinking is off `inference.thinking: off` set only the default level. The model entry kept whatever reasoning flag it had, including one an earlier level set. Off now also sets reasoning: false and drops the effort list, matching MODEL_REASONING=false, so OpenClaw sends no reasoning_effort. Assisted-By: Claude --- .../files/installer/apply_bom.py | 24 ++++++++++++------- docs/custom-inference.md | 3 ++- tests/installer/test_custom_endpoint.py | 7 ++++++ 3 files changed, 25 insertions(+), 9 deletions(-) diff --git a/charts/openshell-saw/files/installer/apply_bom.py b/charts/openshell-saw/files/installer/apply_bom.py index 93304c215..130cac5ac 100644 --- a/charts/openshell-saw/files/installer/apply_bom.py +++ b/charts/openshell-saw/files/installer/apply_bom.py @@ -3977,8 +3977,9 @@ def start_openclaw(self, ws, sb, provider): except ValueError as exc: raise InstallerError(f"cannot read OpenClaw managed models: {exc}") from None thinking = (sb.inference_values or {}).get("thinking", "") - if thinking and thinking != "off": - self.mark_reasoning_model(exec_cmd, oc_env, provider.type, model_id) + 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", @@ -4067,12 +4068,13 @@ 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): - """Let OpenClaw offer thinking levels for a custom provider's model. + 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).""" + 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) @@ -4089,10 +4091,16 @@ def mark_reasoning_model(self, exec_cmd, oc_env, provider_type, model_id): "applies only if OpenClaw already treats it as a reasoning model") return compat = entry.setdefault("compat", {}) - if entry.get("reasoning") is True and compat.get("supportedReasoningEfforts") == REASONING_EFFORTS: + efforts = REASONING_EFFORTS if reasoning else None + if entry.get("reasoning") is reasoning and compat.get("supportedReasoningEfforts") == efforts: return - entry["reasoning"] = True - compat["supportedReasoningEfforts"] = REASONING_EFFORTS + 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))}") diff --git a/docs/custom-inference.md b/docs/custom-inference.md index 1352fcab7..ffbd78419 100644 --- a/docs/custom-inference.md +++ b/docs/custom-inference.md @@ -150,7 +150,8 @@ stated (`openai`): the installer cannot infer it for a profile of your own. 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. A + which OpenClaw sends as `reasoning_effort`; the endpoint may ignore it. + `off` marks it `reasoning: false` instead (like `MODEL_REASONING=false`). A chat's `/think` still overrides the default. VM workspaces only for now. ### Keycloak compatibility diff --git a/tests/installer/test_custom_endpoint.py b/tests/installer/test_custom_endpoint.py index 2abd9f2f0..25765389f 100644 --- a/tests/installer/test_custom_endpoint.py +++ b/tests/installer/test_custom_endpoint.py @@ -408,6 +408,13 @@ def test_a_thinking_level_marks_the_model_as_reasoning_and_sets_its_default( 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) From d53095ee2739d6612966a3093fe9624c77d0d943 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 21:02:29 +0000 Subject: [PATCH 47/69] Read an unquoted YAML `thinking: off` as off YAML 1.1 reads `off` as false, so a profile with `thinking: off` failed validation with "thinking must be one of ...". Treat false as off. Assisted-By: Claude --- charts/openshell-saw/files/installer/saw_core.py | 10 +++++++++- docs/custom-inference.md | 3 ++- tests/installer/test_custom_endpoint.py | 8 ++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/charts/openshell-saw/files/installer/saw_core.py b/charts/openshell-saw/files/installer/saw_core.py index 7499cde79..5138cd96e 100644 --- a/charts/openshell-saw/files/installer/saw_core.py +++ b/charts/openshell-saw/files/installer/saw_core.py @@ -418,6 +418,7 @@ 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)) @@ -514,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) @@ -724,6 +725,13 @@ def secret_ref_problems(src): return out +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 diff --git a/docs/custom-inference.md b/docs/custom-inference.md index ffbd78419..696436dc1 100644 --- a/docs/custom-inference.md +++ b/docs/custom-inference.md @@ -151,7 +151,8 @@ stated (`openai`): the installer cannot infer it for a profile of your own. `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`). A + `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/tests/installer/test_custom_endpoint.py b/tests/installer/test_custom_endpoint.py index 25765389f..b139c6351 100644 --- a/tests/installer/test_custom_endpoint.py +++ b/tests/installer/test_custom_endpoint.py @@ -427,3 +427,11 @@ 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" From 43b54205b2a5bba92167389a470a9468d15d896d Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 21:51:42 +0000 Subject: [PATCH 48/69] Restore the enrollment-enabled semantics the projection tests encode fe412b28 changed enrollment to require an explicit enabled: true and let relay and buildNamespace default in saw-portal-container. But the static saw-users projection runs before the siteDefaults merge, and the projection test suite encodes the established model: only an explicit enabled: false disables enrollment, and an active site must carry relay, revision, image and buildNamespace. The change broke six projection tests (two of them security checks: reviewed-site rejection and the Kata preflight) that CI caught after the chart suites passed. - Revert the enabled check to `is False` in enrolled_site, the foundation gate, verify_gitops_preflight and check_live_boundary_approval (both chart copies). - Restore relay and buildNamespace to the enrolled_site validation. - Keep the enrollment policy (enabled, autoApprove), image, buildNamespace and relay Keycloak settings in overrides/saw-container-defaults.yaml, where the projector reads them; siteDefaults keeps only the template-layer wiring and the enrollment Job's resources. - Gate the enrollment templates on the raw site, since siteDefaults now adds an automaticEnrollment.resources default to every site. - Revert the test fixtures that were compensating for the broken semantics. Assisted-By: Claude --- charts/openshell-rhdh/files/portal.py | 2 +- charts/openshell-rhdh/files/workspace.py | 12 ++++++------ .../templates/auto-enroll.yaml | 2 +- charts/saw-portal-container/values.yaml | 12 +++++------- charts/saw-users/files/projector.py | 2 +- charts/saw-users/files/workspace.py | 12 ++++++------ overrides/saw-container-defaults.yaml | 16 +++++++++++----- tests/charts/test_openshell_saw_chart.py | 3 +-- tests/fixtures/container-site.yaml | 1 - tests/portal/test_portal.py | 2 +- 10 files changed, 33 insertions(+), 31 deletions(-) diff --git a/charts/openshell-rhdh/files/portal.py b/charts/openshell-rhdh/files/portal.py index 400d80de6..83ebed6c9 100644 --- a/charts/openshell-rhdh/files/portal.py +++ b/charts/openshell-rhdh/files/portal.py @@ -812,7 +812,7 @@ 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 not True + 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) diff --git a/charts/openshell-rhdh/files/workspace.py b/charts/openshell-rhdh/files/workspace.py index e1b942677..1addd71e3 100644 --- a/charts/openshell-rhdh/files/workspace.py +++ b/charts/openshell-rhdh/files/workspace.py @@ -136,13 +136,13 @@ def publication(name): return obj["data"] fresh = {k:v for k,v in site.items() if k!="enrollment"} data=publication("saw-portal-enrollment") - if a.get("enabled") is not True: + if a.get("enabled") is False: if data: raise WorkspaceError("cannot disable enrollment of a bound workspace; use desiredState") return fresh auto = a.get("autoApprove") is True - # Relay settings and the build namespace default in saw-portal-container. - for key, kind in ((() if auto else (("reference", dict),)) + (("revision", str), ("image", str))): + 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: @@ -159,8 +159,8 @@ def publication(name): sub=subjects.get("saw-portal-relay-subject","") if site.get("targets") else publication("saw-portal-relay-subject").get("subject","") if sub and (not re.fullmatch(r"[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}",sub) or sub==ws["ownerSubject"]): raise WorkspaceError("invalid relay subject") - relay={**(a.get("relay") or {}),"gatewayCA":bound["gatewayCA"],"subject":sub,"workspaceID":""} - fresh["enrollment"]={**{k:a[k] for k in ("revision","image","buildNamespace") if k in a},"registration":reg,"intent":intent,"approved":bound["approved"],"relay":relay} + relay={**a["relay"],"gatewayCA":bound["gatewayCA"],"subject":sub,"workspaceID":""} + fresh["enrollment"]={**{k:a[k] for k in ("revision","image","buildNamespace")},"registration":reg,"intent":intent,"approved":bound["approved"],"relay":relay} return fresh @@ -259,7 +259,7 @@ 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 not True or automatic.get("autoApprove") is True + 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"): diff --git a/charts/saw-portal-container/templates/auto-enroll.yaml b/charts/saw-portal-container/templates/auto-enroll.yaml index ab046d3dc..5d2176f03 100644 --- a/charts/saw-portal-container/templates/auto-enroll.yaml +++ b/charts/saw-portal-container/templates/auto-enroll.yaml @@ -1,5 +1,5 @@ {{- $s := include "portal.site" . | fromJson }}{{- $a := $s.automaticEnrollment | default dict }} -{{- if eq (toString $a.enabled) "true" }} +{{- 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 }} diff --git a/charts/saw-portal-container/values.yaml b/charts/saw-portal-container/values.yaml index 02057a6a5..77aa73997 100644 --- a/charts/saw-portal-container/values.yaml +++ b/charts/saw-portal-container/values.yaml @@ -15,16 +15,14 @@ driverDefaults: siteDefaults: governanceNamespace: openshell-agents automaticEnrollment: - # Enrollment runs only when a site sets enabled: true. - enabled: false - autoApprove: false - buildNamespace: saw-component-builds + # 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} - relay: - keycloakNamespace: saw-keycloak - keycloakProvisionerSecret: saw-relay-provisioner stack: identity: values: diff --git a/charts/saw-users/files/projector.py b/charts/saw-users/files/projector.py index ecc873dca..fb05ae669 100644 --- a/charts/saw-users/files/projector.py +++ b/charts/saw-users/files/projector.py @@ -88,7 +88,7 @@ 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 not True or automatic.get("autoApprove") is True: + 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) diff --git a/charts/saw-users/files/workspace.py b/charts/saw-users/files/workspace.py index e1b942677..1addd71e3 100644 --- a/charts/saw-users/files/workspace.py +++ b/charts/saw-users/files/workspace.py @@ -136,13 +136,13 @@ def publication(name): return obj["data"] fresh = {k:v for k,v in site.items() if k!="enrollment"} data=publication("saw-portal-enrollment") - if a.get("enabled") is not True: + if a.get("enabled") is False: if data: raise WorkspaceError("cannot disable enrollment of a bound workspace; use desiredState") return fresh auto = a.get("autoApprove") is True - # Relay settings and the build namespace default in saw-portal-container. - for key, kind in ((() if auto else (("reference", dict),)) + (("revision", str), ("image", str))): + 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: @@ -159,8 +159,8 @@ def publication(name): sub=subjects.get("saw-portal-relay-subject","") if site.get("targets") else publication("saw-portal-relay-subject").get("subject","") if sub and (not re.fullmatch(r"[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}",sub) or sub==ws["ownerSubject"]): raise WorkspaceError("invalid relay subject") - relay={**(a.get("relay") or {}),"gatewayCA":bound["gatewayCA"],"subject":sub,"workspaceID":""} - fresh["enrollment"]={**{k:a[k] for k in ("revision","image","buildNamespace") if k in a},"registration":reg,"intent":intent,"approved":bound["approved"],"relay":relay} + relay={**a["relay"],"gatewayCA":bound["gatewayCA"],"subject":sub,"workspaceID":""} + fresh["enrollment"]={**{k:a[k] for k in ("revision","image","buildNamespace")},"registration":reg,"intent":intent,"approved":bound["approved"],"relay":relay} return fresh @@ -259,7 +259,7 @@ 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 not True or automatic.get("autoApprove") is True + 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"): diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml index 611ea8d3f..fc4544ff7 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -22,13 +22,19 @@ containerDefaults: custom-inference: notebook: "ghcr.io/sauagarwa/saw-openclaw@sha256:05f17f3872f864e44231fb3cea30cd4dd2ba9887b382a67b261f068a234b79a2" automaticEnrollment: - # 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:b37bc7e89b44331c6204e19b592b064277a5c865a01388a924762ff6fc6b2f33 # 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:b37bc7e89b44331c6204e19b592b064277a5c865a01388a924762ff6fc6b2f33 + buildNamespace: saw-component-builds + relay: + keycloakNamespace: saw-keycloak + keycloakProvisionerSecret: saw-relay-provisioner diff --git a/tests/charts/test_openshell_saw_chart.py b/tests/charts/test_openshell_saw_chart.py index e03097ecd..ef55e8d8e 100644 --- a/tests/charts/test_openshell_saw_chart.py +++ b/tests/charts/test_openshell_saw_chart.py @@ -1037,8 +1037,7 @@ def test_pattern_puts_keycloak_and_each_saw_in_their_own_namespaces(): 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"] - # Enrollment and autoApprove stay off (the saw-portal-container defaults). - assert "enabled" not in enrollment and "autoApprove" not in enrollment + 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/fixtures/container-site.yaml b/tests/fixtures/container-site.yaml index e3c5960ee..c1d328e09 100644 --- a/tests/fixtures/container-site.yaml +++ b/tests/fixtures/container-site.yaml @@ -214,7 +214,6 @@ portal: workspace: agent sandbox: audited automaticEnrollment: - enabled: true image: registry.example.test/saw-runtime-controller@sha256:966c76c969f074ea088e1499d40fd8d993ecb4df527239736df554d9d726c6d0 revision: '1111111111111111111111111111111111111111' buildNamespace: saw-builds diff --git a/tests/portal/test_portal.py b/tests/portal/test_portal.py index 554b767f4..38c417a93 100644 --- a/tests/portal/test_portal.py +++ b/tests/portal/test_portal.py @@ -2227,7 +2227,7 @@ def test_generator_publishes_only_immutable_owner_bound_data(portal): reg="a"*16; owner="9aaea20f-245f-407a-a0c3-fbd894615b90" sub="e05c1559-5009-4663-81fb-3c5facb5ced8" ws=dict(name="ada",registration=reg,installationID=owner,ownerSubject=sub) - a=dict(enabled=True,image="pinned@sha256:abc",revision="fixed",buildNamespace="trust",profileSHA256="bom", + a=dict(image="pinned@sha256:abc",revision="fixed",buildNamespace="trust",profileSHA256="bom", reference={"gateway":{}},relay={"issuer":"https://issuer","revision":"fixed"}) site={"automaticEnrollment":a} intent=dict(bindings=dict(ownerID=owner,namespace="saw-ada",ownerSubject=sub),profileRef=dict(sha256="bom")) From c9ed0dfa71dbc6bbcdea42af9dc52e1e0b2ea99c Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 01:06:30 +0000 Subject: [PATCH 49/69] Stop generating the unused saw-users governed-profiles.json The catalog generator wrote charts/saw-users/files/governed-profiles.json, but nothing reads it: no template loads it and no code opens it. Providers are declared in saw-bom and checked against the governance profiles that openshell-saw ships (and the runtime image bakes in), or against the live interceptor. Remove the file and its generator entry. Assisted-By: Claude --- charts/saw-users/files/governed-profiles.json | 550 ------------------ scripts/saw-profile-catalog.py | 4 +- .../test_profile_catalog_automation.py | 4 +- 3 files changed, 3 insertions(+), 555 deletions(-) delete mode 100644 charts/saw-users/files/governed-profiles.json 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/scripts/saw-profile-catalog.py b/scripts/saw-profile-catalog.py index d6d6c7d29..fa1907b1e 100644 --- a/scripts/saw-profile-catalog.py +++ b/scripts/saw-profile-catalog.py @@ -579,9 +579,7 @@ def main(argv=None): (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/templates/_governed-proxy-policy.tpl", policy_template.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/tests/scripts/test_profile_catalog_automation.py b/tests/scripts/test_profile_catalog_automation.py index a6943b46b..876c4e881 100644 --- a/tests/scripts/test_profile_catalog_automation.py +++ b/tests/scripts/test_profile_catalog_automation.py @@ -70,12 +70,12 @@ def test_list_names_every_generated_file(): 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 + assert "charts/saw-users/files/governed-profiles.json" 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) == 11 + 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 From 32e63cafdd370770462805d420f80988b1357afe Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 01:08:16 +0000 Subject: [PATCH 50/69] Stop mirroring the governed proxy policy template into saw-users The catalog generator copied openshell-saw's _governed-proxy-policy.tpl into saw-users, but no saw-users template calls saw.governedProxyPolicy. Its only caller is openshell-saw's credential proxy, which uses openshell-saw's own copy. Remove the saw-users copy and its generator entry. Assisted-By: Claude --- .../templates/_governed-proxy-policy.tpl | 52 ------------------- scripts/saw-profile-catalog.py | 5 +- .../test_profile_catalog_automation.py | 7 +-- 3 files changed, 5 insertions(+), 59 deletions(-) delete mode 100644 charts/saw-users/templates/_governed-proxy-policy.tpl 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/scripts/saw-profile-catalog.py b/scripts/saw-profile-catalog.py index fa1907b1e..789e30b61 100644 --- a/scripts/saw-profile-catalog.py +++ b/scripts/saw-profile-catalog.py @@ -570,16 +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/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/tests/scripts/test_profile_catalog_automation.py b/tests/scripts/test_profile_catalog_automation.py index 876c4e881..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" not 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) == 11 + 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 From ebba07c2bab9d348c542e39c5ee548ee26987e84 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 01:15:01 +0000 Subject: [PATCH 51/69] Give the quickstart an explicit make saw-init step Option B mentioned saw-init only in a comment, with no command to run, and said it creates an in-cluster NFS server when no shared-filesystem class exists. That is opt-in now (SAW_SHARED_STORAGE=nfs); otherwise saw-init stops and lists the options. Add step 4b with the command and the current behaviour. Assisted-By: Claude --- README.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index be86a0371..78d837029 100644 --- a/README.md +++ b/README.md @@ -371,13 +371,18 @@ export OPENSHELL_SAW_NAME=alice # the user VM, deployed into namespace saw-a # 4. Verify prerequisites after CNV and RHBK are installed make quickstart-prereqs-check -# Container or kata workspaces (DEPLOYMENT_MODE=container|kata) also need -# OpenShift GitOps installed: their components are Argo CD Applications even -# here. `make saw-create` runs `make saw-init` first for those modes; run it -# now: without a shared-filesystem StorageClass it creates a small in-cluster NFS server. # 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 From 12b41341c64d8cad4b407b3df016ee42aa571390 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 01:55:36 +0000 Subject: [PATCH 52/69] Split the README's add-a-user step into VM, container and Kata Step 7 showed the VM commands, then a comment for container mode that still pointed to make saw-logs ("apply: Done"), which only exists for VMs. Give each mode its own steps: - 7a VM: unchanged. - 7b container: one-time saw-init and network overlay, the enrollment default (off unless the demo overlay is listed), creating the Keycloak account first to get ownerSubject, the entry, and how to watch the Argo apps and the sandbox Pod. - 7c Kata: as container, plus the reviewed RuntimeClass binding. Also say that container and Kata entries default to pruneOnRemove: true. Assisted-By: Claude --- README.md | 55 ++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 44 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 78d837029..8d4efb2f0 100644 --- a/README.md +++ b/README.md @@ -304,26 +304,58 @@ make saw-init # 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" -# Container workspace instead of a VM: add the Keycloak subject and mode, e.g. +# +# 7b. Container workspace. Once per cluster: run make saw-init (step 5d) +# and, after Keycloak is up, generate the network overlay: +# make container-topology > overrides/container-network.yaml, commit it on +# your fork and list it after saw-users.yaml in saw-users' extraValueFiles +# (it holds this cluster's addresses, so it is not in this repository). +# 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: +# 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. Once, after Keycloak is up, generate the network -# overlay: make container-topology > overrides/container-network.yaml, commit -# it on your fork and list it after saw-users.yaml in saw-users' -# extraValueFiles (it holds this cluster's addresses, so it is not in this -# repository). See docs/container-installation.md#minimal-static-entries. +# 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). @@ -348,8 +380,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) From fac2da842db093e9a82d421fdcb10c754a7356c4 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 21:05:48 -0500 Subject: [PATCH 53/69] Add alice (container) --- overrides/saw-users.yaml | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/overrides/saw-users.yaml b/overrides/saw-users.yaml index e6174da35..6fed5d7da 100644 --- a/overrides/saw-users.yaml +++ b/overrides/saw-users.yaml @@ -14,7 +14,18 @@ # inference.model: # values: # deployment: {mode: container} -users: [] +#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. From 4213d95d7559c025ab0bc2def886b7f789400e9d Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 02:46:24 +0000 Subject: [PATCH 54/69] Make the container network overlay a real README step Step 7b mentioned make container-topology only inside a comment, so it read as background rather than a step. Give it command lines (generate, list in extraValueFiles, commit), and say what fails without it. Assisted-By: Claude --- README.md | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 8d4efb2f0..ed05472c2 100644 --- a/README.md +++ b/README.md @@ -316,11 +316,17 @@ 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: run make saw-init (step 5d) -# and, after Keycloak is up, generate the network overlay: -# make container-topology > overrides/container-network.yaml, commit it on -# your fork and list it after saw-users.yaml in saw-users' extraValueFiles -# (it holds this cluster's addresses, so it is not in this repository). +# 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 From 0a6ea8c8cfc79dd419f12dffc49595dd4451edcb Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 02:57:32 +0000 Subject: [PATCH 55/69] TEMPORARY: vvkp4siy test configuration (revert before merge) For testing alice's container workspace on cluster vvkp4siy, which deploys this branch directly: - overrides/container-network.yaml: this cluster's API, DNS and Keycloak egress, storage classes and ApplicationSet controller labels (make container-topology). - values-prod.yaml: list it, and the demo overlay (enrollment on first observation), in saw-users' extraValueFiles. - custom-inference governance profile: api.enmaas.devshift.net. Revert this commit, and fac2da84 (alice's entry), before PR #173 merges. PR tests that expect the shipped values and example host fail until then. Assisted-By: Claude --- overrides/container-network.yaml | 215 ++++++++++++++++++ .../governance-profiles/custom-inference.yaml | 2 +- values-prod.yaml | 2 + 3 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 overrides/container-network.yaml diff --git a/overrides/container-network.yaml b/overrides/container-network.yaml new file mode 100644 index 000000000..871a53a19 --- /dev/null +++ b/overrides/container-network.yaml @@ -0,0 +1,215 @@ +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 + 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 +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/values-prod.yaml b/values-prod.yaml index 9bf24733c..a2939a3ad 100644 --- a/values-prod.yaml +++ b/values-prod.yaml @@ -112,7 +112,9 @@ clusterGroup: 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" From 6497663b01aed508b1ae8a6f12646cae5b5fb0eb Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 03:07:02 +0000 Subject: [PATCH 56/69] Create the projector ApplicationSet after its identity Job The ApplicationSet and the identity Job that creates its plugin token Secret were in the same sync wave. On a first install the ApplicationSet controller read the Secret before the Job had created it and stayed Degraded ("error fetching Secret token") until something refreshed it. Put the ApplicationSet in wave 1, so Argo CD creates it once the wave-0 Job has completed. Assisted-By: Claude --- charts/saw-users/templates/projector.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/charts/saw-users/templates/projector.yaml b/charts/saw-users/templates/projector.yaml index de67c8591..36c1b623a 100644 --- a/charts/saw-users/templates/projector.yaml +++ b/charts/saw-users/templates/projector.yaml @@ -282,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] From b5172ca62056e01ebc5ece9881937453f7acfb0e Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 03:09:16 +0000 Subject: [PATCH 57/69] Default the runtime image when a site sets no gateway workload The container defaults no longer set the gateway's workload block (its image comes from the first sandbox target), but the runtime policy read $gw.workload.runtimeImage directly. A site with no workload block, which is what the shipped defaults now produce, failed to render saw-alice ("nil pointer evaluating interface {}.runtimeImage"). Read it with dig and fall back to driverDefaults.runtimeImage, and add a regression test that renders a site without a workload block. Assisted-By: Claude --- .../saw-portal-container/templates/stack.yaml | 2 +- tests/charts/test_portal_container.py | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/charts/saw-portal-container/templates/stack.yaml b/charts/saw-portal-container/templates/stack.yaml index e3aca72d3..1865e04ef 100644 --- a/charts/saw-portal-container/templates/stack.yaml +++ b/charts/saw-portal-container/templates/stack.yaml @@ -112,7 +112,7 @@ spec: {{- $_ := 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) }} +{{- $_ := 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 }} diff --git a/tests/charts/test_portal_container.py b/tests/charts/test_portal_container.py index b8f9383f7..bfb9e5a7b 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 @@ -441,3 +442,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 From 7c66fb9b1977eb18394c8289a8cfbb7b5f9f728b Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 03:17:07 +0000 Subject: [PATCH 58/69] Allow the router pods when the issuer is behind a LoadBalancer On ARO the Keycloak route resolves to the external IP of the router's LoadBalancer Service. OVN-Kubernetes delivers pod traffic for that IP straight to the router pods before network policy is checked, so the overlay's ipBlock rule never matched: the container gateway's OIDC discovery failed and it crash-looped. The topology probe still passed because it runs from a pod outside these policies. When an issuer address is a LoadBalancer Service's external IP, also allow that Service's pods on its target port. The ipBlock rule stays, for clusters where the traffic does leave through the load balancer. Assisted-By: Claude --- scripts/container_topology.py | 45 +++++++++++++++++++++++- tests/scripts/test_container_topology.py | 38 ++++++++++++++++++++ 2 files changed, 82 insertions(+), 1 deletion(-) diff --git a/scripts/container_topology.py b/scripts/container_topology.py index 41ced3e9b..d86baa7b7 100644 --- a/scripts/container_topology.py +++ b/scripts/container_topology.py @@ -111,6 +111,48 @@ 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")) @@ -224,7 +266,8 @@ def discover(): 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) diff --git a/tests/scripts/test_container_topology.py b/tests/scripts/test_container_topology.py index abe13da15..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}]}}) @@ -288,6 +294,8 @@ def test_make_commands_and_helm_gateway_policy(tmp_path, monkeypatch, base): 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: @@ -324,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) From 0249b01390b528d6ce5b9412302617dc5ce35ea0 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Mon, 23 Nov 2026 22:18:24 -0500 Subject: [PATCH 59/69] TEMPORARY: vvkp4siy overlay with router egress --- overrides/container-network.yaml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/overrides/container-network.yaml b/overrides/container-network.yaml index 871a53a19..501f69414 100644 --- a/overrides/container-network.yaml +++ b/overrides/container-network.yaml @@ -57,6 +57,16 @@ containerDefaults: 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: @@ -165,6 +175,16 @@ containerDefaults: 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: From 09e0836ab0f2139808dacc04b7827a77d50b09bc Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 03:34:08 +0000 Subject: [PATCH 60/69] Grant image pulls only for in-cluster runtime images The enrollment Job, tool gate and relay got ImageStream pull Roles in buildNamespace even when the runtime image is published to an external registry, so a site without that namespace failed to sync. Render the grants (and pass imageBuildNamespace) only for images from the internal OpenShift registry. Assisted-By: Claude --- .../templates/_helpers.tpl | 8 +++++ .../templates/auto-enroll.yaml | 6 ++-- .../templates/enrolled-runtime.yaml | 8 +++-- .../saw-portal-container/templates/relay.yaml | 2 +- .../saw-workspace-relay/templates/access.yaml | 2 ++ tests/charts/test_portal_container.py | 32 ++++++++++++++++++- 6 files changed, 51 insertions(+), 7 deletions(-) diff --git a/charts/saw-portal-container/templates/_helpers.tpl b/charts/saw-portal-container/templates/_helpers.tpl index 87b047597..195f01797 100644 --- a/charts/saw-portal-container/templates/_helpers.tpl +++ b/charts/saw-portal-container/templates/_helpers.tpl @@ -12,6 +12,14 @@ {{ $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). */}} diff --git a/charts/saw-portal-container/templates/auto-enroll.yaml b/charts/saw-portal-container/templates/auto-enroll.yaml index 5d2176f03..a39dbe2ed 100644 --- a/charts/saw-portal-container/templates/auto-enroll.yaml +++ b/charts/saw-portal-container/templates/auto-enroll.yaml @@ -70,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 diff --git a/charts/saw-portal-container/templates/enrolled-runtime.yaml b/charts/saw-portal-container/templates/enrolled-runtime.yaml index 4154562cb..906814f11 100644 --- a/charts/saw-portal-container/templates/enrolled-runtime.yaml +++ b/charts/saw-portal-container/templates/enrolled-runtime.yaml @@ -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 }} @@ -107,7 +109,7 @@ 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 }} diff --git a/charts/saw-portal-container/templates/relay.yaml b/charts/saw-portal-container/templates/relay.yaml index 4eaa4c9e7..59b65b019 100644 --- a/charts/saw-portal-container/templates/relay.yaml +++ b/charts/saw-portal-container/templates/relay.yaml @@ -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-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/tests/charts/test_portal_container.py b/tests/charts/test_portal_container.py index bfb9e5a7b..18dbc2ee7 100644 --- a/tests/charts/test_portal_container.py +++ b/tests/charts/test_portal_container.py @@ -408,11 +408,41 @@ 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_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, From 1a1b1ea4b25436b97568837ee3230abbda270262 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 04:05:03 +0000 Subject: [PATCH 61/69] Keep the admin session until the gateway trusts its CA Under TLS 1.3 the gateway rejects a not-yet-trusted client certificate after the handshake, so the trust probe saw a transport error rather than UNAUTHENTICATED and re-raised it. Each reconciler cycle then dropped its session and minted a new CA, which never outran the ~60s kubelet Secret propagation, so the controller never reached the gateway. Treat transport codes as trust pending within the bounded wait, and give every per-run CA a distinct subject so a stale CA cannot shadow it. Assisted-By: Claude --- .../files/installer/saw_admin.py | 2 +- .../saw_kubernetes/admin_session.py | 10 ++++- .../kubernetes_runtime/test_admin_session.py | 38 +++++++++++++++++++ 3 files changed, 48 insertions(+), 2 deletions(-) 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/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/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 From 67bd4521e88d3edf83070c02685fc4951e4e8224 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 04:18:28 +0000 Subject: [PATCH 62/69] Pin the runtime image with the admin trust fix Assisted-By: Claude --- overrides/saw-container-defaults.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml index fc4544ff7..8817457bd 100644 --- a/overrides/saw-container-defaults.yaml +++ b/overrides/saw-container-defaults.yaml @@ -33,7 +33,7 @@ containerDefaults: # 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:b37bc7e89b44331c6204e19b592b064277a5c865a01388a924762ff6fc6b2f33 + image: ghcr.io/sauagarwa/saw-kubernetes-runtime@sha256:86ab0fca61a1728952b036240653e9167cb677d7a7cb0e7d43f7378de425f923 buildNamespace: saw-component-builds relay: keycloakNamespace: saw-keycloak From 03f386aaadd837f84e5d1cd6fc7dab5cbfe6b01a Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 04:26:57 +0000 Subject: [PATCH 63/69] TEMPORARY: use the in-cluster governance interceptor on vvkp4siy Revert before merge. Assisted-By: Claude --- values-prod.yaml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/values-prod.yaml b/values-prod.yaml index a2939a3ad..3192362d2 100644 --- a/values-prod.yaml +++ b/values-prod.yaml @@ -166,6 +166,12 @@ clusterGroup: name: governance-interceptor namespace: openshell-agents path: charts/governance-interceptor + # TEMPORARY (vvkp4siy): the published interceptor predates mTLS operator + # support; use the one built in-cluster from this branch. Revert before merge. + overrides: + - name: image + value: image-registry.openshift-image-registry.svc:5000/saw-component-builds/governance-interceptor@sha256:3eb0d373a2acbf283765a720d78bd3ee6849bf26aee23f59f81ea920d52facf8 + forceString: true syncPolicy: automated: prune: true From 2b637bc9f4838b086da705edc58cfec7f8380b4d Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 04:33:26 +0000 Subject: [PATCH 64/69] Set up the relay registrar from the Keycloak chart Container workspaces' browser relays need the saw-relay-provisioner credential, which came from a one-time script run by hand; a cluster that skipped it left every relay identity Job stuck on a missing Secret. Run it as a Deployment in openshell-keycloak (like the redirect registrar), enabled in values-prod. It discovers the Keycloak route, creates and keeps the Secret itself so a GitOps self-heal cannot clear the credential, adopts one made by the old script, and retries instead of running to a deadline. Retire scripts/portal-container/setup-relay-provisioner.py. Assisted-By: Claude --- .../files/relay-provisioner.py | 224 ++++++++++++++++++ .../templates/relay-provisioner.yaml | 198 ++++++++++++++++ charts/openshell-keycloak/values.yaml | 16 ++ docs/container-installation.md | 31 +-- .../setup-relay-provisioner.py | 174 -------------- tests/charts/test_openshell_keycloak_chart.py | 27 +++ tests/scripts/test_relay_provisioner.py | 116 +++++++++ values-prod.yaml | 3 + 8 files changed, 595 insertions(+), 194 deletions(-) create mode 100644 charts/openshell-keycloak/files/relay-provisioner.py create mode 100644 charts/openshell-keycloak/templates/relay-provisioner.yaml delete mode 100644 scripts/portal-container/setup-relay-provisioner.py create mode 100644 tests/scripts/test_relay_provisioner.py 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/docs/container-installation.md b/docs/container-installation.md index 86bcd635a..e36e3ce6d 100644 --- a/docs/container-installation.md +++ b/docs/container-installation.md @@ -179,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 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/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/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/values-prod.yaml b/values-prod.yaml index 3192362d2..d642000cb 100644 --- a/values-prod.yaml +++ b/values-prod.yaml @@ -92,6 +92,9 @@ 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: From 88795214f8edf6ff3521a4f4b432143e2653b855 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 04:34:29 +0000 Subject: [PATCH 65/69] Let workspace Jobs wait for inputs from other components The relay identity Job mounts the registrar Secret and gate preparation mounts the relay's browser proof. Both spent their 300s/360s deadlines in ContainerCreating while those were still being produced, and Argo never recreates a failed Job, so each needed a manual delete. Allow 30 minutes; the kubelet starts the pod as soon as its input exists. Relay identity deletion keeps its short deadline. Assisted-By: Claude --- .../saw-portal-container/templates/enrolled-runtime.yaml | 4 +++- charts/saw-workspace-relay/templates/identity.yaml | 5 ++++- tests/charts/test_portal_container.py | 8 ++++++++ tests/charts/test_workspace_relay.py | 9 +++++++++ 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/charts/saw-portal-container/templates/enrolled-runtime.yaml b/charts/saw-portal-container/templates/enrolled-runtime.yaml index 906814f11..1f81eaddf 100644 --- a/charts/saw-portal-container/templates/enrolled-runtime.yaml +++ b/charts/saw-portal-container/templates/enrolled-runtime.yaml @@ -70,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 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/tests/charts/test_portal_container.py b/tests/charts/test_portal_container.py index 18dbc2ee7..df9d759b6 100644 --- a/tests/charts/test_portal_container.py +++ b/tests/charts/test_portal_container.py @@ -428,6 +428,14 @@ def pull_grant_render(image): 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.""" 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) From bad370ac60c72a65c5c58de243669cfc73aa1c52 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 04:52:42 +0000 Subject: [PATCH 66/69] Let maintainers publish a branch build of the governance interceptor The chart's interceptor must carry SAW extension changes (such as mTLS operator support) before they reach main, and an amd64 Rust build does not survive emulation on a laptop. Add a publish input to the workflow's manual run: native per-architecture builds pushed to ghcr.io// with only the :sha- tag, digest in the run summary. :latest and the OpenShell release tag still move only from main, and pull requests still never publish. Other image workflows are unchanged. Assisted-By: Claude --- .github/actions/build-push-image/action.yml | 35 ++++++++++++++----- .github/actions/merge-image/action.yml | 13 +++++-- .../build-governance-interceptor.yml | 14 +++++--- .../test_governance_interceptor_image.py | 25 +++++++++++-- 4 files changed, 69 insertions(+), 18 deletions(-) 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/tests/charts/test_governance_interceptor_image.py b/tests/charts/test_governance_interceptor_image.py index b270c13d7..85864ee57 100644 --- a/tests/charts/test_governance_interceptor_image.py +++ b/tests/charts/test_governance_interceptor_image.py @@ -228,11 +228,32 @@ def test_pr_image_jobs_cannot_publish(filename): 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] From 0e8f7ae2efa72f691078e25a0c44e6ff9da80bbb Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 04:59:02 +0000 Subject: [PATCH 67/69] Pin a governance interceptor that admits the mTLS operator The pinned interceptor (built Nov 12) predates mTLS operator support (118b4cfa), so it rejected the container reconciler's sandbox submission with PERMISSION_DENIED. Pin a build of the current SAW extension. Assisted-By: Claude --- charts/governance-interceptor/values.yaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) 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 From 1352295ecd41b499a6cc431fccea587a29ceb955 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 05:00:32 +0000 Subject: [PATCH 68/69] Let CI publish branch builds of every image the branch pins The branch pins saw-openclaw, saw-kubernetes-runtime and the governance interceptor from a fork's ghcr namespace. Give the openclaw and runtime workflows the same manual publish input as the interceptor (native per-arch builds, :sha- only, never from a pull request), and test that every image pinned outside the project's namespace has such a workflow. Assisted-By: Claude --- .../workflows/build-kubernetes-runtime.yml | 14 +++++++---- .github/workflows/build-openclaw-image.yml | 14 +++++++---- .../test_governance_interceptor_image.py | 24 ++++++++++++++++++- 3 files changed, 43 insertions(+), 9 deletions(-) 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 index 5d20dc3e2..a64d9f7d5 100644 --- a/.github/workflows/build-openclaw-image.yml +++ b/.github/workflows/build-openclaw-image.yml @@ -22,6 +22,11 @@ on: - .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 @@ -32,7 +37,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: @@ -68,13 +73,14 @@ jobs: 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' && secrets.GITHUB_TOKEN || '' }} + 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 }} @@ -83,7 +89,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/tests/charts/test_governance_interceptor_image.py b/tests/charts/test_governance_interceptor_image.py index 85864ee57..1e9b2ab43 100644 --- a/tests/charts/test_governance_interceptor_image.py +++ b/tests/charts/test_governance_interceptor_image.py @@ -222,7 +222,8 @@ 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"} @@ -257,3 +258,24 @@ def test_a_branch_publish_never_moves_shared_tags(): 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) From 4f4e01610dbaa56d3d67d2b1d4d81e30ad88e534 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Tue, 24 Nov 2026 05:00:53 +0000 Subject: [PATCH 69/69] Revert "TEMPORARY: use the in-cluster governance interceptor on vvkp4siy" The chart now pins a published interceptor with mTLS operator support. Assisted-By: Claude --- values-prod.yaml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/values-prod.yaml b/values-prod.yaml index d642000cb..4f32e677d 100644 --- a/values-prod.yaml +++ b/values-prod.yaml @@ -169,12 +169,6 @@ clusterGroup: name: governance-interceptor namespace: openshell-agents path: charts/governance-interceptor - # TEMPORARY (vvkp4siy): the published interceptor predates mTLS operator - # support; use the one built in-cluster from this branch. Revert before merge. - overrides: - - name: image - value: image-registry.openshift-image-registry.svc:5000/saw-component-builds/governance-interceptor@sha256:3eb0d373a2acbf283765a720d78bd3ee6849bf26aee23f59f81ea920d52facf8 - forceString: true syncPolicy: automated: prune: true