From 9bb88ceea00f378d41a64a3bc43f887055670947 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Wed, 25 Nov 2026 07:17:13 +0000 Subject: [PATCH 1/9] Workspace runtime for container and Kata workspaces The saw-kubernetes-runtime controller that drives a user's stock OpenShell gateway: it compiles the workspace plan, enrolls it, and reconciles the workspace, providers and sandboxes. - OpenClaw tool gate: automation approvals, retry hints, harness rules and model thinking, with a best-effort local audit log by default and signed fail-closed receipts as an option. The audit mount stays on log/. - Superseded tool-gate trees are kept for sandboxes that still mount them. - Native providers: an already-configured refresh is observed, not resent. - A credentialed provider's live profile must match the shipped governed profile exactly: every endpoint's host, ports, path, protocol, access and rules (custom inference: the site's host). - Kata: the boundary check requires the workload and the supervisor in the approved RuntimeClass. Assisted-By: Claude --- kubernetes-runtime/Containerfile | 4 +- kubernetes-runtime/saw_kubernetes/adapters.py | 5 +- .../saw_kubernetes/admin_session.py | 10 +- kubernetes-runtime/saw_kubernetes/boundary.py | 31 +-- kubernetes-runtime/saw_kubernetes/compiler.py | 71 ++++-- .../saw_kubernetes/controller.py | 6 +- kubernetes-runtime/saw_kubernetes/harness.py | 13 +- .../saw_kubernetes/portal_contract.py | 14 -- .../saw_kubernetes/prepare_gate.py | 70 ++++-- kubernetes-runtime/saw_kubernetes/provider.py | 151 ++++++----- .../saw_kubernetes/reconcile.py | 238 +++++++++++++++--- kubernetes-runtime/saw_kubernetes/serve.py | 40 ++- tests/kubernetes_runtime/profile_fixtures.py | 7 +- .../kubernetes_runtime/test_admin_session.py | 38 +++ tests/kubernetes_runtime/test_boundary.py | 17 +- tests/kubernetes_runtime/test_briefing.py | 53 +++- tests/kubernetes_runtime/test_controller.py | 8 + .../test_custom_inference.py | 33 +-- tests/kubernetes_runtime/test_gate_update.py | 82 ++++++ .../test_governance_contract.py | 6 + .../test_harness_tool_rules.py | 115 +++++++++ .../test_inference_providers.py | 15 +- tests/kubernetes_runtime/test_intent.py | 2 +- tests/kubernetes_runtime/test_openclaw.py | 15 +- .../test_portal_contract.py | 11 +- .../kubernetes_runtime/test_portal_profile.py | 2 +- .../test_provider_endpoints.py | 156 ++++++++++++ .../test_provider_governance.py | 20 -- .../test_provider_recovery.py | 122 ++++++++- .../test_provider_refresh.py | 175 +++++++++++++ .../test_proxy_ca_projection.py | 126 ---------- .../test_proxy_era_upgrade.py | 30 +++ .../kubernetes_runtime/test_rpc_allowlist.py | 15 ++ 33 files changed, 1295 insertions(+), 406 deletions(-) create mode 100644 tests/kubernetes_runtime/test_gate_update.py create mode 100644 tests/kubernetes_runtime/test_harness_tool_rules.py create mode 100644 tests/kubernetes_runtime/test_provider_endpoints.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 create mode 100644 tests/kubernetes_runtime/test_proxy_era_upgrade.py create mode 100644 tests/kubernetes_runtime/test_rpc_allowlist.py diff --git a/kubernetes-runtime/Containerfile b/kubernetes-runtime/Containerfile index e50b368da..1edc3542b 100644 --- a/kubernetes-runtime/Containerfile +++ b/kubernetes-runtime/Containerfile @@ -17,6 +17,8 @@ COPY charts/openshell-saw/files/provider-profiles/ charts/openshell-saw/files/pr COPY charts/saw-users/files/workspace.py /opt/saw/kubernetes-runtime/saw_workspace.py COPY kubernetes-runtime/saw_kubernetes kubernetes-runtime/saw_kubernetes ENV PYTHONPATH=/opt/saw/kubernetes-runtime:/opt/saw/sdk PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 -RUN python3 -c 'from openshell._proto import openshell_pb2_grpc; from saw_kubernetes import serve' +# COPY keeps the builder's file modes; the runtime runs as a non-root UID. +RUN chmod -R a+rX,go-w /opt/saw USER 1001 +RUN python3 -c 'from openshell._proto import openshell_pb2_grpc; from saw_kubernetes import serve' ENTRYPOINT ["python3", "-m", "saw_kubernetes.serve"] diff --git a/kubernetes-runtime/saw_kubernetes/adapters.py b/kubernetes-runtime/saw_kubernetes/adapters.py index 11535a3ed..406aa0e5b 100644 --- a/kubernetes-runtime/saw_kubernetes/adapters.py +++ b/kubernetes-runtime/saw_kubernetes/adapters.py @@ -12,8 +12,9 @@ RPC_METHODS = { "GetGatewayInfo", "GetWorkspace", "CreateWorkspace", "ListWorkspaceMembers", - "AddWorkspaceMember", "GetProviderProfile", "GetProvider", "CreateProvider", "GetSandbox", - "CreateSandbox", "StartSandbox", "StopSandbox", + "AddWorkspaceMember", "GetProviderProfile", "ListProviderProfiles", "GetProvider", + "CreateProvider", "UpdateProvider", "ConfigureProviderRefresh", "RotateProviderCredential", + "GetProviderRefreshStatus", "GetSandbox", "CreateSandbox", "StartSandbox", "StopSandbox", } diff --git a/kubernetes-runtime/saw_kubernetes/admin_session.py b/kubernetes-runtime/saw_kubernetes/admin_session.py index d34d71cb9..2a2757c93 100644 --- a/kubernetes-runtime/saw_kubernetes/admin_session.py +++ b/kubernetes-runtime/saw_kubernetes/admin_session.py @@ -26,6 +26,8 @@ OWNER = "saw.redhat.com/runtime-owner" NAME = re.compile(r"[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?\Z") OPERATOR_SUBJECT = "/O=openshell/OU=operator/CN=saw-installer" +# Codes a probe sees while the gateway does not trust the session CA yet. +TRUST_PENDING = frozenset({"UNAVAILABLE", "UNAUTHENTICATED", "DEADLINE_EXCEEDED", "UNKNOWN", "INTERNAL"}) def encoded(raw): @@ -200,7 +202,13 @@ def accepted(): gateway.call("GetGatewayInfo", {}) return True except RpcError as exc: - if exc.code not in {"UNAVAILABLE", "UNAUTHENTICATED"}: raise + # Under TLS 1.3 the gateway rejects a not-yet-trusted + # client certificate after the handshake, so the probe + # sees a broken read (UNKNOWN/INTERNAL/DEADLINE_EXCEEDED) + # rather than UNAUTHENTICATED. Re-raising here ended the + # session and minted a fresh CA every cycle, which never + # outran the kubelet's Secret propagation. + if exc.code not in TRUST_PENDING: raise return False admin.wait_for_trust(accepted) gateway.timeout = 20 diff --git a/kubernetes-runtime/saw_kubernetes/boundary.py b/kubernetes-runtime/saw_kubernetes/boundary.py index ea2c1c667..1d6aca740 100644 --- a/kubernetes-runtime/saw_kubernetes/boundary.py +++ b/kubernetes-runtime/saw_kubernetes/boundary.py @@ -4,7 +4,6 @@ import yaml -from . import provider as governed class BoundaryError(ValueError): @@ -55,10 +54,6 @@ def objects(config): "governanceService": (f"{core}/{governance}/services/governance-interceptor", "spec"), "governancePolicy": (f"{core}/{governance}/configmaps/governance-interceptor-policy", "data"), "governanceProfiles": (f"{core}/{governance}/configmaps/governance-interceptor-profiles", "data"), - "proxy": (f"{apps}/{trusted}/deployments/{gateway}-credential-proxy", "spec"), - "proxyNetwork": (f"{net}/{trusted}/networkpolicies/{gateway}-credential-proxy", "spec"), - "proxyPolicy": (f"{core}/{trusted}/configmaps/{config['proxyPolicy']}", "data"), - "publicCA": (f"{core}/{ns}/configmaps/{gateway}-proxy-ca", "data"), } @@ -89,10 +84,18 @@ def excludes_namespace(policy, namespace): return isinstance(name, str) and bool(name) and name != namespace +# Objects of the removed SAW credential proxy. An approval that still lists +# them was published by the proxy-era controller; it cannot be upgraded in +# place, only re-enrolled (a new generation). +PROXY_ERA_OBJECTS = frozenset({"proxy", "proxyNetwork", "proxyPolicy", "publicCA"}) + + def verify(config, plan, get): if (config["namespace"], config["namespaceUID"], config["ownerID"], config["mode"]) != ( plan["namespace"], plan["namespaceUID"], plan["ownerID"], plan["mode"]): raise BoundaryError("WrongInstallation") + if PROXY_ERA_OBJECTS & set(config["approved"]): + raise BoundaryError("ReenrollRequired") refs = objects(config) if set(config["approved"]) != set(refs): raise BoundaryError("IncompleteApproval") @@ -105,26 +108,14 @@ 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 driver = tomllib.loads(observed["gatewayConfig"]["data"]["gateway.toml"])["openshell"]["drivers"]["kubernetes"] runtime = config.get("workloadRuntimeClass") if (not runtime or plan.get("runtimeClass", {}).get("name", runtime) != runtime - or driver.get("default_runtime_class_name") != runtime): + or driver.get("default_runtime_class_name") != runtime + or driver.get("supervisor_runtime_class_name") != runtime): raise BoundaryError("WrongWorkloadPlacement") checks.append("sandboxPlacement") for key in checks: @@ -148,7 +139,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..892713163 100644 --- a/kubernetes-runtime/saw_kubernetes/compiler.py +++ b/kubernetes-runtime/saw_kubernetes/compiler.py @@ -28,9 +28,9 @@ SAFE_FAILURE_REASONS = frozenset({ "ProfileRejected", "InvalidPlan", "PlacementRejected", "IdentityConflict", "InvalidIntent", "StaleIntent", "ReconcilerStateRejected", "GatewayMismatch", - "ProviderProfileMismatch", + "ProviderProfileMismatch", "ProviderRefreshFailed", "WorkspaceRejected", "ProviderRejected", "SandboxRejected", - "SandboxStateMismatch", "SandboxDrift", + "SandboxStateMismatch", "SandboxDrift", "ReenrollRequired", }) @@ -98,8 +98,14 @@ def _storage(binding, workspace): volumes, mounts, refs = [volume], [mount], [reference] if "toolGate" in binding: gate = binding["toolGate"] - mapping(gate, {"trusted", "audit", "ownerLogin", "receiptKey", "modelSelector", "harness"}, {"trusted", "audit", "ownerLogin"}, "toolGate") + mapping(gate, {"trusted", "audit", "ownerLogin", "receiptKey", "localAudit", "modelSelector", "harness"}, {"trusted", "audit", "ownerLogin"}, "toolGate") name(gate["ownerLogin"], "toolGate ownerLogin", 63) + # localAudit: the gate appends a best-effort log to its own audit volume. + # Otherwise that volume is an exchange with the receipt writer (or, in old + # plans, a sealed append-only file). Either way the governance extension + # admits only its log/ subtree; the kubelet creates it group-writable. + if "localAudit" in gate and (gate["localAudit"] is not True or "receiptKey" in gate): + raise ContractError("localAudit is true, and only without a receipt key") for field, volume_name, path, readonly in [ ("trusted", "saw-gate", "/sandbox/.saw/trusted", True), ("audit", "saw-audit", "/sandbox/.saw/audit", False), @@ -167,7 +173,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 +182,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 +203,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 +231,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 +255,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 +304,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 +343,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 @@ -376,8 +391,11 @@ def compile_profile_files(files, config): identity = shared.tool_gate_identity(login, config["ownerSubject"], ws_name, sandbox.name) assets = Path(shared.__file__).parent receipt_key = bindings[key]["toolGate"].get("receiptKey") + local_audit = bindings[key]["toolGate"].get("localAudit") is True 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() @@ -401,9 +419,13 @@ def compile_profile_files(files, config): if browser: script = script.replace("for (const path of treeFiles(root).sort()) {", "for (const path of treeFiles(root).sort()) {\n if (path === root + '/relay-proof') continue;") - if receipt_key: + if receipt_key or local_audit: # Keep the VM-style file preflight for previously published plans. - script = script[:script.index("if (!fs.lstatSync(audit)")] + """ + script = script[:script.index("if (!fs.lstatSync(audit)")] + (""" +// Best-effort audit: the plugin appends each tool decision here, as in VM mode. +fs.closeSync(fs.openSync(audit, O_WRONLY | O_APPEND | fs.constants.O_CREAT | O_NOFOLLOW, 0o600)); +if (!fs.lstatSync(audit).isFile()) throw new Error('audit trail must be a regular file'); +""" if local_audit else "") + """ config.plugins = {allow:['saw-tool-gate'],load:{paths:[root+'/plugin']}, entries:{'saw-tool-gate':{enabled:true}}}; config.tools = {allow:['read','write','exec']}; @@ -422,10 +444,13 @@ def compile_profile_files(files, config): if expected_harness != gate.get("harness"): raise ContractError("sandbox harness differs from its enrolled binding") if expected_harness: - if not gate.get("receiptKey") or sandbox.type not in ("openclaw", "nemoclaw"): - raise ContractError("harness requires an enrolled agent and signed tool gate") + if not (gate.get("receiptKey") or gate.get("localAudit")) or sandbox.type not in ("openclaw", "nemoclaw"): + raise ContractError("harness requires an enrolled agent and its tool gate") provider_types = {p.type for p in workspace.providers if p.enabled and p.name in sandbox.providers} - catalog = {t: governed.requirements(t)[1] for t in provider_types if t in governed.SUPPORTED} + # The providers the gateway serves, as in VM mode; enrollment has + # no gateway yet and leaves this check to the controller. + catalog = (None if gateway_profiles is None else + {t: gateway_profiles[t] for t in provider_types if t in gateway_profiles}) harness.configure(command, driver, bundles[expected_harness["name"]], workspace, sandbox, catalog) except shared.InstallerError as exc: raise ContractError(str(exc)) from exc diff --git a/kubernetes-runtime/saw_kubernetes/controller.py b/kubernetes-runtime/saw_kubernetes/controller.py index de1a8b5df..f092c2be9 100644 --- a/kubernetes-runtime/saw_kubernetes/controller.py +++ b/kubernetes-runtime/saw_kubernetes/controller.py @@ -358,8 +358,10 @@ def _once(self): if intent["desiredState"] == "Running": try: self.verify_boundary(plan) - except Exception: - raise InputError("BoundaryRejected") from None + except Exception as exc: + # Only the proxy-era approval gets its own reason: the fix is a re-enrollment. + reason = "ReenrollRequired" if str(exc) == "ReenrollRequired" else "BoundaryRejected" + raise InputError(reason) from None # Stopped delegates to the core's identity-checked shutdown path. # Renewed network/attachment approval must not prevent stopping an # already recorded sandbox. Input fencing above remains mandatory. diff --git a/kubernetes-runtime/saw_kubernetes/harness.py b/kubernetes-runtime/saw_kubernetes/harness.py index eadc2a73d..56bdfdd41 100644 --- a/kubernetes-runtime/saw_kubernetes/harness.py +++ b/kubernetes-runtime/saw_kubernetes/harness.py @@ -32,17 +32,28 @@ def binding_for(sandbox, bundles): return {"name": bundle.name, "digest": bundle.digest} +def tool_rules(bundle): + """The enrolled bundle's own tool rules, for the gate policy and the allowlist.""" + if bundle is None: + return [] + return shared.harness_tool_rules(shared.describe_harness_tree(bundle_tree(bundle), inline=True)) + + def configure(command, driver, bundle, workspace, sandbox, catalog): """Add only the approved RO tree and retain the existing signed tool gate.""" info = shared.describe_harness_tree(bundle_tree(bundle), inline=True) attached = {p.type for p in workspace.providers if p.enabled and p.name in sandbox.providers} - shared.check_harness_governance(workspace, sandbox, info, catalog, attached) + if catalog is not None: # None: checked later against the gateway's profiles + shared.check_harness_governance(workspace, sandbox, info, catalog, attached) config = shared.openclaw_harness_config(info) ids = shared.harness_plugin_ids(info) if any(not re.fullmatch(r"[a-zA-Z0-9_-]+", name) or name == "saw-tool-gate" for name in ids): raise shared.InstallerError("invalid or reserved harness plugin ID") policy = yaml.safe_load((Path(shared.__file__).parent / "tool-actions.yaml").read_text()) tools = {r["tool"] for r in policy["rules"] if r["action"] in ("allow", "approval")} + # The bundle's own tools, unless the base policy already decides them (as in the gate). + named = {r["tool"] for r in policy["rules"]} + tools |= {r["tool"] for r in shared.harness_tool_rules(info) if r["tool"] not in named} discovery = {"tool_search", "tool_call"} mcp_tools = sorted(t for t in tools if t in discovery or t.partition("__")[0] in info["mcpServers"]) spec = {"trustEnv": shared.MCP_TRUST_ENV, "tools": mcp_tools, "digest": bundle.digest, "paths": config.get("plugins.load.paths", []), diff --git a/kubernetes-runtime/saw_kubernetes/portal_contract.py b/kubernetes-runtime/saw_kubernetes/portal_contract.py index 76dbf3f8e..8f54163ab 100644 --- a/kubernetes-runtime/saw_kubernetes/portal_contract.py +++ b/kubernetes-runtime/saw_kubernetes/portal_contract.py @@ -9,7 +9,6 @@ import ipaddress import json import re -import ssl from .boundary import BoundaryError, fingerprint, objects @@ -25,19 +24,6 @@ def contract(config, get): # Cluster installation is shared across registrations. Keep both UID and hash. output[key]={"uid":obj["metadata"]["uid"],"sha256":fingerprint(value)} continue - if key=="publicCA": - source=get(f"/api/v1/namespaces/{trusted}/configmaps/{config['gateway']}-proxy-ca") - if obj.get("metadata",{}).get("labels",{}).get("saw.redhat.com/runtime-owner")!=owner or set(value)!={"ca.crt"} or value!=source.get("data") or source["metadata"].get("deletionTimestamp"): - raise BoundaryError("UntrustedProxyCA") - cert=value["ca.crt"] - if not re.fullmatch(r"-----BEGIN CERTIFICATE-----\s+[A-Za-z0-9+/=\s]+-----END CERTIFICATE-----\s*",cert): - raise BoundaryError("InvalidProxyCA") - try: - ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT).load_verify_locations(cadata=cert) - except (ssl.SSLError,ValueError) as exc: - raise BoundaryError("InvalidProxyCA") from exc - output[key]="equals independent trusted proxy public CA" - continue if key=="gatewayService": ips=value.get("clusterIPs") if (value.get("type")!="ClusterIP" or not isinstance(ips,list) or not ips or value.get("clusterIP")!=ips[0] diff --git a/kubernetes-runtime/saw_kubernetes/prepare_gate.py b/kubernetes-runtime/saw_kubernetes/prepare_gate.py index 5d382c89c..29530df85 100644 --- a/kubernetes-runtime/saw_kubernetes/prepare_gate.py +++ b/kubernetes-runtime/saw_kubernetes/prepare_gate.py @@ -9,6 +9,10 @@ from .core import shared +# Superseded trees are kept beside the live one and never removed here: a +# running sandbox's subPath mount stays on the tree it started with, and a +# policy update does not restart it. Each tree is a few KB. + def verify(directory, files, model_selector=False, browser=False): if directory.is_symlink() or not directory.is_dir(): @@ -28,27 +32,38 @@ 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) + publish_tree(root, target, files, model_selector=model is not None, browser=browser, replace=True) if model is not None: publish_model(root, target, model, generation) return digest -def publish_tree(root, target, files, *, model_selector=False, browser=False): +def _write_tree(scratch, files): + tmp = Path(scratch) / "bundle" + tmp.mkdir(mode=0o755) + for rel, (data, _) in files.items(): + path = tmp / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + path.chmod(0o444) + return tmp + + +def publish_tree(root, target, files, *, model_selector=False, browser=False, replace=False): + """Publish `files` at `target`, write-once unless `replace` allows an update. + + A content-addressed tree (a harness) is never replaced. The gate tree + is: a policy update for the same owner installs the new tree atomically + and keeps every previous one for sandboxes still running on it. A tree + for another owner, or one that is not a plain directory, is refused. + """ if not target.exists(): with tempfile.TemporaryDirectory(dir=root) as scratch: - tmp = Path(scratch) / "bundle" - tmp.mkdir(mode=0o755) - for rel, (data, _) in files.items(): - path = tmp / rel - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(data) - path.chmod(0o444) - # The final nonempty tree is never overwritten, including concurrent publishers. + tmp = _write_tree(scratch, files) try: tmp.rename(target) except FileExistsError: @@ -56,6 +71,30 @@ def publish_tree(root, target, files, *, model_selector=False, browser=False): except OSError: if not target.is_dir(): raise + try: + verify(target, files, model_selector=model_selector, browser=browser) + return + except ValueError: + if not replace: + raise + with (root / ".bundle-lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + try: # A concurrent publisher of the same tree may have won. + verify(target, files, model_selector=model_selector, browser=browser) + return + except ValueError: + pass + if target.is_symlink() or not target.is_dir(): + raise ValueError("invalid gate directory") + identity = target / "identity.json" + if (not identity.is_file() or identity.is_symlink() + or identity.read_bytes() != files["identity.json"][0]): + raise ValueError("existing gate belongs to another owner or workspace") + with tempfile.TemporaryDirectory(dir=root) as scratch: + tmp = _write_tree(scratch, files) + previous = Path(tempfile.mkdtemp(prefix="superseded-", dir=root)) + target.rename(previous / "bundle") + tmp.rename(target) verify(target, files, model_selector=model_selector, browser=browser) @@ -66,6 +105,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 +172,11 @@ def publish_browser_proof(directory, proof): from .receipt import receipt_key args.receipt_key = receipt_key(args.writer_service, args.writer_namespace, args.writer_ca) os.umask(0o022) + rules = [] if args.harness: - publish_harness(Path("/volume"), Path("/bom"), *args.harness) - result = publish(Path("/volume"), shared.tool_gate_identity(args.owner, args.subject, args.workspace, args.sandbox), args.receipt_key, model=args.model, generation=args.model_generation, browser=bool(args.browser_proof)) + from .harness import tool_rules + rules = tool_rules(publish_harness(Path("/volume"), Path("/bom"), *args.harness)) + result = publish(Path("/volume"), shared.tool_gate_identity(args.owner, args.subject, args.workspace, args.sandbox), args.receipt_key, model=args.model, generation=args.model_generation, browser=bool(args.browser_proof), harness_rules=rules) if args.browser_proof: publish_browser_proof(Path("/volume/bundle"), Path(args.browser_proof).read_bytes()) print(result) diff --git a/kubernetes-runtime/saw_kubernetes/provider.py b/kubernetes-runtime/saw_kubernetes/provider.py index c917691b6..5c5d535f6 100644 --- a/kubernetes-runtime/saw_kubernetes/provider.py +++ b/kubernetes-runtime/saw_kubernetes/provider.py @@ -1,4 +1,15 @@ -"""Verify Kubernetes proxy bindings against the same shipped governance profiles as the VM.""" +"""Provider helpers for configuring the agent. + +OpenShell owns provider security: profiles decide which endpoints a credential +may reach, and the supervisor substitutes the real value only for those. This +module tells the agent which environment variable holds its inference key, +checks the site's custom inference URL, and names the endpoints each +credentialed provider's profile must list (approved_endpoints), which the +reconciler compares with the live profile; for a shipped profile it also +compares every endpoint's path, protocol, access and rules +(approved_endpoint_specs). +""" +import json import re import ipaddress from functools import lru_cache @@ -10,18 +21,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 +40,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 +49,72 @@ 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": + 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] + + +# The profile YAML's access preset as the gateway returns it (NetworkAccessPreset). +ACCESS = {"": "", "read-only": "NETWORK_ACCESS_PRESET_READ_ONLY", + "read-write": "NETWORK_ACCESS_PRESET_READ_WRITE", "full": "NETWORK_ACCESS_PRESET_FULL"} + + +def _pruned(value): + """Drop default (empty) values, as protobuf JSON omits them.""" + if isinstance(value, dict): + kept = {key: _pruned(item) for key, item in value.items()} + return {key: item for key, item in kept.items() if item not in (None, "", [], {}, 0, False)} + if isinstance(value, list): + return [_pruned(item) for item in value] + return value + + +def endpoint_spec(endpoint, *, shipped): + """Everything that decides where and how a credential may be used on one + endpoint: host, ports, path, protocol, access preset and L7 rules. A + shipped profile is YAML; a live one is the gateway's NetworkEndpoint JSON.""" + access = endpoint.get("access") or "" + if shipped: + if access not in ACCESS: + raise ValueError("unknown access preset in a shipped profile") + access = ACCESS[access] + elif access == "NETWORK_ACCESS_PRESET_UNSPECIFIED": + access = "" + ports = endpoint.get("ports") or [endpoint.get("port") or 443] + rules = lambda key: tuple(sorted(json.dumps(_pruned(rule), sort_keys=True) + for rule in endpoint.get(key) or [])) + return (str(endpoint.get("host", "")).lower(), tuple(sorted(int(port) for port in ports)), + endpoint.get("path") or "", str(endpoint.get("protocol") or "").lower(), access, + rules("rules"), rules("deny_rules")) + + +def approved_endpoint_specs(kind): + """The shipped governed profile's endpoints, one entry each (never merged + by host and port), or None for custom inference, whose profile is the + site's own and is checked by host only.""" + if kind == "custom-inference": + return None + 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 sorted(endpoint_spec(e, shipped=True) for e in _shipped(kind).get("endpoints", [])) + + +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": - # Same contract as the VM: the trusted Secret's url supplies the marker - # host. No static profile may add hosts, even under another binding. - return (policy.get("markerPrefix") == "saw-cred" - and not policy["profiles"].get(kind) - and policy["allowHosts"] == hosts - and len(policy["bindings"]) == 1 - and any(b.get("providers") == [kind] and b.get("key") == "api_key" - and not b.get("refresh") and credentials == {slot["env_vars"][0]: - shared.credential_marker("saw-cred", b["secret"], b["key"])} for b in policy["bindings"])) - - if (policy.get("markerPrefix") != "saw-cred" or sorted(policy["profiles"].get(kind, [])) != hosts or - not set(hosts) <= set(policy["allowHosts"])): - return False - for binding in policy["bindings"]: - if kind not in binding["providers"]: - continue - if set(binding["providers"]) - ({kind, "build"} if kind=="nvidia" else {kind}): - continue - marker = shared.credential_marker("saw-cred", binding["secret"], binding["key"]) - if credentials != {slot["env_vars"][0]: marker}: - continue - refresh = binding.get("refresh") - if refresh: - contract = slot.get("refresh", {}) - if (refresh.get("strategy") != contract.get("strategy") or - refresh.get("tokenURL") != contract.get("token_url") or - refresh.get("material") != {"clientID":"client_id", "clientSecret":"client_secret", "refreshToken":"refresh_token"}): - return False - return True - return False + return {(custom_host(custom_url), 443)} + path = PROFILES / (kind + ".yaml") + if not re.fullmatch(r"[a-z0-9-]+", kind or "") or not path.is_file(): + raise ValueError("no governed profile ships for this provider type") + return {(e["host"], int(e.get("port", 443))) for e in _shipped(kind).get("endpoints", [])} diff --git a/kubernetes-runtime/saw_kubernetes/reconcile.py b/kubernetes-runtime/saw_kubernetes/reconcile.py index 04bcbd073..029a059aa 100644 --- a/kubernetes-runtime/saw_kubernetes/reconcile.py +++ b/kubernetes-runtime/saw_kubernetes/reconcile.py @@ -15,8 +15,8 @@ import tempfile from types import SimpleNamespace -from .core import shared from . import provider as governed +from .core import shared from .compiler import ContractError, MANAGED, OWNER, REVISION, SOURCE_REVISION, digest, request_id @@ -102,8 +102,12 @@ class Reconciler: providing a no-op in a deployment is not qualification. """ - def __init__(self, rpc, state_directory, verify_resources, *, verify_shutdown=None): + def __init__(self, rpc, state_directory, verify_resources, *, verify_shutdown=None, read_credential=None): self.rpc = rpc + # read_credential(secret, key) -> (value, revision) from the trusted + # namespace; called only when a value is handed to OpenShell. + self.read_credential = read_credential + self.credential_env = {} self.store = StateStore(state_directory) if not callable(verify_resources): raise ContractError("resource verifier is required", safe_reason="InvalidPlan") @@ -124,10 +128,13 @@ def _get(self, method, request, field): raise ContractError("gateway returned an invalid object", safe_reason="GatewayMismatch") return response[field] - def _mutate(self, method, request, plan, generation): + def _mutate(self, method, request, plan, generation, identity=None): body = copy.deepcopy(request) + # `identity` replaces a request that carries a credential value, so the + # idempotency key never depends on the secret itself. body["request_id"] = request_id(plan["ownerID"], method, - {"request": request, "generation": generation}) + {"request": request if identity is None else identity, + "generation": generation}) try: return self.rpc.call(method, body) except RpcError as exc: @@ -194,6 +201,11 @@ def reconcile(self, plan, *, generation, desired_state="Running"): if state and state.get("identity") != identity: raise ContractError("workspace identity, owner and deployment mode are immutable", safe_reason="IdentityConflict") + if state.get("pendingProxyProviders") or state.get("proxyProviderRevisions"): + # Providers created through the removed credential proxy cannot + # be adopted: their revisions and credentials are not ours. + raise ContractError("workspace was enrolled with the SAW credential proxy; " + "start a new generation to re-enroll it", safe_reason="ReenrollRequired") previous = state.get("intent", {}) intent = {"generation": generation, "revision": plan["revision"], "desiredState": desired_state} if previous.get("generation", 0) > generation or (previous.get("generation") == generation and previous != intent): @@ -238,19 +250,18 @@ def _pass(self, plan, state, generation, desired_state): # Resolve platform scope explicitly (workspace_scope omitted). A # workspace administrator's same-name custom profile is not enough. profile = self.rpc.call("GetProviderProfile", {"id": provider_type}).get("profile", {}) - marker_provider = any(p.get("credentials") for w in plan["workspaces"] for p in w["providers"] - if p["type"] == provider_type) - if marker_provider: + credentialed = any(p.get("credentialRef") for w in plan["workspaces"] for p in w["providers"] + if p["type"] == provider_type) + if credentialed: + # OpenShell attaches this credential only to the profile's + # endpoints, so those must be exactly the approved ones. slots = profile.get("credentials", []) - endpoints = profile.get("endpoints", []) - slot, hosts = governed.requirements(provider_type, plan.get("customInferenceURL")) - if (profile.get("id") != provider_type - or profile.get("source") != "interceptor/governance" or len(slots) != 1 - or slots[0].get("env_vars") != slot["env_vars"] or slots[0].get("name") != slot["name"] - or sorted(e.get("host") for e in endpoints) != hosts - or any(e.get("port") != 443 or e.get("enforcement") != "NETWORK_ENFORCEMENT_MODE_ENFORCE" for e in endpoints)): - raise ContractError("provider profile differs from the approved inference boundary", + if (profile.get("id") != provider_type or len(slots) != 1 + or not slots[0].get("env_vars")): + raise ContractError("provider profile must declare exactly one credential", safe_reason="ProviderProfileMismatch") + self._verify_profile_endpoints(plan, provider_type, profile) + self.credential_env[provider_type] = slots[0]["env_vars"][0] continue if (profile.get("id") != provider_type or profile.get("credentials") or not profile.get("source", "").startswith("interceptor/")): @@ -270,6 +281,35 @@ 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") + # Host and port say where the key goes; path, protocol, access and + # rules say what it may do there. A shipped profile must match exactly. + try: + specs = governed.approved_endpoint_specs(provider_type) + except (ValueError, TypeError): + specs = [] + if specs is not None and sorted(governed.endpoint_spec(e, shipped=False) + for e in profile.get("endpoints", [])) != specs: + raise ContractError("provider profile endpoints differ from the approved ones", + safe_reason="ProviderProfileMismatch") + def _stop_pass(self, plan, state, generation): """Only stop previously observed IDs; never create or repair dependencies. @@ -357,34 +397,48 @@ def _apply_provider(self, ws, provider, plan, state, generation, pending): scope = {"workspace_scope": {"workspace": ws["name"]}} pname = provider["metadata"]["name"] reference = f"{ws['name']}/{pname}" + ref = provider.get("credentialRef") + refresh = provider.get("refresh") + # Only OpenShell Provider fields go to the gateway; it rejects unknown ones. + request = {k: v for k, v in provider.items() if k not in ("credentialRef", "refresh")} + source = None + if ref: + if not callable(self.read_credential): + raise ContractError("no credential source configured", safe_reason="ProviderRejected") + if refresh: + # The Secret holds only refresh material; OpenShell mints the + # access token, so the provider starts without a value and the + # material's Secret revision is the source. + _, source = self.read_credential(ref["secret"], refresh["material"][0]) + else: + value, source = self.read_credential(ref["secret"], ref["key"]) + request["credentials"] = {self.credential_env[provider["type"]]: value} + # What we record and key requests on: the plan entry (a reference, never + # the value) plus the Secret revision the value came from. + identity = {"provider": provider, "source": source} existing = self._get("GetProvider", {**scope, "name": pname}, "provider") # Persist intent before the RPC: a committed create can outlive the # connection (or this process). The pinned gateway durably replays the # same caller/request ID/payload and checks the recorded object revision. # A subsequent GetProvider, even with our labels, is not a create receipt. - creations = state.setdefault("pendingProxyProviders", {}) + creations = state.setdefault("pendingProviders", {}) intent = creations.get(reference) if intent is not None and (not isinstance(intent, dict) - or intent.get("request") != digest(provider) + or intent.get("request") != digest(identity) or type(intent.get("generation")) is not int or intent["generation"] < 1): raise ContractError("pending provider creation changed; explicit recovery is required", safe_reason="ProviderRejected") + revisions = state.setdefault("providerRevisions", {}) if existing is None or intent is not None: - if provider.get("credentials") and intent is None: - intent = {"request": digest(provider), "generation": generation} + if ref and intent is None: + intent = {"request": digest(identity), "generation": generation} creations[reference] = intent self.store.save(state) - reply = self._mutate("CreateProvider", {**scope, "provider": provider}, plan, - intent["generation"] if intent else generation) - if provider.get("credentials") and reply: - created = reply.get("provider", {}) - self._identity("provider", ws["name"], pname, created, plan, state) - meta = created["metadata"] - version = meta.get("resource_version") - if not version: - raise ContractError("missing provider revision", safe_reason="ProviderRejected") - state.setdefault("proxyProviderRevisions", {})[reference] = { - "version": version, "request": digest(provider)} + reply = self._mutate("CreateProvider", {**scope, "provider": request}, plan, + intent["generation"] if intent else generation, + identity=identity if ref else None) + if ref and reply: + self._record_provider(ws, pname, reply, plan, state, identity) creations.pop(reference, None) self.store.save(state) elif existing is not None: @@ -395,18 +449,130 @@ def _apply_provider(self, ws, provider, plan, state, generation, pending): return False self._identity("provider", ws["name"], pname, existing, plan, state) expected_credentials = {} - if provider.get("credentials"): - recorded = state.get("proxyProviderRevisions", {}).get(f"{ws['name']}/{pname}") - if recorded != {"version": existing["metadata"].get("resource_version"), "request": digest(provider)}: - raise ContractError("proxy provider ownership or credential revision requires explicit recovery", + updates = state.setdefault("pendingProviderUpdates", {}) + update = updates.get(reference) + if ref and update is not None: + # A credential update was sent but its reply was lost. If the + # provider moved on from the version we updated, that update (or + # its replay) applied: record it, as long as the provider still has + # exactly our credential slot. Otherwise it is resent below. + current = existing["metadata"].get("resource_version") + if current != update.get("from"): + if (existing.get("type") != provider["type"] or existing.get("config") + or existing.get("credentials", {}) != dict.fromkeys(request.get("credentials", {}), "REDACTED") + or update.get("provider") != digest(provider)): + raise ContractError("provider changed during a credential update; explicit recovery is required", + safe_reason="ProviderRejected") + revisions[reference] = {"version": current, "provider": digest(provider), + "source": update.get("source")} + updates.pop(reference) + self.store.save(state) + if ref: + recorded = revisions.get(reference, {}) + # OpenShell rewrites a refreshed provider (each minted token bumps + # its version), so only a static credential pins the version. + if (recorded.get("provider") != digest(provider) + or (not refresh and recorded.get("version") != existing["metadata"].get("resource_version"))): + raise ContractError("provider ownership or credential revision requires explicit recovery", safe_reason="ProviderRejected") - expected_credentials = dict.fromkeys(provider["credentials"], "REDACTED") + if recorded.get("source") != source and not refresh: + # The Secret rotated: hand OpenShell the new value. Persist the + # intent first, as for creates; a lost reply is resolved above. + updates[reference] = {"provider": digest(provider), "source": source, + "from": existing["metadata"].get("resource_version")} + self.store.save(state) + reply = self._mutate("UpdateProvider", {**scope, "provider": request}, plan, generation, + identity=identity) + if reply: + self._record_provider(ws, pname, reply, plan, state, identity) + updates.pop(reference, None) + self.store.save(state) + pending.append(f"provider/{reference}") + return False + if refresh: + if not self._apply_refresh(ws, provider, plan, state, generation, source, pending): + return False + # Either nothing yet or the one token OpenShell minted. + minted = {self.credential_env[provider["type"]]: "REDACTED"} + expected_credentials = minted if existing.get("credentials") else {} + else: + expected_credentials = dict.fromkeys(request["credentials"], "REDACTED") if (existing.get("type") != provider["type"] or existing.get("config") or existing.get("profile_workspace") - or existing.get("credentials", {}) != expected_credentials or existing.get("credential_handles")): + or existing.get("credentials", {}) != expected_credentials): raise ContractError("provider drift or unexpected credential state requires explicit recovery", safe_reason="ProviderRejected") return True + def _apply_refresh(self, ws, provider, plan, state, generation, source, pending): + """Hand OpenShell the refresh material once per Secret revision. + + OpenShell then refreshes the access token itself and keeps any rotated + refresh token; re-sending the Secret's original one would undo that. + A revision counts as configured only once the gateway's refresh status + shows the credential without an error. Until then a missing status + entry is pending, and a configure whose reply was lost is sent again + (same request ID, so the gateway replays rather than repeats it). + """ + scope = {"workspace_scope": {"workspace": ws["name"]}} + pname = provider["metadata"]["name"] + reference = f"{ws['name']}/{pname}" + key = self.credential_env[provider["type"]] + configured = state.setdefault("refreshConfigured", {}) + sent = state.setdefault("refreshSent", {}) + if configured.get(reference) != source: + attempt = sent.get(reference) or {} + if attempt.get("source") != source or not attempt.get("acknowledged"): + ref, refresh = provider["credentialRef"], provider["refresh"] + material = {} + for name in refresh["material"]: + value, revision = self.read_credential(ref["secret"], name) + if revision != source: + pending.append(f"provider/{reference}") + return False # the Secret changed while reading; next pass + material[name] = value + request = {**scope, "provider": pname, "credential_key": key, + "strategy": "PROVIDER_CREDENTIAL_REFRESH_STRATEGY_" + refresh["strategy"].upper(), + "material": material, "secret_material_keys": sorted(material)} + identity = {"refresh": provider, "source": source} + configure = self._mutate("ConfigureProviderRefresh", request, plan, generation, identity=identity) + rotate = self._mutate("RotateProviderCredential", + {**scope, "provider": pname, "credential_key": key}, + plan, generation, identity=identity) + # Both returned: a reply, or ALREADY_EXISTS (_mutate returns None + # for that only; every other failure raises before this line, + # so a lost reply is resent with the same request ID). Observe + # the refresh status from here on; never resend into ALREADY_EXISTS. + sent[reference] = {"source": source, "acknowledged": True} + self.store.save(state) + pending.append(f"provider/{reference}") + return False + status = self.rpc.call("GetProviderRefreshStatus", {**scope, "provider": pname, "credential_key": key}) + entries = [c for c in status.get("credentials", []) if c.get("credential_key") == key] + if any(c.get("last_error") or c.get("failure_code") for c in entries): + raise ContractError("provider credential refresh is failing; see the gateway's refresh status", + safe_reason="ProviderRefreshFailed") + if not entries: + if configured.get(reference) == source: + # It was working and the gateway no longer has it: refreshing stopped. + raise ContractError("provider credential refresh is no longer configured at the gateway", + safe_reason="ProviderRefreshFailed") + pending.append(f"provider/{reference}") # status not populated yet + return False + if configured.get(reference) != source: + configured[reference] = source + sent.pop(reference, None) + self.store.save(state) + return True + + def _record_provider(self, ws, pname, reply, plan, state, identity): + created = reply.get("provider", {}) + self._identity("provider", ws["name"], pname, created, plan, state) + version = created.get("metadata", {}).get("resource_version") + if not version: + raise ContractError("missing provider revision", safe_reason="ProviderRejected") + state.setdefault("providerRevisions", {})[f"{ws['name']}/{pname}"] = { + "version": version, "provider": digest(identity["provider"]), "source": identity["source"]} + def _apply_sandbox(self, ws, sandbox, plan, state, generation, desired_state, pending): scope = {"workspace_scope": {"workspace": ws["name"]}} sname = sandbox["name"] diff --git a/kubernetes-runtime/saw_kubernetes/serve.py b/kubernetes-runtime/saw_kubernetes/serve.py index 2e6e562b9..91f166be5 100644 --- a/kubernetes-runtime/saw_kubernetes/serve.py +++ b/kubernetes-runtime/saw_kubernetes/serve.py @@ -1,4 +1,5 @@ """Run one retained controller for an administrator-defined workspace.""" +import base64 import json import os from pathlib import Path @@ -37,6 +38,17 @@ def read(kind, name, namespace=None): def boundary(plan): verify(config, plan, get) + + allowed = set(config.get("credentialSecrets", [])) + def read_credential(secret, key): + """A provider credential for OpenShell, from this workspace's own Secrets only.""" + if secret not in allowed or not NAME.fullmatch(secret): + raise ContractError("credential outside controller scope") + obj = get(f"/api/v1/namespaces/{config['trustedNamespace']}/secrets/{secret}") + data = obj.get("data") or {} + if key not in data: + raise ContractError("credential is not available yet", safe_reason="ProviderRejected") + return base64.b64decode(data[key]).decode(), obj["metadata"]["resourceVersion"] resources = KubernetesResourceVerifier(read, boundary) endpoint = f"https://{config['gateway']}-gateway.{scope.namespace}.svc:17670" public_ca = read_public_ca(config["trustedNamespace"], config["gateway"], scope.owner_id, get) @@ -45,11 +57,35 @@ def boundary(plan): os.environ["POD_NAME"], os.environ["POD_UID"]) sessions = GatewaySessions(trust, endpoint) state = Path("/state") + catalog = {} + + def list_profiles(gateway): + """Platform provider profiles the gateway serves: type -> endpoint hosts.""" + profiles, token = {}, "" + while True: + page = gateway.call("ListProviderProfiles", {"page_size": 1000, "page_token": token}) + for profile in page.get("profiles", []): + profiles[profile["id"]] = [e["host"] for e in profile.get("endpoints", [])] + token = page.get("next_page_token", "") + if not token: + return profiles + def reconcile(plan, **kwargs): with sessions.open() as gateway: + # Refresh the catalog in the session we already hold: every session + # mints a client identity the gateway must first trust, so a second + # session per cycle keeps losing that race. + catalog["profiles"] = list_profiles(gateway) return Reconciler(gateway, state / "core", resources.verify_attachments, - verify_shutdown=resources.verify_shutdown).reconcile(plan, **kwargs) - frontend = Controller(api, scope, state, compile_profile_files, reconcile, boundary) + verify_shutdown=resources.verify_shutdown, + read_credential=read_credential).reconcile(plan, **kwargs) + + def compile_files(files, bindings): + if "profiles" not in catalog: # first cycle only + with sessions.open() as gateway: + catalog["profiles"] = list_profiles(gateway) + return compile_profile_files(files, bindings, catalog["profiles"]) + frontend = Controller(api, scope, state, compile_files, reconcile, boundary) stopped = False def stop(signum, frame): nonlocal stopped diff --git a/tests/kubernetes_runtime/profile_fixtures.py b/tests/kubernetes_runtime/profile_fixtures.py index a41be17bd..56180915f 100644 --- a/tests/kubernetes_runtime/profile_fixtures.py +++ b/tests/kubernetes_runtime/profile_fixtures.py @@ -41,10 +41,11 @@ def briefing_inputs(image=IMAGE): slot["toolGate"]["harness"] = {"name": bundle.name, "digest": bundle.digest} ws, = shared.parse_profiles(docs)[0].workspaces bindings = [{"secret":p.credential_secret,"key":p.credential_secret_key,"type":p.type, - "refresh": bool(p.refresh_strategy)} for p in ws.providers if p.enabled] + **({"refresh":p.refresh_strategy} if p.refresh_strategy else {})} + for p in ws.providers if p.enabled and not p.credential_free] cfg = dict(ownerID="b032b2e4-2cd5-47a7-8ef8-ac73e15700b1",namespace="saw-fixture", namespaceUID="fixture-ns",ownerSubject="fixture-subject",mode="container",gatewayVersion="0.1.2-rhaiv.6", - approvedCredentialFreeProviders=[],proxyBindings=bindings,bindings={"personal-assistant/assistant":slot}) + approvedCredentialFreeProviders=[],credentialBindings=bindings,bindings={"personal-assistant/assistant":slot}) return files, cfg @@ -58,7 +59,7 @@ def fixture_inputs(): cfg = dict(namespace="saw-fixture", namespaceUID="fixture", ownerSubject="fixture-owner", mode="container", ownerID="b032b2e4-2cd5-47a7-8ef8-ac73e15700b1", gatewayVersion="0.1.2-rhaiv.6", approvedCredentialFreeProviders=[], - proxyBindings=[{"type":"custom-inference","secret":"inference","key":"api_key","refresh":False}], + credentialBindings=[{"type":"custom-inference","secret":"inference","key":"api_key"}], customInferenceURL="https://models.fixture.test/v1", modelInputs={"inference.model":"fixture/model"}, bindings={"default/notebook":browser_slot()}) return yaml.safe_load(rendered)["data"], cfg diff --git a/tests/kubernetes_runtime/test_admin_session.py b/tests/kubernetes_runtime/test_admin_session.py index 30f3a4d8e..b39e38809 100644 --- a/tests/kubernetes_runtime/test_admin_session.py +++ b/tests/kubernetes_runtime/test_admin_session.py @@ -387,3 +387,41 @@ def test_abandoned_cleanup_does_not_follow_authority_symlink(tmp_path): with pytest.raises(sessions.admin.AdminSessionError, match="symlink"): sessions.admin.remove_abandoned(root) assert (outside/"session.keep").exists() + + +@pytest.mark.parametrize("code", ["UNKNOWN", "INTERNAL", "DEADLINE_EXCEEDED", "UNAVAILABLE"]) +def test_probe_keeps_one_session_until_the_gateway_trusts_it(ca, tmp_path, monkeypatch, code): + """TLS 1.3 rejects an untrusted client after the handshake, so the probe + sees a transport code; the session must survive until the CA propagates.""" + api = Api(ca) + identity_factory = sessions.admin.identity + def identity(base, runtime, **kwargs): + return identity_factory(base, runtime, require_tmpfs=False, erase=lambda p: p.unlink(), **kwargs) + monkeypatch.setattr(sessions.admin, "identity", identity) + monkeypatch.setattr(sessions.admin, "require_memory", lambda _: None) + monkeypatch.setattr(sessions.admin.time, "sleep", lambda _: None) + attempts, seen = [], set() + class Gateway: + def __init__(self, *args, **kwargs): pass + def call(self, method, body): + seen.update(published(api)) + attempts.append(method) + if len(attempts) < 4: raise sessions.RpcError(code) + def close(self): pass + with sessions.GatewaySessions(api.trust(ca), "https://gateway:17670", tmp_path, gateway_factory=Gateway).open(): + assert len(attempts) == 4 + assert len(seen) == 1 and not published(api) + + +def test_each_session_ca_has_a_distinct_name(tmp_path): + names = set() + for n in range(2): + runtime = tmp_path/str(n) + runtime.mkdir() + with sessions.admin.identity(b"server-ca\n", runtime, require_tmpfs=False, + erase=lambda p: p.unlink()) as one: + names.add(one["ca"]) + import subprocess + subjects = {subprocess.run(["openssl", "x509", "-noout", "-subject"], input=pem.encode(), + capture_output=True, check=True).stdout for pem in names} + assert len(subjects) == 2 diff --git a/tests/kubernetes_runtime/test_boundary.py b/tests/kubernetes_runtime/test_boundary.py index ca29e3bd0..311a1ac41 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": @@ -80,7 +80,8 @@ def test_kata_review_includes_sandbox_admission_and_gateway_placement(installati resources[refs[key][0]] = {"metadata": {"uid": key, "generation": 1}, "spec": {}} resources[refs["sandboxPlacement"][0]]["status"] = {"observedGeneration": 1, "typeChecking": {}} gateway = resources[refs["gatewayConfig"][0]]["data"] - gateway["gateway.toml"] = '[openshell.drivers.kubernetes]\ndefault_runtime_class_name = "saw-kata"' + gateway["gateway.toml"] = ('[openshell.drivers.kubernetes]\ndefault_runtime_class_name = "saw-kata"\n' + 'supervisor_runtime_class_name = "saw-kata"') approved = capture(config, resources.__getitem__) assert set(approved["approved"]) >= {"sandboxPlacement", "sandboxPlacementBinding"} with pytest.raises(BoundaryError, match="WrongWorkloadPlacement"): @@ -88,3 +89,7 @@ def test_kata_review_includes_sandbox_admission_and_gateway_placement(installati gateway["gateway.toml"] = '[openshell.drivers.kubernetes]\ndefault_runtime_class_name = ""' with pytest.raises(BoundaryError, match="WrongWorkloadPlacement"): capture(config, resources.__getitem__) + # A supervisor left in the default runtime shares no guest kernel boundary. + gateway["gateway.toml"] = '[openshell.drivers.kubernetes]\ndefault_runtime_class_name = "saw-kata"' + with pytest.raises(BoundaryError, match="WrongWorkloadPlacement"): + capture(config, resources.__getitem__) diff --git a/tests/kubernetes_runtime/test_briefing.py b/tests/kubernetes_runtime/test_briefing.py index 3c4a2947a..662d1df0b 100644 --- a/tests/kubernetes_runtime/test_briefing.py +++ b/tests/kubernetes_runtime/test_briefing.py @@ -6,7 +6,7 @@ from saw_kubernetes import compile_profile_files, ContractError from saw_kubernetes.core import shared -from saw_kubernetes.harness import read_bundles +from saw_kubernetes.harness import read_bundles, tool_rules from saw_kubernetes.prepare_gate import publish_harness from .profile_fixtures import ROOT, briefing_inputs @@ -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,46 @@ 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) + + +def local_audit(cfg): + """The default (no auditReceipts): the gate logs locally instead of waiting for receipts.""" + gate = cfg["bindings"]["personal-assistant/assistant"]["toolGate"] + del gate["receiptKey"] + gate["localAudit"] = True + return gate + + +def test_briefing_runs_with_the_local_audit_gate(): + files, cfg = briefing_inputs() + local_audit(cfg) + spec, = [sb["spec"] for sb in compile_profile_files(files, cfg)["workspaces"][0]["sandboxes"]] + mounts = spec["template"]["driver_config"]["kubernetes"]["containers"]["agent"]["volume_mounts"] + audit, = [m for m in mounts if m["mount_path"] == "/sandbox/.saw/audit"] + # The same log/ subtree the governance extension admits, on the sandbox's own volume. + assert audit == {"name": "saw-audit", "mount_path": "/sandbox/.saw/audit", "read_only": False, "sub_path": "log"} + assert [m for m in mounts if m["mount_path"] == "/sandbox/harness"] + command = spec["command"][2] + # The plugin is loaded and checked, and the gate creates its own log file. + assert "entries:{'saw-tool-gate':{enabled:true}}" in command and "saw-plugins.json" in command + assert "O_CREAT" in command and "permits non-append writes" not in command + # The plugin carries no writer key, so it appends to the local file. + identity = shared.tool_gate_identity("fixture", cfg["ownerSubject"], "personal-assistant", "assistant") + bundle = read_bundles(*shared.split_bom_files(files)[1:])["daily-briefing"] + tree, _, digest, _ = shared.tool_gate_bundle(Path(shared.__file__).parent, identity, None, tool_rules(bundle)) + assert b"__SAW_AUDIT_KEY__" in tree["plugin/index.js"][0] and digest in command + + +@pytest.mark.parametrize("bad", [False, "yes"]) +def test_local_audit_is_true_and_never_beside_a_receipt_key(bad): + files, cfg = briefing_inputs() + gate = local_audit(cfg) + gate["localAudit"] = bad + with pytest.raises(ContractError, match="localAudit"): + compile_profile_files(files, cfg) + files, cfg = briefing_inputs() + cfg["bindings"]["personal-assistant/assistant"]["toolGate"]["localAudit"] = True + with pytest.raises(ContractError, match="localAudit"): + compile_profile_files(files, cfg) diff --git a/tests/kubernetes_runtime/test_controller.py b/tests/kubernetes_runtime/test_controller.py index d48657961..197c30033 100644 --- a/tests/kubernetes_runtime/test_controller.py +++ b/tests/kubernetes_runtime/test_controller.py @@ -263,6 +263,14 @@ def test_boundary_failure_is_sanitized_and_prevents_core(setup): assert not calls and "secret-token" not in canonical(api.objects[c.scope.status_name]) +def test_proxy_era_approval_asks_for_reenrollment(setup): + from saw_kubernetes.boundary import BoundaryError + c, api, _, _, calls, _ = setup + c.verify_boundary = lambda _: (_ for _ in ()).throw(BoundaryError("ReenrollRequired")) + assert c.reconcile_once()["reason"] == "ReenrollRequired" + assert not calls + + def test_ambiguous_core_failure_retains_intent_and_does_not_publish_exception(setup): c, api, *_ = setup c.core_pass = lambda *a, **k: (_ for _ in ()).throw(RuntimeError("private-request-body")) diff --git a/tests/kubernetes_runtime/test_custom_inference.py b/tests/kubernetes_runtime/test_custom_inference.py index 5236a670a..184cabed8 100644 --- a/tests/kubernetes_runtime/test_custom_inference.py +++ b/tests/kubernetes_runtime/test_custom_inference.py @@ -3,14 +3,13 @@ from .profile_fixtures import fixture_inputs from saw_kubernetes import compile_profile_files, ContractError -from saw_kubernetes import provider def test_custom_bom_uses_bound_model_endpoint_timeout_and_marker(): files,cfg=fixture_inputs() plan=compile_profile_files(files,cfg) w,=plan["workspaces"] - assert w["providers"][0]["credentials"]=={"CUSTOM_INFERENCE_API_KEY":"saw-cred.inference.api_key"} + assert w["providers"][0]["credentialRef"]=={"secret":"inference","key":"api_key"} spec=w["sandboxes"][0]["spec"] assert spec["command"][-1]=="fixture/model" assert plan["customInferenceURL"]=='https://models.fixture.test/v1' @@ -39,34 +38,10 @@ def test_bom_cannot_override_site_approved_destination(bad): with pytest.raises((ContractError, ValueError)): compile_profile_files(files,cfg) -def test_missing_approval_and_widened_proxy_policy_are_rejected(): +def test_custom_inference_requires_site_approval(): files,cfg=fixture_inputs() cfg.pop("customInferenceURL") with pytest.raises(ContractError): compile_profile_files(files,cfg) - url="https://models.fixture.test/v1" - creds={"CUSTOM_INFERENCE_API_KEY":"saw-cred.inference.api_key"} - policy={"allowHosts":["models.fixture.test"],"profiles":{},"markerPrefix":"saw-cred", - "bindings":[{"providers":["custom-inference"],"key":"api_key","secret":"inference"}]} - assert provider.check_policy("custom-inference",creds,policy,url) - for patch in ({"profiles":{"custom-inference":["elsewhere.example"]}}, - {"allowHosts":["models.fixture.test","elsewhere.example"]},{"bindings":[]}): - assert not provider.check_policy("custom-inference",creds,{**policy,**patch},url) - - -def test_gateway_profile_must_match_the_pinned_destination(tmp_path): - from saw_kubernetes import Reconciler - from .test_runtime import FakeGateway files,cfg=fixture_inputs() - plan=compile_profile_files(files,cfg) - gateway=FakeGateway() - old=gateway.call - def call(method, request): - if method=="GetProviderProfile": - return {"profile":{"id":"custom-inference","source":"interceptor/governance", - "credentials":[{"env_vars":["CUSTOM_INFERENCE_API_KEY"],"name":"api_key"}], - "endpoints":[{"host":"foreign.example","port":443,"enforcement":"NETWORK_ENFORCEMENT_MODE_ENFORCE"}]}} - return old(method,request) - gateway.call=call - with pytest.raises(ContractError,match="approved inference boundary"): - Reconciler(gateway,tmp_path,lambda _:None).reconcile(plan,generation=1) - assert not gateway.sandboxes and not gateway.providers + cfg["credentialBindings"]=[] + with pytest.raises(ContractError): compile_profile_files(files,cfg) diff --git a/tests/kubernetes_runtime/test_gate_update.py b/tests/kubernetes_runtime/test_gate_update.py new file mode 100644 index 000000000..c791f5455 --- /dev/null +++ b/tests/kubernetes_runtime/test_gate_update.py @@ -0,0 +1,82 @@ +"""A tool-gate policy update reaches an existing container workspace.""" +import json + +import pytest + +from saw_kubernetes.prepare_gate import publish_model, publish_tree, verify + + +def tree(policy, owner="alice"): + identity = {"username": owner, "subject": "s-" + owner, "sandbox": "notebook", "workspace": "default"} + return {"tool-actions.yaml": (policy, False), + "identity.json": ((json.dumps(identity, sort_keys=True) + "\n").encode(), False), + "plugin/index.js": (b"plugin", False)} + + +def test_a_policy_update_replaces_the_gate_and_keeps_the_running_tree(tmp_path): + target = tmp_path / "bundle" + old, new = tree(b"rules: [old]\n"), tree(b"rules: [new]\n") + publish_tree(tmp_path, target, old, replace=True) + running = target.stat().st_ino # a sandbox's subPath mount follows this inode + publish_tree(tmp_path, target, new, replace=True) + verify(target, new) + (kept,) = [p / "bundle" for p in tmp_path.glob("superseded-*")] + assert kept.stat().st_ino == running + verify(kept, old) + + +def test_republishing_the_same_policy_changes_nothing(tmp_path): + target = tmp_path / "bundle" + files = tree(b"rules: []\n") + publish_tree(tmp_path, target, files, replace=True) + inode = target.stat().st_ino + publish_tree(tmp_path, target, files, replace=True) + assert target.stat().st_ino == inode and not list(tmp_path.glob("superseded-*")) + + +def test_the_model_and_proof_follow_the_new_tree(tmp_path): + target = tmp_path / "bundle" + publish_tree(tmp_path, target, tree(b"a\n"), model_selector=True, browser=True, replace=True) + publish_model(tmp_path, target, "first", 3) + (target / "relay-proof").write_bytes(b"0" * 64) + publish_tree(tmp_path, target, tree(b"b\n"), model_selector=True, browser=True, replace=True) + assert not (target / "model.json").exists() + publish_model(tmp_path, target, "first", 3) # the Job republishes its selection + verify(target, tree(b"b\n"), model_selector=True, browser=True) + + +def test_another_owner_never_takes_over_a_gate_volume(tmp_path): + target = tmp_path / "bundle" + publish_tree(tmp_path, target, tree(b"a\n", "alice"), replace=True) + with pytest.raises(ValueError, match="another owner"): + publish_tree(tmp_path, target, tree(b"a\n", "bob"), replace=True) + verify(target, tree(b"a\n", "alice")) + + +def test_content_addressed_trees_stay_write_once(tmp_path): + target = tmp_path / "harness-x" + publish_tree(tmp_path, target, tree(b"a\n")) + with pytest.raises(ValueError, match="differs"): + publish_tree(tmp_path, target, tree(b"b\n")) + + +def test_a_symlinked_gate_is_refused(tmp_path): + real = tmp_path / "elsewhere" + publish_tree(tmp_path, real, tree(b"a\n")) + (tmp_path / "bundle").symlink_to(real) + with pytest.raises(ValueError, match="invalid gate directory"): + publish_tree(tmp_path, tmp_path / "bundle", tree(b"b\n"), replace=True) + + +def test_a_long_running_sandbox_keeps_its_tree_through_later_updates(tmp_path): + """A sandbox mounts its tree by inode and is not restarted by a policy + update, so no number of later updates may remove the tree it started on.""" + target = tmp_path / "bundle" + publish_tree(tmp_path, target, tree(b"v0\n"), replace=True) + first = target.stat().st_ino + for n in range(1, 5): + publish_tree(tmp_path, target, tree(f"v{n}\n".encode()), replace=True) + (running,) = [p / "bundle" for p in tmp_path.glob("superseded-*") if (p / "bundle").stat().st_ino == first] + assert (running / "tool-actions.yaml").read_bytes() == b"v0\n" + assert len(list(tmp_path.glob("superseded-*"))) == 4 + verify(target, tree(b"v4\n")) diff --git a/tests/kubernetes_runtime/test_governance_contract.py b/tests/kubernetes_runtime/test_governance_contract.py index 41bc45193..2971d1090 100644 --- a/tests/kubernetes_runtime/test_governance_contract.py +++ b/tests/kubernetes_runtime/test_governance_contract.py @@ -26,6 +26,12 @@ def test_compiler_harness_output_and_tampering_against_rust_guard(tmp_path): assert len(driver["kubernetes"]["volumes"]) == 3 + additional assert len(driver["kubernetes"]["containers"]["agent"]["volume_mounts"]) == 5 + additional valid.append(driver) + # The default gate without receipts (localAudit) must pass the same guard. + local = copy.deepcopy(config) + gate = local["bindings"]["personal-assistant/assistant"]["toolGate"] + del gate["receiptKey"] + gate["localAudit"] = True + valid.append(compile_profile_files(files, local)["workspaces"][0]["sandboxes"][0]["spec"]["template"]["driver_config"]) invalid = [] for index, field, value in [ (3,"name","saw-workspace"), (3,"read_only",False), (3,"mount_path","/etc"), diff --git a/tests/kubernetes_runtime/test_harness_tool_rules.py b/tests/kubernetes_runtime/test_harness_tool_rules.py new file mode 100644 index 000000000..c0592a135 --- /dev/null +++ b/tests/kubernetes_runtime/test_harness_tool_rules.py @@ -0,0 +1,115 @@ +"""A harness bundle sets the tool-gate actions for its own MCP tools, and only those.""" +import base64 +import json +import subprocess +import shutil +from pathlib import Path +from types import SimpleNamespace + +import pytest +import yaml + +from saw_kubernetes import harness +from saw_kubernetes.core import shared + +ASSETS = Path(shared.__file__).parent +IDENTITY = shared.tool_gate_identity("alice", "subject-1", "default", "notebook") + + +def tree(servers, mcp=("reader", "writer")): + doc = {"apiVersion": "saw.redhat.com/v1alpha1", "kind": "HarnessBundle", + "metadata": {"name": "demo"}, "spec": {"agent": "openclaw", "mcpServers": servers}} + config = {"mcpServers": {name: {"type": "stdio", "command": "node", "args": ["${PLUGIN_ROOT}/mcp/x.mjs"]} + for name in mcp}} + return {"harness.yaml": (yaml.safe_dump(doc).encode(), False), + "plugin.json": (b'{"name": "demo"}', False), + "mcp.json": (json.dumps(config).encode(), False)} + + +def rules(servers, **kwargs): + return shared.harness_tool_rules(shared.describe_harness_tree(tree(servers, **kwargs), inline=True)) + + +def test_declared_tools_become_rules_named_after_their_server(): + assert rules([{"name": "reader", "tools": [{"name": "read_mail", "action": "allow"}]}, + {"name": "writer", "tools": [{"name": "save", "action": "approval"}]}]) == [ + {"id": "harness-reader-read_mail", "tool": "reader__read_mail", "action": "allow"}, + {"id": "harness-writer-save", "tool": "writer__save", "action": "approval"}] + assert rules([{"name": "reader"}]) == [] + + +@pytest.mark.parametrize("servers", [ + [{"name": "other", "tools": [{"name": "x", "action": "allow"}]}], # not this bundle's server + [{"name": "reader", "tools": [{"name": "x", "action": "deny"}]}], # only allow or approval + [{"name": "reader", "tools": [{"name": "../exec", "action": "allow"}]}], + [{"name": "reader", "tools": [{"name": "x", "action": "allow", "when": "always"}]}], + [{"name": "reader", "tools": {"name": "x", "action": "allow"}}], + [{"name": "reader", "tools": [{"name": "x", "action": "allow"}, {"name": "x", "action": "allow"}]}], +]) +def test_a_bundle_cannot_claim_other_tools_or_actions(servers): + with pytest.raises(shared.InstallerError): + rules(servers) + + +def test_gate_policy_appends_harness_rules_after_the_base_and_pins_them(): + base, _, base_digest, base_hash = shared.tool_gate_bundle(ASSETS, IDENTITY) + extra = [{"id": "harness-reader-read_mail", "tool": "reader__read_mail", "action": "allow"}] + merged, _, digest, policy_hash = shared.tool_gate_bundle(ASSETS, IDENTITY, None, extra) + text = merged["tool-actions.yaml"][0] + assert text.startswith(base["tool-actions.yaml"][0].rstrip(b"\n")) + assert b"tool: reader__read_mail" in text + assert (digest, policy_hash) != (base_digest, base_hash) + assert policy_hash.encode() in merged["plugin/index.js"][0] + assert shared.tool_gate_bundle(ASSETS, IDENTITY, None, extra)[2] == digest + + +def test_an_injected_server_name_cannot_add_policy_rules(): + """Regression: a server name with a newline could append `tool: exec` / + `action: allow` to the policy text and bypass default-deny.""" + evil = "reader\n - id: pwn\n tool: exec\n action: allow\n - id: x" + with pytest.raises(shared.InstallerError, match="mcp server name"): + rules([{"name": evil, "tools": [{"name": "x", "action": "allow"}]}], mcp=(evil,)) + + +@pytest.mark.parametrize("rule", [ + {"id": "harness-reader-x", "tool": "exec", "action": "allow"}, # a bare base tool + {"id": "harness-reader-x", "tool": "reader__x\n - id: pwn", "action": "allow"}, + {"id": "pwn\n tool: exec", "tool": "reader__x", "action": "allow"}, + {"id": "harness-reader-x", "tool": "reader__x", "action": "deny"}, + {"id": "harness-reader-x", "tool": "reader__x", "action": "allow", "whenCommandMatches": "rm"}, +]) +def test_the_gate_policy_refuses_rules_it_cannot_write_safely(rule): + with pytest.raises(shared.InstallerError, match="invalid harness tool rule"): + shared.tool_gate_bundle(ASSETS, IDENTITY, None, [rule]) + + +@pytest.mark.skipif(not shutil.which("node"), reason="node is required") +def test_the_gate_allows_the_harness_tool_and_the_base_rule_wins(tmp_path): + # A harness rule cannot name a base tool at all, and its own tools are allowed. + base = yaml.safe_load((ASSETS / "tool-actions.yaml").read_text()) + denied = next(r["tool"] for r in base["rules"] if r["action"] == "approval" and "whenCommandMatches" not in r) + with pytest.raises(shared.InstallerError): + shared.tool_gate_bundle(ASSETS, IDENTITY, None, [{"id": "harness-x-override", "tool": denied, "action": "allow"}]) + extra = [{"id": "harness-reader-read_mail", "tool": "reader__read_mail", "action": "allow"}] + policy = shared.tool_gate_bundle(ASSETS, IDENTITY, None, extra)[0]["tool-actions.yaml"][0].decode() + script = f""" +import {{ decide }} from {json.dumps(str(ASSETS / "tool-gate.mjs"))}; +const input = (tool) => ({{ policyText: {json.dumps(policy)}, identity: {{username: "alice", subject: "s"}}, + toolName: tool, sessionKey: "s1", params: {{}} }}); +console.log(JSON.stringify(["reader__read_mail", {json.dumps(denied)}, "reader__other"].map(t => decide(input(t)).record.decision))); +""" + out = subprocess.run(["node", "--input-type=module", "-e", script], capture_output=True, text=True, check=True) + assert json.loads(out.stdout) == ["allow", "approval_required", "deny"] + + +def test_openclaw_allowlist_gets_the_bundle_tools_but_not_base_decided_ones(): + files = tree([{"name": "reader", "tools": [{"name": "read_mail", "action": "allow"}]}]) + bundle = SimpleNamespace(files={k: base64.b64encode(v).decode() for k, (v, _) in files.items()}, + digest="sha256:" + "a" * 64) + command = ["sh", "-c", "const target = process.env.OPENCLAW_CONFIG_PATH;\nexec openclaw gateway run"] + driver = {"containers": {"agent": {"volume_mounts": []}}} + workspace = SimpleNamespace(providers=[]) + harness.configure(command, driver, bundle, workspace, SimpleNamespace(providers=[]), None) + spec = json.loads(command[2].split("const harness = ", 1)[1].split(";\n", 1)[0]) + assert "reader__read_mail" in spec["tools"] + assert "reader__other" not in spec["tools"] diff --git a/tests/kubernetes_runtime/test_inference_providers.py b/tests/kubernetes_runtime/test_inference_providers.py index f082cf30d..1f8699575 100644 --- a/tests/kubernetes_runtime/test_inference_providers.py +++ b/tests/kubernetes_runtime/test_inference_providers.py @@ -1,4 +1,4 @@ -"""All inference providers share BOM resolution and the VM's proxy profiles.""" +"""All inference providers share BOM resolution; OpenShell holds their keys.""" import json import shutil import subprocess @@ -25,7 +25,7 @@ def test_provider_compiles_native_protocol_and_placeholder_config(source, kind, if native: sandbox(source, lambda s: s["inference"].pop("baseUrl")) workspace = compile_profile(*source)["workspaces"][0] - assert workspace["providers"][0]["credentials"] == {env:"saw-cred.inference.api_key"} + assert workspace["providers"][0]["credentialRef"] == {"secret": "inference", "key": "api_key"} command = workspace["sandboxes"][0]["spec"]["command"] assert "@SAW_" not in command[2] if not shutil.which("node"): @@ -61,16 +61,9 @@ def test_provider_compiles_native_protocol_and_placeholder_config(source, kind, @pytest.mark.parametrize("kind,model,url,api,env", CASES) -def test_provider_uses_shipped_host_and_credential_policy(source, kind, model, url, api, env): +def test_provider_reads_its_placeholder_and_keeps_its_native_endpoint(source, kind, model, url, api, env): agent(source, kind, model) - credentials = compile_profile(*source)["workspaces"][0]["providers"][0]["credentials"] - slot, hosts = governed.requirements(kind) - assert slot["env_vars"] == [env] - policy = {"markerPrefix":"saw-cred", "profiles":{kind:hosts}, "allowHosts":hosts, - "bindings":[{"providers":[kind],"secret":"inference","key":"api_key"}]} - assert governed.check_policy(kind, credentials, policy) - assert not governed.check_policy(kind, credentials, {**policy,"allowHosts":[]}) - assert not governed.check_policy(kind, {env:"saw-cred.foreign.api_key"}, policy) + assert governed.inference_key_env(kind) == env sandbox(source, lambda s: s["inference"].update(baseUrl="https://foreign.example/v1")) with pytest.raises(ContractError): compile_profile(*source) diff --git a/tests/kubernetes_runtime/test_intent.py b/tests/kubernetes_runtime/test_intent.py index fd008580f..fc82cce83 100644 --- a/tests/kubernetes_runtime/test_intent.py +++ b/tests/kubernetes_runtime/test_intent.py @@ -225,7 +225,7 @@ def test_helm_lifecycle_intent_round_trips_through_cli_and_controller(source, in buildNamespace=auto["buildNamespace"], approved={}, intent=json.loads(original["data"]["intent.json"]))) values = {"site": site, "owner": "alice", "ownerSubject": site["subject"], "installationID": bindings["ownerID"], - "registration": reg, "intentGeneration": 2, "vaultPrefix": "secret/data/hub/saw-alice/"+reg, + "registration": reg, "intentGeneration": 2, "vaultPrefix": "secret/data/hub/saw-alice", "global": {"repoURL":"https://example.test/repo", "targetRevision":"test", "clusterDomain":"cluster.example.test", "vpArgoNamespace":"vp-gitops"}} rendered = subprocess.run(["helm","template","alice",str(root/"charts/saw-portal-container"), diff --git a/tests/kubernetes_runtime/test_openclaw.py b/tests/kubernetes_runtime/test_openclaw.py index dff64aeda..c59b7cfcc 100644 --- a/tests/kubernetes_runtime/test_openclaw.py +++ b/tests/kubernetes_runtime/test_openclaw.py @@ -13,7 +13,7 @@ def agent(source, kind="openai", model="gpt-4.1-mini-2025-04-14"): shared.NATIVE_BASE_URLS.get(kind) or shared.PROTOCOL_NATIVE_BASE_URLS[protocol]) if kind == "custom-inference": source[1]["customInferenceURL"] = endpoint - source[1]["proxyBindings"] = [{"type":kind, "secret":"inference", "key":"api_key", "refresh":False}] + source[1]["credentialBindings"] = [{"type":kind, "secret":"inference", "key":"api_key"}] mutate(source, "providers.yaml", lambda d: d["spec"]["providers"].append( {"name": kind, "type": kind, "credentialSecret": "inference"})) sandbox(source, lambda s: s.update(type="openclaw", providers=[kind], inference={ @@ -48,13 +48,14 @@ def test_mutable_model_compiles_and_startup_accepts_published_selection(source, assert result.stdout.strip() == model -def test_openclaw_pinned_proxy_contract(source): +def test_openclaw_reads_its_key_from_the_openshell_placeholder(source): agent(source) ws = compile_profile(*source)["workspaces"][0] - assert ws["providers"][0]["credentials"] == {"OPENAI_API_KEY": "saw-cred.inference.api_key"} + assert ws["providers"][0]["credentialRef"] == {"secret": "inference", "key": "api_key"} + assert "credentials" not in ws["providers"][0] command = ws["sandboxes"][0]["spec"]["command"] assert command[-1] == "gpt-4.1-mini-2025-04-14" - assert "saw-cred" not in json.dumps(command) + assert "OPENAI_API_KEY" in command[2] assert "loopback" in command[2] @@ -62,7 +63,7 @@ def test_openclaw_pinned_proxy_contract(source): def test_openclaw_rejects_unapproved_bindings(source, change): agent(source) if change == "absent": - source[1].pop("proxyBindings") + source[1].pop("credentialBindings") else: update = {"alternative-url": {"baseUrl": "https://example.com/v1"}, "shell": {"model": "$(id)"}, "unknown-input": {"model": {"secretKeyRef": {"name":"private","key":"key"}}}} @@ -77,7 +78,9 @@ def test_redacted_provider_refuses_changed_revision(source, tmp_path): ws = plan["workspaces"][0] provider = ws["providers"][0] gateway = FakeGateway() - core = Reconciler(gateway, tmp_path / "ledger", lambda plan: None) + core = Reconciler(gateway, tmp_path / "ledger", lambda plan: None, + read_credential=lambda secret, key: ("real-key", "1")) + core.credential_env["openai"] = "OPENAI_API_KEY" real_call = gateway.call def call(method, body): result = real_call(method, body) diff --git a/tests/kubernetes_runtime/test_portal_contract.py b/tests/kubernetes_runtime/test_portal_contract.py index 5b7eff77c..25a943fba 100644 --- a/tests/kubernetes_runtime/test_portal_contract.py +++ b/tests/kubernetes_runtime/test_portal_contract.py @@ -13,17 +13,13 @@ def public_test_ca(): def resources(reg="0123456789abcdef", owner="12345678-1234-4123-a123-123456789012", address="10.0.0.18"): - cfg=dict(namespace="runtime",trustedNamespace="saw-ctl-"+reg,ownerID=owner,governanceNamespace="gov",gateway="gw",proxyPolicy="proxy") + cfg=dict(namespace="runtime",trustedNamespace="saw-ctl-"+reg,ownerID=owner,governanceNamespace="gov",gateway="gw") refs=objects(cfg) data={p:{"metadata":{"uid":key},"spec":{},"data":{}} for key,(p,_) in refs.items()} data[refs["gatewayRole"][0]]["rules"] = [] def obj(k):return data[refs[k][0]] - obj("proxy")["spec"]={"namespace":cfg["trustedNamespace"],"owner":owner,"image":"locked"} obj("gateway")["spec"]={"template":{"metadata":{"annotations":{"checksum/config":"c"*64}}}} obj("gatewayService")["spec"]={"type":"ClusterIP","clusterIP":address,"clusterIPs":[address],"ipFamilies":["IPv4"],"ports":[{"port":17670}]} - pem=public_test_ca() - obj("publicCA").update(data={"ca.crt":pem},metadata={"labels":{"saw.redhat.com/runtime-owner":owner}}) - data["/api/v1/namespaces/"+cfg["trustedNamespace"]+"/configmaps/gw-proxy-ca"]={"metadata":{},"data":{"ca.crt":pem}} return cfg,data,obj @@ -33,14 +29,13 @@ def test_rebind_only_per_registration_identifiers(): verify_contract(second,new.__getitem__,contract(first,old.__getitem__)) -@pytest.mark.parametrize("change",["proxyImage","servicePort","governanceUID","fakeCA","replacementIssuer","extra"]) +@pytest.mark.parametrize("change",["gatewayImage","servicePort","governanceUID","replacementIssuer","extra"]) def test_unreviewed_differences_rejected(change): cfg,live,obj=resources() expected=copy.deepcopy(contract(cfg,live.__getitem__)) - if change=="proxyImage":obj("proxy")["spec"]["image"]="foreign" + if change=="gatewayImage":obj("gateway")["spec"]["image"]="foreign" if change=="servicePort":obj("gatewayService")["spec"]["ports"][0]["port"]=80 if change=="governanceUID":obj("governance")["metadata"]["uid"]="foreign" - if change=="fakeCA":obj("publicCA")["data"]["ca.crt"]="-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----" if change=="replacementIssuer":obj("gatewayConfig")["data"]["issuer"]="foreign" if change=="extra":expected["newKey"]="injected" with pytest.raises(BoundaryError):verify_contract(cfg,live.__getitem__,expected) diff --git a/tests/kubernetes_runtime/test_portal_profile.py b/tests/kubernetes_runtime/test_portal_profile.py index d00003610..26fa7e127 100644 --- a/tests/kubernetes_runtime/test_portal_profile.py +++ b/tests/kubernetes_runtime/test_portal_profile.py @@ -21,7 +21,7 @@ def test_portal_bom_route_requires_same_sandboxes_browser_binding(): profile=ROOT/"tests/fixtures/profiles/audited-openclaw" cfg={"namespace":"saw-owner","namespaceUID":"ns","ownerID":"76c95ca5-b9bc-4be7-b764-bc028087ae28", "ownerSubject":"owner","mode":"container","gatewayVersion":"0.1.2-rhaiv.6", - "approvedCredentialFreeProviders":[],"proxyBindings":[{"type":"openai", "secret":"inference", "key":"api_key", "refresh":False}],"bindings":{"agent/audited":{ + "approvedCredentialFreeProviders":[],"credentialBindings":[{"type":"openai", "secret":"inference", "key":"api_key"}],"bindings":{"agent/audited":{ "workspace":{"claimName":"tenant-data","uid":"claim","readOnly":False}, "toolGate":{"ownerLogin":"owner", "trusted":{"claimName":"saw-gate-fixture","uid":"gate","readOnly":True}, "audit":{"claimName":"saw-audit-fixture","uid":"audit","readOnly":False}}, diff --git a/tests/kubernetes_runtime/test_provider_endpoints.py b/tests/kubernetes_runtime/test_provider_endpoints.py new file mode 100644 index 000000000..7f9167c89 --- /dev/null +++ b/tests/kubernetes_runtime/test_provider_endpoints.py @@ -0,0 +1,156 @@ +"""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 copy + +import pytest + +from saw_kubernetes import ContractError, Reconciler, compile_profile_files +from saw_kubernetes import provider as governed +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 live(kind): + """The shipped profile's endpoints as the gateway returns them: the + interceptor's YAML-to-NetworkEndpoint conversion, then protobuf JSON (enums + by name, default fields omitted).""" + out = [] + for e in governed._shipped(kind)["endpoints"]: + item = {"host": e["host"], "port": e["port"], "enforcement": ENFORCE} + for key in ("protocol", "path"): + if e.get(key): + item[key] = e[key] + if governed.ACCESS[e.get("access", "")]: + item["access"] = governed.ACCESS[e["access"]] + if e.get("rules"): + item["rules"] = copy.deepcopy(e["rules"]) + out.append(item) + return out + + +def test_stock_profile_must_match_the_shipped_governed_profile(): + check("nvidia", live("nvidia")) + with pytest.raises(ContractError, match="endpoints differ"): + check("nvidia", live("nvidia") + [endpoint("evil.example")]) + with pytest.raises(ContractError, match="endpoints differ"): + check("no-such-provider", live("nvidia")) + + +@pytest.mark.parametrize("kind", ["github", "gmail", "slack", "nvidia", "openai", "anthropic"]) +def test_every_shipped_profile_matches_itself_as_served(kind): + check(kind, live(kind)) + + +def test_two_entries_on_one_host_and_port_are_not_merged(): + """github lists api.github.com:443 twice: REST, and GraphQL scoped to /graphql.""" + endpoints = live("github") + graphql, = [e for e in endpoints if e.get("path") == "/graphql"] + endpoints.remove(graphql) + with pytest.raises(ContractError, match="endpoints differ"): + check("github", endpoints) # GraphQL entry dropped + unscoped = dict(graphql) + del unscoped["path"] + with pytest.raises(ContractError, match="endpoints differ"): + check("github", endpoints + [unscoped]) # GraphQL on every path + + +@pytest.mark.parametrize("change", [ + lambda e: e.update(access="NETWORK_ACCESS_PRESET_READ_WRITE"), + lambda e: e.update(access="NETWORK_ACCESS_PRESET_FULL"), + lambda e: e.update(protocol="tcp"), # L4 only: no inspection at all + lambda e: e.update(path="/**"), +]) +def test_a_widened_endpoint_on_an_approved_host_is_refused(change): + endpoints = live("github") + change(next(e for e in endpoints if e["host"] == "api.github.com" and "path" not in e)) + with pytest.raises(ContractError, match="endpoints differ"): + check("github", endpoints) + + +def test_l7_rules_must_match_exactly(): + endpoints = live("gmail") + rules = next(e for e in endpoints if e.get("rules"))["rules"] + rules.append({"allow": {"method": "POST", "path": "/gmail/v1/users/me/messages/send"}}) + with pytest.raises(ContractError, match="endpoints differ"): + check("gmail", endpoints) + endpoints = live("gmail") + next(e for e in endpoints if e.get("rules"))["rules"].reverse() + check("gmail", endpoints) # order does not matter + + +@pytest.mark.parametrize("bad", [ + endpoint("models.fixture.test", enforcement="NETWORK_ENFORCEMENT_MODE_AUDIT"), + {"host": "models.fixture.test", "port": 443}, # unspecified = audit + endpoint("models.fixture.test", allowed_ips=["203.0.113.7"]), + endpoint("models.fixture.test", ports=[443, 8443]), +]) +def test_every_endpoint_is_enforced_without_extra_destinations(bad): + with pytest.raises(ContractError, match="endpoints differ"): + check("custom-inference", [bad]) + + +class ProfileGateway(FakeGateway): + def __init__(self, endpoints): + super().__init__() + self.endpoints = endpoints + + def call(self, method, request): + if method == "GetProviderProfile" and request["id"] == "custom-inference": + self.calls.append((method, request)) + return {"profile": {"id": "custom-inference", "endpoints": self.endpoints, + "credentials": [{"env_vars": ["CUSTOM_INFERENCE_API_KEY"]}]}} + return super().call(method, request) + + +def test_mismatched_profile_stops_the_reconciler_before_create_provider(tmp_path): + files, config = fixture_inputs() + plan = compile_profile_files(files, config) + gateway = ProfileGateway([endpoint("api.inference.example.com")]) + reconciler = Reconciler(gateway, tmp_path / "state", lambda _: None, + read_credential=lambda secret, key: ("value", "1")) + with pytest.raises(ContractError) as error: + reconciler.reconcile(plan, generation=1) + assert error.value.safe_reason == "ProviderProfileMismatch" + assert not [m for m, _ in gateway.calls if m == "CreateProvider"] + + +def test_matching_profile_lets_the_reconciler_create_the_provider(tmp_path): + files, config = fixture_inputs() + plan = compile_profile_files(files, config) + gateway = ProfileGateway([endpoint("models.fixture.test")]) + reconciler = Reconciler(gateway, tmp_path / "state", lambda _: None, + read_credential=lambda secret, key: ("value", "1")) + created = lambda: [m for m, _ in gateway.calls if m == "CreateProvider"] + for _ in range(4): # workspace and membership come first + try: + reconciler.reconcile(plan, generation=1) + except ContractError: + pass # the bare fake returns no provider revision; the create is what counts + if created(): + break + assert created() diff --git a/tests/kubernetes_runtime/test_provider_governance.py b/tests/kubernetes_runtime/test_provider_governance.py deleted file mode 100644 index 7d78a1f99..000000000 --- a/tests/kubernetes_runtime/test_provider_governance.py +++ /dev/null @@ -1,20 +0,0 @@ -from saw_kubernetes import provider as governed - - -def test_brave_search_uses_shipped_governance_profile(): - slot, hosts = governed.requirements("brave") - - assert slot["name"] == "api_key" - assert slot["env_vars"] == ["BRAVE_API_KEY"] - assert hosts == ["api.search.brave.com"] - - credentials = {"BRAVE_API_KEY": "saw-cred.web-search.api_key"} - policy = { - "markerPrefix": "saw-cred", - "profiles": {"brave": hosts}, - "allowHosts": hosts, - "bindings": [{"providers": ["brave"], "secret": "web-search", "key": "api_key"}], - } - - assert governed.check_policy("brave", credentials, policy) - assert not governed.check_policy("brave", credentials, {**policy, "allowHosts": []}) diff --git a/tests/kubernetes_runtime/test_provider_recovery.py b/tests/kubernetes_runtime/test_provider_recovery.py index 9208df716..05c35e9f6 100644 --- a/tests/kubernetes_runtime/test_provider_recovery.py +++ b/tests/kubernetes_runtime/test_provider_recovery.py @@ -1,5 +1,6 @@ """CreateProvider ambiguity must use a replay receipt, never redacted Get data.""" import copy +import json import pytest @@ -46,22 +47,30 @@ def interrupted(source, tmp_path): ws = plan["workspaces"][0] provider = ws["providers"][0] gateway = LostProviderResponse() - core = Reconciler(gateway, tmp_path / "ledger", lambda _: None) + secrets = {"revision": "1"} + def read_credential(secret, key): + return "real-" + secret + "-" + secrets["revision"], secrets["revision"] + def reconciler(): + core = Reconciler(gateway, tmp_path / "ledger", lambda _: None, read_credential=read_credential) + core.credential_env[provider["type"]] = "OPENAI_API_KEY" + return core + core = reconciler() with pytest.raises(RpcError, match="DEADLINE_EXCEEDED"): core._apply_provider(ws, provider, plan, {}, 1, []) # Reconstruct the process from durable state; changing intent generation # must not change the original CreateProvider request ID. - core = Reconciler(gateway, tmp_path / "ledger", lambda _: None) + core = reconciler() + core.secrets = secrets return core, gateway, ws, provider, plan def test_lost_provider_response_recovers_across_process_and_generation(interrupted): core, gateway, ws, provider, plan = interrupted state = core.store.load() - assert state["pendingProxyProviders"] and not state.get("proxyProviderRevisions") + assert state["pendingProviders"] and not state.get("providerRevisions") assert core._apply_provider(ws, provider, plan, state, 2, []) assert gateway.creations == 1 and gateway.replays == 1 - assert not core.store.load()["pendingProxyProviders"] + assert not core.store.load()["pendingProviders"] assert core._apply_provider(ws, provider, plan, core.store.load(), 2, []) assert gateway.replays == 1 @@ -78,13 +87,13 @@ def test_recovery_refuses_changed_gateway_resource(interrupted, change): meta["labels"] = {} with pytest.raises(RpcError, match="FAILED_PRECONDITION"): core._apply_provider(ws, provider, plan, core.store.load(), 2, []) - assert not core.store.load().get("proxyProviderRevisions") + assert not core.store.load().get("providerRevisions") -def test_recovery_refuses_changed_marker_or_missing_receipt(interrupted): +def test_recovery_refuses_changed_reference_or_missing_receipt(interrupted): core, gateway, ws, provider, plan = interrupted changed = copy.deepcopy(provider) - changed["credentials"]["OPENAI_API_KEY"] = "saw-cred.other.api_key" + changed["credentialRef"]["secret"] = "other" with pytest.raises(ContractError, match="pending provider creation changed"): core._apply_provider(ws, changed, plan, core.store.load(), 2, []) assert gateway.replays == 0 @@ -94,3 +103,102 @@ def test_recovery_refuses_changed_marker_or_missing_receipt(interrupted): # Losing the local intent must not allow adoption based on labels alone. with pytest.raises(ContractError, match="credential revision"): core._apply_provider(ws, provider, plan, {}, 2, []) + + +def test_credential_value_stays_out_of_the_plan_state_and_request_id(interrupted): + core, gateway, ws, provider, plan = interrupted + assert "credentials" not in provider and provider["credentialRef"] + request, _ = gateway.receipt + assert request["provider"]["credentials"] == {"OPENAI_API_KEY": "real-" + provider["credentialRef"]["secret"] + "-1"} + assert "real-" not in json.dumps(plan) + json.dumps(core.store.load()) + request["request_id"] + + +def test_rotated_secret_updates_the_openshell_provider(interrupted): + core, gateway, ws, provider, plan = interrupted + assert core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + updates = [] + original = gateway.call + def call(method, request): + if method == "UpdateProvider": + updates.append(request) + key = (ws["name"], provider["metadata"]["name"]) + gateway.providers[key]["metadata"]["resource_version"] = "2" + return {"provider": copy.deepcopy(gateway.providers[key])} + return original(method, request) + gateway.call = call + core.secrets["revision"] = "2" + pending = [] + assert not core._apply_provider(ws, provider, plan, core.store.load(), 2, pending) + assert pending and updates[0]["provider"]["credentials"] == { + "OPENAI_API_KEY": "real-" + provider["credentialRef"]["secret"] + "-2"} + assert core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + + + +class LostUpdateResponse: + """UpdateProvider whose reply is lost; it may or may not have applied.""" + + def __init__(self, gateway, key, *, apply, error): + self.gateway, self.key, self.apply, self.error = gateway, key, apply, error + self.original, self.sent = gateway.call, [] + gateway.call = self.call + + def call(self, method, request): + if method != "UpdateProvider": + return self.original(method, request) + self.sent.append(request["request_id"]) + provider = self.gateway.providers[self.key] + if self.apply: + provider["metadata"]["resource_version"] = str(int(provider["metadata"]["resource_version"]) + 1) + self.apply = False # a replay of the same request does not apply twice + if self.error: + error, self.error = self.error, "ALREADY_EXISTS" # replays answer with no body + raise RpcError(error) + return {"provider": copy.deepcopy(provider)} + + +def converged(interrupted): + core, gateway, ws, provider, plan = interrupted + assert core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + core.secrets["revision"] = "2" + return core, gateway, ws, provider, plan, (ws["name"], provider["metadata"]["name"]) + + +def test_applied_update_with_a_lost_reply_is_recorded_not_resent(interrupted): + core, gateway, ws, provider, plan, key = converged(interrupted) + lost = LostUpdateResponse(gateway, key, apply=True, error="DEADLINE_EXCEEDED") + with pytest.raises(RpcError, match="DEADLINE_EXCEEDED"): + core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + assert core.store.load()["pendingProviderUpdates"] + # The next pass sees the provider moved on and records the new source. + assert core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + state = core.store.load() + assert not state["pendingProviderUpdates"] + recorded = next(iter(state["providerRevisions"].values())) + assert recorded["source"] == "2" and recorded["version"] == "2" + assert core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + assert len(lost.sent) == 1 + + +def test_update_replay_without_a_body_converges(interrupted): + core, gateway, ws, provider, plan, key = converged(interrupted) + # First attempt never applied; its replay applies and answers ALREADY_EXISTS. + lost = LostUpdateResponse(gateway, key, apply=False, error="DEADLINE_EXCEEDED") + with pytest.raises(RpcError, match="DEADLINE_EXCEEDED"): + core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + lost.apply = True + pending = [] + assert not core._apply_provider(ws, provider, plan, core.store.load(), 2, pending) and pending + assert lost.sent[0] == lost.sent[1] # same request ID: the gateway replays it + assert core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + assert len(lost.sent) == 2 + + +def test_provider_changed_during_an_update_fails_closed(interrupted): + core, gateway, ws, provider, plan, key = converged(interrupted) + LostUpdateResponse(gateway, key, apply=True, error="DEADLINE_EXCEEDED") + with pytest.raises(RpcError, match="DEADLINE_EXCEEDED"): + core._apply_provider(ws, provider, plan, core.store.load(), 2, []) + gateway.providers[key]["credentials"] = {"OTHER_KEY": "REDACTED"} + with pytest.raises(ContractError, match="changed during a credential update"): + core._apply_provider(ws, provider, plan, core.store.load(), 2, []) diff --git a/tests/kubernetes_runtime/test_provider_refresh.py b/tests/kubernetes_runtime/test_provider_refresh.py new file mode 100644 index 000000000..d0a2eeaf7 --- /dev/null +++ b/tests/kubernetes_runtime/test_provider_refresh.py @@ -0,0 +1,175 @@ +"""OpenShell refreshes OAuth access tokens; the runtime only hands it the material.""" +import copy +import json + +from saw_kubernetes import Reconciler +from saw_kubernetes.compiler import MANAGED, OWNER +from .test_runtime import FakeGateway + +OWNER_ID = "b032b2e4-2cd5-47a7-8ef8-ac73e15700b1" +PLAN = {"ownerID": OWNER_ID} +WS = {"name": "default"} +GMAIL = {"metadata": {"name": "gmail", "labels": {OWNER: OWNER_ID, MANAGED: "kubernetes-runtime"}}, + "type": "gmail", "credentialRef": {"secret": "gmail", "key": "access_token"}, + "refresh": {"strategy": "oauth2_refresh_token", + "material": ["client_id", "client_secret", "refresh_token"]}} + + +class RefreshGateway(FakeGateway): + def __init__(self): + super().__init__() + self.refresh_ok = True + self.status_ready = True # False: the gateway has not populated refresh status yet + self.lose_replies = False # True: configure/rotate fail as a lost reply (UNAVAILABLE) + self.already_exists = False # True: the gateway already has this refresh configuration + + def call(self, method, request): + if method in ("ConfigureProviderRefresh", "RotateProviderCredential"): + self.calls.append((method, copy.deepcopy(request))) + if self.lose_replies or self.already_exists: + from saw_kubernetes import RpcError + raise RpcError("UNAVAILABLE" if self.lose_replies else "ALREADY_EXISTS") + if method == "RotateProviderCredential": + # As the gateway does: store the minted token, bumping the version. + provider = self.providers[(request["workspace_scope"]["workspace"], request["provider"])] + provider["credentials"] = {request["credential_key"]: "REDACTED"} + provider["metadata"]["resource_version"] = str(int(provider["metadata"]["resource_version"]) + 1) + return {"status": {}} + if method == "GetProviderRefreshStatus": + if not self.status_ready: + return {"credentials": []} + status = {"credential_key": request["credential_key"]} + if not self.refresh_ok: + status["last_error"] = "invalid_grant" + return {"credentials": [status]} + response = super().call(method, request) + if method == "CreateProvider": + obj = response["provider"] + obj["metadata"]["resource_version"] = "1" + obj["credentials"] = {k: "REDACTED" for k in obj.get("credentials", {})} + return response + + +def setup(tmp_path): + gateway = RefreshGateway() + secret = {"revision": "1"} + def read_credential(name, key): + # Like the portal's Vault object: refresh material only, no access_token. + assert key in GMAIL["refresh"]["material"], key + return f"{key}-{secret['revision']}", secret["revision"] + core = Reconciler(gateway, tmp_path / "ledger", lambda _: None, read_credential=read_credential) + core.credential_env["gmail"] = "GMAIL_ACCESS_TOKEN" + return core, gateway, secret + + +def run(core, state): + pending = [] + return core._apply_provider(WS, GMAIL, PLAN, state, 1, pending), pending + + +def methods(gateway, name): + return [r for m, r in gateway.calls if m == name] + + +def test_refresh_is_configured_once_per_secret_revision(tmp_path): + core, gateway, secret = setup(tmp_path) + state = {} + assert run(core, state) == (False, ["provider/default/gmail"]) # created + assert run(core, state) == (False, ["provider/default/gmail"]) # refresh configured + configure, = methods(gateway, "ConfigureProviderRefresh") + assert configure["credential_key"] == "GMAIL_ACCESS_TOKEN" + assert configure["strategy"] == "PROVIDER_CREDENTIAL_REFRESH_STRATEGY_OAUTH2_REFRESH_TOKEN" + assert configure["material"] == {"client_id": "client_id-1", "client_secret": "client_secret-1", + "refresh_token": "refresh_token-1"} + assert set(configure["secret_material_keys"]) == {"client_id", "client_secret", "refresh_token"} + assert len(methods(gateway, "RotateProviderCredential")) == 1 + assert run(core, state) == (True, []) + assert len(methods(gateway, "ConfigureProviderRefresh")) == 1 # unchanged Secret: not re-sent + + secret["revision"] = "2" + assert run(core, state)[0] is False + assert len(methods(gateway, "ConfigureProviderRefresh")) == 2 + assert not methods(gateway, "UpdateProvider") # OpenShell owns the refreshed token + assert run(core, state) == (True, []) + + stored = json.dumps(core.store.load()) + json.dumps(state) + ids = json.dumps([r.get("request_id") for _, r in gateway.calls]) + assert "refresh_token-" not in stored + ids and "client_secret-" not in stored + ids + + +def test_failing_refresh_is_reported(tmp_path): + core, gateway, _ = setup(tmp_path) + state = {} + run(core, state); run(core, state) + gateway.refresh_ok = False + import pytest + from saw_kubernetes import ContractError + with pytest.raises(ContractError, match="refresh is failing"): + run(core, state) + + +def test_provider_is_created_from_material_without_an_access_token(tmp_path): + core, gateway, _ = setup(tmp_path) + state = {} + run(core, state) + create, = methods(gateway, "CreateProvider") + # OpenShell mints the token: no credential value, and only Provider fields. + assert "credentials" not in create["provider"] and "refresh" not in create["provider"] + run(core, state) + assert len(methods(gateway, "RotateProviderCredential")) == 1 + # The rotation rewrote the provider (new version, minted token); still converged. + assert run(core, state) == (True, []) + assert run(core, state) == (True, []) + + +def test_unpopulated_status_is_pending_and_a_lost_configure_is_resent(tmp_path): + from saw_kubernetes import RpcError + core, gateway, _ = setup(tmp_path) + state = {} + run(core, state) # create + gateway.status_ready, gateway.lose_replies = False, True + for _ in range(2): # configure: reply lost in transit + try: + run(core, state) + except RpcError: + pass + 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" + + +def test_already_existing_refresh_is_observed_not_resent(tmp_path): + """ALREADY_EXISTS means the gateway has the configuration: resending the + same request can only repeat that answer, so the status decides.""" + core, gateway, _ = setup(tmp_path) + state = {} + run(core, state) # create + gateway.status_ready, gateway.already_exists = False, True + assert run(core, state) == (False, ["provider/default/gmail"]) # acknowledged + assert run(core, state) == (False, ["provider/default/gmail"]) # status empty: pending + assert len(methods(gateway, "ConfigureProviderRefresh")) == 1 # never resent + gateway.status_ready = True + assert run(core, state) == (True, []) + assert core.store.load()["refreshConfigured"] == {"default/gmail": "1"} diff --git a/tests/kubernetes_runtime/test_proxy_ca_projection.py b/tests/kubernetes_runtime/test_proxy_ca_projection.py deleted file mode 100644 index 1efae4a43..000000000 --- a/tests/kubernetes_runtime/test_proxy_ca_projection.py +++ /dev/null @@ -1,126 +0,0 @@ -"""Public trust projection: no Secret reads, adoption, replacement or rotation.""" -import copy -import importlib.util -from pathlib import Path -import subprocess -import pytest - -ROOT=Path(__file__).resolve().parents[2] -SPEC=importlib.util.spec_from_file_location('project_ca',ROOT/'charts/saw-kubernetes-proxy/files/project_ca.py') -mod=importlib.util.module_from_spec(SPEC) -SPEC.loader.exec_module(mod) - - -@pytest.fixture(scope='module') -def cert(tmp_path_factory): - root=tmp_path_factory.mktemp('proxy-ca-test') - subprocess.run(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-days','1', - '-subj','/CN=Public test CA','-keyout',str(root/'key.pem'),'-out',str(root/'ca.pem')], - check=True,capture_output=True) - value=(root/'ca.pem').read_text() - (root/'key.pem').unlink() - return value - - -@pytest.fixture -def config(): - return dict(ownerID='67a9891d-e281-442f-86c3-41771f5ce049',namespace='saw-test-trusted', - targetNamespace='saw-test',name='saw-test-proxy-ca') - - -class Api: - def __init__(self,config,cert): - self.objects={f'/api/v1/namespaces/{ns}':{'metadata':{'name':ns,'labels':{mod.OWNER:config['ownerID']}}} - for ns in [config['namespace'],config['targetNamespace']]} - self.source=f"/api/v1/namespaces/{config['namespace']}/configmaps/{config['name']}" - self.target=f"/api/v1/namespaces/{config['targetNamespace']}/configmaps/{config['name']}" - self.objects[self.source]={'metadata':{'name':config['name'],'namespace':config['namespace']},'data':{'ca.crt':cert}} - self.calls=[] - self.race=None - - def call(self,method,path,body=None): - self.calls.append((method,path)) - assert '/secrets' not in path - assert method in ['GET','POST'] - if method=='POST': - target=path+'/'+body['metadata']['name'] - if self.race: - body=self.race(copy.deepcopy(body)) - self.objects.setdefault(target,copy.deepcopy(body)) - return copy.deepcopy(self.objects.get(path)) - - -def test_repeat_sync_and_only_public_material(config,cert): - api=Api(config,cert) - mod.project(api,config) - before=copy.deepcopy(api.objects) - mod.project(api,config) - assert api.objects==before - assert sum(m=='POST' for m,p in api.calls)==1 - target=api.objects[api.target] - assert target['immutable'] is True and target['data']=={'ca.crt':cert} - assert target['metadata']['annotations']['argocd.argoproj.io/sync-options']==mod.KEEP - - -@pytest.mark.parametrize('mutation',[ - lambda b: b.update(immutable=False), - lambda b: b.update(data={'ca.crt':'different'}), - lambda b: b.update(binaryData={'private':'data'}), - lambda b: b['metadata'].update(ownerReferences=[{'name':'foreign'}]), - lambda b: b['metadata'].update(deletionTimestamp='now'), - lambda b: b['metadata'].update(labels={mod.OWNER:'foreign'}), - lambda b: b['metadata'].update(annotations={}), - lambda b: b.update(metadata=None), -]) -def test_refuses_foreign_changed_or_malformed_target(config,cert,mutation): - api=Api(config,cert) - mod.project(api,config) - mutation(api.objects[api.target]) - before=copy.deepcopy(api.objects) - with pytest.raises(mod.Failure):mod.project(api,config) - assert api.objects==before - - -def test_conflicting_create_race_is_not_adopted(config,cert): - api=Api(config,cert) - def race(body): - body['metadata']['labels'][mod.OWNER]='foreign' - return body - api.race=race - with pytest.raises(mod.Failure,match='explicit trust recovery'):mod.project(api,config) - - -def test_matching_create_race_is_safe(config,cert): - api=Api(config,cert) - api.race=lambda body:body - mod.project(api,config) - - -@pytest.mark.parametrize('value',['secret','-----BEGIN PRIVATE KEY-----','not a certificate',None]) -def test_invalid_source_rejected_before_any_write(config,cert,value): - api=Api(config,cert) - api.objects[api.source]['data']={'ca.crt':value} - with pytest.raises(mod.Failure):mod.project(api,config) - assert not any(m=='POST' for m,p in api.calls) - - -def test_extra_text_cannot_be_projected(config,cert): - api=Api(config,cert) - api.objects[api.source]['data']['ca.crt']=cert+'secret trailing text' - with pytest.raises(mod.Failure):mod.project(api,config) - - -def test_namespace_ownership_required_before_reading_ca(config,cert): - api=Api(config,cert) - api.objects['/api/v1/namespaces/saw-test']['metadata']['labels']={} - with pytest.raises(mod.Failure,match='ownership'):mod.project(api,config) - assert all('/configmaps' not in p for m,p in api.calls) - - -@pytest.mark.parametrize('patch',[{'ownerID':'0'*32},{'targetNamespace':'saw-test-trusted'}, - {'name':'../secrets'},{'targetNamespace':'kube-system'},{'extra':'field'}]) -def test_bad_config_never_calls_api(config,cert,patch): - api=Api(config,cert) - config.update(patch) - with pytest.raises(mod.Failure):mod.project(api,config) - assert not api.calls diff --git a/tests/kubernetes_runtime/test_proxy_era_upgrade.py b/tests/kubernetes_runtime/test_proxy_era_upgrade.py new file mode 100644 index 000000000..a241052b4 --- /dev/null +++ b/tests/kubernetes_runtime/test_proxy_era_upgrade.py @@ -0,0 +1,30 @@ +"""Workspaces enrolled by the removed credential-proxy controller must re-enroll.""" +import pytest + +from saw_kubernetes import ContractError, Reconciler, compile_profile +from saw_kubernetes.boundary import PROXY_ERA_OBJECTS, BoundaryError, verify +from .test_openclaw import agent +from .test_runtime import FakeGateway, source # noqa: F401 (fixture) + + +@pytest.mark.parametrize("key", ["proxyProviderRevisions", "pendingProxyProviders"]) +def test_proxy_era_controller_state_is_not_adopted(source, tmp_path, key): + agent(source) + plan = compile_profile(*source) + gateway = FakeGateway() + reconciler = Reconciler(gateway, tmp_path / "state", lambda _: None, + read_credential=lambda secret, name: ("value", "1")) + identity = {k: plan[k] for k in ["ownerID", "namespaceUID", "ownerSubject", "mode"]} + reference = plan["workspaces"][0]["name"] + "/" + plan["workspaces"][0]["providers"][0]["metadata"]["name"] + reconciler.store.save({"identity": identity, key: {reference: {"version": "7"}}}) + with pytest.raises(ContractError, match="re-enroll") as error: + reconciler.reconcile(plan, generation=1) + assert error.value.safe_reason == "ReenrollRequired" + assert not gateway.calls # nothing adopted, nothing created + + +def test_proxy_era_approval_requires_reenrollment(): + plan = {"namespace": "saw-alice", "namespaceUID": "u", "ownerID": "o", "mode": "container"} + config = {**plan, "approved": dict.fromkeys(PROXY_ERA_OBJECTS | {"gateway"}, {})} + with pytest.raises(BoundaryError, match="ReenrollRequired"): + verify(config, plan, lambda path: pytest.fail("no object is read before the check")) diff --git a/tests/kubernetes_runtime/test_rpc_allowlist.py b/tests/kubernetes_runtime/test_rpc_allowlist.py new file mode 100644 index 000000000..949b1dca0 --- /dev/null +++ b/tests/kubernetes_runtime/test_rpc_allowlist.py @@ -0,0 +1,15 @@ +"""The gateway adapter refuses RPCs it does not list; test fakes accept any.""" +import re +from pathlib import Path + +import saw_kubernetes +from saw_kubernetes.adapters import RPC_METHODS + + +def test_every_rpc_the_runtime_calls_is_allowed(): + called = set() + for source in Path(saw_kubernetes.__file__).parent.glob("*.py"): + called |= set(re.findall(r'(?:\.call|_mutate)\(\s*"([A-Z][A-Za-z]+)"', source.read_text())) + assert {"ListProviderProfiles", "UpdateProvider", "ConfigureProviderRefresh", + "RotateProviderCredential", "GetProviderRefreshStatus"} <= called + assert called <= RPC_METHODS From 01577d32608492e17a038d5422c8a2f494e1f244 Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Wed, 25 Nov 2026 07:17:16 +0000 Subject: [PATCH 2/9] Container and Kata workspace charts on OpenShell v0.1.10 Portal and GitOps projection of container and Kata workspaces, and the platform charts they need. - saw-portal-container: per-user stack (identity, policy, gateway, audit, relay). No cluster-specific addresses: the Kubernetes API through the control-plane nodes, DNS by selector, the cluster's default StorageClass. Signed audit receipts are optional (auditReceipts); OCSF events and the agent trace relay go to the pattern's OpenTelemetry collector. The gateway and the admission policy pin the same runtime and supervisor images. - saw-runtime-policies: supervisors may carry only the configured OCSF and agent-trace collectors and a numeric attach timeout; in Kata mode both the workload and the supervisor must use the approved class (two VMs). - saw-users: projection with an IP-free projector; Kata users default to saw-kata, bound by its live UID and placement digest on autoApprove sites. - saw-kata (KataConfig and an attachable saw-kata RuntimeClass) and saw-telemetry (OCSF logs and agent traces collector). - OpenShell v0.1.10-rhaiv.0 for VM and container users; the governance interceptor rebuilt from v0.1.10; container sandboxes on a temporary openshell-sandbox carry until a fixed image is released. - openshell-rhdh portal, Keycloak relay registrar, container defaults. Assisted-By: Claude --- charts/governance-interceptor/values.yaml | 9 +- charts/governance-policy/tool-actions.yaml | 29 + .../files/relay-provisioner.py | 224 +++++++ .../templates/relay-provisioner.yaml | 198 +++++++ charts/openshell-keycloak/values.yaml | 16 + charts/openshell-rhdh/files/portal.py | 130 ++++- charts/openshell-rhdh/files/preflight.py | 43 +- charts/openshell-rhdh/files/workspace.py | 88 ++- charts/openshell-rhdh/templates/_helpers.tpl | 21 +- charts/openshell-saw-kubernetes/Chart.yaml | 2 +- .../templates/_helpers.tpl | 9 +- .../templates/gateway-config.yaml | 24 + .../templates/gateway.yaml | 9 +- charts/openshell-saw-kubernetes/values.yaml | 27 +- .../files/installer/apply_bom.py | 51 +- .../files/installer/saw_admin.py | 2 +- .../openshell-saw/files/installer/saw_core.py | 97 ++- .../files/installer/tool-actions.yaml | 29 + .../files/installer/tool-gate.mjs | 77 ++- .../files/installer/tool-gate.test.mjs | 83 ++- charts/openshell-saw/values.yaml | 18 +- charts/saw-audit-writer/templates/writer.yaml | 22 +- charts/saw-audit-writer/values.yaml | 5 + charts/saw-kata/Chart.yaml | 6 + charts/saw-kata/templates/kataconfig.yaml | 31 + charts/saw-kata/values.yaml | 28 + .../templates/controller.yaml | 12 +- .../templates/bootstrap.yaml | 1 + .../values.schema.json | 40 ++ charts/saw-kubernetes-identity/values.yaml | 2 +- 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 | 39 +- .../files/portal_contract.py | 14 - .../saw-portal-container/files/preflight.py | 43 +- .../templates/_helpers.tpl | 48 +- .../templates/auto-enroll.yaml | 30 +- .../templates/enrolled-runtime.yaml | 29 +- .../templates/foundation.yaml | 47 +- .../templates/publications.yaml | 4 +- .../saw-portal-container/templates/relay.yaml | 8 +- .../saw-portal-container/templates/stack.yaml | 78 ++- charts/saw-portal-container/values.yaml | 163 +++++- .../templates/admin-network-policy.yaml | 16 + .../templates/runtime-validation.yaml | 18 +- .../saw-runtime-policies/values.schema.json | 11 + charts/saw-runtime-policies/values.yaml | 13 +- charts/saw-telemetry/Chart.yaml | 6 + charts/saw-telemetry/templates/collector.yaml | 35 ++ charts/saw-telemetry/values.yaml | 14 + charts/saw-users/files/governed-profiles.json | 550 ------------------ charts/saw-users/files/preflight.py | 43 +- charts/saw-users/files/projector.py | 30 +- charts/saw-users/files/workspace.py | 88 ++- .../templates/_governed-proxy-policy.tpl | 52 -- charts/saw-users/templates/_helpers.tpl | 111 +++- charts/saw-users/templates/applications.yaml | 21 +- .../saw-users/templates/awaiting-owner.yaml | 15 + charts/saw-users/templates/namespaces.yaml | 3 +- charts/saw-users/templates/projector.yaml | 45 +- charts/saw-users/values.yaml | 42 +- .../saw-workspace-relay/templates/access.yaml | 4 +- .../templates/identity.yaml | 5 +- charts/saw-workspace-relay/templates/ui.yaml | 2 +- examples/saw/installer-bom.yaml | 18 +- overrides/saw-container-defaults.yaml | 40 ++ overrides/saw-container-demo.yaml | 20 + overrides/saw-users.yaml | 15 + .../golden/gateway-interceptor-direct.toml | 4 +- .../golden/gateway-interceptor-oidc.toml | 4 +- tests/charts/golden/gateway-interceptor.toml | 4 +- .../test_governance_interceptor_image.py | 55 +- tests/charts/test_openshell_keycloak_chart.py | 27 + tests/charts/test_openshell_saw_chart.py | 9 +- tests/charts/test_portal_container.py | 313 +++++++++- tests/charts/test_saw_kata_chart.py | 66 +++ tests/charts/test_saw_kubernetes_chart.py | 50 +- .../charts/test_saw_kubernetes_proxy_chart.py | 67 --- tests/charts/test_saw_runtime_policies.py | 59 +- tests/charts/test_saw_users_chart.py | 200 ++++++- tests/charts/test_workspace_relay.py | 9 + tests/fixtures/container-site.yaml | 161 ++--- tests/installer/test_cli.py | 2 +- tests/installer/test_custom_endpoint.py | 51 ++ tests/portal/test_portal.py | 56 +- 88 files changed, 3038 insertions(+), 1656 deletions(-) create mode 100644 charts/openshell-keycloak/files/relay-provisioner.py create mode 100644 charts/openshell-keycloak/templates/relay-provisioner.yaml create mode 100644 charts/saw-kata/Chart.yaml create mode 100644 charts/saw-kata/templates/kataconfig.yaml create mode 100644 charts/saw-kata/values.yaml 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 create mode 100644 charts/saw-telemetry/Chart.yaml create mode 100644 charts/saw-telemetry/templates/collector.yaml create mode 100644 charts/saw-telemetry/values.yaml delete mode 100644 charts/saw-users/files/governed-profiles.json delete mode 100644 charts/saw-users/templates/_governed-proxy-policy.tpl create mode 100644 charts/saw-users/templates/awaiting-owner.yaml create mode 100644 overrides/saw-container-defaults.yaml create mode 100644 overrides/saw-container-demo.yaml create mode 100644 tests/charts/test_saw_kata_chart.py delete mode 100644 tests/charts/test_saw_kubernetes_proxy_chart.py diff --git a/charts/governance-interceptor/values.yaml b/charts/governance-interceptor/values.yaml index 5b111ade4..0db9a9798 100644 --- a/charts/governance-interceptor/values.yaml +++ b/charts/governance-interceptor/values.yaml @@ -16,10 +16,11 @@ 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.10 interceptor with the SAW extension that admits the +# container runtime's mTLS operator (118b4cfa). CI image tag sha-3ed7ef66 +# (build-governance-interceptor.yml, linux/amd64 + linux/arm64). Replace with +# the main publish once this reaches main. +image: "ghcr.io/sauagarwa/governance-interceptor@sha256:890df5d17388d98330a240625a36e4ce70810b4ab3bccc28d0f49919c25f5127" # gRPC listen port port: 18081 # Provider profiles a deployment adds to the shipped catalog: a ConfigMap of diff --git a/charts/governance-policy/tool-actions.yaml b/charts/governance-policy/tool-actions.yaml index 3becbac16..029dc993c 100644 --- a/charts/governance-policy/tool-actions.yaml +++ b/charts/governance-policy/tool-actions.yaml @@ -42,24 +42,53 @@ rules: - openclaw cron get - openclaw cron show - openclaw cron runs + - openclaw cron --help + - openclaw cron add --help + - openclaw cron create --help + - openclaw cron edit --help + - openclaw cron rm --help + - openclaw cron remove --help + - openclaw cron delete --help + - openclaw cron enable --help + - openclaw cron disable --help + - openclaw cron run --help - openclaw automations list - openclaw automations status - openclaw automations get - openclaw automations show - openclaw automations runs + - openclaw automations --help + - openclaw automations add --help + - openclaw automations create --help + - openclaw automations edit --help + - openclaw automations rm --help + - openclaw automations remove --help + - openclaw automations delete --help + - openclaw automations enable --help + - openclaw automations disable --help + - openclaw automations run --help + # "Allow always" skips the card for later automation changes until the + # gateway restarts; each call is still audited. - id: exec-openclaw-automation-change tool: exec action: approval + allowAlways: true whenCommandMatches: - openclaw cron add + - openclaw cron create - openclaw cron edit - openclaw cron rm + - openclaw cron remove + - openclaw cron delete - openclaw cron enable - openclaw cron disable - openclaw cron run - openclaw automations add + - openclaw automations create - openclaw automations edit - openclaw automations rm + - openclaw automations remove + - openclaw automations delete - openclaw automations enable - openclaw automations disable - openclaw automations run diff --git a/charts/openshell-keycloak/files/relay-provisioner.py b/charts/openshell-keycloak/files/relay-provisioner.py new file mode 100644 index 000000000..0102d0218 --- /dev/null +++ b/charts/openshell-keycloak/files/relay-provisioner.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Keep the workspace relay registrar in place for container-mode SAW sites. + +Each container workspace's browser relay registers its own Keycloak client +(charts/saw-workspace-relay/files/identity.py). It does that with the +registrar this helper maintains, so no relay Job needs the master admin: + + - the client scope SCOPE (OpenShell audience plus the openshell-user role), + allowed for authenticated dynamic client registration; + - the confidential client NAME whose service account holds only + realm-management/create-client in REALM; + - its credential in the Secret NAME in this namespace, which relay Jobs mount. + +Runs in Keycloak's namespace and re-verifies every INTERVAL seconds, so a +cluster comes up without a manual step and drift is repaired. The Secret is +created here, not by Helm, so a GitOps self-heal never clears the generated +credential. Errors are retried; nothing is deleted. + +Env: REALM, KEYCLOAK_NAME, KEYCLOAK_NAMESPACE, KC_URL (empty: discover the +operator's HTTPS Route), CA_FILE, ADMIN_DIR (username, password), AUDIENCE, +INTERVAL. Standard library only. +""" +import base64 +import json +import os +import secrets +import ssl +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +import saw_tls + +SA = "/var/run/secrets/kubernetes.io/serviceaccount" +NAME = "saw-relay-provisioner" +SCOPE = "saw-workspace-relay" +LABEL = "saw.redhat.com/component" + + +def log(msg): + print(f"[relay-provisioner] {msg}", flush=True) + + +class HttpError(OSError): + """An OSError so saw_tls.tls_context treats it as a failed cluster read.""" + + def __init__(self, code, msg): + super().__init__(msg) + self.code = code + + +def call(url, method="GET", *, token=None, body=None, form=None, ctx=None, patch=False): + headers, data = {}, None + if form is not None: + headers["Content-Type"] = "application/x-www-form-urlencoded" + data = urllib.parse.urlencode(form).encode() + if body is not None: + headers["Content-Type"] = "application/merge-patch+json" if patch else "application/json" + data = json.dumps(body).encode() + if token: + headers["Authorization"] = "Bearer " + token + opener = urllib.request.build_opener(saw_tls.NoRedirect(), urllib.request.HTTPSHandler(context=ctx)) + try: + with opener.open(urllib.request.Request(url, data=data, method=method, headers=headers), + timeout=20) as response: + raw = response.read() + except urllib.error.HTTPError as exc: + raise HttpError(exc.code, f"HTTP {exc.code} at {urllib.parse.urlsplit(url).path}") from None + return json.loads(raw) if raw else None + + +class Kube: + def __init__(self): + host, port = os.environ["KUBERNETES_SERVICE_HOST"], os.environ.get("KUBERNETES_SERVICE_PORT", "443") + self.base = f"https://{host}:{port}" + self.ctx = ssl.create_default_context(cafile=f"{SA}/ca.crt") + + def __call__(self, path, method="GET", body=None, patch=False): + token = open(f"{SA}/token", encoding="utf-8").read().strip() + return call(self.base + path, method, token=token, body=body, ctx=self.ctx, patch=patch) + + def get(self, path): + return self(path) + + +def credential(kube, namespace, issuer): + """The registrar's client ID and secret, kept in a Secret only this helper writes.""" + path = f"/api/v1/namespaces/{namespace}/secrets/{NAME}" + fresh = {"client-id": NAME, "client-secret": secrets.token_urlsafe(40), "issuer": issuer} + try: + state = kube(path) + except HttpError as exc: + if exc.code != 404: + raise + kube(f"/api/v1/namespaces/{namespace}/secrets", "POST", { + "apiVersion": "v1", "kind": "Secret", "type": "Opaque", + "metadata": {"name": NAME, "labels": {LABEL: NAME}}, "stringData": fresh}) + log(f"Secret {NAME} created") + state = kube(path) + if (state["metadata"].get("labels") or {}).get(LABEL) != NAME: + raise ValueError(f"Secret {NAME} exists but is not this helper's") + if not state.get("data"): + state = kube(path, "PATCH", {"metadata": {"resourceVersion": state["metadata"]["resourceVersion"]}, + "stringData": fresh}, patch=True) + values = {k: base64.b64decode(v, validate=True).decode() for k, v in state["data"].items()} + if set(values) != {"issuer", "client-id", "client-secret"} or values["client-id"] != NAME: + raise ValueError(f"Secret {NAME} has unexpected contents") + if values["issuer"] != issuer: + raise ValueError(f"Secret {NAME} is for issuer {values['issuer']}, not {issuer}") + return values + + +def setup(kube, ctx, issuer, namespace): + base, realm = issuer.rsplit("/realms/", 1) + admin = os.environ["ADMIN_DIR"] + token = call(base + "/realms/master/protocol/openid-connect/token", "POST", ctx=ctx, form={ + "client_id": "admin-cli", "grant_type": "password", + "username": open(os.path.join(admin, "username"), encoding="utf-8").read().strip(), + "password": open(os.path.join(admin, "password"), encoding="utf-8").read().strip()})["access_token"] + + def kc(path, method="GET", body=None): + return call(base + "/admin/realms/" + realm + path, method, token=token, body=body, ctx=ctx) + + if kc("") is None: + raise ValueError(f"realm {realm} is not imported yet") + values = credential(kube, namespace, issuer) + audience = os.environ["AUDIENCE"] + mappers = [ + {"name": "relay-audience", "protocol": "openid-connect", "protocolMapper": "oidc-audience-mapper", + "config": {"included.client.audience": audience, "access.token.claim": "true"}}, + {"name": "relay-user", "protocol": "openid-connect", "protocolMapper": "oidc-hardcoded-claim-mapper", + "config": {"claim.name": "realm_access.roles", "claim.value": '["openshell-user"]', + "jsonType.label": "JSON", "access.token.claim": "true"}}] + if not any(s["name"] == SCOPE for s in kc("/client-scopes")): + kc("/client-scopes", "POST", {"name": SCOPE, "protocol": "openid-connect", + "description": "SAW registration-scoped workspace relay", + "protocolMappers": mappers}) + log(f"client scope {SCOPE} created") + scope = next(s for s in kc("/client-scopes") if s["name"] == SCOPE) + actual = kc("/client-scopes/" + scope["id"] + "/protocol-mappers/models") + if {m["name"] for m in actual} != {m["name"] for m in mappers}: + raise ValueError("unexpected relay scope mappers") + for desired in mappers: + found = next(m for m in actual if m["name"] == desired["name"]) + if found["protocolMapper"] != desired["protocolMapper"] or \ + any(found["config"].get(k) != v for k, v in desired["config"].items()): + raise ValueError("foreign relay scope configuration") + # Allow this pre-approved scope for authenticated registration. Clients + # never author their own role or audience mappers. + policies = kc("/components?" + urllib.parse.urlencode( + {"type": "org.keycloak.services.clientregistration.policy.ClientRegistrationPolicy"})) + allowed = [p for p in policies if p.get("providerId") == "allowed-client-templates" + and p.get("subType") == "authenticated"] + if len(allowed) != 1: + raise ValueError("expected one authenticated client-scope registration policy") + policy = allowed[0] + permitted = policy.setdefault("config", {}).setdefault("allowed-client-scopes", []) + if SCOPE not in permitted: + permitted.append(SCOPE) + kc("/components/" + policy["id"], "PUT", policy) + log(f"{SCOPE} allowed for authenticated registration") + + def lookup(client_id): + return next((c for c in kc("/clients?" + urllib.parse.urlencode({"clientId": client_id})) + if c["clientId"] == client_id), None) + settings = dict(clientId=NAME, enabled=True, protocol="openid-connect", publicClient=False, + serviceAccountsEnabled=True, standardFlowEnabled=False, implicitFlowEnabled=False, + directAccessGrantsEnabled=False, fullScopeAllowed=False) + if not lookup(NAME): + kc("/clients", "POST", {**settings, "secret": values["client-secret"], "attributes": {LABEL: NAME}, + "defaultClientScopes": ["basic", "roles"], "optionalClientScopes": []}) + log(f"client {NAME} created") + client = kc("/clients/" + lookup(NAME)["id"]) + if client.get("attributes", {}).get(LABEL) != NAME and \ + client.get("attributes", {}).get("saw.component") != NAME: + raise ValueError("refusing to adopt a foreign provisioning client") + if any(client.get(k) != v for k, v in settings.items()): + raise ValueError("provisioning client settings drifted") + prefix = "/clients/" + client["id"] + management = lookup("realm-management")["id"] + role = kc("/clients/" + management + "/roles/create-client") + user = kc(prefix + "/service-account-user")["id"] + for path in [prefix + "/scope-mappings/clients/" + management, + "/users/" + user + "/role-mappings/clients/" + management]: + current = kc(path) + if {r["name"] for r in current} - {"create-client"}: + raise ValueError("provisioner has unexpected realm-management privileges") + if not current: + kc(path, "POST", [role]) + result = call(issuer + "/protocol/openid-connect/token", "POST", ctx=ctx, form={ + "client_id": NAME, "client_secret": values["client-secret"], "grant_type": "client_credentials"}) + part = result["access_token"].split(".")[1] + claim = json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))) + if set(claim.get("resource_access", {}).get("realm-management", {}).get("roles", [])) != {"create-client"}: + raise ValueError("unexpected effective registrar privilege") + + +def main(argv): + kube = Kube() + namespace, name = os.environ["KEYCLOAK_NAMESPACE"], os.environ["KEYCLOAK_NAME"] + realm, interval = os.environ["REALM"], int(os.environ.get("INTERVAL", "300")) + once = "--once" in argv + while True: + try: + url = os.environ.get("KC_URL") or saw_tls.keycloak_url(name, namespace, kube.get) + ctx = saw_tls.tls_context(url, kube.get, log, os.environ.get("CA_FILE") or None) + issuer = url.rstrip("/") + "/realms/" + realm + setup(kube, ctx, issuer, namespace) + log(f"registrar verified for {issuer}: create-client only") + wait = interval + except (HttpError, OSError, KeyError, ValueError) as exc: + if once: + raise + log(f"WARN: {exc}; retrying in 15s") + wait = 15 + if once: + return 0 + time.sleep(wait) + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/charts/openshell-keycloak/templates/relay-provisioner.yaml b/charts/openshell-keycloak/templates/relay-provisioner.yaml new file mode 100644 index 000000000..cbdb96f5a --- /dev/null +++ b/charts/openshell-keycloak/templates/relay-provisioner.yaml @@ -0,0 +1,198 @@ +{{- /* +The workspace relay registrar (files/relay-provisioner.py). Container-mode +browser relays register their own Keycloak clients with the credential this +keeps in the saw-relay-provisioner Secret, so no relay Job needs the master +admin. Re-verified every interval; the helper creates the Secret itself, so a +GitOps self-heal never clears the generated credential. +*/ -}} +{{- if .Values.relayProvisioner.enabled }} +{{- $r := .Values.relayProvisioner }} +{{- $kc := .Values.keycloak.existing | default .Values.keycloak.name }} +{{- if and $r.keycloakUrl (not (hasPrefix "https://" $r.keycloakUrl)) }} +{{- fail "relayProvisioner.keycloakUrl must use HTTPS" }} +{{- end }} +{{- $name := "saw-relay-provisioner" }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ $name }} + labels: + app.kubernetes.io/name: {{ $name }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ $name }} + labels: + app.kubernetes.io/name: {{ $name }} +rules: + # Create cannot be limited by name; read and update only its own Secret. + - apiGroups: [""] + resources: ["secrets"] + verbs: ["create"] + - apiGroups: [""] + resources: ["secrets"] + resourceNames: [{{ $name | quote }}] + verbs: ["get", "patch"] + - apiGroups: ["route.openshift.io"] + resources: ["routes"] + verbs: ["list"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ $name }} + labels: + app.kubernetes.io/name: {{ $name }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ $name }} +subjects: + - kind: ServiceAccount + name: {{ $name }} + namespace: {{ .Release.Namespace }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ $name }}-{{ .Release.Namespace }} + labels: + app.kubernetes.io/name: {{ $name }} +rules: + - apiGroups: ["config.openshift.io"] + resources: ["ingresses"] + resourceNames: ["cluster"] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ $name }}-{{ .Release.Namespace }} + labels: + app.kubernetes.io/name: {{ $name }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ $name }}-{{ .Release.Namespace }} +subjects: + - kind: ServiceAccount + name: {{ $name }} + namespace: {{ .Release.Namespace }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ $name }}-{{ .Release.Namespace }} + namespace: openshift-config-managed +rules: + - apiGroups: [""] + resources: ["configmaps"] + resourceNames: ["default-ingress-cert"] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ $name }}-{{ .Release.Namespace }} + namespace: openshift-config-managed +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ $name }}-{{ .Release.Namespace }} +subjects: + - kind: ServiceAccount + name: {{ $name }} + namespace: {{ .Release.Namespace }} +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ $name }}-scripts + labels: + app.kubernetes.io/name: {{ $name }} +data: + ca-bundle.crt: | +{{ $r.caBundle | default "" | indent 4 }} + saw_tls.py: | +{{ .Files.Get "files/saw_tls.py" | indent 4 }} + relay-provisioner.py: | +{{ .Files.Get "files/relay-provisioner.py" | indent 4 }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ $name }} + labels: + app.kubernetes.io/name: {{ $name }} +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app.kubernetes.io/name: {{ $name }} + template: + metadata: + labels: + app.kubernetes.io/name: {{ $name }} + annotations: + checksum/script: {{ print (.Files.Get "files/relay-provisioner.py") (.Files.Get "files/saw_tls.py") ($r.caBundle | default "") | sha256sum }} + spec: + serviceAccountName: {{ $name }} + securityContext: + runAsNonRoot: true + seccompProfile: + type: RuntimeDefault + containers: + - name: provisioner + image: {{ $r.image | quote }} + command: ["python3", "/scripts/relay-provisioner.py"] + env: + - name: KC_URL + value: {{ $r.keycloakUrl | default "" | quote }} + - name: KEYCLOAK_NAME + value: {{ $kc | quote }} + - name: KEYCLOAK_NAMESPACE + value: {{ .Release.Namespace | quote }} + {{- if $r.caBundle }} + - name: CA_FILE + value: /scripts/ca-bundle.crt + {{- end }} + - name: REALM + value: {{ .Values.keycloak.realm | quote }} + - name: AUDIENCE + value: {{ $r.audience | quote }} + - name: ADMIN_DIR + value: /admin + - name: INTERVAL + value: {{ $r.intervalSeconds | quote }} + volumeMounts: + - name: scripts + mountPath: /scripts + readOnly: true + - name: admin + mountPath: /admin + readOnly: true + securityContext: + readOnlyRootFilesystem: true + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + resources: + requests: + cpu: 10m + memory: 48Mi + limits: + memory: 128Mi + volumes: + - name: scripts + configMap: + name: {{ $name }}-scripts + - name: admin + secret: + secretName: {{ $r.adminSecret | default (printf "%s-initial-admin" $kc) }} + items: + - {key: username, path: username} + - {key: password, path: password} +{{- end }} diff --git a/charts/openshell-keycloak/values.yaml b/charts/openshell-keycloak/values.yaml index 64ddcdc5f..bda9815cf 100644 --- a/charts/openshell-keycloak/values.yaml +++ b/charts/openshell-keycloak/values.yaml @@ -144,6 +144,22 @@ redirectRegistrar: hostSuffix: "" intervalSeconds: 15 +# Container-mode workspace relays register their own Keycloak clients with a +# registrar credential (Secret saw-relay-provisioner) that this keeps in place. +# Enable wherever container workspaces may be created. +relayProvisioner: + enabled: false + image: registry.access.redhat.com/ubi9/python-311@sha256:a0bdb55576fc5b8d6704279307817828ef027e1065533ceba133fe9516003a6c + # The OpenShell audience relay tokens carry (the gateway's OIDC client). + audience: openshell-cli + # Empty: discover the operator's -ingress HTTPS Route. + keycloakUrl: "" + # Optional PEM CA for an external/private issuer. + caBundle: "" + # Empty: -initial-admin (the operator's). + adminSecret: "" + intervalSeconds: 300 + # Resolve Pattern user-list owners without placing Keycloak admin credentials # in tenant namespaces. The user-list chart grants this service account patch # access only to each tenant's saw-owner-subject ConfigMap. diff --git a/charts/openshell-rhdh/files/portal.py b/charts/openshell-rhdh/files/portal.py index 5e8c5232a..83ebed6c9 100644 --- a/charts/openshell-rhdh/files/portal.py +++ b/charts/openshell-rhdh/files/portal.py @@ -116,8 +116,8 @@ def public_model_inputs(profile, secrets): return _project(_workspace.public_model_inputs, profile, secrets) -def approved_endpoint(profile, secrets, boundary): - return _project(_workspace.approved_endpoint, profile, secrets, boundary) +def approved_endpoint(profile, secrets): + return _project(_workspace.approved_endpoint, profile, secrets) def enrolled_site(site, workspace, read): @@ -394,17 +394,84 @@ def check_user(user): PROVISIONABLE_MODES = ("vm",) -def container_site(user): - """Trusted site inventory, never names/URLs supplied by the request.""" +def _deep_merge(base, over): + out = json.loads(json.dumps(base)) + for key, value in over.items(): + out[key] = (_deep_merge(out[key], value) if isinstance(value, dict) and isinstance(out.get(key), dict) + else json.loads(json.dumps(value))) + return out + + +def container_defaults(): + """Operator-owned shared site (saw-users containerDefaults); empty when unset.""" + defaults = json.loads(os.environ.get("SAW_CONTAINER_DEFAULTS") or "{}") + return defaults if isinstance(defaults, dict) else {} + + +_OWNER_SUBJECTS = {} + + +def owner_subject(user): + """The owner's enabled Keycloak id from the owner directory, or "" when unavailable.""" + if user not in _OWNER_SUBJECTS: + url = os.environ.get("KEYCLOAK_URL", "") + try: + with open(env("KEYCLOAK_SECRET_FILE"), encoding="utf-8") as credential: + ids = keycloak_user_ids(url.rstrip("/"), env("KEYCLOAK_REALM"), env("KEYCLOAK_CLIENT_ID"), + credential.read().strip(), [user], + os.environ.get("KEYCLOAK_SKIP_VERIFY") == "true") if url else {} + except (PortalError, OSError, ValueError, KeyError) as exc: + log(f"WARN: owner lookup for {user} failed ({exc})") + return "" + if not ids.get(user): + return "" # not cached: the account may be created later + _OWNER_SUBJECTS[user] = ids[user] + return _OWNER_SUBJECTS[user] + + +def container_site(user, subject=None): + """Trusted site inventory, never names/URLs supplied by the request. + + An owner's own containerSites entry is layered over the shared + containerDefaults. A site from the defaults takes the owner's subject from + the registry entry or the owner directory, and unset chart revisions follow + the pattern branch, as for saw-users entries.""" sites = json.loads(os.environ.get("SAW_CONTAINER_SITES", "{}")) site = sites.get(user) + defaults = container_defaults() + if defaults and (site is None or isinstance(site, dict)): + site = _deep_merge(defaults, site or {}) + if not site.get("subject"): + site["subject"] = subject or owner_subject(user) + # Only an autoApprove site follows the pattern branch; a reviewed site + # pins commit SHAs, and preflight rejects any it leaves unset. + revision = os.environ.get("SAW_TARGET_REVISION", "") if auto_approved(site) else "" + if revision: + stack = site.setdefault("stack", {}) + for key in ("identity", "policy", "gateway", "audit"): + item = stack.setdefault(key, {}) + if isinstance(item, dict) and not item.get("revision"): + item["revision"] = revision + automatic = site.get("automaticEnrollment") + if isinstance(automatic, dict): + automatic.setdefault("revision", revision) + if isinstance(automatic.get("relay"), dict): + automatic["relay"].setdefault("revision", revision) if not isinstance(site, dict) or not re.fullmatch( r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", str(site.get("subject", ""))): return None return site -def container_profiles(site): +def auto_approved(site): + automatic = (site or {}).get("automaticEnrollment", {}) + return isinstance(automatic, dict) and automatic.get("autoApprove") is True + + +def container_profiles(site, catalog=None): + """Profiles an owner may request: every catalog profile on an autoApprove site.""" + if auto_approved(site): + return {profile: "" for profile in (catalog or {})} automatic = site.get("automaticEnrollment", {}) return automatic.get("approvedProfiles", {}) @@ -428,7 +495,8 @@ def read(path): if exc.code == 403: return {} raise - return _workspace.container_status(read, normalized, container_site(user), argo_ns, domain, ping, catalog) + return _workspace.container_status(read, normalized, container_site(user, entry.get("ownerSubject")), + argo_ns, domain, ping, catalog) def installation_id(user, registration): @@ -744,8 +812,9 @@ def _approved_profile_reference(site, profile): def check_live_boundary_approval(k8s, user, site, mode, profile, catalog): """Check the existing namespace policy against the owner-approved hash.""" automatic = site.get("automaticEnrollment", {}) if isinstance(site, dict) else {} - if not isinstance(automatic, dict) or not automatic or automatic.get("enabled") is False: - return + if (not isinstance(automatic, dict) or not automatic or automatic.get("enabled") is False + or automatic.get("autoApprove") is True): + return # autoApprove: enrollment publishes the first observed boundary reference = _approved_profile_reference(site, profile) try: _preflight.verify_boundary_reference(reference, mode) @@ -815,8 +884,41 @@ def resource(path, key, normalize=False): "sandboxPlacementBinding") +def credential_bindings(entry): + """Which Secret key backs which OpenShell provider type for one profile. + + Mirrors the saw-users.credentialBindings helper, which renders the same + list into the site once the workspace is created. + """ + keys = {} + for name, spec in (entry.get("secrets") or {}).items(): + fields = list(spec.get("fields") or []) + refresh = spec.get("refresh") or {} + if refresh: + fields.append({"key": refresh.get("credentialKey"), "kind": "secret", "refresh": True}) + for field in fields: + if field.get("kind") != "secret" or field.get("refreshMaterial"): + continue + binding = keys.setdefault((name, field["key"]), {"providers": [], "refresh": False}) + for provider in spec.get("providers") or []: + for kind in [provider] + (["build"] if provider == "nvidia" else []): + if kind not in binding["providers"]: + binding["providers"].append(kind) + binding["refresh"] = binding["refresh"] or bool(field.get("refresh")) + bindings = [] + for (name, key), binding in sorted(keys.items()): + for kind in binding["providers"]: + item = {"secret": name, "key": key, "type": kind} + if binding["refresh"]: + item["refresh"] = "oauth2_refresh_token" + bindings.append(item) + return bindings + + def check_workspace_preflight(k8s, user, site, mode, profile, catalog): """Run read-only platform gates before reserving or writing keys.""" + if "credentialBindings" not in site: + site = {**site, "credentialBindings": credential_bindings(catalog[profile])} observations = _preflight.configuration_facts(site) observations["api"] = True try: @@ -1327,7 +1429,7 @@ def workspace_status(k8s, user, catalog, ns, argo_ns, domain, ping=None): "title": message, "text": message, "message": message, "ready": False, "failed": state != "running", "steps": [], "links": []} mode = entry_deployment_mode(entry) - if mode in KUBERNETES_MODES and container_site(user): + if mode in KUBERNETES_MODES and container_site(user, entry.get("ownerSubject")): return container_status(k8s, user, entry, argo_ns, domain, ping or owner_route_available, catalog) if mode not in PROVISIONABLE_MODES: message = f"{mode} workspace lifecycle and readiness are not qualified in this release" @@ -1674,7 +1776,7 @@ def handle(action, request_name): _workspace.validate_runtime_placement(mode, site) except _workspace.WorkspaceError as exc: raise PortalError(str(exc)) from exc - approved = container_profiles(site) + approved = container_profiles(site, catalog) if data.get("profile") not in approved: raise PortalError("selected profile is not approved for your container workspace; " "approved profiles: " + (", ".join(sorted(approved)) or "none") + @@ -1693,8 +1795,7 @@ def handle(action, request_name): if mode in KUBERNETES_MODES: if cm and read_entry(cm)["profiles"] != [profile]: raise PortalError("changing the profile requires a new container registration") - endpoint = approved_endpoint(catalog[profile], secrets, - site.get("profileBoundaries", {}).get(profile, {})) + endpoint = approved_endpoint(catalog[profile], secrets) if cm and endpoint != read_entry(cm).get("customInferenceURL"): raise PortalError("changing the endpoint requires a new registration") models = public_model_inputs(catalog[profile], secrets) @@ -1723,7 +1824,7 @@ def handle(action, request_name): entry["webSearch"] = {"enabled": False} if models: entry["modelInputs"] = models - if "approvedProfiles" in site.get("automaticEnrollment",{}): + if "approvedProfiles" in site.get("automaticEnrollment",{}) or auto_approved(site): slots=sandbox_targets(user,generation,catalog[profile]) entry["uiNamespaces"]=sorted({"saw-ui-"+slot["relayID"] for slot in slots.values() if slot["ui"]}) entry["intentGeneration"] = previous.get("intentGeneration", 0) + 1 @@ -1900,7 +2001,8 @@ def generator_params(workspaces, defaults, read=None, catalog=None, previous=Non for entry in workspaces: ws = {**entry, "values": {**entry.get("values", {}), "deployment": {"mode": entry_deployment_mode(entry)}}} - site = container_site(ws["name"]) if entry_deployment_mode(ws) in KUBERNETES_MODES else {} + site = (container_site(ws["name"], ws.get("ownerSubject")) + if entry_deployment_mode(ws) in KUBERNETES_MODES else {}) if site: if not ws.get("ownerSubject") or ws["ownerSubject"] != site["subject"]: continue diff --git a/charts/openshell-rhdh/files/preflight.py b/charts/openshell-rhdh/files/preflight.py index c32862180..dc499183c 100644 --- a/charts/openshell-rhdh/files/preflight.py +++ b/charts/openshell-rhdh/files/preflight.py @@ -196,24 +196,33 @@ def check_observations(mode, observations): return tuple(required) +# Reviewed sites pin every chart to a full commit SHA. An autoApprove +# (development) site may follow a branch instead: saw-users and portal defaults +# use global.targetRevision when a site sets no revision. +PINNED_REVISION = r"[a-f0-9]{40}" +BRANCH_REVISION = r"[a-f0-9]{40}|[A-Za-z0-9][A-Za-z0-9._/-]*" + + def configuration_facts(site): """Check site-owned inputs that do not require cluster access.""" if not isinstance(site, dict): return {key: False for key in ("network", "storage", "secrets", "registry", "providerEgress", "revisions")} stack = site.get("stack") if isinstance(site.get("stack"), dict) else {} + enrollment = site.get("automaticEnrollment") or {} + revision_pattern = BRANCH_REVISION if isinstance(enrollment, dict) and enrollment.get( + "autoApprove") is True else PINNED_REVISION revisions = [item.get("revision") for item in stack.values() if isinstance(item, dict)] - required_components = ("identity", "policy", "proxy", "gateway", "audit") + required_components = ("identity", "policy", "gateway", "audit") revision_pin = all(isinstance(stack.get(name), dict) for name in required_components) and all( isinstance(stack[name].get("revision"), str) - and re.fullmatch(r"[a-f0-9]{40}", stack[name]["revision"]) + and re.fullmatch(revision_pattern, stack[name]["revision"]) for name in required_components) and bool(revisions) and len(revisions) == len(stack) and all( - isinstance(value, str) and re.fullmatch(r"[a-f0-9]{40}", value) for value in revisions) - enrollment = site.get("automaticEnrollment") or {} + isinstance(value, str) and re.fullmatch(revision_pattern, value) for value in revisions) if enrollment and not isinstance(enrollment, dict): revision_pin = False elif enrollment: - revision_pin = revision_pin and bool(re.fullmatch(r"[a-f0-9]{40}", str(enrollment.get("revision", "")))) + revision_pin = revision_pin and bool(re.fullmatch(revision_pattern, str(enrollment.get("revision", "")))) image_values = [] storage_values = [] @@ -233,28 +242,20 @@ def walk(value, path=()): walk(child, path) walk(site) - declared_hosts = site.get("providerAllowHosts") - policy = site.get("providerPolicy") - clean_hosts = (isinstance(declared_hosts, list) and bool(declared_hosts) - and all(isinstance(host, str) and host and "*" not in host - for host in declared_hosts) - and (policy is None or (isinstance(policy, dict) - and isinstance(policy.get("allowHosts"), list) - and all(isinstance(host, str) for host in policy["allowHosts"]) - and set(policy["allowHosts"]) == set(declared_hosts)))) - proxy = stack.get("proxy") or {} - proxy_values = proxy.get("values") or {} if isinstance(proxy, dict) else {} - bootstrap_egress = ((proxy_values.get("network") or {}).get("bootstrapEgress") - if isinstance(proxy_values, dict) else None) + # OpenShell decides where each credential may go (provider profiles); the + # site only lists which Secret backs which provider type. + bindings = site.get("credentialBindings") + clean_bindings = (isinstance(bindings, list) and all( + isinstance(b, dict) and {"secret", "key", "type"} <= set(b) <= {"secret", "key", "type", "refresh"} + and all(isinstance(v, str) and v for v in b.values()) for b in bindings)) storage_ok = bool(storage_values) and all(value.strip() for value in storage_values) return { - "network": bool(stack.get("policy")) and isinstance(bootstrap_egress, list) - and bool(bootstrap_egress), + "network": bool(stack.get("policy")), "storage": storage_ok, "secrets": isinstance(site.get("secretStore", "vault-backend"), str) and bool(site.get("secretStore", "vault-backend")), "registry": bool(image_values) and all("@sha256:" in image for image in image_values), - "providerEgress": clean_hosts, + "providerEgress": clean_bindings, "revisions": revision_pin, } diff --git a/charts/openshell-rhdh/files/workspace.py b/charts/openshell-rhdh/files/workspace.py index bc86b4d01..1addd71e3 100644 --- a/charts/openshell-rhdh/files/workspace.py +++ b/charts/openshell-rhdh/files/workspace.py @@ -5,6 +5,7 @@ resource application. This module never discovers or changes cluster state. """ import hashlib +import ipaddress import json import re import urllib.parse @@ -18,9 +19,9 @@ class WorkspaceError(ValueError): SAFE_FAILURE_REASONS = frozenset({ "ProfileRejected", "InvalidPlan", "PlacementRejected", "IdentityConflict", "InvalidIntent", "StaleIntent", "ReconcilerStateRejected", "GatewayMismatch", - "ProviderProfileMismatch", "WorkspaceRejected", "ProviderRejected", + "ProviderProfileMismatch", "ProviderRefreshFailed", "WorkspaceRejected", "ProviderRejected", "SandboxRejected", "SandboxStateMismatch", "SandboxDrift", "CoreRejected", - "CoreFailure", + "CoreFailure", "ReenrollRequired", }) SAFE_RPC_CODES = frozenset({ "NOT_FOUND", "ALREADY_EXISTS", "UNAVAILABLE", "DEADLINE_EXCEEDED", "ABORTED", @@ -82,24 +83,40 @@ def public_model_inputs(profile, secrets): return values -def approved_endpoint(profile, secrets, boundary): +CUSTOM_INFERENCE_URL = re.compile(r"https://[a-z0-9-]+(?:\.[a-z0-9-]+)+(?::443)?(?:/[A-Za-z0-9_-]+)*/v1") + + +def custom_inference_url(endpoint): + """The workspace's own OpenAI-compatible base URL: HTTPS, a DNS name, port 443, ending /v1. + + Which host may receive the API key is not decided here: the custom-inference + governance profile names it, and the runtime controller refuses a workspace + whose URL host is not that profile's only endpoint (ProviderProfileMismatch). + """ + if not isinstance(endpoint, str) or not CUSTOM_INFERENCE_URL.fullmatch(endpoint): + raise WorkspaceError("custom inference needs an HTTPS base URL ending in /v1") + try: + ipaddress.ip_address(urllib.parse.urlsplit(endpoint).hostname) + except ValueError: + return endpoint + raise WorkspaceError("custom inference needs an HTTPS base URL ending in /v1, with a DNS name") + + +def approved_endpoint(profile, secrets): + """The endpoint URL the owner entered (public metadata), if the profile takes one.""" refs = {sb["endpointInput"] for _, sb in enabled_catalog_sandboxes(profile) if sb.get("endpointInput")} if not refs: return None - endpoint = boundary.get("inferenceBaseURL", "") - if not isinstance(endpoint, str) or not re.fullmatch( - r"https://[a-z0-9-]+(?:\.[a-z0-9-]+)+(?::443)?(?:/[A-Za-z0-9_-]+)*/v1", endpoint): - raise WorkspaceError("site has no approved custom inference endpoint") - if boundary.get("allowHosts") != [urllib.parse.urlsplit(endpoint).hostname]: - raise WorkspaceError("custom inference requires a dedicated broker host") + endpoints = set() for ref in refs: secret, key = ref.split(".", 1) fields = profile["secrets"][secret]["fields"] if not any(f["key"] == key and f["kind"] == "url" for f in fields): raise WorkspaceError("endpoint input must be public URL metadata") - if secrets.get(secret, {}).get(key, "").rstrip("/") != endpoint: - raise WorkspaceError("endpoint differs from the site-approved custom inference URL") - return endpoint + endpoints.add(secrets.get(secret, {}).get(key, "").rstrip("/")) + if len(endpoints) != 1: + raise WorkspaceError("custom inference endpoint inputs disagree") + return custom_inference_url(endpoints.pop()) def enrolled_site(site, ws, read): @@ -123,17 +140,18 @@ def publication(name): if data: raise WorkspaceError("cannot disable enrollment of a bound workspace; use desiredState") return fresh - for key, kind in (("reference", dict), ("relay", dict), ("revision", str), - ("image", str), ("buildNamespace", str)): + auto = a.get("autoApprove") is True + for key, kind in ((() if auto else (("reference", dict),)) + (("relay", dict), ("revision", str), + ("image", str), ("buildNamespace", str))): if not isinstance(a.get(key), kind) or not a[key]: raise WorkspaceError(f"container site for {ws['name']} requires automaticEnrollment.{key}") if not data: return fresh bound=json.loads(data["binding.json"]) - if set(bound)!={"registration","intent","approved","gatewayCA"} or bound["registration"]!=reg or set(bound["approved"])!=set(a["reference"]): + if set(bound)!={"registration","intent","approved","gatewayCA"} or bound["registration"]!=reg or (not auto and set(bound["approved"])!=set(a["reference"])): raise WorkspaceError("invalid published enrollment") intent=bound["intent"] - if intent["bindings"]["ownerID"]!=install or intent["bindings"]["namespace"]!="saw-"+ws["name"] or intent["bindings"]["ownerSubject"]!=ws["ownerSubject"] or intent["profileRef"]["sha256"]!=site.get("selectedDigest",a.get("profileSHA256")): + if intent["bindings"]["ownerID"]!=install or intent["bindings"]["namespace"]!="saw-"+ws["name"] or intent["bindings"]["ownerSubject"]!=ws["ownerSubject"] or (not auto and intent["profileRef"]["sha256"]!=site.get("selectedDigest",a.get("profileSHA256"))): raise WorkspaceError("published intent does not belong to this workspace") subjects = {target["subjectMap"]:publication(target["subjectMap"]).get("subject", "") for target in site.get("targets",{}).values() if target["ui"]} @@ -204,7 +222,7 @@ def project_workspace(workspace, defaults, site, catalog, read=None, previous=No # Inputs include operator configuration and immutable API publications. # Do not include arbitrary values (especially JSON bodies) in diagnostics. detail = f"missing {exc.args[0]}" if isinstance(exc, KeyError) and exc.args[0] in { - "subject", "registration", "installationID", "reference", "allowHosts", "bindings", + "subject", "registration", "installationID", "reference", "bindings", "binding.json", "profileRef", "sha256", "initialModelInputs"} else "invalid site or publication" raise WorkspaceError(f"workspace {workspace.get('name', '?')}: {detail}") from None @@ -241,11 +259,26 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): validate_runtime_placement(mode, site) automatic = site.get("automaticEnrollment", {}) selected, *extra = ws.get("profiles", []) or [None] - foundation = automatic.get("enabled") is False + foundation = automatic.get("enabled") is False or automatic.get("autoApprove") is True if extra or selected not in catalog or not foundation and selected not in automatic.get("approvedProfiles", {}): raise WorkspaceError("container requires one approved BOM profile") if not ws.get("registration") or not ws.get("installationID"): raise WorkspaceError("container requires a registration and installation identity") + # As the portal does at registration: a dedicated-endpoint profile (such as + # custom-inference) has no web-search credential unless the entry asks for it. + if "dedicatedEndpointSecrets" in catalog[selected] and "webSearch" not in ws: + ws["webSearch"] = {"enabled": False} + # The runtime compiles the model from public inputs, never from the Secret. + # The portal reads it from the form; a static entry must name it. + given = ws.get("initialModelInputs") if ws.get("lifecycleVersion") == 1 else ws.get("modelInputs") + for _, sandbox in enabled_catalog_sandboxes(catalog[selected]): + key = sandbox.get("modelInput") + if not key: + continue + secret, field = key.split(".", 1) + definition = next((f for f in catalog[selected]["secrets"][secret]["fields"] if f["key"] == field), {}) + if definition.get("required") and not definition.get("default") and not (given or {}).get(key): + raise WorkspaceError(f"{ws['name']}: set modelInputs.{key} (the model this profile requires)") overrides = site.get("profileImageOverrides", {}).get(selected, {}) if overrides: ws["imageOverrides"] = overrides @@ -259,12 +292,19 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): target["image"] = overrides.get(target["sandbox"], target["image"]) boundary = site.get("profileBoundaries", {}).get(selected) if boundary: - site = {**site, "providerAllowHosts": boundary["allowHosts"], - "automaticEnrollment": {**automatic, "reference": boundary["reference"]}} - if ws.get("customInferenceURL"): - if not boundary or boundary.get("inferenceBaseURL") != ws["customInferenceURL"]: - raise WorkspaceError("endpoint differs from the site-approved custom inference URL") - site["customInferenceURL"] = ws["customInferenceURL"] + # autoApprove sites have no operator-reviewed reference to pin. + reviewed = {"reference": boundary["reference"]} if "reference" in boundary or \ + automatic.get("autoApprove") is not True else {} + site = {**site, "automaticEnrollment": {**automatic, **reviewed}} + # A profile with an endpoint input (custom-inference) uses the owner's own + # URL: the portal form value, or customInferenceURL in a static entry. The + # custom-inference governance profile approves its host at run time. + if any(sb.get("endpointInput") for _, sb in enabled_catalog_sandboxes(catalog[selected])): + if not ws.get("customInferenceURL"): + raise WorkspaceError(f"{ws['name']}: set customInferenceURL (the inference server's base URL)") + site["customInferenceURL"] = custom_inference_url(ws["customInferenceURL"]) + elif ws.get("customInferenceURL"): + raise WorkspaceError("only a profile with an endpoint input takes customInferenceURL") if managed: site.update(lifecycleVersion=1, modelInputs=ws["initialModelInputs"], requestedModels=ws.get("modelInputs", {}), desiredState=ws["desiredState"], diff --git a/charts/openshell-rhdh/templates/_helpers.tpl b/charts/openshell-rhdh/templates/_helpers.tpl index 985206768..621c6823d 100644 --- a/charts/openshell-rhdh/templates/_helpers.tpl +++ b/charts/openshell-rhdh/templates/_helpers.tpl @@ -170,7 +170,7 @@ from the release is enough and keeps renders stable. {{- if and .Values.portal.containerSites .Values.portal.containerSitesSecretName -}} {{- fail "set only one of portal.containerSites and portal.containerSitesSecretName" -}} {{- end -}} -{{- if or .Values.portal.containerSites .Values.portal.containerSitesSecretName -}}true{{- else -}}false{{- end -}} +{{- if or .Values.portal.containerSites .Values.portal.containerSitesSecretName .Values.containerDefaults -}}true{{- else -}}false{{- end -}} {{- end -}} {{- define "openshell-rhdh.containerSitesEnv" -}} @@ -183,6 +183,13 @@ from the release is enough and keeps renders stable. {{- else }} value: {{ .Values.portal.containerSites | default dict | toJson | quote }} {{- end }} +{{- /* Shared site for every owner without their own entry (saw-users' +containerDefaults, from overrides/saw-container-defaults.yaml). Subjects come +from the owner directory; unset chart revisions follow the pattern branch. */}} +- name: SAW_CONTAINER_DEFAULTS + value: {{ .Values.containerDefaults | default dict | toJson | quote }} +- name: SAW_TARGET_REVISION + value: {{ .Values.global.targetRevision | default "" | quote }} {{- end -}} {{/* Generated forms have vm as their safe default; project the administrator's @@ -221,6 +228,18 @@ The server still verifies the authenticated owner's exact profile approval. */ - {{- end -}} {{- end -}} {{- end -}} +{{- with $root.Values.containerDefaults -}} +{{- /* The shared site serves every owner: autoApprove offers each catalog +profile, otherwise its approvedProfiles. */ -}} +{{- $a := .automaticEnrollment | default dict -}} +{{- if has "container" $modes -}} +{{- range $id := $step.properties.profile.enum -}} +{{- if or (eq (toString ($a.autoApprove | default false)) "true") (hasKey ($a.approvedProfiles | default dict) $id) -}} +{{- $_ := set (index $approved "container") $id true -}} +{{- end -}} +{{- end -}} +{{- end -}} +{{- end -}} {{- $profilesByMode := dict -}} {{- range $mode := list "container" "kata" -}} {{- $ids := list -}}{{- $names := list -}} diff --git a/charts/openshell-saw-kubernetes/Chart.yaml b/charts/openshell-saw-kubernetes/Chart.yaml index 5782371f8..79676baae 100644 --- a/charts/openshell-saw-kubernetes/Chart.yaml +++ b/charts/openshell-saw-kubernetes/Chart.yaml @@ -3,4 +3,4 @@ name: openshell-saw-kubernetes description: Experimental SAW integration for the stock OpenShell Kubernetes driver type: application version: 0.1.0 -appVersion: "0.1.6-rhaiv.4" +appVersion: "0.1.10-rhaiv.0" diff --git a/charts/openshell-saw-kubernetes/templates/_helpers.tpl b/charts/openshell-saw-kubernetes/templates/_helpers.tpl index cccd7beed..692f869c5 100644 --- a/charts/openshell-saw-kubernetes/templates/_helpers.tpl +++ b/charts/openshell-saw-kubernetes/templates/_helpers.tpl @@ -21,14 +21,17 @@ app.kubernetes.io/part-of: secure-agent-workspace {{- range $name, $secret := $k.identity -}} {{- if or (not $secret) (gt (len $secret) 253) (not (regexMatch "^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$" $secret)) -}}{{- fail (printf "kubernetes.identity.%s requires an existing retained Secret name" $name) -}}{{- end -}} {{- end -}} -{{- if not $k.storage.className -}}{{- fail "kubernetes.storage.className must be explicit" -}}{{- end -}} {{- if and (eq .Values.deployment.mode "container") $k.workload.runtimeClassName -}}{{- fail "container mode must use the default workload runtime" -}}{{- end -}} {{- 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 -}} +{{- with .Values.telemetry.ocsfEndpoint -}} +{{- if not (regexMatch "^https?://[a-z0-9.-]+:[0-9]+$" .) -}}{{- fail "telemetry.ocsfEndpoint must be http(s)://host:port (OTLP/gRPC)" -}}{{- end -}} +{{- end -}} +{{- if and .Values.telemetry.agentTraces (not .Values.telemetry.ocsfEndpoint) -}}{{- fail "telemetry.agentTraces relays to the telemetry.ocsfEndpoint collector; set it" -}}{{- end -}} {{- if not $k.network.gatewayEgress -}}{{- fail "explicit gateway API/DNS/OIDC/governance/proxy egress rules are required" -}}{{- end -}} {{- range $rule := $k.network.gatewayEgress -}} {{- if or (not $rule.to) (not $rule.ports) -}}{{- fail "gateway egress rules need nonempty destinations and ports" -}}{{- end -}} @@ -37,7 +40,7 @@ app.kubernetes.io/part-of: secure-agent-workspace {{- if hasKey $peer "namespaceSelector" -}} {{- if and (empty $peer.namespaceSelector.matchLabels) (empty $peer.namespaceSelector.matchExpressions) -}}{{- fail "gateway egress must not select all namespaces" -}}{{- end -}} {{- end -}} -{{- if and $peer.ipBlock (has $peer.ipBlock.cidr (list "0.0.0.0/0" "::/0")) (not $peer.ipBlock.except) -}}{{- fail "gateway egress must not allow all addresses" -}}{{- end -}} +{{- if and $peer.ipBlock (has $peer.ipBlock.cidr (list "0.0.0.0/0" "::/0")) (not $peer.ipBlock.except) (ne (toJson $rule.ports) (toJson (list (dict "protocol" "TCP" "port" 443)))) -}}{{- fail "gateway egress may allow all addresses only for HTTPS (TCP 443)" -}}{{- end -}} {{- end -}} {{- end -}} {{- end -}} diff --git a/charts/openshell-saw-kubernetes/templates/gateway-config.yaml b/charts/openshell-saw-kubernetes/templates/gateway-config.yaml index b0143a11c..ce394b724 100644 --- a/charts/openshell-saw-kubernetes/templates/gateway-config.yaml +++ b/charts/openshell-saw-kubernetes/templates/gateway-config.yaml @@ -42,6 +42,22 @@ data: admin_role = {{ .Values.oidc.adminRole | quote }} user_role = {{ .Values.oidc.userRole | quote }} dangerously_allow_insecure_http = false + {{- with .Values.telemetry.ocsfEndpoint }} + # Best-effort OCSF export over OTLP/gRPC. Supervisors receive the same + # endpoint and export their own events to it. No trace export. + [openshell.gateway.otlp] + [openshell.gateway.otlp.ocsf] + enabled = true + endpoint = {{ . | quote }} + {{- if $.Values.telemetry.agentTraces }} + # Agent trace relay: each supervisor forwards the workload's own OTLP/HTTP + # traces (sent to a reserved in-sandbox address) to the same collector, + # tagged openshell.telemetry.source=agent. Best-effort. + [openshell.gateway.otlp.agent] + enabled = true + endpoint = {{ . | quote }} + {{- end }} + {{- end }} [openshell.drivers.kubernetes] namespace = {{ .Release.Namespace | quote }} gateway_id = {{ .Release.Name | quote }} @@ -54,6 +70,12 @@ data: # Driver projects only ca.crt: supervisors must trust the SERVER root. client_tls_secret_name = {{ .Values.kubernetes.identity.serverTlsSecret | quote }} default_runtime_class_name = {{ .Values.kubernetes.workload.runtimeClassName | quote }} + {{- if eq .Values.deployment.mode "kata" }} + # Kata: the supervisor gets its own Kata VM too (OpenShell >= 0.1.10), + # separate from the workload's, so agent traffic is handled behind a + # second guest kernel. + supervisor_runtime_class_name = {{ .Values.kubernetes.workload.runtimeClassName | quote }} + {{- end }} workspace_storage_class = {{ .Values.kubernetes.storage.className | quote }} workspace_default_storage_size = {{ .Values.kubernetes.storage.workspaceSize | quote }} allow_driver_config = true @@ -62,10 +84,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..1b9fa2c07 100644 --- a/charts/openshell-saw-kubernetes/templates/gateway.yaml +++ b/charts/openshell-saw-kubernetes/templates/gateway.yaml @@ -17,6 +17,7 @@ spec: labels: {{- include "saw-kubernetes.labels" . | nindent 8 }} openshell.pattern/role: gateway + saw.redhat.com/kubernetes-api: allow annotations: checksum/config: {{ include (print $.Template.BasePath "/gateway-config.yaml") . | sha256sum }} spec: @@ -88,7 +89,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 +107,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 }}}} @@ -125,7 +130,9 @@ metadata: argocd.argoproj.io/sync-options: Prune=false,Delete=false spec: accessModes: [ReadWriteOnce] - storageClassName: {{ $k.storage.className | quote }} + {{- with $k.storage.className }} + storageClassName: {{ . | quote }} + {{- end }} resources: requests: {storage: {{ $k.storage.gatewaySize | quote }}} {{- end }} diff --git a/charts/openshell-saw-kubernetes/values.yaml b/charts/openshell-saw-kubernetes/values.yaml index 50781a176..e92137c35 100644 --- a/charts/openshell-saw-kubernetes/values.yaml +++ b/charts/openshell-saw-kubernetes/values.yaml @@ -11,17 +11,20 @@ kubernetes: runtimeBootstrapGraceSeconds: 900 sandboxAttachRequestTimeoutSeconds: 900 gateway: - version: 0.1.6-rhaiv.4 - image: quay.io/opendatahub/odh-openshell-gateway@sha256:bd2d7c9084b80b8d3d8ef92d00a27b963b35168fad84cd862b7f91fd9c488c3e + version: 0.1.10-rhaiv.0 + image: quay.io/opendatahub/odh-openshell-gateway@sha256:e4b89770ef55238cc45d9880614eda64b8ab9a76be5e6c81c63a350889eb0717 resources: requests: {cpu: 100m, memory: 256Mi} limits: {memory: 1Gi} supervisor: - image: quay.io/opendatahub/odh-openshell-supervisor@sha256:626b91a0f53393dac0d591c142b81100916aa66b4e65444b5527672b5533fe86 + image: quay.io/opendatahub/odh-openshell-supervisor@sha256:c2c8e9d3d19a1612074df0f637078064cff45b92d35c74b116a72fb503b3c1bc workload: # Application image; set to an approved immutable sandbox image. image: "" - runtimeImage: quay.io/opendatahub/odh-openshell-sandbox@sha256:0cde11346e68485907c22d3c9b30802e52cf16e3853720a864ac8347bb68f6ef + # TEMPORARY carry (openshell-sandbox-carry/): the official + # odh-openshell-sandbox v0.1.10-rhaiv.0 panics on every connect on RHEL 9. + # Keep equal to saw-portal-container driverDefaults.runtimeImage. + runtimeImage: ghcr.io/sauagarwa/saw-openshell-sandbox@sha256:402b9727a690e8c8a10fb10c0cee21e96ea034b652d6c7d5b3f06eba916c9881 runtimeClassName: "" identity: # Existing, retained identity; generated once outside Helm by its owner. @@ -33,6 +36,8 @@ kubernetes: # key: key-encryption-key (stock gateway format) credentialKeySecret: "" storage: + # Empty uses the cluster's default StorageClass, as upstream OpenShell + # does for the gateway and workspace volumes. Use a block-backed class. className: "" gatewaySize: 5Gi workspaceSize: 20Gi @@ -47,8 +52,10 @@ kubernetes: governance: endpoint: "" network: - # All gateway egress is explicit; no namespace-wide internet allowance. - # Include API Service + real backend IPs, DNS, OIDC, governance and proxy. + # All gateway egress is explicit: DNS, governance, proxy, and the OIDC + # issuer (HTTPS to any address is allowed for it). The Kubernetes API is + # opened separately, by an AdminNetworkPolicy to the control-plane nodes + # for pods labeled saw.redhat.com/kubernetes-api=allow. gatewayEgress: [] # Trusted API reconciler Pods are selected by exact namespace AND label. reconcilerNamespace: "" @@ -64,3 +71,11 @@ oidc: route: enabled: true host: "" + +telemetry: + # OTLP/gRPC collector for OCSF events from the gateway and its supervisors, + # e.g. http://saw-ocsf-collector.openshell-agents.svc:4317. Empty: no export. + ocsfEndpoint: "" + # Relay the agent's own OpenTelemetry traces through each supervisor to the + # same collector (OpenShell agent trace relay). Needs ocsfEndpoint. + agentTraces: false diff --git a/charts/openshell-saw/files/installer/apply_bom.py b/charts/openshell-saw/files/installer/apply_bom.py index 35d8b0ad7..130cac5ac 100644 --- a/charts/openshell-saw/files/installer/apply_bom.py +++ b/charts/openshell-saw/files/installer/apply_bom.py @@ -3976,7 +3976,11 @@ def start_openclaw(self, ws, sb, provider): raise ValueError("expected a list of model IDs") except ValueError as exc: raise InstallerError(f"cannot read OpenClaw managed models: {exc}") from None - if (sb.inference_values or {}).get("models") or previous: + thinking = (sb.inference_values or {}).get("thinking", "") + if thinking: + self.mark_reasoning_model(exec_cmd, oc_env, provider.type, model_id, + reasoning=thinking != "off") + if (sb.inference_values or {}).get("models") or previous or thinking: current_models = self.cli(*exec_cmd, "sh", "-c", f"{oc_env} openclaw config get agents.defaults --json", quiet=True) @@ -3989,7 +3993,9 @@ def start_openclaw(self, ws, sb, provider): raise ValueError("expected a mapping") except ValueError as exc: raise InstallerError(f"cannot read OpenClaw model choices: {exc}") from None - desired = {model_id: {}} + # The profile's thinking level is this model's default; /think in a + # chat still overrides it for that session. + desired = {model_id: {"params": {"thinking": thinking}} if thinking else {}} for name, selected_model in (sb.inference_values or {}).get("models", {}).items(): kind = next(p.type for p in ws.providers if p.name == name) selected_id = (selected_model if selected_model.startswith(f"{kind}/") @@ -4001,6 +4007,11 @@ def start_openclaw(self, ws, sb, provider): choices.pop(name, None) for name, settings in desired.items(): choices.setdefault(name, {}).update(settings) + if not thinking and isinstance(choices[model_id].get("params"), dict): + # A thinking level removed from the profile stops applying. + choices[model_id]["params"].pop("thinking", None) + if not choices[model_id]["params"]: + choices[model_id].pop("params") self.cli(*exec_cmd, "sh", "-c", f"{oc_env} openclaw config set agents.defaults.models " + shlex.quote(json.dumps(choices)) @@ -4057,6 +4068,42 @@ def launch_openclaw(self, ws, sb, exec_cmd, oc_env): self.clear_confinement_stop(ws, sb) self.install_keepalive(ws, sb) + def mark_reasoning_model(self, exec_cmd, oc_env, provider_type, model_id, reasoning=True): + """Set whether OpenClaw treats a custom provider's model as reasoning. + + OpenClaw knows which of its own models reason; a custom model offers + only default and off unless its entry says reasoning: true and lists + the efforts the endpoint accepts (sent as reasoning_effort). Thinking + off marks it reasoning: false, so no effort is sent.""" + key = f"models.providers.{shlex.quote(provider_type)}.models" + found = self.cli(*exec_cmd, "sh", "-c", f"{oc_env} openclaw config get {key} --json", + check=False, quiet=True) + if self.sh.dry_run: + return + try: + models = json.loads(found.out) if found.ok else None + except ValueError: + models = None + bare = model_id.removeprefix(f"{provider_type}/") + entry = next((m for m in models or [] if isinstance(m, dict) and m.get("id") in (bare, model_id)), None) + if entry is None: + log(f"WARN: {provider_type} has no model entry for '{bare}'; its thinking level " + "applies only if OpenClaw already treats it as a reasoning model") + return + compat = entry.setdefault("compat", {}) + efforts = REASONING_EFFORTS if reasoning else None + if entry.get("reasoning") is reasoning and compat.get("supportedReasoningEfforts") == efforts: + return + entry["reasoning"] = reasoning + if reasoning: + compat["supportedReasoningEfforts"] = REASONING_EFFORTS + else: + compat.pop("supportedReasoningEfforts", None) + if not compat: + entry.pop("compat") + self.cli(*exec_cmd, "sh", "-c", + f"{oc_env} openclaw config set {key} {shlex.quote(json.dumps(models))}") + def disable_provider_channels(self, ws, sb, exec_cmd, oc_env): """Keep OpenClaw's own chat channel off for a provider that shares its name (slack). The provider is for governed reads (the harness's diff --git a/charts/openshell-saw/files/installer/saw_admin.py b/charts/openshell-saw/files/installer/saw_admin.py index 0a5a986fb..3dbc9eb27 100644 --- a/charts/openshell-saw/files/installer/saw_admin.py +++ b/charts/openshell-saw/files/installer/saw_admin.py @@ -64,7 +64,7 @@ def issue(authority, client, *, subject, crypto=openssl, erase=erase_ca_key): try: crypto("req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes", "-keyout", ca_key, "-out", ca, "-days", "1", - "-subj", "/O=openshell/OU=SAW-apply/CN=saw-apply-ca", + "-subj", "/O=openshell/OU=SAW-apply/CN=saw-apply-ca-" + secrets.token_hex(8), "-addext", "basicConstraints=critical,CA:TRUE", "-addext", "keyUsage=critical,keyCertSign") crypto("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes", "-keyout", key, "-subj", subject, "-out", csr) diff --git a/charts/openshell-saw/files/installer/saw_core.py b/charts/openshell-saw/files/installer/saw_core.py index c74428747..5138cd96e 100644 --- a/charts/openshell-saw/files/installer/saw_core.py +++ b/charts/openshell-saw/files/installer/saw_core.py @@ -200,7 +200,7 @@ class Sandbox: # (the agent, and argv, can read these): those stay on providers. env: dict = field(default_factory=dict) # `inference:` -- how the agent reaches its model: {providerRef, protocol, - # baseUrl?, model, models?, timeoutSeconds?}. models maps optional native + # baseUrl?, model, models?, timeoutSeconds?, thinking?}. models maps optional native # provider names to additional chat model inputs. baseUrl/model/timeoutSeconds # is a literal or an input ({secretKeyRef: {name, key}, default?, # required?, title?}); inference_values is it resolved. The installer onboards the @@ -418,6 +418,10 @@ def validate_profile_document(doc, kind, where="profile"): raise InstallerError(f"{where}: inference.providerRef must be a string") if "protocol" in inference and not isinstance(inference["protocol"], str): raise InstallerError(f"{where}: inference.protocol must be a string") + inference = _thinking_off(inference) + if "thinking" in inference and inference["thinking"] not in THINKING_LEVELS: + raise InstallerError(f"{where}: inference.thinking must be one of " + + ", ".join(THINKING_LEVELS)) for field_name in ("model", "baseUrl", "timeoutSeconds"): kinds = (str, int) if field_name == "timeoutSeconds" else (str,) if field_name in inference: @@ -511,7 +515,7 @@ def parse_profiles(files, *, strict=False, document_check=None): harness_ref=dict(s.get("harnessRef") or {}), ui=dict(s.get("ui") or {}), env=s.get("env") if s.get("env") is not None else {}, - inference=s.get("inference") if s.get("inference") is not None else {}, + inference=_thinking_off(s.get("inference") if s.get("inference") is not None else {}), gpu_enabled=gpu_enabled, gpu_count=gpu_count)) profile.workspaces.append(ws) profiles.append(profile) @@ -721,7 +725,19 @@ def secret_ref_problems(src): return out -INFERENCE_KEYS = {"providerRef", "protocol", "baseUrl", "model", "models", "timeoutSeconds"} +def _thinking_off(inference): + """YAML reads an unquoted `thinking: off` as false; it means off.""" + if isinstance(inference, dict) and inference.get("thinking") is False: + return {**inference, "thinking": "off"} + return inference + + +INFERENCE_KEYS = {"providerRef", "protocol", "baseUrl", "model", "models", "timeoutSeconds", "thinking"} +# OpenClaw thinking levels a profile may make the model's default. A level +# other than off also marks the model as a reasoning model that accepts +# these efforts, which OpenClaw only assumes for its own known models. +THINKING_LEVELS = ("off", "minimal", "low", "medium", "high") +REASONING_EFFORTS = ["low", "medium", "high"] # A profile controls allowed credential destinations; the protocol controls @@ -948,6 +964,8 @@ def resolve_inference(ws, sb, read_value, validate_endpoint, forbidden=()): if timeout and (not str(timeout).isdigit() or int(timeout) < 0): raise InstallerError(f"{where}: inference timeoutSeconds must be a non-negative integer") out["timeoutSeconds"] = int(timeout) if timeout else 0 + if spec.get("thinking"): + out["thinking"] = spec["thinking"] if "models" in spec: out["models"] = {} for name, src in spec["models"].items(): @@ -1007,6 +1025,11 @@ def sandbox_inference_problems(sb, provider_types, declared_provider_types=None) for key in ("baseUrl", "model"): if key in spec: out += [f"inference {key} {p}" for p in input_problems(spec[key])] + if "thinking" in spec: + if spec["thinking"] not in THINKING_LEVELS: + out.append(f"inference thinking must be one of {', '.join(THINKING_LEVELS)}") + elif sb.type != "openclaw": + out.append("inference thinking is supported only for openclaw sandboxes") models = spec.get("models", {}) if not isinstance(models, dict): out.append("inference models must be a mapping of provider names to model inputs") @@ -1058,7 +1081,7 @@ def profiles_from_plan(data): 'SANDBOX_TYPES', 'BASE_URL_CONFIG_KEYS', 'InstallerError', 'Provider', 'Sandbox', 'Workspace', 'Profile', 'HarnessBundle', 'read_profile_files', '_yaml', 'parse_profiles', 'enabled_workspaces', 'validate_profiles', 'ENV_NAME_RE', 'CREDENTIAL_NAME_RE', 'ENV_VALUE_LIMIT', 'SANDBOX_ENV_KEYS', - 'INPUT_KEYS', 'secret_ref', 'secret_ref_problems', 'INFERENCE_KEYS', 'INFERENCE_PROTOCOLS', + 'INPUT_KEYS', 'secret_ref', 'secret_ref_problems', 'INFERENCE_KEYS', 'INFERENCE_PROTOCOLS', 'THINKING_LEVELS', 'REASONING_EFFORTS', 'PROVIDER_PROTOCOLS', 'check_env_value', 'sandbox_env_problems', 'input_problems', 'check_base_url', 'resolve_bom_input', 'resolve_inference', 'inference_protocol', 'sandbox_inference_problems', 'harness_from_plan', 'profiles_from_plan', 'validate_profile_document', 'apply_workspace_sequence', 'select_inference_provider', @@ -1113,13 +1136,33 @@ def tool_gate_identity(owner, subject, workspace, sandbox): "sandbox": sandbox, "workspace": workspace} -def tool_gate_bundle(here, identity, receipt_key=None): - """Build the identical policy, identity and OpenClaw extension for both runtimes.""" +def tool_gate_bundle(here, identity, receipt_key=None, harness_rules=()): + """Build the identical policy, identity and OpenClaw extension for both runtimes. + + `harness_rules` are the enrolled harness's own tool rules + (harness_tool_rules). They follow the base rules, so where both name a + tool the base rule decides, and the pinned policy hash covers them. + """ names = ("tool-actions.yaml", "tool-gate.mjs", "tool-gate-plugin.mjs") missing = [name for name in names if not (here / name).is_file()] if missing: raise InstallerError("tool gate files missing from the installer disk: " + ", ".join(missing)) policy = (here / "tool-actions.yaml").read_bytes() + if harness_rules: + lines = [b"", b" # From the enrolled harness bundle (its own MCP tools only)."] + for rule in harness_rules: + # Written into policy text, so check every field here as well as + # where the rules are built: only a __ rule with a + # harness action, in a charset the policy reads verbatim. + if (not isinstance(rule, dict) or set(rule) != {"id", "tool", "action"} + or not all(isinstance(v, str) for v in rule.values()) + or not HARNESS_RULE_ID_RE.fullmatch(rule["id"]) + or not HARNESS_TOOL_RE.fullmatch(rule["tool"]) + or rule["action"] not in HARNESS_TOOL_ACTIONS): + raise InstallerError(f"invalid harness tool rule {rule!r}") + lines += [f" - id: {rule['id']}".encode(), f" tool: {rule['tool']}".encode(), + f" action: {rule['action']}".encode()] + policy = policy.rstrip(b"\n") + b"\n".join(lines) + b"\n" policy_hash = "sha256:" + hashlib.sha256(policy).hexdigest() plugin = (here / "tool-gate-plugin.mjs").read_bytes().replace( b"__SAW_POLICY_HASH__", policy_hash.encode()) @@ -1142,6 +1185,20 @@ def tool_gate_bundle(here, identity, receipt_key=None): # Inline harness parsing and OpenClaw registration are shared by both installers. HARNESS_MOUNT = "/sandbox/harness" +# A bundle can allow its own MCP tools or ask for approval; refusing is the +# default, and the site's tool-actions.yaml can still deny or require approval. +HARNESS_TOOL_ACTIONS = ("allow", "approval") +# A harness rule names only __ of its own MCP servers; both +# parts are letters, digits, '_' or '-' (MCP_SERVER_NAME_RE), never a +# newline or YAML syntax, and never a bare tool such as exec. +HARNESS_PART = r"[A-Za-z0-9_-]{1,64}" +HARNESS_TOOL_RE = re.compile(rf"{HARNESS_PART}__{HARNESS_PART}") +HARNESS_RULE_ID_RE = re.compile(rf"harness-{HARNESS_PART}-{HARNESS_PART}") + + +def harness_tool_rules(info): + """The tool-gate rules a described harness declares for its own MCP tools.""" + return list(info.get("toolRules", [])) # mcp.json env/header value: exactly ${VAR}, or Authorization-style @@ -1286,6 +1343,33 @@ def describe_harness_tree(files, inline=False, *, warn=lambda _: None): "governanceProfile in harness.yaml spec.mcpServers") governance.append({"kind": "MCP server", "name": server, "governanceProfile": profile, "hosts": [host]}) + tool_rules = [] + for server, decl in sorted(declared.items()): + tools = decl.get("tools") + if tools is None: + continue + if not isinstance(server, str) or not re.fullmatch(HARNESS_PART, server): + raise InstallerError( + f"harness '{name}': mcp server name {server!r} must be 1-64 letters, digits, " + "'_' or '-' to declare tool actions") + if server not in mcp_server_names: + raise InstallerError( + f"harness '{name}': tools are declared for '{server}', which mcp.json does not " + "define; a bundle may only set actions for its own MCP servers' tools") + if not isinstance(tools, list): + raise InstallerError(f"harness '{name}': mcp server '{server}' tools must be a list") + for item in tools: + if (not isinstance(item, dict) or set(item) != {"name", "action"} + or not isinstance(item["name"], str) + or not re.fullmatch(HARNESS_PART, item["name"]) + or item["action"] not in HARNESS_TOOL_ACTIONS): + raise InstallerError( + f"harness '{name}': mcp server '{server}' tools entries need exactly a name " + "(letters, digits, '_' or '-') and an action of allow or approval") + tool_rules.append({"id": f"harness-{server}-{item['name']}", + "tool": f"{server}__{item['name']}", "action": item["action"]}) + if len({r["id"] for r in tool_rules}) != len(tool_rules): + raise InstallerError(f"harness '{name}': a tool is declared twice") bundle_id = name if "plugin.json" in files: try: @@ -1303,6 +1387,7 @@ def describe_harness_tree(files, inline=False, *, warn=lambda _: None): "mcpConfigs": mcp_configs, "pluginDirs": plugin_dirs, "governance": governance, + "toolRules": tool_rules, } diff --git a/charts/openshell-saw/files/installer/tool-actions.yaml b/charts/openshell-saw/files/installer/tool-actions.yaml index 3becbac16..029dc993c 100644 --- a/charts/openshell-saw/files/installer/tool-actions.yaml +++ b/charts/openshell-saw/files/installer/tool-actions.yaml @@ -42,24 +42,53 @@ rules: - openclaw cron get - openclaw cron show - openclaw cron runs + - openclaw cron --help + - openclaw cron add --help + - openclaw cron create --help + - openclaw cron edit --help + - openclaw cron rm --help + - openclaw cron remove --help + - openclaw cron delete --help + - openclaw cron enable --help + - openclaw cron disable --help + - openclaw cron run --help - openclaw automations list - openclaw automations status - openclaw automations get - openclaw automations show - openclaw automations runs + - openclaw automations --help + - openclaw automations add --help + - openclaw automations create --help + - openclaw automations edit --help + - openclaw automations rm --help + - openclaw automations remove --help + - openclaw automations delete --help + - openclaw automations enable --help + - openclaw automations disable --help + - openclaw automations run --help + # "Allow always" skips the card for later automation changes until the + # gateway restarts; each call is still audited. - id: exec-openclaw-automation-change tool: exec action: approval + allowAlways: true whenCommandMatches: - openclaw cron add + - openclaw cron create - openclaw cron edit - openclaw cron rm + - openclaw cron remove + - openclaw cron delete - openclaw cron enable - openclaw cron disable - openclaw cron run - openclaw automations add + - openclaw automations create - openclaw automations edit - openclaw automations rm + - openclaw automations remove + - openclaw automations delete - openclaw automations enable - openclaw automations disable - openclaw automations run diff --git a/charts/openshell-saw/files/installer/tool-gate.mjs b/charts/openshell-saw/files/installer/tool-gate.mjs index 3429a31ee..22a029999 100644 --- a/charts/openshell-saw/files/installer/tool-gate.mjs +++ b/charts/openshell-saw/files/installer/tool-gate.mjs @@ -102,6 +102,12 @@ export function parsePolicy(text) { ids.add(rule.id); if (typeof rule.tool !== "string" || !rule.tool) throw new Error(`rule ${rule.id} needs a tool`); if (!ACTIONS.has(rule.action)) throw new Error(`rule ${rule.id} has an unknown action`); + if (rule.allowAlways !== undefined) { + if (rule.allowAlways !== "true" || rule.action !== "approval") { + throw new Error(`rule ${rule.id}: allowAlways must be true on an approval rule`); + } + rule.allowAlways = true; + } if (rule.whenCommandMatches !== undefined) { if (!Array.isArray(rule.whenCommandMatches) || rule.whenCommandMatches.length === 0) { throw new Error(`rule ${rule.id} has an empty whenCommandMatches`); @@ -147,6 +153,8 @@ export function commandText(params) { function normalizedExec(command) { if (!command.trim()) return { error: "exec-unreadable" }; + // A trailing 2>&1 only merges stderr into stdout; agents add it out of habit. + command = command.replace(/(?:[ \t]+2>&1)+[ \t]*$/, ""); if (/[;&|`\n\r<>]|\$\(|\$\{/.test(command)) return { error: "exec-opaque" }; const words = command.trim().split(/\s+/); const assignments = []; @@ -206,11 +214,43 @@ function baseRecord(input, extras) { }; } -function effectFor(action, tool, ruleId) { +// Said back to the agent with a denial so it can retry in an accepted form +// instead of guessing. +const EXEC_HINTS = { + "exec-unreadable": "Send the command as one plain string.", + "exec-opaque": "Run one command per exec call, with no ;, &&, |, backticks, $(...), " + + "redirects or shell wrappers such as sh -c (a trailing 2>&1 is fine). " + + "Each command is checked on its own.", +}; + +// For an unlisted exec command, the accepted commands that start with the +// same two words (such as `openclaw automations`), so the agent can use the +// right spelling instead of giving up or guessing. +function sameFamily(policy, command) { + const words = command.split(" ").slice(0, 2); + if (words.length < 2) return ""; + const prefix = `${words.join(" ")} `; + const found = { allow: [], approval: [] }; + for (const rule of policy.rules) { + if (rule.tool !== "exec" || !found[rule.action]) continue; + for (const needle of rule.whenCommandMatches || []) { + const normalized = needle.toLowerCase().replace(/\s+/g, " ").trim(); + const verb = normalized.startsWith(prefix) ? normalized.slice(prefix.length) : ""; + if (verb && !verb.includes(" ") && !found[rule.action].includes(verb)) found[rule.action].push(verb); + } + } + const parts = []; + if (found.allow.length) parts.push(`${found.allow.join(", ")} (run directly)`); + if (found.approval.length) parts.push(`${found.approval.join(", ")} (ask the user for approval)`); + return parts.length ? `. Accepted \`${words.join(" ")}\` commands: ${parts.join("; ")}` : ""; +} + +function effectFor(action, tool, ruleId, allowAlways = false, hint = "") { if (action === "allow") return { kind: "allow" }; if (action === "deny") { const why = ruleId === "default" - ? `Tool ${tool} is denied by the default action` + ? `Tool ${tool} is denied by the default action${tool === "exec" + ? `: this command is not on the allowed list, so do not retry it in another form${hint}` : ""}` : `Tool ${tool} is denied by rule ${ruleId}`; return { kind: "deny", blockReason: why }; } @@ -221,7 +261,7 @@ function effectFor(action, tool, ruleId) { description: `Tool ${tool} matches ${ruleId} and needs approval before it runs.`, severity: "warning", timeoutMs: 120000, - allowedDecisions: ["allow-once", "deny"], + allowedDecisions: allowAlways ? ["allow-once", "allow-always", "deny"] : ["allow-once", "deny"], }, }; } @@ -280,14 +320,27 @@ export function decide(input) { const task = { id: session, title }; const rawCommand = commandText(input.params); const exec = tool === "exec" ? normalizedExec(rawCommand) : null; - if (exec?.error) return blocked(input, exec.error, `Tool call blocked: ${exec.error}`, task); + if (exec?.error) return blocked(input, exec.error, `Tool call blocked: ${exec.error}. ${EXEC_HINTS[exec.error]}`, task); const command = exec ? exec.command : rawCommand; const rule = policy.rules.find((item) => ruleMatches(item, tool, command)); const action = rule ? rule.action : policy.defaultAction; const ruleId = rule ? rule.id : "default"; + // "Allow always" on an allowAlways rule lets later matching calls run + // without asking while this gateway runs. Keyed by the policy hash, so a + // policy change asks again. Every call is still audited. + const rememberKey = rule && rule.allowAlways ? `${policyHash}:${ruleId}` : null; + if (rememberKey && input.remembered && input.remembered.has(rememberKey)) { + return { + record: { ...baseRecord(input, { task, rule: ruleId, policyHash, decision: "allow" }), + approval: { mode: "remembered", resolution: "allow-always" } }, + effect: { kind: "allow" }, + }; + } return { record: baseRecord(input, { task, rule: ruleId, policyHash, decision: decisionName(action) }), - effect: effectFor(action, tool, ruleId), + effect: effectFor(action, tool, ruleId, Boolean(rememberKey), + exec && !rule ? sameFamily(policy, command) : ""), + rememberKey, }; } @@ -354,9 +407,13 @@ export function parseIdentity(text) { } } +// Rules the signed-in user answered "Allow always" for, for this gateway process. +const REMEMBERED = new Set(); + // The before_tool_call hook without the OpenClaw import. A thrown audit write // blocks the call. onResolution appends a second line and does not execute. export function evaluateToolCall(input) { + const remembered = input.remembered || REMEMBERED; const identity = input.identityText !== undefined ? parseIdentity(input.identityText) : input.identity; const decided = decide({ policyText: input.policyText, @@ -368,6 +425,7 @@ export function evaluateToolCall(input) { sessionKey: input.sessionKey, sessionId: input.sessionId, now: input.now, + remembered, }); const append = input.appendRecord || (input.auditFile && (record => appendAudit(input.auditFile, record))); if (append) { @@ -383,9 +441,16 @@ export function evaluateToolCall(input) { } } const hook = hookResult(decided, (resolution) => { - if (!append) return; + const remember = () => { + if (resolution === "allow-always" && decided.rememberKey) remembered.add(decided.rememberKey); + }; + if (!append) { + remember(); + return; + } try { append(resolutionRecord(decided.record, resolution)); + remember(); } catch { const record = { ...resolutionRecord(decided.record, resolution), auditWriteFailed: true }; process.stderr.write(`${JSON.stringify(record)}\n`); diff --git a/charts/openshell-saw/files/installer/tool-gate.test.mjs b/charts/openshell-saw/files/installer/tool-gate.test.mjs index 1721d8e49..fec32941b 100644 --- a/charts/openshell-saw/files/installer/tool-gate.test.mjs +++ b/charts/openshell-saw/files/installer/tool-gate.test.mjs @@ -159,12 +159,12 @@ test("identity configuration always requires approval, including file and avatar test("both automation aliases allow only inspection and hold mutations for approval", () => { for (const group of ["cron", "automations"]) { - for (const verb of ["list", "status", "get", "show", "runs"]) { + for (const verb of ["list", "status", "get", "show", "runs", "--help", "edit --help", "rm --help"]) { const result = call({ params: { command: `openclaw ${group} ${verb} --json` } }); assert.equal(result.effect.kind, "allow"); assert.equal(result.record.rule, "exec-openclaw-automation-inspect"); } - for (const verb of ["add", "edit", "rm", "enable", "disable", "run"]) { + for (const verb of ["add", "create", "edit", "rm", "remove", "delete", "enable", "disable", "run"]) { const result = call({ params: { command: `openclaw ${group} ${verb} job-id` } }); assert.equal(result.effect.kind, "approval"); assert.equal(result.record.rule, "exec-openclaw-automation-change"); @@ -175,7 +175,7 @@ test("both automation aliases allow only inspection and hold mutations for appro } } // Unsupported aliases, mixed read/write surfaces and unknown verbs stay denied. - for (const verb of ["", "create", "remove", "delete", "scratch", "listx", "runsx", "run-all"]) { + for (const verb of ["", "scratch", "bind", "listx", "runsx", "run-all", "removex"]) { assert.equal(call({ params: { command: `openclaw ${group} ${verb}` } }).effect.kind, "deny"); } for (const command of [ @@ -520,3 +520,80 @@ test("an unavailable audit file blocks an otherwise allowed call", () => { assert.equal(result.record.rule, "audit-unwritable"); assert.equal(result.hook.block, true); }); + +test("allow always skips later automation approvals but never other rules", () => { + const remembered = new Set(); + const records = []; + const run = (command) => evaluateToolCall({ + policyText, identity, toolName: "exec", params: { command }, sessionKey: "session-1", + appendRecord: (record) => records.push(record), remembered, + }); + const first = run("openclaw cron rm job-1"); + assert.deepEqual(first.hook.requireApproval.allowedDecisions, ["allow-once", "allow-always", "deny"]); + // Allow once remembers nothing. + first.hook.requireApproval.onResolution("allow-once"); + assert.ok(run("openclaw cron edit job-1").hook.requireApproval); + run("openclaw cron add --name x").hook.requireApproval.onResolution("allow-always"); + // Later automation changes run, in any session, and are still audited. + for (const command of ["openclaw cron rm job-1", "openclaw automations edit job-2"]) { + records.length = 0; + assert.equal(run(command).hook, undefined); + assert.equal(records[0].decision, "allow"); + assert.equal(records[0].rule, "exec-openclaw-automation-change"); + assert.deepEqual(records[0].approval, { mode: "remembered", resolution: "allow-always" }); + } + // Other approval rules still ask, and offer no allow always. + const push = run("git push"); + assert.deepEqual(push.hook.requireApproval.allowedDecisions, ["allow-once", "deny"]); + push.hook.requireApproval.onResolution("allow-always"); + assert.ok(run("git push").hook.requireApproval); + // Unmatched commands are still denied. + assert.equal(run("openclaw cron update job-1").hook.block, true); +}); + +test("allow always is forgotten when the policy changes or the answer is not recorded", () => { + const remembered = new Set(); + const changed = policyText.replace("defaultAction: deny", "defaultAction: deny\n# changed"); + const run = (text, append) => evaluateToolCall({ + policyText: text, identity, toolName: "exec", params: { command: "openclaw cron rm job-1" }, + sessionKey: "session-1", appendRecord: append, remembered, + }); + run(policyText, () => {}).hook.requireApproval.onResolution("allow-always"); + assert.equal(run(policyText, () => {}).hook, undefined); + assert.ok(run(changed, () => {}).hook.requireApproval); + const unrecorded = new Set(); + const failing = evaluateToolCall({ + policyText, identity, toolName: "exec", params: { command: "openclaw cron rm job-1" }, + sessionKey: "session-1", remembered: unrecorded, + appendRecord: (record) => { if (record.approval) throw new Error("down"); }, + }); + failing.hook.requireApproval.onResolution("allow-always"); + assert.equal(unrecorded.size, 0); +}); + +test("allowAlways is only valid as true on an approval rule", () => { + const rule = (action, value) => `version: 1\ndefaultAction: deny\nrules:\n - id: r\n tool: exec\n action: ${action}\n allowAlways: ${value}\n`; + assert.equal(parsePolicy(rule("approval", "true")).rules[0].allowAlways, true); + assert.throws(() => parsePolicy(rule("allow", "true")), /allowAlways/); + assert.throws(() => parsePolicy(rule("approval", "yes")), /allowAlways/); +}); + +test("a trailing 2>&1 is accepted, and blocked exec calls say how to retry", () => { + for (const command of ["openclaw automations list --all 2>&1", "git status 2>&1 2>&1", "git status\t2>&1 "]) { + assert.equal(call({ params: { command } }).effect.kind, "allow", command); + } + // Only a trailing stderr merge: any other redirect or chain is still opaque. + for (const command of ["git status 2>&1 | head", "git status > /tmp/x 2>&1", "git status 2>&1; rm -rf /", + "git status 2>/tmp/x", "git status 2>&1\nrm -rf /", "git status &>/tmp/x"]) { + assert.equal(call({ params: { command } }).record.rule, "exec-opaque", command); + } + const opaque = call({ params: { command: "openclaw automations show a; openclaw automations show b" } }); + assert.match(opaque.effect.blockReason, /exec-opaque\. Run one command per exec call/); + const unlisted = call({ params: { command: "openclaw automations scratch" } }); + assert.match(unlisted.effect.blockReason, /not on the allowed list/); + // A wrong spelling learns the accepted ones for the same command family. + const remove = call({ params: { command: "openclaw automations update 69f1c7c1" } }).effect.blockReason; + assert.match(remove, /Accepted `openclaw automations` commands: list, status, get, show, runs, --help \(run directly\); add, create, edit, rm, remove, delete, enable, disable, run \(ask the user for approval\)$/); + assert.doesNotMatch(call({ params: { command: "curl https://x" } }).effect.blockReason, /Accepted/); + assert.match(call({ toolName: "web_fetch", params: {} }).effect.blockReason, /^Tool web_fetch is denied by the default action$/); +}); diff --git a/charts/openshell-saw/values.yaml b/charts/openshell-saw/values.yaml index 63aa6d87e..c02876cfe 100644 --- a/charts/openshell-saw/values.yaml +++ b/charts/openshell-saw/values.yaml @@ -106,27 +106,27 @@ bom: apiVersion: saw.redhat.com/v1alpha1 kind: InstallerBOM metadata: - name: openshell-0-1-6-rhaiv-4 + name: openshell-0-1-10-rhaiv-0 spec: installerVersion: 0.1.0 # OpenShell 0.1.x. Moving from 0.0.x recreates the gateway state and # every sandbox (the installer does it; see docs/versioned-bom-installer.md). openshell: cli: - version: 0.1.6-rhaiv.4 - image: quay.io/opendatahub/odh-openshell-cli@sha256:9128f07cbb29b87472a71e09a4b164ec35ea0484712cc31028209f8d1e5291c4 + version: 0.1.10-rhaiv.0 + image: quay.io/opendatahub/odh-openshell-cli@sha256:439f6ea6acc93e4d3539125b15ca93d23e20740d2ab7150eef56bf7842c8a6c4 gateway: - version: 0.1.6-rhaiv.4 - image: quay.io/opendatahub/odh-openshell-gateway@sha256:bd2d7c9084b80b8d3d8ef92d00a27b963b35168fad84cd862b7f91fd9c488c3e + version: 0.1.10-rhaiv.0 + image: quay.io/opendatahub/odh-openshell-gateway@sha256:e4b89770ef55238cc45d9880614eda64b8ab9a76be5e6c81c63a350889eb0717 supervisor: - version: 0.1.6-rhaiv.4 - image: quay.io/opendatahub/odh-openshell-supervisor@sha256:626b91a0f53393dac0d591c142b81100916aa66b4e65444b5527672b5533fe86 + version: 0.1.10-rhaiv.0 + image: quay.io/opendatahub/odh-openshell-supervisor@sha256:c2c8e9d3d19a1612074df0f637078064cff45b92d35c74b116a72fb503b3c1bc # Sandbox runtime image: the podman driver mounts the supervisor from it # into every sandbox (gateway.toml sandbox_runtime_image). Pulled, not # extracted. sandbox: - version: 0.1.6-rhaiv.4 - image: quay.io/opendatahub/odh-openshell-sandbox@sha256:0cde11346e68485907c22d3c9b30802e52cf16e3853720a864ac8347bb68f6ef + version: 0.1.10-rhaiv.0 + image: quay.io/opendatahub/odh-openshell-sandbox@sha256:365d321345ea142a10d442f91bebeaf6d67dac4384b6dc29b4e72ada01a9b959 # NemoClaw CLI, needed by `type: nemoclaw` sandboxes (the default # data-science profile has one). Remove it if no profile needs it. # A tag is accepted here with a warning; pin a digest when one exists. diff --git a/charts/saw-audit-writer/templates/writer.yaml b/charts/saw-audit-writer/templates/writer.yaml index 72d72e35e..ae047843e 100644 --- a/charts/saw-audit-writer/templates/writer.yaml +++ b/charts/saw-audit-writer/templates/writer.yaml @@ -1,19 +1,27 @@ {{- if .Values.enabled }} -{{- $tn := required "trustedNamespace required" .Values.trustedNamespace }} +{{- $receipts := .Values.receipts }} {{- $rn := required "runtimeNamespace required" .Values.runtimeNamespace }} +{{- $tn := "" }} +{{- if $receipts }} +{{- $tn = required "trustedNamespace required" .Values.trustedNamespace }} {{- if eq $tn $rn }}{{ fail "writer history requires a separate trusted namespace" }}{{ end }} +{{- end }} {{- $image := required "pinned Node 24 image required" .Values.image }} {{- if not (regexMatch "@sha256:[0-9a-f]{64}$" $image) }}{{ fail "image must be digest pinned" }}{{ end }} {{- $id := .Values.identity }} {{- range $f := list "subject" "username" "workspace" "sandbox" }}{{- $_ := required $f (get $id $f) }}{{- end }} {{- $base := .Release.Name }} -{{- range $name, $ns := dict "history" $tn "exchange" $rn "gate" $rn "workspace" $rn }} +{{- /* Without receipts the sandbox keeps a best-effort local audit log on its + own ReadWriteOnce volume: no history, exchange, forwarder or writer. */}} +{{- $claims := dict "audit" $rn "gate" $rn "workspace" $rn }} +{{- if $receipts }}{{- $claims = dict "history" $tn "exchange" $rn "gate" $rn "workspace" $rn }}{{- end }} +{{- range $name, $ns := $claims }} --- apiVersion: v1 kind: PersistentVolumeClaim metadata: namespace: {{ $ns }} - name: {{ if eq $name "exchange" }}saw-audit-{{ $base }}{{ else if eq $name "gate" }}saw-gate-{{ $base }}{{ else if eq $name "workspace" }}workspace-{{ $base }}{{ else }}{{ $base }}-{{ $name }}{{ end }} + name: {{ if or (eq $name "exchange") (eq $name "audit") }}saw-audit-{{ $base }}{{ else if eq $name "gate" }}saw-gate-{{ $base }}{{ else if eq $name "workspace" }}workspace-{{ $base }}{{ else }}{{ $base }}-{{ $name }}{{ end }} annotations: {argocd.argoproj.io/sync-options: 'Prune=false,Delete=false'} {{- if ne $name "history" }} labels: @@ -22,10 +30,15 @@ metadata: saw.redhat.com/runtime-owner: {{ $.Values.ownerID }} {{- end }} spec: - storageClassName: {{ if or (eq $name "exchange") (and (eq $name "gate") $.Values.shareGateForModelSelection) }}{{ required "exchangeStorageClass required" $.Values.exchangeStorageClass }}{{ else }}{{ required "storageClass required" $.Values.storageClass }}{{ end }} + {{- if or (eq $name "exchange") (and (eq $name "gate") $.Values.shareGateForModelSelection) }} + storageClassName: {{ required "exchangeStorageClass required" $.Values.exchangeStorageClass }} + {{- else if $.Values.storageClass }} + storageClassName: {{ $.Values.storageClass }} + {{- end }} accessModes: [{{ if or (eq $name "exchange") (and (eq $name "gate") $.Values.shareGateForModelSelection) }}ReadWriteMany{{ else }}ReadWriteOnce{{ end }}] resources: {requests: {storage: 1Gi}} {{- end }} +{{- if $receipts }} --- apiVersion: v1 kind: Service @@ -128,3 +141,4 @@ spec: {{- end }} {{- end }} {{- end }} +{{- end }} diff --git a/charts/saw-audit-writer/values.yaml b/charts/saw-audit-writer/values.yaml index 57ae10487..0cdcb29ee 100644 --- a/charts/saw-audit-writer/values.yaml +++ b/charts/saw-audit-writer/values.yaml @@ -1,4 +1,9 @@ enabled: false +# Signed, fail-closed audit receipts: a writer in trustedNamespace keeps the +# history, and the sandbox reaches it through a shared (ReadWriteMany) +# exchange volume. false keeps only a best-effort audit log on the sandbox's +# own volume. +receipts: true trustedNamespace: "" runtimeNamespace: "" image: "" diff --git a/charts/saw-kata/Chart.yaml b/charts/saw-kata/Chart.yaml new file mode 100644 index 000000000..52efbbfe9 --- /dev/null +++ b/charts/saw-kata/Chart.yaml @@ -0,0 +1,6 @@ +apiVersion: v2 +name: saw-kata +description: KataConfig for Kata container workspaces (OpenShift sandboxed containers) +type: application +version: 0.1.0 +appVersion: "0.1.0" diff --git a/charts/saw-kata/templates/kataconfig.yaml b/charts/saw-kata/templates/kataconfig.yaml new file mode 100644 index 000000000..36b44f925 --- /dev/null +++ b/charts/saw-kata/templates/kataconfig.yaml @@ -0,0 +1,31 @@ +{{- if .Values.enabled }} +{{- if not .Values.poolSelector }}{{ fail "poolSelector is required: an empty selector installs Kata on every worker" }}{{ end }} +# Installs the local Kata runtime (OSC creates the kata RuntimeClass). Nodes +# reboot while their machine config pool updates. +apiVersion: kataconfiguration.openshift.io/v1 +kind: KataConfig +metadata: + name: {{ .Values.name }} + annotations: + argocd.argoproj.io/sync-options: SkipDryRunOnMissingResource=true +spec: + enablePeerPods: false + checkNodeEligibility: {{ .Values.checkNodeEligibility }} + kataConfigPoolSelector: {{ .Values.poolSelector | toJson }} +{{- end }} +{{- if .Values.enabled }} +{{- with .Values.runtimeClass }} +{{- if or (ne .handler "kata") (not .nodeSelector) }}{{ fail "runtimeClass needs the kata handler and a node selector for the Kata pool" }}{{ end }} +--- +apiVersion: node.k8s.io/v1 +kind: RuntimeClass +metadata: + name: {{ .name }} + labels: + openshell.ai/sandbox-attachable: "true" +handler: {{ .handler }} +overhead: {{ .overhead | toJson }} +scheduling: + nodeSelector: {{ .nodeSelector | toJson }} +{{- end }} +{{- end }} diff --git a/charts/saw-kata/values.yaml b/charts/saw-kata/values.yaml new file mode 100644 index 000000000..a581d85ba --- /dev/null +++ b/charts/saw-kata/values.yaml @@ -0,0 +1,28 @@ +# Creating a KataConfig installs the Kata runtime on the selected nodes, which +# reboots them one machine config pool at a time. Off by default: enable it on +# clusters that run Kata workspaces (docs/kata-workspaces.md). +enabled: false +name: saw-kata-pool +# The operator's node eligibility check needs Node Feature Discovery (the NFD +# operator and a NodeFeatureDiscovery) to label the nodes; without NFD the +# KataConfig never installs. Off: check KVM with make kata-worker-check instead. +checkNodeEligibility: false +# Plain workers only. On clusters whose control-plane nodes are also +# schedulable workers, this keeps the API servers out of the Kata pool. +poolSelector: + matchExpressions: + - {key: node-role.kubernetes.io/worker, operator: Exists} + - {key: node-role.kubernetes.io/control-plane, operator: DoesNotExist} + - {key: node-role.kubernetes.io/master, operator: DoesNotExist} +# The RuntimeClass Kata workspaces use. It copies the operator's own "kata" +# class (handler, pod overhead, the kata-oc pool's node selector) and carries +# the label OpenShell requires before a sandbox may use a class, so no one has +# to label the operator-owned class by hand. saw-users binds Kata users to it +# by name (kata.runtimeClassName). +runtimeClass: + name: saw-kata + handler: kata + overhead: + podFixed: {cpu: 250m, memory: 350Mi} + nodeSelector: + node-role.kubernetes.io/kata-oc: "" diff --git a/charts/saw-kubernetes-controller/templates/controller.yaml b/charts/saw-kubernetes-controller/templates/controller.yaml index 029a0b1ab..a62239500 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]} @@ -107,7 +109,7 @@ spec: selector: {matchLabels: {app.kubernetes.io/instance: {{ $g }}, openshell.pattern/role: reconciler}} template: metadata: - labels: {app.kubernetes.io/instance: {{ $g }}, openshell.pattern/role: reconciler} + labels: {app.kubernetes.io/instance: {{ $g }}, openshell.pattern/role: reconciler, saw.redhat.com/kubernetes-api: allow} annotations: {checksum/config: {{ $c | toJson | sha256sum | quote }}} spec: serviceAccountName: {{ $name }} diff --git a/charts/saw-kubernetes-identity/templates/bootstrap.yaml b/charts/saw-kubernetes-identity/templates/bootstrap.yaml index f0edf2925..25c78e833 100644 --- a/charts/saw-kubernetes-identity/templates/bootstrap.yaml +++ b/charts/saw-kubernetes-identity/templates/bootstrap.yaml @@ -111,6 +111,7 @@ spec: metadata: labels: openshell.pattern/role: identity-bootstrap + saw.redhat.com/kubernetes-api: allow spec: restartPolicy: Never serviceAccountName: {{ $name }} 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-identity/values.yaml b/charts/saw-kubernetes-identity/values.yaml index 5d9822b0c..9011a823e 100644 --- a/charts/saw-kubernetes-identity/values.yaml +++ b/charts/saw-kubernetes-identity/values.yaml @@ -4,5 +4,5 @@ ownerID: "" targetNamespace: "" gateway: "" serverSans: [] -gatewayImage: quay.io/opendatahub/odh-openshell-gateway@sha256:bd2d7c9084b80b8d3d8ef92d00a27b963b35168fad84cd862b7f91fd9c488c3e +gatewayImage: quay.io/opendatahub/odh-openshell-gateway@sha256:e4b89770ef55238cc45d9880614eda64b8ab9a76be5e6c81c63a350889eb0717 helperImage: registry.access.redhat.com/ubi9/python-311@sha256:a0bdb55576fc5b8d6704279307817828ef027e1065533ceba133fe9516003a6c diff --git a/charts/saw-kubernetes-proxy/Chart.yaml b/charts/saw-kubernetes-proxy/Chart.yaml deleted file mode 100644 index cee97f759..000000000 --- a/charts/saw-kubernetes-proxy/Chart.yaml +++ /dev/null @@ -1,5 +0,0 @@ -apiVersion: v2 -name: saw-kubernetes-proxy -description: Existing SAW credential proxy in a separate trusted namespace -type: application -version: 0.1.0 diff --git a/charts/saw-kubernetes-proxy/files/project_ca.py b/charts/saw-kubernetes-proxy/files/project_ca.py deleted file mode 100644 index 814e982b0..000000000 --- a/charts/saw-kubernetes-proxy/files/project_ca.py +++ /dev/null @@ -1,145 +0,0 @@ -"""Project only the stock proxy's public CA; refuse replacement or adoption. - -The preceding init container runs the unchanged SAW proxy init-ca command. -This helper never reads a Secret, returns credential data or rotates trust. -""" -import json -from pathlib import Path -import re -import ssl -import sys -from urllib.error import HTTPError, URLError -from urllib.request import Request, HTTPSHandler, HTTPRedirectHandler, build_opener -import uuid - -OWNER = "saw.redhat.com/runtime-owner" -KEEP = "Prune=false,Delete=false" -NAME = re.compile(r"[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\Z") -LIMIT = 128 * 1024 - - -class Failure(Exception): - pass - - -class NoRedirect(HTTPRedirectHandler): - def redirect_request(self, req, fp, code, msg, headers, newurl): - return None - - -class Api: - def __init__(self): - root = Path('/var/run/secrets/kubernetes.io/serviceaccount') - self.token = root / 'token' - self.opener = build_opener(NoRedirect(), HTTPSHandler( - context=ssl.create_default_context(cafile=str(root / 'ca.crt')))) - - def call(self, method, path, body=None): - try: - token = self.token.read_text().strip() - if not token or any(c.isspace() for c in token): - raise ValueError() - data = None if body is None else json.dumps(body).encode() - request = Request('https://kubernetes.default.svc' + path, data=data, - headers={'Authorization': 'Bearer ' + token, - 'Content-Type': 'application/json'}, method=method) - with self.opener.open(request, timeout=20) as response: - raw = response.read(LIMIT + 1) - if len(raw) > LIMIT: - raise ValueError() - result = json.loads(raw) - if not isinstance(result, dict): - raise ValueError() - return result - except HTTPError as exc: - status = exc.code - exc.close() - if (method == 'GET' and status == 404) or (method == 'POST' and status == 409): - return None - raise Failure(f'projection API failed ({status})') from None - except (OSError, ValueError, URLError): - raise Failure('projection API unavailable') from None - - -def validate(config): - if not isinstance(config, dict) or set(config) != {'ownerID', 'namespace', 'targetNamespace', 'name'}: - raise Failure('invalid projection fields') - for key in ('namespace', 'targetNamespace', 'name'): - name = config[key] - if (not isinstance(name, str) or len(name) > 63 or not NAME.fullmatch(name) - or name == 'default' or name.startswith(('openshift', 'kube-'))): - raise Failure('dedicated projection names required') - if config['namespace'] == config['targetNamespace']: - raise Failure('proxy and runtime namespaces must differ') - try: - identity = uuid.UUID(config['ownerID']) - if str(identity) != config['ownerID'] or identity.int == 0: - raise ValueError() - except (ValueError, TypeError, AttributeError): - raise Failure('canonical nonzero installation UUID required') from None - - -def mapping(value): - if not isinstance(value, dict): - raise Failure('invalid projection object') - return value - - -def metadata(obj): - meta = mapping(mapping(obj or {}).get('metadata', {})) - mapping(meta.get('labels', {})) - mapping(meta.get('annotations', {})) - return meta - - -def project(api, config): - validate(config) - owner = config['ownerID'] - for namespace in (config['namespace'], config['targetNamespace']): - obj = api.call('GET', '/api/v1/namespaces/' + namespace) - meta = metadata(obj) - if (meta.get('name') != namespace or meta.get('deletionTimestamp') - or meta.get('labels', {}).get(OWNER) != owner): - raise Failure('namespace ownership mismatch') - name = config['name'] - source = api.call('GET', f"/api/v1/namespaces/{config['namespace']}/configmaps/{name}") - meta = metadata(source) - data = mapping((source or {}).get('data', {})) - if (meta.get('name') != name or meta.get('namespace') != config['namespace'] - or meta.get('deletionTimestamp') or set(data) != {'ca.crt'} - or (source or {}).get('binaryData')): - raise Failure('invalid public CA source') - cert = data['ca.crt'] - if (not isinstance(cert, str) or len(cert) > 32768 or 'PRIVATE KEY' in cert - or not re.fullmatch(r'-----BEGIN CERTIFICATE-----\s+[A-Za-z0-9+/=\s]+-----END CERTIFICATE-----\s*', cert)): - raise Failure('public certificate only') - try: - ssl.create_default_context().load_verify_locations(cadata=cert) - except (ValueError, ssl.SSLError): - raise Failure('invalid public certificate') from None - base = f"/api/v1/namespaces/{config['targetNamespace']}/configmaps" - existing = api.call('GET', base + '/' + name) - if existing is None: - api.call('POST', base, {'apiVersion': 'v1', 'kind': 'ConfigMap', - 'metadata': {'name': name, 'namespace': config['targetNamespace'], - 'labels': {OWNER: owner}, - 'annotations': {'argocd.argoproj.io/sync-options': KEEP}}, - 'immutable': True, 'data': {'ca.crt': cert}}) - existing = api.call('GET', base + '/' + name) - meta = metadata(existing) - if (meta.get('name') != name or meta.get('namespace') != config['targetNamespace'] - or meta.get('deletionTimestamp') or meta.get('ownerReferences') - or meta.get('labels', {}).get(OWNER) != owner - or meta.get('annotations', {}).get('argocd.argoproj.io/sync-options') != KEEP - or (existing or {}).get('immutable') is not True - or (existing or {}).get('binaryData') or (existing or {}).get('data') != {'ca.crt': cert}): - raise Failure('public projection differs; explicit trust recovery required') - - -if __name__ == '__main__': - try: - project(Api(), json.loads(Path('/config/config.json').read_text())) - print('Public proxy CA projection verified') - except (Failure, OSError, ValueError) as exc: - print(str(exc) if isinstance(exc, Failure) else 'projection configuration unavailable', file=sys.stderr) - sys.exit(1) diff --git a/charts/saw-kubernetes-proxy/templates/proxy.yaml b/charts/saw-kubernetes-proxy/templates/proxy.yaml deleted file mode 100644 index ac074fa66..000000000 --- a/charts/saw-kubernetes-proxy/templates/proxy.yaml +++ /dev/null @@ -1,226 +0,0 @@ -{{- if .Values.enabled }} -{{- $v := .Values -}} -{{- range $name := list .Release.Namespace $v.targetNamespace $v.gateway }} -{{- if or (gt (len $name) 40) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $name)) (eq $name "default") (hasPrefix "openshift" $name) (hasPrefix "kube-" $name) }}{{- fail "dedicated DNS-label names of at most 40 characters required" }}{{- end }}{{- end }} -{{- if eq .Release.Namespace $v.targetNamespace }}{{- fail "trusted and runtime namespaces must differ" }}{{- end }} -{{- if or (eq $v.ownerID "00000000-0000-0000-0000-000000000000") (not (regexMatch "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" $v.ownerID)) }}{{- fail "installation UUID required" }}{{- end }} -{{- range $image := list $v.image $v.helperImage }}{{- if not (regexMatch "^.+@sha256:[0-9a-f]{64}$" $image) }}{{- fail "digest-pinned images required" }}{{- end }}{{- end }} -{{- if or (not $v.policyConfigMap) (not $v.credentialSecretNames) (not $v.network.bootstrapEgress) (not $v.network.proxyEgress) }}{{- fail "existing policy, credential references and explicit egress required" }}{{- end }} -{{- range $name := append (deepCopy $v.credentialSecretNames) $v.policyConfigMap }}{{- if or (gt (len $name) 63) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $name)) }}{{- fail "policy and credential references must be DNS labels" }}{{- end }}{{- end }} -{{- if ne (len (uniq $v.credentialSecretNames)) (len $v.credentialSecretNames) }}{{- fail "duplicate credential reference" }}{{- end }} -{{- if not (regexMatch "^[0-9a-f]{64}$" $v.policyDigest) }}{{- fail "SHA256 of policy config.json required for explicit rollout" }}{{- end }} -{{- $name := printf "%s-credential-proxy" $v.gateway }} -{{- $job := printf "%s-proxy-bootstrap" $v.gateway }} -{{- $ca := printf "%s-proxy-ca" $v.gateway }} -apiVersion: v1 -kind: ConfigMap -metadata: - name: {{ $job }} - annotations: {argocd.argoproj.io/sync-wave: "-20"} -data: - config.json: {{ dict "ownerID" $v.ownerID "namespace" .Release.Namespace "targetNamespace" $v.targetNamespace "name" $ca | toJson | quote }} - project_ca.py: | -{{ .Files.Get "files/project_ca.py" | indent 4 }} ---- -apiVersion: v1 -kind: ServiceAccount -metadata: - name: {{ $job }} - annotations: {argocd.argoproj.io/sync-wave: "-20"} -automountServiceAccountToken: false -{{- range $ns := list .Release.Namespace $v.targetNamespace }} ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: - name: {{ $job }} - namespace: {{ $ns }} - annotations: {argocd.argoproj.io/sync-wave: "-20"} -rules: - - apiGroups: [""] - resources: [configmaps] - verbs: [create] - - apiGroups: [""] - resources: [configmaps] - resourceNames: [{{ $ca }}] - verbs: [get{{ if eq $ns $.Release.Namespace }}, update{{ end }}] -{{- if eq $ns $.Release.Namespace }} - - apiGroups: [""] - resources: [secrets] - verbs: [create] - - apiGroups: [""] - resources: [secrets] - resourceNames: [{{ $ca }}] - verbs: [get] -{{- end }} ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - name: {{ $job }} - namespace: {{ $ns }} - annotations: {argocd.argoproj.io/sync-wave: "-20"} -roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: {{ $job }}} -subjects: - - {kind: ServiceAccount, name: {{ $job }}, namespace: {{ $.Release.Namespace }}} -{{- end }} ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - name: {{ .Release.Namespace }}-{{ $job }} - annotations: {argocd.argoproj.io/sync-wave: "-20"} -rules: - - apiGroups: [""] - resources: [namespaces] - resourceNames: [{{ .Release.Namespace }}, {{ $v.targetNamespace }}] - verbs: [get] ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - name: {{ .Release.Namespace }}-{{ $job }} - annotations: {argocd.argoproj.io/sync-wave: "-20"} -roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: {{ .Release.Namespace }}-{{ $job }}} -subjects: - - {kind: ServiceAccount, name: {{ $job }}, namespace: {{ .Release.Namespace }}} ---- -apiVersion: networking.k8s.io/v1 -kind: NetworkPolicy -metadata: - name: {{ $job }} - annotations: {argocd.argoproj.io/sync-wave: "-20"} -spec: - podSelector: - matchLabels: {app.kubernetes.io/instance: {{ $v.gateway }}, openshell.pattern/role: proxy-bootstrap} - policyTypes: [Ingress, Egress] - ingress: [] - egress: -{{ toYaml $v.network.bootstrapEgress | indent 4 }} ---- -apiVersion: batch/v1 -kind: Job -metadata: - name: {{ $job }} - annotations: - argocd.argoproj.io/hook: Sync - argocd.argoproj.io/hook-delete-policy: BeforeHookCreation,HookSucceeded - argocd.argoproj.io/sync-wave: "-10" -spec: - backoffLimit: 2 - activeDeadlineSeconds: 300 - template: - metadata: - labels: {app.kubernetes.io/instance: {{ $v.gateway }}, openshell.pattern/role: proxy-bootstrap} - spec: - serviceAccountName: {{ $job }} - automountServiceAccountToken: false - restartPolicy: Never - securityContext: {runAsNonRoot: true, seccompProfile: {type: RuntimeDefault}} - initContainers: - - name: stock-ca - image: {{ $v.image }} - args: [init-ca] - env: - - {name: POD_NAMESPACE, value: {{ .Release.Namespace }}} - - {name: SAW_CA_SECRET_NAME, value: {{ $ca }}} - - {name: SAW_CA_CONFIGMAP_NAME, value: {{ $ca }}} - securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}} - resources: {requests: {cpu: 50m, memory: 64Mi}, limits: {memory: 256Mi}} - volumeMounts: - - {name: api, mountPath: /var/run/secrets/kubernetes.io/serviceaccount, readOnly: true} - containers: - - name: public-projection - image: {{ $v.helperImage }} - command: [python3, /config/project_ca.py] - env: [{name: PYTHONDONTWRITEBYTECODE, value: "1"}] - securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}} - resources: {requests: {cpu: 50m, memory: 64Mi}, limits: {memory: 256Mi}} - volumeMounts: - - {name: api, mountPath: /var/run/secrets/kubernetes.io/serviceaccount, readOnly: true} - - {name: config, mountPath: /config, readOnly: true} - volumes: - - name: config - configMap: {name: {{ $job }}} - - name: api - projected: - defaultMode: 0440 - sources: - - serviceAccountToken: {path: token, expirationSeconds: 600} - - configMap: {name: kube-root-ca.crt, items: [{key: ca.crt, path: ca.crt}]} ---- -apiVersion: v1 -kind: ServiceAccount -metadata: {name: {{ $name }}} -automountServiceAccountToken: false ---- -apiVersion: apps/v1 -kind: Deployment -metadata: {name: {{ $name }}} -spec: - replicas: 1 - selector: - matchLabels: {app.kubernetes.io/instance: {{ $v.gateway }}, openshell.pattern/role: credential-proxy} - template: - metadata: - annotations: {checksum/policy: {{ $v.policyDigest | quote }}} - labels: {app.kubernetes.io/instance: {{ $v.gateway }}, openshell.pattern/role: credential-proxy} - spec: - serviceAccountName: {{ $name }} - automountServiceAccountToken: false - securityContext: {runAsNonRoot: true, seccompProfile: {type: RuntimeDefault}} - containers: - - name: proxy - image: {{ $v.image }} - args: [serve] - securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}} - resources: {requests: {cpu: 50m, memory: 64Mi}, limits: {memory: 256Mi}} - ports: [{name: connect, containerPort: 3128}, {name: health, containerPort: 8081}] - readinessProbe: {httpGet: {path: /healthz, port: health}, periodSeconds: 5} - livenessProbe: {tcpSocket: {port: connect}, periodSeconds: 30} - volumeMounts: - - {name: policy, mountPath: /etc/saw-proxy, readOnly: true} - - {name: ca, mountPath: /var/run/saw/ca, readOnly: true} -{{- range $i, $secret := $v.credentialSecretNames }} - - {name: credential-{{ $i }}, mountPath: /var/run/saw/secrets/{{ $secret }}, readOnly: true} -{{- end }} - volumes: - - name: policy - configMap: {name: {{ $v.policyConfigMap }}} - - name: ca - secret: {secretName: {{ $ca }}, defaultMode: 0440} -{{- range $i, $secret := $v.credentialSecretNames }} - - name: credential-{{ $i }} - secret: {secretName: {{ $secret }}, defaultMode: 0440} -{{- end }} ---- -apiVersion: v1 -kind: Service -metadata: {name: {{ $name }}} -spec: - selector: - app.kubernetes.io/instance: {{ $v.gateway }} - openshell.pattern/role: credential-proxy - ports: [{name: connect, port: 3128, targetPort: connect}] ---- -apiVersion: networking.k8s.io/v1 -kind: NetworkPolicy -metadata: {name: {{ $name }}} -spec: - podSelector: - matchLabels: {app.kubernetes.io/instance: {{ $v.gateway }}, openshell.pattern/role: credential-proxy} - policyTypes: [Ingress, Egress] - ingress: - - from: - - namespaceSelector: - matchLabels: {kubernetes.io/metadata.name: {{ $v.targetNamespace }}} - podSelector: - matchLabels: {app.kubernetes.io/instance: {{ $v.gateway }}, openshell.pattern/role: gateway} - - namespaceSelector: - matchLabels: {kubernetes.io/metadata.name: {{ $v.targetNamespace }}} - podSelector: - matchLabels: {openshell.ai/gateway-id: {{ $v.gateway }}, openshell.ai/boundary-role: supervisor} - ports: [{protocol: TCP, port: 3128}] - egress: -{{ toYaml $v.network.proxyEgress | indent 4 }} -{{- end }} diff --git a/charts/saw-kubernetes-proxy/values.schema.json b/charts/saw-kubernetes-proxy/values.schema.json deleted file mode 100644 index daa6b9bd3..000000000 --- a/charts/saw-kubernetes-proxy/values.schema.json +++ /dev/null @@ -1,111 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "type": "object", - "additionalProperties": false, - "properties": { - "ownerID": { - "type": "string" - }, - "targetNamespace": { - "type": "string" - }, - "gateway": { - "type": "string" - }, - "policyConfigMap": { - "type": "string" - }, - "policyDigest": { - "type": "string" - }, - "image": { - "type": "string" - }, - "helperImage": { - "type": "string" - }, - "enabled": { - "type": "boolean" - }, - "credentialSecretNames": { - "type": "array", - "uniqueItems": true, - "maxItems": 16, - "items": { - "type": "string" - } - }, - "network": { - "type": "object", - "additionalProperties": false, - "required": [ - "bootstrapEgress", - "proxyEgress" - ], - "properties": { - "bootstrapEgress": { - "type": "array", - "items": { - "type": "object", - "required": [ - "to", - "ports" - ], - "additionalProperties": false, - "properties": { - "to": { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "minProperties": 1 - } - }, - "ports": { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "required": [ - "port" - ] - } - } - } - } - }, - "proxyEgress": { - "type": "array", - "items": { - "type": "object", - "required": [ - "to", - "ports" - ], - "additionalProperties": false, - "properties": { - "to": { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "minProperties": 1 - } - }, - "ports": { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "required": [ - "port" - ] - } - } - } - } - } - } - } - } -} diff --git a/charts/saw-kubernetes-proxy/values.yaml b/charts/saw-kubernetes-proxy/values.yaml deleted file mode 100644 index 499e458b2..000000000 --- a/charts/saw-kubernetes-proxy/values.yaml +++ /dev/null @@ -1,17 +0,0 @@ -enabled: false -ownerID: "" -targetNamespace: "" -gateway: "" -# Administrator-owned policy and ESO-created credentials in the release namespace. -# No credential values are accepted by this chart. -policyConfigMap: "" -# SHA256 of config.json; changing policy must roll the stock proxy. -policyDigest: "" -credentialSecretNames: [] -image: ghcr.io/validatedpatterns-sandbox/saw-credential-proxy@sha256:73f271de2eb6166315603fbb72c800b939a14770a69c86debaabbd29a46a0f93 -helperImage: registry.access.redhat.com/ubi9/python-311@sha256:a0bdb55576fc5b8d6704279307817828ef027e1065533ceba133fe9516003a6c -network: - # Standard NetworkPolicy egress rules. Bootstrap needs only API access. - bootstrapEgress: [] - # Explicit DNS and approved upstream paths; the proxy also checks host policy. - proxyEgress: [] diff --git a/charts/saw-portal-container/files/enroll.py b/charts/saw-portal-container/files/enroll.py index 9780d7ad0..cf10cccf7 100644 --- a/charts/saw-portal-container/files/enroll.py +++ b/charts/saw-portal-container/files/enroll.py @@ -39,6 +39,16 @@ def obj(kind,name,namespace=ns): return api("/api/v1/namespaces/"+namespace+"/"+plural+"/"+name) nsobj=obj("namespace",ns)["metadata"] if nsobj["labels"].get("saw.redhat.com/runtime-owner")!=ident or nsobj.get("deletionTimestamp"):raise ValueError("namespace ownership") + if x.get("autoApprove"): + # autoApprove publishes the first observation once. A rerun (new chart + # inputs) must not compare it with today's, which includes the running + # workspace; the reconciler still rejects later boundary changes. + published=api(f"/api/v1/namespaces/{t}/configmaps/saw-portal-enrollment") + binding=(published.get("data") or {}).get("binding.json") + if ((published["metadata"].get("labels") or {}).get("saw.redhat.com/runtime-owner")==ident + and binding and json.loads(binding).get("registration")==r): + print("Registration "+r+" is already enrolled",flush=True) + return if runtime: try: runtime_class=obj("runtimeclass",runtime["name"]) @@ -74,16 +84,20 @@ def obj(kind,name,namespace=ns): ("validatingadmissionpolicies", "validatingadmissionpolicybindings")) verify_kata_platform(x, runtime_class, configs, nodes, api_readiness, cluster_version) cfg=dict(namespace=ns,namespaceUID=nsobj["uid"],ownerID=ident,mode=mode,trustedNamespace=t, - governanceNamespace=x["governance"],gateway=u,proxyPolicy=u+"-proxy-policy",slotKeys=sorted(x["targets"])) + governanceNamespace=x["governance"],gateway=u,slotKeys=sorted(x["targets"])) if runtime: cfg["workloadRuntimeClass"]=runtime["name"] cache={} def get(p): if p not in cache:cache[p]=api(p) return cache[p] - approved=capture(cfg,get)["approved"] - verify_contract(cfg,get,x["reference"]) + approved=capture(cfg,get)["approved"] # health, admission and network checks always run profile=obj("configmap","saw-bom-profiles") - if digest(profile["data"])!=x["profileSHA256"]:raise ValueError("unapproved BOM") + if not x.get("autoApprove"): + # Reviewed sites compare the live boundary and BOM with the operator's approval. + # autoApprove (an explicit cluster setting) publishes this first observation instead; + # later changes to the enrolled boundary still fail closed. + verify_contract(cfg,get,x["reference"]) + if digest(profile["data"])!=x["profileSHA256"]:raise ValueError("unapproved BOM") def pvc(name,ro): return dict(claimName=name,uid=obj("persistentvolumeclaim",name)["metadata"]["uid"],readOnly=ro) harnesses = {} @@ -98,10 +112,13 @@ def pvc(name,ro): slots={} for key, target in x["targets"].items(): base=target["base"] - slot={"workspace":pvc("workspace-"+base,False), - "toolGate":{"ownerLogin":u,"receiptKey":receipt_key(base,hist,"/writer-ca/service-ca.crt"), - "trusted":pvc("saw-gate-"+base,True),"audit":pvc("saw-audit-"+base,False)}, - "resources":x["resources"]} + gate={"ownerLogin":u,"trusted":pvc("saw-gate-"+base,True),"audit":pvc("saw-audit-"+base,False)} + if x.get("auditReceipts"): + # Fail-closed: each approved tool action waits for the writer's signed receipt. + gate["receiptKey"]=receipt_key(base,hist,"/writer-ca/service-ca.crt") + else: + gate["localAudit"]=True # best-effort log on the sandbox's own audit volume + slot={"workspace":pvc("workspace-"+base,False),"toolGate":gate,"resources":x["resources"]} if x.get("lifecycleVersion") == 1 and target.get("modelInput"): slot["toolGate"]["modelSelector"] = True if key in harnesses: @@ -115,10 +132,8 @@ def pvc(name,ro): if runtime: bindings.update(workloadRuntimeClass=runtime["name"],workloadRuntimeClassUID=runtime["uid"], workloadRuntimeClassDigest=runtime["sha256"]) - if x.get("providerPolicy"): - bindings["proxyBindings"] = [{"secret": b["secret"], "key": b["key"], "type": typ, - "refresh": bool(b.get("refresh"))} - for b in x["providerPolicy"]["bindings"] for typ in b["providers"]] + if x.get("credentialBindings"): + bindings["credentialBindings"] = x["credentialBindings"] if x.get("customInferenceURL"): bindings["customInferenceURL"] = x["customInferenceURL"] if x.get("modelInputs"): diff --git a/charts/saw-portal-container/files/portal_contract.py b/charts/saw-portal-container/files/portal_contract.py index 94cd4e791..9257a94d0 100644 --- a/charts/saw-portal-container/files/portal_contract.py +++ b/charts/saw-portal-container/files/portal_contract.py @@ -9,7 +9,6 @@ import ipaddress import json import re -import ssl from saw_kubernetes.boundary import BoundaryError, fingerprint, objects @@ -25,19 +24,6 @@ def contract(config, get): # Cluster installation is shared across registrations. Keep both UID and hash. output[key]={"uid":obj["metadata"]["uid"],"sha256":fingerprint(value)} continue - if key=="publicCA": - source=get(f"/api/v1/namespaces/{trusted}/configmaps/{config['gateway']}-proxy-ca") - if obj.get("metadata",{}).get("labels",{}).get("saw.redhat.com/runtime-owner")!=owner or set(value)!={"ca.crt"} or value!=source.get("data") or source["metadata"].get("deletionTimestamp"): - raise BoundaryError("UntrustedProxyCA") - cert=value["ca.crt"] - if not re.fullmatch(r"-----BEGIN CERTIFICATE-----\s+[A-Za-z0-9+/=\s]+-----END CERTIFICATE-----\s*",cert): - raise BoundaryError("InvalidProxyCA") - try: - ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT).load_verify_locations(cadata=cert) - except (ssl.SSLError,ValueError) as exc: - raise BoundaryError("InvalidProxyCA") from exc - output[key]="equals independent trusted proxy public CA" - continue if key=="gatewayService": ips=value.get("clusterIPs") if (value.get("type")!="ClusterIP" or not isinstance(ips,list) or not ips or value.get("clusterIP")!=ips[0] diff --git a/charts/saw-portal-container/files/preflight.py b/charts/saw-portal-container/files/preflight.py index c32862180..dc499183c 100644 --- a/charts/saw-portal-container/files/preflight.py +++ b/charts/saw-portal-container/files/preflight.py @@ -196,24 +196,33 @@ def check_observations(mode, observations): return tuple(required) +# Reviewed sites pin every chart to a full commit SHA. An autoApprove +# (development) site may follow a branch instead: saw-users and portal defaults +# use global.targetRevision when a site sets no revision. +PINNED_REVISION = r"[a-f0-9]{40}" +BRANCH_REVISION = r"[a-f0-9]{40}|[A-Za-z0-9][A-Za-z0-9._/-]*" + + def configuration_facts(site): """Check site-owned inputs that do not require cluster access.""" if not isinstance(site, dict): return {key: False for key in ("network", "storage", "secrets", "registry", "providerEgress", "revisions")} stack = site.get("stack") if isinstance(site.get("stack"), dict) else {} + enrollment = site.get("automaticEnrollment") or {} + revision_pattern = BRANCH_REVISION if isinstance(enrollment, dict) and enrollment.get( + "autoApprove") is True else PINNED_REVISION revisions = [item.get("revision") for item in stack.values() if isinstance(item, dict)] - required_components = ("identity", "policy", "proxy", "gateway", "audit") + required_components = ("identity", "policy", "gateway", "audit") revision_pin = all(isinstance(stack.get(name), dict) for name in required_components) and all( isinstance(stack[name].get("revision"), str) - and re.fullmatch(r"[a-f0-9]{40}", stack[name]["revision"]) + and re.fullmatch(revision_pattern, stack[name]["revision"]) for name in required_components) and bool(revisions) and len(revisions) == len(stack) and all( - isinstance(value, str) and re.fullmatch(r"[a-f0-9]{40}", value) for value in revisions) - enrollment = site.get("automaticEnrollment") or {} + isinstance(value, str) and re.fullmatch(revision_pattern, value) for value in revisions) if enrollment and not isinstance(enrollment, dict): revision_pin = False elif enrollment: - revision_pin = revision_pin and bool(re.fullmatch(r"[a-f0-9]{40}", str(enrollment.get("revision", "")))) + revision_pin = revision_pin and bool(re.fullmatch(revision_pattern, str(enrollment.get("revision", "")))) image_values = [] storage_values = [] @@ -233,28 +242,20 @@ def walk(value, path=()): walk(child, path) walk(site) - declared_hosts = site.get("providerAllowHosts") - policy = site.get("providerPolicy") - clean_hosts = (isinstance(declared_hosts, list) and bool(declared_hosts) - and all(isinstance(host, str) and host and "*" not in host - for host in declared_hosts) - and (policy is None or (isinstance(policy, dict) - and isinstance(policy.get("allowHosts"), list) - and all(isinstance(host, str) for host in policy["allowHosts"]) - and set(policy["allowHosts"]) == set(declared_hosts)))) - proxy = stack.get("proxy") or {} - proxy_values = proxy.get("values") or {} if isinstance(proxy, dict) else {} - bootstrap_egress = ((proxy_values.get("network") or {}).get("bootstrapEgress") - if isinstance(proxy_values, dict) else None) + # OpenShell decides where each credential may go (provider profiles); the + # site only lists which Secret backs which provider type. + bindings = site.get("credentialBindings") + clean_bindings = (isinstance(bindings, list) and all( + isinstance(b, dict) and {"secret", "key", "type"} <= set(b) <= {"secret", "key", "type", "refresh"} + and all(isinstance(v, str) and v for v in b.values()) for b in bindings)) storage_ok = bool(storage_values) and all(value.strip() for value in storage_values) return { - "network": bool(stack.get("policy")) and isinstance(bootstrap_egress, list) - and bool(bootstrap_egress), + "network": bool(stack.get("policy")), "storage": storage_ok, "secrets": isinstance(site.get("secretStore", "vault-backend"), str) and bool(site.get("secretStore", "vault-backend")), "registry": bool(image_values) and all("@sha256:" in image for image in image_values), - "providerEgress": clean_hosts, + "providerEgress": clean_bindings, "revisions": revision_pin, } diff --git a/charts/saw-portal-container/templates/_helpers.tpl b/charts/saw-portal-container/templates/_helpers.tpl index a6ad840c2..195f01797 100644 --- a/charts/saw-portal-container/templates/_helpers.tpl +++ b/charts/saw-portal-container/templates/_helpers.tpl @@ -1,6 +1,6 @@ {{/* Targets are derived from the selected BOM, never a fixed profile. */}} {{- define "portal.targets" -}} -{{- $s := .Values.site | default dict -}} +{{- $s := include "portal.site" . | fromJson -}} {{ required "BOM-derived sandbox targets are required" $s.targets | toJson }} {{- end -}} {{- define "portal.claims" -}} @@ -11,3 +11,49 @@ {{- end -}}{{- end -}} {{ $claims | toJson }} {{- end -}} + +{{/* The namespace whose ImageStreams the runtime image is pulled from: the +site's buildNamespace when the image is in the OpenShift internal registry, +else "" (a published image needs no pull grant, and the namespace need not +exist). Takes the enrollment or automaticEnrollment dict. */}} +{{- define "portal.pullNamespace" -}} +{{- if hasPrefix "image-registry.openshift-image-registry.svc:5000/" (.image | default "") -}}{{ .buildNamespace }}{{- end -}} +{{- end -}} + +{{/* Chart revisions a site may use. Reviewed sites pin every chart to a full +commit SHA; an autoApprove (development) site may follow a branch. The +portal and installer preflight apply the same rule (preflight.py). */}} +{{- define "portal.revisionPattern" -}} +{{- $a := (include "portal.site" . | fromJson).automaticEnrollment | default dict -}} +{{- if eq (toString ($a.autoApprove | default false)) "true" -}}^[A-Za-z0-9][A-Za-z0-9._/-]*${{- else -}}^[a-f0-9]{40}${{- end -}} +{{- end -}} + +{{/* Recursive merge of .over into .base by key presence (as saw-users.deepMerge): +a false, 0 or "" in .over replaces the base value. Maps merge; every other +value (lists included) is replaced. Returns JSON. */}} +{{- define "portal.deepMerge" -}} +{{- $out := deepCopy (.base | default dict) -}} +{{- range $key, $value := (.over | default dict) -}} +{{- $current := index $out $key -}} +{{- if and (kindIs "map" $value) (kindIs "map" $current) -}} +{{- $_ := set $out $key (include "portal.deepMerge" (dict "base" $current "over" $value) | fromJson) -}} +{{- else -}} +{{- $_ := set $out $key $value -}} +{{- end -}} +{{- end -}} +{{- toJson $out -}} +{{- end -}} + +{{/* The site layered over siteDefaults. A published enrollment carries the +site's relay settings and build namespace; fill what the site left to the +defaults, and let the relay follow the enrollment revision. Returns JSON. */}} +{{- define "portal.site" -}} +{{- $site := include "portal.deepMerge" (dict "base" .Values.siteDefaults "over" (.Values.site | default dict)) | fromJson -}} +{{- with $site.enrollment -}} +{{- $a := $site.automaticEnrollment -}} +{{- $_ := set . "relay" (include "portal.deepMerge" (dict "base" ($a.relay | default dict) "over" (.relay | default dict)) | fromJson) -}} +{{- if not .relay.revision }}{{ $_ := set .relay "revision" .revision }}{{ end -}} +{{- if not .buildNamespace }}{{ $_ := set . "buildNamespace" $a.buildNamespace }}{{ end -}} +{{- end -}} +{{- toJson $site -}} +{{- end -}} diff --git a/charts/saw-portal-container/templates/auto-enroll.yaml b/charts/saw-portal-container/templates/auto-enroll.yaml index 47853e0fc..90689dd32 100644 --- a/charts/saw-portal-container/templates/auto-enroll.yaml +++ b/charts/saw-portal-container/templates/auto-enroll.yaml @@ -1,6 +1,7 @@ -{{- $s := .Values.site | default dict }}{{- $a := $s.automaticEnrollment | default dict }} -{{- if and $a (ne (get $a "enabled" | toString) "false") }} -{{- if or (not (regexMatch "^.+@sha256:[a-f0-9]{64}$" $a.image)) (not (regexMatch "^[a-f0-9]{40}$" $a.revision)) (ne (len $a.reference) (ternary 27 25 (not (empty $s.kataRuntimeClass)))) }}{{ fail "automatic enrollment requires pinned code and a reviewed boundary" }}{{- end }} +{{- $s := include "portal.site" . | fromJson }}{{- $a := $s.automaticEnrollment | default dict }} +{{- if and (.Values.site | default dict).automaticEnrollment (ne (get $a "enabled" | toString) "false") }} +{{- $autoApprove := eq (toString ($a.autoApprove | default false)) "true" }} +{{- if or (not (regexMatch "^.+@sha256:[a-f0-9]{64}$" $a.image)) (not (regexMatch (include "portal.revisionPattern" $) ($a.revision | default ""))) (and (not $autoApprove) (ne (len ($a.reference | default dict)) (ternary 23 21 (not (empty $s.kataRuntimeClass))))) }}{{ fail "automatic enrollment requires a pinned image, a full Git commit SHA revision and a reviewed boundary (or autoApprove, which may follow a branch)" }}{{- end }} {{- $observer := $s.observer | default dict }} {{- $r := .Values.registration }}{{- $g := .Values.owner }}{{- $n := .Release.Namespace }} {{- $t := printf "saw-ctl-%s" $r }}{{- $archive := printf "saw-history-%s" $r }} @@ -8,7 +9,7 @@ {{- $bases := list }}{{- range $slot := $targets }}{{- $bases = append $bases $slot.base }}{{- end }} {{- $gov := $s.governanceNamespace }}{{- $name := printf "enroll-%s" $r }}{{- $policy := printf "saw-%s-runtime" $n }} {{- $gatewayVersion := dig "stack" "gateway" "values" "kubernetes" "gateway" "version" .Values.driverDefaults.gatewayVersion $s -}} -{{- $bootstrap := dict "registration" $r "installation" .Values.installationID "user" $g "subject" .Values.ownerSubject "governance" $gov "reference" $a.reference "profileSHA256" ($s.selectedDigest | default $a.profileSHA256) "targets" $targets "gatewayVersion" $gatewayVersion "customInferenceURL" ($s.customInferenceURL | default "") "providerPolicy" ($s.providerPolicy | default dict) "lifecycleVersion" ($s.lifecycleVersion | default 0) "modelInputs" ($s.modelInputs | default dict) "resources" $a.resources "domain" .Values.global.clusterDomain -}} +{{- $bootstrap := dict "registration" $r "installation" .Values.installationID "user" $g "subject" .Values.ownerSubject "governance" $gov "reference" ($a.reference | default dict) "autoApprove" $autoApprove "profileSHA256" ($s.selectedDigest | default $a.profileSHA256) "targets" $targets "gatewayVersion" $gatewayVersion "customInferenceURL" ($s.customInferenceURL | default "") "credentialBindings" ($s.credentialBindings | default list) "lifecycleVersion" ($s.lifecycleVersion | default 0) "modelInputs" ($s.modelInputs | default dict) "resources" $a.resources "domain" .Values.global.clusterDomain "auditReceipts" ($s.auditReceipts | default false) -}} {{- $scripts := (.Files.Glob "files/*.py").AsConfig -}} {{- with $s.kataRuntimeClass }}{{- $_ := set $bootstrap "kataRuntimeClass" . }}{{- end }} {{- $revision := dict "chartVersion" .Chart.Version "image" $a.image "config" $bootstrap "scripts" $scripts | toJson | sha256sum | trunc 12 -}} @@ -48,15 +49,13 @@ metadata: {name: {{ $name }}, namespace: {{ $ns }}} rules: {{- if eq $ns $n }} - {apiGroups: [rbac.authorization.k8s.io], resources: [roles], resourceNames: [{{ $g }}-gateway], verbs: [get]} - - {apiGroups: [""], resources: [configmaps], resourceNames: [saw-bom-profiles, {{ $g }}-gateway-config, {{ $g }}-proxy-ca], verbs: [get]} + - {apiGroups: [""], resources: [configmaps], resourceNames: [saw-bom-profiles, {{ $g }}-gateway-config], verbs: [get]} - {apiGroups: [""], resources: [persistentvolumeclaims], resourceNames: {{ include "portal.claims" $ }}, verbs: [get]} - {apiGroups: [apps], resources: [statefulsets], resourceNames: [{{ $g }}-gateway], verbs: [get]} - {apiGroups: [""], resources: [services], resourceNames: [{{ $g }}-gateway], verbs: [get]} - {apiGroups: [networking.k8s.io], resources: [networkpolicies], resourceNames: [{{ $g }}-gateway, {{ $g }}-default-deny, openshell-sandbox-workloads, openshell-sandbox-supervisors], verbs: [get]} {{- else if eq $ns $t }} - - {apiGroups: [apps], resources: [deployments], resourceNames: [{{ $g }}-credential-proxy], verbs: [get]} - - {apiGroups: [networking.k8s.io], resources: [networkpolicies], resourceNames: [{{ $g }}-credential-proxy], verbs: [get]} - - {apiGroups: [""], resources: [configmaps], resourceNames: [{{ $g }}-proxy-policy, {{ $g }}-proxy-ca, {{ $g }}-gateway-ca], verbs: [get]} + - {apiGroups: [""], resources: [configmaps], resourceNames: [{{ $g }}-gateway-ca], verbs: [get]} - {apiGroups: [""], resources: [configmaps], resourceNames: [saw-portal-enrollment], verbs: [get, patch]} {{- else }} - {apiGroups: [apps], resources: [deployments], resourceNames: [governance-interceptor], verbs: [get]} @@ -71,17 +70,19 @@ roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: {{ $name }}} subjects: [{kind: ServiceAccount, name: {{ $name }}, namespace: {{ $t }}}] {{- end }} +{{- with include "portal.pullNamespace" $a }} --- apiVersion: rbac.authorization.k8s.io/v1 kind: Role -metadata: {name: {{ $name }}-pull, namespace: {{ $a.buildNamespace }}} +metadata: {name: {{ $name }}-pull, namespace: {{ . }}} rules: [{apiGroups: [image.openshift.io], resources: [imagestreams/layers], resourceNames: [{{ base (index (splitList "@" $a.image) 0) | quote }}], verbs: [get]}] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding -metadata: {name: {{ $name }}-pull, namespace: {{ $a.buildNamespace }}} +metadata: {name: {{ $name }}-pull, namespace: {{ . }}} roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: {{ $name }}-pull} subjects: [{kind: ServiceAccount, name: {{ $name }}, namespace: {{ $t }}}] +{{- end }} --- apiVersion: v1 kind: ConfigMap @@ -90,6 +91,7 @@ immutable: true data: config.json: {{ $bootstrap | toJson | quote }} {{ $scripts | indent 2 }} +{{- if $s.auditReceipts }} --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy @@ -102,6 +104,7 @@ spec: - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: {{ $t }}}} podSelector: {matchLabels: {app: {{ $name }}}} ports: [{port: 8443, protocol: TCP}] +{{- end }} --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy @@ -110,11 +113,14 @@ 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 }} + {{- if $s.auditReceipts }} + # Reads each writer's receipt key for the tool gate. - to: - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: {{ $archive }}}} podSelector: {matchExpressions: [{key: saw-audit-writer, operator: In, values: {{ $bases | toJson }}}]} ports: [{port: 8443, protocol: TCP}] + {{- end }} --- apiVersion: batch/v1 kind: Job @@ -123,7 +129,7 @@ spec: backoffLimit: 1 activeDeadlineSeconds: 1200 template: - metadata: {labels: {app: {{ $name }}}} + metadata: {labels: {app: {{ $name }}, saw.redhat.com/kubernetes-api: allow}} spec: serviceAccountName: {{ $name }} restartPolicy: Never diff --git a/charts/saw-portal-container/templates/enrolled-runtime.yaml b/charts/saw-portal-container/templates/enrolled-runtime.yaml index c82c2714d..9f3f77f3c 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 }} @@ -24,7 +24,9 @@ apiVersion: v1 kind: PersistentVolumeClaim metadata: {name: portal-ledger, namespace: {{ $ctl }}} spec: - storageClassName: {{ $site.stack.audit.values.storageClass }} + {{- with $site.stack.audit.values.storageClass }} + storageClassName: {{ . }} + {{- end }} accessModes: [ReadWriteOnce] resources: {requests: {storage: 1Gi}} --- @@ -32,21 +34,23 @@ 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 }} -{{- if or (ne $slot.workspace.claimName (printf "workspace-%s" $target.base)) (ne $gate.trusted.claimName (printf "saw-gate-%s" $target.base)) (ne $gate.audit.claimName (printf "saw-audit-%s" $target.base)) (ne $gate.ownerLogin $u) (not $gate.receiptKey) }}{{ fail "invalid storage binding" }}{{- end }} +{{- if or (ne $slot.workspace.claimName (printf "workspace-%s" $target.base)) (ne $gate.trusted.claimName (printf "saw-gate-%s" $target.base)) (ne $gate.audit.claimName (printf "saw-audit-%s" $target.base)) (ne $gate.ownerLogin $u) (not (or $gate.receiptKey $gate.localAudit)) }}{{ fail "invalid storage binding" }}{{- end }} {{- if and $target.ui (or (ne $slot.browser.ownerLogin $u) (ne $slot.browser.origin (printf "https://%s-%s-%s-ui.apps.%s" $u $target.workspace $target.sandbox $.Values.global.clusterDomain))) }}{{ fail "invalid owner UI binding" }}{{- end }} {{- $job := ternary "saw-gate-preparation" (printf "gate-%s" $target.relayID) (eq (len $targets) 1) }} {{- if $gate.harness }} @@ -68,7 +72,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 @@ -78,11 +84,13 @@ spec: containers: - name: prep image: {{ $e.image | quote }} - command: [python3, -m, saw_kubernetes.prepare_gate, --owner, {{ $u | quote }}, --subject, {{ $b.ownerSubject | quote }}, --workspace, {{ $target.workspace }}, --sandbox, {{ $target.sandbox }}, --receipt-key, {{ $gate.receiptKey | quote }}{{ if $target.ui }}, --browser-proof, /proof/relay-proof{{ end }}{{ if $gate.harness }}, --harness, {{ $gate.harness.name | quote }}, {{ $gate.harness.digest | quote }}{{ end }}{{ if $model }}, --model, {{ $model | quote }}, --model-generation, {{ $publication | quote }}{{ end }}] + command: [python3, -m, saw_kubernetes.prepare_gate, --owner, {{ $u | quote }}, --subject, {{ $b.ownerSubject | quote }}, --workspace, {{ $target.workspace }}, --sandbox, {{ $target.sandbox }}{{ with $gate.receiptKey }}, --receipt-key, {{ . | quote }}{{ end }}{{ if $target.ui }}, --browser-proof, /proof/relay-proof{{ end }}{{ if $gate.harness }}, --harness, {{ $gate.harness.name | quote }}, {{ $gate.harness.digest | quote }}{{ end }}{{ if $model }}, --model, {{ $model | quote }}, --model-generation, {{ $publication | quote }}{{ end }}] securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}} volumeMounts: [{name: gate, mountPath: /volume}{{ if $target.ui }}, {name: proof, mountPath: /proof, readOnly: true}{{ end }}{{ if $gate.harness }}, {name: bom, mountPath: /bom, readOnly: true}{{ end }}] volumes: [{name: gate, persistentVolumeClaim: {claimName: {{ $gate.trusted.claimName }}}}{{ if $target.ui }}, {name: proof, secret: {secretName: ui-{{ $target.relayID }}-browser-proof, items: [{key: relay-proof, path: relay-proof}]}}{{ end }}{{ if $gate.harness }}, {name: bom, configMap: {name: saw-bom-profiles}}{{ end }}] {{- end }} +{{- $credentialSecrets := list }} +{{- range ($site.credentialBindings | default list) }}{{- $credentialSecrets = append $credentialSecrets .secret }}{{- end }} --- apiVersion: argoproj.io/v1alpha1 kind: Application @@ -105,14 +113,15 @@ spec: enabled: true image: {{ $e.image | quote }} stateClaim: portal-ledger - imageBuildNamespace: {{ $e.buildNamespace }} + imageBuildNamespace: {{ include "portal.pullNamespace" $e | quote }} claimNames: {{ $claims | toJson }} configuration: gateway: {{ $u }} namespace: {{ $ns }} trustedNamespace: {{ $ctl }} governanceNamespace: {{ $site.governanceNamespace }} - proxyPolicy: {{ $u }}-proxy-policy + # The Secrets this workspace's providers read from (External Secrets copies). + credentialSecrets: {{ $credentialSecrets | uniq | sortAlpha | toJson }} ownerID: {{ $b.ownerID }} namespaceUID: {{ $b.namespaceUID }} mode: {{ $b.mode }} @@ -124,7 +133,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..47a035a57 100644 --- a/charts/saw-portal-container/templates/foundation.yaml +++ b/charts/saw-portal-container/templates/foundation.yaml @@ -7,7 +7,7 @@ {{- $trusted := printf "saw-ctl-%s" $id }} {{- if ne .Release.Namespace $runtime }}{{ fail "release namespace must match workspace owner" }}{{ end }} {{- $prefix := required "owner-scoped vaultPrefix required" .Values.vaultPrefix }} -{{- if not (regexMatch (printf "^[a-zA-Z0-9_-]+/data/([a-zA-Z0-9_-]+/)*saw-%s/%s$" $u $id) $prefix) }}{{ fail "vaultPrefix must match the owner and registration" }}{{ end }} +{{- if not (regexMatch (printf "^[a-zA-Z0-9_-]+/data/([a-zA-Z0-9_-]+/)*saw-%s(/%s)?$" $u $id) $prefix) }}{{ fail "vaultPrefix must match the owner (…/saw-, or …/saw-/ from the portal)" }}{{ end }} apiVersion: v1 kind: Namespace metadata: @@ -20,6 +20,37 @@ metadata: annotations: argocd.argoproj.io/sync-wave: "-2" --- +# The workspace's platform pods (gateway, controller, identity and enrollment +# Jobs, relay) reach the Kubernetes API through the control-plane nodes. An +# AdminNetworkPolicy can select nodes by label, so no cluster IPs are needed. +# Allow here is final and takes precedence over the default-deny below. It +# comes after the runtime's own policy (priority 51), which only covers +# sandbox supervisors, and never selects a sandbox pod. +{{- $apiSite := include "portal.site" . | fromJson }} +{{- $api := $apiSite.kubernetesApi | default dict }} +{{- $apiNamespaces := list $runtime $trusted }} +{{- range $slot := ($apiSite.targets | default dict) }}{{- if $slot.ui }}{{- $apiNamespaces = append $apiNamespaces (printf "saw-ui-%s" $slot.relayID) }}{{- end }}{{- end }} +apiVersion: policy.networking.k8s.io/v1alpha1 +kind: AdminNetworkPolicy +metadata: + name: saw-{{ $id }}-kubernetes-api + annotations: {argocd.argoproj.io/sync-wave: "-1"} +spec: + priority: {{ required "kubernetesApi.priority required" $api.priority }} + subject: + pods: + namespaceSelector: + matchExpressions: + - {key: kubernetes.io/metadata.name, operator: In, values: {{ $apiNamespaces | uniq | toJson }}} + podSelector: + matchLabels: {saw.redhat.com/kubernetes-api: allow} + matchExpressions: [{key: openshell.ai/boundary-role, operator: DoesNotExist}] + egress: + - name: kubernetes-api + action: Allow + to: {{ required "kubernetesApi.to required" $api.to | toJson }} + ports: [{portNumber: {protocol: TCP, port: {{ $api.port | default 6443 }}}}] +--- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: {name: default-deny, namespace: {{ $trusted }}, annotations: {argocd.argoproj.io/sync-wave: "-1"}} @@ -31,17 +62,15 @@ metadata: {name: default-deny, namespace: {{ $runtime }}, annotations: {argocd.a spec: {podSelector: {}, policyTypes: [Ingress, Egress], ingress: [], egress: []} {{- $customSecret := "" }} {{- $sources := dict }} -{{- with required "explicit governed provider policy required" (.Values.site | default dict).providerPolicy }} -{{- $sources = dict }} -{{- range .bindings }} +{{- /* helm lint turns required into a warning and yields "", which range cannot iterate. */}} +{{- $bindings := required "explicit credential bindings required" (.Values.site | default dict).credentialBindings }} +{{- range ($bindings | default list) }} +{{- if eq .type "custom-inference" }}{{- $customSecret = .secret }}{{- end }} {{- $fields := get $sources .secret | default list }} -{{- if .refresh }} -{{- range .refresh.material }}{{- $fields = append $fields . }}{{- end }} -{{- else }}{{- $fields = append $fields .key }}{{- end }} -{{- if has "custom-inference" .providers }}{{- $customSecret = .secret }}{{- end }} +{{- /* A refreshable credential's Secret holds only the refresh material; OpenShell mints the token. */}} +{{- if .refresh }}{{- $fields = concat $fields (list "client_id" "client_secret" "refresh_token") }}{{- else }}{{- $fields = append $fields .key }}{{- end }} {{- $_ := set $sources .secret ($fields | uniq | sortAlpha) }} {{- end }} -{{- end }} {{- range $secret, $fields := $sources }} --- apiVersion: external-secrets.io/v1 diff --git a/charts/saw-portal-container/templates/publications.yaml b/charts/saw-portal-container/templates/publications.yaml index a39f271b2..bbbc02cd1 100644 --- a/charts/saw-portal-container/templates/publications.yaml +++ b/charts/saw-portal-container/templates/publications.yaml @@ -1,5 +1,5 @@ -{{- $s := .Values.site | default dict }} -{{- if $s.automaticEnrollment }} +{{- $s := include "portal.site" . | fromJson }} +{{- if (.Values.site | default dict).automaticEnrollment }} {{- $observer := $s.observer | default dict }} {{- $t := printf "saw-ctl-%s" .Values.registration }} {{- $targets := include "portal.targets" . | fromJson }} diff --git a/charts/saw-portal-container/templates/relay.yaml b/charts/saw-portal-container/templates/relay.yaml index 5ac8ecea6..afab357dd 100644 --- a/charts/saw-portal-container/templates/relay.yaml +++ b/charts/saw-portal-container/templates/relay.yaml @@ -1,8 +1,8 @@ -{{- $site := .Values.site | default dict }} +{{- $site := include "portal.site" . | fromJson }} {{- $e := $site.enrollment | default dict }} {{- if and $e (eq $e.registration .Values.registration) $e.relay }} {{- $r := $e.relay }} -{{- if not (regexMatch "^[a-f0-9]{40}$" ($r.revision | default "")) }}{{ fail "relay revision must be a full Git commit SHA" }}{{ end }} +{{- if not (regexMatch (include "portal.revisionPattern" $) ($r.revision | default "")) }}{{ fail "relay revision must be a full Git commit SHA (only autoApprove sites may follow a branch)" }}{{ end }} {{- $u := .Values.owner }} {{- $reg := .Values.registration }} {{- $ctl := printf "saw-ctl-%s" $reg }} @@ -48,13 +48,13 @@ spec: gateway: {{ $u }} gatewayEndpoint: https://{{ $u }}-gateway.{{ $ns }}.svc:17670 gatewayCA: {{ $r.gatewayCA | quote }} - issuer: {{ $r.issuer | quote }} + issuer: {{ $r.issuer | default (printf "https://openshell-keycloak-ingress-%s.apps.%s/realms/openshell" $r.keycloakNamespace $.Values.global.clusterDomain) | quote }} ownerLogin: {{ $u }} ownerSubject: {{ $.Values.ownerSubject }} installationID: {{ $.Values.installationID }} host: {{ $u }}-{{ $target.workspace }}-{{ $target.sandbox }}-ui.apps.{{ $.Values.global.clusterDomain }} sdkImage: {{ $e.image }} - imageBuildNamespace: {{ $e.buildNamespace }} + imageBuildNamespace: {{ include "portal.pullNamespace" $e | quote }} egress: {{ $r.egress | toJson }} ignoreDifferences: - {group: "", kind: Secret, name: ui-{{ $rid }}-registration-state, namespace: {{ $r.keycloakNamespace }}, jsonPointers: [/data]} diff --git a/charts/saw-portal-container/templates/stack.yaml b/charts/saw-portal-container/templates/stack.yaml index a0a540369..0576cd6c7 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 }} @@ -13,7 +13,11 @@ {{- $ui := printf "saw-ui-%s" $reg }} {{- $map := dict "RUNTIME" $runtime "TRUSTED" $trusted "ARCHIVE" $archive "UI" $ui "OWNER" $u "SUBJECT" .Values.ownerSubject "INSTALLATION" $ownerID "DOMAIN" $g.clusterDomain }} {{- $targets := include "portal.targets" . | fromJson }} -{{- $namespaces := dict $archive "retained" }} +{{- /* auditReceipts (advanced): signed, fail-closed tool-gate receipts with a + retained history namespace. Off, the gate keeps a local audit log. */}} +{{- $receipts := $site.auditReceipts | default false }} +{{- $namespaces := dict }} +{{- if $receipts }}{{- $_ := set $namespaces $archive "retained" }}{{- end }} {{- range $slot := $targets }}{{- if $slot.ui }}{{- $_ := set $namespaces (printf "saw-ui-%s" $slot.relayID) "ephemeral" }}{{- end }}{{- end }} {{- range $name, $dest := $namespaces }} --- @@ -47,7 +51,7 @@ metadata: {name: identity-api, namespace: {{ $trusted }}} spec: podSelector: {matchLabels: {openshell.pattern/role: identity-bootstrap}} policyTypes: [Egress] - egress: {{ $stack.proxy.values.network.bootstrapEgress | toJson }} + egress: {{ required "site.stack.identity.values.network.bootstrapEgress is required" (dig "identity" "values" "network" "bootstrapEgress" nil $stack) | toJson }} --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy @@ -60,22 +64,46 @@ 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) }} -{{- 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 }} + +{{- $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" (ternary $archive $runtime $receipts) $slot) }}{{- end }} {{- range $key, $c := $charts }} {{- $item := required (printf "missing site.stack.%s" $key) (get $stack (ternary "audit" $key (eq (len $c) 3))) }} -{{- if not (regexMatch "^[a-f0-9]{40}$" ($item.revision | default "")) }}{{ fail "each infrastructure chart must be pinned to a Git commit" }}{{ end }} +{{- if not (regexMatch (include "portal.revisionPattern" $) ($item.revision | default "")) }}{{ fail "each infrastructure chart must be pinned to a full Git commit SHA (only autoApprove sites may follow a branch)" }}{{ end }} {{- $values := $item.values | toJson }} {{- range $k, $v := $map }} {{- $values = replace (printf "@%s@" $k) $v $values }} {{- end }} +{{- if eq $key "gateway" }} +{{- /* The interceptor endpoint and the egress to reach it follow the site's + governance namespace; the default sandbox image is the first target's. */}} +{{- $gateway := fromJson $values }} +{{- $k := $gateway.kubernetes }} +{{- $gov := $site.governanceNamespace }} +{{- $_ := set $k "governance" (dict "endpoint" (printf "http://governance-interceptor.%s.svc:18081" $gov)) }} +{{- $interceptor := dict "to" (list (dict "namespaceSelector" (dict "matchLabels" (dict "kubernetes.io/metadata.name" $gov)) "podSelector" (dict "matchLabels" (dict "app.kubernetes.io/name" "governance-interceptor")))) "ports" (list (dict "protocol" "TCP" "port" 18081)) }} +{{- $network := $k.network | default dict }} +{{- $_ := set $network "gatewayEgress" (prepend ($network.gatewayEgress | default list) $interceptor) }} +{{- with $site.telemetry }}{{- if .ocsfEndpoint }} +{{- $_ := set $gateway "telemetry" (dict "ocsfEndpoint" .ocsfEndpoint "agentTraces" (.agentTraces | default false)) }} +{{- $collector := dict "to" (list (dict "namespaceSelector" (dict "matchLabels" (dict "kubernetes.io/metadata.name" .collector.namespace)) "podSelector" (dict "matchLabels" .collector.podLabels))) "ports" (list (dict "protocol" "TCP" "port" (int .collector.port))) }} +{{- $_ := set $network "gatewayEgress" (append $network.gatewayEgress $collector) }} +{{- end }}{{- end }} +{{- $_ := 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 }} +{{- /* The admission policy pins these same images (below): give the gateway +the identical resolved values instead of its own chart defaults. */}} +{{- if not $workload.runtimeImage }}{{- $_ := set $workload "runtimeImage" $.Values.driverDefaults.runtimeImage }}{{- end }} +{{- $_ := set $k "workload" $workload }} +{{- $supervisor := $k.supervisor | default dict }} +{{- if not $supervisor.image }}{{- $_ := set $supervisor "image" $.Values.driverDefaults.supervisorImage }}{{- end }} +{{- $_ := set $k "supervisor" $supervisor }} +{{- $values = toJson $gateway }} +{{- end }} {{- if and (eq $key "gateway") $site.kataRuntimeClass }} {{- $gateway := fromJson $values }} {{- $_ := set $gateway "deployment" (dict "mode" "kata") }} @@ -99,19 +127,18 @@ data: {{- $_ := set $policy "forwarderImage" $stack.audit.values.image }} {{- $_ := set $policy "serverTLSSecret" (replace "@OWNER@" $u $gw.identity.serverTlsSecret) }} {{- $_ := set $policy "supervisorImage" (dig "supervisor" "image" $.Values.driverDefaults.supervisorImage $gw) }} -{{- $_ := set $policy "runtimeImage" ($gw.workload.runtimeImage | default $.Values.driverDefaults.runtimeImage) }} -{{- $proxyURL := replace "@TRUSTED@" $trusted (replace "@OWNER@" $u $gw.proxy.url) }} -{{- $_ := set $policy "supervisorCommand" (list "/openshell-supervisor" "--backend-descriptor-file" "/.openshell/supervisor/runtime-descriptor.json" "--auth-bundle-file" "/.openshell/supervisor/auth.json" "--workdir" "/sandbox" "--health-socket-path" "/run/openshell/health.sock" "--health-port" "5501" "--upstream-proxy" $proxyURL "--upstream-proxy-connect-by-hostname" "--upstream-proxy-ca-bundle" "/.openshell/supervisor/upstream-proxy-ca.pem") }} +{{- $_ := set $policy "runtimeImage" (dig "workload" "runtimeImage" "" $gw | default $.Values.driverDefaults.runtimeImage) }} +{{- $_ := set $policy "supervisorCommand" (list "/openshell-supervisor" "--backend-descriptor-file" "/.openshell/supervisor/runtime-descriptor.json" "--auth-bundle-file" "/.openshell/supervisor/auth.json" "--workdir" "/sandbox" "--health-socket-path" "/run/openshell/health.sock" "--health-port" "5501") }} +{{- $_ := set $policy.network "publicHTTPS" true }} +{{- with $site.telemetry }}{{- if .ocsfEndpoint }} +{{- /* Supervisors export their own OCSF events to the same collector. */}} +{{- $rule := dict "name" "ocsf-collector" "to" (list (dict "pods" (dict "namespaceSelector" (dict "matchLabels" (dict "kubernetes.io/metadata.name" .collector.namespace)) "podSelector" (dict "matchLabels" .collector.podLabels)))) "ports" (list (dict "portNumber" (dict "protocol" "TCP" "port" (int .collector.port)))) }} +{{- $_ := set $policy.network "egress" (append $policy.network.egress $rule) }} +{{- $_ := set $policy "ocsfEndpoint" .ocsfEndpoint }} +{{- if .agentTraces }}{{- $_ := set $policy "agentTraceEndpoint" .ocsfEndpoint }}{{- end }} +{{- end }}{{- end }} {{- $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 }} @@ -119,6 +146,7 @@ data: {{- $v := $values | fromJson }} {{- if and $site.lifecycleVersion $slot.modelInput }}{{- $_ := set $v "shareGateForModelSelection" true }}{{- end }} {{- $_ := set $v.identity "workspace" $slot.workspace }}{{- $_ := set $v.identity "sandbox" $slot.sandbox }} +{{- $_ := set $v "receipts" $receipts }} {{- $values = toJson $v }} {{- end }} {{- if regexMatch "@[A-Z_]+@" $values }}{{ fail "unknown site value placeholder" }}{{ end }} diff --git a/charts/saw-portal-container/values.yaml b/charts/saw-portal-container/values.yaml index ec815deab..27b17574e 100644 --- a/charts/saw-portal-container/values.yaml +++ b/charts/saw-portal-container/values.yaml @@ -5,6 +5,163 @@ vaultPrefix: "" secretStore: vault-backend 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 + gatewayVersion: 0.1.10-rhaiv.0 + supervisorImage: quay.io/opendatahub/odh-openshell-supervisor@sha256:c2c8e9d3d19a1612074df0f637078064cff45b92d35c74b116a72fb503b3c1bc + # TEMPORARY carry of odh-openshell-sandbox v0.1.10-rhaiv.0 with the auxv + # warm-up fix (openshell-sandbox-carry/, CI image tag sha-e8bfde1f): the official + # build's network broker panics on every connect on RHEL 9 kernels. Return to + # quay.io/opendatahub/odh-openshell-sandbox once a fixed build is released. + runtimeImage: ghcr.io/sauagarwa/saw-openshell-sandbox@sha256:402b9727a690e8c8a10fb10c0cee21e96ea034b652d6c7d5b3f06eba916c9881 + +# 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 + # Best-effort audit: the gateway and each sandbox's supervisor export OCSF + # events over OTLP/gRPC to the pattern's collector (charts/saw-telemetry). + # ocsfEndpoint: "" turns export off. + telemetry: + ocsfEndpoint: http://saw-ocsf-collector.openshell-agents.svc:4317 + # Also relay the agent's own OpenTelemetry traces through the supervisor + # to the same collector (needs ocsfEndpoint). + agentTraces: true + collector: + namespace: openshell-agents + podLabels: + app.kubernetes.io/name: saw-ocsf-collector + app.kubernetes.io/component: opentelemetry-collector + port: 4317 + # How the workspace's platform pods reach the Kubernetes API. The default + # selects the control-plane nodes, so nothing is cluster specific. On a + # cluster whose API is not served from its own nodes (a hosted control + # plane), list the API addresses instead: [{networks: ["/32"]}]. + kubernetesApi: + priority: 70 + port: 6443 + to: + - nodes: {matchExpressions: [{key: node-role.kubernetes.io/control-plane, operator: Exists}]} + automaticEnrollment: + # Enrollment policy (enabled, autoApprove), the runtime image, build + # namespace and relay Keycloak settings come from the site itself + # (saw-users containerDefaults), because the workspace projector reads and + # checks them before this chart's defaults are merged. Only the compute + # request for the enrollment Job defaults here. + resources: + requests: {cpu: 500m, memory: 1Gi} + limits: {cpu: "2", memory: 4Gi} + # The relay's egress besides its gateway: DNS, and HTTPS for the issuer. + # Its Kubernetes API access comes from kubernetesApi. + relay: + egress: + - to: + - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: openshift-dns}} + podSelector: {matchLabels: {dns.operator.openshift.io/daemonset-dns: default}} + ports: [{protocol: UDP, port: 5353}, {protocol: TCP, port: 5353}, {protocol: UDP, port: 53}, {protocol: TCP, port: 53}] + - to: [{ipBlock: {cidr: 0.0.0.0/0}}] + ports: [{protocol: TCP, port: 443}] + stack: + identity: + values: + enabled: true + ownerID: '@INSTALLATION@' + # DNS only: the Kubernetes API is reached through kubernetesApi. + network: + bootstrapEgress: + - to: + - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: openshift-dns}} + podSelector: {matchLabels: {dns.operator.openshift.io/daemonset-dns: default}} + ports: [{protocol: UDP, port: 5353}, {protocol: TCP, port: 5353}, {protocol: UDP, port: 53}, {protocol: TCP, port: 53}] + 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} + oidc: + issuerUrl: 'https://openshell-keycloak-ingress-saw-keycloak.apps.@DOMAIN@/realms/openshell' + 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: + # DNS, and HTTPS for the OIDC issuer (any address: the issuer may + # sit behind a load balancer or an ingress virtual IP). The API + # comes from kubernetesApi; the interceptor rule is added by + # stack.yaml. + gatewayEgress: + - to: + - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: openshift-dns}} + podSelector: {matchLabels: {dns.operator.openshift.io/daemonset-dns: default}} + ports: [{protocol: UDP, port: 5353}, {protocol: TCP, port: 5353}, {protocol: UDP, port: 53}, {protocol: TCP, port: 53}] + - to: [{ipBlock: {cidr: 0.0.0.0/0}}] + ports: [{protocol: TCP, port: 443}] + 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 + # Volumes use the cluster's default class unless storageClass is set. + # The exchange volume needs a shared filesystem (ReadWriteMany): + # make saw-init creates saw-shared as a copy of the cluster's. + exchangeStorageClass: saw-shared + identity: + subject: '@SUBJECT@' + username: '@OWNER@' + workspace: agent + sandbox: audited diff --git a/charts/saw-runtime-policies/templates/admin-network-policy.yaml b/charts/saw-runtime-policies/templates/admin-network-policy.yaml index 48694cfc2..2b50d2dce 100644 --- a/charts/saw-runtime-policies/templates/admin-network-policy.yaml +++ b/charts/saw-runtime-policies/templates/admin-network-policy.yaml @@ -24,6 +24,22 @@ spec: action: Pass to: {{ .to | toYaml | nindent 8 }} ports: {{ .ports | toYaml | nindent 8 }} +{{- end }} +{{- if .Values.network.publicHTTPS }} + # The supervisor reaches providers itself and OpenShell enforces which + # hosts each sandbox may use (as OpenShell's own supervisor fence leaves + # egress open). Private ranges stay closed unless passed above. + - name: deny-private-networks + action: Deny + to: + - networks: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10", + "169.254.0.0/16", "127.0.0.0/8", "0.0.0.0/8", "fc00::/7", "fe80::/10", "::1/128"] + - name: public-https + action: Pass + to: + - networks: ["0.0.0.0/0", "::/0"] + ports: + - portNumber: {protocol: TCP, port: 443} {{- end }} - name: deny-other-egress action: Deny diff --git a/charts/saw-runtime-policies/templates/runtime-validation.yaml b/charts/saw-runtime-policies/templates/runtime-validation.yaml index baa4fb3ae..8c60b6653 100644 --- a/charts/saw-runtime-policies/templates/runtime-validation.yaml +++ b/charts/saw-runtime-policies/templates/runtime-validation.yaml @@ -177,7 +177,18 @@ spec: 'OPENSHELL_SANDBOX_ID','OPENSHELL_SANDBOX','OPENSHELL_MAIN_PROCESS_SPEC','OPENSHELL_K8S_SA_TOKEN_FILE', 'OPENSHELL_SSH_SOCKET_PATH','OPENSHELL_SSH_SOCKET_SHARED','OPENSHELL_PROXY_TLS_DIR','OPENSHELL_PROXY_CA_CERT', 'OPENSHELL_PROXY_CA_KEY','OPENSHELL_LOG_LEVEL','OPENSHELL_TELEMETRY_ENABLED','OPENSHELL_NETWORK_RUNTIME_CAPABILITIES', - 'OPENSHELL_TLS_CA','OPENSHELL_GATEWAY_TLS_SERVER_NAME','OPENSHELL_GATEWAY_NAME']) && + 'OPENSHELL_TLS_CA','OPENSHELL_GATEWAY_TLS_SERVER_NAME','OPENSHELL_GATEWAY_NAME', + 'OPENSHELL_ATTACH_REQUEST_TIMEOUT_SECONDS'{{ if .Values.ocsfEndpoint }}, + 'OPENSHELL_OTLP_OCSF_ENDPOINT'{{ end }}{{ if .Values.agentTraceEndpoint }}, + 'OPENSHELL_OTLP_AGENT_ENDPOINT'{{ end }}]) && + object.spec.containers[0].env.all(e, e.name != 'OPENSHELL_ATTACH_REQUEST_TIMEOUT_SECONDS' || + (has(e.value) && e.value.matches('^[1-9][0-9]{0,4}$'))) && + {{- if .Values.ocsfEndpoint }} + object.spec.containers[0].env.all(e, e.name != 'OPENSHELL_OTLP_OCSF_ENDPOINT' || e.value == {{ .Values.ocsfEndpoint | toJson }}) && + {{- end }} + {{- if .Values.agentTraceEndpoint }} + object.spec.containers[0].env.all(e, e.name != 'OPENSHELL_OTLP_AGENT_ENDPOINT' || e.value == {{ .Values.agentTraceEndpoint | toJson }}) && + {{- end }} object.spec.volumes.all(v, has(v.emptyDir) || (v.name == 'bootstrap' && has(v.secret) && v.secret.secretName.matches('^os-supervisor-' + variables.pair + '-[a-f0-9]{12}$')) || (v.name == 'client-tls' && has(v.secret) && v.secret.secretName == {{ .Values.serverTLSSecret | toJson }} && @@ -272,8 +283,13 @@ spec: message: Only this workspace gateway may create supervisor Pods. reason: Forbidden - expression: >- +{{- if eq .Values.mode "kata" }} + variables.role != 'supervisor' || (has(object.spec.runtimeClassName) && object.spec.runtimeClassName == {{ .Values.workloadRuntimeClassName | toJson }}) + message: Kata supervisors require the approved RuntimeClass, in a VM of their own. +{{- else }} variables.role != 'supervisor' || !has(object.spec.runtimeClassName) || object.spec.runtimeClassName == '' message: Stock supervisor Pods must use the default container runtime. +{{- end }} reason: Forbidden - expression: >- {{- if eq .Values.mode "kata" }} diff --git a/charts/saw-runtime-policies/values.schema.json b/charts/saw-runtime-policies/values.schema.json index a8834a079..2aae0b06b 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": [ @@ -123,6 +126,14 @@ "additionalProperties": false } }, + "agentTraceEndpoint": { + "type": "string", + "pattern": "^(https?://[a-z0-9.-]+:[0-9]+)?$" + }, + "ocsfEndpoint": { + "type": "string", + "pattern": "^(https?://[a-z0-9.-]+:[0-9]+)?$" + }, "supervisorCommand": { "type": "array", "items": { diff --git a/charts/saw-runtime-policies/values.yaml b/charts/saw-runtime-policies/values.yaml index 6ee07a152..ff403e1f9 100644 --- a/charts/saw-runtime-policies/values.yaml +++ b/charts/saw-runtime-policies/values.yaml @@ -10,9 +10,14 @@ network: # Required administrator allocation, unique among overlapping ANPs (0..99). priority: null # ANP egress peers/ports. The chart fixes each action to Pass, then denies - # all remaining IPv4/IPv6. Populate actual DNS, gateway, workload-boundary, - # credential-proxy and approved external destinations before enabling. + # all remaining IPv4/IPv6. Populate actual DNS, gateway, workload-boundary + # and approved in-cluster destinations before enabling. egress: [] + # Let supervisors reach public HTTPS (provider APIs). Credentials go only to + # their provider profile's endpoints, and the runtime controller refuses a + # credentialed profile whose endpoints are not the approved set (the shipped + # governed profile, or the site's custom inference host). + publicHTTPS: false # Filled by the shared composition from the approved BOM and gateway configuration. sandboxControllerUsername: system:serviceaccount:agent-sandbox-system:agent-sandbox-controller @@ -21,5 +26,9 @@ supervisorImage: "" runtimeImage: "" serverTLSSecret: "" supervisorCommand: [] +# OCSF collector the gateway passes to supervisors; empty means none may be set. +ocsfEndpoint: "" +# Collector the agent trace relay forwards to; empty means none may be set. +agentTraceEndpoint: "" preparationImage: "" forwarderImage: "" diff --git a/charts/saw-telemetry/Chart.yaml b/charts/saw-telemetry/Chart.yaml new file mode 100644 index 000000000..f2da3cf60 --- /dev/null +++ b/charts/saw-telemetry/Chart.yaml @@ -0,0 +1,6 @@ +apiVersion: v2 +name: saw-telemetry +description: OpenTelemetry collector for the OCSF events that OpenShell gateways and supervisors export +type: application +version: 0.1.0 +appVersion: "0.1.0" diff --git a/charts/saw-telemetry/templates/collector.yaml b/charts/saw-telemetry/templates/collector.yaml new file mode 100644 index 000000000..3f081ab6c --- /dev/null +++ b/charts/saw-telemetry/templates/collector.yaml @@ -0,0 +1,35 @@ +{{- if not .Values.exporters }}{{ fail "at least one exporter is required" }}{{ end }} +# Managed by the Red Hat build of OpenTelemetry operator. Best-effort: OpenShell +# drops events it cannot export, and nothing waits for this collector. +apiVersion: opentelemetry.io/v1beta1 +kind: OpenTelemetryCollector +metadata: + name: {{ .Values.name }} + annotations: + argocd.argoproj.io/sync-options: SkipDryRunOnMissingResource=true +spec: + mode: deployment + replicas: {{ .Values.replicas }} + resources: {{ .Values.resources | toJson }} + config: + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + processors: + batch: {} + exporters: {{ .Values.exporters | toJson }} + service: + pipelines: + # OCSF events from gateways and supervisors. + logs: + receivers: [otlp] + processors: [batch] + exporters: {{ keys .Values.exporters | sortAlpha | toJson }} + # Agent traces from the OpenShell agent trace relay, tagged + # openshell.telemetry.source=agent and openshell.sandbox.id. + traces: + receivers: [otlp] + processors: [batch] + exporters: {{ keys .Values.exporters | sortAlpha | toJson }} diff --git a/charts/saw-telemetry/values.yaml b/charts/saw-telemetry/values.yaml new file mode 100644 index 000000000..6d311076f --- /dev/null +++ b/charts/saw-telemetry/values.yaml @@ -0,0 +1,14 @@ +# The collector OpenShell gateways and sandbox supervisors send OCSF events to +# (OTLP/gRPC on 4317). Its name gives the Service saw-ocsf-collector, which the +# container site's telemetry.ocsfEndpoint points at. +name: saw-ocsf +replicas: 1 +# Where the events go. The debug exporter writes them to the collector's log +# (oc logs deploy/saw-ocsf-collector); replace it with your SIEM or log store, +# for example an otlp or otlphttp exporter. +exporters: + debug: + verbosity: basic +resources: + requests: {cpu: 50m, memory: 128Mi} + limits: {memory: 512Mi} diff --git a/charts/saw-users/files/governed-profiles.json b/charts/saw-users/files/governed-profiles.json deleted file mode 100644 index 6819eb497..000000000 --- a/charts/saw-users/files/governed-profiles.json +++ /dev/null @@ -1,550 +0,0 @@ -{ - "anthropic": { - "binaries": [ - "/usr/bin/curl", - "/usr/local/bin/curl", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "inference", - "credentials": [ - { - "auth_style": "header", - "description": "Anthropic API key", - "env_vars": [ - "ANTHROPIC_API_KEY" - ], - "header_name": "x-api-key", - "name": "api_key", - "required": true - } - ], - "description": "Anthropic inference API", - "discovery": { - "credentials": [ - "api_key" - ] - }, - "display_name": "Anthropic", - "endpoints": [ - { - "access": "read-write", - "enforcement": "enforce", - "host": "api.anthropic.com", - "port": 443, - "protocol": "rest" - } - ], - "id": "anthropic", - "inference_capable": true - }, - "brave": { - "binaries": [ - "/usr/bin/curl", - "/usr/local/bin/curl", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "other", - "credentials": [ - { - "auth_style": "header", - "description": "Brave Search API key", - "env_vars": [ - "BRAVE_API_KEY" - ], - "header_name": "X-Subscription-Token", - "name": "api_key", - "required": true - } - ], - "description": "Brave Search API access for governed sandbox agents", - "discovery": { - "credentials": [ - "api_key" - ] - }, - "display_name": "Brave Search", - "endpoints": [ - { - "access": "read-only", - "enforcement": "enforce", - "host": "api.search.brave.com", - "port": 443, - "protocol": "rest" - } - ], - "id": "brave" - }, - "gemini": { - "binaries": [ - "/usr/bin/gemini", - "/usr/lib/node_modules/@google/gemini-cli/dist/index.js", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "other", - "credentials": [ - { - "auth_style": "query", - "description": "Google Gemini API key", - "env_vars": [ - "GEMINI_API_KEY" - ], - "name": "api_key", - "query_param": "key", - "required": true - } - ], - "description": "Google Gemini AI and Vertex AI API access", - "discovery": { - "credentials": [ - "api_key" - ] - }, - "display_name": "Google Gemini", - "endpoints": [ - { - "access": "read-write", - "enforcement": "enforce", - "host": "generativelanguage.googleapis.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-write", - "enforcement": "enforce", - "host": "*-aiplatform.googleapis.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-write", - "enforcement": "enforce", - "host": "cloudcode-pa.googleapis.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "accounts.google.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "oauth2.googleapis.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "www.googleapis.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "iamcredentials.googleapis.com", - "port": 443, - "protocol": "rest" - } - ], - "id": "gemini" - }, - "github": { - "binaries": [ - "/usr/bin/gh", - "/usr/local/bin/gh", - "/usr/bin/git", - "/usr/local/bin/git", - "/usr/bin/curl", - "/usr/local/bin/curl" - ], - "category": "source_control", - "credentials": [ - { - "auth_style": "bearer", - "description": "GitHub token", - "env_vars": [ - "GITHUB_TOKEN", - "GH_TOKEN" - ], - "header_name": "authorization", - "name": "api_token", - "required": true - } - ], - "description": "GitHub API and Git operations", - "discovery": { - "credentials": [ - "api_token" - ] - }, - "display_name": "GitHub", - "endpoints": [ - { - "access": "read-only", - "enforcement": "enforce", - "host": "api-1.github.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "api.github.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "api.github.com", - "path": "/graphql", - "port": 443, - "protocol": "graphql" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "github.com", - "port": 443, - "protocol": "rest" - } - ], - "id": "github" - }, - "gmail": { - "binaries": [ - "/usr/bin/curl", - "/usr/local/bin/curl", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "messaging", - "credentials": [ - { - "auth_style": "bearer", - "description": "Gmail OAuth access token (gmail.readonly)", - "env_vars": [ - "GMAIL_ACCESS_TOKEN" - ], - "header_name": "authorization", - "name": "access_token", - "refresh": { - "material": [ - { - "description": "Google OAuth client ID", - "name": "client_id", - "required": true - }, - { - "description": "Google OAuth client secret", - "name": "client_secret", - "required": true, - "secret": true - }, - { - "description": "Google OAuth refresh token (scope gmail.readonly)", - "name": "refresh_token", - "required": true, - "secret": true - } - ], - "max_lifetime_seconds": 3600, - "refresh_before_seconds": 300, - "strategy": "oauth2_refresh_token", - "token_url": "https://oauth2.googleapis.com/token" - }, - "required": true - } - ], - "description": "Read-only Gmail API access for governed sandbox agents", - "discovery": { - "credentials": [ - "access_token" - ] - }, - "display_name": "Gmail", - "endpoints": [ - { - "enforcement": "enforce", - "host": "gmail.googleapis.com", - "port": 443, - "protocol": "rest", - "rules": [ - { - "allow": { - "method": "GET", - "path": "/gmail/v1/users/me/profile" - } - }, - { - "allow": { - "method": "GET", - "path": "/gmail/v1/users/me/labels" - } - }, - { - "allow": { - "method": "GET", - "path": "/gmail/v1/users/me/messages" - } - }, - { - "allow": { - "method": "GET", - "path": "/gmail/v1/users/me/messages/*" - } - }, - { - "allow": { - "method": "GET", - "path": "/gmail/v1/users/me/threads" - } - }, - { - "allow": { - "method": "GET", - "path": "/gmail/v1/users/me/threads/*" - } - } - ] - } - ], - "id": "gmail" - }, - "nvidia": { - "binaries": [ - "/usr/bin/curl", - "/usr/local/bin/curl", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "inference", - "credentials": [ - { - "auth_style": "bearer", - "description": "NVIDIA API key", - "env_vars": [ - "NVIDIA_API_KEY" - ], - "header_name": "authorization", - "name": "api_key", - "required": true - } - ], - "description": "NVIDIA API inference endpoints", - "discovery": { - "credentials": [ - "api_key" - ] - }, - "display_name": "NVIDIA Endpoints", - "endpoints": [ - { - "access": "read-write", - "enforcement": "enforce", - "host": "integrate.api.nvidia.com", - "port": 443, - "protocol": "rest" - } - ], - "id": "nvidia", - "inference_capable": true - }, - "openai": { - "binaries": [ - "/usr/bin/curl", - "/usr/local/bin/curl", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "inference", - "credentials": [ - { - "auth_style": "bearer", - "description": "OpenAI API key", - "env_vars": [ - "OPENAI_API_KEY" - ], - "header_name": "authorization", - "name": "api_key", - "required": true - } - ], - "description": "OpenAI inference API", - "discovery": { - "credentials": [ - "api_key" - ] - }, - "display_name": "OpenAI", - "endpoints": [ - { - "access": "read-write", - "enforcement": "enforce", - "host": "api.openai.com", - "port": 443, - "protocol": "rest" - } - ], - "id": "openai", - "inference_capable": true - }, - "slack": { - "binaries": [ - "/usr/bin/curl", - "/usr/local/bin/curl", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "messaging", - "credentials": [ - { - "auth_style": "bearer", - "description": "Slack bot or user token", - "env_vars": [ - "SLACK_BOT_TOKEN", - "SLACK_TOKEN" - ], - "header_name": "authorization", - "name": "api_token", - "refresh": { - "material": [ - { - "description": "Slack app client ID", - "name": "client_id", - "required": true - }, - { - "description": "Slack app client secret", - "name": "client_secret", - "required": true, - "secret": true - }, - { - "description": "Slack refresh token (xoxe-...)", - "name": "refresh_token", - "required": true, - "secret": true - } - ], - "max_lifetime_seconds": 43200, - "refresh_before_seconds": 600, - "strategy": "oauth2_refresh_token", - "token_url": "https://slack.com/api/oauth.v2.access" - }, - "required": true - } - ], - "description": "Read-only Slack Web API access for governed sandbox agents", - "discovery": { - "credentials": [ - "api_token" - ] - }, - "display_name": "Slack", - "endpoints": [ - { - "enforcement": "enforce", - "host": "slack.com", - "port": 443, - "protocol": "rest", - "rules": [ - { - "allow": { - "method": "GET", - "path": "/api/auth.test" - } - }, - { - "allow": { - "method": "GET", - "path": "/api/team.info" - } - }, - { - "allow": { - "method": "GET", - "path": "/api/users.info" - } - }, - { - "allow": { - "method": "GET", - "path": "/api/conversations.list" - } - }, - { - "allow": { - "method": "GET", - "path": "/api/conversations.info" - } - }, - { - "allow": { - "method": "GET", - "path": "/api/conversations.history" - } - }, - { - "allow": { - "method": "GET", - "path": "/api/conversations.replies" - } - } - ] - } - ], - "id": "slack" - }, - "web-search": { - "binaries": [ - "/usr/bin/curl", - "/usr/local/bin/curl", - "/usr/bin/node", - "/usr/bin/node-*", - "/usr/local/bin/node" - ], - "category": "other", - "description": "Tavily and Brave Search API endpoints and plugin registry", - "display_name": "Web Search", - "endpoints": [ - { - "access": "read-only", - "enforcement": "enforce", - "host": "api.tavily.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "api.search.brave.com", - "port": 443, - "protocol": "rest" - }, - { - "access": "read-only", - "enforcement": "enforce", - "host": "registry.npmjs.org", - "port": 443, - "protocol": "rest" - } - ], - "id": "web-search" - } -} diff --git a/charts/saw-users/files/preflight.py b/charts/saw-users/files/preflight.py index c32862180..dc499183c 100644 --- a/charts/saw-users/files/preflight.py +++ b/charts/saw-users/files/preflight.py @@ -196,24 +196,33 @@ def check_observations(mode, observations): return tuple(required) +# Reviewed sites pin every chart to a full commit SHA. An autoApprove +# (development) site may follow a branch instead: saw-users and portal defaults +# use global.targetRevision when a site sets no revision. +PINNED_REVISION = r"[a-f0-9]{40}" +BRANCH_REVISION = r"[a-f0-9]{40}|[A-Za-z0-9][A-Za-z0-9._/-]*" + + def configuration_facts(site): """Check site-owned inputs that do not require cluster access.""" if not isinstance(site, dict): return {key: False for key in ("network", "storage", "secrets", "registry", "providerEgress", "revisions")} stack = site.get("stack") if isinstance(site.get("stack"), dict) else {} + enrollment = site.get("automaticEnrollment") or {} + revision_pattern = BRANCH_REVISION if isinstance(enrollment, dict) and enrollment.get( + "autoApprove") is True else PINNED_REVISION revisions = [item.get("revision") for item in stack.values() if isinstance(item, dict)] - required_components = ("identity", "policy", "proxy", "gateway", "audit") + required_components = ("identity", "policy", "gateway", "audit") revision_pin = all(isinstance(stack.get(name), dict) for name in required_components) and all( isinstance(stack[name].get("revision"), str) - and re.fullmatch(r"[a-f0-9]{40}", stack[name]["revision"]) + and re.fullmatch(revision_pattern, stack[name]["revision"]) for name in required_components) and bool(revisions) and len(revisions) == len(stack) and all( - isinstance(value, str) and re.fullmatch(r"[a-f0-9]{40}", value) for value in revisions) - enrollment = site.get("automaticEnrollment") or {} + isinstance(value, str) and re.fullmatch(revision_pattern, value) for value in revisions) if enrollment and not isinstance(enrollment, dict): revision_pin = False elif enrollment: - revision_pin = revision_pin and bool(re.fullmatch(r"[a-f0-9]{40}", str(enrollment.get("revision", "")))) + revision_pin = revision_pin and bool(re.fullmatch(revision_pattern, str(enrollment.get("revision", "")))) image_values = [] storage_values = [] @@ -233,28 +242,20 @@ def walk(value, path=()): walk(child, path) walk(site) - declared_hosts = site.get("providerAllowHosts") - policy = site.get("providerPolicy") - clean_hosts = (isinstance(declared_hosts, list) and bool(declared_hosts) - and all(isinstance(host, str) and host and "*" not in host - for host in declared_hosts) - and (policy is None or (isinstance(policy, dict) - and isinstance(policy.get("allowHosts"), list) - and all(isinstance(host, str) for host in policy["allowHosts"]) - and set(policy["allowHosts"]) == set(declared_hosts)))) - proxy = stack.get("proxy") or {} - proxy_values = proxy.get("values") or {} if isinstance(proxy, dict) else {} - bootstrap_egress = ((proxy_values.get("network") or {}).get("bootstrapEgress") - if isinstance(proxy_values, dict) else None) + # OpenShell decides where each credential may go (provider profiles); the + # site only lists which Secret backs which provider type. + bindings = site.get("credentialBindings") + clean_bindings = (isinstance(bindings, list) and all( + isinstance(b, dict) and {"secret", "key", "type"} <= set(b) <= {"secret", "key", "type", "refresh"} + and all(isinstance(v, str) and v for v in b.values()) for b in bindings)) storage_ok = bool(storage_values) and all(value.strip() for value in storage_values) return { - "network": bool(stack.get("policy")) and isinstance(bootstrap_egress, list) - and bool(bootstrap_egress), + "network": bool(stack.get("policy")), "storage": storage_ok, "secrets": isinstance(site.get("secretStore", "vault-backend"), str) and bool(site.get("secretStore", "vault-backend")), "registry": bool(image_values) and all("@sha256:" in image for image in image_values), - "providerEgress": clean_hosts, + "providerEgress": clean_bindings, "revisions": revision_pin, } diff --git a/charts/saw-users/files/projector.py b/charts/saw-users/files/projector.py index 23282e0eb..91b181706 100644 --- a/charts/saw-users/files/projector.py +++ b/charts/saw-users/files/projector.py @@ -85,11 +85,35 @@ def previous(self, owner): return workspace.previous_child(app, appset, owner) +def bind_runtime_class(site, read): + """Bind an autoApprove Kata site to the live RuntimeClass it names. + + autoApprove already trusts the first boundary enrollment observes, and + enrollment keeps failing closed on any later change. A reviewed site must + carry the operator's explicit {name, uid, sha256} approval instead. + """ + approval = site.get("kataRuntimeClass") if isinstance(site, dict) else None + if not isinstance(approval, dict) or set(approval) != {"name"}: + return site # explicit approval (or invalid input, rejected later) + automatic = site.get("automaticEnrollment") or {} + if automatic.get("enabled") is False or automatic.get("autoApprove") is not True: + raise preflight.PreflightError("RuntimeClassApprovalMissing") + if not callable(read): + raise preflight.PreflightError("RuntimeClassUnavailable") + observed = read("/apis/node.k8s.io/v1/runtimeclasses/" + approval["name"]) + if not isinstance(observed, dict) or not observed: + raise preflight.PreflightError("RuntimeClassUnavailable") + bound = {"name": approval["name"], "uid": (observed.get("metadata") or {}).get("uid"), + "sha256": preflight.runtime_placement_digest(observed)} + preflight.check_runtime_class(bound, observed) + return {**site, "kataRuntimeClass": bound} + + 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": @@ -186,6 +210,8 @@ def parameters(config, catalog, read): try: profile = (owner.get("profiles") or [None])[0] preflight.verify_profile_image_access(site, profile, catalog) + if owner.get("values", {}).get("deployment", {}).get("mode") == "kata": + site = bind_runtime_class(site, getattr(read, "preflight_resource", None)) values = workspace.project_workspace(owner, defaults, site, catalog, read, getattr(read, "previous", None)) live_read = getattr(read, "preflight_resource", None) if callable(live_read): diff --git a/charts/saw-users/files/workspace.py b/charts/saw-users/files/workspace.py index bc86b4d01..1addd71e3 100644 --- a/charts/saw-users/files/workspace.py +++ b/charts/saw-users/files/workspace.py @@ -5,6 +5,7 @@ resource application. This module never discovers or changes cluster state. """ import hashlib +import ipaddress import json import re import urllib.parse @@ -18,9 +19,9 @@ class WorkspaceError(ValueError): SAFE_FAILURE_REASONS = frozenset({ "ProfileRejected", "InvalidPlan", "PlacementRejected", "IdentityConflict", "InvalidIntent", "StaleIntent", "ReconcilerStateRejected", "GatewayMismatch", - "ProviderProfileMismatch", "WorkspaceRejected", "ProviderRejected", + "ProviderProfileMismatch", "ProviderRefreshFailed", "WorkspaceRejected", "ProviderRejected", "SandboxRejected", "SandboxStateMismatch", "SandboxDrift", "CoreRejected", - "CoreFailure", + "CoreFailure", "ReenrollRequired", }) SAFE_RPC_CODES = frozenset({ "NOT_FOUND", "ALREADY_EXISTS", "UNAVAILABLE", "DEADLINE_EXCEEDED", "ABORTED", @@ -82,24 +83,40 @@ def public_model_inputs(profile, secrets): return values -def approved_endpoint(profile, secrets, boundary): +CUSTOM_INFERENCE_URL = re.compile(r"https://[a-z0-9-]+(?:\.[a-z0-9-]+)+(?::443)?(?:/[A-Za-z0-9_-]+)*/v1") + + +def custom_inference_url(endpoint): + """The workspace's own OpenAI-compatible base URL: HTTPS, a DNS name, port 443, ending /v1. + + Which host may receive the API key is not decided here: the custom-inference + governance profile names it, and the runtime controller refuses a workspace + whose URL host is not that profile's only endpoint (ProviderProfileMismatch). + """ + if not isinstance(endpoint, str) or not CUSTOM_INFERENCE_URL.fullmatch(endpoint): + raise WorkspaceError("custom inference needs an HTTPS base URL ending in /v1") + try: + ipaddress.ip_address(urllib.parse.urlsplit(endpoint).hostname) + except ValueError: + return endpoint + raise WorkspaceError("custom inference needs an HTTPS base URL ending in /v1, with a DNS name") + + +def approved_endpoint(profile, secrets): + """The endpoint URL the owner entered (public metadata), if the profile takes one.""" refs = {sb["endpointInput"] for _, sb in enabled_catalog_sandboxes(profile) if sb.get("endpointInput")} if not refs: return None - endpoint = boundary.get("inferenceBaseURL", "") - if not isinstance(endpoint, str) or not re.fullmatch( - r"https://[a-z0-9-]+(?:\.[a-z0-9-]+)+(?::443)?(?:/[A-Za-z0-9_-]+)*/v1", endpoint): - raise WorkspaceError("site has no approved custom inference endpoint") - if boundary.get("allowHosts") != [urllib.parse.urlsplit(endpoint).hostname]: - raise WorkspaceError("custom inference requires a dedicated broker host") + endpoints = set() for ref in refs: secret, key = ref.split(".", 1) fields = profile["secrets"][secret]["fields"] if not any(f["key"] == key and f["kind"] == "url" for f in fields): raise WorkspaceError("endpoint input must be public URL metadata") - if secrets.get(secret, {}).get(key, "").rstrip("/") != endpoint: - raise WorkspaceError("endpoint differs from the site-approved custom inference URL") - return endpoint + endpoints.add(secrets.get(secret, {}).get(key, "").rstrip("/")) + if len(endpoints) != 1: + raise WorkspaceError("custom inference endpoint inputs disagree") + return custom_inference_url(endpoints.pop()) def enrolled_site(site, ws, read): @@ -123,17 +140,18 @@ def publication(name): if data: raise WorkspaceError("cannot disable enrollment of a bound workspace; use desiredState") return fresh - for key, kind in (("reference", dict), ("relay", dict), ("revision", str), - ("image", str), ("buildNamespace", str)): + auto = a.get("autoApprove") is True + for key, kind in ((() if auto else (("reference", dict),)) + (("relay", dict), ("revision", str), + ("image", str), ("buildNamespace", str))): if not isinstance(a.get(key), kind) or not a[key]: raise WorkspaceError(f"container site for {ws['name']} requires automaticEnrollment.{key}") if not data: return fresh bound=json.loads(data["binding.json"]) - if set(bound)!={"registration","intent","approved","gatewayCA"} or bound["registration"]!=reg or set(bound["approved"])!=set(a["reference"]): + if set(bound)!={"registration","intent","approved","gatewayCA"} or bound["registration"]!=reg or (not auto and set(bound["approved"])!=set(a["reference"])): raise WorkspaceError("invalid published enrollment") intent=bound["intent"] - if intent["bindings"]["ownerID"]!=install or intent["bindings"]["namespace"]!="saw-"+ws["name"] or intent["bindings"]["ownerSubject"]!=ws["ownerSubject"] or intent["profileRef"]["sha256"]!=site.get("selectedDigest",a.get("profileSHA256")): + if intent["bindings"]["ownerID"]!=install or intent["bindings"]["namespace"]!="saw-"+ws["name"] or intent["bindings"]["ownerSubject"]!=ws["ownerSubject"] or (not auto and intent["profileRef"]["sha256"]!=site.get("selectedDigest",a.get("profileSHA256"))): raise WorkspaceError("published intent does not belong to this workspace") subjects = {target["subjectMap"]:publication(target["subjectMap"]).get("subject", "") for target in site.get("targets",{}).values() if target["ui"]} @@ -204,7 +222,7 @@ def project_workspace(workspace, defaults, site, catalog, read=None, previous=No # Inputs include operator configuration and immutable API publications. # Do not include arbitrary values (especially JSON bodies) in diagnostics. detail = f"missing {exc.args[0]}" if isinstance(exc, KeyError) and exc.args[0] in { - "subject", "registration", "installationID", "reference", "allowHosts", "bindings", + "subject", "registration", "installationID", "reference", "bindings", "binding.json", "profileRef", "sha256", "initialModelInputs"} else "invalid site or publication" raise WorkspaceError(f"workspace {workspace.get('name', '?')}: {detail}") from None @@ -241,11 +259,26 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): validate_runtime_placement(mode, site) automatic = site.get("automaticEnrollment", {}) selected, *extra = ws.get("profiles", []) or [None] - foundation = automatic.get("enabled") is False + foundation = automatic.get("enabled") is False or automatic.get("autoApprove") is True if extra or selected not in catalog or not foundation and selected not in automatic.get("approvedProfiles", {}): raise WorkspaceError("container requires one approved BOM profile") if not ws.get("registration") or not ws.get("installationID"): raise WorkspaceError("container requires a registration and installation identity") + # As the portal does at registration: a dedicated-endpoint profile (such as + # custom-inference) has no web-search credential unless the entry asks for it. + if "dedicatedEndpointSecrets" in catalog[selected] and "webSearch" not in ws: + ws["webSearch"] = {"enabled": False} + # The runtime compiles the model from public inputs, never from the Secret. + # The portal reads it from the form; a static entry must name it. + given = ws.get("initialModelInputs") if ws.get("lifecycleVersion") == 1 else ws.get("modelInputs") + for _, sandbox in enabled_catalog_sandboxes(catalog[selected]): + key = sandbox.get("modelInput") + if not key: + continue + secret, field = key.split(".", 1) + definition = next((f for f in catalog[selected]["secrets"][secret]["fields"] if f["key"] == field), {}) + if definition.get("required") and not definition.get("default") and not (given or {}).get(key): + raise WorkspaceError(f"{ws['name']}: set modelInputs.{key} (the model this profile requires)") overrides = site.get("profileImageOverrides", {}).get(selected, {}) if overrides: ws["imageOverrides"] = overrides @@ -259,12 +292,19 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): target["image"] = overrides.get(target["sandbox"], target["image"]) boundary = site.get("profileBoundaries", {}).get(selected) if boundary: - site = {**site, "providerAllowHosts": boundary["allowHosts"], - "automaticEnrollment": {**automatic, "reference": boundary["reference"]}} - if ws.get("customInferenceURL"): - if not boundary or boundary.get("inferenceBaseURL") != ws["customInferenceURL"]: - raise WorkspaceError("endpoint differs from the site-approved custom inference URL") - site["customInferenceURL"] = ws["customInferenceURL"] + # autoApprove sites have no operator-reviewed reference to pin. + reviewed = {"reference": boundary["reference"]} if "reference" in boundary or \ + automatic.get("autoApprove") is not True else {} + site = {**site, "automaticEnrollment": {**automatic, **reviewed}} + # A profile with an endpoint input (custom-inference) uses the owner's own + # URL: the portal form value, or customInferenceURL in a static entry. The + # custom-inference governance profile approves its host at run time. + if any(sb.get("endpointInput") for _, sb in enabled_catalog_sandboxes(catalog[selected])): + if not ws.get("customInferenceURL"): + raise WorkspaceError(f"{ws['name']}: set customInferenceURL (the inference server's base URL)") + site["customInferenceURL"] = custom_inference_url(ws["customInferenceURL"]) + elif ws.get("customInferenceURL"): + raise WorkspaceError("only a profile with an endpoint input takes customInferenceURL") if managed: site.update(lifecycleVersion=1, modelInputs=ws["initialModelInputs"], requestedModels=ws.get("modelInputs", {}), desiredState=ws["desiredState"], diff --git a/charts/saw-users/templates/_governed-proxy-policy.tpl b/charts/saw-users/templates/_governed-proxy-policy.tpl deleted file mode 100644 index 39b52d032..000000000 --- a/charts/saw-users/templates/_governed-proxy-policy.tpl +++ /dev/null @@ -1,52 +0,0 @@ -{{/* Shared broker config for VM and container. The catalog generator mirrors this template into saw-users. */}} -{{- define "saw.governedProxyPolicy" -}} -{{- $profiles := dict -}} -{{- $refresh := dict -}} -{{- range $profile := .catalog -}} - {{- range $credential := $profile.credentials | default list -}} - {{- $spec := $credential.refresh | default dict -}} - {{- if eq ($spec.strategy | default "") "oauth2_refresh_token" -}} - {{- $keys := list -}} - {{- range $spec.material -}}{{- $keys = append $keys .name -}}{{- end -}} - {{- range list "client_id" "client_secret" "refresh_token" -}} - {{- if not (has . $keys) -}}{{- fail "OAuth refresh requires client_id, client_secret and refresh_token material" -}}{{- end -}} - {{- end -}} - {{- $_ := set $refresh $profile.id (dict "credential" $credential.name "spec" (dict "strategy" $spec.strategy "tokenURL" $spec.token_url "refreshBeforeSeconds" $spec.refresh_before_seconds "maxLifetimeSeconds" $spec.max_lifetime_seconds "material" (dict "clientID" "client_id" "clientSecret" "client_secret" "refreshToken" "refresh_token"))) -}} - {{- end -}} - {{- end -}} - {{- if $profile.credentials -}} - {{- $hosts := list -}} - {{- range $profile.endpoints -}} - {{- if and .host (not (has .host $hosts)) -}}{{- $hosts = append $hosts .host -}}{{- end -}} - {{- end -}} - {{- $_ := set $profiles $profile.id $hosts -}} - {{- end -}} -{{- end -}} -{{- if hasKey $profiles "nvidia" -}}{{- $_ := set $profiles "build" (index $profiles "nvidia") -}}{{- end -}} -{{- $bindings := list -}} -{{- $attached := .attached -}} -{{- range .bindings -}} - {{- if has .name $attached -}} - {{- if and .name (not (regexMatch "^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$" .name)) -}}{{ fail (printf "invalid secret name %q" .name) }}{{- end -}} - {{- if not (regexMatch "^[A-Za-z0-9_.-]+$" (.key | default "")) -}} - {{- fail (printf "credentialProxy.secrets[%s].key is invalid" .name) -}} - {{- end -}} - {{- if not .providers -}}{{- fail (printf "credentialProxy.secrets[%s].providers is required" .name) -}}{{- end -}} - {{- if and (hasKey . "refresh") (not (kindIs "bool" .refresh)) -}} - {{- fail "credentialProxy.secrets[].refresh must be a boolean" -}} - {{- end -}} - {{- $binding := dict "secret" .name "key" .key "providers" .providers -}} - {{- if .refresh -}} - {{- if ne (len .providers) 1 -}}{{- fail "refresh binding requires exactly one provider type" -}}{{- end -}} - {{- $type := first .providers -}} - {{- if not (hasKey $refresh $type) -}}{{- fail (printf "provider %s has no OAuth refresh spec" $type) -}}{{- end -}} - {{- $entry := index $refresh $type -}} - {{- if ne .key $entry.credential -}}{{- fail "refresh binding key must match the profile credential" -}}{{- end -}} - {{- $_ := set $binding "refresh" $entry.spec -}} - {{- end -}} - {{- $bindings = append $bindings $binding -}} - {{- end -}} -{{- end -}} -{{- $policy := dict "markerPrefix" "saw-cred" "allowHosts" .allowHosts "profiles" $profiles "bindings" $bindings -}} -{{ $policy | toJson }} -{{- end -}} diff --git a/charts/saw-users/templates/_helpers.tpl b/charts/saw-users/templates/_helpers.tpl index b3a987fa3..8aa5a7882 100644 --- a/charts/saw-users/templates/_helpers.tpl +++ b/charts/saw-users/templates/_helpers.tpl @@ -23,7 +23,9 @@ watches, not in whatever namespace this chart happens to be released into. {{- $seen := dict -}} {{- range .Values.users | default list -}} {{- $name := .name | default "" | toString -}} +{{- if not (include "saw-users.awaitingOwner" (dict "root" $ "user" .)) -}} {{- include "saw-users.validateDeploymentMode" (dict "root" $ "user" .) -}} +{{- end -}} {{- if and $.Values.ownerResolution.enabled (not (has (dig "deployment" "mode" "vm" (.values | default dict)) (list "container" "kata"))) -}} {{- $entryValues := .values | default dict -}} {{- $entryAccess := index $entryValues "accessControl" | default dict -}} @@ -459,11 +461,11 @@ openshellValues. Keep omission as vm without changing existing rendered values. {{- if not (has $mode (list "vm" "container" "kata")) -}} {{- fail "deployment.mode must be one of vm, container, kata" -}} {{- end -}} -{{- if and (has $mode (list "container" "kata")) (hasKey (.root.Values.containerSites | default dict) .user.name) -}} -{{- $u := .user -}} -{{- $site := index .root.Values.containerSites $u.name -}} +{{- if and (has $mode (list "container" "kata")) (or (hasKey (.root.Values.containerSites | default dict) .user.name) .root.Values.containerDefaults) -}} +{{- $u := include "saw-users.containerUser" (dict "root" .root "user" .user) | fromJson -}} +{{- $site := include "saw-users.containerSite" (dict "root" .root "user" $u) | fromJson -}} {{- if not (has (dig "deployment" "mode" "vm" ($u.values | default dict)) (list "container" "kata")) -}}{{- fail "deployment.mode=container must be explicit on each user" -}}{{- end -}} -{{- $foundation := eq (dig "automaticEnrollment" "enabled" true $site | toString) "false" -}} +{{- $foundation := or (eq (dig "automaticEnrollment" "enabled" true $site | toString) "false") (eq (dig "automaticEnrollment" "autoApprove" false $site | toString) "true") -}} {{- $catalog := (.root.Files.Get "files/profile-catalog.json" | fromJson).profiles -}} {{- $profile := first ($u.profiles | default list) | default "" -}} {{- $approved := or $foundation (hasKey (dig "automaticEnrollment" "approvedProfiles" dict $site) $profile) -}} @@ -471,6 +473,105 @@ 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, the same for every generation. A path already ending in + /saw-, or in /saw-/ (the portal stores each + registration's keys there), 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 (or (hasSuffix (printf "/saw-%s" $u.name) $base) (hasSuffix (printf "/saw-%s/%s" $u.name $u.registration) $base)) -}} +{{- $base = printf "%s/saw-%s" $base $u.name -}} +{{- end -}} +{{- $_ := set $u "vaultPrefix" $base -}} +{{- if not (hasKey $u "pruneOnRemove") }}{{ $_ := set $u "pruneOnRemove" true }}{{ end -}} +{{- if not (hasKey $u "intentGeneration") }}{{ $_ := set $u "intentGeneration" 1 }}{{ end -}} +{{- with include "saw-users.installationID" $u }}{{ $_ := set $u "installationID" . }}{{ end -}} +{{- toJson $u -}} +{{- end -}} + +{{/* Recursive merge of .over into .base by key presence: unlike Sprig's +mergeOverwrite, a false, 0 or "" in .over replaces the base value. Maps merge; +every other value (lists included) is replaced. Returns JSON. */}} +{{- define "saw-users.deepMerge" -}} +{{- $out := deepCopy (.base | default dict) -}} +{{- range $key, $value := (.over | default dict) -}} +{{- $current := index $out $key -}} +{{- if and (kindIs "map" $value) (kindIs "map" $current) -}} +{{- $_ := set $out $key (include "saw-users.deepMerge" (dict "base" $current "over" $value) | fromJson) -}} +{{- else -}} +{{- $_ := set $out $key $value -}} +{{- end -}} +{{- end -}} +{{- toJson $out -}} {{- end -}} + +{{/* A container user's site: containerSites. layered over the shared +containerDefaults (site values win). subject defaults to the user's +ownerSubject. On an autoApprove site every unset chart revision defaults to +global.targetRevision, so the workspace follows the pattern's branch like VM +users; reviewed sites must pin each revision to a commit SHA and are left +unset so the chart and preflight fail instead. Merged by key presence +(saw-users.deepMerge), so a per-user false or "" overrides a default, as in +the portal. Returns JSON. */}} +{{- define "saw-users.containerSite" -}} +{{- $root := .root -}}{{- $u := .user -}} +{{- $site := include "saw-users.deepMerge" (dict "base" ($root.Values.containerDefaults | default dict) "over" (index ($root.Values.containerSites | default dict) $u.name | default dict)) | fromJson -}} +{{- if and $site (not $site.subject) }}{{ $_ := set $site "subject" $u.ownerSubject }}{{ end -}} +{{- if and $site (eq (dig "deployment" "mode" "vm" ($u.values | default dict)) "kata") (not $site.kataRuntimeClass) -}} +{{- $_ := set $site "kataRuntimeClass" (dict "name" (($root.Values.kata | default dict).runtimeClassName | default "saw-kata")) -}} +{{- end -}} +{{- $rev := $root.Values.global.targetRevision -}} +{{- if eq (toString (dig "automaticEnrollment" "autoApprove" false $site)) "true" -}} +{{- $stack := $site.stack | default dict -}} +{{- range $key := list "identity" "policy" "gateway" "audit" -}} +{{- $item := index $stack $key | default dict -}} +{{- if and (kindIs "map" $item) (not $item.revision) }}{{ $_ := set $item "revision" $rev }}{{ end -}} +{{- $_ := set $stack $key $item -}} +{{- end -}} +{{- $_ := set $site "stack" $stack -}} +{{- with $site.automaticEnrollment -}} +{{- if not .revision }}{{ $_ := set . "revision" $rev }}{{ end -}} +{{- if and .relay (not .relay.revision) }}{{ $_ := set .relay "revision" $rev }}{{ end -}} +{{- end -}} +{{- end -}} +{{- toJson $site -}} +{{- end -}} + +{{/* "true" for a container or Kata user whose ownerSubject is not known yet +(typically before the Keycloak account exists) on an installation configured +for containers (containerDefaults or the user's containerSites entry). Such a +user is left out of every rendered resource and listed in the +saw-users-awaiting-owner ConfigMap, so VM users and the rest of the install +still sync. Without any container configuration the entry still fails. */}} +{{- define "saw-users.awaitingOwner" -}} +{{- $u := .user -}} +{{- $configured := or .root.Values.containerDefaults (hasKey (.root.Values.containerSites | default dict) ($u.name | default "")) -}} +{{- if and $configured (has (dig "deployment" "mode" "vm" ($u.values | default dict)) (list "container" "kata")) (not $u.ownerSubject) -}}true{{- end -}} {{- end -}} diff --git a/charts/saw-users/templates/applications.yaml b/charts/saw-users/templates/applications.yaml index 96905913b..e3323bd5a 100644 --- a/charts/saw-users/templates/applications.yaml +++ b/charts/saw-users/templates/applications.yaml @@ -1,7 +1,8 @@ {{- include "saw-users.validate" . -}} {{- range $user := .Values.users | default list }} -{{- if not (and $.Values.projection.enabled (has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata"))) }} +{{- if and (not (include "saw-users.awaitingOwner" (dict "root" $ "user" $user))) (not (and $.Values.projection.enabled (has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata")))) }} {{- $container := has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata") }} +{{- if $container }}{{- $user = include "saw-users.containerUser" (dict "root" $ "user" $user) | fromJson }}{{- end }} {{- if not $container }} --- {{ include "saw-users.application" (dict @@ -26,14 +27,24 @@ ) }} --- {{- if $container }} -{{- $site := deepCopy (index $.Values.containerSites $user.name | default dict) }} +{{- $site := include "saw-users.containerSite" (dict "root" $ "user" $user) | fromJson }} {{- $mode := dig "deployment" "mode" "vm" ($user.values | default dict) }} {{- if ne (eq $mode "kata") (not (empty $site.kataRuntimeClass)) }}{{ fail "registration placement differs from the site RuntimeClass approval" }}{{- end }} -{{- with $site.providerAllowHosts }} +{{- /* Which Secret backs which provider type; OpenShell's provider profiles + decide where each credential may be used. */}} {{- $scope := dict "root" $ "user" $user }} -{{- $policy := include "saw.governedProxyPolicy" (dict "catalog" ($.Files.Get "files/governed-profiles.json" | fromJson) "bindings" (include "saw-users.credentialBindings" $scope | fromJsonArray) "attached" (include "saw-users.secretNames" $scope | fromJsonArray) "allowHosts" .) | fromJson }} -{{- $_ := set $site "providerPolicy" $policy }} +{{- $attached := include "saw-users.secretNames" $scope | fromJsonArray }} +{{- $credentials := list }} +{{- range $binding := include "saw-users.credentialBindings" $scope | fromJsonArray }} +{{- if has $binding.name $attached }} +{{- range $type := $binding.providers }} +{{- $credential := dict "secret" $binding.name "key" $binding.key "type" $type }} +{{- if $binding.refresh }}{{- $_ := set $credential "refresh" "oauth2_refresh_token" }}{{- end }} +{{- $credentials = append $credentials $credential }} {{- end }} +{{- end }} +{{- end }} +{{- $_ := set $site "credentialBindings" $credentials }} {{ $values := dict "owner" $user.name "ownerSubject" $user.ownerSubject "registration" $user.registration "vaultPrefix" $user.vaultPrefix "installationID" $user.installationID "intentGeneration" $user.intentGeneration "site" $site "global" $.Values.global }} {{ include "saw-users.application" (dict "root" $ "user" $user "appName" (printf "saw-%s" $user.name) "wave" $.Values.syncWave.sandbox "path" "charts/saw-portal-container" "release" $user.name "values" (toYaml $values)) }} {{- else }} diff --git a/charts/saw-users/templates/awaiting-owner.yaml b/charts/saw-users/templates/awaiting-owner.yaml new file mode 100644 index 000000000..8d834cb7c --- /dev/null +++ b/charts/saw-users/templates/awaiting-owner.yaml @@ -0,0 +1,15 @@ +{{- /* Container/Kata users left out until their ownerSubject is set; see +saw-users.awaitingOwner. `oc get cm saw-users-awaiting-owner -o yaml` lists them. */ -}} +{{- $waiting := list }} +{{- range $user := .Values.users | default list }} +{{- if include "saw-users.awaitingOwner" (dict "root" $ "user" $user) }}{{- $waiting = append $waiting $user.name }}{{- end }} +{{- end }} +{{- if $waiting }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: saw-users-awaiting-owner +data: + users: {{ join "," $waiting | quote }} + next: "Create the Keycloak account (make keycloak-add-user KC_USER=), read its subject (make keycloak-user-info KC_USER=), set ownerSubject on the entry in overrides/saw-users.yaml and push." +{{- end }} diff --git a/charts/saw-users/templates/namespaces.yaml b/charts/saw-users/templates/namespaces.yaml index dce93a39f..6e8ca308e 100644 --- a/charts/saw-users/templates/namespaces.yaml +++ b/charts/saw-users/templates/namespaces.yaml @@ -1,6 +1,7 @@ {{- include "saw-users.validate" . -}} {{- range $user := .Values.users | default list }} -{{- if not (and $.Values.projection.enabled (has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata"))) }} +{{- if and (not (include "saw-users.awaitingOwner" (dict "root" $ "user" $user))) (not (and $.Values.projection.enabled (has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata")))) }} +{{- if has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata") }}{{- $user = include "saw-users.containerUser" (dict "root" $ "user" $user) | fromJson }}{{- end }} --- apiVersion: v1 kind: Namespace diff --git a/charts/saw-users/templates/projector.yaml b/charts/saw-users/templates/projector.yaml index 0ef7fd960..946a316b3 100644 --- a/charts/saw-users/templates/projector.yaml +++ b/charts/saw-users/templates/projector.yaml @@ -1,14 +1,23 @@ {{- if .Values.projection.enabled }} {{- $users := list }} {{- range $user := .Values.users }} -{{- if has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata") }} -{{- $users = append $users $user }} +{{- if and (has (dig "deployment" "mode" "vm" ($user.values | default dict)) (list "container" "kata")) $user.ownerSubject }} +{{- $users = append $users (include "saw-users.containerUser" (dict "root" $ "user" $user) | fromJson) }} {{- end }}{{- end }} {{- $owner := printf "%s/%s" .Release.Namespace .Release.Name | sha256sum | trunc 20 }} {{- $name := printf "saw-projector-%s" $owner }} {{- $config := dict }} {{- if $users }}{{- $config = deepCopy .Values }}{{- end }} {{- $_ := set $config "users" $users }} +{{- if $users }} +{{- $sites := dict }} +{{- range $user := $users }} +{{- $resolved := include "saw-users.containerSite" (dict "root" $ "user" $user) | fromJson }} +{{- if $resolved }}{{- $_ := set $sites $user.name $resolved }}{{- end }} +{{- end }} +{{- $_ := set $config "containerSites" $sites }} +{{- $_ := unset $config "containerDefaults" }} +{{- end }} {{- range $user := $users }} {{- $site := index $config.containerSites $user.name }} {{- if not $site }}{{ fail (printf "user %q: deployment.mode=container requires a containerSites entry" $user.name) }}{{ end }} @@ -24,10 +33,11 @@ data: {{- $argo := include "saw-users.argoNamespace" . }} {{- if eq .Release.Namespace $argo }}{{ fail "workspace projection requires a dedicated namespace outside Argo CD" }}{{ end }} {{- if or (not .Values.projection.egress) (not (regexMatch "^.+@sha256:[a-f0-9]{64}$" .Values.projection.image)) }}{{ fail "projection requires a pinned helper image and explicit API/DNS egress" }}{{ end }} -{{- if not .Values.projection.applicationSetControllerLabels }}{{ fail "projection requires the actual ApplicationSet controller Pod labels" }}{{ end }} +{{- $appsetLabels := .Values.projection.applicationSetControllerLabels | default (dict "app.kubernetes.io/name" (printf "%s-applicationset-controller" $argo)) }} {{- $identity := dict "namespace" .Release.Namespace "argoNamespace" $argo "name" $name "owner" $owner }} {{- $identityCode := .Files.Get "files/projector_identity.py" }} -{{- $bootstrapRevision := dict "config" $identity "source" $identityCode "image" .Values.projection.image | toJson | sha256sum | trunc 12 }} +{{- /* Job templates are immutable: anything in the Pod template goes into the name. */}} +{{- $bootstrapRevision := dict "config" $identity "source" $identityCode "image" .Values.projection.image "podLabels" "kubernetes-api" | toJson | sha256sum | trunc 12 }} {{- $bootstrap := printf "%s-%s" $name $bootstrapRevision }} --- apiVersion: v1 @@ -94,7 +104,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 @@ -186,7 +196,7 @@ spec: backoffLimit: 3 activeDeadlineSeconds: 300 template: - metadata: {labels: {app.kubernetes.io/name: {{ $name }}}} + metadata: {labels: {app.kubernetes.io/name: {{ $name }}, saw.redhat.com/kubernetes-api: allow}} spec: serviceAccountName: {{ $name }}-identity automountServiceAccountToken: true @@ -212,7 +222,7 @@ spec: selector: {matchLabels: {app.kubernetes.io/name: {{ $name }}, app.kubernetes.io/component: projector}} template: metadata: - labels: {app.kubernetes.io/name: {{ $name }}, app.kubernetes.io/component: projector} + labels: {app.kubernetes.io/name: {{ $name }}, app.kubernetes.io/component: projector, saw.redhat.com/kubernetes-api: allow} annotations: checksum/source: {{ printf "%s%s%s%s" (.Files.Get "files/projector.py") (.Files.Get "files/workspace.py") (.Files.Get "files/preflight.py") (.Files.Get "files/profile-catalog.json") | sha256sum }} spec: @@ -247,6 +257,25 @@ spec: selector: {app.kubernetes.io/name: {{ $name }}, app.kubernetes.io/component: projector} ports: [{name: http, port: 4355, targetPort: http}] --- +# The projector and its identity Job reach the Kubernetes API through the +# control-plane nodes, selected by label: no cluster IPs. +apiVersion: policy.networking.k8s.io/v1alpha1 +kind: AdminNetworkPolicy +metadata: + name: {{ $name }}-kubernetes-api + annotations: {argocd.argoproj.io/sync-wave: "-11"} +spec: + priority: {{ .Values.projection.kubernetesApi.priority }} + subject: + pods: + namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: {{ .Release.Namespace }}}} + podSelector: {matchLabels: {app.kubernetes.io/name: {{ $name }}, saw.redhat.com/kubernetes-api: allow}} + egress: + - name: kubernetes-api + action: Allow + to: {{ .Values.projection.kubernetesApi.to | toJson }} + ports: [{portNumber: {protocol: TCP, port: {{ .Values.projection.kubernetesApi.port | default 6443 }}}}] +--- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: {name: {{ $name }}} @@ -256,7 +285,7 @@ spec: ingress: - from: - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: {{ $argo }}}} - podSelector: {matchLabels: {{ .Values.projection.applicationSetControllerLabels | toJson }}} + podSelector: {matchLabels: {{ $appsetLabels | toJson }}} ports: [{protocol: TCP, port: 4355}] egress: {{ .Values.projection.egress | toJson }} --- diff --git a/charts/saw-users/values.yaml b/charts/saw-users/values.yaml index c863a7f3c..32dc69620 100644 --- a/charts/saw-users/values.yaml +++ b/charts/saw-users/values.yaml @@ -138,13 +138,47 @@ 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: {} +# RuntimeClass a Kata user runs in when their site names none: the one the +# saw-kata application creates. On an autoApprove site the projector binds it +# by its live UID and placement digest; a reviewed site sets +# containerSites..kataRuntimeClass {name, uid, sha256} explicitly. +kata: + runtimeClassName: saw-kata + # Static container entries use the same workspace projector as the portal. # RHDH supplies already-projected values and leaves this disabled. projection: enabled: false image: registry.access.redhat.com/ubi9/python-311@sha256:a0bdb55576fc5b8d6704279307817828ef027e1065533ceba133fe9516003a6c - # Explicit API/DNS egress for the projector and its identity bootstrap. - egress: [] - # Match the selected OpenShift GitOps instance's controller Pod, not a - # presumed instance name. Used together with the Argo namespace selector. + # DNS for the projector and its identity bootstrap. They reach the + # Kubernetes API through kubernetesApi below, so no cluster IPs are needed. + egress: + - to: + - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: openshift-dns}} + podSelector: {matchLabels: {dns.operator.openshift.io/daemonset-dns: default}} + ports: [{protocol: UDP, port: 5353}, {protocol: TCP, port: 5353}, {protocol: UDP, port: 53}, {protocol: TCP, port: 53}] + # An AdminNetworkPolicy that lets the projector's pods reach the API on the + # control-plane nodes. On a hosted control plane, list the API addresses + # instead: [{networks: ["/32"]}]. + kubernetesApi: + priority: 70 + port: 6443 + to: + - nodes: {matchExpressions: [{key: node-role.kubernetes.io/control-plane, operator: Exists}]} + # The ApplicationSet controller Pod labels, used together with the Argo + # namespace selector. Empty means the OpenShift GitOps convention for an + # instance named after its namespace (-applicationset-controller). applicationSetControllerLabels: {} diff --git a/charts/saw-workspace-relay/templates/access.yaml b/charts/saw-workspace-relay/templates/access.yaml index 2bf81382f..934f932ab 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 @@ -90,7 +92,7 @@ spec: backoffLimit: 2 activeDeadlineSeconds: 510 template: - metadata: {labels: {app: {{ $n }}, role: bind}} + metadata: {labels: {app: {{ $n }}, role: bind, saw.redhat.com/kubernetes-api: allow}} spec: serviceAccountName: {{ $n }} automountServiceAccountToken: false 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/charts/saw-workspace-relay/templates/ui.yaml b/charts/saw-workspace-relay/templates/ui.yaml index de1718cd5..e449a022e 100644 --- a/charts/saw-workspace-relay/templates/ui.yaml +++ b/charts/saw-workspace-relay/templates/ui.yaml @@ -34,7 +34,7 @@ spec: selector: {matchLabels: {app: {{ $n }}, role: relay}} template: metadata: - labels: {app: {{ $n }}, role: relay} + labels: {app: {{ $n }}, role: relay, saw.redhat.com/kubernetes-api: allow} annotations: {checksum/config: {{ printf "%s%s%s" ($v | toJson) (.Files.Get "files/token.py") (.Files.Get "files/saw_ui_limit.py") | sha256sum }}} spec: serviceAccountName: {{ $n }} diff --git a/examples/saw/installer-bom.yaml b/examples/saw/installer-bom.yaml index 4f1ef776d..b462763ae 100644 --- a/examples/saw/installer-bom.yaml +++ b/examples/saw/installer-bom.yaml @@ -5,27 +5,27 @@ apiVersion: saw.redhat.com/v1alpha1 kind: InstallerBOM metadata: - name: openshell-0-1-6-rhaiv-4 + name: openshell-0-1-10-rhaiv-0 spec: # Version of charts/openshell-saw/files/installer/apply_bom.py this BOM targets. installerVersion: 0.1.0 openshell: cli: - version: 0.1.6-rhaiv.4 - image: quay.io/opendatahub/odh-openshell-cli@sha256:9128f07cbb29b87472a71e09a4b164ec35ea0484712cc31028209f8d1e5291c4 + version: 0.1.10-rhaiv.0 + image: quay.io/opendatahub/odh-openshell-cli@sha256:439f6ea6acc93e4d3539125b15ca93d23e20740d2ab7150eef56bf7842c8a6c4 gateway: - version: 0.1.6-rhaiv.4 - image: quay.io/opendatahub/odh-openshell-gateway@sha256:bd2d7c9084b80b8d3d8ef92d00a27b963b35168fad84cd862b7f91fd9c488c3e + version: 0.1.10-rhaiv.0 + image: quay.io/opendatahub/odh-openshell-gateway@sha256:e4b89770ef55238cc45d9880614eda64b8ab9a76be5e6c81c63a350889eb0717 supervisor: - version: 0.1.6-rhaiv.4 - image: quay.io/opendatahub/odh-openshell-supervisor@sha256:626b91a0f53393dac0d591c142b81100916aa66b4e65444b5527672b5533fe86 + version: 0.1.10-rhaiv.0 + image: quay.io/opendatahub/odh-openshell-supervisor@sha256:c2c8e9d3d19a1612074df0f637078064cff45b92d35c74b116a72fb503b3c1bc # Optional: where the binary lives inside the image (this is the default). # path: /openshell-supervisor # OpenShell 0.1.x: the sandbox runtime image the gateway mounts the # supervisor from. Pulled only; nothing is extracted. sandbox: - version: 0.1.6-rhaiv.4 - image: quay.io/opendatahub/odh-openshell-sandbox@sha256:0cde11346e68485907c22d3c9b30802e52cf16e3853720a864ac8347bb68f6ef + version: 0.1.10-rhaiv.0 + image: quay.io/opendatahub/odh-openshell-sandbox@sha256:365d321345ea142a10d442f91bebeaf6d67dac4384b6dc29b4e72ada01a9b959 # Optional: only needed by `type: nemoclaw` sandboxes. # nemoclaw: # cliImage: ghcr.io/validatedpatterns-sandbox/nemoclaw-cli@sha256: diff --git a/overrides/saw-container-defaults.yaml b/overrides/saw-container-defaults.yaml new file mode 100644 index 000000000..50522b252 --- /dev/null +++ b/overrides/saw-container-defaults.yaml @@ -0,0 +1,40 @@ +# Cluster-wide settings for container and Kata workspaces, set once by the +# platform admin; saw-users and the portal (openshell-rhdh) both read it. Users +# only add an entry to overrides/saw-users.yaml; per-user changes go under +# containerSites.. Everything else a site needs is a default in +# charts/saw-portal-container (siteDefaults). +# +# Nothing here is cluster specific: workspaces reach the Kubernetes API +# through the control-plane nodes and DNS through the cluster DNS pods, and use +# the cluster's default StorageClass plus saw-shared, which `make saw-init` +# creates as a copy of its shared-filesystem class. +projection: + enabled: true + +containerDefaults: + # OpenClaw with /sandbox searchable by OpenShift namespace UIDs, published by + # .github/workflows/build-openclaw-image.yml. Pin the src-<12 hex> tag that + # matches the BOM's source image (for now the amd64 build of 896d1526ee29). + # Disconnected clusters can build it in-cluster (make container-notebook-image). + profileImageOverrides: + data-science: + notebook: "ghcr.io/sauagarwa/saw-openclaw@sha256:05f17f3872f864e44231fb3cea30cd4dd2ba9887b382a67b261f068a234b79a2" + custom-inference: + notebook: "ghcr.io/sauagarwa/saw-openclaw@sha256:05f17f3872f864e44231fb3cea30cd4dd2ba9887b382a67b261f068a234b79a2" + automaticEnrollment: + # Enrollment stays off until an operator reviews a workspace's boundary; + # then set enabled: true, the reviewed reference and approvedProfiles + # digest under containerSites..automaticEnrollment, and pin chart + # revisions to commit SHAs (docs/container-installation.md). Demo clusters + # list overrides/saw-container-demo.yaml after this file instead. + enabled: false + autoApprove: false + # The saw-kubernetes-runtime image, pinned by digest and pullable + # anonymously from inside the cluster (make saw-init checks this). + # For now a multi-arch CI build of this branch (image tag sha-057e58ff), until + # .github/workflows/build-kubernetes-runtime.yml publishes it from main. + image: ghcr.io/sauagarwa/saw-kubernetes-runtime@sha256:519d559382a14b0e57ea0a10f54d5f2038089a0dcee065a8b2a24f6ab69882be + buildNamespace: saw-component-builds + relay: + keycloakNamespace: saw-keycloak + keycloakProvisionerSecret: saw-relay-provisioner diff --git a/overrides/saw-container-demo.yaml b/overrides/saw-container-demo.yaml new file mode 100644 index 000000000..d53d5eeeb --- /dev/null +++ b/overrides/saw-container-demo.yaml @@ -0,0 +1,20 @@ +# Development and demo clusters only. Never list this file in production +# values: it skips the operator boundary review. +# +# List it after /overrides/saw-container-defaults.yaml in the saw-users and +# openshell-rhdh extraValueFiles. Enrollment then publishes the first boundary +# and BOM it observes instead of comparing them with a reviewed reference and +# approvedProfiles digest, the portal offers Container and every catalog +# profile, and chart revisions may follow the pattern's branch. Later boundary +# changes still fail closed; start a new generation to re-enroll. A user can +# opt back into review with +# containerSites..automaticEnrollment.autoApprove: false. +containerDefaults: + automaticEnrollment: + enabled: true + autoApprove: true + +# The self-service portal offers Container next to VM; any Keycloak user may +# request it, and their site is containerDefaults. +portal: + deploymentModes: [vm, container, kata] diff --git a/overrides/saw-users.yaml b/overrides/saw-users.yaml index 03b297a07..00565bad3 100644 --- a/overrides/saw-users.yaml +++ b/overrides/saw-users.yaml @@ -1,5 +1,20 @@ # 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 (every generation). +# To start over with a fresh workspace, remove the entry, let Argo delete it, +# then add it back with a higher generation (two pushes). +# - name: alice +# ownerSubject: +# profiles: [custom-inference] +# vaultPrefix: secret/data/hub +# customInferenceURL: https:///v1 # custom-inference only +# modelInputs: +# inference.model: +# values: +# deployment: {mode: container} users: [] # Opt in only for users of a configured custom-inference endpoint. Match diff --git a/tests/charts/golden/gateway-interceptor-direct.toml b/tests/charts/golden/gateway-interceptor-direct.toml index d1d363bc0..3cc542f8c 100644 --- a/tests/charts/golden/gateway-interceptor-direct.toml +++ b/tests/charts/golden/gateway-interceptor-direct.toml @@ -15,8 +15,8 @@ public_key_path = "/home/cloud-user/.local/state/openshell/tls/jwt/public.pem" kid_path = "/home/cloud-user/.local/state/openshell/tls/jwt/kid" [openshell.drivers.podman] -supervisor_image = "quay.io/opendatahub/odh-openshell-supervisor@sha256:626b91a0f53393dac0d591c142b81100916aa66b4e65444b5527672b5533fe86" -sandbox_runtime_image = "quay.io/opendatahub/odh-openshell-sandbox@sha256:0cde11346e68485907c22d3c9b30802e52cf16e3853720a864ac8347bb68f6ef" +supervisor_image = "quay.io/opendatahub/odh-openshell-supervisor@sha256:c2c8e9d3d19a1612074df0f637078064cff45b92d35c74b116a72fb503b3c1bc" +sandbox_runtime_image = "quay.io/opendatahub/odh-openshell-sandbox@sha256:365d321345ea142a10d442f91bebeaf6d67dac4384b6dc29b4e72ada01a9b959" # Agent sandboxes mount their trusted gate and audit volumes through caller # driver config; an OpenClaw harness adds a third mount. Admission is limited # to the installer's admin identity and exact volume targets. diff --git a/tests/charts/golden/gateway-interceptor-oidc.toml b/tests/charts/golden/gateway-interceptor-oidc.toml index a3a12b30c..170ea5c77 100644 --- a/tests/charts/golden/gateway-interceptor-oidc.toml +++ b/tests/charts/golden/gateway-interceptor-oidc.toml @@ -25,8 +25,8 @@ public_key_path = "/home/cloud-user/.local/state/openshell/tls/jwt/public.pem" kid_path = "/home/cloud-user/.local/state/openshell/tls/jwt/kid" [openshell.drivers.podman] -supervisor_image = "quay.io/opendatahub/odh-openshell-supervisor@sha256:626b91a0f53393dac0d591c142b81100916aa66b4e65444b5527672b5533fe86" -sandbox_runtime_image = "quay.io/opendatahub/odh-openshell-sandbox@sha256:0cde11346e68485907c22d3c9b30802e52cf16e3853720a864ac8347bb68f6ef" +supervisor_image = "quay.io/opendatahub/odh-openshell-supervisor@sha256:c2c8e9d3d19a1612074df0f637078064cff45b92d35c74b116a72fb503b3c1bc" +sandbox_runtime_image = "quay.io/opendatahub/odh-openshell-sandbox@sha256:365d321345ea142a10d442f91bebeaf6d67dac4384b6dc29b4e72ada01a9b959" # Agent sandboxes mount their trusted gate and audit volumes through caller # driver config; an OpenClaw harness adds a third mount. Admission is limited # to the installer's admin identity and exact volume targets. diff --git a/tests/charts/golden/gateway-interceptor.toml b/tests/charts/golden/gateway-interceptor.toml index e662d51f9..ee93b4a59 100644 --- a/tests/charts/golden/gateway-interceptor.toml +++ b/tests/charts/golden/gateway-interceptor.toml @@ -15,8 +15,8 @@ public_key_path = "/home/cloud-user/.local/state/openshell/tls/jwt/public.pem" kid_path = "/home/cloud-user/.local/state/openshell/tls/jwt/kid" [openshell.drivers.podman] -supervisor_image = "quay.io/opendatahub/odh-openshell-supervisor@sha256:626b91a0f53393dac0d591c142b81100916aa66b4e65444b5527672b5533fe86" -sandbox_runtime_image = "quay.io/opendatahub/odh-openshell-sandbox@sha256:0cde11346e68485907c22d3c9b30802e52cf16e3853720a864ac8347bb68f6ef" +supervisor_image = "quay.io/opendatahub/odh-openshell-supervisor@sha256:c2c8e9d3d19a1612074df0f637078064cff45b92d35c74b116a72fb503b3c1bc" +sandbox_runtime_image = "quay.io/opendatahub/odh-openshell-sandbox@sha256:365d321345ea142a10d442f91bebeaf6d67dac4384b6dc29b4e72ada01a9b959" # Agent sandboxes mount their trusted gate and audit volumes through caller # driver config; an OpenClaw harness adds a third mount. Admission is limited # to the installer's admin identity and exact volume targets. diff --git a/tests/charts/test_governance_interceptor_image.py b/tests/charts/test_governance_interceptor_image.py index b270c13d7..e1958d6e3 100644 --- a/tests/charts/test_governance_interceptor_image.py +++ b/tests/charts/test_governance_interceptor_image.py @@ -152,8 +152,8 @@ def test_exact_embedded_guard_behavior(builder, tmp_path): @pytest.mark.ci_external def test_builder_pins_and_runs_embedded_tests(): values = yaml.safe_load((CHART / "values.yaml").read_text()) - assert values["source"]["git"]["ref"] == "v0.1.6" - assert "ARG OPENSHELL_REF=v0.1.6" in DOCKERFILE.read_text() + assert values["source"]["git"]["ref"] == "v0.1.10" + assert "ARG OPENSHELL_REF=v0.1.10" in DOCKERFILE.read_text() texts = [DOCKERFILE.read_text()] if HELM: texts.append(inline_dockerfile()) @@ -214,7 +214,7 @@ def test_shared_recipe_preserves_both_runtime_variants(): def test_default_build_output_is_internal_and_push_requires_explicit_destination(): rendered = subprocess.check_output([HELM, "template", "image", str(CHART)], text=True) build = next(d for d in yaml.safe_load_all(rendered) if d and d["kind"] == "BuildConfig") - assert build["spec"]["output"]["to"] == {"kind": "ImageStreamTag", "name": "governance-interceptor:v0.1.6"} + assert build["spec"]["output"]["to"] == {"kind": "ImageStreamTag", "name": "governance-interceptor:v0.1.10"} assert "pushSecret" not in build["spec"]["output"] rendered = subprocess.check_output([HELM, "template", "image", str(CHART), "--set", "output.imageStreamTag=", "--set", "output.externalImage=ghcr.io/example/governance-interceptor:v0.1.6"], text=True) @@ -222,17 +222,60 @@ def test_default_build_output_is_internal_and_push_requires_explicit_destination assert build["spec"]["output"]["to"]["name"] == "ghcr.io/example/governance-interceptor:v0.1.6" -@pytest.mark.parametrize("filename", ["build-governance-interceptor.yml", "build-kubernetes-runtime.yml"]) +@pytest.mark.parametrize("filename", ["build-governance-interceptor.yml", "build-kubernetes-runtime.yml", + "build-openclaw-image.yml"]) def test_pr_image_jobs_cannot_publish(filename): workflow = yaml.safe_load((ROOT / ".github/workflows" / filename).read_text()) assert workflow["permissions"] == {"contents": "read"} jobs = workflow["jobs"] assert "permissions" not in jobs["build"] - assert jobs["build"]["if"] == "github.event_name == 'pull_request' || github.ref != 'refs/heads/main'" + main = "github.event_name != 'pull_request' && github.ref == 'refs/heads/main'" + if "publish" in (workflow[True].get("workflow_dispatch") or {}).get("inputs", {}): + # A maintainer's manual run may publish a branch; pull_request events + # carry no dispatch inputs, so a PR still never publishes. + assert workflow[True]["workflow_dispatch"]["inputs"]["publish"]["default"] is False + assert jobs["build"]["if"] == ("github.event_name == 'pull_request' || " + "(github.ref != 'refs/heads/main' && !inputs.publish)") + publish_if = f"({main}) || inputs.publish" + else: + assert jobs["build"]["if"] == "github.event_name == 'pull_request' || github.ref != 'refs/heads/main'" + publish_if = main for job in ("publish", "merge"): - assert jobs[job]["if"] == "github.event_name != 'pull_request' && github.ref == 'refs/heads/main'" + assert jobs[job]["if"] == publish_if assert jobs[job]["permissions"] == {"contents": "read", "packages": "write"} assert jobs["merge"]["needs"] == "publish" assert jobs["build"]["steps"] == jobs["publish"]["steps"] image = next(s for s in jobs["build"]["steps"] if s.get("uses") == "./.github/actions/build-push-image") assert "github.event_name != 'pull_request' && github.ref == 'refs/heads/main'" in image["with"]["registry_token"] + + +def test_a_branch_publish_never_moves_shared_tags(): + """Manual branch publishes are addressed by commit; :latest and the + OpenShell release tag move only from main.""" + for action in ("build-push-image", "merge-image"): + text = (ROOT / ".github/actions" / action / "action.yml").read_text() + main_block = text[text.index('if [ "$REF" = refs/heads/main ]'):] + assert ":latest" in main_block and "EXTRA_TAG" in main_block + before = text[:text.index('if [ "$REF" = refs/heads/main ]')] + assert ":latest" not in before.split("tags")[-1] + + +def test_every_pinned_personal_image_has_a_publishing_workflow(): + """An image pinned from a fork owner's ghcr namespace must be rebuildable + by CI from this branch, not only from a laptop.""" + import re + pinned = set() + for path in [*(ROOT / "charts").rglob("values*.yaml"), *(ROOT / "overrides").glob("*.yaml")]: + for owner, image in re.findall(r"ghcr\.io/([a-z0-9-]+)/([a-z0-9-]+)@sha256:", path.read_text()): + # The project's own namespace publishes from main; upstream + # vendors' images are not built here. + if owner not in {"validatedpatterns-sandbox", "openclaw", "nvidia"}: + pinned.add(image) + publishable = set() + for wf in (ROOT / ".github/workflows").glob("*.yml"): + workflow = yaml.safe_load(wf.read_text()) + dispatch = (workflow.get(True) or {}).get("workflow_dispatch") or {} + if "publish" not in (dispatch.get("inputs") or {}): + continue + publishable |= set(re.findall(r"image_name: ([a-z0-9-]+)", wf.read_text())) + assert pinned <= publishable, sorted(pinned - publishable) diff --git a/tests/charts/test_openshell_keycloak_chart.py b/tests/charts/test_openshell_keycloak_chart.py index db788385c..a0984a8d7 100644 --- a/tests/charts/test_openshell_keycloak_chart.py +++ b/tests/charts/test_openshell_keycloak_chart.py @@ -358,3 +358,30 @@ def test_shared_admin_scope_helper_is_mounted_and_rolls_bootstraps(tmp_path): for name in names: dep = next(d for d in changed if d["kind"] == "Deployment" and d["metadata"]["name"] == name) assert dep["spec"]["template"]["metadata"]["annotations"]["checksum/script"] != checksums[name] + + +def test_the_relay_provisioner_is_off_unless_container_workspaces_need_it(): + assert not [d for d in render() if "relay-provisioner" in d["metadata"]["name"]] + + +def test_the_relay_provisioner_runs_as_a_self_healing_deployment(): + docs = render("--set", "relayProvisioner.enabled=true") + mine = [d for d in docs if "relay-provisioner" in d["metadata"]["name"]] + (deploy,) = [d for d in mine if d["kind"] == "Deployment"] + # The generated credential lives in a Secret Helm does not own, so a + # GitOps self-heal cannot clear it, and nothing runs against a deadline. + assert not [d for d in mine if d["kind"] == "Secret"] + assert not [d for d in mine if d["kind"] == "Job"] + spec = deploy["spec"]["template"]["spec"] + (admin,) = [v for v in spec["volumes"] if v["name"] == "admin"] + assert admin["secret"]["secretName"] == "openshell-keycloak-initial-admin" + (role,) = [d for d in mine if d["kind"] == "Role" and d["metadata"]["name"] == "saw-relay-provisioner"] + named = [r for r in role["rules"] if r.get("resourceNames")] + assert named == [{"apiGroups": [""], "resources": ["secrets"], + "resourceNames": ["saw-relay-provisioner"], "verbs": ["get", "patch"]}] + + +def test_the_pattern_enables_the_relay_provisioner(): + values = yaml.safe_load((ROOT / "values-prod.yaml").read_text()) + overrides = values["clusterGroup"]["applications"]["openshell-keycloak"]["overrides"] + assert {"name": "relayProvisioner.enabled", "value": "true"} in overrides diff --git a/tests/charts/test_openshell_saw_chart.py b/tests/charts/test_openshell_saw_chart.py index f5354222e..ef55e8d8e 100644 --- a/tests/charts/test_openshell_saw_chart.py +++ b/tests/charts/test_openshell_saw_chart.py @@ -1030,7 +1030,14 @@ def test_pattern_puts_keycloak_and_each_saw_in_their_own_namespaces(): users_app = apps["saw-users"] assert users_app["namespace"] == "openshell-agents" assert users_app["path"] == "charts/saw-users" - assert users_app["extraValueFiles"] == ["/overrides/saw-users.yaml"] + # Shared container defaults first, then the users; never the demo-only file. + assert users_app["extraValueFiles"] == ["/overrides/saw-container-defaults.yaml", + "/overrides/saw-users.yaml"] + for app in apps.values(): + assert "/overrides/saw-container-demo.yaml" not in (app or {}).get("extraValueFiles", []) + defaults = yaml.safe_load((ROOT / "overrides/saw-container-defaults.yaml").read_text()) + enrollment = defaults["containerDefaults"]["automaticEnrollment"] + assert enrollment["autoApprove"] is False and enrollment["enabled"] is False assert users_app["syncPolicy"]["automated"]["prune"] is True listed = yaml.safe_load((ROOT / "overrides/saw-users.yaml").read_text())["users"] assert listed == [] diff --git a/tests/charts/test_portal_container.py b/tests/charts/test_portal_container.py index 6ffeb3a1f..0e4c67dc4 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 @@ -33,7 +34,7 @@ def child(app): def user(): return {"name":U, "ownerSubject":SITE["subject"],"installationID":"802fe583-9329-54b6-b5b4-7be58ec171f3", - "registration":REG,"intentGeneration":1,"vaultPrefix":f"secret/data/hub/saw-{U}/{REG}", + "registration":REG,"intentGeneration":1,"vaultPrefix":f"secret/data/hub/saw-{U}", "values":{"deployment":{"mode":"container"}},"profiles":["data-science"],"pruneOnRemove":True} @@ -62,8 +63,27 @@ def test_container_has_own_gateway_credential_audit_and_policy(): assert "saw-unrelated-vm" not in json.dumps(workloads) +@pytest.mark.parametrize("prefix", ["secret/data/hub/saw-" + U, "secret/data/hub/saw-" + U + "/" + REG]) +def test_container_reads_keys_where_they_were_written(prefix): + """Static entries keep one per-user path; the portal writes each + registration's keys under .../saw-/ (vault.write uses + the registry entry's vaultPrefix). Both must reach the ExternalSecret as is.""" + entry = {**user(), "vaultPrefix": prefix} + top = render("saw-users", "portal-ws-" + U, "saw-portal", {"global": GLOBAL, "users": [entry], "containerSites": {U: SITE}}) + resources = [r for a in top if a["kind"] == "Application" for r in child(a)] + es, = [r for r in resources if r["kind"] == "ExternalSecret" and r["metadata"]["name"] == "inference"] + assert es["spec"]["data"][0]["remoteRef"]["key"] == prefix + "/inference" + + +@pytest.mark.parametrize("prefix", ["secret/data/hub/saw-other/" + REG, "secret/data/hub/saw-" + U + "/" + "f" * 16]) +def test_container_refuses_another_owners_or_registrations_path(prefix): + v = dict(owner=U, ownerSubject=SITE["subject"], registration=REG, vaultPrefix=prefix) + with pytest.raises(AssertionError, match="vaultPrefix must match"): + render("saw-portal-container", U, "saw-" + U, v) + + def test_container_rejects_another_registrations_keys(): - v = dict(owner=U,ownerSubject=SITE["subject"],registration=REG,vaultPrefix="secret/data/hub/saw-other/"+REG) + v = dict(owner=U,ownerSubject=SITE["subject"],registration=REG,vaultPrefix="secret/data/hub/saw-other") with pytest.raises(AssertionError,match="vaultPrefix must match"): render("saw-portal-container",U,"saw-"+U,v) @@ -180,6 +200,26 @@ def test_gateway_api_versions_require_the_same_reviewed_identity_revision(older_ assert "apiVersions" not in helm +@pytest.mark.parametrize("auto_approve,revision,renders", [ + (False, "a" * 40, True), (False, "main", False), (True, "main", True), (True, "a" * 40, True)]) +def test_only_auto_approve_sites_may_follow_a_branch(auto_approve, revision, renders): + # The same rule as preflight.configuration_facts (the portal and installer). + site = json.loads(json.dumps(SITE)) + for item in site["stack"].values(): + item["revision"] = revision + site["automaticEnrollment"]["revision"] = revision + site["automaticEnrollment"]["relay"]["revision"] = revision + site["automaticEnrollment"]["autoApprove"] = auto_approve + values = dict(site=site, owner=U, registration=REG, installationID=user()["installationID"], + ownerSubject=SITE["subject"], vaultPrefix=user()["vaultPrefix"], **{"global": GLOBAL}) + result = subprocess.run(["helm", "template", U, str(ROOT / "charts/saw-portal-container"), "--namespace", "saw-" + U, + "--api-versions", "agents.x-k8s.io/v1beta1", "-f", "-"], + input=json.dumps(values), text=True, capture_output=True) + assert (result.returncode == 0) == renders, result.stderr + if not renders: + assert "full Git commit SHA" in result.stderr + + def test_model_gate_claim_is_shared_only_for_the_publisher_and_agent(): audit = SITE["stack"]["audit"]["values"] # Use the same per-registration Helm values projection as the nested Applications. @@ -196,40 +236,47 @@ def test_model_gate_claim_is_shared_only_for_the_publisher_and_agent(): assert claims["workspace-"+U]["accessModes"] == claims[U+"-history"]["accessModes"] == ["ReadWriteOnce"] -def test_personal_assistant_uses_the_vm_proxy_policy_and_trusted_secret_projection(): +def app_values(application): + source = application["spec"]["source"]["helm"] + return source.get("valuesObject") or yaml.safe_load(source["values"]) + + +def test_personal_assistant_credentials_are_projected_for_openshell(): owner = {**user(), "profiles":["personal-assistant"]} - site = {**SITE, "providerAllowHosts":["integrate.api.nvidia.com","slack.com","gmail.googleapis.com","oauth2.googleapis.com"]} + site = {**SITE} site["automaticEnrollment"]={**SITE["automaticEnrollment"],"approvedProfiles":{"personal-assistant":"a"*64}} parent = render("saw-users","portal-ws-"+U,"saw-portal",{"global":GLOBAL,"users":[owner],"containerSites":{U:site}}) app, = [a for a in parent if a.get("spec",{}).get("source",{}).get("path")=="charts/saw-portal-container"] - resources=child(app) - broker,=[r for r in resources if r["kind"]=="ConfigMap" and r["metadata"]["name"].endswith("-proxy-policy")] - policy=json.loads(broker["data"]["config.json"]) - bindings={b["secret"]:b for b in policy["bindings"]} + bindings = {b["secret"]: b for b in app_values(app)["site"]["credentialBindings"]} assert set(bindings)=={"gmail","slack","inference"} - assert bindings["gmail"]["refresh"]["tokenURL"]=="https://oauth2.googleapis.com/token" - assert bindings["slack"]=={"secret":"slack","key":"bot_token","providers":["slack"]} + assert bindings["gmail"]=={"secret":"gmail","key":"access_token","type":"gmail","refresh":"oauth2_refresh_token"} + assert bindings["slack"]=={"secret":"slack","key":"bot_token","type":"slack"} + resources=child(app) secrets={r["metadata"]["name"]:r for r in resources if r["kind"]=="ExternalSecret"} + # Gmail's Secret holds only the refresh material; OpenShell mints the access token. for name,keys in {"gmail":{"refresh_token","client_id","client_secret"},"slack":{"bot_token"},"inference":{"api_key"}}.items(): assert secrets[name]["metadata"]["namespace"]=="saw-ctl-"+REG assert {e["secretKey"] for e in secrets[name]["spec"]["data"]}==keys - proxy,=[r for r in resources if r["kind"]=="Application" and r["spec"]["source"]["path"]=="charts/saw-kubernetes-proxy"] - assert proxy["spec"]["source"]["helm"]["valuesObject"]["credentialSecretNames"]==sorted(secrets) - - -def test_custom_inference_projection_pins_broker_url_and_keeps_key_private(): + # Every Vault property synced is one the profile collects (what the portal writes). + catalog = json.loads((ROOT/"charts/saw-users/files/profile-catalog.json").read_text())["profiles"] + for name, spec in catalog["personal-assistant"]["secrets"].items(): + collected = {f["key"] for f in spec.get("fields", [])} + assert {e["remoteRef"]["property"] for e in secrets[name]["spec"]["data"]} <= collected, name + # No SAW credential proxy: OpenShell's supervisor injects the credentials. + assert not [r for r in resources if "proxy" in r["metadata"]["name"]] + assert not [r for r in resources if r["kind"]=="Application" + and r["spec"]["source"]["path"].endswith("saw-kubernetes-proxy")] + + +def test_custom_inference_secret_carries_the_site_url(): url="https://models.fixture.test/v1" owner={**user(),"profiles":["custom-inference"],"webSearch":{"enabled":False}} - site={**SITE,"providerAllowHosts":["models.fixture.test"],"customInferenceURL":url, + site={**SITE,"customInferenceURL":url, "automaticEnrollment":{**SITE["automaticEnrollment"],"approvedProfiles":{"custom-inference":"a"*64}}} root=render("saw-users","portal-ws-"+U,"saw-portal",{"global":GLOBAL,"users":[owner],"containerSites":{U:site}}) app,=[a for a in root if a.get("spec",{}).get("source",{}).get("path")=="charts/saw-portal-container"] - resources=child(app) - broker,=[r for r in resources if r["kind"]=="ConfigMap" and r["metadata"]["name"].endswith("-proxy-policy")] - policy=json.loads(broker["data"]["config.json"]) - assert policy["allowHosts"]==["models.fixture.test"] and not policy["profiles"].get("custom-inference") - assert policy["bindings"]==[{"providers":["custom-inference"],"key":"api_key","secret":"inference"}] - es,=[r for r in resources if r["kind"]=="ExternalSecret"] + assert app_values(app)["site"]["credentialBindings"]==[{"secret":"inference","key":"api_key","type":"custom-inference"}] + es,=[r for r in child(app) if r["kind"]=="ExternalSecret"] assert es["metadata"]["namespace"]=="saw-ctl-"+REG assert es["spec"]["target"]["template"]=={"engineVersion":"v2","mergePolicy":"Merge","data":{"url":url}} assert [e["secretKey"] for e in es["spec"]["data"]]==["api_key"] @@ -258,7 +305,7 @@ def publication(v): @pytest.mark.parametrize("override, expected", [ - (None, "0.1.6-rhaiv.4"), + (None, "0.1.10-rhaiv.0"), ("0.1.7-rhaiv.1", "0.1.7-rhaiv.1"), ]) def test_enrollment_compiles_the_selected_gateway_version(override, expected): @@ -380,11 +427,49 @@ def test_foundation_can_be_reviewed_without_placeholder_approval_or_workload(): assert any(o.get("spec", {}).get("source", {}).get("path") == "charts/openshell-saw-kubernetes" for o in docs) +def pull_grant_render(image): + site = copy.deepcopy(SITE) + site["automaticEnrollment"]["image"] = image + site["enrollment"] = dict( + registration=REG, image=image, buildNamespace="builds", revision="1" * 40, + approved={}, intent={"profileRef": {"name": "saw-bom-profiles"}, "bindings": { + "ownerID": user()["installationID"], "ownerSubject": SITE["subject"], + "namespace": "saw-" + U, "namespaceUID": "fixture-uid", "mode": "container", + "bindings": {"default/notebook": { + "workspace": {"claimName": "workspace-" + U}, + "toolGate": {"trusted": {"claimName": "saw-gate-" + U}, + "audit": {"claimName": "saw-audit-" + U}, + "ownerLogin": U, "receiptKey": "fixture-public-key"}, + "browser": {"ownerLogin": U, "origin": "https://alice-default-notebook-ui.apps.cluster.example.com"}}}}}) + return render("saw-portal-container", U, "saw-" + U, dict( + site=site, owner=U, ownerSubject=SITE["subject"], registration=REG, + installationID=user()["installationID"], intentGeneration=1, + vaultPrefix=user()["vaultPrefix"], **{"global": GLOBAL})) + + +def test_gate_preparation_waits_for_the_relay_browser_proof(): + """Argo never recreates a failed Job, so preparation must outlast the + relay identity Job that projects the proof it mounts.""" + resources = pull_grant_render("ghcr.io/example/saw-kubernetes-runtime@sha256:" + "b" * 64) + jobs = [r for r in resources if r["kind"] == "Job" and r["metadata"]["name"].startswith("saw-gate-preparation")] + assert jobs and all(j["spec"]["activeDeadlineSeconds"] == 1800 for j in jobs) + + +def test_a_published_runtime_image_needs_no_build_namespace(): + """A registry image needs no ImageStream pull grant, so nothing is created + in buildNamespace (which need not exist) and the charts are told none.""" + resources = pull_grant_render("ghcr.io/example/saw-kubernetes-runtime@sha256:" + "b" * 64) + assert not [r for r in resources if r["metadata"].get("namespace") == "builds"] + for app in (r for r in resources if r["kind"] == "Application"): + values = app_values(app) + assert values.get("imageBuildNamespace", "") == "", app["metadata"]["name"] + + @pytest.mark.parametrize("stream", ["saw-kubernetes-runtime", "custom-runtime"]) def test_runtime_pull_grants_follow_the_configured_image(stream): from copy import deepcopy site = deepcopy(SITE) - image = "image-registry.example.test/builds/" + stream + "@sha256:" + "b" * 64 + image = "image-registry.openshift-image-registry.svc:5000/builds/" + stream + "@sha256:" + "b" * 64 site["automaticEnrollment"]["image"] = image site["enrollment"] = dict( registration=REG, image=image, buildNamespace="builds", revision="1" * 40, @@ -414,3 +499,183 @@ 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 + + +def ip_free_site(): + """The site as a fresh cluster has it: no egress lists, issuer, IPs or class names.""" + site = copy.deepcopy(SITE) + site.pop("auditReceipts") + site["stack"]["gateway"]["values"]["kubernetes"]["storage"].pop("className", None) + for key in ("storageClass", "exchangeStorageClass"): + site["stack"]["audit"]["values"].pop(key, None) + site["stack"]["identity"]["values"].pop("network", None) + gateway = site["stack"]["gateway"]["values"] + gateway["kubernetes"]["network"].pop("gatewayEgress", None) + gateway.get("oidc", {}).pop("issuerUrl", None) + relay = site["automaticEnrollment"]["relay"] + relay.pop("egress", None) + relay.pop("issuer", None) + return site + + +def test_workspace_reaches_the_api_through_control_plane_nodes_without_cluster_ips(): + top = render("saw-users", "portal-ws-" + U, "saw-portal", + {"global": GLOBAL, "users": [user()], "containerSites": {U: ip_free_site()}}) + resources = [r for a in top if a["kind"] == "Application" for r in child(a)] + api, = [r for r in resources if r["kind"] == "AdminNetworkPolicy"] + assert api["metadata"]["name"] == f"saw-{REG}-kubernetes-api" + assert api["spec"]["priority"] > 51 # after the runtime's own supervisor policy + subject = api["spec"]["subject"]["pods"] + names = subject["namespaceSelector"]["matchExpressions"][0]["values"] + assert {"saw-" + U, "saw-ctl-" + REG} <= set(names) + assert subject["podSelector"]["matchLabels"] == {"saw.redhat.com/kubernetes-api": "allow"} + assert {"key": "openshell.ai/boundary-role", "operator": "DoesNotExist"} in subject["podSelector"]["matchExpressions"] + rule, = api["spec"]["egress"] + assert rule["action"] == "Allow" and rule["ports"] == [{"portNumber": {"protocol": "TCP", "port": 6443}}] + assert rule["to"] == [{"nodes": {"matchExpressions": [ + {"key": "node-role.kubernetes.io/control-plane", "operator": "Exists"}]}}] + workloads = [r for a in resources if a["kind"] == "Application" for r in child(a)] + every = resources + workloads + # No policy anywhere in the workspace names a cluster address other than "any" for HTTPS. + for policy in (r for r in every if r["kind"] == "NetworkPolicy"): + for egress in policy["spec"].get("egress") or []: + for peer in egress.get("to", []): + if "ipBlock" in peer: + assert peer["ipBlock"]["cidr"] == "0.0.0.0/0", policy["metadata"]["name"] + assert egress["ports"] == [{"protocol": "TCP", "port": 443}] + gateway, = [r for r in workloads if r["kind"] == "StatefulSet" and r["metadata"]["name"] == U + "-gateway"] + assert gateway["spec"]["template"]["metadata"]["labels"]["saw.redhat.com/kubernetes-api"] == "allow" + config = next(r for r in workloads if r["kind"] == "ConfigMap" and r["metadata"]["name"] == U + "-gateway-config") + assert "https://openshell-keycloak-ingress-saw-keycloak.apps.cluster.example.com/realms/openshell" in json.dumps(config) + claims = {r["metadata"]["name"]: r["spec"].get("storageClassName") for r in every + if r["kind"] == "PersistentVolumeClaim"} + # Without receipts every volume is ReadWriteOnce on the cluster default class. + assert claims and all(c is None for c in claims.values()) + sandboxes = [r for r in every if r["kind"] in ("Pod", "Sandbox")] + assert not any("saw.redhat.com/kubernetes-api" in json.dumps(s) for s in sandboxes) + + +def test_without_receipts_the_gate_keeps_a_local_log_and_no_history(): + site = ip_free_site() + top = render("saw-users", "portal-ws-" + U, "saw-portal", + {"global": GLOBAL, "users": [user()], "containerSites": {U: site}}) + resources = [r for a in top if a["kind"] == "Application" for r in child(a)] + assert not [r for r in resources if r["kind"] == "Namespace" and r["metadata"]["name"].startswith("saw-history-")] + writer, = [r for r in resources if r["kind"] == "Application" + and r["spec"]["source"]["path"] == "charts/saw-audit-writer"] + assert writer["spec"]["destination"]["namespace"] == "saw-" + U + audit = child(writer) + assert sorted(r["kind"] for r in audit) == ["PersistentVolumeClaim"] * 3 + assert {r["metadata"]["name"]: r["spec"]["accessModes"] for r in audit} == { + "saw-audit-" + U: ["ReadWriteOnce"], "saw-gate-" + U: ["ReadWriteOnce"], "workspace-" + U: ["ReadWriteOnce"]} + enroll, = [r for r in resources if r["kind"] == "ConfigMap" and r["metadata"]["name"].startswith("bootstrap-")] + assert json.loads(enroll["data"]["config.json"])["auditReceipts"] is False + assert not [r for r in resources if r["kind"] == "NetworkPolicy" and r["metadata"]["name"] == "bootstrap-writer"] + + +def test_receipts_keep_the_history_writer_and_exchange(): + top = render("saw-users", "portal-ws-" + U, "saw-portal", + {"global": GLOBAL, "users": [user()], "containerSites": {U: SITE}}) + resources = [r for a in top if a["kind"] == "Application" for r in child(a)] + assert [r for r in resources if r["kind"] == "Namespace" and r["metadata"]["name"] == "saw-history-" + REG] + writer, = [r for r in resources if r["kind"] == "Application" + and r["spec"]["source"]["path"] == "charts/saw-audit-writer"] + audit = child(writer) + assert {r["metadata"]["name"] for r in audit if r["kind"] == "Deployment"} == {U + "-writer", U + "-forward"} + exchange, = [r for r in audit if r["kind"] == "PersistentVolumeClaim" and r["metadata"]["name"] == "saw-audit-" + U] + assert exchange["spec"]["accessModes"] == ["ReadWriteMany"] + + +def test_gateway_and_supervisors_reach_the_ocsf_collector(): + top = render("saw-users", "portal-ws-" + U, "saw-portal", + {"global": GLOBAL, "users": [user()], "containerSites": {U: ip_free_site()}}) + resources = [r for a in top if a["kind"] == "Application" for r in child(a)] + workloads = [r for a in resources if a["kind"] == "Application" for r in child(a)] + collector = {"namespaceSelector": {"matchLabels": {"kubernetes.io/metadata.name": "openshell-agents"}}, + "podSelector": {"matchLabels": {"app.kubernetes.io/name": "saw-ocsf-collector", + "app.kubernetes.io/component": "opentelemetry-collector"}}} + config = next(r for r in workloads if r["kind"] == "ConfigMap" and r["metadata"]["name"] == U + "-gateway-config") + assert "endpoint = \"http://saw-ocsf-collector.openshell-agents.svc:4317\"" in config["data"]["gateway.toml"] + gateway = next(r for r in workloads if r["kind"] == "NetworkPolicy" and r["metadata"]["name"] == U + "-gateway") + assert {"to": [collector], "ports": [{"protocol": "TCP", "port": 4317}]} in gateway["spec"]["egress"] + supervisors, = [r for r in workloads if r["kind"] == "AdminNetworkPolicy"] + rule, = [e for e in supervisors["spec"]["egress"] if e["name"] == "ocsf-collector"] + assert rule["action"] == "Pass" and rule["to"] == [{"pods": collector}] + assert rule["ports"] == [{"portNumber": {"protocol": "TCP", "port": 4317}}] + # Before the private-network deny, so the in-cluster collector stays reachable. + names = [e["name"] for e in supervisors["spec"]["egress"]] + assert names.index("ocsf-collector") < names.index("deny-private-networks") + # The supervisor admission check accepts the collector the gateway passes it. + admission = [r for r in workloads if r["kind"] == "ValidatingAdmissionPolicy"] + checks = " ".join(v["expression"] for a in admission for v in a["spec"]["validations"]) + assert "e.value == \"http://saw-ocsf-collector.openshell-agents.svc:4317\"" in checks + # The agent trace relay is on by default and goes to the same collector. + assert "[openshell.gateway.otlp.agent]" in config["data"]["gateway.toml"] + assert ("e.name != 'OPENSHELL_OTLP_AGENT_ENDPOINT' || " + "e.value == \"http://saw-ocsf-collector.openshell-agents.svc:4317\"") in " ".join(checks.split()) + + +def test_ocsf_export_can_be_turned_off(): + site = ip_free_site() + site["telemetry"] = {"ocsfEndpoint": ""} + top = render("saw-users", "portal-ws-" + U, "saw-portal", + {"global": GLOBAL, "users": [user()], "containerSites": {U: site}}) + resources = [r for a in top if a["kind"] == "Application" for r in child(a)] + workloads = [r for a in resources if a["kind"] == "Application" for r in child(a)] + assert "otlp" not in json.dumps([r for r in workloads if r["kind"] == "ConfigMap"]) + supervisors, = [r for r in workloads if r["kind"] == "AdminNetworkPolicy"] + assert "ocsf-collector" not in [e["name"] for e in supervisors["spec"]["egress"]] + admission = [r for r in workloads if r["kind"] == "ValidatingAdmissionPolicy"] + assert "OPENSHELL_OTLP" not in json.dumps(admission) + + +def test_gateway_and_admission_pin_the_same_runtime_and_supervisor_images(): + """The policy admits only the images the gateway is configured with; the two + must come from one value, not from two charts' separate defaults.""" + top = render("saw-users", "portal-ws-" + U, "saw-portal", + {"global": GLOBAL, "users": [user()], "containerSites": {U: ip_free_site()}}) + resources = [r for a in top if a["kind"] == "Application" for r in child(a)] + workloads = [r for a in resources if a["kind"] == "Application" for r in child(a)] + config = next(r for r in workloads if r["kind"] == "ConfigMap" and r["metadata"]["name"] == U + "-gateway-config") + toml = config["data"]["gateway.toml"] + defaults = yaml.safe_load((ROOT / "charts/saw-portal-container/values.yaml").read_text())["driverDefaults"] + assert f'sandbox_runtime_image = "{defaults["runtimeImage"]}"' in toml + assert f'supervisor_image = "{defaults["supervisorImage"]}"' in toml + checks = " ".join(v["expression"] for a in workloads if a["kind"] == "ValidatingAdmissionPolicy" + for v in a["spec"]["validations"]) + assert json.dumps(defaults["runtimeImage"]) in checks + assert json.dumps(defaults["supervisorImage"]) in checks + # The gateway chart's own defaults name the same images. + gateway = yaml.safe_load((ROOT / "charts/openshell-saw-kubernetes/values.yaml").read_text())["kubernetes"] + assert gateway["workload"]["runtimeImage"] == defaults["runtimeImage"] + assert gateway["supervisor"]["image"] == defaults["supervisorImage"] + + +def test_the_pattern_installs_the_collector(): + values = yaml.safe_load((ROOT / "values-prod.yaml").read_text())["clusterGroup"] + assert values["subscriptions"]["opentelemetry"]["name"] == "opentelemetry-product" + assert values["applications"]["saw-telemetry"]["path"] == "charts/saw-telemetry" + collector, = render("saw-telemetry", "saw-telemetry", "openshell-agents", {}) + assert collector["metadata"]["name"] == "saw-ocsf" # Service saw-ocsf-collector + pipelines = collector["spec"]["config"]["service"]["pipelines"] + for signal in ("logs", "traces"): # OCSF events and relayed agent traces + assert pipelines[signal]["receivers"] == ["otlp"] and pipelines[signal]["exporters"] == ["debug"] + assert collector["spec"]["config"]["receivers"]["otlp"]["protocols"] == {"grpc": {"endpoint": "0.0.0.0:4317"}} diff --git a/tests/charts/test_saw_kata_chart.py b/tests/charts/test_saw_kata_chart.py new file mode 100644 index 000000000..16a10cf8c --- /dev/null +++ b/tests/charts/test_saw_kata_chart.py @@ -0,0 +1,66 @@ +"""charts/saw-kata: the KataConfig is opt-in and never selects control-plane nodes.""" +from pathlib import Path +import subprocess + +import yaml + +ROOT = Path(__file__).resolve().parents[2] +CHART = ROOT / "charts/saw-kata" + + +def render(*args): + result = subprocess.run(["helm", "template", "saw-kata", str(CHART), *args], capture_output=True, text=True) + return result, [d for d in yaml.safe_load_all(result.stdout or "") if d] + + +def test_off_by_default(): + result, docs = render() + assert result.returncode == 0, result.stderr + assert docs == [] + + +def test_enabled_selects_plain_workers_only(): + result, docs = render("--set", "enabled=true") + assert result.returncode == 0, result.stderr + config, = [d for d in docs if d["kind"] == "KataConfig"] + assert config["kind"] == "KataConfig" and config["spec"]["enablePeerPods"] is False + # Eligibility needs NFD labels; without NFD an enabled check blocks the install. + assert config["spec"]["checkNodeEligibility"] is False + _, (checked, _runtime) = render("--set", "enabled=true", "--set", "checkNodeEligibility=true") + assert checked["spec"]["checkNodeEligibility"] is True + expressions = config["spec"]["kataConfigPoolSelector"]["matchExpressions"] + assert {"key": "node-role.kubernetes.io/control-plane", "operator": "DoesNotExist"} in expressions + assert {"key": "node-role.kubernetes.io/master", "operator": "DoesNotExist"} in expressions + + +def test_enabled_ships_an_attachable_copy_of_the_operator_class(): + result, docs = render("--set", "enabled=true") + runtime, = [d for d in docs if d["kind"] == "RuntimeClass"] + assert runtime["metadata"]["name"] == "saw-kata" + # OpenShell refuses a class without this label; nobody labels it by hand. + assert runtime["metadata"]["labels"] == {"openshell.ai/sandbox-attachable": "true"} + assert runtime["handler"] == "kata" + assert runtime["overhead"] == {"podFixed": {"cpu": "250m", "memory": "350Mi"}} + assert runtime["scheduling"] == {"nodeSelector": {"node-role.kubernetes.io/kata-oc": ""}} + + +def test_the_class_must_stay_kata_and_placed(): + for override in (["--set", "runtimeClass.handler=runc"], ["--set-json", "runtimeClass.nodeSelector=null"]): + result, _ = render("--set", "enabled=true", *override) + assert result.returncode != 0 + + +def test_an_empty_selector_is_refused(): + result, _ = render("--set", "enabled=true", "--set-json", "poolSelector=null") + assert result.returncode != 0 + + +def test_the_pattern_installs_the_operator_and_leaves_the_pool_off(): + values = yaml.safe_load((ROOT / "values-prod.yaml").read_text())["clusterGroup"] + assert values["subscriptions"]["sandboxed-containers"]["name"] == "sandboxed-containers-operator" + namespace = values["namespaces"]["openshift-sandboxed-containers-operator"] + assert namespace["targetNamespaces"] == ["openshift-sandboxed-containers-operator"] + app = values["applications"]["saw-kata"] + assert app["path"] == "charts/saw-kata" + # Enabling reboots nodes: a per-cluster choice, never the shared default. + assert not [o for o in app.get("overrides", []) if o["name"] == "enabled"] diff --git a/tests/charts/test_saw_kubernetes_chart.py b/tests/charts/test_saw_kubernetes_chart.py index 1d5e918fa..c1d6f76c8 100644 --- a/tests/charts/test_saw_kubernetes_chart.py +++ b/tests/charts/test_saw_kubernetes_chart.py @@ -159,7 +159,7 @@ def test_repeat_renders_have_no_random_keys_or_identity(): @pytest.mark.parametrize('assignment', [ 'kubernetes.experimental=false', 'deployment.mode=confidential', 'deployment.mode=vm', 'kubernetes.gateway.image=repo:latest', - 'kubernetes.identity.serverTlsSecret=', 'kubernetes.storage.className=', + 'kubernetes.identity.serverTlsSecret=', 'kubernetes.workload.runtimeClassName=kata', 'kubernetes.supervisor.runtimeClassName=kata', 'oidc.issuerUrl=http://issuer.test', 'kubernetes.proxy.caConfigMap=', 'kubernetes.governance.endpoint=http://outside.example.test:18081', @@ -211,17 +211,31 @@ def test_unbounded_gateway_egress_rejected(rules): assert not result.stdout.strip() +def test_gateway_may_reach_any_address_only_for_https(): + """The OIDC issuer can sit behind a load balancer or an ingress virtual IP.""" + rules = [{'to': [{'ipBlock': {'cidr': '0.0.0.0/0'}}], 'ports': [{'protocol': 'TCP', 'port': 443}]}] + assert template('--set-json', 'kubernetes.network.gatewayEgress=' + json.dumps(rules)).returncode == 0 + rules[0]['ports'].append({'protocol': 'TCP', 'port': 80}) + assert template('--set-json', 'kubernetes.network.gatewayEgress=' + json.dumps(rules)).returncode != 0 + + def test_kata_uses_stock_workload_runtime_default_and_named_read(): docs = render('--set', 'deployment.mode=kata', '--set', 'kubernetes.workload.runtimeClassName=saw-kata') driver = config(docs)['drivers']['kubernetes'] assert driver['default_runtime_class_name'] == 'saw-kata' - assert 'supervisor_runtime_class_name' not in driver + # Two VMs: the supervisor gets its own Kata guest, not the workload's. + assert driver['supervisor_runtime_class_name'] == 'saw-kata' rules = docs['ClusterRole', 'saw-test-saw-test-gateway']['rules'] assert [r for r in rules if 'runtimeclasses' in r['resources']] == [ {'apiGroups': ['node.k8s.io'], 'resources': ['runtimeclasses'], 'verbs': ['get'], 'resourceNames': ['saw-kata']}] +def test_container_supervisors_keep_the_default_runtime(): + driver = config(render())['drivers']['kubernetes'] + assert 'supervisor_runtime_class_name' not in driver + + def test_container_keeps_stock_openshell_startup_timeouts(): docs = render() cfg = config(docs) @@ -267,3 +281,35 @@ 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']} + + +def test_ocsf_export_is_off_unless_a_collector_is_named(): + assert 'otlp' not in config(render())['gateway'] + endpoint = 'http://saw-ocsf-collector.openshell-agents.svc:4317' + otlp = config(render('--set', 'telemetry.ocsfEndpoint=' + endpoint))['gateway']['otlp'] + # OCSF only: no top-level endpoint, so OpenShell's own spans are not exported. + assert otlp == {'ocsf': {'enabled': True, 'endpoint': endpoint}} + + +def test_agent_trace_relay_forwards_to_the_same_collector(): + endpoint = 'http://saw-ocsf-collector.openshell-agents.svc:4317' + otlp = config(render('--set', 'telemetry.ocsfEndpoint=' + endpoint, + '--set', 'telemetry.agentTraces=true'))['gateway']['otlp'] + assert otlp == {'ocsf': {'enabled': True, 'endpoint': endpoint}, + 'agent': {'enabled': True, 'endpoint': endpoint}} + # The relay needs a collector to forward to. + assert template('--set', 'telemetry.agentTraces=true').returncode != 0 + + +@pytest.mark.parametrize('endpoint', ['saw-ocsf-collector:4317', 'http://collector', 'http://c:4317/v1/logs']) +def test_ocsf_endpoint_must_be_an_otlp_grpc_address(endpoint): + assert template('--set', 'telemetry.ocsfEndpoint=' + endpoint).returncode != 0 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..843084af3 100644 --- a/tests/charts/test_saw_runtime_policies.py +++ b/tests/charts/test_saw_runtime_policies.py @@ -169,6 +169,40 @@ def test_supervisor_accepts_stock_gateway_names_only(): assert "AWS_SECRET_ACCESS_KEY" not in rule +def supervisor_rule(*args): + validations = render(*args)["ValidatingAdmissionPolicy"]["spec"]["validations"] + rule, = [" ".join(item["expression"].split()) for item in validations + if item["message"] == "Supervisor executable, TLS projection and token must match the stock contract."] + return rule + + +def test_supervisor_may_carry_only_the_configured_ocsf_collector(): + assert "OPENSHELL_OTLP" not in supervisor_rule() + rule = supervisor_rule("--set", "ocsfEndpoint=http://saw-ocsf-collector.openshell-agents.svc:4317") + assert "'OPENSHELL_OTLP_OCSF_ENDPOINT'" in rule + assert ("e.name != 'OPENSHELL_OTLP_OCSF_ENDPOINT' || " + "e.value == \"http://saw-ocsf-collector.openshell-agents.svc:4317\"") in rule + assert "OPENSHELL_OTLP_ENDPOINT'" not in rule # traces stay off + assert "OPENSHELL_OTLP_AGENT_ENDPOINT" not in rule + + +def test_supervisor_may_carry_only_the_configured_agent_trace_collector(): + collector = "http://saw-ocsf-collector.openshell-agents.svc:4317" + rule = supervisor_rule("--set", "ocsfEndpoint=" + collector, "--set", "agentTraceEndpoint=" + collector) + assert "'OPENSHELL_OTLP_AGENT_ENDPOINT'" in rule + assert f"e.name != 'OPENSHELL_OTLP_AGENT_ENDPOINT' || e.value == \"{collector}\"" in rule + assert "OPENSHELL_OTLP_AGENT_PROTOCOL" not in rule # gRPC: the gateway sets no protocol + + +def test_supervisor_may_carry_a_numeric_attach_timeout(): + """OpenShell 0.1.10 passes a configured attach timeout (Kata: 900 s) to the + supervisor; only a plain number of seconds is admitted.""" + rule = supervisor_rule() + assert "'OPENSHELL_ATTACH_REQUEST_TIMEOUT_SECONDS'" in rule + assert ("e.name != 'OPENSHELL_ATTACH_REQUEST_TIMEOUT_SECONDS' || " + "(has(e.value) && e.value.matches('^[1-9][0-9]{0,4}$'))") in rule + + def test_identity_fences_cover_creation_and_label_removal_on_update(): vap = render()["ValidatingAdmissionPolicy"]["spec"] variables = {item["name"]: item["expression"] for item in vap["variables"]} @@ -255,5 +289,26 @@ def test_kata_enforces_reviewed_runtime_at_sandbox_and_pod(): else: assert resource == "pods" 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) + # The supervisor runs in a Kata VM of its own, never the default runtime. + assert any("variables.role != 'supervisor' || (has(object.spec.runtimeClassName) && " + 'object.spec.runtimeClassName == "saw-kata")' in check for check in checks) + assert not any("variables.role != 'supervisor' || !has(object.spec.runtimeClassName)" in check + for check in checks) + + +@pytest.mark.parametrize("packet,expected", [ + ({"ip": "203.0.113.7"}, "Pass"), # a public provider API on 443 + ({"ip": "203.0.113.7", "port": 80}, "Deny"), + ({"ip": "10.20.30.40"}, "Deny"), # private ranges stay closed + ({"ip": "172.16.0.9"}, "Deny"), + ({"ip": "192.168.1.1"}, "Deny"), + ({"ip": "169.254.169.254"}, "Deny"), # cloud metadata + ({"ip": "192.0.2.10"}, "Pass"), # explicit rules still apply first +]) +def test_public_https_lets_supervisors_reach_providers_but_not_private_networks(packet, expected): + anp = render("--set", "network.publicHTTPS=true")["AdminNetworkPolicy"] + assert packet_action(anp, **packet) == expected + + +def test_public_https_is_off_by_default(): + assert packet_action(render()["AdminNetworkPolicy"], ip="203.0.113.7") == "Deny" diff --git a/tests/charts/test_saw_users_chart.py b/tests/charts/test_saw_users_chart.py index 32d18e428..4311ad49c 100644 --- a/tests/charts/test_saw_users_chart.py +++ b/tests/charts/test_saw_users_chart.py @@ -69,19 +69,151 @@ 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", "ownerSubject": site["subject"], "profiles": ["data-science"], - "intentGeneration": 1, "vaultPrefix": "secret/data/hub/saw-alice/" + "a" * 16, + "intentGeneration": 1, "vaultPrefix": "secret/data/hub/saw-alice", "pruneOnRemove": True, "values": {"deployment": {"mode": "container"}}, } docs = docs_from(render_file(tmp_path, [user], {"containerSites": {"alice": site}})) rendered_site = helm_values(app(docs, "saw-alice"))["site"] - assert rendered_site["providerPolicy"]["allowHosts"] == site["providerAllowHosts"] + assert "providerPolicy" not in rendered_site and "providerAllowHosts" not in rendered_site + assert {b["secret"] for b in rendered_site["credentialBindings"]} >= {"inference"} + assert all(set(b) >= {"secret", "key", "type"} for b in rendered_site["credentialBindings"]) + + +def container_alice(**extra): + site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] + user = {"name": "alice", "registration": "3f9a1c0e7b2d4a68", "ownerSubject": site["subject"], + "profiles": ["data-science"], "intentGeneration": 1, "pruneOnRemove": True, + "vaultPrefix": "secret/data/hub/saw-alice", + "values": {"deployment": {"mode": "container"}}, **extra} + return user, {"containerSites": {"alice": site}} + + +@pytest.mark.parametrize(("given", "expected"), [ + (None, "c4d7d813-fd00-5645-b4b9-7b73e372d0dd"), # uuid5 of urn:saw:portal:alice:3f9a1c0e7b2d4a68 + ("22222222-2222-4222-8222-222222222222", "22222222-2222-4222-8222-222222222222"), +]) +def test_container_installation_id_defaults_to_portal_uuid5(tmp_path, given, expected): + user, extra = container_alice(**({"installationID": given} if given else {})) + docs = docs_from(render_file(tmp_path, [user], extra)) + namespace = [d for d in by_kind(docs, "Namespace") if d["metadata"]["name"] == "saw-alice"][0] + assert namespace["metadata"]["labels"]["saw.redhat.com/runtime-owner"] == expected + assert helm_values(app(docs, "saw-alice"))["installationID"] == expected + + +@pytest.mark.parametrize("auto_approve", [True, False]) +def test_minimal_container_entry_uses_cluster_defaults(tmp_path, auto_approve): + site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] + subject = site.pop("subject") + for item in site["stack"].values(): + item.pop("revision") + site["automaticEnrollment"].pop("revision") + site["automaticEnrollment"]["relay"].pop("revision") + site["automaticEnrollment"]["autoApprove"] = auto_approve + user = {"name": "alice", "ownerSubject": subject, "profiles": ["data-science"], + "vaultPrefix": "secret/data/hub", "values": {"deployment": {"mode": "container"}}} + docs = docs_from(render_file(tmp_path, [user], {"containerDefaults": site})) + values = helm_values(app(docs, "saw-alice")) + registration = "1f732dc2bd1766a0" # sha256("alice:1")[:16] + assert values["registration"] == registration + assert values["installationID"] == "a4300afa-4ae4-5da1-a5b1-44e50a34eb59" + assert values["vaultPrefix"] == "secret/data/hub/saw-alice" # the same for every generation + assert values["site"]["subject"] == subject + # Only an autoApprove site follows the pattern branch; a reviewed site must + # pin commit SHAs itself, so its revisions stay unset and the workspace + # chart and preflight reject it. + expected = {"main"} if auto_approve else {None} + assert {item.get("revision") for item in values["site"]["stack"].values()} == expected + assert values["site"]["automaticEnrollment"].get("revision") == next(iter(expected)) + assert values["site"]["automaticEnrollment"]["relay"].get("revision") == next(iter(expected)) + + +def test_per_user_auto_approve_false_overrides_the_default(tmp_path): + # Sprig's mergeOverwrite would drop the false; the portal's merge keeps it + # (tests/portal/test_portal.py), so both paths must agree. + site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] + subject = site.pop("subject") + site["automaticEnrollment"]["autoApprove"] = True + alice = {"name": "alice", "ownerSubject": subject, "profiles": ["data-science"], + "vaultPrefix": "secret/data/hub", "values": {"deployment": {"mode": "container"}}} + override = {"alice": {"automaticEnrollment": {"autoApprove": False}}} + values = helm_values(app(docs_from(render_file( + tmp_path, [alice], {"containerDefaults": site, "containerSites": override})), "saw-alice")) + enrollment = values["site"]["automaticEnrollment"] + assert enrollment["autoApprove"] is False + assert enrollment["image"] == site["automaticEnrollment"]["image"] # siblings still come from the defaults + + projection = {"enabled": True, "applicationSetControllerLabels": { + "app.kubernetes.io/name": "vp-gitops-applicationset-controller"}, + "egress": [{"to": [{"ipBlock": {"cidr": "10.0.0.3/32"}}], + "ports": [{"protocol": "TCP", "port": 6443}]}]} + (tmp_path / "projected").mkdir() + docs = docs_from(render_file(tmp_path / "projected", [alice], { + "containerDefaults": site, "containerSites": override, "projection": projection, + "ownerResolution": {"enabled": True}})) + config = [d for d in by_kind(docs, "ConfigMap") if d["metadata"]["name"].endswith("-configuration")] + projected = json.loads(config[0]["data"]["workspaces.json"])["containerSites"]["alice"] + assert projected["automaticEnrollment"]["autoApprove"] is False + + +def test_vm_and_container_users_coexist(tmp_path): + site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] + subject = site.pop("subject") + alice = {"name": "alice", "ownerSubject": subject, "profiles": ["data-science"], + "vaultPrefix": "secret/data/hub", "values": {"deployment": {"mode": "container"}}} + bob = {"name": "bob"} + projection = {"enabled": True, "applicationSetControllerLabels": { + "app.kubernetes.io/name": "vp-gitops-applicationset-controller"}, + "egress": [{"to": [{"ipBlock": {"cidr": "10.0.0.3/32"}}], + "ports": [{"protocol": "TCP", "port": 6443}]}]} + extra = {"containerDefaults": site, "projection": projection, "ownerResolution": {"enabled": True}} + mixed = docs_from(render_file(tmp_path, [alice, bob], extra)) + (tmp_path / "vm").mkdir() + alone = docs_from(render_file(tmp_path / "vm", [bob], {"ownerResolution": {"enabled": True}})) + + # Bob's VM resources are exactly what a VM-only list renders. + def bobs(docs): + return sorted((d["kind"], d["metadata"]["name"], json.dumps(d, sort_keys=True)) for d in docs + if d["metadata"].get("labels", {}).get("openshell.pattern/owner") == "bob" + or d["metadata"].get("namespace") == "saw-bob" or d["metadata"]["name"] == "saw-bob") + assert bobs(mixed) and bobs(mixed) == bobs(alone) + assert {"saw-bob", "saw-bob-secrets", "saw-bob-bom"} <= {d["metadata"]["name"] for d in by_kind(mixed, "Application")} + + # Alice goes through the projector only: no direct Application or Namespace. + names = {(d["kind"], d["metadata"]["name"]) for d in mixed} + assert ("Application", "saw-alice") not in names and ("Namespace", "saw-alice") not in names + config = [d for d in by_kind(mixed, "ConfigMap") if d["metadata"]["name"].endswith("-configuration")] + workspaces = json.loads(config[0]["data"]["workspaces.json"]) + assert [u["name"] for u in workspaces["users"]] == ["alice"] + assert list(workspaces["containerSites"]) == ["alice"] + assert workspaces["containerSites"]["alice"]["subject"] == subject + assert workspaces["users"][0]["registration"] == "1f732dc2bd1766a0" + assert "containerDefaults" not in workspaces + + +def test_container_user_without_subject_waits_without_blocking_others(tmp_path): + site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] + site.pop("subject") + alice = {"name": "alice", "profiles": ["data-science"], "values": {"deployment": {"mode": "container"}}} + docs = docs_from(render_file(tmp_path, [alice, {"name": "bob"}], {"containerDefaults": site})) + names = {(d["kind"], d["metadata"]["name"]) for d in docs} + assert ("Application", "saw-bob") in names + assert not any(n == "saw-alice" or n.startswith("saw-alice-") for _, n in names) + waiting = [d for d in by_kind(docs, "ConfigMap") if d["metadata"]["name"] == "saw-users-awaiting-owner"] + assert waiting[0]["data"]["users"] == "alice" + + +def test_container_entry_without_defaults_or_site_fails(tmp_path): + user = {"name": "alice", "ownerSubject": "11111111-1111-4111-8111-111111111111", + "profiles": ["data-science"], "values": {"deployment": {"mode": "container"}}} + result = render_file(tmp_path, [user]) + assert result.returncode != 0 and "requires containerDefaults or a containerSites entry" in result.stderr def test_static_owner_revision_pin_selects_all_children_and_preserves_sibling(tmp_path): @@ -805,3 +937,63 @@ def test_invalid_deployment_shape_rejected(tmp_path, deployment, level): assert result.returncode != 0 assert "deployment" in result.stderr assert not result.stdout.strip() + + +def test_the_projector_applicationset_is_not_held_behind_its_identity_job(): + """The identity Job owner-references its Secrets to the ApplicationSet and + waits for it, so a later sync wave would deadlock a fresh install.""" + source = (ROOT / "charts/saw-users/templates/projector.yaml").read_text() + appset = source[source.index("kind: ApplicationSet"):] + appset = appset[:appset.index("\nspec:")] + assert "sync-wave" not in appset + identity = (ROOT / "charts/saw-users/files/projector_identity.py").read_text() + assert '"ApplicationSet", "applicationsets"' in identity + + +def test_projector_needs_no_cluster_addresses(tmp_path): + """Defaults only: DNS by selector, the API through the control-plane nodes, + and the conventional ApplicationSet controller label.""" + 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"}}} + docs = docs_from(render_file(tmp_path, [alice], { + "containerDefaults": site, "projection": {"enabled": True}, "ownerResolution": {"enabled": True}})) + api, = by_kind(docs, "AdminNetworkPolicy") + assert api["spec"]["egress"][0]["action"] == "Allow" + assert api["spec"]["egress"][0]["to"][0]["nodes"]["matchExpressions"][0]["key"] == "node-role.kubernetes.io/control-plane" + labels = api["spec"]["subject"]["pods"]["podSelector"]["matchLabels"] + pods = [d["spec"]["template"]["metadata"]["labels"] for d in docs if d["kind"] in ("Deployment", "Job") + and d["metadata"]["name"].startswith("saw-projector-")] + assert pods and all(labels.items() <= p.items() for p in pods) + policy, = [d for d in by_kind(docs, "NetworkPolicy") if d["metadata"]["name"].startswith("saw-projector-")] + assert "ipBlock" not in json.dumps(policy["spec"]["egress"]) + assert policy["spec"]["ingress"][0]["from"][0]["podSelector"]["matchLabels"] == { + "app.kubernetes.io/name": "vp-gitops-applicationset-controller"} + + +def test_a_kata_user_defaults_to_the_pattern_runtime_class(tmp_path): + """No per-cluster binding in git: the projector reads saw-kata's UID and + digest on an autoApprove site, so it may read exactly that class.""" + site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] + subject = site.pop("subject") + site["automaticEnrollment"]["autoApprove"] = True + bob = {"name": "bob", "ownerSubject": subject, "profiles": ["data-science"], + "vaultPrefix": "secret/data/hub", "values": {"deployment": {"mode": "kata"}}} + docs = docs_from(render_file(tmp_path, [bob], {"containerDefaults": site, "projection": {"enabled": True}})) + config, = [d for d in by_kind(docs, "ConfigMap") if d["metadata"]["name"].endswith("-configuration")] + sites = json.loads(config["data"]["workspaces.json"])["containerSites"] + assert sites["bob"]["kataRuntimeClass"] == {"name": "saw-kata"} + rules = [r for d in by_kind(docs, "ClusterRole") for r in d.get("rules", [])] + assert {"apiGroups": ["node.k8s.io"], "resources": ["runtimeclasses"], + "resourceNames": ["saw-kata"], "verbs": ["get"]} in rules + + +def test_a_container_user_gets_no_runtime_class(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"}}} + docs = docs_from(render_file(tmp_path, [alice], {"containerDefaults": site, "projection": {"enabled": True}})) + config, = [d for d in by_kind(docs, "ConfigMap") if d["metadata"]["name"].endswith("-configuration")] + assert "kataRuntimeClass" not in json.loads(config["data"]["workspaces.json"])["containerSites"]["alice"] diff --git a/tests/charts/test_workspace_relay.py b/tests/charts/test_workspace_relay.py index 71e8fadb4..6016491f8 100644 --- a/tests/charts/test_workspace_relay.py +++ b/tests/charts/test_workspace_relay.py @@ -152,3 +152,12 @@ async def request(headers): for headers in [b"X-Forwarded-Email: reused-login", b"X-Forwarded-Email: owner-sub\r\nX-Forwarded-Email: foreign"]: with pytest.raises(ValueError): asyncio.run(request(headers)) + + +def test_identity_creation_waits_for_its_registrar_secret(): + """A failed Job is never recreated by Argo; creation must outlast a + Keycloak chart that is still bringing up the registrar credential.""" + import re + from pathlib import Path + source = (Path(__file__).resolve().parents[2] / "charts/saw-workspace-relay/templates/identity.yaml").read_text() + assert re.search(r'activeDeadlineSeconds: \{\{ if eq \$action "delete" \}\}300\{\{ else \}\}1800\{\{ end \}\}', source) diff --git a/tests/fixtures/container-site.yaml b/tests/fixtures/container-site.yaml index 65331a2b3..4109abba8 100644 --- a/tests/fixtures/container-site.yaml +++ b/tests/fixtures/container-site.yaml @@ -6,6 +6,8 @@ portal: containerSites: alice: modelLifecycle: true + # Most chart tests cover signed receipts; tests of the default remove this. + auditReceipts: true governanceNamespace: saw-builds subject: 11111111-1111-4111-8111-111111111111 stack: @@ -19,6 +21,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 +114,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 +132,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 +196,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 +256,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 +313,7 @@ portal: relayID: a8cb6cbd0eb62f31 subjectMap: saw-portal-relay-subject selectedDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - providerAllowHosts: - - api.openai.com - providerPolicy: - allowHosts: - - api.openai.com - bindings: - - secret: inference - key: api_key - providers: - - openai - markerPrefix: saw-cred - profiles: - openai: - - api.openai.com + credentialBindings: + - secret: inference + key: api_key + type: openai diff --git a/tests/installer/test_cli.py b/tests/installer/test_cli.py index 8356e62f1..c4ff75972 100644 --- a/tests/installer/test_cli.py +++ b/tests/installer/test_cli.py @@ -135,7 +135,7 @@ def test_new_bom_needs_install_before_apply(world): (world.inputs / "installer" / "installer-bom.yaml").write_text(yaml.safe_dump(world.bom)) result = world.run("apply") assert result.returncode == 1 - assert "install has not finished for BOM openshell-next (install: Done for openshell-0-1-6-rhaiv-4)" in result.stdout + assert "install has not finished for BOM openshell-next (install: Done for openshell-0-1-10-rhaiv-0)" in result.stdout assert not (world.state / "ready").exists() diff --git a/tests/installer/test_custom_endpoint.py b/tests/installer/test_custom_endpoint.py index acacf09bc..b139c6351 100644 --- a/tests/installer/test_custom_endpoint.py +++ b/tests/installer/test_custom_endpoint.py @@ -384,3 +384,54 @@ def test_reference_plan_shell_validates_regular_file_and_cleans_up(ab, tmp_path, assert [c['dryRun'] for c in calls] == ([True] if preflight_fails else [True, False]) assert all(t['ref']['id'] == 'CUSTOM_INFERENCE_API_KEY' for t in calls[0]['plan']['targets']) assert not list(tmp_path.glob('saw-credential-ref.*')) + + +def test_a_thinking_level_marks_the_model_as_reasoning_and_sets_its_default( + ab, fake_env, config, profiles, custom_secrets, governed_catalog): + """OpenClaw offers only default/off for a custom model unless its entry + says reasoning: true and lists the efforts; the level is then the model's + default (a chat's /think still overrides it).""" + notebook(profiles).inference["thinking"] = "medium" + creds = resolve(ab, profiles, custom_secrets) + ab.ProfileApplier(ab.Shell(), config, creds).apply(profiles) + state = fake_env.openshell_state() + sb = state["sandboxes"]["default/notebook"] + model_id = f"custom-inference/{MODEL}" + assert sb["openclawConfig"]["agents.defaults.models"][model_id] == {"params": {"thinking": "medium"}} + # Onboarding wrote the model entry; a rerun marks it as a reasoning model. + sb["openclawConfig"]["models.providers.custom-inference.models"] = [ + {"id": MODEL, "name": MODEL, "contextWindow": 128000}, {"id": "other"}] + fake_env.set_openshell_state(state) + ab.ProfileApplier(ab.Shell(), config, creds).apply(profiles) + models = fake_env.openshell_state()["sandboxes"]["default/notebook"]["openclawConfig"][ + "models.providers.custom-inference.models"] + assert models == [{"id": MODEL, "name": MODEL, "contextWindow": 128000, "reasoning": True, + "compat": {"supportedReasoningEfforts": ["low", "medium", "high"]}}, + {"id": "other"}] + # off marks the model as not reasoning, so no reasoning_effort is sent. + notebook(profiles).inference["thinking"] = "off" + ab.ProfileApplier(ab.Shell(), config, resolve(ab, profiles, custom_secrets)).apply(profiles) + cfg = fake_env.openshell_state()["sandboxes"]["default/notebook"]["openclawConfig"] + assert cfg["models.providers.custom-inference.models"][0] == { + "id": MODEL, "name": MODEL, "contextWindow": 128000, "reasoning": False} + assert cfg["agents.defaults.models"][model_id] == {"params": {"thinking": "off"}} + # Removing the level stops it applying. + del notebook(profiles).inference["thinking"] + ab.ProfileApplier(ab.Shell(), config, resolve(ab, profiles, custom_secrets)).apply(profiles) + assert fake_env.openshell_state()["sandboxes"]["default/notebook"]["openclawConfig"][ + "agents.defaults.models"][model_id] == {} + + +@pytest.mark.parametrize("level", ["max", "Medium", 1]) +def test_an_unknown_thinking_level_is_refused(ab, profiles, level): + sb = notebook(profiles) + sb.inference["thinking"] = level + assert any("thinking must be one of" in p for p in ab.sandbox_inference_problems(sb, {"custom-inference": "custom-inference"})) + + +def test_an_unquoted_yaml_off_means_off(ab): + """YAML 1.1 reads `thinking: off` as false; it still means off.""" + files = profile_files("custom-inference") + key = next(k for k in files if k.endswith("__sandbox.yaml")) + files[key] = files[key].replace('timeoutSeconds: "300"', 'timeoutSeconds: "300"\n thinking: off') + assert notebook(ab.parse_profiles(files)).inference["thinking"] == "off" diff --git a/tests/portal/test_portal.py b/tests/portal/test_portal.py index 3dc99b405..38c417a93 100644 --- a/tests/portal/test_portal.py +++ b/tests/portal/test_portal.py @@ -17,6 +17,7 @@ from urllib.parse import parse_qs, urlsplit import pytest +import yaml ROOT = Path(__file__).resolve().parents[2] PORTAL = ROOT / "charts" / "openshell-rhdh" / "files" / "portal.py" @@ -242,6 +243,52 @@ def catalog(portal): return portal.load_catalog(CATALOG) +def test_per_user_auto_approve_false_overrides_the_default(portal, monkeypatch): + # Same override as tests/charts/test_saw_users_chart.py: the portal and the + # saw-users chart must agree that a per-user false wins. + defaults = {"automaticEnrollment": {"autoApprove": True, "image": "runtime@sha256:" + "a" * 64}} + monkeypatch.setenv("SAW_CONTAINER_DEFAULTS", json.dumps(defaults)) + monkeypatch.setenv("SAW_CONTAINER_SITES", json.dumps( + {"alice": {"automaticEnrollment": {"autoApprove": False}}})) + monkeypatch.delenv("SAW_TARGET_REVISION", raising=False) + alice = portal.container_site("alice", subject="11111111-1111-4111-8111-111111111111") + assert alice["automaticEnrollment"] == {"autoApprove": False, "image": "runtime@sha256:" + "a" * 64} + assert portal.auto_approved(alice) is False + assert portal.auto_approved(portal.container_site( + "bob", subject="22222222-2222-4222-8222-222222222222")) is True + + +@pytest.mark.parametrize("auto_approve", [True, False]) +def test_only_auto_approve_sites_follow_the_pattern_branch(portal, monkeypatch, auto_approve): + # Same rule as the saw-portal-container chart (tests/charts/test_portal_container.py). + site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] + for item in site["stack"].values(): + item.pop("revision") + site["automaticEnrollment"].pop("revision") + site["automaticEnrollment"]["relay"].pop("revision") + site["automaticEnrollment"]["autoApprove"] = auto_approve + site["credentialBindings"] = [] + monkeypatch.setenv("SAW_CONTAINER_DEFAULTS", json.dumps(site)) + monkeypatch.setenv("SAW_CONTAINER_SITES", "{}") + monkeypatch.setenv("SAW_TARGET_REVISION", "main") + resolved = portal.container_site("alice", subject=site["subject"]) + revisions = {item.get("revision") for item in resolved["stack"].values()} + assert revisions == ({"main"} if auto_approve else {None}) + assert portal._preflight.configuration_facts(resolved)["revisions"] is auto_approve + + +def test_preflight_gets_the_bindings_the_chart_renders(portal, catalog): + # Same list as saw-users.credentialBindings: nvidia also serves build, + # and a refreshable credential is marked for OpenShell's refresh flow. + assert portal.credential_bindings(catalog["personal-assistant"]) == [ + {"secret": "gmail", "key": "access_token", "type": "gmail", "refresh": "oauth2_refresh_token"}, + {"secret": "inference", "key": "api_key", "type": "nvidia"}, + {"secret": "inference", "key": "api_key", "type": "build"}, + {"secret": "slack", "key": "bot_token", "type": "slack"}, + ] + assert portal.credential_bindings({}) == [] + + def test_a_request_gets_the_profiles_secrets(portal, catalog): profile, secrets = portal.parse_request({ "profile": "data-science", "inference.api_key": " nvapi-1 ", "web-search.api_key": "brave-1", @@ -2254,13 +2301,11 @@ def state(name, operation, generation, **extra): assert json.dumps(fake.vault, sort_keys=True) == vault_before -def test_custom_endpoint_is_approved_before_writing_vault(portal, world, monkeypatch): +def test_custom_endpoint_is_validated_before_writing_vault(portal, world, monkeypatch): fake, signer = world url="https://models.fixture.test/v1" - boundary={"allowHosts":["models.fixture.test"],"inferenceBaseURL":url} site=synthetic_preflight_site(portal, { "subject":"478fdd1f-8db9-41e8-97ad-b563215c89e9", - "profileBoundaries":{"custom-inference":boundary}, "automaticEnrollment":{"approvedProfiles":{"custom-inference":"a"*64}}, }) monkeypatch.setenv("SAW_DEPLOYMENT_MODES",'["vm","container"]') @@ -2271,7 +2316,10 @@ def submit(name,endpoint): request.pop("web-search.api_key") fake.request(name,request) return portal.main(["create",name]) - assert submit("saw-req-bad","https://elsewhere.example/v1") != 0 + # A malformed URL is refused before any key reaches Vault. Which host may + # receive the key is the custom-inference governance profile's call, checked + # by the runtime controller (tests/kubernetes_runtime/test_provider_endpoints.py). + assert submit("saw-req-bad","http://models.fixture.test/v1") != 0 assert not fake.vault and REGISTRY not in fake.objects assert submit("saw-req-good",url) == 0 entry=portal.read_entry(fake.objects[REGISTRY]) From 89b80e6ae359d1ffa976e60c6265d20972f971fe Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Wed, 25 Nov 2026 07:17:17 +0000 Subject: [PATCH 3/9] Pattern configuration, saw-init and live checks - values-prod: OpenShift sandboxed containers and Red Hat build of OpenTelemetry operators, saw-kata (off by default), saw-telemetry, agent-sandbox, container defaults for saw-users and the portal. - make saw-init is the one preparation step: storage classes and, only for audit receipts, the shared RWX class. - make e2e-workspace checks one user's live workspace for vm, container or kata: Argo, sandbox, Kata placement, a real inference turn, the tool-gate audit entry and OCSF export. - Scripts and tests follow OpenShell v0.1.10. Assisted-By: Claude --- Makefile | 4 +- Makefile-quickstart | 28 +- scripts/ci/deployment_validation.py | 6 +- scripts/container-workspace.py | 65 ++- scripts/container_topology.py | 226 ---------- scripts/e2e-workspace.sh | 191 +++++++++ scripts/keycloak-users.sh | 40 +- scripts/oidc_topology_probe.py | 47 --- .../setup-relay-provisioner.py | 174 -------- scripts/saw-init.sh | 162 ++++++++ scripts/saw-profile-catalog.py | 7 +- scripts/shared-storage.sh | 389 ++++++++++++++++++ scripts/test-deployment.sh | 2 +- tests/scripts/test_container_installation.py | 87 ++-- tests/scripts/test_container_topology.py | 270 ------------ tests/scripts/test_make_interface.py | 9 +- .../test_profile_catalog_automation.py | 7 +- tests/scripts/test_relay_provisioner.py | 116 ++++++ tests/scripts/test_saw_init.py | 99 +++++ tests/scripts/test_saw_preflight.py | 35 +- tests/scripts/test_shared_storage.py | 116 ++++++ tests/scripts/test_standalone_projector.py | 54 ++- tests/scripts/test_workspace_projection.py | 78 ++++ values-prod.yaml | 49 +++ 24 files changed, 1433 insertions(+), 828 deletions(-) delete mode 100644 scripts/container_topology.py create mode 100755 scripts/e2e-workspace.sh delete mode 100644 scripts/oidc_topology_probe.py delete mode 100644 scripts/portal-container/setup-relay-provisioner.py create mode 100755 scripts/saw-init.sh create mode 100755 scripts/shared-storage.sh delete mode 100644 tests/scripts/test_container_topology.py create mode 100644 tests/scripts/test_relay_provisioner.py create mode 100644 tests/scripts/test_saw_init.py create mode 100644 tests/scripts/test_shared_storage.py diff --git a/Makefile b/Makefile index 7405b836e..96d8c9ff5 100644 --- a/Makefile +++ b/Makefile @@ -8,7 +8,9 @@ include Makefile-quickstart # SAW: a default StorageClass must exist before the GitOps apply provisions # the VM disks (they set no storageClassName). Interactive on a TTY; offers to # reuse an existing class or enable HPP. See scripts/storage-class-check.sh. -pattern-install: storage-class-check +# saw-init adds the container-mode checks when overrides/saw-users.yaml has +# container or kata users (scripts/saw-init.sh). +pattern-install: saw-init # Bootstrap stock GitOps before the framework selects its Argo CD namespace. .PHONY: prepare-gitops diff --git a/Makefile-quickstart b/Makefile-quickstart index df2eb1e81..81003e375 100644 --- a/Makefile-quickstart +++ b/Makefile-quickstart @@ -18,7 +18,7 @@ MIRROR_IMAGES ?= openshell-gateway IMAGE_TAG ?= latest # OpenShell release the governance interceptor is built from (must match the # SAW gateways; image-builder-charts/helm/governance-interceptor-image). -OPENSHELL_INTERCEPTOR_REF ?= v0.1.6 +OPENSHELL_INTERCEPTOR_REF ?= v0.1.10 DEPLOYMENT_MODE ?= vm SAW_USERS_VALUES_FILE ?= SAW_INSTALL_NAMESPACE ?= saw-workspaces @@ -119,10 +119,10 @@ endif governance-interceptor-build governance-interceptor-build-local \ keycloak-deploy keycloak-delete keycloak-check keycloak-issuer \ keycloak-register keycloak-redirects keycloak-redirects-sync \ - keycloak-passwords keycloak-harden keycloak-session-max keycloak-add-users keycloak-add-user keycloak-password keycloak-reset-password \ + keycloak-passwords keycloak-harden keycloak-session-max keycloak-add-users keycloak-add-user keycloak-password keycloak-reset-password keycloak-user-info saw-init \ login whoami logout saw-create saw-configure saw-list saw-logs saw-status \ saw-restart saw-restart-pending saw-vm-ssh saw-ssh saw-tui saw-gui saw-delete \ - sandbox-pre-delete quickstart-delete status test test-deployment test-dependencies test-pattern-e2e test-pattern-e2e-install test-pattern-e2e-live test-pattern-e2e-cleanup test-harness-e2e lint \ + 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 e2e-workspace lint \ governance-profile-list governance-profile-add governance-profile-remove \ governance-profile-create governance-deploy governance-delete governance-demo portal-vault-setup sandbox-ui \ nemoclaw-tui openclaw-tui nemoclaw-gui openclaw-gui \ @@ -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, SSH keys, OIDC CA check, gateway image, container prerequisites + @$(SCRIPTS_DIR)/saw-init.sh + check-oidc-ca: ## Check if the OIDC issuer needs a CA bundle @$(SCRIPTS_DIR)/check-oidc-ca.sh @@ -314,9 +317,6 @@ pre-uninstall: ## Drain GitOps writers, then delete owned VMs before framework u @python3 $(SCRIPTS_DIR)/pattern-drain-applications.py @$(SCRIPTS_DIR)/pattern-pre-uninstall.sh -# Generate SSH keys before install. No deletions — safe to run repeatedly. -pattern-install: ssh-key-generate - # Handle a missing pattern CR without changing the framework install target. # OLM cleanup runs AFTER rhvp.cluster_utils.uninstall removes the ArgoCD apps # (including the openshift-cnv app that manages the Subscription). This prevents @@ -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)" @@ -425,16 +429,9 @@ keycloak-delete: ## Uninstall Keycloak and its database ##@ Sandbox Operations -.PHONY: container-topology check-container-topology -container-topology: ## Print the site network overlay discovered from OpenShift and a trusted Pod - @$(or $(PYTHON),uv run --locked python) $(SCRIPTS_DIR)/container_topology.py - -check-container-topology: ## Compare the reviewed site network overlay with live OpenShift observations - @test -n "$${SAW_TOPOLOGY_OVERLAY}" || { echo "Set SAW_TOPOLOGY_OVERLAY" >&2; exit 1; } - @$(or $(PYTHON),uv run --locked python) $(SCRIPTS_DIR)/container_topology.py --check "$${SAW_TOPOLOGY_OVERLAY}" - 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 @@ -591,6 +588,9 @@ git-hooks: ## Use the repo's git hooks (regenerate the catalogs on commit) test-deployment: ## Run the live OpenShift deployment test (read docs first) @$(SCRIPTS_DIR)/test-deployment.sh +e2e-workspace: .check-saw-name .check-deployment-mode ## Check one workspace end to end: Argo, sandbox, OpenClaw inference, audit, OCSF (OPENSHELL_SAW_NAME=alice DEPLOYMENT_MODE=container|kata|vm) + @$(SCRIPTS_DIR)/e2e-workspace.sh --mode "$(DEPLOYMENT_MODE)" --user "$(OPENSHELL_SAW_NAME)" + test-dependencies: ## Validate rendered charts and deployment dependencies @uv run --locked scripts/ci/deployment_validation.py --report deployment-validation.json diff --git a/scripts/ci/deployment_validation.py b/scripts/ci/deployment_validation.py index 4d7f83ecf..f66d01b3e 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", @@ -105,6 +105,8 @@ def chart_args(chart: Path, mode="proxy") -> list[str]: return ["--set", "enabled=true", "--set-string", f"images[0]={image}"] if name == "agent-sandbox": return ["--namespace", "agent-sandbox-system", "--set", "enabled=true"] + if name == "saw-kata": + return ["--namespace", "openshift-sandboxed-containers-operator", "--set", "enabled=true"] if name == "saw-kubernetes-controller": return ["--namespace", "saw-ci-trusted", "-f", str(ROOT / "tests/fixtures/saw-kubernetes-controller-values.yaml")] @@ -130,7 +132,7 @@ def render_charts(result: Validation, output_dir: Path) -> None: portal_values = dict( owner="alice", ownerSubject=site["subject"], registration="a8cb6cbd0eb62f31", installationID="802fe583-9329-54b6-b5b4-7be58ec171f3", intentGeneration=1, - vaultPrefix="secret/data/hub/saw-alice/a8cb6cbd0eb62f31", site=site, + vaultPrefix="secret/data/hub/saw-alice", site=site, **{"global": {"repoURL": "https://github.com/example/secure-agent-workspace", "targetRevision": "main", "vpArgoNamespace": "vp-gitops", "clusterDomain": "cluster.example.test"}}) diff --git a/scripts/container-workspace.py b/scripts/container-workspace.py index 36e876024..82e7ab48d 100644 --- a/scripts/container-workspace.py +++ b/scripts/container-workspace.py @@ -7,6 +7,7 @@ """ import argparse import copy +import hashlib import importlib.util import json import os @@ -17,6 +18,7 @@ import sys import tempfile import time +import uuid from urllib.request import HTTPRedirectHandler, build_opener import yaml @@ -32,7 +34,6 @@ def load_module(name, source): workspace = load_module("saw_workspace", ROOT / "charts/saw-users/files/workspace.py") -container_topology = load_module("container_topology", ROOT / "scripts/container_topology.py") preflight_checks = load_module("saw_preflight", ROOT / "charts/saw-portal-container/files/preflight.py") kata_worker_check = load_module("kata_worker_check", ROOT / "scripts/kata_worker_check.py") @@ -64,6 +65,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 base.endswith((f"/saw-{name}", f"/saw-{name}/{user['registration']}")): + base = f"{base}/saw-{name}" # the same for every generation; the portal's keeps its registration + user["vaultPrefix"] = base + user.setdefault("pruneOnRemove", True) + user.setdefault("intentGeneration", 1) + if not user.get("installationID") and re.fullmatch(r"[a-f0-9]{16}", str(user["registration"])): + user["installationID"] = str(uuid.uuid5(uuid.NAMESPACE_URL, f"urn:saw:portal:{name}:{user['registration']}")) + + +def container_site(config, user): + """Same layering as saw-users.containerSite: containerDefaults under containerSites..""" + site = deep_merge(config.get("containerDefaults") or {}, config.get("containerSites", {}).get(user["name"]) or {}) + if site and not site.get("subject"): + site["subject"] = user.get("ownerSubject") + return site + + +def resolve_subject(name): + """The enabled Keycloak account's subject, as `make keycloak-user-info` prints it.""" + try: + subject = subprocess.run([str(Path(__file__).with_name("keycloak-users.sh")), "resolve-subject", name], + capture_output=True, text=True, timeout=90, check=True).stdout.strip() + except (OSError, subprocess.SubprocessError): + raise InstallError(f"set ownerSubject for {name}, or create the Keycloak account first " + f"(make keycloak-add-user KC_USER={name})") from None + return subject + + def select(values, name): """The operator supplies the same public saw-users/site configuration as GitOps.""" if not isinstance(values, dict): @@ -82,12 +125,15 @@ def select(values, name): if mode not in {"container", "kata"} or mode != os.environ.get("DEPLOYMENT_MODE", "container"): raise InstallError("the selected user must explicitly select the requested Kubernetes deployment mode") config["ownerResolution"] = {**config.get("ownerResolution", {}), "enabled": False} + if not user.get("ownerSubject"): + user["ownerSubject"] = resolve_subject(name) + apply_container_defaults(config, user) for field, pattern in [("registration", r"[a-f0-9]{16}"), ("installationID", r"[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}"), ("ownerSubject", r"[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}")]: if not re.fullmatch(pattern, str(user.get(field, ""))): raise InstallError("container inputs require a valid "+field) - site = config.get("containerSites", {}).get(name) + site = container_site(config, user) if not site or site.get("subject") != user["ownerSubject"] or user.get("pruneOnRemove") is not True: raise InstallError("container inputs require the matching site identity and foreground cleanup") if type(user.get("intentGeneration")) is not int or user["intentGeneration"] < 1: @@ -322,8 +368,11 @@ def status(user, config): class NoRedirect(HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): return None - site = config["containerSites"][user["name"]] - issuer = site["automaticEnrollment"]["relay"]["issuer"] + site = container_site(config, user) + relay = site.get("automaticEnrollment", {}).get("relay", {}) + # The charts' default: the cluster's Keycloak route. + issuer = relay.get("issuer") or "https://openshell-keycloak-ingress-{}.apps.{}/realms/openshell".format( + relay.get("keycloakNamespace") or "saw-keycloak", config.get("global", {}).get("clusterDomain")) client = build_opener(NoRedirect()) catalog = json.loads((ROOT/"charts/saw-users/files/profile-catalog.json").read_text())["profiles"] def observed(path): @@ -355,14 +404,6 @@ def main(): config, user = select(yaml.safe_load(Path(args.values).read_text()), args.name) for command in ("oc", "helm"): if not shutil.which(command): raise InstallError(command+" is required") - overlay = os.environ.get("SAW_TOPOLOGY_OVERLAY") - if not overlay and os.environ.get("SAW_TOPOLOGY_PROBE"): - raise InstallError("set SAW_TOPOLOGY_OVERLAY to the local reviewed overlay path") - if overlay: - container_topology.install_values(config, args.name, overlay, - os.environ.get("SAW_TOPOLOGY_PROBE"), - os.environ.get("SAW_TOPOLOGY_CONTAINER"), - verify=args.action == "apply") # Validate chart inputs before contacting or changing the cluster. with tempfile.TemporaryDirectory(prefix="saw-container-values-") as directory: values_file = Path(directory)/"values.json" diff --git a/scripts/container_topology.py b/scripts/container_topology.py deleted file mode 100644 index 7fd342686..000000000 --- a/scripts/container_topology.py +++ /dev/null @@ -1,226 +0,0 @@ -#!/usr/bin/env python3 -"""Render or check a public container egress overlay using cluster observations.""" -import argparse -import ipaddress -import json -import os -from pathlib import Path -import re -import subprocess -import sys -import tempfile -from urllib.parse import urlsplit - -import yaml - -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") -RELAY = ("automaticEnrollment", "relay") - - -def command(*args): - result = subprocess.run(args, capture_output=True, text=True, timeout=90) - if result.returncode: - raise ValueError(f"{Path(args[0]).name} {args[1]} failed; check the cluster context, probe and trust configuration") - return result.stdout.strip() - - -def path_value(obj, path, default=None): - for key in path: - if not isinstance(obj, dict): - raise ValueError("expected a mapping at " + ".".join(path)) - if key not in obj: - return default - obj = obj[key] - return obj - - -def put(obj, path, value): - for key in path[:-1]: - obj = obj.setdefault(key, {}) - obj[path[-1]] = value - - -def egress(base, path, extra): - rules = path_value(base, path, []) - if not isinstance(rules, list): - raise ValueError("expected an egress list at " + ".".join(path)) - # Helm replaces lists. Carry forward operator-authored governance/proxy rules. - return rules + [rule for rule in extra if rule not in rules] - - -def host_rule(address, port): - ip = ipaddress.IPv4Address(address) - if ip.is_unspecified or ip.is_loopback or ip.is_multicast or ip.is_link_local or ip.is_reserved: - raise ValueError("unsafe IPv4 policy destination") - if type(port) is not int or not 1 <= port <= 65535: - raise ValueError("invalid policy port") - return {"to": [{"ipBlock": {"cidr": f"{ip}/32"}}], - "ports": [{"protocol": "TCP", "port": port}]} - - -def issuer_port(url): - parsed = urlsplit(url) - if (parsed.scheme != "https" or not parsed.hostname or parsed.username is not None - or parsed.password is not None or any(ch in url for ch in ("?", "#", "\\")) - or any(ord(ch) < 33 or ord(ch) == 127 for ch in url) or parsed.port == 0): - raise ValueError("expected an HTTPS issuer without userinfo, query or fragment") - return parsed.port or 443 - - -def discover_issuer(issuer, probe, container): - ns, sep, pod = probe.partition("/") - if not sep or not DNS_LABEL.fullmatch(ns) or not all(DNS_LABEL.fullmatch(x) for x in pod.split(".")): - raise ValueError("probe must be an existing namespace/pod") - if container and not DNS_LABEL.fullmatch(container): - raise ValueError("invalid probe container") - port = issuer_port(issuer) - args = ["oc", "-n", ns, "exec", "pod/" + pod] - if container: - args += ["-c", container] - script = (SCRIPTS / "oidc_topology_probe.py").read_text() - answers = json.loads(command(*args, "--", "python3", "-c", script, issuer)) - if isinstance(answers, dict): - reason = answers.get("error") - messages = {"dns": "in-cluster issuer DNS failed", "tls": "issuer TLS verification failed", - "connection": "issuer HTTPS connection failed", "discovery": "invalid issuer address or discovery document"} - raise ValueError(messages.get(reason, "invalid in-cluster probe response") - if isinstance(reason, str) else "invalid in-cluster probe response") - if not isinstance(answers, list) or not answers or not all(isinstance(a, str) for a in answers): - raise ValueError("invalid in-cluster DNS result") - return [host_rule(ip, port) for ip in sorted(set(answers), key=ipaddress.IPv4Address)] - - -def container_overlay(values, probe, container=None): - topology = json.loads(command(sys.executable, str(SCRIPTS / "network-topology.py"), "print-json")) - api = topology["cleanupApi"] - destinations = {(api["serviceIP"], 443)} | {(e["ip"], e["port"]) for e in api["endpoints"]} - api_rules = [host_rule(ip, port) for ip, port in sorted(destinations)] - dns = json.loads(command("oc", "get", "service", "dns-default", "-n", "openshift-dns", "-o", "json"))["spec"] - peers = {"namespaceSelector": {"matchLabels": {"kubernetes.io/metadata.name": "openshift-dns"}}, - "podSelector": {"matchLabels": {"dns.operator.openshift.io/daemonset-dns": "default"}}} - if dns.get("selector", {}).get("dns.operator.openshift.io/daemonset-dns") != "default": - raise ValueError("unrecognized OpenShift DNS Service selector") - dns_ip = host_rule(dns["clusterIP"], 53)["to"] - service_ports = {p["name"]: p["protocol"] for p in dns.get("ports", []) - if p.get("port") == 53 and p.get("protocol") in ("TCP", "UDP")} - if set(service_ports.values()) != {"TCP", "UDP"}: - raise ValueError("expected OpenShift DNS on TCP and UDP port 53") - slices = json.loads(command("oc", "get", "endpointslice", "-n", "openshift-dns", "-l", - "kubernetes.io/service-name=dns-default", "-o", "json")) - backends = {(p["protocol"], p["port"]) for item in slices["items"] if item.get("addressType") == "IPv4" - for p in item.get("ports", []) if p.get("name") in service_ports - and p.get("protocol") == service_ports[p["name"]] and type(p.get("port")) is int - and 0 < p["port"] <= 65535} - if {protocol for protocol, port in backends} != {"TCP", "UDP"}: - raise ValueError("incomplete DNS EndpointSlice ports") - dns_ports = [{"protocol": protocol, "port": 53} for protocol in ("TCP", "UDP")] - dns_rules = [{"to": dns_ip, "ports": dns_ports}, - {"to": [peers], "ports": [{"protocol": p, "port": n} for p, n in sorted(backends)]}] - common = api_rules + dns_rules - domain = json.loads(command("oc", "get", "ingress.config.openshift.io", "cluster", "-o", "json"))["spec"]["domain"] - if not domain.startswith("apps.") or path_value(values, ("global", "clusterDomain"), domain[5:]) != domain[5:]: - raise ValueError("clusterDomain differs from the current cluster ingress domain") - overlay = {} - checked = {} - for scope in [(), ("portal",)]: - sites = path_value(values, scope + ("containerSites",), {}) - if not isinstance(sites, dict): - raise ValueError("containerSites must be a mapping") - for owner, site in sites.items(): - if not isinstance(site, dict) or not path_value(site, GATEWAY) or not path_value(site, RELAY): - raise ValueError("expected gateway and automatic enrollment relay site inputs") - 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): - raise ValueError("gateway and relay must use the same issuer") - if issuers: - issuer = issuers.pop() - else: - namespace = path_value(site, RELAY + ("keycloakNamespace",)) - if not isinstance(namespace, str) or not DNS_LABEL.fullmatch(namespace): - raise ValueError("expected relay Keycloak namespace") - host = command(str(SCRIPTS / "keycloak-host.sh"), namespace) - issuer = f"https://{host}/realms/{os.environ.get('KEYCLOAK_REALM', 'openshell')}" - if issuer not in checked: - checked[issuer] = discover_issuer(issuer, probe, container) - out = {} - for path in [GATEWAY + ("oidc", "issuerUrl"), RELAY + ("issuer",)]: - put(out, path, issuer) - for path in [GATEWAY + ("kubernetes", "network", "gatewayEgress"), RELAY + ("egress",)]: - put(out, path, egress(site, path, common + checked[issuer])) - put(out, BOOTSTRAP, egress(site, BOOTSTRAP, common)) - put(overlay, scope + ("containerSites", owner), out) - if not scope and sites: - put(overlay, ("projection", "egress"), egress(values, ("projection", "egress"), common)) - if not overlay: - raise ValueError("no containerSites in site values") - return overlay - - -def install_values(config, owner, overlay_file, probe, container, verify): - """Consume only managed fields from this owner's reviewed overlay.""" - site_path = ("containerSites", owner) - paths = [("projection", "egress")] + [site_path + path for path in [ - GATEWAY + ("oidc", "issuerUrl"), RELAY + ("issuer",), - GATEWAY + ("kubernetes", "network", "gatewayEgress"), RELAY + ("egress",), BOOTSTRAP]] - expected = None - if verify: - if not probe: - raise ValueError("SAW_TOPOLOGY_PROBE is required to check live container topology") - base = {"global": config.get("global", {}), "projection": config.get("projection", {}), - "containerSites": {owner: path_value(config, site_path)}} - expected = container_overlay(base, probe, container) - path_on_disk = Path(overlay_file) - if not path_on_disk.exists() and verify: - if path_value(config, site_path + ("automaticEnrollment", "enabled")) is not False: - 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) - tmp.flush() - try: - os.link(tmp.name, path_on_disk) - except FileExistsError: - pass - try: - approved = yaml.safe_load(path_on_disk.read_text()) - except yaml.YAMLError: - raise ValueError("invalid YAML in container topology overlay") from None - if not isinstance(approved, dict): - raise ValueError("expected a reviewed container topology overlay") - for path in paths: - value = path_value(approved, path) - if value is None or (verify and value != path_value(expected, path)): - raise ValueError("missing or stale container topology at " + ".".join(path) - + "; regenerate from base inputs and review the changes") - for path in paths: - put(config, path, path_value(approved, path)) - - -def main(): - p = argparse.ArgumentParser(description=__doc__) - p.add_argument("--values-file", default=os.environ.get("SAW_USERS_VALUES_FILE"), type=Path) - p.add_argument("--probe", default=os.environ.get("SAW_TOPOLOGY_PROBE"), help="trusted namespace/pod with Python 3 and issuer CA trust") - p.add_argument("--container", default=os.environ.get("SAW_TOPOLOGY_CONTAINER")) - p.add_argument("--check", type=Path, help="compare a reviewed overlay with live observations") - args = p.parse_args() - if not args.values_file or not args.probe: - p.error("supply the base values file and trusted probe namespace/pod") - try: - found = container_overlay(yaml.safe_load(args.values_file.read_text()), args.probe, args.container) - if args.check: - 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)) - except yaml.YAMLError: - p.exit(1, "Container topology check failed: invalid YAML input\n") - except (ValueError, OSError, KeyError, TypeError, subprocess.SubprocessError) as exc: - p.exit(1, f"Container topology check failed: {exc}\n") - - -if __name__ == "__main__": - main() diff --git a/scripts/e2e-workspace.sh b/scripts/e2e-workspace.sh new file mode 100755 index 000000000..c329d4d44 --- /dev/null +++ b/scripts/e2e-workspace.sh @@ -0,0 +1,191 @@ +#!/usr/bin/env bash +# Live end-to-end check of one SAW user's workspace, for any deployment mode. +# +# Follows the README: a user added in overrides/saw-users.yaml, deployed by +# Argo CD. This script changes nothing on the cluster except one OpenClaw +# turn inside the user's own sandbox (which adds one tool-gate audit entry). +# +# W1 Argo CD applications for the user are Synced and Healthy +# W2 sandbox is running (container/kata: supervisor + workload Ready; +# vm: VirtualMachineInstance Running and the gateway answers) +# W3 kata only: workload and supervisor Pods both run in the Kata +# RuntimeClass; each Kata Pod is its own VM, so that is two VMs +# W4 OpenClaw answers a real turn through the user's inference profile +# (a random nonce must come back, so a cached or canned reply fails; +# the turn also asks for one tool call, which the gate may deny) +# W5 container/kata: the tool gate recorded that turn's tool call +# (local log by default; receipts mode is reported, not checked here) +# W6 container/kata: OCSF events reached the pattern's collector +# +# Usage: +# scripts/e2e-workspace.sh --mode container|kata|vm --user NAME +# [--sandbox notebook] [--workspace default] +# [--kata-class saw-kata] [--argo-namespace vp-gitops] +# make e2e-workspace MODE=container SAW_USER=alice +# +# Needs: oc logged in with exec rights in the user's runtime namespace. +# vm mode also needs the openshell CLI with a gateway named after the user +# (README: "Connect with the OpenShell CLI"). + +set -euo pipefail + +MODE="" USER_NAME="" SANDBOX="${SANDBOX:-notebook}" WORKSPACE="${WORKSPACE:-default}" +KATA_CLASS="${KATA_CLASS:-saw-kata}" ARGO_NS="${ARGO_NAMESPACE:-vp-gitops}" +COLLECTOR_NS="${COLLECTOR_NS:-openshell-agents}" +COLLECTOR_SELECTOR="${COLLECTOR_SELECTOR:-app.kubernetes.io/name=saw-ocsf-collector}" +TURN_TIMEOUT="${TURN_TIMEOUT:-180}" + +while [[ $# -gt 0 ]]; do + case "$1" in + --mode) MODE="$2"; shift 2 ;; + --user) USER_NAME="$2"; shift 2 ;; + --sandbox) SANDBOX="$2"; shift 2 ;; + --workspace) WORKSPACE="$2"; shift 2 ;; + --kata-class) KATA_CLASS="$2"; shift 2 ;; + --argo-namespace) ARGO_NS="$2"; shift 2 ;; + -h|--help) sed -n '/^# Usage:/,/^$/p' "$0"; exit 0 ;; + *) echo "unknown argument: $1 (see --help)" >&2; exit 2 ;; + esac +done +case "${MODE}" in container|kata|vm) ;; *) echo "Error: --mode container|kata|vm" >&2; exit 2 ;; esac +[[ "${USER_NAME}" =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$ ]] || { echo "Error: --user NAME" >&2; exit 2; } + +NS="saw-${USER_NAME}" +RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m' +FAILED=0 +step() { echo -e "\n${CYAN}=== $1 ===${NC}"; } +pass() { echo -e " ${GREEN}PASS${NC} $1"; } +fail() { echo -e " ${RED}FAIL${NC} $1"; FAILED=1; } +note() { echo -e " ${YELLOW}NOTE${NC} $1"; } +json() { python3 -c "import json,sys; d=json.load(sys.stdin); $1"; } +# macOS has no timeout(1); use coreutils' gtimeout when present, else none. +limit() { + if command -v timeout >/dev/null; then timeout "${TURN_TIMEOUT}" "$@" + elif command -v gtimeout >/dev/null; then gtimeout "${TURN_TIMEOUT}" "$@" + else "$@"; fi +} + +command -v oc >/dev/null || { echo "Error: oc is required" >&2; exit 2; } +oc get namespace "${NS}" >/dev/null 2>&1 || { echo "Error: namespace ${NS} not found; is ${USER_NAME} deployed?" >&2; exit 1; } +START="$(date -u +%Y-%m-%dT%H:%M:%SZ)" + +step "W1 Argo CD applications" +REG="$(oc get namespace "${NS}" -o jsonpath='{.metadata.labels.saw\.redhat\.com/registration}')" +apps="$(oc get applications.argoproj.io -n "${ARGO_NS}" -o json | json " +user, reg = '${USER_NAME}', '${REG}' +for a in d['items']: + n = a['metadata']['name'] + if n in ('saw-'+user, 'saw-'+user+'-bom') or (reg and n.startswith('saw-c-'+reg+'-')) or n.endswith('-'+user) and n.startswith('saw-projector-'): + s = a.get('status', {}) + print(n, s.get('sync', {}).get('status'), s.get('health', {}).get('status'))")" +if [[ -z "${apps}" ]]; then + fail "no Argo CD applications found for ${USER_NAME} in ${ARGO_NS}" +else + while read -r name sync health; do + if [[ "${sync}" == Synced && "${health}" == Healthy ]]; then pass "${name}"; else fail "${name}: ${sync}/${health}"; fi + done <<< "${apps}" +fi + +# In-sandbox turn. Arguments: config path, OpenClaw home, nonce. +read -r -d '' TURN <<'SH' || true +set -eu +cfg="$1"; home="$2"; nonce="$3" +export HOME="$home" OPENCLAW_HOME="$home" OPENCLAW_CONFIG_PATH="$cfg" +export TMPDIR="$(dirname "$cfg")/state" SQLITE_TMPDIR="$(dirname "$cfg")/state" +[ -f "$cfg" ] || { echo "no OpenClaw config at $cfg"; exit 3; } +mode=$(node -e 'process.stdout.write(String(require(process.argv[1]).gateway.auth.mode||""))' "$cfg") +secret=$(node -e 'const a=require(process.argv[1]).gateway.auth;process.stdout.write(a.password||a.token||"")' "$cfg") +[ -n "$secret" ] || { echo "no gateway secret in $cfg"; exit 3; } +if [ "$mode" = token ]; then export OPENCLAW_GATEWAY_TOKEN="$secret"; else export OPENCLAW_GATEWAY_PASSWORD="$secret"; fi +unset secret +openclaw agent --agent main --message "Try to run the shell command date once; it may be denied, and that is fine. Whatever happens, finish your reply with this exact line: $nonce" +SH + +NONCE="SAW_E2E_$(python3 -c 'import secrets; print(secrets.token_hex(4).upper())')" + +if [[ "${MODE}" == vm ]]; then + step "W2 VM and gateway" + phase="$(oc get vmi -n "${NS}" -o jsonpath='{.items[0].status.phase}' 2>/dev/null || true)" + [[ "${phase}" == Running ]] && pass "VirtualMachineInstance Running" || fail "VirtualMachineInstance phase: ${phase:-none}" + command -v openshell >/dev/null || { fail "openshell CLI not installed"; exit 1; } + sandboxes="$(openshell --gateway "${USER_NAME}" sandbox list --workspace "${WORKSPACE}" 2>/dev/null || true)" + if grep -qw "${SANDBOX}" <<< "${sandboxes}"; then + pass "gateway ${USER_NAME} lists sandbox ${SANDBOX}" + else + fail "gateway ${USER_NAME} does not list sandbox ${SANDBOX} (is the CLI logged in?)" + fi + run_turn() { + limit openshell --gateway "${USER_NAME}" sandbox exec -n "${SANDBOX}" \ + --workspace "${WORKSPACE}" --no-tty -- bash -c "${TURN}" turn \ + /sandbox/.openclaw/openclaw.json /sandbox "${NONCE}" + } +else + step "W2 sandbox Pods" + pod_of() { oc get pods -n "${NS}" -l "openshell.ai/boundary-role=$1" -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true; } + WORKLOAD="$(pod_of workload)" SUPERVISOR="$(pod_of supervisor)" + for pod in "${SUPERVISOR}" "${WORKLOAD}"; do + if [[ -z "${pod}" ]]; then fail "missing supervisor or workload Pod in ${NS}"; continue; fi + ready="$(oc get pod -n "${NS}" "${pod}" -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}')" + [[ "${ready}" == True ]] && pass "${pod} Ready" || fail "${pod} not Ready" + done + [[ -n "${WORKLOAD}" ]] || { echo; echo "No workload Pod; stopping."; exit 1; } + + if [[ "${MODE}" == kata ]]; then + step "W3 Kata runtime" + rc="$(oc get pod -n "${NS}" "${WORKLOAD}" -o jsonpath='{.spec.runtimeClassName}')" + [[ "${rc}" == "${KATA_CLASS}" ]] && pass "workload runs in ${KATA_CLASS}" || fail "workload runtimeClassName: ${rc:-none}" + rc="$(oc get pod -n "${NS}" "${SUPERVISOR}" -o jsonpath='{.spec.runtimeClassName}' 2>/dev/null || true)" + [[ "${rc}" == "${KATA_CLASS}" ]] && pass "supervisor runs in its own ${KATA_CLASS} VM" || fail "supervisor runtimeClassName: ${rc:-none}" + fi + + AUDIT=/sandbox/.saw/audit/tool-actions.jsonl + before="$(oc exec -n "${NS}" "${WORKLOAD}" -c agent -- sh -c "wc -l < ${AUDIT} 2>/dev/null || echo missing" | tr -d ' ')" + run_turn() { + limit oc exec -n "${NS}" "${WORKLOAD}" -c agent -- bash -c "${TURN}" turn \ + /sandbox/workspace/.openclaw/openclaw.json /sandbox/workspace "${NONCE}" + } +fi + +step "W4 OpenClaw inference turn" +if out="$(run_turn 2>&1)"; then status=0; else status=$?; fi +if grep -qF "${NONCE}" <<< "${out}"; then + pass "model returned the nonce through the user's inference profile" +else + fail "no nonce in the reply (exit ${status}):"; sed 's/^/ /' <<< "${out}" | tail -n 12 +fi + +if [[ "${MODE}" != vm ]]; then + step "W5 tool-gate audit" + if oc get namespace "saw-history-${REG}" >/dev/null 2>&1; then + note "auditReceipts mode: receipts go to saw-history-${REG}; local log not checked" + elif [[ "${before}" == missing ]]; then + fail "${AUDIT} does not exist" + else + entry="$(oc exec -n "${NS}" "${WORKLOAD}" -c agent -- sh -c "tail -n +$((before + 1)) ${AUDIT}" 2>/dev/null || true)" + if [[ -z "${entry}" ]]; then + fail "no new entry in ${AUDIT} (the agent made no tool call?)" + else + summary="$(printf '%s\n' "${entry}" | tail -n 1 | json "print(d.get('tool'), d.get('decision'), d.get('user', {}).get('username'))" 2>/dev/null || echo unparsable)" + read -r tool decision who <<< "${summary}" + if [[ -n "${decision}" && "${decision}" != None && "${who}" == "${USER_NAME}" ]]; then + pass "gate recorded ${tool}: ${decision} for ${who}" + else + fail "unexpected audit entry: ${summary}" + fi + fi + fi + + step "W6 OCSF export" + collector="$(oc get pods -n "${COLLECTOR_NS}" -l "${COLLECTOR_SELECTOR}" -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)" + if [[ -z "${collector}" ]]; then + fail "no OCSF collector Pod in ${COLLECTOR_NS}" + else + batches="$(oc logs -n "${COLLECTOR_NS}" "${collector}" --since-time="${START}" 2>/dev/null | grep -c 'Logs' || true)" + (( batches > 0 )) && pass "collector received ${batches} log batch(es) since ${START}" \ + || fail "collector received nothing since ${START}" + fi +fi + +echo +if (( FAILED )); then echo -e "${RED}${MODE} workspace for ${USER_NAME}: FAILED${NC}"; exit 1; fi +echo -e "${GREEN}${MODE} workspace for ${USER_NAME}: all checks passed${NC}" diff --git a/scripts/keycloak-users.sh b/scripts/keycloak-users.sh index fc3e8503a..af9e5200b 100755 --- a/scripts/keycloak-users.sh +++ b/scripts/keycloak-users.sh @@ -10,6 +10,8 @@ # Secret; --show prints the value (never printed otherwise). # reset-password USER Give USER a new generated password in the Secret. # resolve-subject USER Return the exact enabled user's Keycloak subject. +# user-info USER Show USER's subject (ownerSubject), enabled flag and +# email, or say why there is no usable account. # show List users that have stored passwords. # ensure Create or complete Secret $SECRET: a generated # password per test user in the chart's values (the @@ -333,6 +335,41 @@ resolve_subject() { printf '%s\n' "${subject}" } +user_info() { + local user="${1:-}" response count + [[ "${user}" =~ ^[a-z0-9][-a-z0-9]*$ ]] || { + echo "usage: $0 user-info USER (a plain Keycloak username)" >&2 + return 2 + } + admin_login + response="$(api_get "/users?exact=true&username=${user}")" + count="$(jq -r 'if type == "array" then length else -1 end' <<<"${response}" 2>/dev/null || echo -1)" + if [[ "${count}" == -1 ]]; then + echo "Error: Keycloak user lookup failed in realm ${REALM} (namespace ${NS})." >&2 + return 1 + fi + if [[ "${count}" == 0 ]]; then + echo "${user} is not in realm ${REALM} (namespace ${NS})." >&2 + echo "Create it with: make keycloak-add-user KC_USER=${user}" >&2 + echo "or set KEYCLOAK_REALM / KEYCLOAK_NS if it lives elsewhere." >&2 + return 1 + fi + jq -r --arg realm "${REALM}" '.[] | + "realm: \($realm)", + "username: \(.username)", + "subject: \(.id)", + "enabled: \(.enabled)", + "email: \(.email // "-")", + "name: \([.firstName, .lastName] | map(select(. != null)) | join(" ") | if . == "" then "-" else . end)", + ""' <<<"${response}" + if [[ "${count}" == 1 ]] && [[ "$(jq -r '.[0].enabled' <<<"${response}")" == true ]]; then + echo "ownerSubject: $(jq -r '.[0].id' <<<"${response}")" + else + echo "Warning: no single enabled account; resolve-subject and container registration will refuse it." >&2 + return 1 + fi +} + set_password() { # user id, password, temporary (true|false) api_code PUT "/users/$1/reset-password" \ "$(jq -n --arg pw "$2" --argjson t "$3" '{type: "password", value: $pw, temporary: $t}')" @@ -502,5 +539,6 @@ case "${1:-}" in password) password "${@:2}" ;; reset-password) reset_password "${2:-}" ;; resolve-subject) resolve_subject "${2:-}" ;; - *) echo "usage: $0 add-users [FILE]|password USER|reset-password USER|show|ensure|harden|session-max" >&2; exit 2 ;; + user-info) user_info "${2:-}" ;; + *) echo "usage: $0 add-users [FILE]|password USER|reset-password USER|resolve-subject USER|user-info USER|show|ensure|harden|session-max" >&2; exit 2 ;; esac diff --git a/scripts/oidc_topology_probe.py b/scripts/oidc_topology_probe.py deleted file mode 100644 index f909a97d8..000000000 --- a/scripts/oidc_topology_probe.py +++ /dev/null @@ -1,47 +0,0 @@ -"""Verify OIDC discovery from the trusted Pod's DNS and TLS trust context.""" -import http.client -import ipaddress -import json -import socket -import ssl -import sys -from urllib.parse import urlsplit - - -def probe(issuer): - url = urlsplit(issuer) - port = url.port or 443 - answers = {row[4][0] for row in socket.getaddrinfo(url.hostname, port, type=socket.SOCK_STREAM)} - context = ssl.create_default_context() - for address in sorted(answers): - ip = ipaddress.ip_address(address) - if ip.version != 4 or ip.is_unspecified or ip.is_loopback or ip.is_multicast or ip.is_link_local or ip.is_reserved: - raise ValueError("unsupported or unsafe issuer address") - # Connect directly to each DNS answer. SNI, hostname verification and - # the HTTP Host header still use the configured issuer's hostname. - conn = http.client.HTTPSConnection(url.hostname, port, timeout=5, context=context) - try: - with socket.create_connection((address, port), timeout=5) as sock: - conn.sock = context.wrap_socket(sock, server_hostname=url.hostname) - conn.request("GET", url.path.rstrip("/") + "/.well-known/openid-configuration") - response = conn.getresponse() - data = response.read(1024 * 1024 + 1) - if response.status != 200 or len(data) > 1024 * 1024 or json.loads(data).get("issuer") != issuer: - raise ValueError("issuer discovery mismatch") - finally: - conn.close() - return sorted(answers) - - -if __name__ == "__main__": - try: - result = probe(sys.argv[1]) - except socket.gaierror: - result = {"error": "dns"} - except ssl.SSLError: - result = {"error": "tls"} - except (OSError, http.client.HTTPException): - result = {"error": "connection"} - except (ValueError, AttributeError): - result = {"error": "discovery"} - print(json.dumps(result)) diff --git a/scripts/portal-container/setup-relay-provisioner.py b/scripts/portal-container/setup-relay-provisioner.py deleted file mode 100644 index 9517e6b75..000000000 --- a/scripts/portal-container/setup-relay-provisioner.py +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env python3 -"""Render or run the one-time, platform-owned Keycloak relay registrar setup.""" -import argparse -import base64 -import json -import os -from pathlib import Path -import secrets -import ssl -import sys -from urllib.error import HTTPError -from urllib.parse import urlencode, urlsplit -from urllib.request import build_opener, HTTPRedirectHandler, HTTPSHandler, Request - -NAME = "saw-relay-provisioner" -SCOPE = "saw-workspace-relay" -IMAGE = "registry.access.redhat.com/ubi9/python-311@sha256:a0bdb55576fc5b8d6704279307817828ef027e1065533ceba133fe9516003a6c" - - -class NoRedirect(HTTPRedirectHandler): - def redirect_request(self, *args): - return None - - -def call(url, method="GET", *, token=None, body=None, form=None, ca=None, patch=False): - headers = {} - data = None - if form is not None: - headers["Content-Type"] = "application/x-www-form-urlencoded" - data = urlencode(form).encode() - if body is not None: - headers["Content-Type"] = "application/merge-patch+json" if patch else "application/json" - data = json.dumps(body).encode() - if token: - headers["Authorization"] = "Bearer " + token - client = build_opener(NoRedirect(), HTTPSHandler(context=ssl.create_default_context(cafile=ca))) - with client.open(Request(url, data=data, method=method, headers=headers), timeout=20) as response: - raw = response.read() - return json.loads(raw) if raw else None - - -def setup(): - issuer = os.environ["ISSUER"].rstrip("/") - base, realm = issuer.rsplit("/realms/", 1) - if urlsplit(issuer).scheme != "https" or not realm or realm == "master": - raise ValueError("expected a dedicated HTTPS realm") - admin = Path("/bootstrap") - token = call(base + "/realms/master/protocol/openid-connect/token", "POST", - form={"client_id":"admin-cli", "grant_type":"password", - "username":(admin/"username").read_text().strip(), - "password":(admin/"password").read_text().strip()})["access_token"] - def kc(path, method="GET", body=None): - return call(base + "/admin/realms/" + realm + path, method, token=token, body=body) - - sa = Path("/var/run/secrets/kubernetes.io/serviceaccount") - secret_url = ("https://kubernetes.default.svc/api/v1/namespaces/" + os.environ["NAMESPACE"] - + "/secrets/" + NAME) - opts = dict(ca=str(sa/"ca.crt"), token=(sa/"token").read_text().strip()) - state = call(secret_url, **opts) - if state["metadata"]["labels"].get("saw.redhat.com/component") != NAME: - raise ValueError("unexpected destination Secret") - if not state.get("data"): - state = call(secret_url, "PATCH", patch=True, **opts, body={ - "metadata":{"resourceVersion":state["metadata"]["resourceVersion"]}, - "stringData":{"client-id":NAME, "client-secret":secrets.token_urlsafe(40), "issuer":issuer}}) - values = {k:base64.b64decode(v,validate=True).decode() for k,v in state["data"].items()} - if set(values) != {"issuer","client-id","client-secret"} or values["issuer"] != issuer or values["client-id"] != NAME: - raise ValueError("incompatible provisioner Secret") - audience = os.environ["AUDIENCE"] - mappers = [ - {"name":"relay-audience", "protocol":"openid-connect", "protocolMapper":"oidc-audience-mapper", - "config":{"included.client.audience":audience, "access.token.claim":"true"}}, - {"name":"relay-user", "protocol":"openid-connect", "protocolMapper":"oidc-hardcoded-claim-mapper", - "config":{"claim.name":"realm_access.roles","claim.value":'["openshell-user"]', - "jsonType.label":"JSON","access.token.claim":"true"}}] - scopes = {s["name"]:s for s in kc("/client-scopes")} - if SCOPE not in scopes: - kc("/client-scopes","POST",{"name":SCOPE, "protocol":"openid-connect", - "description":"SAW registration-scoped workspace relay", "protocolMappers":mappers}) - scope = next(s for s in kc("/client-scopes") if s["name"]==SCOPE) - actual = kc("/client-scopes/"+scope["id"]+"/protocol-mappers/models") - if {m["name"] for m in actual} != {m["name"] for m in mappers}: - raise ValueError("unexpected relay scope mappers") - for desired in mappers: - found=next(m for m in actual if m["name"]==desired["name"]) - if found["protocolMapper"]!=desired["protocolMapper"] or any(found["config"].get(k)!=v for k,v in desired["config"].items()): - raise ValueError("foreign relay scope configuration") - # Add this specific pre-approved scope to authenticated DCR. Never allow - # clients to author their own role or audience mappers. - policies=kc("/components?"+urlencode({"type":"org.keycloak.services.clientregistration.policy.ClientRegistrationPolicy"})) - allowed=[p for p in policies if p.get("providerId")=="allowed-client-templates" and p.get("subType")=="authenticated"] - if len(allowed)!=1: - raise ValueError("expected one authenticated client-scope registration policy") - policy=allowed[0] - config=policy.setdefault("config",{}) - permitted=config.setdefault("allowed-client-scopes",[]) - if SCOPE not in permitted: - permitted.append(SCOPE) - kc("/components/"+policy["id"],"PUT",policy) - - def lookup(client_id): - return next((c for c in kc("/clients?"+urlencode({"clientId":client_id})) if c["clientId"]==client_id), None) - settings=dict(clientId=NAME, enabled=True, protocol="openid-connect", publicClient=False, - serviceAccountsEnabled=True,standardFlowEnabled=False,implicitFlowEnabled=False, - directAccessGrantsEnabled=False,fullScopeAllowed=False) - if not lookup(NAME): - kc("/clients","POST",{**settings,"secret":values["client-secret"],"attributes":{"saw.component":NAME}, - "defaultClientScopes":["basic","roles"],"optionalClientScopes":[]}) - client=kc("/clients/"+lookup(NAME)["id"]) - if client.get("attributes",{}).get("saw.component")!=NAME or any(client.get(k)!=v for k,v in settings.items()): - raise ValueError("refusing to adopt a foreign provisioning client") - prefix="/clients/"+client["id"] - management=lookup("realm-management")["id"] - role=kc("/clients/"+management+"/roles/create-client") - user=kc(prefix+"/service-account-user")["id"] - for path in [prefix+"/scope-mappings/clients/"+management, - "/users/"+user+"/role-mappings/clients/"+management]: - current=kc(path) - if {r["name"] for r in current} - {"create-client"}: - raise ValueError("provisioner has unexpected realm-management privileges") - if not current: - kc(path,"POST",[role]) - result=call(issuer+"/protocol/openid-connect/token","POST",form={ - "client_id":NAME,"client_secret":values["client-secret"],"grant_type":"client_credentials"}) - part=result["access_token"].split(".")[1] - claim=json.loads(base64.urlsafe_b64decode(part+"="*(-len(part)%4))) - if set(claim.get("resource_access",{}).get("realm-management",{}).get("roles",[]))!={"create-client"}: - raise ValueError("unexpected effective registrar privilege") - print("Realm registrar verified: create-client in the workspace realm.") - - -def render(args): - ns=args.namespace - metadata={"name":NAME,"namespace":ns} - subject={"kind":"ServiceAccount","name":NAME,"namespace":ns} - objects=[ - {"apiVersion":"v1","kind":"Secret","metadata":{**metadata,"labels":{"saw.redhat.com/component":NAME}},"type":"Opaque"}, - {"apiVersion":"v1","kind":"ServiceAccount","metadata":metadata}, - {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"Role","metadata":metadata,"rules":[ - {"apiGroups":[""],"resources":["secrets"],"verbs":["get","patch"],"resourceNames":[NAME]}]}, - {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"RoleBinding","metadata":metadata,"subjects":[subject], - "roleRef":{"apiGroup":"rbac.authorization.k8s.io","kind":"Role","name":NAME}}, - {"apiVersion":"v1","kind":"ConfigMap","metadata":metadata,"data":{"setup.py":Path(__file__).read_text()}}] - volumes=[{"name":"script","configMap":{"name":NAME}},{"name":"bootstrap","secret":{ - "secretName":args.bootstrap_secret,"items":[{"key":k,"path":k} for k in ("username","password")]}}] - mounts=[{"name":v["name"],"mountPath":"/"+v["name"],"readOnly":True} for v in volumes] - env={"ISSUER":args.issuer,"NAMESPACE":ns,"AUDIENCE":args.audience} - if args.ca_configmap: - volumes.append({"name":"trust","configMap":{"name":args.ca_configmap}}) - mounts.append({"name":"trust","mountPath":"/trust","readOnly":True}) - env["SSL_CERT_FILE"]="/trust/ca-bundle.crt" - objects.append({"apiVersion":"batch/v1","kind":"Job","metadata":metadata,"spec":{ - "activeDeadlineSeconds":180,"backoffLimit":1,"ttlSecondsAfterFinished":900, - "template":{"spec":{"serviceAccountName":NAME,"restartPolicy":"Never","volumes":volumes, - "securityContext":{"runAsNonRoot":True,"seccompProfile":{"type":"RuntimeDefault"}}, - "containers":[{"name":"setup","image":IMAGE,"command":["python3","/script/setup.py","run"], - "volumeMounts":mounts,"env":[{"name":k,"value":v} for k,v in env.items()], - "securityContext":{"readOnlyRootFilesystem":True,"allowPrivilegeEscalation":False,"capabilities":{"drop":["ALL"]}}}]}}}}) - print(json.dumps({"apiVersion":"v1","kind":"List","items":objects})) - - -if __name__=="__main__": - if sys.argv[1:]==["run"]: - try: - setup() - except HTTPError as exc: - sys.exit(f"Setup API failed: HTTP {exc.code} at {urlsplit(exc.url).path}") - else: - parser=argparse.ArgumentParser(description=__doc__) - for flag in ("namespace","issuer","bootstrap-secret"): - parser.add_argument("--"+flag,required=True) - parser.add_argument("--audience",default="openshell-cli") - parser.add_argument("--ca-configmap") - render(parser.parse_args()) diff --git a/scripts/saw-init.sh b/scripts/saw-init.sh new file mode 100755 index 000000000..bea4ab4b9 --- /dev/null +++ b/scripts/saw-init.sh @@ -0,0 +1,162 @@ +#!/usr/bin/env bash +# Prepare a cluster for SAW before `./pattern.sh make install` or `make saw-create`. +# Safe to run again. After the default StorageClass check (a make prerequisite): +# - SSH keys and ~/values-secret.yaml (generate-keys.sh; never replaces a key); +# - whether workspaces will trust the OIDC issuer (check-oidc-ca.sh); +# - the gateway VM image in the internal registry (images-mirror.sh), when a +# user is a VM user or no users are listed yet (the portal may create VMs); +# - for container or Kata users: OVN-Kubernetes, AdminNetworkPolicy and +# ValidatingAdmissionPolicy and a pullable runtime image; with auditReceipts, +# also a shared-filesystem (ReadWriteMany) StorageClass (offers to create one); +# - StorageClass saw-shared, a copy of the shared-filesystem class: the fixed +# name the container charts use, so no class name goes into Git. +# +# 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), +# DEPLOYMENT_MODE=container|kata with OPENSHELL_SAW_NAME (quickstart), +# SAW_INIT_SKIP_MIRROR=1, 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, so read users and defaults from +# all of them. +read -r container_users vm_needed image receipts < <(python3 - "$users_file" "${root}/overrides/saw-users.yaml" "$defaults_file" <<'EOF' +import sys, yaml +names, image, seen, users, vm, receipts = [], "", set(), 0, False, False +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 []: + users += 1 + mode = ((u.get("values") or {}).get("deployment") or {}).get("mode") + if mode in ("container", "kata"): + if u.get("name") not in names: + names.append(u.get("name", "?")) + else: + vm = True + image = image or ((doc.get("containerDefaults") or {}).get("automaticEnrollment") or {}).get("image", "") + sites = [doc.get("containerDefaults") or {}] + list((doc.get("containerSites") or {}).values()) + receipts = receipts or any(isinstance(s, dict) and s.get("auditReceipts") is True for s in sites) +print(",".join(names) or "-", "yes" if vm or not users else "no", image or "-", "yes" if receipts else "no") +EOF +) + +# Quickstart (make saw-create) names its one user with DEPLOYMENT_MODE. +case "${DEPLOYMENT_MODE:-}" in + container|kata) + if [ "$container_users" = "-" ]; then + container_users="${OPENSHELL_SAW_NAME:-${DEPLOYMENT_MODE}}" + vm_needed=no + fi ;; +esac + +cd "$root" +"${script_dir}/generate-keys.sh" >/dev/null && ok "SSH keys and ~/values-secret.yaml" \ + || fail "could not create the SSH keys (scripts/generate-keys.sh)" + +rc=0; oidc="$("${script_dir}/check-oidc-ca.sh" 2>&1)" || rc=$? +case "$rc" in + 0|3) ok "OIDC issuer certificate" ;; + 2) fail "workspaces will not trust the OIDC issuer; add oidc.caBundle:"; echo "$oidc" >&2 ;; + *) warn "could not check the OIDC issuer certificate (make check-oidc-ca for details)" ;; +esac + +if [ "$vm_needed" = no ]; then + ok "gateway VM image not needed (container/Kata users only)" +elif [ "${SAW_INIT_SKIP_MIRROR:-0}" = 1 ]; then + warn "gateway VM image mirror skipped (make images-mirror before VM workspaces)" +elif echo " ... mirroring the gateway VM image (a few minutes the first time)" && "${script_dir}/images-mirror.sh" >/dev/null; then + ok "gateway VM image in the internal registry" +else + fail "could not mirror the gateway VM image (make images-mirror for details)" +fi + +if [ "$container_users" = "-" ]; then + # Ready for container workspaces requested later (the portal), where the + # cluster can already back them; silent otherwise. + "${script_dir}/shared-storage.sh" --classes-only || true + echo + [ "$failed" = 0 ] || { echo "SAW init: fix the items above, then run make saw-init again." >&2; exit 1; } + echo "SAW init: ready." + 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" + +# A shared filesystem is only needed for signed audit receipts (auditReceipts). +if [ "$receipts" = yes ]; then + if "${script_dir}/shared-storage.sh"; then :; else failed=1; fi +else + "${script_dir}/shared-storage.sh" --classes-only || true +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 +echo "SAW init: ready. After install, see 'Add a user' in the README." diff --git a/scripts/saw-profile-catalog.py b/scripts/saw-profile-catalog.py index d6d6c7d29..789e30b61 100644 --- a/scripts/saw-profile-catalog.py +++ b/scripts/saw-profile-catalog.py @@ -570,18 +570,13 @@ def main(argv=None): for src in sorted(GOVERNANCE_PROFILES.glob("*.yaml"))} extra = [p for p in sorted(INSTALLER_PROFILES.glob("*.yaml")) if p not in mirror] lifecycle = TEMPLATE_OUTPUT.with_name("set-workspace-state.yaml") - # Independent Helm charts package the same reviewed broker renderer. - policy_template = ROOT / "charts/openshell-saw/templates/_governed-proxy-policy.tpl" policy_outputs = [ (ROOT / "charts/openshell-rhdh/files/saw_keycloak_admin.py", (ROOT / "charts/openshell-keycloak/files/saw_keycloak_admin.py").read_text()), (ROOT / "charts/saw-workspace-relay/files/saw_ui_limit.py", (ROOT / "charts/openshell-saw/files/installer/saw_ui_limit.py").read_text()), (ROOT / "charts/openshell-rhdh/files/workspace.py", - (ROOT / "charts/saw-users/files/workspace.py").read_text()), - (ROOT / "charts/saw-users/templates/_governed-proxy-policy.tpl", policy_template.read_text()), - (ROOT / "charts/saw-users/files/governed-profiles.json", json.dumps( - {p.stem: load(p) for p in sorted(GOVERNANCE_PROFILES.glob("*.yaml"))}, sort_keys=True, indent=2) + "\n")] + (ROOT / "charts/saw-users/files/workspace.py").read_text())] if args.list: # Every path this script owns: the generated files, each mirror, and # the mirror directory itself, so `git add -A -- ` (the hook, diff --git a/scripts/shared-storage.sh b/scripts/shared-storage.sh new file mode 100755 index 000000000..2f38ffa42 --- /dev/null +++ b/scripts/shared-storage.sh @@ -0,0 +1,389 @@ +#!/usr/bin/env bash +# Ensure a shared-filesystem (ReadWriteMany) StorageClass for container workspaces. +# +# The audit exchange volume is mounted by several Pods at once, so it needs a +# ReadWriteMany class (CephFS, NFS, EFS, ...). Block classes such as EBS +# (gp3-csi) cannot serve it. This script: +# - a known shared-filesystem class exists -> continue +# - otherwise, by SAW_SHARED_STORAGE: +# unset / none -> print the options and fail (nothing is created) +# nfs -> dev/demo only, explicit opt-in: create a small in-cluster +# NFS server (privileged SCC) and provisioner (cluster-scoped +# role, StorageClass `saw-nfs`) and verify it. One Pod, no +# replication: not for production. +# efs -> on AWS with working `aws` credentials, offer to create EFS +# (filesystem, mount targets, NFS security group), the AWS +# EFS CSI Driver Operator and StorageClass `saw-efs`. EFS is +# billed per GB; it is tagged kubernetes.io/cluster/. +# For production, provide a real RWX class (ODF CephFS, EFS, vendor NFS) first; +# this script then leaves storage alone. +# +# Container workspaces then name the shared class saw-shared, a copy of the +# shared-filesystem class, so Git holds no cluster-specific class name (other +# volumes use the cluster's default class). An existing saw-shared is kept. +# --classes-only creates just the copy, and only when the cluster can back it +# (make saw-init uses it before any container user exists). +# +# 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}" +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 +CLASSES_ONLY=0 +[ "${1:-}" = --classes-only ] && CLASSES_ONLY=1 + +err() { echo "$@" >&2; } +interactive() { [ -t 0 ] && [ -t 1 ]; } +ask_yes() { + [ "${SAW_STORAGE_ASSUME_YES:-0}" = 1 ] && return 0 + interactive || return 1 + local ans + read -r -p "$1 [y/N] " ans || return 1 + [[ "$ans" =~ ^[Yy]([Ee][Ss])?$ ]] +} +guidance() { + err "Container workspaces need a ReadWriteMany (shared filesystem) StorageClass." + err "Options, then run make saw-init again:" + err " - AWS: EFS with the AWS EFS CSI Driver Operator (this script automates it" + err " when 'aws sts get-caller-identity' works for the cluster's account)" + err " - OpenShift Data Foundation (CephFS: ocs-storagecluster-cephfs)" + err " - an NFS server with the NFS CSI driver (nfs.csi.k8s.io)" + err " - dev/demo only: SAW_SHARED_STORAGE=nfs make saw-init creates a small in-cluster NFS" + err " server (privileged SCC, cluster-scoped provisioner role; one Pod, no replication)" + err " - or name an existing RWX class in containerDefaults.stack.audit.values.exchangeStorageClass" + err "See docs/container-installation.md." +} + +# A Pod writes and reads through a ReadWriteMany claim of the class. +verify_rwx() { + local ns="$1" class="$2" + oc apply -n "$ns" -f - >/dev/null </dev/null 2>&1 + oc apply -n "$ns" -f - >/dev/null < /data/check && cat /data/check"] + securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}, runAsNonRoot: true, seccompProfile: {type: RuntimeDefault}} + volumeMounts: [{name: data, mountPath: /data}] + volumes: [{name: data, persistentVolumeClaim: {claimName: rwx-check}}] +EOF + local phase="" + for _ in $(seq 60); do + phase="$(oc get pod rwx-check -n "$ns" -o jsonpath='{.status.phase}' 2>/dev/null)" + case "$phase" in Succeeded|Failed) break ;; esac + sleep 5 + done + if [ "$phase" = Succeeded ] && [ "$(oc logs rwx-check -n "$ns" 2>/dev/null)" = saw ]; then + echo " ok shared-filesystem StorageClass: ${class} (demo NFS, verified read/write)" + else + err " FAIL ${class} did not serve a ReadWriteMany volume (check Pod: ${phase:-not started})" + err " oc -n ${ns} get pvc,pods; oc -n ${ns} describe pod rwx-check; oc -n ${ns} logs deploy/nfs-provisioner" + exit 1 + fi + oc delete pod rwx-check -n "$ns" --wait=false >/dev/null 2>&1 || true + oc delete pvc rwx-check -n "$ns" --wait=false >/dev/null 2>&1 || true +} + +# Create class $2 as a copy of class $1, unless $2 exists. +copy_class() { + local source="$1" name="$2" + if oc get storageclass "$name" >/dev/null 2>&1; then + echo " ok StorageClass ${name}" + return 0 + fi + [ -n "$source" ] || return 1 + oc get storageclass "$source" -o json | jq --arg n "$name" --arg src "$source" ' + {apiVersion: "storage.k8s.io/v1", kind: "StorageClass", + metadata: {name: $n, labels: {"app.kubernetes.io/part-of": "secure-agent-workspace"}, + annotations: {"saw.redhat.com/copy-of": $src}}, + provisioner, parameters, reclaimPolicy, volumeBindingMode, allowVolumeExpansion, + mountOptions, allowedTopologies} | with_entries(select(.value != null))' \ + | oc create -f - >/dev/null || { err " FAIL could not create StorageClass ${name}"; return 1; } + echo " ok StorageClass ${name} (a copy of ${source})" +} + +# saw-shared, the shared class name the container charts use. +ensure_classes() { + local shared + shared="$(oc get storageclass -o json | jq -r --argjson p "$SHARED" '[.items[] + | select(.metadata.name != "saw-shared") | select(.provisioner as $x | $p | index($x))] + | sort_by(.metadata.name) | .[0].metadata.name // empty')" + if [ "$CLASSES_ONLY" = 1 ]; then + { [ -n "$shared" ] || oc get storageclass saw-shared >/dev/null 2>&1; } && copy_class "$shared" saw-shared + return 0 + fi + copy_class "$shared" saw-shared || { err " FAIL no shared-filesystem StorageClass to copy as saw-shared"; return 1; } +} + +if [ "$CLASSES_ONLY" = 1 ]; then + ensure_classes + exit 0 +fi + +existing="$(oc get storageclass -o json | jq -r --argjson p "$SHARED" \ + '[.items[] | select(.metadata.name != "saw-shared") | 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 + ensure_classes || exit 1 + exit 0 +fi + +# SAW_SHARED_STORAGE=nfs (explicit opt-in): a small NFS server inside the cluster. +# One server Pod on a default-class (RWO) volume, exported to a dynamic +# provisioner; not replicated and a single point of failure. +setup_demo_nfs() { + local ns="${SAW_NFS_NAMESPACE:-saw-nfs}" class="${SAW_NFS_STORAGECLASS:-saw-nfs}" size="${SAW_NFS_SIZE:-20Gi}" + # Upstream Kubernetes images: the e2e NFS server (kernel nfsd, exports /exports + # as the NFSv4 root) and the sig-storage subdirectory provisioner. + local server_image="${SAW_NFS_SERVER_IMAGE:-registry.k8s.io/e2e-test-images/volume/nfs:1.4}" + local provisioner_image="${SAW_NFS_PROVISIONER_IMAGE:-registry.k8s.io/sig-storage/nfs-subdir-external-provisioner:v4.0.2}" + echo " info no shared-filesystem StorageClass: creating an in-cluster NFS server in ${ns}" + echo " (privileged Pod on a ${size} default-class volume, provisioner, StorageClass ${class})." + echo " Dev/demo only: one Pod, no replication." + + oc create namespace "$ns" --dry-run=client -o yaml | oc apply -f - >/dev/null + oc create serviceaccount nfs-server -n "$ns" --dry-run=client -o yaml | oc apply -f - >/dev/null + oc create serviceaccount nfs-provisioner -n "$ns" --dry-run=client -o yaml | oc apply -f - >/dev/null + oc adm policy add-scc-to-user privileged -z nfs-server -n "$ns" >/dev/null + # Pods with nfs volumes need an SCC that allows them. + oc adm policy add-scc-to-user hostmount-anyuid -z nfs-provisioner -n "$ns" >/dev/null + oc apply -n "$ns" -f - >/dev/null </dev/null \ + || { err " FAIL demo NFS server did not start (oc -n ${ns} describe deployment/nfs-server)"; exit 1; } + # Nodes mount NFS from the host network, which reaches the Service IP but not cluster DNS. + local server_ip + server_ip="$(oc get service nfs-server -n "$ns" -o jsonpath='{.spec.clusterIP}')" + echo " ok demo NFS server at ${server_ip}" + + oc apply -f - >/dev/null </dev/null \ + || { err " FAIL demo NFS provisioner did not start (oc -n ${ns} describe deployment/nfs-provisioner)"; exit 1; } + + verify_rwx "$ns" "$class" +} + +case "${SAW_SHARED_STORAGE:-}" in + nfs) setup_demo_nfs; ensure_classes || exit 1; 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})" +ensure_classes || exit 1 diff --git a/scripts/test-deployment.sh b/scripts/test-deployment.sh index bc26df635..d32abd396 100755 --- a/scripts/test-deployment.sh +++ b/scripts/test-deployment.sh @@ -367,7 +367,7 @@ record config.web-search 0 "${web_search}" record version.oc-client 0 "$(oc version --client | sed -n '1p')" record version.helm 0 "$(helm version --short)" record version.gateway-image 0 "${IMAGE_REPO:-ghcr.io/validatedpatterns-sandbox}/openshell-gateway:${IMAGE_TAG:-latest}" -record version.interceptor 0 "${OPENSHELL_INTERCEPTOR_REF:-v0.1.6}" +record version.interceptor 0 "${OPENSHELL_INTERCEPTOR_REF:-v0.1.10}" record version.bom-gateway 0 "$(awk '/^ gateway:/{getline; print $2; exit}' charts/openshell-saw/values.yaml)" record initial.saw-namespaces 0 "$(jq -r '[.items[].metadata.name | select(startswith("saw-"))] | join(",")' <<<"${namespaces}")" diff --git a/tests/scripts/test_container_installation.py b/tests/scripts/test_container_installation.py index 31e55ec10..e196f1eb9 100644 --- a/tests/scripts/test_container_installation.py +++ b/tests/scripts/test_container_installation.py @@ -25,7 +25,7 @@ def inputs(): site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] user = dict(name="alice", registration="a"*16, installationID="22222222-2222-4222-8222-222222222222", ownerSubject=site["subject"], profiles=["data-science"], intentGeneration=1, - vaultPrefix="secret/data/hub/saw-alice/"+"a"*16, pruneOnRemove=True, + vaultPrefix="secret/data/hub/saw-alice", pruneOnRemove=True, values={"deployment": {"mode": "container"}}) return {"users": [user, {"name": "bob"}], "containerSites": {"alice": site}, "ownerResolution": {"enabled": True}, @@ -42,6 +42,42 @@ 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" + portal = {**user, "vaultPrefix": "secret/data/hub/saw-alice/" + user["registration"]} + install.apply_container_defaults({}, portal) + assert portal["vaultPrefix"] == "secret/data/hub/saw-alice/" + user["registration"] # the portal's path is kept + assert user["ownerSubject"] == subject and user["pruneOnRemove"] is True and user["intentGeneration"] == 1 + assert selected["containerSites"]["alice"]["subject"] == subject + + +def test_select_without_subject_or_keycloak_account_explains(monkeypatch): + values = inputs() + del values["users"][0]["ownerSubject"] + def missing(name): + raise install.InstallError("set ownerSubject for alice, or create the Keycloak account first") + monkeypatch.setattr(install, "resolve_subject", missing) + with pytest.raises(install.InstallError, match="Keycloak account"): + install.select(values, "alice") + + +def test_select_derives_installation_id_like_the_portal(): + values = inputs() + del values["users"][0]["installationID"] + _, user = install.select(values, "alice") + assert user["installationID"] == "12305846-148f-5386-9827-819d16cda0e1" # uuid5 of urn:saw:portal:alice:aaaa... + + @pytest.mark.parametrize(("requested", "declared"), [ ("container", "kata"), ("kata", "container"), ("vm", "container"), ]) @@ -79,7 +115,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: @@ -298,51 +333,3 @@ def failed(*args, **kwargs): with pytest.raises(install.InstallError, match=expected) as exc: install.run("oc", "get", "namespace", "test") assert "private-fixture-value" not in str(exc.value) - - -def test_make_applies_checked_overlay_before_render_and_fails_before_mutation_on_drift(monkeypatch, tmp_path): - values, user = install.select(inputs(), "alice") - values["containerSites"]["alice"]["automaticEnrollment"]["enabled"] = False - base = tmp_path / "site.yaml" - overlay = tmp_path / "net.yaml" - base.write_text(yaml.safe_dump(values)) - network = install.container_topology - site = values["containerSites"]["alice"] - ip = ["10.0.0.7"] - def discover(config, probe, container): - assert probe == "ops/probe" and config["containerSites"]["alice"] == site - result = {"projection": {"egress": []}, "containerSites": {"alice": {}}} - o = result["containerSites"]["alice"] - for path in (network.GATEWAY + ("oidc", "issuerUrl"), network.RELAY + ("issuer",)): - network.put(o, path, "https://issuer.example") - for path in (network.BOOTSTRAP, network.RELAY + ("egress",), network.GATEWAY + ("kubernetes", "network", "gatewayEgress")): - network.put(o, path, [network.host_rule(ip[0], 443)]) - return result - - monkeypatch.setenv("SAW_TOPOLOGY_OVERLAY", str(overlay)) - monkeypatch.setenv("SAW_TOPOLOGY_PROBE", "ops/probe") - monkeypatch.setattr(network, "container_overlay", discover) - monkeypatch.setattr(sys, "argv", ["container-workspace.py", "apply", "--name", "alice", "--values", str(base)]) - monkeypatch.setattr(install.shutil, "which", lambda _: "/tool") - monkeypatch.setattr(install, "get", lambda kind, *a: {"spec":{"domain":"apps.cluster.example.test"}} - if kind == "ingress.config.openshift.io" else None) - monkeypatch.setattr(install, "preflight", lambda *args: ({}, "vp-gitops")) - writes = [] - monkeypatch.setattr(install, "ensure_namespace", lambda *args: writes.append("namespace")) - def run(*args, **kwargs): - if args[:2] == ("helm", "list"): - return "[]" - if args[:2] in (("helm", "template"), ("helm", "upgrade")): - rendered_values = json.loads(Path(args[args.index("-f")+1]).read_text()) - assert network.path_value(rendered_values["containerSites"]["alice"], network.RELAY + ("egress",)) == [ - network.host_rule("10.0.0.7", 443)] - if args[:2] == ("helm", "upgrade"): - writes.append("helm") - return "" - monkeypatch.setattr(install, "run", run) - assert install.main() == 0 and writes == ["namespace", "helm"] - ip[0] = "10.0.0.8" - writes.clear() - with pytest.raises(SystemExit): - install.main() - assert not writes diff --git a/tests/scripts/test_container_topology.py b/tests/scripts/test_container_topology.py deleted file mode 100644 index 60dc3985d..000000000 --- a/tests/scripts/test_container_topology.py +++ /dev/null @@ -1,270 +0,0 @@ -"""Role-scoped topology, review protection, and the in-Pod HTTPS check.""" -import copy -import importlib.util -import json -from pathlib import Path -from unittest.mock import MagicMock - -import pytest -import yaml - -ROOT = Path(__file__).resolve().parents[2] - - -def module(name): - spec = importlib.util.spec_from_file_location(name, ROOT / "scripts" / (name + ".py")) - loaded = importlib.util.module_from_spec(spec) - spec.loader.exec_module(loaded) - return loaded - - -topo = module("container_topology") -probe = module("oidc_topology_probe") - - -@pytest.fixture -def cluster(monkeypatch): - calls = [] - addresses = ["10.10.10.101", "10.10.10.102"] - def command(*args): - calls.append(args) - if "print-json" in args: - return json.dumps({"cleanupApi": {"serviceIP": "172.30.0.1", "endpoints": [ - {"ip": "10.10.1.2", "port": 6443}]}}) - if "dns-default" in args: - return json.dumps({"spec": {"clusterIP": "172.30.0.10", - "selector": {"dns.operator.openshift.io/daemonset-dns": "default"}, - "ports": [{"name": p.lower(), "port": 53, "protocol": p} for p in ["TCP", "UDP"]]}}) - if "endpointslice" in args: - return json.dumps({"items": [{"addressType": "IPv4", "ports": [ - {"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 args[0].endswith("keycloak-host.sh"): - return "keycloak.apps.cluster.example.test" - if "exec" in args: - assert args[1:5] == ("-n", "trusted-tools", "exec", "pod/network-probe") - return json.dumps(addresses) - pytest.fail(f"unexpected command: {args[:3]}") - monkeypatch.setattr(topo, "command", command) - return addresses, calls - - -@pytest.fixture -def base(): - site = yaml.safe_load((ROOT / "tests/fixtures/container-site.yaml").read_text())["portal"]["containerSites"]["alice"] - site["automaticEnrollment"]["enabled"] = False - for prefix, field in [(topo.GATEWAY + ("kubernetes", "network"), "gatewayEgress"), - (topo.BOOTSTRAP[:-1], "bootstrapEgress"), (topo.RELAY, "egress")]: - topo.path_value(site, prefix)[field] = [] - return {"containerSites": {"alice": site}, "global": {"clusterDomain": "cluster.example.test"}} - - -def test_overlay_uses_one_probe_and_preserves_separation(base, cluster): - addresses, calls = cluster - site = base["containerSites"]["alice"] - operator_rule = {"to": [{"podSelector": {"matchLabels": {"role": "proxy"}}}], - "ports": [{"port": 3128, "protocol": "TCP"}]} - topo.path_value(site, topo.GATEWAY + ("kubernetes", "network", "gatewayEgress")).append(operator_rule) - base["portal"] = {"containerSites": {"alice": copy.deepcopy(site)}} - before = copy.deepcopy(base) - overlay = topo.container_overlay(base, "trusted-tools/network-probe", "tools") - assert base == before - assert len([c for c in calls if "exec" in c]) == 1 - assert overlay["portal"]["containerSites"] == overlay["containerSites"] - result = overlay["containerSites"]["alice"] - gateway = topo.path_value(result, topo.GATEWAY + ("kubernetes", "network", "gatewayEgress")) - relay = topo.path_value(result, topo.RELAY + ("egress",)) - bootstrap = topo.path_value(result, topo.BOOTSTRAP) - assert gateway == [operator_rule, *relay] - assert relay == bootstrap + [topo.host_rule(ip, 443) for ip in addresses] - assert bootstrap == overlay["projection"]["egress"] - assert topo.host_rule("172.30.0.1", 443) in bootstrap - assert topo.host_rule("10.10.1.2", 6443) in bootstrap - 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"} - - -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" - topo.install_values(values, "alice", file, "trusted-tools/network-probe", None, verify=True) - approved = file.read_bytes() - cluster[0].append("10.10.10.103") - with pytest.raises(ValueError, match="stale"): - topo.install_values(copy.deepcopy(base), "alice", file, "trusted-tools/network-probe", None, verify=True) - assert file.read_bytes() == approved - calls = len(cluster[1]) - topo.install_values(copy.deepcopy(base), "alice", file, None, None, verify=False) - assert len(cluster[1]) == calls - base["containerSites"]["alice"]["automaticEnrollment"]["enabled"] = True - with pytest.raises(ValueError, match="review"): - topo.install_values(base, "alice", tmp_path/"missing", "trusted-tools/network-probe", None, verify=True) - assert not (tmp_path/"missing").exists() - - -def test_default_and_conflicting_issuer(base, cluster): - site = base["containerSites"]["alice"] - del topo.path_value(site, topo.GATEWAY + ("oidc",))["issuerUrl"] - del topo.path_value(site, topo.RELAY)["issuer"] - result = topo.container_overlay(base, "trusted-tools/network-probe") - assert topo.path_value(result["containerSites"]["alice"], topo.RELAY + ("issuer",)) == ( - "https://keycloak.apps.cluster.example.test/realms/openshell") - topo.put(site, topo.RELAY + ("issuer",), "https://a.example/realm") - topo.put(site, topo.GATEWAY + ("oidc", "issuerUrl"), "https://b.example/realm") - with pytest.raises(ValueError, match="same issuer"): - topo.container_overlay(base, "trusted-tools/network-probe") - - -@pytest.mark.parametrize("url", ["http://issuer.example", "https://me@issuer.example", "https://issuer.example?q=1", - "https://issuer.example/#here", "https://issuer.example:0", - "https://issuer.example?", "https://issuer.example/#", "https://issuer.example\\path"]) -def test_unsafe_issuer_rejected_before_exec(url, cluster): - with pytest.raises(ValueError): - topo.discover_issuer(url, "trusted-tools/network-probe", None) - assert not cluster[1] - - -@pytest.mark.parametrize(("status", "claimed", "passes"), [(200, "https://k.test:8443/realm", True), - (302, "https://k.test:8443/realm", False), (200, "https://different.test/realm", False)]) -def test_each_address_uses_original_tls_name_and_checks_document(monkeypatch, status, claimed, passes): - hosts = ["10.0.0.50", "10.0.0.51"] - tls = MagicMock() - monkeypatch.setattr(probe.ssl, "create_default_context", lambda: tls) - monkeypatch.setattr(probe.socket, "getaddrinfo", lambda *a, **kw: [(None, None, None, None, (ip, 8443)) for ip in hosts]) - connect = MagicMock() - monkeypatch.setattr(probe.socket, "create_connection", connect) - https = MagicMock() - monkeypatch.setattr(probe.http.client, "HTTPSConnection", https) - response = https.return_value.getresponse.return_value - response.status = status - response.read.return_value = json.dumps({"issuer": claimed}).encode() - issuer = "https://k.test:8443/realm" - if not passes: - with pytest.raises(ValueError, match="mismatch"): - probe.probe(issuer) - return - assert probe.probe(issuer) == hosts - assert [c.args[0] for c in connect.call_args_list] == [(ip, 8443) for ip in hosts] - assert all(c.kwargs["server_hostname"] == "k.test" for c in tls.wrap_socket.call_args_list) - assert all(c.args == ("GET", "/realm/.well-known/openid-configuration") for c in https.return_value.request.call_args_list) - - -@pytest.mark.parametrize("bad", ["127.0.0.1", "169.254.169.254", "224.0.0.1", "::1"]) -def test_probe_refuses_unsafe_or_unhandled_answers(monkeypatch, bad): - monkeypatch.setattr(probe.socket, "getaddrinfo", lambda *a, **kw: [(None, None, None, None, (bad, 443))]) - connect = MagicMock() - monkeypatch.setattr(probe.socket, "create_connection", connect) - with pytest.raises(ValueError, match="unsafe"): - probe.probe("https://keycloak.example/realms/openshell") - connect.assert_not_called() - - -@pytest.mark.parametrize("hostname", ["issuer.example", "wrong.example"]) -def test_probe_verifies_certificate_over_real_tls(tmp_path, monkeypatch, hostname): - import socket - import ssl - import subprocess - from concurrent.futures import ThreadPoolExecutor - from threading import Event - - cert, key = tmp_path / "cert.pem", tmp_path / "key.pem" - subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "1", - "-subj", "/CN=issuer.example", "-addext", "subjectAltName=DNS:issuer.example", - "-keyout", str(key), "-out", str(cert)], check=True, capture_output=True) - server = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) - server.load_cert_chain(cert, key) - monkeypatch.setenv("SSL_CERT_FILE", str(cert)) - issuer = f"https://{hostname}/realms/test" - response_read = Event() - client_sock, server_sock = socket.socketpair() - for sock in (client_sock, server_sock): - sock.settimeout(5) - monkeypatch.setattr(probe.socket, "getaddrinfo", - lambda *args, **kwargs: [(None, None, None, None, ("10.0.1.2", 443))]) - monkeypatch.setattr(probe.socket, "create_connection", lambda *args, **kwargs: client_sock) - - def serve(): - with server.wrap_socket(server_sock, server_side=True) as stream: - with stream.makefile("rb") as request: - assert request.readline() == b"GET /realms/test/.well-known/openid-configuration HTTP/1.1\r\n" - headers = [] - while (line := request.readline()) not in (b"\r\n", b""): - headers.append(line) - assert b"Host: issuer.example\r\n" in headers - payload = json.dumps({"issuer": issuer}).encode() - stream.sendall(f"HTTP/1.1 200 OK\r\nContent-Length: {len(payload)}\r\n\r\n".encode() + payload) - assert response_read.wait(timeout=5) - - with client_sock, server_sock, ThreadPoolExecutor(max_workers=1) as pool: - served = pool.submit(serve) - if hostname == "issuer.example": - try: - assert probe.probe(issuer) == ["10.0.1.2"] - finally: - response_read.set() - served.result(timeout=5) - else: - with pytest.raises(ssl.SSLCertVerificationError): - probe.probe(issuer) - with pytest.raises(ssl.SSLError): - served.result(timeout=5) - - -@pytest.mark.ci_external -def test_make_commands_and_helm_gateway_policy(tmp_path, monkeypatch, base): - import subprocess - import os - import sys - - # The synthetic oc is only a cluster fixture. Exercise the real VM discovery - # script, Make entry points, YAML review comparison and stock Helm template. - oc = tmp_path / "oc" - oc.write_text("""#!/usr/bin/env python3 -import sys, json, os -args = sys.argv[1:] -if "exec" in args: - data = [os.environ["MOCK_ISSUER_IP"]] -elif "network.config" in args: - 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 "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: - data = {"items":[{"addressType":"IPv4","ports":[{"port":6443}],"endpoints":[{"addresses":["10.0.0.3"]}]}]} -elif "service" in args and "dns-default" in args: - data = {"spec":{"clusterIP":"172.30.0.10","selector":{"dns.operator.openshift.io/daemonset-dns":"default"}, - "ports":[{"name":p.lower(),"port":53,"protocol":p} for p in ["UDP","TCP"]]}} -elif "endpointslice" in args and "openshift-dns" in args: - data = {"items":[{"addressType":"IPv4","ports":[{"name":p.lower(),"port":5353,"protocol":p} for p in ["UDP","TCP"]]}]} -else: - sys.exit(3) -print(json.dumps(data)) -""") - oc.chmod(0o755) - monkeypatch.setenv("PATH", str(tmp_path) + os.pathsep + os.environ["PATH"]) - monkeypatch.setenv("MOCK_ISSUER_IP", "10.10.10.101") - base_file = tmp_path / "site.yaml" - out = tmp_path / "overlay.yaml" - base_file.write_text(yaml.safe_dump(base)) - monkeypatch.setenv("SAW_USERS_VALUES_FILE", str(base_file)) - monkeypatch.setenv("SAW_TOPOLOGY_OVERLAY", str(out)) - monkeypatch.setenv("SAW_TOPOLOGY_PROBE", "trusted-tools/network-probe") - make = ["make", "--no-print-directory", "PYTHON=" + sys.executable] - out.write_text(subprocess.check_output([*make, "container-topology"], text=True, cwd=ROOT)) - subprocess.run([*make, "check-container-topology"], check=True, cwd=ROOT) - gateway = yaml.safe_load(out.read_text())["containerSites"]["alice"]["stack"]["gateway"]["values"] - rendered = subprocess.check_output(["helm", "template", "saw-test", "charts/openshell-saw-kubernetes", - "-n", "saw-test", "--api-versions", "agents.x-k8s.io/v1beta1/Sandbox", - "--api-versions", "policy.networking.k8s.io/v1alpha1/AdminNetworkPolicy", "-f", "tests/fixtures/saw-kubernetes-values.yaml", - "-f", "-"], input=yaml.safe_dump(gateway), text=True, cwd=ROOT) - policies = [r for r in yaml.safe_load_all(rendered) if r and r["kind"] == "NetworkPolicy"] - matching = [r for r in policies if topo.host_rule("10.10.10.101", 443) in r["spec"].get("egress", [])] - assert len(matching) == 1 and matching[0]["spec"]["podSelector"]["matchLabels"]["openshell.pattern/role"] == "gateway" - 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 diff --git a/tests/scripts/test_make_interface.py b/tests/scripts/test_make_interface.py index f9c01723e..8407d8041 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"]) @@ -296,7 +299,7 @@ def test_prereqs_distinguish_missing_operator_from_access_failure(tmp_path): bindir = tmp_path / "bin" bindir.mkdir() executable(bindir / "uv", 'exit 0\n') - executable(bindir / "openshell", 'printf "openshell 0.1.6\\n"\n') + executable(bindir / "openshell", 'printf "openshell 0.1.10\\n"\n') executable(bindir / "oc", ''' case "$*" in whoami) exit 0 ;; @@ -333,7 +336,7 @@ def test_pattern_prereqs_do_not_require_operators(tmp_path): bindir = tmp_path / "bin" bindir.mkdir() executable(bindir / "uv", 'exit 0\n') - executable(bindir / "openshell", 'printf "openshell 0.1.6\\n"\n') + executable(bindir / "openshell", 'printf "openshell 0.1.10\\n"\n') executable(bindir / "oc", ''' case "$*" in whoami) exit 0 ;; @@ -562,7 +565,7 @@ def test_manual_builds_keep_images_local_unless_safe_destination_is_explicit(tmp assert "push " not in calls assert "output.externalImage=ghcr.io" not in calls elif target == "governance-interceptor-build": - assert "output.externalImage=ghcr.io/example/governance-interceptor:v0.1.6" in calls + assert "output.externalImage=ghcr.io/example/governance-interceptor:v0.1.10" in calls else: assert "push " in calls and "ghcr.io/example" in calls diff --git a/tests/scripts/test_profile_catalog_automation.py b/tests/scripts/test_profile_catalog_automation.py index a6943b46b..9a392123d 100644 --- a/tests/scripts/test_profile_catalog_automation.py +++ b/tests/scripts/test_profile_catalog_automation.py @@ -69,13 +69,14 @@ def test_list_names_every_generated_file(): mirrored = [p for p in listed if p.startswith("charts/openshell-saw/files/provider-profiles/")] shipped = sorted(p.name for p in (ROOT / "charts/governance-policy/profiles").glob("*.yaml")) # ... plus the mirror directory itself (so a removed mirror is staged too). - assert "charts/saw-users/templates/_governed-proxy-policy.tpl" in listed - assert "charts/saw-users/files/governed-profiles.json" in listed + for unused in ("charts/saw-users/templates/_governed-proxy-policy.tpl", + "charts/saw-users/files/governed-profiles.json"): + assert unused not in listed assert "charts/openshell-rhdh/files/set-workspace-state.yaml" in listed assert "charts/openshell-rhdh/files/workspace.py" in listed assert "charts/openshell-rhdh/files/saw_keycloak_admin.py" in listed assert UI_MIRROR in listed - assert len(listed) == 12 + len(shipped) + 1 + assert len(listed) == 10 + len(shipped) + 1 assert sorted(p.rsplit("/", 1)[1] for p in mirrored) == shipped assert "charts/openshell-saw/files/provider-profiles" in listed assert "charts/openshell-rhdh/files/create-workspace.yaml" in listed diff --git a/tests/scripts/test_relay_provisioner.py b/tests/scripts/test_relay_provisioner.py new file mode 100644 index 000000000..37c3a7561 --- /dev/null +++ b/tests/scripts/test_relay_provisioner.py @@ -0,0 +1,116 @@ +"""The relay registrar: created without a manual step, never adopts foreign state.""" +import base64 +import importlib.util +import json +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "charts/openshell-keycloak/files")) +SCRIPT = ROOT / "charts/openshell-keycloak/files/relay-provisioner.py" +SPEC = importlib.util.spec_from_file_location("relay_provisioner", SCRIPT) +prov = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(prov) + +ISSUER = "https://keycloak.apps.example.test/realms/openshell" + + +class FakeKube: + """One Secret, with the API's create/get/merge-patch behaviour.""" + + def get(self, path): + return self(path) + + def __init__(self, secret=None): + self.secret, self.writes = secret, [] + + def __call__(self, path, method="GET", body=None, patch=False): + if method == "GET": + if self.secret is None: + raise prov.HttpError(404, "not found") + return json.loads(json.dumps(self.secret)) + self.writes.append(method) + if method == "POST": + assert path.endswith("/secrets") and self.secret is None + self.secret = {"metadata": {**body["metadata"], "resourceVersion": "1"}, + "data": {k: base64.b64encode(v.encode()).decode() + for k, v in body["stringData"].items()}} + else: + assert patch + self.secret["data"] = {k: base64.b64encode(v.encode()).decode() + for k, v in body["stringData"].items()} + return json.loads(json.dumps(self.secret)) + + +def secret(labels, data=None): + return {"metadata": {"name": prov.NAME, "labels": labels, "resourceVersion": "7"}, + "data": {k: base64.b64encode(v.encode()).decode() for k, v in (data or {}).items()}} + + +def test_a_new_cluster_gets_its_credential_without_a_manual_step(): + kube = FakeKube() + values = prov.credential(kube, "saw-keycloak", ISSUER) + assert kube.writes == ["POST"] + assert values["client-id"] == prov.NAME and values["issuer"] == ISSUER + assert len(values["client-secret"]) >= 40 + assert kube.secret["metadata"]["labels"] == {prov.LABEL: prov.NAME} + + +def test_the_credential_is_kept_across_runs(): + kube = FakeKube() + first = prov.credential(kube, "saw-keycloak", ISSUER) + assert prov.credential(kube, "saw-keycloak", ISSUER) == first + assert kube.writes == ["POST"] + + +def test_a_secret_from_the_old_setup_script_is_adopted(): + """Clusters set up by hand with the retired script keep their client.""" + data = {"client-id": prov.NAME, "client-secret": "s" * 54, "issuer": ISSUER} + kube = FakeKube(secret({prov.LABEL: prov.NAME}, data)) + assert prov.credential(kube, "saw-keycloak", ISSUER) == data and kube.writes == [] + + +def test_an_empty_owned_secret_is_filled(): + kube = FakeKube(secret({prov.LABEL: prov.NAME})) + assert prov.credential(kube, "saw-keycloak", ISSUER)["client-id"] == prov.NAME + assert kube.writes == ["PATCH"] + + +@pytest.mark.parametrize("labels,data,message", [ + ({}, {"client-id": prov.NAME, "client-secret": "x", "issuer": ISSUER}, "not this helper's"), + ({prov.LABEL: prov.NAME}, {"client-id": prov.NAME, "client-secret": "x", "issuer": "https://other/realms/x"}, + "issuer"), + ({prov.LABEL: prov.NAME}, {"client-id": "other", "client-secret": "x", "issuer": ISSUER}, "unexpected"), +]) +def test_foreign_or_mismatched_secrets_are_refused(labels, data, message): + kube = FakeKube(secret(labels, data)) + with pytest.raises(ValueError, match=message): + prov.credential(kube, "saw-keycloak", ISSUER) + assert kube.writes == [] + + +def test_errors_are_retried_rather_than_crashing(monkeypatch): + class Stop(Exception): + pass + monkeypatch.setenv("KEYCLOAK_NAMESPACE", "saw-keycloak") + monkeypatch.setenv("KEYCLOAK_NAME", "openshell-keycloak") + monkeypatch.setenv("REALM", "openshell") + monkeypatch.setenv("KC_URL", "https://keycloak.apps.example.test") + monkeypatch.setattr(prov, "Kube", lambda: FakeKube()) + monkeypatch.setattr(prov.saw_tls, "tls_context", lambda *a: None) + calls, sleeps = [], [] + def setup(*args): + calls.append(args) + if len(calls) == 1: + raise prov.HttpError(503, "keycloak starting") + def sleep(seconds): + sleeps.append(seconds) + if len(sleeps) == 2: + raise Stop + monkeypatch.setattr(prov, "setup", setup) + monkeypatch.setattr(prov.time, "sleep", sleep) + with pytest.raises(Stop): + prov.main(["relay-provisioner.py"]) + assert sleeps == [15, 300] and calls[1][2] == ISSUER diff --git a/tests/scripts/test_saw_init.py b/tests/scripts/test_saw_init.py new file mode 100644 index 000000000..a80505860 --- /dev/null +++ b/tests/scripts/test_saw_init.py @@ -0,0 +1,99 @@ +"""make saw-init is the one preparation step: keys, OIDC check, VM image, container checks.""" +import os +from pathlib import Path +import shutil +import subprocess + +import pytest + +ROOT = Path(__file__).resolve().parents[2] + +FAKE_OC = """#!/usr/bin/env bash +case "$*" in + *network.config*) echo OVNKubernetes ;; + *clusterversion*) echo 4.22.0 ;; + *api-resources*) echo validatingadmissionpolicies.admissionregistration.k8s.io ;; +esac +exit 0 +""" + + +def stub(path, body): + path.write_text("#!/usr/bin/env bash\n" + body) + path.chmod(0o755) + + +def run(tmp_path, users, oidc_exit=0, defaults="containerDefaults: {}\n", storage_exit=0, **extra): + repo = tmp_path / "repo" + scripts = repo / "scripts" + scripts.mkdir(parents=True) + shutil.copy(ROOT / "scripts/saw-init.sh", scripts / "saw-init.sh") + log = tmp_path / "calls" + for name in ("generate-keys.sh", "images-mirror.sh"): + stub(scripts / name, f'echo {name} >> "{log}"\n') + stub(scripts / "shared-storage.sh", f'echo shared-storage.sh "$@" >> "{log}"\nexit {storage_exit}\n') + stub(scripts / "check-oidc-ca.sh", f'echo check-oidc-ca.sh >> "{log}"\necho "add oidc.caBundle"\nexit {oidc_exit}\n') + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + stub(bin_dir / "oc", FAKE_OC.split("\n", 1)[1]) + (repo / "overrides").mkdir() + users_file = repo / "overrides/saw-users.yaml" + users_file.write_text("users:\n" + "".join( + f" - name: {name}\n values: {{deployment: {{mode: {mode}}}}}\n" for name, mode in users) if users + else "users: []\n") + (repo / "overrides/saw-container-defaults.yaml").write_text(defaults) + env = {k: v for k, v in os.environ.items() if k not in ("DEPLOYMENT_MODE", "OPENSHELL_SAW_NAME")} + env.update(PATH=f"{bin_dir}:{os.environ['PATH']}", SAW_INIT_SKIP_IMAGE_CHECK="1", **extra) + result = subprocess.run([str(scripts / "saw-init.sh")], cwd=repo, env=env, capture_output=True, text=True) + calls = log.read_text().split() if log.exists() else [] + return result, calls + + +@pytest.mark.parametrize("users", [[], [("alice", "vm")], [("alice", "container"), ("bob", "vm")]]) +def test_vm_workspaces_get_keys_oidc_check_and_the_gateway_image(tmp_path, users): + result, calls = run(tmp_path, users) + assert result.returncode == 0, result.stderr + assert calls[:3] == ["generate-keys.sh", "check-oidc-ca.sh", "images-mirror.sh"] + + +def test_container_only_users_skip_the_vm_image(tmp_path): + result, calls = run(tmp_path, [("alice", "container")]) + assert result.returncode == 0, result.stderr + assert "images-mirror.sh" not in calls + assert calls[:2] == ["generate-keys.sh", "check-oidc-ca.sh"] and "shared-storage.sh" in calls + + +@pytest.mark.parametrize(("code", "fails"), [(0, False), (3, False), (1, False), (2, True)]) +def test_an_untrusted_oidc_issuer_stops_init(tmp_path, code, fails): + result, _ = run(tmp_path, [("alice", "vm")], oidc_exit=code) + assert (result.returncode != 0) is fails + if fails: + assert "oidc.caBundle" in result.stderr + + +def test_a_quickstart_container_install_runs_the_container_checks(tmp_path): + result, calls = run(tmp_path, [], DEPLOYMENT_MODE="container", OPENSHELL_SAW_NAME="alice") + assert result.returncode == 0, result.stderr + assert "images-mirror.sh" not in calls and "shared-storage.sh" in calls + assert "alice" in result.stdout + + + +def test_without_container_users_init_still_prepares_the_storage_classes(tmp_path): + """The portal can request a container workspace later.""" + result, calls = run(tmp_path, [("bob", "vm")]) + assert result.returncode == 0, result.stderr + assert "shared-storage.sh" in calls + + +def test_a_shared_filesystem_is_optional_without_receipts(tmp_path): + result, calls = run(tmp_path, [("alice", "container")], storage_exit=1) + assert result.returncode == 0, result.stderr + assert "--classes-only" in calls + + +def test_receipts_require_a_shared_filesystem(tmp_path): + receipts = "containerDefaults: {auditReceipts: true}\n" + result, calls = run(tmp_path, [("alice", "container")], defaults=receipts, storage_exit=1) + assert result.returncode != 0 + assert "shared-storage.sh" in calls and "--classes-only" not in calls diff --git a/tests/scripts/test_saw_preflight.py b/tests/scripts/test_saw_preflight.py index c8a288b3f..1952e8213 100644 --- a/tests/scripts/test_saw_preflight.py +++ b/tests/scripts/test_saw_preflight.py @@ -187,15 +187,10 @@ def site_config(): pin = "a" * 40 image = "registry.example.invalid/worker@sha256:" + "b" * 64 return { - "providerAllowHosts": ["api.example.invalid"], - "providerPolicy": {"allowHosts": ["api.example.invalid"]}, + "credentialBindings": [{"secret": "inference", "key": "api_key", "type": "openai"}], "automaticEnrollment": {"revision": pin, "image": image}, "stack": { "policy": {"revision": pin}, - "proxy": {"revision": pin, "values": { - "image": image, - "network": {"bootstrapEgress": [{"to": ["api.example.invalid"]}]}, - }}, "gateway": {"revision": pin, "values": { "kubernetes": {"storage": {"className": "workspace-rwx"}, "image": image}, }}, @@ -216,33 +211,39 @@ def test_site_configuration_requires_pinned_sources_and_scoped_egress(): "revisions": True, } changed = site_config() - changed["providerPolicy"]["allowHosts"] = ["*"] + changed["credentialBindings"] = [{"secret": "inference", "key": "api_key"}] changed["stack"]["gateway"]["revision"] = "main" changed["stack"]["audit"]["values"]["image"] = "image:latest" facts = preflight.configuration_facts(changed) assert facts["providerEgress"] is False assert facts["revisions"] is False assert facts["registry"] is False + development = site_config() + development["automaticEnrollment"]["autoApprove"] = True + for component in development["stack"].values(): + component["revision"] = "configure-alice-custom-inference" + development["automaticEnrollment"]["revision"] = "main" + assert preflight.configuration_facts(development)["revisions"] is True + development["stack"]["gateway"]["revision"] = "-not-a-branch" + assert preflight.configuration_facts(development)["revisions"] is False missing_component = site_config() del missing_component["stack"]["audit"] assert preflight.configuration_facts(missing_component)["revisions"] is False invalid_network = site_config() - invalid_network["stack"]["proxy"]["values"]["network"]["bootstrapEgress"] = "all" + del invalid_network["stack"]["policy"] assert preflight.configuration_facts(invalid_network)["network"] is False -def test_documented_provider_hosts_do_not_need_generated_policy(): +def test_credential_bindings_name_a_secret_key_and_provider_type(): site = site_config() - del site["providerPolicy"] assert preflight.configuration_facts(site)["providerEgress"] is True - for hosts in ([], ["*"], ["api.example.invalid", "*.example.invalid"]): - site["providerAllowHosts"] = hosts + site["credentialBindings"].append({"secret": "gmail", "key": "access_token", "type": "gmail", + "refresh": "oauth2_refresh_token"}) + assert preflight.configuration_facts(site)["providerEgress"] is True + for bad in ({"secret": "", "key": "k", "type": "t"}, {"secret": "s", "key": "k"}, + {"secret": "s", "key": "k", "type": "t", "allowHosts": ["*"]}): + site["credentialBindings"] = [bad] assert preflight.configuration_facts(site)["providerEgress"] is False - site["providerAllowHosts"] = ["api.example.invalid"] - site["providerPolicy"] = {"allowHosts": ["other.example.invalid"]} - assert preflight.configuration_facts(site)["providerEgress"] is False - site["providerPolicy"] = {"allowHosts": [{}]} - assert preflight.configuration_facts(site)["providerEgress"] is False def test_storage_preflight_rejects_missing_class_and_accepts_default_class(): diff --git a/tests/scripts/test_shared_storage.py b/tests/scripts/test_shared_storage.py new file mode 100644 index 000000000..4af84cdd4 --- /dev/null +++ b/tests/scripts/test_shared_storage.py @@ -0,0 +1,116 @@ +"""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 + + +def copies(tmp_path, items, *args): + """Run against a fake oc that knows the given classes and records creates.""" + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + (tmp_path / "classes.json").write_text(json.dumps({"items": items})) + for item in items: + (tmp_path / (item["metadata"]["name"] + ".json")).write_text(json.dumps(item)) + created = tmp_path / "created" + oc = bin_dir / "oc" + oc.write_text(f"""#!/usr/bin/env bash +case "$*" in + "get storageclass -o json") cat {tmp_path}/classes.json ;; + "get storageclass "*" -o json") cat {tmp_path}/$3.json ;; + "get storageclass "*) [ -f {tmp_path}/$3.json ] ;; + "create -f -") cat >> {created}; echo --- >> {created} ;; +esac +""") + oc.chmod(0o755) + env = dict(os.environ, PATH=f"{bin_dir}:{os.environ['PATH']}") + env.pop("SAW_SHARED_STORAGE", None) + result = subprocess.run(["bash", str(SCRIPT), *args], env=env, stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=60, check=False) + made = [json.loads(doc) for doc in created.read_text().split("---") if doc.strip()] if created.exists() else [] + return result, made + + +RBD = {"metadata": {"name": "rbd", "annotations": {"storageclass.kubernetes.io/is-default-class": "true"}}, + "provisioner": "rbd.csi.ceph.com", "parameters": {"pool": "p"}, "reclaimPolicy": "Delete"} +CEPHFS = {"metadata": {"name": "cephfs"}, "provisioner": "openshift-storage.cephfs.csi.ceph.com", + "parameters": {"fsName": "fs"}, "volumeBindingMode": "Immediate"} + + +def test_the_shared_class_name_is_a_copy_of_the_clusters_shared_class(tmp_path): + result, made = copies(tmp_path, [RBD, CEPHFS]) + assert result.returncode == 0, result.stderr + shared, = made + assert shared["metadata"]["name"] == "saw-shared" + assert shared["provisioner"] == "openshift-storage.cephfs.csi.ceph.com" + assert shared["parameters"] == {"fsName": "fs"} and shared["volumeBindingMode"] == "Immediate" + assert shared["metadata"]["annotations"] == {"saw.redhat.com/copy-of": "cephfs"} + + +def test_an_existing_copy_is_kept(tmp_path): + mine = {"metadata": {"name": "saw-shared"}, "provisioner": "nfs.csi.k8s.io"} + result, made = copies(tmp_path, [RBD, CEPHFS, mine]) + assert result.returncode == 0, result.stderr + assert made == [] and "StorageClass saw-shared" in result.stdout + + +@pytest.mark.parametrize("items", [[RBD], [RBD, CEPHFS]]) +def test_classes_only_creates_the_copy_only_where_the_cluster_can_back_it(tmp_path, items): + result, made = copies(tmp_path, items, "--classes-only") + assert result.returncode == 0, result.stderr + assert [m["metadata"]["name"] for m in made] == (["saw-shared"] if CEPHFS in items else []) + assert not result.stderr diff --git a/tests/scripts/test_standalone_projector.py b/tests/scripts/test_standalone_projector.py index ef3a486fc..637475dd7 100644 --- a/tests/scripts/test_standalone_projector.py +++ b/tests/scripts/test_standalone_projector.py @@ -99,6 +99,58 @@ def test_gitops_kata_preflight_checks_live_runtime(projector): projector.verify_gitops_preflight(owner, site, "kata", read) +KATA_CLASS = {"metadata": {"name": "saw-kata", "uid": "22222222-2222-4222-8222-222222222222", + "labels": {"openshell.ai/sandbox-attachable": "true"}}, + "handler": "kata", "overhead": {"podFixed": {"cpu": "250m", "memory": "350Mi"}}, + "scheduling": {"nodeSelector": {"node-role.kubernetes.io/kata-oc": ""}}} + + +def demo_site(**approval): + return {"automaticEnrollment": {"enabled": True, "autoApprove": True}, + "kataRuntimeClass": {"name": "saw-kata", **approval}} + + +def test_autoapprove_kata_binds_the_live_runtime_class(projector): + reads = [] + def read(path): + reads.append(path) + return copy.deepcopy(KATA_CLASS) + site = demo_site() + bound = projector.bind_runtime_class(site, read) + assert reads == ["/apis/node.k8s.io/v1/runtimeclasses/saw-kata"] + approval = bound["kataRuntimeClass"] + assert approval["uid"] == KATA_CLASS["metadata"]["uid"] + assert approval["sha256"] == projector.preflight.runtime_placement_digest(KATA_CLASS) + assert site["kataRuntimeClass"] == {"name": "saw-kata"} # input untouched + + +def test_explicit_kata_approval_is_never_replaced(projector): + site = demo_site(uid="33333333-3333-4333-8333-333333333333", sha256="a" * 64) + assert projector.bind_runtime_class(site, lambda path: pytest.fail("no live read")) is site + + +@pytest.mark.parametrize("change, reason", [ + (lambda c: c["metadata"]["labels"].clear(), "RuntimeClassNotAttachable"), + (lambda c: c.update(handler="runc"), "RuntimeClassHandlerMismatch"), + (lambda c: c.update(scheduling=None), "RuntimeClassSchedulingInvalid"), + (lambda c: c.clear(), "RuntimeClassUnavailable"), +]) +def test_autoapprove_still_refuses_an_unsuitable_class(projector, change, reason): + live = copy.deepcopy(KATA_CLASS) + change(live) + with pytest.raises(projector.preflight.PreflightError) as exc: + projector.bind_runtime_class(demo_site(), lambda path: live) + assert exc.value.reason == reason + + +def test_a_reviewed_site_needs_an_explicit_kata_approval(projector): + site = demo_site() + site["automaticEnrollment"]["autoApprove"] = False + with pytest.raises(projector.preflight.PreflightError) as exc: + projector.bind_runtime_class(site, lambda path: copy.deepcopy(KATA_CLASS)) + assert exc.value.reason == "RuntimeClassApprovalMissing" + + def test_gitops_preflight_reader_rejects_secret_paths(projector): reader = object.__new__(projector.Publications) with pytest.raises(projector.ProjectionError, match="outside the workspace scope"): @@ -110,7 +162,7 @@ def config(): user = dict(name="alice", ownerSubject=site["subject"], registration="a"*16, installationID="22222222-2222-4222-8222-222222222222", profiles=["data-science"], values={"deployment": {"mode": "container"}}, pruneOnRemove=True, - intentGeneration=1, vaultPrefix="secret/data/hub/saw-alice/"+"a"*16) + intentGeneration=1, vaultPrefix="secret/data/hub/saw-alice") return dict(users=[user], containerSites={"alice": site}, global_={}) diff --git a/tests/scripts/test_workspace_projection.py b/tests/scripts/test_workspace_projection.py index 5e5dbbe01..c7f5fbf5c 100644 --- a/tests/scripts/test_workspace_projection.py +++ b/tests/scripts/test_workspace_projection.py @@ -83,6 +83,84 @@ def test_foundation_requires_no_synthetic_approval_hash(): workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) +def auto_site(owner): + return dict(subject=owner["ownerSubject"], automaticEnrollment={ + "autoApprove": True, "revision": "main", "image": "example/runtime@sha256:" + "d"*64, + "buildNamespace": "saw-builds", "relay": {"revision": "main"}}) + + +def published(owner, subject=None): + intent = {"bindings": {"ownerID": owner["installationID"], "namespace": "saw-" + owner["name"], + "ownerSubject": subject or owner["ownerSubject"]}, + "profileRef": {"name": "saw-bom-profiles", "sha256": "e"*64}} + binding = {"registration": owner["registration"], "intent": intent, + "approved": {"observed": "f"*64}, "gatewayCA": "ca"} + return {"immutable": True, "metadata": {"labels": {"saw.redhat.com/runtime-owner": owner["installationID"]}}, + "data": {"binding.json": json.dumps(binding)}} + + +def test_auto_approve_needs_no_reference_or_profile_digest(): + owner, _ = inputs() + result = workspace.project_workspace(owner, {}, auto_site(owner), CATALOG, lambda _: {}) + projected = result["containerSites"]["alice"] + assert not projected["selectedDigest"] and "enrollment" not in projected + + +def test_auto_approve_accepts_the_observed_enrollment_but_still_binds_the_owner(): + owner, _ = inputs() + projected = workspace.project_workspace(owner, {}, auto_site(owner), CATALOG, + lambda _: published(owner))["containerSites"]["alice"] + assert projected["enrollment"]["approved"] == {"observed": "f"*64} + assert projected["enrollment"]["revision"] == "main" + with pytest.raises(workspace.WorkspaceError, match="does not belong"): + workspace.project_workspace(owner, {}, auto_site(owner), CATALOG, + lambda _: published(owner, subject="33333333-3333-4333-8333-333333333333")) + + +def test_custom_inference_uses_the_owners_own_url(): + owner, _ = inputs() + owner.update(profiles=["custom-inference"]) + for key in ("lifecycleVersion", "initialModelInputs", "modelInputs", "desiredState", "restartGeneration"): + owner.pop(key) + owner["modelInputs"] = {"inference.model": "org/model"} + site = auto_site(owner) + # No site-level URL: the entry names its own; the governance profile approves the host at run time. + with pytest.raises(workspace.WorkspaceError, match="set customInferenceURL"): + workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) + owner["customInferenceURL"] = "https://api.inference.example/v1" + result = workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) + projected = result["containerSites"]["alice"] + assert projected["customInferenceURL"] == "https://api.inference.example/v1" + assert "profileBoundaries" not in projected or "custom-inference" not in projected["profileBoundaries"] + assert "reference" not in projected["automaticEnrollment"] + assert result["users"][0]["webSearch"] == {"enabled": False} # dedicated endpoint, as in the portal + for bad in ("http://api.inference.example/v1", "https://api.inference.example/v2", + "https://api.inference.example:8443/v1", "https://10.0.0.1/v1"): + owner["customInferenceURL"] = bad + with pytest.raises(workspace.WorkspaceError, match="HTTPS base URL ending in /v1"): + workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) + owner["customInferenceURL"] = "https://api.inference.example/v1" + del owner["modelInputs"] + with pytest.raises(workspace.WorkspaceError, match="set modelInputs.inference.model"): + workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) + + +def test_only_an_endpoint_profile_takes_a_custom_inference_url(): + owner, _ = inputs() + owner["customInferenceURL"] = "https://api.inference.example/v1" + with pytest.raises(workspace.WorkspaceError, match="only a profile with an endpoint input"): + workspace.project_workspace(owner, {}, auto_site(owner), CATALOG, lambda _: {}) + + +def test_reviewed_site_still_rejects_an_unreviewed_enrollment(): + owner, _ = inputs() + site = auto_site(owner) + site["automaticEnrollment"].update(autoApprove=False, reference={"other": "0"*64}, + approvedProfiles={"data-science": "e"*64}) + with pytest.raises(workspace.WorkspaceError, match="invalid published enrollment"): + workspace.project_workspace(owner, {}, site, CATALOG, lambda _: published(owner)) + + @pytest.mark.parametrize("mode", ["vm", "container"]) def test_operator_revision_pin_is_shared_and_does_not_change_repository(mode): owner, site = inputs() diff --git a/values-prod.yaml b/values-prod.yaml index 96722476b..a82d1a6de 100644 --- a/values-prod.yaml +++ b/values-prod.yaml @@ -35,9 +35,22 @@ 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: [] + # OpenShift sandboxed containers, for Kata workspaces. The operator alone + # changes no node; the saw-kata application's KataConfig (off by default) + # installs the runtime. + openshift-sandboxed-containers-operator: + operatorGroup: true + targetNamespaces: + - openshift-sandboxed-containers-operator + # Red Hat build of OpenTelemetry: the collector for OCSF audit events. + openshift-opentelemetry-operator: + operatorGroup: true + targetNamespaces: [] vault: subscriptions: eso: @@ -65,6 +78,14 @@ clusterGroup: name: rhods-operator namespace: redhat-ods-operator channel: fast + sandboxed-containers: + name: sandboxed-containers-operator + namespace: openshift-sandboxed-containers-operator + channel: stable + opentelemetry: + name: opentelemetry-product + namespace: openshift-opentelemetry-operator + channel: stable applications: openshift-external-secrets: name: openshift-external-secrets @@ -90,6 +111,18 @@ clusterGroup: value: "true" - name: ownerResolver.enabled value: "true" + # Registrar for container workspaces' browser relays. + - name: relayProvisioner.enabled + value: "true" + # Stock upstream Agent Sandbox controller (CRDs + controller), required by + # container and Kata workspaces. Remove if the platform already provides it. + agent-sandbox: + name: agent-sandbox + namespace: agent-sandbox-system + path: charts/agent-sandbox + overrides: + - name: enabled + value: "true" # One namespace and three apps (secrets, bill of materials, VM) per user, # from overrides/saw-users.yaml. The chart release is tracked here; the # Application objects it creates live in the Argo CD namespace. @@ -100,6 +133,7 @@ clusterGroup: namespace: openshell-agents path: charts/saw-users extraValueFiles: + - /overrides/saw-container-defaults.yaml - /overrides/saw-users.yaml overrides: - name: ownerResolution.enabled @@ -124,7 +158,22 @@ 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. + - /overrides/saw-container-defaults.yaml - /overrides/saw-users.yaml + # Kata runtime for Kata workspaces. Reboots the selected workers when + # enabled (charts/saw-kata); off by default. + saw-kata: + name: saw-kata + namespace: openshift-sandboxed-containers-operator + path: charts/saw-kata + # Collector for the OCSF events container gateways and their supervisors + # export (best-effort audit). Point its exporters at your SIEM or log store. + saw-telemetry: + name: saw-telemetry + namespace: openshell-agents + path: charts/saw-telemetry governance-policy: name: governance-policy namespace: openshell-agents From 1441169dff1748946f60acde6e2a23d824eb580f Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Wed, 25 Nov 2026 07:17:18 +0000 Subject: [PATCH 4/9] Images and CI for OpenShell v0.1.10 - OpenShift-ready OpenClaw image and the workspace runtime image, published from branches on demand. - Governance interceptor built from OpenShell v0.1.10 (Rust 1.95) with the SAW extension; the NVIDIA/OpenShell#3929 workaround stays. - TEMPORARY carry: odh-openshell-sandbox v0.1.10-rhaiv.0 rebuilt with one fix. Its network broker panicked on every connect on RHEL 9: rustix could read the aux vector neither through PR_GET_AUXV (Linux 6.4+) nor through /proc/self/auxv once the sandbox is nondumpable. The patch reads it at the top of main(). Remove once a fixed image is released. Assisted-By: Claude --- .github/actions/build-push-image/action.yml | 35 ++++-- .github/actions/merge-image/action.yml | 13 ++- .../build-governance-interceptor.yml | 14 ++- .../workflows/build-kubernetes-runtime.yml | 14 ++- .github/workflows/build-openclaw-image.yml | 106 ++++++++++++++++++ .../build-openshell-sandbox-carry.yml | 75 +++++++++++++ .../files/Dockerfile | 6 +- .../governance-interceptor-image/values.yaml | 8 +- .../helm/openshell-gateway-image/values.yaml | 6 +- images/saw-openclaw/Containerfile | 15 +++ openshell-sandbox-carry/Dockerfile | 55 +++++++++ openshell-sandbox-carry/auxv-warmup.patch | 31 +++++ 12 files changed, 348 insertions(+), 30 deletions(-) create mode 100644 .github/workflows/build-openclaw-image.yml create mode 100644 .github/workflows/build-openshell-sandbox-carry.yml create mode 100644 images/saw-openclaw/Containerfile create mode 100644 openshell-sandbox-carry/Dockerfile create mode 100644 openshell-sandbox-carry/auxv-warmup.patch diff --git a/.github/actions/build-push-image/action.yml b/.github/actions/build-push-image/action.yml index 1eb3300fd..4d3c6f123 100644 --- a/.github/actions/build-push-image/action.yml +++ b/.github/actions/build-push-image/action.yml @@ -1,7 +1,7 @@ name: Build and push image description: >- Shared tail for the container image builds: buildx setup, ghcr.io login, and a - gated build/push (publish only on main) with GitHub Actions layer cache. + gated build/push (publish on main, or on request) with GitHub Actions layer cache. Callers do their own checkout / values.yaml read / upstream clone as normal steps before calling this. @@ -30,6 +30,13 @@ inputs: description: Optional extra tag pushed with :latest and :sha- (e.g. the upstream version) required: false default: "" + publish: + description: >- + 'true' also publishes from a branch (a manual run), tagged only + :sha-; :latest and extra_tag move only from main. + Empty -> publish only on main. + required: false + default: "" platform: description: >- One platform to build (e.g. linux/arm64) on a runner of that architecture. @@ -53,11 +60,18 @@ runs: run: | owner=${OWNER,,} echo "owner=$owner" >> "$GITHUB_OUTPUT" + publish=false + if [ "$PUBLISH" = true ] || { [ "$EVENT" != pull_request ] && [ "$REF" = refs/heads/main ]; }; then + publish=true + fi + echo "publish=$publish" >> "$GITHUB_OUTPUT" { echo "tags<> "$GITHUB_OUTPUT" env: @@ -65,11 +79,14 @@ runs: IMAGE: ${{ inputs.image_name }} SHA: ${{ github.sha }} EXTRA_TAG: ${{ inputs.extra_tag }} + PUBLISH: ${{ inputs.publish }} + EVENT: ${{ github.event_name }} + REF: ${{ github.ref }} - uses: docker/setup-buildx-action@v3 - name: Log in to ghcr.io - if: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + if: ${{ steps.meta.outputs.publish == 'true' }} uses: docker/login-action@v3 with: registry: ghcr.io @@ -84,7 +101,7 @@ runs: context: ${{ inputs.context }} file: ${{ inputs.dockerfile }} build-args: ${{ inputs.build_args }} - push: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + push: ${{ steps.meta.outputs.publish == 'true' }} tags: ${{ steps.meta.outputs.tags }} labels: org.opencontainers.image.source=https://github.com/${{ github.repository }} cache-from: type=gha,scope=${{ inputs.cache_scope }} @@ -92,7 +109,7 @@ runs: provenance: false - uses: ./.github/actions/verify-public-image - if: ${{ inputs.platform == '' && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + if: ${{ inputs.platform == '' && steps.meta.outputs.publish == 'true' }} with: image: ghcr.io/${{ steps.meta.outputs.owner }}/${{ inputs.image_name }}:sha-${{ github.sha }} @@ -115,13 +132,13 @@ runs: platforms: ${{ inputs.platform }} tags: ghcr.io/${{ steps.meta.outputs.owner }}/${{ inputs.image_name }} labels: org.opencontainers.image.source=https://github.com/${{ github.repository }} - outputs: type=image,push-by-digest=true,name-canonical=true,push=${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + outputs: type=image,push-by-digest=true,name-canonical=true,push=${{ steps.meta.outputs.publish == 'true' }} cache-from: type=gha,scope=${{ inputs.cache_scope }}-${{ steps.plat.outputs.suffix }} cache-to: type=gha,mode=max,scope=${{ inputs.cache_scope }}-${{ steps.plat.outputs.suffix }},ignore-error=true provenance: false - name: Record digest - if: inputs.platform != '' && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + if: inputs.platform != '' && steps.meta.outputs.publish == 'true' shell: bash run: | mkdir -p "$RUNNER_TEMP/digests" @@ -130,7 +147,7 @@ runs: DIGEST: ${{ steps.digest-build.outputs.digest }} - uses: actions/upload-artifact@v4 - if: inputs.platform != '' && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + if: inputs.platform != '' && steps.meta.outputs.publish == 'true' with: name: digests-${{ inputs.image_name }}-${{ steps.plat.outputs.suffix }} path: ${{ runner.temp }}/digests/* diff --git a/.github/actions/merge-image/action.yml b/.github/actions/merge-image/action.yml index 7635530af..8f5d990d0 100644 --- a/.github/actions/merge-image/action.yml +++ b/.github/actions/merge-image/action.yml @@ -43,18 +43,25 @@ runs: owner=${OWNER,,} echo "owner=$owner" >> "$GITHUB_OUTPUT" repo="ghcr.io/$owner/$IMAGE" - tags=(-t "$repo:latest" -t "$repo:sha-$SHA") - if [ -n "$EXTRA_TAG" ]; then tags+=(-t "$repo:$EXTRA_TAG"); fi + tags=(-t "$repo:sha-$SHA") + # Moving tags only from main; a branch publish is reachable by commit. + if [ "$REF" = refs/heads/main ]; then + tags+=(-t "$repo:latest") + if [ -n "$EXTRA_TAG" ]; then tags+=(-t "$repo:$EXTRA_TAG"); fi + fi sources=() for d in *; do sources+=("$repo@sha256:$d"); done [ "${#sources[@]}" -ge 2 ] || { echo "expected a digest per platform, got: ${sources[*]}" >&2; exit 1; } docker buildx imagetools create "${tags[@]}" "${sources[@]}" - docker buildx imagetools inspect "$repo:latest" + docker buildx imagetools inspect "$repo:sha-$SHA" + echo "### $IMAGE" >> "$GITHUB_STEP_SUMMARY" + docker buildx imagetools inspect "$repo:sha-$SHA" --format '`{{.Manifest.Digest}}`' >> "$GITHUB_STEP_SUMMARY" env: OWNER: ${{ github.repository_owner }} IMAGE: ${{ inputs.image_name }} SHA: ${{ github.sha }} EXTRA_TAG: ${{ inputs.extra_tag }} + REF: ${{ github.ref }} - uses: ./.github/actions/verify-public-image with: diff --git a/.github/workflows/build-governance-interceptor.yml b/.github/workflows/build-governance-interceptor.yml index 254f73646..53de4c863 100644 --- a/.github/workflows/build-governance-interceptor.yml +++ b/.github/workflows/build-governance-interceptor.yml @@ -19,6 +19,11 @@ on: - tests/charts/test_governance_interceptor_image.py - image-builder-charts/helm/governance-interceptor-image/** workflow_dispatch: + inputs: + publish: + description: Publish this branch's build as ghcr.io//governance-interceptor:sha- + type: boolean + default: false permissions: contents: read @@ -31,7 +36,7 @@ jobs: # One native build per architecture (no QEMU), each pushed by digest; the # merge job joins them into one multi-arch :latest / :sha- tag. build: - if: github.event_name == 'pull_request' || github.ref != 'refs/heads/main' + if: github.event_name == 'pull_request' || (github.ref != 'refs/heads/main' && !inputs.publish) strategy: &platforms # Each architecture reports its own result; merge still needs both. fail-fast: false @@ -78,7 +83,8 @@ jobs: # the interceptor must match the SAW gateways' OpenShell release. extra_tag: ${{ steps.params.outputs.openshell_ref }} platform: ${{ matrix.platform }} - registry_token: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && secrets.GITHUB_TOKEN || '' }} + publish: ${{ inputs.publish && 'true' || '' }} + registry_token: ${{ ((github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish) && secrets.GITHUB_TOKEN || '' }} # Compile the OpenShift build source too, including its behavioral # tests, on each architecture. This targets the builder stage; no @@ -121,7 +127,7 @@ jobs: provenance: false publish: - if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + if: (github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish permissions: {contents: read, packages: write} strategy: *platforms runs-on: ${{ matrix.runner }} @@ -130,7 +136,7 @@ jobs: merge: needs: publish permissions: {contents: read, packages: write} - if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + if: (github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/build-kubernetes-runtime.yml b/.github/workflows/build-kubernetes-runtime.yml index 36a45f813..b9a449981 100644 --- a/.github/workflows/build-kubernetes-runtime.yml +++ b/.github/workflows/build-kubernetes-runtime.yml @@ -29,6 +29,11 @@ on: - .github/actions/merge-image/** - .github/actions/verify-public-image/** workflow_dispatch: + inputs: + publish: + description: Publish this branch's build as ghcr.io//saw-kubernetes-runtime:sha- + type: boolean + default: false permissions: contents: read @@ -39,7 +44,7 @@ concurrency: jobs: build: - if: github.event_name == 'pull_request' || github.ref != 'refs/heads/main' + if: github.event_name == 'pull_request' || (github.ref != 'refs/heads/main' && !inputs.publish) strategy: &platforms fail-fast: false matrix: @@ -58,9 +63,10 @@ jobs: dockerfile: kubernetes-runtime/Containerfile cache_scope: saw-kubernetes-runtime platform: ${{ matrix.platform }} - registry_token: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && secrets.GITHUB_TOKEN || '' }} + publish: ${{ inputs.publish && 'true' || '' }} + registry_token: ${{ ((github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish) && secrets.GITHUB_TOKEN || '' }} publish: - if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + if: (github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish permissions: {contents: read, packages: write} strategy: *platforms runs-on: ${{ matrix.runner }} @@ -69,7 +75,7 @@ jobs: merge: needs: publish permissions: {contents: read, packages: write} - if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + if: (github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/build-openclaw-image.yml b/.github/workflows/build-openclaw-image.yml new file mode 100644 index 000000000..a64d9f7d5 --- /dev/null +++ b/.github/workflows/build-openclaw-image.yml @@ -0,0 +1,106 @@ +name: Build the OpenShift-ready OpenClaw image + +# Publishes ghcr.io//saw-openclaw (linux/amd64 and +# linux/arm64): the notebook BOM's stock OpenClaw image with /sandbox +# searchable by OpenShift namespace UIDs (images/saw-openclaw/Containerfile). +# Pin the published digest in containerDefaults.profileImageOverrides. + +on: + push: + branches: [main] + paths: + - images/saw-openclaw/** + - charts/saw-bom/profiles/data-science/default/sandbox.yaml + - .github/workflows/build-openclaw-image.yml + - .github/actions/build-push-image/** + - .github/actions/merge-image/** + pull_request: + paths: + - images/saw-openclaw/** + - charts/saw-bom/profiles/data-science/default/sandbox.yaml + - .github/workflows/build-openclaw-image.yml + - .github/actions/build-push-image/** + - .github/actions/merge-image/** + workflow_dispatch: + inputs: + publish: + description: Publish this branch's build as ghcr.io//saw-openclaw:sha- + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: build-openclaw-image-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + if: github.event_name == 'pull_request' || (github.ref != 'refs/heads/main' && !inputs.publish) + strategy: &platforms + fail-fast: false + matrix: + include: + - platform: linux/amd64 + runner: ubuntu-latest + - platform: linux/arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + steps: &build_steps + - uses: actions/checkout@v4 + - name: Resolve the stock image and its user + id: source + env: + PLATFORM: ${{ matrix.platform }} + run: | + set -euo pipefail + image=$(yq -r '.spec.sandboxes[] | select(.name == "notebook") | .image' charts/saw-bom/profiles/data-science/default/sandbox.yaml) + [[ "$image" =~ ^[a-z0-9][a-z0-9./:_-]+@sha256:([0-9a-f]{64})$ ]] || { echo "notebook image must be pinned by digest: $image" >&2; exit 1; } + digest="${BASH_REMATCH[1]}" + user=$(docker buildx imagetools inspect "$image" --format '{{json .Image}}' | + jq -er --arg p "$PLATFORM" 'if has("config") then .config.User else .[$p].config.User end | select(type == "string" and length > 0)') + [[ "$user" =~ ^[A-Za-z0-9_-]+(:[A-Za-z0-9_-]+)?$ && "${user%%:*}" != root && "${user%%:*}" != 0 ]] || { echo "stock image must declare a non-root USER: $user" >&2; exit 1; } + { + echo "image=$image" + echo "user=$user" + echo "tag=src-${digest:0:12}" + } >> "$GITHUB_OUTPUT" + - uses: ./.github/actions/build-push-image + with: + image_name: saw-openclaw + context: images/saw-openclaw + dockerfile: images/saw-openclaw/Containerfile + cache_scope: saw-openclaw + platform: ${{ matrix.platform }} + publish: ${{ inputs.publish && 'true' || '' }} + build_args: | + SOURCE_IMAGE=${{ steps.source.outputs.image }} + IMAGE_USER=${{ steps.source.outputs.user }} + registry_token: ${{ ((github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish) && secrets.GITHUB_TOKEN || '' }} + + publish: + if: (github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish + permissions: {contents: read, packages: write} + strategy: *platforms + runs-on: ${{ matrix.runner }} + steps: *build_steps + + merge: + needs: publish + permissions: {contents: read, packages: write} + if: (github.event_name != 'pull_request' && github.ref == 'refs/heads/main') || inputs.publish + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Source tag + id: source + run: | + image=$(yq -r '.spec.sandboxes[] | select(.name == "notebook") | .image' charts/saw-bom/profiles/data-science/default/sandbox.yaml) + digest="${image##*@sha256:}" + echo "tag=src-${digest:0:12}" >> "$GITHUB_OUTPUT" + - uses: ./.github/actions/merge-image + with: + image_name: saw-openclaw + extra_tag: ${{ steps.source.outputs.tag }} + registry_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/build-openshell-sandbox-carry.yml b/.github/workflows/build-openshell-sandbox-carry.yml new file mode 100644 index 000000000..2d647729d --- /dev/null +++ b/.github/workflows/build-openshell-sandbox-carry.yml @@ -0,0 +1,75 @@ +name: Build and push openshell-sandbox carry image + +# TEMPORARY: rebuilds odh-openshell-sandbox v0.1.10-rhaiv.0 with the auxv +# warm-up fix (openshell-sandbox-carry/). Remove with that directory. + +on: + # A push of the carry publishes it: workflow_dispatch only works once the + # workflow is on the default branch. + push: + paths: + - .github/workflows/build-openshell-sandbox-carry.yml + - openshell-sandbox-carry/** + pull_request: + paths: + - .github/workflows/build-openshell-sandbox-carry.yml + - openshell-sandbox-carry/** + workflow_dispatch: + inputs: + publish: + description: Publish this branch's build as ghcr.io//saw-openshell-sandbox:sha- + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: build-openshell-sandbox-carry-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + if: github.event_name == 'pull_request' || (github.event_name == 'workflow_dispatch' && !inputs.publish) + strategy: &platforms + fail-fast: false + matrix: + include: + - platform: linux/amd64 + runner: ubuntu-latest + - platform: linux/arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + steps: &build_steps + - uses: actions/checkout@v4 + + - uses: ./.github/actions/build-push-image + with: + image_name: saw-openshell-sandbox + context: openshell-sandbox-carry + dockerfile: openshell-sandbox-carry/Dockerfile + cache_scope: saw-openshell-sandbox + extra_tag: v0.1.10-rhaiv.0-auxv + platform: ${{ matrix.platform }} + publish: ${{ (github.event_name == 'push' || inputs.publish) && 'true' || '' }} + registry_token: ${{ (github.event_name == 'push' || inputs.publish) && secrets.GITHUB_TOKEN || '' }} + + publish: + if: github.event_name == 'push' || inputs.publish + permissions: {contents: read, packages: write} + strategy: *platforms + runs-on: ${{ matrix.runner }} + steps: *build_steps + + merge: + needs: publish + permissions: {contents: read, packages: write} + if: github.event_name == 'push' || inputs.publish + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/merge-image + with: + image_name: saw-openshell-sandbox + extra_tag: v0.1.10-rhaiv.0-auxv + registry_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/image-builder-charts/helm/governance-interceptor-image/files/Dockerfile b/image-builder-charts/helm/governance-interceptor-image/files/Dockerfile index aba29a8ce..3a0731fc6 100644 --- a/image-builder-charts/helm/governance-interceptor-image/files/Dockerfile +++ b/image-builder-charts/helm/governance-interceptor-image/files/Dockerfile @@ -1,5 +1,5 @@ -# OpenShell 0.1.x needs Rust 1.94 (rust-version in its Cargo.toml). -ARG BUILDER_IMAGE=rust:1.94-bookworm +# OpenShell 0.1.10 pins Rust 1.95 (its rust-toolchain.toml). +ARG BUILDER_IMAGE=rust:1.95-bookworm ARG RUNTIME_IMAGE=debian-runtime FROM ${BUILDER_IMAGE} AS builder @@ -7,7 +7,7 @@ FROM ${BUILDER_IMAGE} AS builder RUN apt-get update && apt-get install -y protobuf-compiler pkg-config libssl-dev git make cmake g++ && rm -rf /var/lib/apt/lists/* WORKDIR /build -ARG OPENSHELL_REF=v0.1.6 +ARG OPENSHELL_REF=v0.1.10 ARG OPENSHELL_URI=https://github.com/NVIDIA/OpenShell.git ARG CONTEXT_DIR=examples/governance-interceptor RUN git init . \ diff --git a/image-builder-charts/helm/governance-interceptor-image/values.yaml b/image-builder-charts/helm/governance-interceptor-image/values.yaml index afcdd08ce..41da4edc8 100644 --- a/image-builder-charts/helm/governance-interceptor-image/values.yaml +++ b/image-builder-charts/helm/governance-interceptor-image/values.yaml @@ -1,7 +1,7 @@ source: git: uri: "https://github.com/NVIDIA/OpenShell.git" - ref: "v0.1.6" + ref: "v0.1.10" build: # For GitOps, give each new build recipe its own BuildConfig name. @@ -9,8 +9,8 @@ build: # Default preserves the existing explicit Make build command. configChangeTrigger: false contextDir: "examples/governance-interceptor" - # OpenShell 0.1.x needs Rust 1.94 (rust-version in its Cargo.toml). - builderImage: "rust:1.94-bookworm" + # OpenShell 0.1.10 pins Rust 1.95 (its rust-toolchain.toml). + builderImage: "rust:1.95-bookworm" runtimeImage: "registry.access.redhat.com/ubi9-micro:latest" # Shared Dockerfile stage with Debian and its CA certificates installed. ghcrRuntimeImage: "debian-runtime" @@ -23,4 +23,4 @@ output: pushSecretName: "ghcr-push-secret" # Build into the internal registry by default. To publish elsewhere, clear # this and explicitly set externalImage plus pushSecretName. - imageStreamTag: "governance-interceptor:v0.1.6" + imageStreamTag: "governance-interceptor:v0.1.10" diff --git a/image-builder-charts/helm/openshell-gateway-image/values.yaml b/image-builder-charts/helm/openshell-gateway-image/values.yaml index 6d0b9c8c8..5ada8ab28 100644 --- a/image-builder-charts/helm/openshell-gateway-image/values.yaml +++ b/image-builder-charts/helm/openshell-gateway-image/values.yaml @@ -6,9 +6,9 @@ containerRuntime: podman openshell: # Informational: the in-VM installer installs OpenShell from the SAW's # InstallerBOM (charts/openshell-saw values `bom:`), not from these. - version: "0.1.6" - gatewayImage: "quay.io/opendatahub/odh-openshell-gateway:v0.1.6-rhaiv.4" - supervisorImage: "quay.io/opendatahub/odh-openshell-supervisor:v0.1.6-rhaiv.4" + version: "0.1.10" + gatewayImage: "quay.io/opendatahub/odh-openshell-gateway:v0.1.10-rhaiv.0" + supervisorImage: "quay.io/opendatahub/odh-openshell-supervisor:v0.1.10-rhaiv.0" pipIndexUrl: "https://packages.redhat.com/api/pypi/public-rhai/rhoai/3.6-EA1/cpu-ubi9-test/simple/" # Pinned cosign used only to verify the installer bundle. The OpenShell diff --git a/images/saw-openclaw/Containerfile b/images/saw-openclaw/Containerfile new file mode 100644 index 000000000..5d3df5321 --- /dev/null +++ b/images/saw-openclaw/Containerfile @@ -0,0 +1,15 @@ +# The stock OpenClaw image with /sandbox searchable by any UID. +# +# Its /sandbox is 0770 and owned by 1000:0, but OpenShift runs each workspace +# as its namespace's UID, which then cannot reach the volumes SAW mounts under +# /sandbox. This adds only the search bit (o+x); nothing else changes. The same +# steps as make container-notebook-image, built in CI instead of in-cluster. +# +# SOURCE_IMAGE: the digest-pinned stock image (the notebook BOM's image). +# IMAGE_USER: the stock image's own USER, restored after the change. +ARG SOURCE_IMAGE +FROM ${SOURCE_IMAGE} +ARG IMAGE_USER +USER 0 +RUN test -d /sandbox && chmod o+x /sandbox +USER ${IMAGE_USER} diff --git a/openshell-sandbox-carry/Dockerfile b/openshell-sandbox-carry/Dockerfile new file mode 100644 index 000000000..2882b7e80 --- /dev/null +++ b/openshell-sandbox-carry/Dockerfile @@ -0,0 +1,55 @@ +# TEMPORARY CARRY: odh-openshell-sandbox v0.1.10-rhaiv.0 with one fix. +# +# On RHEL 9 kernels (5.14) the v0.1.10 sandbox's network broker panics on every +# connect: openshell-binary-identity calls rustix clock_ticks_per_second(), +# which reads the aux vector with prctl(PR_GET_AUXV) (Linux 6.4+) or +# /proc/self/auxv, and a nondumpable non-root process cannot read the latter. +# auxv-warmup.patch caches the aux vector at the top of main(), before the +# sandbox makes itself nondumpable. Everything else is the official image: the +# binary is rebuilt from the same downstream commit the way Konflux builds it +# (static, NSS pinned) and replaces /openshell-sandbox in that image. +# +# Drop this carry once a fixed odh-openshell-sandbox build is released. + +ARG BASE_IMAGE=quay.io/opendatahub/odh-openshell-sandbox@sha256:365d321345ea142a10d442f91bebeaf6d67dac4384b6dc29b4e72ada01a9b959 + +FROM registry.access.redhat.com/ubi9/ubi:9.8@sha256:25a147defd01e19674714f55d17538c8dbe55d8c305fa157ecc3f9c8977b05b6 AS builder +ARG OPENSHELL_URI=https://github.com/opendatahub-io/openshell.git +ARG OPENSHELL_COMMIT=c2775b8df05619cdd57cb354ea8cd829ec79ee40 +ARG OPENSHELL_VERSION=0.1.10-rhaiv.0 +ARG RUST_VERSION=1.95.0 +RUN dnf install -y --nodocs --setopt=install_weak_deps=0 \ + gcc gcc-c++ make cmake glibc-static openssl-devel git-core xz binutils \ + && dnf clean all +RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \ + | sh -s -- -y --profile minimal --default-toolchain "${RUST_VERSION}" +ENV PATH=/root/.cargo/bin:${PATH} CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse +WORKDIR /build +RUN git init -q . \ + && git remote add origin "${OPENSHELL_URI}" \ + && git fetch -q --depth 1 origin "${OPENSHELL_COMMIT}" \ + && git checkout -q --detach FETCH_HEAD +COPY auxv-warmup.patch /tmp/auxv-warmup.patch +# Fails if the downstream source no longer matches the reviewed patch. Then +# remove .git so the version comes from OPENSHELL_VERSION, as in Konflux. +RUN git apply --check /tmp/auxv-warmup.patch \ + && git apply /tmp/auxv-warmup.patch \ + && rm -rf .git +RUN set -eu; \ + RUST_TARGET="$(uname -m)-unknown-linux-gnu"; \ + export OPENSHELL_GIT_VERSION="${OPENSHELL_VERSION#v}"; \ + gcc -O2 -fPIE -Wall -Wextra -c deploy/konflux/sandbox/pin-nss.c -o /build/pin-nss.o; \ + RUSTFLAGS="-C target-feature=+crt-static -C link-arg=/build/pin-nss.o -C link-arg=-Wl,--undefined=__nss_configure_lookup" \ + cargo build --locked --release --target "${RUST_TARGET}" \ + --package openshell-sandbox --bin openshell-sandbox; \ + install -D -m 0555 "target/${RUST_TARGET}/release/openshell-sandbox" /out/openshell-sandbox; \ + if readelf -l /out/openshell-sandbox | grep -q 'Requesting program interpreter'; then \ + echo "openshell-sandbox is not statically linked" >&2; exit 1; fi; \ + grep -qa 'failed to pin NSS database' /out/openshell-sandbox \ + || { echo "openshell-sandbox is missing the NSS pin" >&2; exit 1; } + +FROM ${BASE_IMAGE} +COPY --from=builder --chmod=0555 /out/openshell-sandbox /openshell-sandbox +LABEL io.openshell.saw.carry="auxv-warmup" \ + io.openshell.saw.carry.base="odh-openshell-sandbox v0.1.10-rhaiv.0" \ + io.openshell.saw.carry.source="opendatahub-io/openshell c2775b8df05619cdd57cb354ea8cd829ec79ee40" diff --git a/openshell-sandbox-carry/auxv-warmup.patch b/openshell-sandbox-carry/auxv-warmup.patch new file mode 100644 index 000000000..edee256b3 --- /dev/null +++ b/openshell-sandbox-carry/auxv-warmup.patch @@ -0,0 +1,31 @@ +diff --git a/crates/openshell-sandbox/Cargo.toml b/crates/openshell-sandbox/Cargo.toml +index 0ccc79af8..7e25438da 100644 +--- a/crates/openshell-sandbox/Cargo.toml ++++ b/crates/openshell-sandbox/Cargo.toml +@@ -67,7 +67,7 @@ tracing-subscriber = { workspace = true } + + [target.'cfg(unix)'.dependencies] + libc = "0.2" +-rustix = { workspace = true, features = ["termios", "fs", "process", "net", "event"] } ++rustix = { workspace = true, features = ["termios", "fs", "process", "net", "event", "param"] } + russh-sftp = "3.0" + uuid = { workspace = true } + +diff --git a/crates/openshell-sandbox/src/main.rs b/crates/openshell-sandbox/src/main.rs +index 8978659ba..0d71edbdd 100644 +--- a/crates/openshell-sandbox/src/main.rs ++++ b/crates/openshell-sandbox/src/main.rs +@@ -1813,6 +1813,13 @@ fn run_boundary(_bootstrap: &Path, _log_level: &str) -> Result<()> { + } + + fn main() -> Result<()> { ++ // SAW carry: cache rustix's aux vector before anything makes this process ++ // nondumpable. rustix reads it with prctl(PR_GET_AUXV) (Linux 6.4+) or ++ // /proc/self/auxv, which a nondumpable non-root process cannot read, so on ++ // RHEL 9 (5.14) the network broker's first clock_ticks_per_second() call ++ // (openshell-binary-identity) panicked on every connect. ++ #[cfg(target_os = "linux")] ++ let _ = rustix::param::clock_ticks_per_second(); + let raw_args = std::env::args().collect::>(); + if raw_args.get(1).map(String::as_str) == Some(COPY_SELF_SUBCOMMAND) { + let dest = raw_args.get(2).ok_or_else(|| { From 848ca3a7a2caccdfbf976718c6f3e12d2b2123bd Mon Sep 17 00:00:00 2001 From: sauagarwa Date: Wed, 25 Nov 2026 07:43:42 +0000 Subject: [PATCH 5/9] Docs: install guide, container, Kata and audit README rewritten as an install guide (VM, container and Kata users, make e2e-workspace); container installation, Kata (pattern-managed runtime, two VMs per sandbox), audit events and receipts, deployment and governance docs updated for OpenShell v0.1.10. Assisted-By: Claude --- README.md | 1491 ++++++++++---------------------- docs/architecture-alignment.md | 2 +- docs/arm64.md | 2 +- docs/container-images.md | 19 +- docs/container-installation.md | 331 ++++--- docs/container-workspaces.md | 39 +- docs/custom-inference.md | 8 + docs/deployment-guide.md | 159 ++++ docs/governance-interceptor.md | 8 +- docs/harness-bundles.md | 27 + docs/kata-workspaces.md | 84 +- docs/openshell-016-release.md | 5 +- docs/personal-assistant.md | 8 +- 13 files changed, 966 insertions(+), 1217 deletions(-) diff --git a/README.md b/README.md index 55f77877b..2e84598e9 100644 --- a/README.md +++ b/README.md @@ -1,602 +1,363 @@ # Secure Agent Workspace -Deploy isolated, per-user AI agent sandboxes on OpenShift with OIDC authentication and policy-controlled access. VM is the default backend; container workspaces use the stock OpenShell Kubernetes driver. - -For container mode, see [architecture and data flows](docs/container-workspaces.md) -and [installation, inputs and enablement](docs/container-installation.md). -The VM procedures below remain the default. Container Make installations use -the shared GitOps services described in their installation guide. - -**Existing SAW deployments using OpenShell older than 0.1.6 must deploy SAW -fresh.** In-place upgrades from those versions are not supported. Back up the -workspace files you need before retiring the old deployment. See the -[OpenShell 0.1.6 release record](docs/openshell-016-release.md) for deployment -guidance and validation results. - -## Upgrade: stage network isolation per user - -This release adds default-deny NetworkPolicy to each SAW. The `openshell-saw` -chart enables it by default and requires the target cluster's pod and Service -CIDRs plus the Kubernetes API Service IP and exact EndpointSlice backend IPs -and ports. A direct Helm render fails until these values are supplied. -`make saw-create` discovers them before changing the cluster. - -The GitOps `saw-users` chart stages NetworkPolicy **off** for existing and new -users. Before enabling one user, audit its in-cluster inference, MCP, and -package-mirror destinations; add narrow `networkPolicy.extraEgress` rules; run -`make prereqs-check` and paste its live topology snippet under -`defaults.openshellSaw` in `overrides/saw-users.yaml`; then set that user's -`values.networkPolicy.enabled: true` and sync it. Test that user before -continuing to the next. Re-run the check after API endpoint rotation. Argo CD -cannot discover cluster topology while rendering. See the -[rollout procedure](docs/deployment-guide.md#networkpolicy-upgrade-procedure). - -## Table of Contents +Secure Agent Workspace (SAW) gives each user an isolated AI agent workspace on +OpenShift. Every workspace runs NVIDIA OpenShell with an OpenClaw or NemoClaw +agent. Keycloak handles sign-in, only the owner can reach a workspace, and +provider keys stay outside the agent. + +A workspace runs on one of three backends: + +| Backend | Runs as | Use it when | +|---|---|---| +| **VM** (default) | One OpenShift Virtualization VM per user | You want the strongest isolation and the most tested path | +| **Container** | Pods in per-user namespaces, using the OpenShell Kubernetes driver | You don't have virtualization or want faster starts | +| **Kata** | Container workspaces in OpenShift sandboxed containers | You want container workspaces with VM-backed pod isolation | + +This repository implements NVIDIA's +[Secure Agent Workspace reference design](https://docs.nvidia.com/enterprise-reference-architectures/secure-agent-workspace-reference-design/latest/openshift-virtualization-reference-implementation.html) +as a Red Hat Validated Pattern. + +**Video walkthrough: from cluster installation to a working workspace** + +https://github.com/user-attachments/assets/6858c0b1-239a-4a6a-b0e4-5872796dcc32 + +## Contents - [Secure Agent Workspace](#secure-agent-workspace) - - [Upgrade: stage network isolation per user](#upgrade-stage-network-isolation-per-user) - - [Table of Contents](#table-of-contents) - - [Overview](#overview) - - [Detailed description](#detailed-description) - - [Architecture diagrams](#architecture-diagrams) - - [Reference Architecture](#reference-architecture) - - [GitOps Policy Model](#gitops-policy-model) - - [Storage Layout](#storage-layout) - - [Implementation Overview](#implementation-overview) + - [Contents](#contents) + - [How it works](#how-it-works) - [Requirements](#requirements) - - [Minimum hardware requirements](#minimum-hardware-requirements) - - [Minimum software requirements](#minimum-software-requirements) - - [Required user permissions](#required-user-permissions) - - [Deploy](#deploy) - - [Prerequisites](#prerequisites) - - [Installation](#installation) - - [Option A: Validated Pattern (automated, GitOps)](#option-a-validated-pattern-automated-gitops) - - [Option B: Quickstart (manual, step-by-step)](#option-b-quickstart-manual-step-by-step) - - [Supported inference providers](#supported-inference-providers) - - [Custom inference provider](#custom-inference-provider) - - [Governance with APF (optional)](#governance-with-apf-optional) - - [Validating the deployment](#validating-the-deployment) - - [Delete](#delete) + - [Installation](#installation) + - [1. Fork and clone](#1-fork-and-clone) + - [2. Log in to the cluster](#2-log-in-to-the-cluster) + - [3. Prepare the cluster](#3-prepare-the-cluster) + - [4. Add your keys](#4-add-your-keys) + - [5. Deploy](#5-deploy) + - [Add a user](#add-a-user) + - [VM workspace](#vm-workspace) + - [Container workspace](#container-workspace) + - [Kata workspace](#kata-workspace) + - [Remove a user or start over](#remove-a-user-or-start-over) + - [Use your workspace](#use-your-workspace) + - [Inference providers](#inference-providers) + - [Supported inference providers](#supported-inference-providers) + - [Custom inference provider](#custom-inference-provider) + - [Governance with APF (optional)](#governance-with-apf-optional) + - [Quickstart without GitOps](#quickstart-without-gitops) + - [Uninstall](#uninstall) + - [Testing](#testing) + - [Security model](#security-model) + - [Keycloak production and demo users](#keycloak-production-and-demo-users) + - [Web UI sign-in (redirect URIs)](#web-ui-sign-in-redirect-uris) - [Repository structure](#repository-structure) - [References](#references) - - [Technical details](#technical-details) - - [Security model](#security-model) - - [Keycloak production and demo users](#keycloak-production-and-demo-users) - - [Web UI sign-in (redirect URIs)](#web-ui-sign-in-redirect-uris) - - [Namespace modes](#namespace-modes) - - [OIDC issuer resolution](#oidc-issuer-resolution) - [Tags](#tags) -## Overview +## How it works -Secure Agent Workspace provisions dedicated KubeVirt virtual machines for each user, running NVIDIA OpenShell with NemoClaw/OpenClaw AI agents. Each sandbox is isolated at the VM level, authenticated via OIDC, and connected to the user's chosen inference provider. The platform supports both a GitOps-driven Validated Pattern deployment and a manual quickstart flow. +![Reference architecture with an endpoint, Phase I and Phase II workspace VMs, APF governance, and corporate services](docs/images/openshift-reference-shape.png) -## Detailed description +Argo CD deploys the platform from your fork: operators, Vault, External +Secrets, Keycloak, the governance service and the self-service portal. Each +entry in `overrides/saw-users.yaml` becomes a workspace. Users can also create +their own in Red Hat Developer Hub. -Organizations adopting AI coding and knowledge agents need strong isolation guarantees: each user's agent must run in its own boundary, with auditable access to enterprise systems, controlled network egress, and centralized identity management. Traditional container-based isolation is insufficient when agents can execute arbitrary code and tool calls. +| Component | Technology | Purpose | +|---|---|---| +| Isolation | OpenShift Virtualization, or pods (optionally Kata) | One boundary per user | +| Identity | Red Hat Build of Keycloak | OIDC sign-in for the CLI and web UIs | +| Agent runtime | NVIDIA OpenShell + OpenClaw / NemoClaw | Sandboxes, gateway, inference routing | +| Secrets | Vault + External Secrets | Provider keys stay outside the sandbox | +| Governance | OpenShell governance interceptor, or APF | Fail-closed approval of gateway operations | +| GitOps | Argo CD (Validated Patterns) | Everything, including users, comes from Git | -This quickstart implements NVIDIA's [Secure Agent Workspace reference architecture](https://docs.nvidia.com/enterprise-reference-architectures/secure-agent-workspace-reference-design/latest/openshift-virtualization-reference-implementation.html) on Red Hat OpenShift. Each user gets a dedicated Fedora 44 VM running the OpenShell gateway and an AI agent (OpenClaw, Hermes, or Deep Agents Code). The VM provides process-level and network-level isolation. OIDC authentication (via Red Hat Build of Keycloak) ensures only the sandbox owner can access their workspace. Provider keys flow through Vault and External Secrets into a per-namespace credential proxy (the reference design's external credential placement); the VM receives nonsecret markers and metadata by default. Optional direct mode (`credentialProxy.enabled: false`) mounts full Secrets in the VM. See [Credential isolation](docs/credential-isolation.md). +| Namespace | Contents | +|---|---| +| `saw-` | The user's workspace: the gateway VM, or the container sandbox and gateway | +| `saw-ctl-`, `saw-ui-` | Container workspaces only: controller and browser relay | +| `saw-history-` | Container workspaces with audit receipts only: signed audit history, kept after deletion | +| `openshell-agents` | Golden VM image, image builds, governance service | +| `saw-keycloak` | Keycloak | +| `vp-gitops` | Argo CD applications, one set per user | + +More detail: [deployment guide](docs/deployment-guide.md), +[container architecture](docs/container-workspaces.md), +[GitOps policy model](docs/images/gitops-policy-model.png), +[storage layout](docs/images/nfs-storage-layout.png). -The system supports multiple inference providers (Gemini, Anthropic, OpenAI, NVIDIA Build, OpenRouter, Ollama, or custom endpoints) and optional web search integration (Tavily, Brave). A bootc-based golden image pipeline pre-bakes all packages into a container image that CDI imports directly, enabling fast VM provisioning without cloud-init package installation. +## Requirements -For a self-hosted OpenAI-compatible endpoint (vLLM, Ollama, ...), see [Custom inference provider](#custom-inference-provider). +| Resource | Per VM workspace | Platform | +|---|---|---| +| CPU | 4 cores | 8 cores | +| Memory | 8 GiB | 16 GiB | +| Storage | 40 GiB | 50 GiB | -### Architecture diagrams +- OpenShift 4.22+ on x86_64 or arm64 ([arm64 notes](docs/arm64.md)), with + OVN-Kubernetes. +- Cluster-admin for the install. End users only need their Keycloak account + and the `openshell` CLI. +- On your machine: `oc`, `helm` 3.x, `jq`, `curl`, `openssl`, `uv`, Podman, + and the [`openshell` CLI](https://github.com/NVIDIA/OpenShell/releases) + 0.1.x. +- A key for at least one inference provider, or your own OpenAI-compatible + endpoint. +- Kata workspaces also need OpenShift sandboxed containers + ([Kata guide](docs/kata-workspaces.md)). -The first diagram shows an OpenShift Virtualization and APF governance reference -architecture. It shows conceptual Phase I and Phase II workspaces. APF is an -optional governance engine in this repository; the OpenShell governance -interceptor is the default. The two diagrams that follow also illustrate the -[NVIDIA Secure Agent Workspace OpenShift Virtualization reference design](https://docs.nvidia.com/enterprise-reference-architectures/secure-agent-workspace-reference-design/latest/openshift-virtualization-reference-implementation.html). +## Installation -#### OpenShift Virtualization and APF reference architecture +Run `./pattern.sh` from a host that can run the Validated Patterns utility +image natively (for example, an x86_64 Linux machine with Podman). -![Reference architecture with an endpoint, Phase I and Phase II workspace VMs, APF governance, and corporate services](docs/images/openshift-reference-shape.png) +### 1. Fork and clone -#### Reference design: GitOps policy model +Argo CD deploys from your fork, because users and settings are files in it. +[Fork the repository](https://github.com/validatedpatterns-sandbox/secure-agent-workspace/fork), +then: -![GitOps Policy Model — End-to-End Policy Flow](docs/images/gitops-policy-model.png) +```bash +git clone https://github.com//secure-agent-workspace.git +cd secure-agent-workspace +``` -#### Reference design: storage layout +### 2. Log in to the cluster -![NFS storage layout for policy bundles and workspace persistence](docs/images/nfs-storage-layout.png) +```bash +oc login --server=https://api.:6443 -u +``` -#### Implementation Overview +### 3. Prepare the cluster +```bash +make saw-init ``` - OpenShift Cluster -┌──────────────────────────────────────────────────────────┐ -│ │ -│ Operators (deployed by Validated Pattern or manually): │ -│ ┌──────────────────┐ ┌──────────────────┐ │ -│ │ OpenShift │ │ Red Hat Build │ │ -│ │ Virtualization │ │ of Keycloak │ │ -│ └──────────────────┘ └──────────────────┘ │ -│ │ -│ Infrastructure (ArgoCD-managed): │ -│ ┌──────────┐ ┌──────────┐ ┌──────────────────────────┐ │ -│ │ Vault │ │ ESO │ │ Keycloak (OIDC provider) │ │ -│ └──────────┘ └──────────┘ └──────────────────────────┘ │ -│ │ │ │ -│ │ secrets sync │ JWKS validation │ -│ ▼ ▼ │ -│ ┌──────────────────────────────────────────┐ │ -│ │ Golden Image (bootc) │ │ -│ │ Fedora 44 + OpenShell + podman + nodejs │ │ -│ │ Built via BuildConfig → image registry │ │ -│ └─────────────────┬────────────────────────┘ │ -│ │ CDI import per user │ -│ ┌────────────┼────────────┐ │ -│ ▼ ▼ ▼ │ -│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ -│ │ alice │ │ bob │ │ carol │ Per-user VMs │ -│ │ sandbox │ │ sandbox │ │ sandbox │ with gateway + │ -│ │ VM │ │ VM │ │ VM │ agent + routes │ -│ └─────────┘ └─────────┘ └─────────┘ │ -│ │ │ │ │ -│ └────────────┼────────────┘ │ -│ │ │ -│ Routes: TLS passthrough (gRPC) + edge (dashboard) │ -└──────────────────────────────────────────────────────────┘ - │ - ▼ - User (openshell CLI / browser) + +This creates your SSH keys and `~/values-secret.yaml`, mirrors the VM image, +and checks storage, the OIDC certificate and the container prerequisites. It +is safe to run again. + +### 4. Add your keys + +Put each key in a file, one line with no trailing newline: + +- `~/.nvidia-api-key`: used by the default profile. +- `~/.brave-api-key`: optional, for web search. + +`~/values-secret.yaml` already points at these files. + +### 5. Deploy + +```bash +./pattern.sh make install ``` -| Component | Technology | Purpose | -|---|---|---| -| VM isolation | OpenShift Virtualization (KubeVirt) | One VM per user with process and network isolation | -| Identity | Red Hat Build of Keycloak (RHBK) | OIDC authentication, user management, SSO | -| Agent runtime | NVIDIA OpenShell + OpenClaw/NemoClaw | AI coding and knowledge agents inside sandbox | -| Gateway | OpenShell Gateway (gRPC over TLS) | Sandbox lifecycle, SSH proxy, inference routing | -| Golden image | Bootc (Fedora 44) + CDI | Pre-baked VM image for fast provisioning | -| Secrets | Vault + External Secrets Operator + credential proxy | Provider API keys stay outside the VM; SSH public keys grant guest access | -| GitOps | ArgoCD (Validated Patterns) | Declarative cluster configuration | -| Access control | Dashboard token + OIDC gateway validation | Per-user access via application-level tokens | +Without a Brave key, add `WEB_SEARCH_ENABLED=false`. Argo CD follows the branch +you install from, so keep it pushed. To use a branch other than the one checked +out, set `TARGET_BRANCH` and `TARGET_ORIGIN`. -## Requirements +No SAW user workspace exists yet. Next, [add a user](#add-a-user). -### Minimum hardware requirements +## Add a user -| Resource | Per sandbox VM | Cluster overhead | -|---|---|---| -| CPU | 4 cores | 8 cores (operators, Keycloak, Vault) | -| Memory | 8 GiB | 16 GiB | -| Storage | 40 GiB (VM disk) | 50 GiB (golden image, registry) | +Add the user to `overrides/saw-users.yaml`, then commit and push. Names are +lowercase and at most 19 characters. Each user gets a Keycloak account and a +workspace in namespace `saw-`. -### Minimum software requirements +### VM workspace -| Software | Version | -|---|---| -| Red Hat OpenShift | 4.22+ | -| Cluster architecture | x86_64 or arm64 ([arm64 notes](docs/arm64.md)) | -| Network plugin | OVN-Kubernetes (the OpenShift default), for each workspace's egress firewall; set `egress.enabled: false` otherwise | -| OpenShift Virtualization operator | stable channel | -| Red Hat Build of Keycloak operator | stable-v26 channel | -| Helm CLI | 3.x | -| oc CLI | matching cluster version | -| openshell CLI | [a release from the gateway's release series](https://github.com/NVIDIA/OpenShell/releases) (0.1.x for this BOM) | -| jq, curl, openssl | required by `make login` | -| uv | required for local deployment commands and Python tests; uses the root `pyproject.toml` and `uv.lock` | +1. Add the entry: -### Required user permissions + ```yaml + users: + - name: alice + ``` -**Cluster admin** is required for the initial deployment (operator installation, namespace creation). After setup, end users interact only via the `openshell` CLI and their OIDC credentials — no OpenShift access needed. +2. Create the Keycloak account and push: -## Deploy + ```bash + make keycloak-add-users + git add overrides/saw-users.yaml + git commit -m "Add alice" + git push + ``` -### Prerequisites +3. Wait until the workspace is Synced and Healthy, then until the installer + inside the VM is done: -1. An OpenShift 4.22+ cluster with the required operators installed (see Requirements) -2. `oc` CLI logged in with cluster-admin -3. `helm` 3.x installed -4. An API key for at least one inference provider (Gemini, Anthropic, OpenAI, NVIDIA, OpenRouter) -5. The `openshell` CLI installed at the API version pinned by the gateway BOM - (`0.1.6` for the current `0.1.6-rhaiv.4` image; - [releases](https://github.com/NVIDIA/OpenShell/releases)) + ```bash + oc -n vp-gitops get application saw-alice + make saw-logs OPENSHELL_SAW_NAME=alice # wait for apply: Done + ``` -Verify prerequisites: +### Container workspace -```bash -make prereqs-check -``` +**Audit:** the gateway and each sandbox send OCSF security events (sign-ins, +refused API calls, network decisions) to an OpenTelemetry collector the pattern +installs in `openshell-agents`. Its log shows them +(`oc -n openshell-agents logs deploy/saw-ocsf-collector`); point it at your +SIEM in `charts/saw-telemetry/values.yaml`. The agent's tool gate also keeps a +log of tool calls in the workspace. For signed, fail-closed receipts with +history kept outside the workspace, see +[Audit receipts](docs/container-installation.md#audit-receipts) (advanced). -### Installation +1. Create the Keycloak account and get its subject: -Two deployment paths are available: + ```bash + make keycloak-add-users + make keycloak-user-info KC_USER=alice + ``` -**Video walkthrough: from cluster installation to a working workspace** +2. Add the user's inference key to `~/values-secret.yaml`, and load it: -Follow the Validated Pattern installation, inspect the applications deployed by -Argo CD, and create a Keycloak user. The walkthrough then provisions a workspace -through Red Hat Developer Hub, compares the GitOps and manual quickstart paths, -and configures a custom inference endpoint. Follow the steps below for the -current commands, or see the [Developer Hub user guide](docs/rhdh-user-guide.md) -for the portal flow and [Custom inference provider](#custom-inference-provider) -for endpoint configuration. + ```yaml + - name: inference + vaultPrefixes: + - hub/saw-alice + fields: + - name: api_key + path: ~/.alice-inference-key + ``` -https://github.com/user-attachments/assets/6858c0b1-239a-4a6a-b0e4-5872796dcc32 + ```bash + ./pattern.sh make load-secrets + ``` -#### Option A: Validated Pattern (automated, GitOps) +3. Add the entry: -Run `./pattern.sh` from a host that can execute the Validated Patterns utility -image natively. For a `linux/amd64` utility image, use an x86_64 Linux bastion -with Podman and the target cluster's kubeconfig. An Apple Silicon host can -manage the cluster with `oc` while the install command runs on that bastion. + ```yaml + users: + - name: alice + ownerSubject: + profiles: [custom-inference] + vaultPrefix: secret/data/hub + customInferenceURL: https:///v1 + modelInputs: + inference.model: + values: + deployment: {mode: container} + ``` -Deploys the platform — operators, Vault, ESO, Keycloak, and secrets — via Argo CD. No workspace VM is created until you add a user in step 7 or request a workspace through the portal. +4. Push and check: -On a fresh cluster, the Make target installs the Red Hat OpenShift GitOps -Operator through OLM and waits for its deployment before creating the Pattern. -It uses the channel and catalog from the framework's rendered configuration. -This prevents a temporary default Argo CD instance from receiving a second -root Application. Existing GitOps installations keep their operator configuration. -The framework's normal sync and health checks run at the end. -[OpenShift GitOps default-instance configuration](https://docs.redhat.com/en/documentation/red_hat_openshift_gitops/1.21/html/argo_cd_instance/setting-up-argocd-instance). + ```bash + git add overrides/ + git commit -m "Add alice (container)" + git push + oc -n vp-gitops get applications.argoproj.io | grep -E 'saw-alice|saw-c-' + ``` -```bash -# 1. Fork, then clone your fork. Argo CD deploys from the branch you push -# (users, profiles, endpoints are files in this repository), so GitOps -# changes need a remote you can write to: -# https://github.com/validatedpatterns-sandbox/secure-agent-workspace/fork -# (Cloning upstream directly also installs; then add users outside git, -# see step 7.) -git clone https://github.com//secure-agent-workspace.git -cd secure-agent-workspace -git remote add upstream https://github.com/validatedpatterns-sandbox/secure-agent-workspace.git - -# 2. Log in to OpenShift with cluster-admin -oc login --server=https://api.:6443 -u - -# 3. Generate SSH keys (used for on-demand SSH into the gateway VM) -make ssh-key-generate - -# 4. Configure secrets -# make ssh-key-generate (step 3) already created ~/values-secret.yaml from the -# template; edit it to add your inference and web-search keys. The Validated -# Patterns framework reads ~/values-secret-secure-agent-workspace.yaml before ~/values-secret.yaml, -# so the pattern-named file wins when both exist. -# The default profile needs an NVIDIA key; the Brave Search key is optional -# when web search is off (omit its whole entry from the secrets file): -# ~/.nvidia-api-key and ~/.brave-api-key (one line each, chmod 600) - -# 5. Copy pre-built images to the cluster (~5 min) -# Mirrors images from ghcr.io/validatedpatterns-sandbox to the internal registry. -# No build needed — images are pre-built by maintainers. -make images-mirror - -# 5b. Optional: check whether workspace VMs will trust Keycloak's -# certificate. On a cluster with OpenShift's self-signed *.apps certificate the -# pattern trusts the cluster's ingress CA by itself (saw-ingress-ca imperative -# job); for an external issuer with a private CA (ISSUER=) it prints the -# oidc.caBundle snippet to add to overrides/saw-users.yaml. -make check-oidc-ca - -# 5c. Proxy mode defaults to the published, digest-pinned multi-arch GHCR image. -# Only for a mirror or custom build, override in overrides/saw-users.yaml: -# defaults: -# openshellSaw: -# credentialProxy: -# image: /saw-credential-proxy@sha256: -# To disable globally: defaults.openshellSaw.credentialProxy.enabled: false -# To disable for one user: users[].values.credentialProxy.enabled: false -# Direct mode needs no proxy image and exposes keys to VM root; see -# docs/credential-isolation.md for migrations and required key rotation. -# See docs/container-images.md for published images, releases and mirroring. - -# 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. -# pattern.sh forwards TARGET_BRANCH and TARGET_ORIGIN (not TARGET_REVISION). -# export TARGET_BRANCH=main TARGET_ORIGIN=origin -./pattern.sh make install -# Without a Brave Search key, use this instead: -# ./pattern.sh make install WEB_SEARCH_ENABLED=false -# 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: -# - 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" -# 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). - -# 8. Authenticate and configure the CLI -make login # Opens the browser for Keycloak sign-in -export OPENSHELL_SAW_NAME=alice # VM alice in namespace saw-alice -make saw-configure -openshell gateway login $OPENSHELL_SAW_NAME # Authenticate CLI with gateway - -# 9. Verify -# The first command lists the default workspace; the second lists cuda-dev. -openshell sandbox list -openshell sandbox list --workspace cuda-dev -``` +New container workspaces wait for an operator review before they start. On a +demo or development cluster, skip the review by listing +`/overrides/saw-container-demo.yaml` after `/overrides/saw-container-defaults.yaml`. +Never do this in production. For the review flow and all entry fields, see +[Installing container workspaces](docs/container-installation.md#minimal-static-entries). -`make logout` clears the local OIDC token and stored credentials for all -registered OpenShell gateways. Set `OPENSHELL_SAW_NAME` to clear one gateway. -Local cleanup still runs if the issuer cannot confirm token revocation; -the command then reports a failure. +### Kata workspace -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. -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. -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). +Kata workspaces are container workspaces that run in OpenShift sandboxed +containers: the agent and its supervisor each get their own Kata VM. -#### Option B: Quickstart (manual, step-by-step) +1. Turn on the Kata runtime for the cluster's workers. The pattern already + installs the OpenShift sandboxed containers operator; enabling the + `saw-kata` application reboots the workers once. See + [Prepare OpenShift sandboxed containers](docs/kata-workspaces.md#prepare-openshift-sandboxed-containers). + It also creates the `saw-kata` RuntimeClass the workspaces run in; on + demo clusters (`autoApprove`) users are bound to it automatically. +2. Follow the [container workspace](#container-workspace) steps, with + `mode: kata`: -Install operators from OperatorHub first, then deploy components manually. After the OpenShift Virtualization operator is installed, create a `HyperConverged` resource, or no node can run VMs; External Secrets is only needed for Option A. See [Quickstart notes](docs/deployment-guide.md#quickstart-notes). The images-mirror step mirrors CI-built GHCR images using the exact `IMAGE_TAG` (`latest` by default); see [Golden image tag](docs/deployment-guide.md#golden-image-tag). RHBK must be installed in the `saw-keycloak` namespace (step 3 sets `KEYCLOAK_NS`; point it at another namespace to reuse a Keycloak your cluster already has). Each sandbox gets its own namespace, `saw-`. + ```yaml + values: + deployment: {mode: kata} + ``` -```bash -# 1. Clone the repository -git clone https://github.com/validatedpatterns-sandbox/secure-agent-workspace.git -cd secure-agent-workspace +### Remove a user or start over -# 2. Log in to OpenShift with cluster-admin -oc login --server=https://api.:6443 -u -# Lab clusters with a self-signed API certificate: add --insecure-skip-tls-verify (disposable clusters only) - -# 3. Set the variables the following targets read (set them again in every new terminal) -export KEYCLOAK_NS=saw-keycloak # or the namespace of a Keycloak your cluster already runs -export OPENSHELL_SAW_NAME=alice # the user VM, deployed into namespace saw-alice - -# 4. Verify prerequisites after CNV and RHBK are installed -make quickstart-prereqs-check -# This check does not change the cluster. It can save ingress-ca.pem here. -# make images-mirror enables the registry route. - -# 5. Generate SSH keys -make ssh-key-generate - -# 6. Copy pre-built images to the cluster -make images-mirror - -# 7. Deploy Keycloak (if one is already running in KEYCLOAK_NS, it is used; -# you are asked before the OpenShell realm is imported into it; -# set USE_EXISTING_KEYCLOAK=yes to import the realm without the prompt) -# A fresh deploy waits for both the server and the openshell-keycloak-realm -# import. The OIDC endpoints are needed by the next two commands. -make keycloak-deploy - -# 8. Verify Keycloak (realm, openshell-cli client, roles) -make keycloak-check -make keycloak-issuer - -# 9. Deploy governance policy and interceptor -make governance-deploy - -# 10. Authenticate -make login # Opens the browser for Keycloak sign-in -make whoami # Verify identity - -# 11. Create the user VM (deploys into namespace saw-$OPENSHELL_SAW_NAME) -# CREDENTIAL_PROXY_IMAGE is optional: a digest-pinned mirror/custom override. -# Keys come from files so they stay out of the shell history. -# WEB_SEARCH_API_KEY is optional. Without it (and without an existing -# web-search Secret), saw-create disables the Brave Search provider. -# The target asks "Press Enter to set owner to '', ..."; press Enter. -# For another local Keycloak user, first run make keycloak-add-user KC_USER=, -# then pass OWNER=; the target resolves and verifies their user ID. -# For another owner with an external issuer, also pass a verified -# OWNER_SUBJECT=. -# Optional, to enable web search: -# read -r WEB_SEARCH_API_KEY < "$HOME/.brave-api-key" -# export WEB_SEARCH_API_KEY -read -r API_KEY < "$HOME/.nvidia-api-key" -export API_KEY -make saw-create \ - PROVIDER=build \ - MODEL=nvidia/nemotron-3.5-lightning-30b-a3b -unset API_KEY WEB_SEARCH_API_KEY -``` +- **Remove:** delete the entry and push. Container and Kata workspaces are + removed with it (with audit receipts, their history namespace is kept). A VM entry only + removes its Argo CD applications and leaves the VM running. To delete the VM + too, first set `pruneOnRemove: true` on the entry and push, then remove the + entry. +- **Start over (container and Kata):** remove the entry and push. Wait until + Argo CD has deleted `saw-`, then add the entry back with a higher + `generation:` (for example `generation: 2`) and push. +- **Self-service:** users can create and delete their own workspaces in Red Hat + Developer Hub. See the [Developer Hub user guide](docs/rhdh-user-guide.md) + and [self-service portal](docs/self-service-portal.md). -> **OIDC issuer:** `make saw-create` stops before changing the cluster if it cannot find Keycloak in `KEYCLOAK_NS`. Set `OIDC_ISSUER` to use a different issuer. Set `OIDC_ISSUER=none` only when you intend to deploy without OIDC. This sets chart `oidc.enabled: false`, even when `global.clusterDomain` is set, and disables the dashboard and sandbox UI routes. An external issuer disables these routes by default. Set `DASHBOARD=true` with an external issuer only after you register its redirect URIs yourself. +## Use your workspace -Updating the create script does not fix a gateway deployed earlier without OIDC. Check its effective `oidc.enabled` and `oidc.issuerUrl` Helm values and the rendered gateway configuration. Reapply that workspace with the intended issuer, then verify owner access and rejection without credentials. +Sign in and connect the CLI to your workspace: ```bash -# 12. Follow the in-VM installer (in another terminal) -make saw-logs - -# 13. Check status -make saw-list -make status - -# 14. Wait for the installer to finish -# saw-status adds your public key to the VM's access Secret, -# then reaches the VM over SSH to read the installer status. -make saw-status -# Wait for "install" and "apply" to show "phase": "Done" - -# 15. Configure the openshell CLI: registers the gateway and signs you in -# through the browser (log in with a test account). -make saw-configure -# openshell gateway login $OPENSHELL_SAW_NAME -# Only needed when a device-code sign-in (OPENSHELL_NO_BROWSER=1) did not -# finish, or the token expired. - -# 16. Verify sandboxes -# sandbox list without --workspace only shows workspace "default" +make login # opens the browser for Keycloak sign-in +export OPENSHELL_SAW_NAME=alice +make saw-configure # registers the gateway and signs you in openshell sandbox list openshell sandbox list --workspace cuda-dev - -# 17. Launch TUI (pick one) -# At OpenShell 0.1.x, cuda-sandbox runs plain OpenClaw (NemoClaw onboarding stops in its preflight checks). -SANDBOX_NAME=cuda-sandbox \ -WORKSPACE=cuda-dev \ -make nemoclaw-tui # NemoClaw -SANDBOX_NAME=notebook \ -make openclaw-tui # OpenClaw - -# 18. Launch GUI (pick one): make ...-gui port-forwards to the sandbox UI. -# make sandbox-ui lists owner-restricted routes for enabled profile UIs. -make sandbox-ui -SANDBOX_NAME=cuda-sandbox \ -WORKSPACE=cuda-dev \ -GUI_PORT=18789 \ -make nemoclaw-gui # NemoClaw -SANDBOX_NAME=notebook \ -GUI_PORT=18790 \ -make openclaw-gui # OpenClaw ``` -> **Token expiry:** A fresh OIDC access token can last up to 24 hours. The `openshell-cli` client and realm SSO Session Max are both set to 24 hours; session age can shorten the token, and the refresh token expires after 30 minutes without use. A chart import does not update an existing realm, so run `make keycloak-session-max` after upgrading. If the gateway token expires, run `openshell gateway login $OPENSHELL_SAW_NAME` to sign in again. Use `make saw-configure` if the gateway configuration is missing. +To get the user's password for the sign-in, run +`make keycloak-password KC_USER=alice`. It copies the password without printing +it. -> **Shell in a sandbox:** `openshell sandbox connect` attaches to the sandbox's main process, which in SAW sandboxes is `sleep infinity` with no terminal, so it shows nothing. Open a shell with `openshell sandbox exec -n notebook -- sh` (use `--workspace cuda-dev` for `cuda-sandbox`). See [Shell access](docs/deployment-guide.md#shell-access). +Open an agent: -> **Agent UI:** `make openclaw-gui` and `make nemoclaw-gui` port-forward to the sandbox UI. `make saw-create` now also gives each enabled profile UI its own owner-restricted Route when it uses local Keycloak. The `-dashboard` Route does not reach the sandbox UI on OpenShell 0.1.x. See [OpenClaw UI and the dashboard Route](docs/deployment-guide.md#openclaw-ui-and-the-dashboard-route). Web search and web fetch do not work in the default `notebook` sandbox; see [Web search in the default sandbox](docs/deployment-guide.md#web-search-in-the-default-sandbox). +```bash +make sandbox-ui # browser URLs for profile UIs +SANDBOX_NAME=notebook make openclaw-tui # terminal UI +SANDBOX_NAME=notebook GUI_PORT=18790 make openclaw-gui +SANDBOX_NAME=cuda-sandbox WORKSPACE=cuda-dev make nemoclaw-tui +openshell sandbox exec -n notebook -- sh # a shell in the sandbox +``` -You can set `OPENSHELL_SAW_NAME` once via `export` and all `saw-*` targets will use it automatically. The sandbox namespace defaults to `saw-$OPENSHELL_SAW_NAME`; set `SAW_NS` if it differs (the pattern's default sandbox is `alice` in `saw-alice`). +- **Signed out?** Tokens last up to 24 hours. Run + `openshell gateway login $OPENSHELL_SAW_NAME` again. +- **Sign out:** run `make logout`. +- **GUI tunnel password:** enter `gateway.auth.password` from the sandbox's + `/sandbox/.openclaw/openclaw.json`. +- **Known limits:** web search does not work in the default `notebook` sandbox + ([details](docs/deployment-guide.md#web-search-in-the-default-sandbox)). + `openshell sandbox connect` shows nothing; use `exec` + ([details](docs/deployment-guide.md#shell-access)). -> **Sandbox name limit:** `OPENSHELL_SAW_NAME` must be **19 characters or fewer**. OpenShell rejects longer names with "name exceeds maximum length". The Helm chart and `make saw-create` will both fail fast with a clear error if this limit is exceeded. +**Video walkthrough: sandbox UIs and the OpenShell CLI** -### Make target migration +https://github.com/user-attachments/assets/d1e93830-ce8b-47c0-9b78-761971ee6067 -The old names remain as aliases for one release. Each alias prints its -replacement. Use `make help` to see all commands. +## Inference providers -| Previous target | Current target | -|---|---| -| `check-prereqs` | `prereqs-check` | -| `generate-keys` | `ssh-key-generate` | -| `build-nemoclaw` | `sandbox-build` | -| `build-nemoclaw-cli` | `cli-build` | -| `build-gateway-podman` | `gateway-build-podman` | -| `build-gateway-docker` | `gateway-build-docker` | -| `build-governance-interceptor` | `governance-interceptor-build` | -| `build-governance-interceptor-local` | `governance-interceptor-build-local` | -| `copy-images` | `images-mirror` | -| `keycloak` | `keycloak-deploy` | -| `delete-keycloak` | `keycloak-delete` | -| `delete-all` | `quickstart-delete` | -| `openshell-saw-create` | `saw-create` | -| `openshell-saw-configure-gateway` | `saw-configure` | -| `openshell-saw-list` | `saw-list` | -| `openshell-saw-logs` | `saw-logs` | -| `openshell-saw-status` | `saw-status` | -| `openshell-saw-vm-ssh` | `saw-vm-ssh` | -| `openshell-saw-restart` | `saw-restart` | -| `openshell-saw-ssh` | `saw-ssh` | -| `openshell-saw-tui` | `saw-tui` | -| `openshell-saw-gui` | `saw-gui` | -| `openshell-saw-delete` | `saw-delete` | -| `governance-list-profiles` | `governance-profile-list` | -| `governance-add-profile` | `governance-profile-add` | -| `governance-remove-profile` | `governance-profile-remove` | -| `governance-create-profile` | `governance-profile-create` | - -`make gateway-build` selects Podman by default. Set -`CONTAINER_RUNTIME=docker` for Docker. Other values fail before a build starts. -`make pattern-uninstall` calls the standard `uninstall` target. The old -`ssh-secret` target is gone. The chart creates a public key Secret for each -SAW, and `saw-vm-ssh` updates it when needed. - -`saw-create`, `saw-delete`, `saw-status`, `saw-logs`, `saw-configure`, and -user access targets require `OPENSHELL_SAW_NAME`. `saw-list`, `status`, and -`governance-profile-list` work without it. The defaults are `NS=openshell-agents`, -`BUILD_NS=openshell-agents`, `KEYCLOAK_NS=saw-keycloak`, and -`SAW_NS=saw-$OPENSHELL_SAW_NAME`. Manual builds stay in-cluster by default. To push, explicitly set -`IMAGE_REPO` to your own namespace and `IMAGE_TAG` as needed; the upstream -CI namespace is refused. For `saw-create`, set `PROVIDER`, `MODEL`, and -`API_KEY` in the environment for keyed providers; `OWNER` and `OWNER_SUBJECT` select another owner. The chart defaults to the published proxy image. Optionally set `CREDENTIAL_PROXY_IMAGE`, or `credentialProxy.image` through `SAW_VALUES_FILE`, to a digest-pinned mirror or custom build. A new inference Secret needs `PROVIDER` and `MODEL`; `API_KEY` may be empty for a keyless provider. A repeat `saw-create` keeps an existing inference Secret when `API_KEY` is empty. - -`IMAGE_TAG=latest` selects the CI-built gateway disk used by `images-mirror`; -`IMAGE_TAG=sha-` selects a particular CI build. The chart's in-VM BOM -separately pins OpenShell `0.1.6-rhaiv.4` by digest. See -[the deployment guide](docs/deployment-guide.md#golden-image-tag). - -If a prerequisite fails, inspect the reported CLI or operator and run -`make prereqs-check` again. That check does not change the cluster. -`make images-mirror` enables the registry route and stops on access errors. -CI image names, tags, public pull checks, and retained upstream Quay dependencies -are documented in [Container images](docs/container-images.md). -`make ssh-key-generate` and `make keycloak-deploy` keep existing keys and -passwords. If a GUI port is in use, choose another `GUI_PORT`; the command -will not stop the other process. - -The live acceptance test runs only on a dedicated OpenShift test cluster. -After the tested commit is pushed, set `TEST_CLUSTER_CONTEXT`, -`TEST_SAW_NAME`, `TEST_PATTERN_SAW_NAME`, `TEST_OWNER`, `TEST_OWNER_SUBJECT`, -`TEST_SECOND_TOKEN_DIR`, `PROVIDER`, `MODEL`, `API_KEY`, -`TARGET_BRANCH`, `TARGET_ORIGIN`, and the inference -and owner access checks described in the deployment guide. The repo supplies -the second-user denial check by default. `CREDENTIAL_PROXY_IMAGE` is optional, -for a digest-pinned mirror or PR build override. Set `WEB_SEARCH_API_KEY` to test -web search on; leave it unset to test off. Then run -`make test-deployment`. It tests manual setup and -the pattern install, uninstall, and reinstall cycle. It records timestamps, -the commit, the cluster context, and exit codes in a local evidence file. -It requires confirmation for interactive TUI and GUI checks. It runs -inference and access checks and records their status codes. See -[the deployment guide](docs/deployment-guide.md#live-deployment-test). - -The existing Python CLI has a smaller command set than Make. - -#### Supported inference providers +### Supported inference providers | Provider | Key | Example model | |---|---|---| +| NVIDIA Build (default) | `build` | `nvidia/nemotron-3.5-lightning-30b-a3b` | | Google Gemini | `gemini` | `gemini-2.5-flash` | | Anthropic | `anthropic` | `claude-sonnet-4-6` | | OpenAI | `openai` | `gpt-4o` | -| NVIDIA Build | `build` | `meta/llama-3.3-70b-instruct` | | OpenRouter | `openrouter` | `anthropic/claude-sonnet-4-6` | -| Ollama (local) | `ollama` | `llama3` | -| Custom OpenAI-compatible endpoint (vLLM, Ollama, ...) | `custom-inference` + `ENDPOINT_URL` | the model the server serves; see [Custom inference provider](#custom-inference-provider) | +| Ollama | `ollama` | `llama3` | +| Your own OpenAI-compatible endpoint | `custom-inference` | the model it serves | -The `data-science` profile defaults to NVIDIA -`nvidia/nemotron-3.5-lightning-30b-a3b`. OpenAI and Anthropic are optional and -disabled by default. To add either to the existing notebook with Option A: +To add OpenAI or Anthropic to the default `notebook` sandbox: -1. Set its `enabled: true` in +1. Set `enabled: true` for it in `charts/saw-bom/profiles/data-science/default/providers.yaml`. -2. Add its name (`openai` or `anthropic`) to `notebook.providers` in the same - directory's `sandbox.yaml`. Keep `inference.providerRef: nvidia` and its - `inference.model` to retain the NVIDIA startup model. The additional - OpenAI and Anthropic choices are configured in `inference.models`. -3. Add its separate `inference-openai` or `inference-anthropic` entry from - `values-secret.yaml.template`, keeping the existing NVIDIA and web-search - entries. Each uses `api_key`, an optional `provider` check, and an optional - `model` override. The Secret's `model` overrides that provider's model in - the sandbox's `inference.models`; defaults are `gpt-6-luna` for OpenAI and - `claude-sonnet-4-6` for Anthropic. Official APIs need no URL. -4. Run `uv run --locked scripts/saw-profile-catalog.py`, then commit and push - the updated profiles and catalogs. The generated credential bindings attach - each API Secret to its provider's allowed hosts. ESO creates the full Secrets - for the namespace proxy and `inference-openai-meta` / - `inference-anthropic-meta` for the VM, containing only the nonsecret - `provider`, `model` and `url` fields. The sandbox sends a nonsecret marker; - the namespace proxy injects the real key only for the bound HTTPS host on - port 443. - -Select the provider's model in the notebook chat's model picker. These optional -providers apply only to `default/notebook`; `cuda-dev` continues to use NVIDIA. - -#### Custom inference provider - -Use a model server of your own (vLLM, Ollama, or any OpenAI-compatible API) instead of a cloud provider. The key stays in the namespace credential proxy; the VM and sandbox use a nonsecret marker. A keyed endpoint must use HTTPS on port 443 with a publicly trusted certificate. The proxy binds the key to the host of `url` in the `inference` Secret. Add a governance profile under `overrides/governance-profiles/` for the same host, served by the `governance-extra-profiles` application. The `custom-inference` SAW-BOM profile reads the URL and model through the sandbox's typed `inference:` block and onboards OpenClaw against that URL (see [docs/custom-inference.md](docs/custom-inference.md)). - -**Option A (Validated Pattern)** — configure an admin-approved endpoint in your fork, then provide the key through the Secret. Replace `api.inference.example.com` below with the hostname in the `inference.url` value; it must be identical in steps 2 and 3. - -1. **Publish the profile** — `overrides/governance-profiles/kustomization.yaml` already publishes `custom-inference.yaml`. Publishing the profile alone does not grant any workspace egress or access to a credential destination: +2. Add it to `notebook.providers` in `sandbox.yaml` in the same directory. +3. Add its `inference-openai` or `inference-anthropic` entry from + `values-secret.yaml.template` to your secrets file. +4. Run `uv run --locked scripts/saw-profile-catalog.py`, then commit and push. - ```yaml - configMapGenerator: - - name: governance-interceptor-extra-profiles - files: - - custom-inference.yaml - ``` +Pick the model in the notebook chat's model picker. -2. **Approve the credential destination** — in `overrides/governance-profiles/custom-inference.yaml`, set the endpoint the credential proxy may use: +### Custom inference provider + +Use your own model server (vLLM, Ollama, or any OpenAI-compatible API). A keyed +endpoint must use HTTPS on port 443 with a publicly trusted certificate. Use +the same host in every step. + +1. Approve the host in `overrides/governance-profiles/custom-inference.yaml`: ```yaml endpoints: @@ -607,7 +368,7 @@ Use a model server of your own (vLLM, Ollama, or any OpenAI-compatible API) inst access: read-write ``` -3. **Allow VM egress to that same host** — add it under `defaults.openshellSaw` in `overrides/saw-users.yaml`: +2. For VM users, allow egress to the same host in `overrides/saw-users.yaml`: ```yaml defaults: @@ -617,18 +378,12 @@ Use a model server of your own (vLLM, Ollama, or any OpenAI-compatible API) inst - api.inference.example.com ``` - An in-cluster Service needs a narrow `networkPolicy.extraEgress` rule instead. +3. Give the user `profiles: [custom-inference]`. Container users also set + `customInferenceURL` and `modelInputs` (see + [Container workspace](#container-workspace)). -4. **Select the profile** — give the user entry in `overrides/saw-users.yaml` `profiles: [custom-inference]`. For example, add Erin alongside any existing users: - - ```yaml - users: - # Keep existing user entries here. - - name: erin - profiles: [custom-inference] - ``` - -5. **Add the Secret** — update the existing `inference` entry under `secrets:` in `~/values-secret-secure-agent-workspace.yaml`. Set a `url` ending in `/v1`, the served `model`, and an `api_key` file reference: +4. For VM users, set the endpoint in the `inference` entry of your secrets + file: ```yaml - name: inference @@ -641,587 +396,255 @@ Use a model server of your own (vLLM, Ollama, or any OpenAI-compatible API) inst path: ~/.custom-inference-api-key ``` - `provider: custom-inference` is an optional check for a Secret dedicated to this profile. Omit the `provider` field when the same Secret also serves data-science workspaces. Keep this file and the key outside Git. +5. Load the secrets and push: -A second endpoint with its own key needs its own profile `id` and a SAW-BOM provider named and typed after that id. This configures the agent to call an existing endpoint; it does not deploy a model server. + ```bash + ./pattern.sh make load-secrets + git add overrides + git commit -m "Configure custom inference" + git push + ``` -Load the Secret, create any missing Keycloak accounts from the local user file, and push the configuration to the branch Argo CD watches: +An existing VM picks up the change after `make saw-restart OPENSHELL_SAW_NAME=`. +For more, including a second endpoint and in-cluster model servers, see +[Custom inference](docs/custom-inference.md). -```bash -./pattern.sh make load-secrets -make keycloak-add-users -git add overrides -git commit -m "Configure custom inference for erin" -git push -oc -n vp-gitops get applications | grep -E 'governance-extra-profiles|saw-erin' -``` +## Governance with APF (optional) -Wait for `governance-extra-profiles`, `saw-erin`, `saw-erin-bom`, and `saw-erin-secrets` to be Synced/Healthy. A **new VM** runs the installer on boot and needs no restart. For an **existing VM**, run `make saw-restart OPENSHELL_SAW_NAME=erin` after the updated profiles and Secret have synced. In either case, follow the installer until `apply: Done`: +Every gateway calls a fail-closed governance service. The default is the +OpenShell governance interceptor. You can switch to NVIDIA Agent Policy Fabric +(APF), which serves the same policy as a signed bundle and keeps an audit +trail. -```bash -make saw-logs OPENSHELL_SAW_NAME=erin -``` +1. Get read access to the private APF chart and images on `ghcr.io/mkhaas/apf`. + Then save a `read:packages` token in `~/.ghcr-token`. +2. Create your signing key and bundle, then commit and push them: -Argo CD health alone does not confirm the in-VM installer finished. The log shows `Provider 'custom-inference': type 'custom-inference' is a governance-catalog profile` and OpenClaw onboarded with `--custom-base-url `. + ```bash + make apf-keys + make apf-bundle + git add charts/governance-interceptor/files/apf + git commit -m "Sign the APF policy bundle" + git push + ``` -To open the chat, configure the CLI and sign in as Erin, then open the notebook through a local tunnel: +3. Add the `ghcr` and `apf-signing` entries to your secrets file, then run + `./pattern.sh make load-secrets`. +4. Set `global.governance.engine: apf` in `values-global.yaml`, push, then + restart each VM workspace once. -```bash -make saw-configure OPENSHELL_SAW_NAME=erin SAW_NS=saw-erin -make openclaw-gui OPENSHELL_SAW_NAME=erin SAW_NS=saw-erin \ - WORKSPACE=default SANDBOX_NAME=notebook GUI_PORT=28789 -``` +Full steps, the quickstart variant, and switching back are in +[APF](docs/apf.md). -`make keycloak-password KC_USER=erin` copies Erin's password using an available clipboard tool. Keep the GUI command running while using the browser. GitOps user entries do not automatically create RHDH catalog entries or Tekton runs; the shipped custom-inference profile also has no notebook UI Route enabled. The tunnel works without either. +## Quickstart without GitOps -For Keycloak releases that enforce Admin REST audience checks, deploy the updated service-client bootstrap before creating workspaces; see [Keycloak compatibility](docs/custom-inference.md#keycloak-compatibility). +The quickstart deploys one VM workspace with Make, without Argo CD. Install the +OpenShift Virtualization and Red Hat Build of Keycloak operators first, and +create a `HyperConverged` resource. See +[Quickstart notes](docs/deployment-guide.md#quickstart-notes). -**Option B (Quickstart)** — one command: +1. Clone the repository and log in: -```bash -make saw-create OPENSHELL_SAW_NAME=alice PROFILES=custom-inference \ - PROVIDER=custom-inference MODEL= \ - ENDPOINT_URL=https:///v1 \ - API_KEY= -``` + ```bash + git clone https://github.com/validatedpatterns-sandbox/secure-agent-workspace.git + cd secure-agent-workspace + oc login --server=https://api.:6443 -u + export KEYCLOAK_NS=saw-keycloak OPENSHELL_SAW_NAME=alice + ``` -Notes: +2. Prepare the cluster and deploy Keycloak and governance: -- The namespace credential proxy reaches keyed HTTPS endpoints; the VM reaches keyless HTTP endpoints. `ENDPOINT_URL=http://vllm..svc:8000/v1` is supported only with `API_KEY=''`. `localhost` and keyed HTTPS ports other than 443 are refused. -- Governance must be on: the `custom-inference` profile reaches the gateway through the governance catalog. The installer refuses the apply, naming `overrides/governance-profiles`, until the profile is served. -- Self-hosted models can be slow; the profile sets a 300-second inference timeout (`inference.timeoutSeconds`). + ```bash + make quickstart-prereqs-check + make saw-init + make keycloak-deploy + make keycloak-check + make governance-deploy + make login + ``` -Details: [docs/custom-inference.md](docs/custom-inference.md). +3. Create the workspace. When asked, press Enter to make yourself the owner. -#### Governance with APF (optional) + ```bash + read -r API_KEY < "$HOME/.nvidia-api-key"; export API_KEY + make saw-create PROVIDER=build MODEL=nvidia/nemotron-3.5-lightning-30b-a3b + unset API_KEY + ``` -Every SAW gateway calls a fail-closed governance service. By default that is the OpenShell governance interceptor. It can instead be NVIDIA **Agent Policy Fabric (APF)**, which serves the same policy (`charts/governance-policy`) as an Ed25519-signed bundle, stamps provenance on every sandbox, refuses runtime policy changes and writes an audit trail. Details: [docs/apf.md](docs/apf.md). + For web search, also export `WEB_SEARCH_API_KEY` from `~/.brave-api-key`. + For a custom endpoint, add `PROFILES=custom-inference PROVIDER=custom-inference + ENDPOINT_URL=https:///v1`. -**1. Get access to APF (once).** APF's Helm chart and images are private on `ghcr.io/mkhaas/apf`. +4. Wait for the installer, then connect: -- Ask the owner (@mkhaas) for read access to the chart **and to each image package**: `apf-policy-service`, `apf-policy-gateway` and `apf-compile`. On GHCR each image has its own access list, so access to one does not give the others. -- Create a GitHub token (classic) with the `read:packages` scope and save it: - ```bash - printf '%s' '' > ~/.ghcr-token && chmod 600 ~/.ghcr-token - ``` -- Check that you can pull: - ```bash - docker login ghcr.io -u --password-stdin < ~/.ghcr-token - docker pull ghcr.io/mkhaas/apf/apf-policy-gateway:0.1.0-driverconfig.3 - ``` + ```bash + make saw-status # wait for install and apply: Done + make saw-configure + openshell sandbox list + ``` -**2. Create your signing key and bundle.** This repository ships no key and no bundle. Each deployment makes its own, so no deployment trusts someone else's key. +For container or Kata workspaces, add `DEPLOYMENT_MODE=container` or +`DEPLOYMENT_MODE=kata` to `saw-init` and `saw-create`. See +[Standalone installation](docs/container-installation.md#standalone-installation-and-first-site-approval). -```bash -python3 -m pip install cryptography # if missing -make apf-keys # seed -> ~/.apf-keys/apf.seed (never in git); public key -> charts/governance-interceptor/files/apf/apf.pub -make apf-bundle # signs charts/governance-policy -> charts/governance-interceptor/files/apf/bundle.tar.gz -git add charts/governance-interceptor/files/apf -git commit -m "chore(governance): sign the APF policy bundle" -git push origin -``` +## Uninstall -Keep `~/.apf-keys/apf.seed` safe: only its holder can sign policy changes. `make apf-bundle-check` verifies the committed bundle. - -**3. Add the secrets.** Add these two entries under `secrets:` in your values-secret file (`~/values-secret-secure-agent-workspace.yaml`, or `~/values-secret.yaml`): - -```yaml - # Pull the private APF chart (Argo CD) and images (cluster) - - name: ghcr - fields: - - name: username - value: - - name: token - path: ~/.ghcr-token - # The private half of the key from step 2 - - name: apf-signing - fields: - - name: seed - path: ~/.apf-keys/apf.seed -``` +Remove workspaces first, while Keycloak, the portal and Argo CD are still +running: + +- portal workspaces: use **Delete my agent workspace** in Developer Hub; +- Git users: remove the entries (with `pruneOnRemove: true` for VM users); +- quickstart workspaces: run `make saw-delete`. -Load them and check that the three ExternalSecrets become ready: +Then remove the platform: ```bash -./pattern.sh make load-secrets # reports one more secret per entry -oc get externalsecret ghcr-pull governance-apf-signing -n openshell-agents -oc get externalsecret governance-apf-chart-repo -n vp-gitops +./pattern.sh make pattern-uninstall # Validated Pattern +make quickstart-delete # quickstart ``` -They read `secret/hub/ghcr` and `secret/hub/apf-signing` in Vault and create the image pull secret, the signing key Secret, and the Argo CD repository Secret for the private chart, all outside the user namespaces. - -**4. Switch the engine.** Either set it in git: - -```yaml -# values-global.yaml -global: - governance: - engine: apf -``` +For reinstall checks and troubleshooting, see +[Uninstall and reinstall](docs/deployment-guide.md#uninstall-and-reinstall). -or set it on the installed pattern without a commit: +## Testing ```bash -oc patch pattern secure-agent-workspace -n patterns-operator --type merge \ - -p '{"spec":{"extraParameters":[{"name":"global.governance.engine","value":"apf"}]}}' +make lint # charts and static checks, no cluster needed +make test # the full pytest suite ``` -For a new install, pass the same override: `./pattern.sh make install EXTRA_HELM_OPTS="--set main.extraParameters[0].name=global.governance.engine --set main.extraParameters[0].value=apf"`. - -Argo CD then removes the interceptor, creates the `governance-apf` app (the APF chart, still serving `governance-interceptor.openshell-agents.svc:18081`), and re-renders each user's gateway config with APF's bindings. Restart each user VM once so it boots with them: +To check a deployed user's workspace end to end (Argo CD health, the sandbox, +one real OpenClaw turn through the user's inference provider, the tool-gate +audit log and OCSF export), with `oc` logged in as an administrator: ```bash -oc get application governance-apf -n vp-gitops # Synced / Healthy -oc get pod -n openshell-agents -l app.kubernetes.io/name=apf # 2/2 Running -virtctl -n saw- restart +make e2e-workspace OPENSHELL_SAW_NAME=alice DEPLOYMENT_MODE=container # or kata, vm ``` -While APF is not running the gateways refuse write operations (fail closed). If the APF pod shows `ErrImagePull` with `denied`, your account lacks access to that image package (step 1). - -**Quickstart (no Argo CD):** after steps 1 and 2, `GHCR_USER= GHCR_TOKEN="$(cat ~/.ghcr-token)" make governance-apf`, then create SAWs with `make saw-create ... GOVERNANCE_ENGINE=apf`. - -**Changing policy:** edit `charts/governance-policy`, run `make apf-bundle` (it bumps `policy_revision`), commit and push the new bundle. **Switching back:** set `engine: interceptor` (or remove the override), delete the `governance-apf` Application and restart the user VMs. - -### Self-service workspaces and sandbox web UIs - -Users can create their own workspace from Red Hat Developer Hub: they pick a SAW-BOM profile and enter only the keys it needs; the keys go to Vault under `secret/data/hub/saw-`, and an Argo CD ApplicationSet builds the workspace like any `overrides/saw-users.yaml` entry. A sandbox with `ui: {route: true}` in its profile gets its own route to the OpenClaw / NemoClaw web UI, signed in with Keycloak and open to the workspace owner only (its sign-in is registered by the redirect registrar: [Web UI sign-in](#web-ui-sign-in-redirect-uris)). Details: [docs/self-service-portal.md](docs/self-service-portal.md); step-by-step test: [docs/rhdh-user-guide.md](docs/rhdh-user-guide.md). +`vm` also needs the OpenShell CLI connected to the user's gateway (see +[Use your workspace](#use-your-workspace)). + +See [Testing](docs/testing.md), and the +[live deployment test](docs/deployment-guide.md#live-deployment-test) for a +dedicated test cluster. + +## Security model + +1. **Isolation:** each user gets their own VM or set of namespaces. No agent + process is shared. +2. **Sign-in:** Keycloak OIDC for the CLI and every web UI. The gateway + validates tokens itself, through a TLS passthrough route. +3. **Owner-only access:** web UIs admit only the owner and explicit support + users. The gateway checks workspace membership. +4. **Keys outside the sandbox:** provider keys come from Vault through External + Secrets. The sandbox only sees non-secret markers. See + [Credential isolation](docs/credential-isolation.md). +5. **Network:** default-deny NetworkPolicy, plus an egress firewall that allows + only listed hosts. +6. **Governance:** every gateway calls a fail-closed governance service. +7. **Audit:** container gateways and sandboxes export OCSF events to an + OpenTelemetry collector (best-effort); signed tool-call receipts are an + option. -### Agent harness: skills, MCP servers and tools - -A sandbox's `harnessRef` in its SAW-BOM profile names a harness bundle: skills, MCP servers (`mcp.json`) and OpenClaw tool plugins (`.mjs`). The installer puts it, unchanged, into a volume the sandbox mounts read-only at `/sandbox/harness`, and points OpenClaw at it. Keys never go in a bundle: a server or plugin that calls a service gets its key through a provider attached to the sandbox. A bundle is either an OCI image built from `harness-bundles/` and published to GHCR by CI (`harnessRef: { image: ghcr.io//saw-harness-@sha256:… }`), or an inline bundle in the saw-bom chart (`harnessRef: { name: }`). Details: [docs/harness-bundles.md](docs/harness-bundles.md). - -For an MCP server running inside OpenShift, see [In-cluster MCP Services](docs/harness-bundles.md#in-cluster-mcp-services) for network rules, governance, provider attachment, and BOM provider provisioning. +**Video walkthrough: a personal assistant with governed access** -### Validating the deployment +https://github.com/user-attachments/assets/fdbcb0f3-705c-4546-9d22-d86106c33538 -**Video walkthrough: sandbox UIs and the OpenShell CLI** +See the [personal assistant guide](docs/personal-assistant.md) and the +[governance interceptor](docs/governance-interceptor.md). -Explore the data-science profile's notebook and CUDA workspaces, open the -OpenClaw and NemoClaw sandbox UIs through Developer Hub, and connect from a -laptop with the OpenShell CLI. The walkthrough covers signing in through -Keycloak, selecting a workspace, and inspecting the running sandboxes. Use the -commands below to check your deployment and open its UIs. +## Keycloak production and demo users -https://github.com/user-attachments/assets/d1e93830-ce8b-47c0-9b78-761971ee6067 +Production has no demo users, and self-registration is off. Accounts come from +`overrides/saw-users.yaml`: ```bash -# List sandboxes (default workspace, then cuda-dev) -openshell sandbox list -openshell sandbox list --workspace cuda-dev - -# NemoClaw sandbox (TUI and GUI) — workspace cuda-dev -SANDBOX_NAME=cuda-sandbox \ -WORKSPACE=cuda-dev \ -make nemoclaw-tui -SANDBOX_NAME=cuda-sandbox \ -WORKSPACE=cuda-dev \ -GUI_PORT=18789 \ -make nemoclaw-gui - -# OpenClaw sandbox (TUI and GUI) — workspace default -SANDBOX_NAME=notebook \ -make openclaw-tui -SANDBOX_NAME=notebook \ -GUI_PORT=18790 \ -make openclaw-gui - -# Default NemoClaw entry points -make saw-tui -make saw-gui - -# List owner-restricted sandbox UI routes, when the profile enables them -make sandbox-ui - -# Installer status, and a shell on the gateway VM for debugging -# (adds your SSH key to the VM on demand) -make saw-status -make saw-vm-ssh - -# Local tests and all 13 Helm charts (no cluster needed) -make lint -make test - -# Tool-action gate tests (needs node; also included in the CI suite) -make test-tool-gate - -# Run offline template validation -./tests/test-oidc-templates.sh - -# NetworkPolicy chart checks run offline; name two test SAWs for live checks -SKIP_LIVE=1 ./tests/test-network-policy.sh -SAW_NS=saw-nptest-a VM_NAME=nptest-a PEER_NS=saw-nptest-b \ - PEER_VM_NAME=nptest-b REQUIRE_PEER=1 ./tests/test-network-policy.sh +make keycloak-add-users # create missing accounts +make keycloak-password KC_USER=carol # copy a password (never printed) +make keycloak-reset-password KC_USER=carol # set a new one +make keycloak-passwords # list users with stored passwords ``` -When a sandbox has an owner-restricted UI route, its gateway uses trusted-proxy -authentication. The localhost GUI forward authenticates with the gateway's -loopback password: enter `gateway.auth.password` from the selected sandbox's -`/sandbox/.openclaw/openclaw.json` in **Gateway secret** (or **Password (not -stored)** in older clients) and click **Connect**. The `make sandbox-ui` routes use the owner's Keycloak sign-in. +Each account gets a random strong password, stored in a Secret in the Keycloak +namespace. Each entry can also set `email`, `firstName`, `lastName` and +`roles` (default `[openshell-user]`). Give `openshell-admin` only to operators: +it grants admin access to every gateway. -See the [test-writing and test-running guide](docs/testing.md) for local tools, -selection commands, CI coverage, and fixture rules. `make test` and -`make test-installer` both run the complete pytest suite. +To test as two users, sign in as the second user in a private browser window. -### Delete +**Demo users** (`developer`, `admin`, `alice`, `bob`) are only for test +clusters. In the quickstart, use +`make -f Makefile-quickstart keycloak-deploy DEMO_ENABLED=true`. For the +pattern, set `demo.enabled=true` on the Keycloak application, and use +`overrides/saw-users-demo.yaml`. -For a clean reinstall, retire workspaces while the portal, Keycloak and Argo -are available. Use the RHDH **Delete my agent workspace** template for portal owners, -remove static owners through Git with `pruneOnRemove: true`, and run -`make saw-delete` with the original site inputs for standalone installations. -Wait for each workspace Application and runtime namespace to disappear before -uninstalling the platform. RHDH preserves generated Applications when its -ApplicationSet disappears. A successful platform uninstall alone can therefore -leave a workspace running. Container audit history is retained separately. +On a realm imported by an older release, run `make keycloak-harden` and +`make keycloak-session-max` to apply the current password, lockout and session +settings. -```bash -# Delete a single sandbox -make saw-delete +## Web UI sign-in (redirect URIs) -# Delete Keycloak + PostgreSQL -make keycloak-delete +Every workspace web UI has its own host. Keycloak needs each one registered as +a redirect URI. The **redirect registrar** in the Keycloak namespace does this +automatically, within seconds of a route appearing. It also removes entries for +deleted workspaces. -# Delete quickstart Keycloak and image releases after deleting each SAW -make quickstart-delete +To keep Keycloak admin access out of the cluster, set +`redirectRegistrar.enabled: false` in the `openshell-keycloak` values. +Register the redirect URIs yourself instead: -# Uninstall the validated pattern through the documented wrapper -./pattern.sh make pattern-uninstall +```bash +make -f Makefile-quickstart keycloak-register KC_USER=carol # one user's UIs +make -f Makefile-quickstart keycloak-redirects # show what is missing +make -f Makefile-quickstart keycloak-redirects-sync # sync all workspaces ``` -A full SAW uninstall first drains the Pattern-owned `openshell-rhdh` and -`saw-users` Applications. The command sets their clustergroup `disabled` -overrides on the Pattern and waits for Argo to mark each child for pruning. -It terminates any active sync and waits for foreground deletion before -the framework removes operators and webhooks. The VM cleanup runs after this -drain so a reconciling SAW Application cannot recreate a VM during teardown. -If the drain fails, correct -the reported problem and rerun `pattern-uninstall`. Those two overrides -persist on the Pattern until uninstall completes. - -To qualify a fresh RHDH-enabled installation, run the first check on the -clean cluster and the second after installing with the configured site inputs: +With another OIDC issuer, register the callbacks there. To list them, run: ```bash -scripts/check-rhdh-bootstrap.sh before -./pattern.sh make install -scripts/check-rhdh-bootstrap.sh after -``` - -ESO creates `rhdh/rhdh-oidc` from Vault before the Keycloak client hook can -start. The hook requires that Secret and has a 15-minute execution deadline. -The check requires the completed Job, a Synced/Healthy RHDH Application, and -a ready rollout of the actual Backstage Deployment. On a cold start, dynamic -plugins can still be installing when Argo reports Healthy. The portal Deployment -has a 30-minute rollout deadline and retains the operator’s startup health -endpoint with a larger failure budget for a cold backend. The check waits up -to 30 minutes for Deployment availability. Set `RHDH_NAME` if the Backstage -resource has a site-specific name. Verify owner sign-in and workspace creation -through the portal separately. After changing owner enrollment, wait until the -RHDH catalog offers the intended deployment mode and profile before submitting -a create request. Catalog ingestion can finish after the Deployment rollout. - -On busy clusters, use a site value to reserve CPU for the framework's -imperative Jobs during cold bootstrap. For example, add this to -`values-cluster-.yaml` and size the requests for available nodes: - -```yaml -clusterGroup: - extraObjects: - bootstrap-resources: - apiVersion: v1 - kind: LimitRange - metadata: - name: bootstrap-requests - namespace: imperative - spec: - limits: - - type: Container - defaultRequest: - cpu: "1" - memory: 256Mi +oc get routes -A -l saw.redhat.com/oidc-redirect=true \ + -o jsonpath='{range .items[*]}https://{.spec.host}/oauth2/callback{"\n"}{end}' ``` -Check `oc -n imperative get pods,limitrange` and the admitted unseal Pod's -`spec.initContainers[].resources.requests`. In clustergroup 0.9.58 the stock -unseal playbook has a 600-second timeout. Exit 124 followed by HTTP 403 -creating the Vault secrets engine can indicate an interruption after unseal -and before the stock CLI login. In that state the RHDH ExternalSecret stays -unready. A CPU reservation can reduce contention. It cannot recover an -already interrupted bootstrap. [Stock Job](https://github.com/validatedpatterns/clustergroup-chart/blob/v0.9.58/templates/imperative/unsealjob.yaml), -[stock Vault role](https://github.com/validatedpatterns/rhvp.cluster_utils/blob/6aec8c6d50/roles/vault_utils/tasks/vault_unseal.yaml). - -A reinstall also depends on OpenShift Virtualization cleanup. Uninstall waits -up to one hour for the Pattern-owned `openshift-cnv` namespace to disappear -before checking whether its marked HyperConverged CRD is unused. A timeout -returns an error. Check namespace termination, then rerun -`./pattern.sh make pattern-uninstall` before installing again. A retained -CRD can point OLM at a conversion webhook that no longer exists. - -When switching from an OperatorHub Quickstart to a clean Pattern test, confirm -that both the test CNV namespace and its HyperConverged CRD are absent. A CSV -uninstall can leave the CRD behind. On Pattern teardown, the cleanup command -reads HyperConverged objects through the CRD's served storage version. This -allows it to remove the tracked SAW instance even after the conversion service -disappears. It checks for other instances and subscriptions before deleting -the marked CRD. - ## Repository structure ``` . -├── Makefile # Root Makefile (includes common + quickstart) -├── Makefile-common # Validated Pattern targets (install, load-secrets, etc.) -├── Makefile-quickstart # Component-action quickstart targets -├── values-global.yaml # Pattern config (name, ArgoCD, secret loader) -├── values-prod.yaml # ClusterGroup (operators, subscriptions, applications) -├── values-secret.yaml.template # Secrets template (inference keys, SSH keys) +├── Makefile, Makefile-common, Makefile-quickstart # all make targets (make help) +├── pattern.sh # Validated Patterns wrapper +├── values-global.yaml # pattern settings +├── values-prod.yaml # cluster group: operators and applications +├── values-secret.yaml.template # secrets template ├── overrides/ -│ └── saw-users.yaml # One list entry per user -├── charts/ # ArgoCD-managed Helm charts -│ ├── openshell-keycloak/ # Keycloak CR + KeycloakRealmImport (RHBK operator) -│ ├── openshell-saw/ # Per-user sandbox VM + gateway + agent -│ ├── pattern-secrets/ # ExternalSecrets for provider API keys + SSH -│ └── saw-users/ # Turns the user list into namespaces and Argo apps -├── credential-proxy/ # Per-namespace TLS proxy that injects provider keys -├── image-builder-charts/ # Build-time charts (imagestreams, bootc image) -│ └── helm/ -│ ├── nemoclaw-imagestream/ # NemoClaw sandbox image BuildConfig -│ ├── nemoclaw-cli-imagestream/ # NemoClaw CLI image BuildConfig -│ └── openshell-gateway-image/ # Bootc gateway VM image + golden image -├── scripts/ # Runtime utilities and automation -│ ├── test-deployment.sh # Live OpenShift deployment test -│ ├── openshell-saw-create.sh # Sandbox provisioning logic -│ ├── openshell-saw-gui.sh # Web UI port-forward -│ ├── openshell-saw-logout.sh # Clear local gateway credentials -│ ├── generate-keys.sh # SSH keypair generation -│ └── oidc-login.sh # Browser-based OIDC login -├── tests/ # Test scripts -│ ├── test-bootc-e2e.sh # Bootc pipeline E2E (28 checks) -│ ├── test-oidc-templates.sh # Helm template validation (43 checks) -│ └── test-network-policy.sh # Offline and live network isolation checks -├── cli/ # Admin provisioning CLI (openshell-saw) -├── pattern.sh # VP utility container wrapper -└── ansible.cfg # VP ansible config +│ ├── saw-users.yaml # one entry per user +│ ├── saw-container-defaults.yaml +│ └── governance-profiles/ # extra governance profiles +├── charts/ # Argo CD-managed Helm charts +├── kubernetes-runtime/ # container workspace controller +├── credential-proxy/ # VM credential proxy +├── harness-bundles/ # agent skills, MCP servers and tools +├── image-builder-charts/ # image builds and the golden VM image +├── scripts/ # install and helper scripts +├── tests/ # pytest suite and shell checks +└── docs/ # guides ``` ## References -- [NVIDIA Secure Agent Workspace Reference Design](https://docs.nvidia.com/enterprise-reference-architectures/secure-agent-workspace-reference-design/latest/) -- [Network troubleshooting](docs/troubleshooting.md) -- [OpenShift Virtualization Reference Implementation](https://docs.nvidia.com/enterprise-reference-architectures/secure-agent-workspace-reference-design/latest/openshift-virtualization-reference-implementation.html) -- [NVIDIA OpenShell](https://github.com/NVIDIA/OpenShell) -- [NVIDIA NemoClaw](https://github.com/NVIDIA/NemoClaw) +- [NVIDIA Secure Agent Workspace reference design](https://docs.nvidia.com/enterprise-reference-architectures/secure-agent-workspace-reference-design/latest/) +- [NVIDIA OpenShell](https://github.com/NVIDIA/OpenShell) and [NemoClaw](https://github.com/NVIDIA/NemoClaw) - [Red Hat Validated Patterns](https://validatedpatterns.io/) - [Red Hat Build of Keycloak](https://docs.redhat.com/en/documentation/red_hat_build_of_keycloak/) - -## Technical details - -### Security model - -The system implements layered isolation: - -1. **VM-level isolation** — Each user gets a dedicated KubeVirt VM (one VM per user, no shared agent process space) -2. **OIDC authentication** — Keycloak provides SSO with PKCE and device code flow support -3. **Per-user access control** — Dashboard and sandbox UI proxies allow the owner and explicit support users by `preferred_username`. Each gateway also checks workspace membership for list and create operations. -4. **TLS passthrough** — Gateway route preserves gRPC/HTTP2 end-to-end; the gateway validates OIDC tokens directly -5. **Secret management** — Provider keys stay in namespace Secrets mounted into the credential proxy. The VM stores markers and metadata, and its platform admin mTLS identity exists only during an installer apply in tmpfs. The user's SSH private key never touches the cluster. See [Credential isolation](docs/credential-isolation.md). -6. **Network isolation** — Default-deny NetworkPolicy blocks cross-namespace and API/metadata traffic from the VM; EgressFirewall limits external destinations to exact allowed hostnames. CI checks shipped profile hosts and ports against both layers. -7. **Governed gateways** — every gateway calls a fail-closed governance service: the OpenShell governance interceptor, or APF with a signed policy bundle ([docs/apf.md](docs/apf.md)) - -**Video walkthrough: a personal assistant with governed access** - -See a personal assistant read Slack messages and Gmail under read-only provider -profiles. The walkthrough demonstrates a denied Slack -write, rejection of an unapproved provider type, and a reviewed policy change -that grants read-only access to Notion through GitOps. Credentials stay outside -the sandbox in default proxy mode; provider profiles define the allowed -destinations and operations. The interceptor approves gateway operations such -as provider creation; sandbox policy enforces API access and the agent tool -gate can refuse a write before it reaches the network. -See the [personal assistant guide](docs/personal-assistant.md) for setup, -[Governance interceptor](docs/governance-interceptor.md) for policy rules, and -[Credential isolation](docs/credential-isolation.md) for how credentials are -handled. - -https://github.com/user-attachments/assets/fdbcb0f3-705c-4546-9d22-d86106c33538 - -### Keycloak production and demo users - -Production deploys no demo identities, and self-registration is off. Create -real accounts with `make keycloak-add-users` after adding names to -`overrides/saw-users.yaml`. The Pattern resolves each existing Keycloak account -to its subject and enrolls it without a first-login edit. A regular owner -needs only `openshell-user`. `openshell-admin` is a platform operator role: -it grants administrative access at every gateway. Give it only to an -explicit operator account. - -Quickstart demo identities require an explicit command: - -```bash -make -f Makefile-quickstart keycloak-deploy DEMO_ENABLED=true -``` - -For a Pattern demo, set the Keycloak application override -`demo.enabled=true`, use `overrides/saw-users-demo.yaml` as the saw-users -extra values file, and add generated `keycloak-users` fields for `developer`, -`admin`, `alice`, and `bob` to your private `values-secret.yaml`. The normal -`values-secret.yaml.template` has no demo password keys. - -| Username | Roles | -|---|---| -| `developer` | `openshell-user` | -| `admin` | `openshell-user`, `openshell-admin` | -| `alice` | `openshell-user` | -| `bob` | `openshell-user` | - -There are no default passwords. Each user gets a random one (20+ -characters with upper and lower case, digits and symbols), kept in Secret -`openshell-keycloak-user-passwords` in the Keycloak namespace: from Vault in -an explicitly configured demo Vault entry in the Validated Pattern, or -generated by the demo quickstart command. -`make keycloak-passwords` lists the users with stored passwords. It does not -print the values. - -To sign in as Alice or Bob on macOS, first find the Secret for that user. -For an explicit Pattern demo, the command names -`openshell-keycloak-user-passwords` in `saw-keycloak`. - -```bash -make keycloak-password KC_USER=alice -set -o pipefail -oc get secret openshell-keycloak-user-passwords -n saw-keycloak \ - -o jsonpath='{.data.alice}' | base64 -D | pbcopy -``` - -On Linux, use `base64 -d | xclip -selection clipboard` in place of -`base64 -D | pbcopy` (or use `wl-copy` on Wayland). - -Paste the clipboard value into Alice's Keycloak password field. For Bob: - -```bash -make keycloak-password KC_USER=bob -set -o pipefail -oc get secret openshell-keycloak-user-passwords -n saw-keycloak \ - -o jsonpath='{.data.bob}' | base64 -D | pbcopy -``` - -The commands do not print a password in the terminal. Clear the clipboard -after sign-in with `printf '' | pbcopy`. -If `make keycloak-password` names `openshell-keycloak-users` instead, use -that Secret name in the `oc get` command; it holds passwords created or reset -through the quickstart targets. Do not put a password in a command argument -or share it in a test log. - -For a separate Bob sign-in, open a private browser window and start the -Keycloak login flow there. A normal window can reuse Alice's session and -open her chat without a login page. Bob must receive HTTP 403 when he opens -Alice's sandbox UI. Use Bob's own workspace URL to test his access. -The default `overrides/saw-users.yaml` creates no workspace. The demo file -creates Alice's workspace. Add Bob to the selected list for a second -workspace. - -Self-registration is off: an admin adds users from `overrides/saw-users.yaml` -(the same list that creates their workspaces). Each name not in the realm -yet gets an account with a generated password; users that exist are left -alone, so running it again is safe. Optional per entry: `email`, -`firstName`, `lastName`, `roles` (default `[openshell-user]`). Another file: -`USERS_FILE=`. - -```bash -make keycloak-add-users # add missing users -make keycloak-password KC_USER=carol # show the Secret location -make keycloak-reset-password KC_USER=carol # reset the stored password -``` - -Passwords set this way are kept in Secret `openshell-keycloak-users`; -`keycloak-passwords` lists the users. These commands do not print passwords. - -The realm requires strong passwords for anything users set themselves -(`keycloak.passwordPolicy`: 14+ characters, upper, lower, digit, special, -not the user name or email, not one of the last 5), and locks an account out -for a growing time after 5 failed sign-ins (`keycloak.bruteForce`). A realm -imported before this kept its old settings and passwords (an import never -changes an existing realm): run `make keycloak-harden` to apply the policy -and turn registration off. Run `make keycloak-session-max` to apply the -chart's 24-hour SSO session maximum. This command keeps the realm's current -idle timeout. Follow the existing-install migration in the deployment guide -before disabling any account. - -### Web UI sign-in (redirect URIs) - -Each workspace's web UIs (the VM's OpenShell dashboard, and each sandbox UI -route) sign in through Keycloak's `openshell-dashboard` client, and Keycloak -only sends the browser back to a redirect URI registered on that client. Every -UI has its own host, and Keycloak takes no wildcard in a host name, so each -one is registered. - -By default the **redirect registrar** does it: one Deployment in Keycloak's -namespace (`charts/openshell-keycloak`, `redirectRegistrar`) registers each -web UI route's `https:///oauth2/callback` within about 15 seconds of -the route appearing (from `overrides/saw-users.yaml` or the self-service -portal), and removes the entries of workspaces that are gone. It signs in as -its own Keycloak client that may only manage the OpenShell realm's clients; -its init container uses the Keycloak admin Secret once per start to set that -client up, and the registrar itself never sees it. - -To keep Keycloak admin access out of the cluster entirely, turn it off -(`redirectRegistrar.enabled: false` in the `openshell-keycloak` values) and -register as an administrator instead, with your own `oc` session. The same -targets work alongside the registrar too: - -```bash -make -f Makefile-quickstart keycloak-register KC_USER=carol # account (if new) + carol's web UIs -make -f Makefile-quickstart keycloak-redirects # what is registered, what is missing -make -f Makefile-quickstart keycloak-redirects-sync # all workspaces; drops deleted ones -``` - -`keycloak-register` creates the Keycloak account if it does not exist yet -(generated password stored in a Secret), then adds -`https:///oauth2/callback` for each of the user's web UI routes, -waiting up to `REDIRECT_WAIT` seconds (default 600) for Argo CD to create -them. Until then, signing in to that workspace's UIs fails with Keycloak's -"Invalid parameter: redirect_uri". `keycloak-redirects-sync` adds whatever is -missing and removes the entries it added for workspaces that are gone; -entries it did not add (registered by hand, other apps) are kept. - -The registrar and `keycloak-redirects-sync` apply the same rules. - -The web UI routes are the ones labelled `saw.redhat.com/oidc-redirect=true` in -the `saw-*` namespaces. With another OIDC issuer, register their callbacks -there instead; this lists them: - -```bash -oc get routes -A -l saw.redhat.com/oidc-redirect=true \ - -o jsonpath='{range .items[*]}https://{.spec.host}/oauth2/callback{"\n"}{end}' -``` - -The scripts verify Keycloak's certificate; for a router certificate signed by -a private CA, set `KEYCLOAK_CA=`. For a Keycloak CR not named -`openshell-keycloak`, set `KEYCLOAK_NAME`. - -### Namespaces - -| Namespace | Contents | -|---|---| -| `saw-` (one per sandbox) | The gateway VM, metadata inputs, credential proxy, and provider Secrets mounted only into that proxy | -| `openshell-agents` | Golden VM image, image builds, governance interceptor | -| `saw-keycloak` | Keycloak (RHBK) | - -The gateway VM installs itself from a versioned Bill of Materials on every boot; see [docs/versioned-bom-installer.md](docs/versioned-bom-installer.md). - -### OIDC issuer resolution - -The sandbox chart resolves the OIDC issuer URL automatically: -- **Validated Pattern flow:** Computed from `global.clusterDomain` (injected by ArgoCD) -- **Quickstart flow:** Detected from the Keycloak route at `make saw-create` time -- **Manual override:** Set `oidc.issuerUrl` explicitly +- [Troubleshooting](docs/troubleshooting.md) +- [Agent harness bundles](docs/harness-bundles.md) +- [Versioned BOM installer](docs/versioned-bom-installer.md) ## Tags | Field | Value | |---|---| | **Title** | Secure Agent Workspace | -| **Description** | Deploy isolated, per-user AI agent sandboxes on OpenShift Virtualization | +| **Description** | Deploy isolated, per-user AI agent sandboxes on OpenShift | | **Industry** | Cross-industry | | **Product** | Red Hat OpenShift | | **Use case** | AI agent sandboxing, secure coding environments | diff --git a/docs/architecture-alignment.md b/docs/architecture-alignment.md index fca508966..ec7e0413e 100644 --- a/docs/architecture-alignment.md +++ b/docs/architecture-alignment.md @@ -73,7 +73,7 @@ This document maps the [NVIDIA Secure Agent Workspace OpenShift Virtualization R **Reference:** "OpenShell or equivalent runtime sandboxing." **Implementation:** -- The golden image is built with `virt-customize`; the in-VM BOM installer installs the OpenShell gateway and CLI at boot (OpenShell `0.1.6-rhaiv.4`) +- The golden image is built with `virt-customize`; the in-VM BOM installer installs the OpenShell gateway and CLI at boot (OpenShell `0.1.10-rhaiv.0`) - OpenClaw, Hermes, and Deep Agents Code agents supported - Agents run inside container sandboxes managed by the OpenShell gateway - Inference routed through user-configured provider endpoints diff --git a/docs/arm64.md b/docs/arm64.md index 2975c6074..b61d04612 100644 --- a/docs/arm64.md +++ b/docs/arm64.md @@ -4,7 +4,7 @@ OpenShift Virtualization runs guests on the host architecture. On an arm64 clust ## Images -- The InstallerBOM pins the OpenShell CLI, gateway, supervisor, and sandbox runtime at `0.1.6-rhaiv.4` by multi-architecture index digest. Podman pulls the VM architecture. +- The InstallerBOM pins the OpenShell CLI, gateway, supervisor, and sandbox runtime at `0.1.10-rhaiv.0` by multi-architecture index digest. Podman pulls the VM architecture. - `make images-mirror` copies the multi-architecture Podman golden disk; each node pulls its own architecture. To build the disk on the cluster instead, run `make gateway-build-podman`. The build picks the Fedora Cloud image and cosign by the build node's architecture. The optional Docker disk (`openshell-gateway-docker`) is x86_64 only; ARM clusters use the default Podman runtime. Without an explicit `IMAGE_REPO`, the result stays in the internal registry. Check an existing image and DataVolume before rebuilding: a new build replaces the shared golden image tag. - The `build-openshell-gateway` workflow builds the Podman disk on amd64 and arm64 and merges their digests into one GHCR tag. The `build-governance-interceptor`, `build-nemoclaw-sandbox`, and `build-nemoclaw-cli` workflows do the same for their images. Check a published tag with `oc image info --show-multiarch ` before relying on it. Until the interceptor's GHCR tag includes arm64, run `make governance-interceptor-build-local` and set the `governance-interceptor` application's `image` override to the resulting in-cluster ImageStream tag. - The NemoClaw sandbox and CLI defaults use GHCR. If their GHCR tags do not yet include arm64, `make sandbox-build` and `make cli-build` build for the cluster architecture. `sandbox-build` detects a single architecture among schedulable nodes and sets the upstream Dockerfile's required `TARGETARCH`; on a mixed cluster, set `BUILD_ARCH=arm64` or `amd64`. The BuildConfig pins its pod to the selected architecture. Set `IMAGE_REPO` to a namespace you control only when you intend to publish; verify the pushed digest and update the workspace image values. The Makefile refuses the upstream namespace. diff --git a/docs/container-images.md b/docs/container-images.md index ca73cae31..3457ea167 100644 --- a/docs/container-images.md +++ b/docs/container-images.md @@ -18,7 +18,7 @@ those deployment overrides local when preparing changes for upstream. | `openshell-gateway-docker` | `latest`, `sha-` | x86_64-only Docker VM disk, `make gateway-build-docker` | | `nemoclaw-cli` | `latest`, `sha-` | Installer BOM `spec.nemoclaw.cliImage` | | `nemoclaw-sandbox` | `latest`, `sha-` | Data-science default and CUDA profiles | -| `governance-interceptor` | `latest`, `sha-`, OpenShell ref (currently `v0.1.6`) | Interceptor deployment and image builder | +| `governance-interceptor` | `latest`, `sha-`, OpenShell ref (currently `v0.1.10`) | Interceptor deployment and image builder | | `saw-credential-proxy` | `latest`, `sha-` (multi-arch) | Chart default `credentialProxy.image` (digest pinned in `charts/openshell-saw/values.yaml`) | | `saw-kubernetes-runtime` | `latest`, `sha-` (multi-arch) | Container reconciler, preparation/enrollment helpers, standalone projector and relay membership Job; operator site values pin the manifest digest. | | `saw-harness-` | Bundle version, `sha-` | Optional digest-pinned `harnessRef.image` | @@ -31,8 +31,8 @@ the arm64 Podman disk ([arm64 guide](arm64.md)). The legacy `openshell-gateway-docker` disk is x86_64 only and publishes its tags directly; ARM clusters use the default Podman runtime. -The OpenShell 0.1.6 public interceptor is published and pinned in -`charts/governance-interceptor/values.yaml`. +The OpenShell 0.1.10 interceptor (with the SAW extension) is published and +pinned in `charts/governance-interceptor/values.yaml`. The credential and guest-shutdown corrections in #162/#164 are merged. Build provenance and validation are in the [release record](openshell-016-release.md). @@ -254,7 +254,18 @@ published image blobs while any site references their digests. The shipped notebook image sets `WORKDIR /sandbox` with mode `0770` and ownership `1000:0`. Container workspaces run with the OpenShift namespace UID and group. They need search permission on this directory to start the sandbox -entrypoint. Prepare the image once in the same build namespace as the runtime: +entrypoint. + +CI publishes the prepared image: `.github/workflows/build-openclaw-image.yml` +builds `images/saw-openclaw/Containerfile` from the notebook BOM's pinned +image and pushes `ghcr.io//saw-openclaw` (linux/amd64 and +linux/arm64), tagged +`src-`. Pin that tag's digest in +`containerDefaults.profileImageOverrides` (public, so no `imagePull` is +needed). A changed source digest in the BOM publishes a new tag. + +Disconnected clusters can prepare the image once in the same build namespace +as the runtime instead: ```sh make container-notebook-image BUILD_NS="$BUILD_NS" BUILD_ARCH=amd64 > notebook-site.yaml diff --git a/docs/container-installation.md b/docs/container-installation.md index ff5ed7b3c..9d79a7505 100644 --- a/docs/container-installation.md +++ b/docs/container-installation.md @@ -38,12 +38,15 @@ Additional requirements: destinations/resource kinds, and permission for Argo to manage the workload, control, UI and history namespaces. The standalone projector's namespace is separate from Argo CD and labelled `argocd.argoproj.io/managed-by`. -- RWO storage for gateway state, workspace data, controller ledger and audit - history; a shared filesystem class for the preparation/audit exchange PVCs. +- RWO storage for gateway state, workspace data, the controller ledger and the + tool gate's audit log. With [audit receipts](#audit-receipts), also a shared + filesystem class for the audit exchange. - 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. + approved provider endpoints. No cluster addresses are configured: see + [Network access and storage](#network-access-and-storage). + Workspaces share one AdminNetworkPolicy priority (each policy selects only + its own namespace); enrollment refuses a workspace if any other policy + covering its namespace comes at or before it. - `oc`, Helm 3 and `uv` on the installation machine. Provider credentials stay in Vault; local files and Git contain references and public configuration. @@ -86,21 +89,26 @@ For Kata workload placement, follow the [Kata installation and Developer Hub gui The same site object is used as `containerSites.` for static installs or `portal.containerSites.` for RHDH. It is administrator-owned, not a form -field. Start from the component charts' values and schemas: +field. The component wiring (namespaces, service accounts, SANs, the +workspace egress policy, governance endpoint, enrollment build namespace, +resources and relay Keycloak settings) defaults in +[`siteDefaults`](../charts/saw-portal-container/values.yaml); a site sets only +what differs, and its values win (maps merge, lists replace). Start from the +component charts' values and schemas: | Site input | Contents / source | |---|---| | `subject` | Resolved Keycloak subject UUID matching the owner. Static inputs supply it explicitly; RHDH resolves the authenticated owner and requires a matching site. | -| `stack.identity` | Pinned revision and [identity chart values](../charts/saw-kubernetes-identity/values.yaml): installation identity, gateway SANs and stock generator/helper images. Administrator sessions use the VM's shared temporary-identity mechanism; no administrator certificate or renewal input is supplied. | -| `stack.policy` | Pinned revision and [admission/network values](../charts/saw-runtime-policies/values.yaml): runtime namespace, service accounts, explicit egress and unique priority. | -| `stack.proxy` | Pinned revision and [credential-proxy values](../charts/saw-kubernetes-proxy/values.yaml): trusted namespace and egress. Provider bindings/digest derive from the shared catalog. | +| `stack.identity` | Pinned revision and [identity chart values](../charts/saw-kubernetes-identity/values.yaml): installation identity, gateway SANs, stock generator/helper images and the bootstrap's egress (`network.bootstrapEgress`, DNS by default). Administrator sessions use the VM's shared temporary-identity mechanism; no administrator certificate or renewal input is supplied. | +| `stack.policy` | Pinned revision and [admission/network values](../charts/saw-runtime-policies/values.yaml): runtime namespace, service accounts, explicit egress and priority. | | `stack.gateway` | Pinned revision and [gateway values](../charts/openshell-saw-kubernetes/values.yaml): stock gateway/driver images, storage, OIDC and network configuration. | | `stack.audit` | Pinned revision and [audit values](../charts/saw-audit-writer/values.yaml): history/exchange storage classes, image and owner identity. Targets derive from the BOM. | -| `governanceNamespace`, `providerAllowHosts` | Shared governance location and permitted provider destinations. | -| `automaticEnrollment` | `enabled`, pinned helper image/revision, build namespace, resource limits, approved profile digests and reviewed boundary reference. | -| `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. | +| `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 (defaults to the cluster's Keycloak route), Keycloak namespace and realm registrar Secret **name**, and egress (DNS and HTTPS by default). 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. | +| `customInferenceURL` (per user) | `custom-inference` only: the owner's OpenAI-compatible base URL (HTTPS, port 443, ending `/v1`), from the portal form or the user's entry in `overrides/saw-users.yaml`. Its host must be the only endpoint in `overrides/governance-profiles/custom-inference.yaml`, where OpenShell sends the API key; the runtime controller otherwise refuses the provider (`ProviderProfileMismatch`). | RHDH offers **Container** on the create form when `portal.deploymentModes` includes `container` and at least one configured owner site has a catalog profile @@ -172,29 +180,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 @@ -237,21 +236,16 @@ The composition substitutes these as data; it does not evaluate user input as Helm templates. Do not author `targets`, `enrollment`, `providerPolicy` or relay subjects manually; the common projector and trusted bootstrap derive them. -`automaticEnrollment.relay.egress` must permit the cluster's Kubernetes API -Service/backends and their ports, using the same approved destinations as the -controller's bootstrap egress, as well as DNS and the OIDC issuer. The relay -membership Job reads Pod identities and updates the named public client-trust -Secret before connecting to OpenShell. DNS/OIDC access alone cannot complete -that Job. The gateway can create the workspace before the reconciler grants the -owner its administrator role. The binding Job waits up to 210 seconds after -authentication for both observations, pins the workspace UUID once observed, -and rejects a changed UUID or unexpected owner role. The browser relay has no Kubernetes token or trust-write RBAC. Changing -the relay inputs creates a new input-hashed binding Job through GitOps. - -For sites with split-horizon DNS, run the [topology preflight](#discover-and-review-container-egress) -from a trusted in-cluster Pod. The gateway and relay need the issuer address -that Pod resolves on TCP 443. A successful browser login from the workstation -does not test this path. +The relay membership Job reads Pod identities and updates the named public +client-trust Secret before connecting to OpenShell, so it reaches the +Kubernetes API like the other platform pods +([Network access and storage](#network-access-and-storage)). The gateway can +create the workspace before the reconciler grants the owner its administrator +role. The binding Job waits up to 210 seconds after authentication for both +observations, pins the workspace UUID once observed, and rejects a changed UUID +or unexpected owner role. The browser relay has no Kubernetes token or +trust-write RBAC. Changing the relay inputs creates a new input-hashed binding +Job through GitOps. Public trust publication is asynchronous: the Kubernetes Secret volume must refresh, then the stock gateway must reload it. Initial TLS failures, including @@ -271,19 +265,17 @@ global: clusterDomain: cluster.example.com # ingress is apps.cluster.example.com projection: enabled: true - applicationSetControllerLabels: - app.kubernetes.io/name: - egress: # explicit Kubernetes API and DNS NetworkPolicy rules - - to: - - ipBlock: {cidr: /32} - ports: [{protocol: TCP, port: 6443}] - # Add the cluster's API Service and DNS paths as required by its networking. + # Defaults to -applicationset-controller; set it only for + # an instance named differently. + # applicationSetControllerLabels: + # app.kubernetes.io/name: users: - name: alice ownerSubject: registration: <16-lowercase-hex-characters> - installationID: - vaultPrefix: secret/data/hub/saw-alice/ + # installationID: optional; defaults to the portal's + # uuid5(NAMESPACE_URL, "urn:saw:portal::") + vaultPrefix: secret/data/hub/saw-alice profiles: [data-science] pruneOnRemove: true intentGeneration: 1 @@ -308,7 +300,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 @@ -326,8 +319,8 @@ restricted to the image stream named by the configured digest-pinned image. The selected BOM determines provider Secret names and fields. For example, with the default NVIDIA-backed `data-science` profile, store its key in -`secret/data/hub/saw-alice//inference` as `api_key`. Configure any -additional enabled provider inputs in the same registration prefix. RHDH uses +`secret/data/hub/saw-alice/inference` as `api_key`. Configure any +additional enabled provider inputs under the same per-user prefix. RHDH uses the existing request-to-Vault pipeline; standalone operators use their normal Vault provisioning. Neither the Make helper nor projector loads raw keys. @@ -496,6 +489,87 @@ operator-owned; deleting the standalone Helm release does not erase it. ## Pattern and RHDH enablement +### Minimal static entries + +The pattern reads two files for `saw-users`. The platform admin sets the +cluster-wide container settings once in `overrides/saw-container-defaults.yaml` +(`projection` and `containerDefaults`, the site every container user gets). +Users only add an entry to `overrides/saw-users.yaml`: + +```yaml +users: + - name: alice + ownerSubject: # make keycloak-user-info KC_USER=alice + profiles: [custom-inference] + vaultPrefix: secret/data/hub # credential base path + values: + deployment: {mode: container} +``` + +The chart fills in the rest; an explicit value always wins: + +| Field | Default | +|---|---| +| `registration` | `sha256(":")[:16]`; to start over, remove the entry and let Argo delete it, then add it back with a higher `generation` (default 1); two generations of a user cannot overlap | +| `installationID` | `uuid5(NAMESPACE_URL, "urn:saw:portal::")` | +| `vaultPrefix` | base path + `/saw-`, the same for every generation; credentials go under it (for example `.../inference`) | +| `pruneOnRemove`, `intentGeneration` | `true`, `1` | +| site | `containerDefaults`, overlaid by `containerSites.`; `subject` is the user's `ownerSubject` | +| chart revisions | Reviewed sites: none. Set `stack.*.revision`, `automaticEnrollment.revision` and `relay.revision` to full commit SHAs; the workspace chart and preflight reject a branch or a missing revision. `autoApprove` sites: `global.targetRevision`, so they follow the pattern's branch like VM users. | + +Enrollment stays off unless a site sets `automaticEnrollment.enabled: true` +(and `autoApprove` defaults to `false`): a new workspace deploys its foundation and waits for +the reviewed flow below. After the review, set `enabled: true`, the reviewed +`reference` and the `approvedProfiles` digest under +`containerSites..automaticEnrollment`, and pin its chart revisions to +full SHAs. + +Development and demo clusters can skip the review by listing +`overrides/saw-container-demo.yaml` after `saw-container-defaults.yaml` in the +`saw-users` and `openshell-rhdh` `extraValueFiles`. It sets `autoApprove: true`: +the enrollment Job still runs its health, admission and network checks, then +publishes the boundary and BOM it observes instead of comparing them with a +reviewed `reference` and `approvedProfiles` digest. Later changes to an +enrolled boundary still fail closed; start a new `generation` to re-enroll. +`containerSites..automaticEnrollment.autoApprove: false` puts one user +back on the reviewed flow. Never list the demo file in production values. + +**Upgrading from the credential-proxy controller.** Container workspaces +enrolled before OpenShell-native providers cannot be upgraded in place: their +approved boundary lists the removed proxy objects, and their controller state +records proxy-era providers. They report `ReenrollRequired` and make no +changes. Re-enroll each one by starting a new generation (`generation: ` +in `overrides/saw-users.yaml`, or a new request in the portal), copying its +credentials to the new registration's Vault path first. With +`pruneOnRemove` (the default) the old registration's namespaces are removed. + +Before install, `make saw-init` checks the cluster for these entries: OVN-Kubernetes, +AdminNetworkPolicy and ValidatingAdmissionPolicy and an anonymous pull of the +runtime image from inside the cluster. With [audit receipts](#audit-receipts) it +also needs a shared-filesystem (ReadWriteMany) StorageClass for the audit +exchange, and creates `saw-shared`, the class name the charts use, as a copy of +it. `pattern-install` and `make saw-create DEPLOYMENT_MODE=container|kata` run it +first. + +With receipts and no 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` only adds its `saw-shared` copy. Two +opt-ins: + +- `SAW_SHARED_STORAGE=efs` offers to create EFS on AWS (filesystem, mount + targets, security group, the AWS EFS CSI Driver Operator and StorageClass + `saw-efs`) with working `aws` credentials. +- `SAW_SHARED_STORAGE=nfs`, for development and demo clusters only, creates a + privileged NFS server Pod on a default-class volume in namespace `saw-nfs`, + the upstream NFS subdirectory provisioner (with a cluster-scoped role) and + StorageClass `saw-nfs`, then verifies a read/write mount. It is a single Pod + with no replication. + +A container entry without `ownerSubject` waits: it renders nothing and is listed +in the `saw-users-awaiting-owner` ConfigMap, so other users still sync. Set it +from `make keycloak-user-info KC_USER=` once the account exists. With +`make saw-create`, an omitted `ownerSubject` is resolved from Keycloak. + For static pattern users, put the same values under `overrides/saw-users.yaml`, enable `projection`, commit them and let the existing `saw-users` Application reconcile. Its namespace must be separate from Argo CD. VM users keep their @@ -703,77 +777,66 @@ The intent CLI accepts `--restart-generation`. When updating with including absence on legacy intents. The value ranges from zero through the intent generation and cannot decrease. -### Discover and review container egress - -The optional container topology preflight reuses the VM's API Service and ready -EndpointSlice discovery. It also reads the OpenShift DNS Service and endpoint -ports. It runs HTTPS discovery from an existing, administrator-selected Pod to -find the issuer addresses in the cluster's DNS view. Use a trusted Pod with -Python 3, the correct CA trust, DNS and HTTPS access. The caller needs read -access to those cluster resources and exec access to that Pod. The probe sends -no credentials, follows no redirects, and verifies the issuer hostname and -discovery document at every IPv4 answer. IPv6 issuer answers are unsupported. - -Keep governance, proxy and other administrator-approved rules in your base site -file. When migrating an existing site, remove the hand-maintained API, issuer -and DNS rules from the base lists first. Every base rule is preserved. A stale -address left in the base remains allowed. Configure the gateway or relay issuer -once, or omit both to discover the Keycloak host in the relay's configured -namespace with the same helper used by VM Make. The default realm is -`openshell`; set `KEYCLOAK_REALM` for another realm. Explicit gateway and relay -issuer URLs must agree. - -```sh -export SAW_USERS_VALUES_FILE="$PWD/container-users.yaml" # base values -# On a stock SAW platform, the portal generator has Python 3 and access to its issuer. -PROBE_POD=$(oc -n saw-portal get pods -l app.kubernetes.io/name=saw-workspaces-generator -o json | - jq -er '[.items[] | select(.metadata.deletionTimestamp == null and - any(.status.conditions[]?; .type == "Ready" and .status == "True"))][0].metadata.name') -export SAW_TOPOLOGY_PROBE="saw-portal/$PROBE_POD" -export SAW_TOPOLOGY_CONTAINER=generator -export SAW_TOPOLOGY_OVERLAY="$PWD/container-network.yaml" -# Set SAW_TOPOLOGY_CONTAINER if the Pod has multiple containers. -make container-topology > "$SAW_TOPOLOGY_OVERLAY.new" && - mv "$SAW_TOPOLOGY_OVERLAY.new" "$SAW_TOPOLOGY_OVERLAY" -make check-container-topology -``` - -For GitOps, commit the generated file and include it **after** the base file -in the Application's Helm value files. Generate from `containerSites` for -saw-users or `portal.containerSites` for RHDH. A base file containing both -produces both sets of overrides. Run the check against the original base file -and the committed overlay before enrollment and when DNS or API endpoints -change. A mismatch exits nonzero. Review the regenerated diff before syncing. - -For a Pattern site with both sources, store the reviewed overlay at -`overrides/container-network.yaml` and declare the value file order in the -site's cluster-group values. Preserve any other value files the site already -uses. - -```yaml -clusterGroup: - applications: - saw-users: - extraValueFiles: [/overrides/saw-users.yaml, /overrides/container-network.yaml] - openshell-rhdh: - extraValueFiles: [/overrides/saw-users.yaml, /overrides/container-network.yaml] -``` - -For standalone Make, keep the base and overlay paths for the installation. -Run the Ready Pod selection above again before each `make saw-create`, -including enrollment after the boundary review. A portal rollout can replace -the probe Pod between those steps. Check the **existing** overlay against -the current trusted Pod. Regenerate it only after reviewing a topology change. -On first -foundation apply (`automaticEnrollment.enabled: false`), Make can create the -specified overlay if absent. Later applies require the saved values to match -live discovery. Status and delete can use that file without contacting the -issuer. Keep the file per installation. Existing deployments using explicit -egress inputs can continue to use that workflow. - -Generated rules grant individual addresses and ports to the gateway and relay. -API and DNS rules also go to bootstrap and, for static sites, the projector. -Workload/supervisor policies, provider host approvals, storage and enrollment -approval still come from their existing sources. This preflight validates the -probe Pod's view; workload readiness after deployment verifies the actual -gateway path. +### Network access and storage + +Container workspaces need no cluster addresses. Each workspace namespace +starts from default-deny, and its platform pods get only what they use: + +- **Kubernetes API.** The gateway, controller, identity and enrollment Jobs, + relay and projector carry the label `saw.redhat.com/kubernetes-api: allow`. + An AdminNetworkPolicy (`saw--kubernetes-api`, and one for the + projector) lets those pods, and no sandbox pod, reach the control-plane + nodes on port 6443. Its priority (70) comes after the runtime's own + supervisor policy (51). On a hosted control plane, set + `kubernetesApi.to` to the API addresses: `[{networks: ["/32"]}]`. +- **DNS.** The cluster DNS pods, selected by label. +- **OIDC issuer.** The gateway and relay may use HTTPS (TCP 443) to any + address, because the issuer can sit behind a load balancer or an ingress + virtual IP. The issuer URL defaults to the cluster's Keycloak route + (`https://openshell-keycloak-ingress-saw-keycloak.apps./realms/openshell`); + set `stack.gateway.values.oidc.issuerUrl` and `automaticEnrollment.relay.issuer` + together for another issuer. +- **Sandboxes** keep their own fences: OpenShell's workload policy and the + runtime's supervisor AdminNetworkPolicy, which allows only the hosts the + profile approves. + +Rules you add to the egress lists (governance, a proxy) still apply; the lists +replace the defaults, so keep the DNS and HTTPS rules when you set one. + +Storage needs no configuration either: volumes use the cluster's default +StorageClass, as upstream OpenShell does. Set +`stack.gateway.values.kubernetes.storage.className` or +`stack.audit.values.storageClass` in `containerDefaults` to use another class. + +### Audit events and receipts + +By default audit is best-effort, as in upstream OpenShell. The gateway and each +sandbox's supervisor export OCSF events (authentication, refused API calls, +network and request decisions) over OTLP/gRPC to the collector in +`openshell-agents` (`charts/saw-telemetry`, Red Hat build of OpenTelemetry). +Its debug exporter writes them to the collector's log; replace it with your +SIEM or log store in `charts/saw-telemetry/values.yaml`. Set +`telemetry.ocsfEndpoint: ""` in `containerDefaults` to turn export off. +OpenShell drops events it cannot export, and nothing waits for the collector. +OpenShell 0.1.6 does not export the agent's own tool calls; those are in the +tool gate's log below. + +#### Audit receipts + +By default the agent's tool gate checks every tool call against its policy, +asks for approval where the policy says so, and appends each decision to a +best-effort log on the sandbox's own audit volume (`/sandbox/.saw/audit`), as +VM workspaces do. The agent can modify that log, and it is removed with the +workspace. + +Set `auditReceipts: true` in `containerDefaults` (or one owner's +`containerSites` entry) for signed, fail-closed receipts instead. Each +workspace then gets an audit writer in `saw-history-`, which keeps +an append-only history outside the workload, kept after the workspace is +deleted, and signs a receipt for each record. An approved tool action does not +run until its receipt arrives. The sandbox reaches the writer through a shared +(ReadWriteMany) exchange volume, named `saw-shared`: `make saw-init` creates it +as a copy of the cluster's shared-filesystem class (an existing `saw-shared` is +kept; set `stack.audit.values.exchangeStorageClass` for another class). +Changing the model at run time (`lifecycleVersion: 1`) requires receipts. +Changing `auditReceipts` changes the enrolled boundary: recreate the workspace. diff --git a/docs/container-workspaces.md b/docs/container-workspaces.md index d6d5bfb18..2dd481de3 100644 --- a/docs/container-workspaces.md +++ b/docs/container-workspaces.md @@ -44,14 +44,14 @@ 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. | -| Audit writer | Owns retained history outside the application namespace and signs acknowledgements after append. The application mounts an exchange volume, not the history PVC. | +| 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 | With `auditReceipts` only: owns retained history outside the application namespace and signs acknowledgements after append. The application mounts an exchange volume, not the history PVC. Without it, the tool gate appends to a best-effort log on the sandbox's own audit volume. | | 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. | The implementation lives in `kubernetes-runtime/` and the `saw-kubernetes-*`, @@ -103,8 +103,8 @@ not mean that a container runs the VM installer. 4. Argo creates the foundation. Enrollment verifies the approved configuration and publishes the registration binding. The generator reads only the named public publications and reprojects the values to enable runtime resources. - A new site can set `automaticEnrollment.enabled: false` to deploy its - foundation for review. Enabling enrollment requires approved reference + A new site deploys only its foundation for review until it sets + `automaticEnrollment.enabled: true`. Enabling enrollment requires approved reference hashes; discovery is not approval. 5. The reconciler requires a coherent BOM digest and intent generation, checks namespace/PVC UIDs and the live boundary, and then calls the gateway. It @@ -121,7 +121,7 @@ sequenceDiagram participant Gateway as OpenShell gateway participant Pod as Workload Git->>Argo: Approved profile + site + desired registration - Argo->>Argo: Identity, network, proxy, gateway, PVCs, BOM + Argo->>Argo: Identity, network, gateway, PVCs, BOM Argo->>Enroll: Pinned bootstrap inputs Enroll->>Enroll: Check approved boundary and ownership Enroll->>Project: Immutable binding: UIDs, hashes, public keys @@ -144,8 +144,16 @@ Policies protect different boundaries: - **OpenShift admission and network policy** constrain Pod roles, service accounts, placement and network reachability. A reconciler's permission to call the gateway does not bypass these controls. -- **Credential-proxy policy** derives from the same provider catalog and Helm - helper used by VM mode; credentials are not copied into application Pods. +- **Provider credentials** follow OpenShell's provider model: the platform + provider profiles the gateway serves (shipped or published by the governance + interceptor) decide where each credential may be used, and the supervisor + enforces it. The agent Pod never receives a credential, only a placeholder. + Supervisors may reach public HTTPS (`network.publicHTTPS`). Before creating a + credentialed provider, the runtime controller requires the live profile's + endpoints to be exactly the approved set, all in enforce mode: the governed + profile shipped with the runtime image, or for `custom-inference` only the + workspace's `customInferenceURL` host on 443. Otherwise it stops with + `ProviderProfileMismatch`. - **Tool-action policy** uses the same `tool-actions.yaml`, decision engine and OpenClaw hook as VM mode. The Kubernetes adapter changes storage and audit transport, not the decision rules. @@ -224,11 +232,12 @@ flowchart LR Login --> Relay[Scoped relay / OpenShell forward] Relay --> Gateway[Gateway and supervisor] Gateway --> Agent[Agent / OpenClaw] - Agent -->|Provider marker| Proxy[Trusted credential proxy] + Agent -->|Placeholder| Supervisor[OpenShell supervisor Pod] Vault[Vault] --> ESO[External Secrets] ESO --> Secrets[Trusted-namespace Secrets] - Secrets --> Proxy - Proxy -->|Real credential| Provider[Approved inference / tool API] + Secrets -->|Reconciler, on create or rotation| Gateway[OpenShell gateway credential store] + Gateway --> Supervisor + Supervisor -->|Real credential, profile endpoints only| Provider[Approved inference / tool API] Agent --> Gate[Shared tool gate] Gate --> Exchange[Audit exchange PVC] Exchange --> Writer[Restricted forwarder and writer] @@ -252,14 +261,18 @@ 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 that restore configurations missing metadata. It uses synthetic credentials in temporary state and sends no inference requests. +By default the gate appends each decision to a best-effort log on the sandbox's +own audit volume, which the agent can modify. The rest of this section describes +`auditReceipts: true` ([Audit receipts](container-installation.md#audit-receipts)). + The application receives its writable workspace, a read-only prepared gate and optional harness, and an audit exchange. The writer's history and signing key remain outside its mounts. A missing/invalid acknowledgement blocks the gated diff --git a/docs/custom-inference.md b/docs/custom-inference.md index 049ab7d47..696436dc1 100644 --- a/docs/custom-inference.md +++ b/docs/custom-inference.md @@ -146,6 +146,14 @@ stated (`openai`): the installer cannot infer it for a profile of your own. Custom keyed ports and in-cluster service-CA trust are follow-up work. - `inferenceTimeout` on a provider is no longer used: there is no gateway router to time out. Use the sandbox's `inference.timeoutSeconds`. +- OpenClaw offers only `default` and `off` thinking for a custom model. Set + the sandbox's `inference.thinking` (`off`, `minimal`, `low`, `medium` or + `high`) to make that level the model's default. Any level but `off` also + marks the model as a reasoning model accepting `low`, `medium` and `high`, + which OpenClaw sends as `reasoning_effort`; the endpoint may ignore it. + `off` marks it `reasoning: false` instead (like `MODEL_REASONING=false`); an + unquoted YAML `off` (read as `false`) also means off. A + chat's `/think` still overrides the default. VM workspaces only for now. ### Keycloak compatibility diff --git a/docs/deployment-guide.md b/docs/deployment-guide.md index da00b74ba..31336aadc 100644 --- a/docs/deployment-guide.md +++ b/docs/deployment-guide.md @@ -799,3 +799,162 @@ cleanup after switching to direct; returning to proxy requires provider-key rotation and a `credentialProxy.keyGeneration` increase. Follow the exact [mode-switch instructions](credential-isolation.md#switching-modes), including the Helm-only `cleanupOnDelete=false` firewall caveat. + +## Make target reference + +Targets renamed in earlier releases. The old names remain as aliases for one release. Each alias prints its +replacement. Use `make help` to see all commands. + +| Previous target | Current target | +|---|---| +| `check-prereqs` | `prereqs-check` | +| `generate-keys` | `ssh-key-generate` | +| `build-nemoclaw` | `sandbox-build` | +| `build-nemoclaw-cli` | `cli-build` | +| `build-gateway-podman` | `gateway-build-podman` | +| `build-gateway-docker` | `gateway-build-docker` | +| `build-governance-interceptor` | `governance-interceptor-build` | +| `build-governance-interceptor-local` | `governance-interceptor-build-local` | +| `copy-images` | `images-mirror` | +| `keycloak` | `keycloak-deploy` | +| `delete-keycloak` | `keycloak-delete` | +| `delete-all` | `quickstart-delete` | +| `openshell-saw-create` | `saw-create` | +| `openshell-saw-configure-gateway` | `saw-configure` | +| `openshell-saw-list` | `saw-list` | +| `openshell-saw-logs` | `saw-logs` | +| `openshell-saw-status` | `saw-status` | +| `openshell-saw-vm-ssh` | `saw-vm-ssh` | +| `openshell-saw-restart` | `saw-restart` | +| `openshell-saw-ssh` | `saw-ssh` | +| `openshell-saw-tui` | `saw-tui` | +| `openshell-saw-gui` | `saw-gui` | +| `openshell-saw-delete` | `saw-delete` | +| `governance-list-profiles` | `governance-profile-list` | +| `governance-add-profile` | `governance-profile-add` | +| `governance-remove-profile` | `governance-profile-remove` | +| `governance-create-profile` | `governance-profile-create` | + +`make gateway-build` selects Podman by default. Set +`CONTAINER_RUNTIME=docker` for Docker. Other values fail before a build starts. +`make pattern-uninstall` calls the standard `uninstall` target. The old +`ssh-secret` target is gone. The chart creates a public key Secret for each +SAW, and `saw-vm-ssh` updates it when needed. + +`saw-create`, `saw-delete`, `saw-status`, `saw-logs`, `saw-configure`, and +user access targets require `OPENSHELL_SAW_NAME`. `saw-list`, `status`, and +`governance-profile-list` work without it. The defaults are `NS=openshell-agents`, +`BUILD_NS=openshell-agents`, `KEYCLOAK_NS=saw-keycloak`, and +`SAW_NS=saw-$OPENSHELL_SAW_NAME`. Manual builds stay in-cluster by default. To push, explicitly set +`IMAGE_REPO` to your own namespace and `IMAGE_TAG` as needed; the upstream +CI namespace is refused. For `saw-create`, set `PROVIDER`, `MODEL`, and +`API_KEY` in the environment for keyed providers; `OWNER` and `OWNER_SUBJECT` select another owner. The chart defaults to the published proxy image. Optionally set `CREDENTIAL_PROXY_IMAGE`, or `credentialProxy.image` through `SAW_VALUES_FILE`, to a digest-pinned mirror or custom build. A new inference Secret needs `PROVIDER` and `MODEL`; `API_KEY` may be empty for a keyless provider. A repeat `saw-create` keeps an existing inference Secret when `API_KEY` is empty. + +`IMAGE_TAG=latest` selects the CI-built gateway disk used by `images-mirror`; +`IMAGE_TAG=sha-` selects a particular CI build. The chart's in-VM BOM +separately pins OpenShell `0.1.10-rhaiv.0` by digest. See +[the deployment guide](docs/deployment-guide.md#golden-image-tag). + +If a prerequisite fails, inspect the reported CLI or operator and run +`make prereqs-check` again. That check does not change the cluster. +`make images-mirror` enables the registry route and stops on access errors. +CI image names, tags, public pull checks, and retained upstream Quay dependencies +are documented in [Container images](docs/container-images.md). +`make ssh-key-generate` and `make keycloak-deploy` keep existing keys and +passwords. If a GUI port is in use, choose another `GUI_PORT`; the command +will not stop the other process. + +## Uninstall and reinstall + +For a clean reinstall, retire workspaces while the portal, Keycloak and Argo +are available. Use the RHDH **Delete my agent workspace** template for portal owners, +remove static owners through Git with `pruneOnRemove: true`, and run +`make saw-delete` with the original site inputs for standalone installations. +Wait for each workspace Application and runtime namespace to disappear before +uninstalling the platform. RHDH preserves generated Applications when its +ApplicationSet disappears. A successful platform uninstall alone can therefore +leave a workspace running. Container audit history is retained separately. + +```bash +make saw-delete # one quickstart workspace +make keycloak-delete # quickstart Keycloak and PostgreSQL +make quickstart-delete # quickstart Keycloak and image releases +./pattern.sh make pattern-uninstall +``` + +A full SAW uninstall first drains the Pattern-owned `openshell-rhdh` and +`saw-users` Applications. The command sets their clustergroup `disabled` +overrides on the Pattern and waits for Argo to mark each child for pruning. +It terminates any active sync and waits for foreground deletion before +the framework removes operators and webhooks. The VM cleanup runs after this +drain so a reconciling SAW Application cannot recreate a VM during teardown. +If the drain fails, correct +the reported problem and rerun `pattern-uninstall`. Those two overrides +persist on the Pattern until uninstall completes. + +To qualify a fresh RHDH-enabled installation, run the first check on the +clean cluster and the second after installing with the configured site inputs: + +```bash +scripts/check-rhdh-bootstrap.sh before +./pattern.sh make install +scripts/check-rhdh-bootstrap.sh after +``` + +ESO creates `rhdh/rhdh-oidc` from Vault before the Keycloak client hook can +start. The hook requires that Secret and has a 15-minute execution deadline. +The check requires the completed Job, a Synced/Healthy RHDH Application, and +a ready rollout of the actual Backstage Deployment. On a cold start, dynamic +plugins can still be installing when Argo reports Healthy. The portal Deployment +has a 30-minute rollout deadline and retains the operator’s startup health +endpoint with a larger failure budget for a cold backend. The check waits up +to 30 minutes for Deployment availability. Set `RHDH_NAME` if the Backstage +resource has a site-specific name. Verify owner sign-in and workspace creation +through the portal separately. After changing owner enrollment, wait until the +RHDH catalog offers the intended deployment mode and profile before submitting +a create request. Catalog ingestion can finish after the Deployment rollout. + +On busy clusters, use a site value to reserve CPU for the framework's +imperative Jobs during cold bootstrap. For example, add this to +`values-cluster-.yaml` and size the requests for available nodes: + +```yaml +clusterGroup: + extraObjects: + bootstrap-resources: + apiVersion: v1 + kind: LimitRange + metadata: + name: bootstrap-requests + namespace: imperative + spec: + limits: + - type: Container + defaultRequest: + cpu: "1" + memory: 256Mi +``` + +Check `oc -n imperative get pods,limitrange` and the admitted unseal Pod's +`spec.initContainers[].resources.requests`. In clustergroup 0.9.58 the stock +unseal playbook has a 600-second timeout. Exit 124 followed by HTTP 403 +creating the Vault secrets engine can indicate an interruption after unseal +and before the stock CLI login. In that state the RHDH ExternalSecret stays +unready. A CPU reservation can reduce contention. It cannot recover an +already interrupted bootstrap. [Stock Job](https://github.com/validatedpatterns/clustergroup-chart/blob/v0.9.58/templates/imperative/unsealjob.yaml), +[stock Vault role](https://github.com/validatedpatterns/rhvp.cluster_utils/blob/6aec8c6d50/roles/vault_utils/tasks/vault_unseal.yaml). + +A reinstall also depends on OpenShift Virtualization cleanup. Uninstall waits +up to one hour for the Pattern-owned `openshift-cnv` namespace to disappear +before checking whether its marked HyperConverged CRD is unused. A timeout +returns an error. Check namespace termination, then rerun +`./pattern.sh make pattern-uninstall` before installing again. A retained +CRD can point OLM at a conversion webhook that no longer exists. + +When switching from an OperatorHub Quickstart to a clean Pattern test, confirm +that both the test CNV namespace and its HyperConverged CRD are absent. A CSV +uninstall can leave the CRD behind. On Pattern teardown, the cleanup command +reads HyperConverged objects through the CRD's served storage version. This +allows it to remove the tracked SAW instance even after the conversion service +disappears. It checks for other instances and subscriptions before deleting +the marked CRD. diff --git a/docs/governance-interceptor.md b/docs/governance-interceptor.md index f2df6a303..d27c9d851 100644 --- a/docs/governance-interceptor.md +++ b/docs/governance-interceptor.md @@ -186,23 +186,23 @@ rpc = "openshell.v1.OpenShell/CreateProvider" phases = ["validate"] ``` -The interceptor must be built from the same OpenShell release as the gateways (0.1.x negotiates `PeerMetadata`), and for 0.1.6 it carries a two-line patch for [NVIDIA/OpenShell#3929](https://github.com/NVIDIA/OpenShell/issues/3929): it keeps only the profile-signature annotation, because the gateway hashes profiles with more than one annotation non-deterministically and no sandbox with a provider becomes ready. See `image-builder-charts/helm/governance-interceptor-image/files/Dockerfile`. +The interceptor must be built from the same OpenShell release as the gateways (0.1.x negotiates `PeerMetadata`), and for 0.1.x (0.1.10 included) it carries a two-line patch for [NVIDIA/OpenShell#3929](https://github.com/NVIDIA/OpenShell/issues/3929): it keeps only the profile-signature annotation, because the gateway hashes profiles with more than one annotation non-deterministically and no sandbox with a provider becomes ready. See `image-builder-charts/helm/governance-interceptor-image/files/Dockerfile`. The `binding_policy = "allowlist"` means only the explicitly listed RPCs are intercepted. The `failure_policy = "fail_closed"` means if the interceptor is unreachable, all intercepted operations are denied. ## Tool actions -The interceptor above does not see a tool call. OpenShell 0.1.6 only forwards allowlisted control-plane RPCs (`CreateSandbox`, `CreateProvider`, `UpdateConfig`, `SubmitPolicyAnalysis`), and its timeout is too short for a person to approve something. Agent tool calls run inside the sandbox. +The interceptor above does not see a tool call. The gateway only forwards the RPCs bound in its configuration (`CreateSandbox`, `CreateProvider`, `UpdateConfig`, `SubmitPolicyAnalysis`), and its timeout is too short for a person to approve something. Agent tool calls run inside the sandbox. `charts/governance-policy/tool-actions.yaml` is the tool policy (`allow`, `deny`, or `approval` per tool; `whenCommandMatches` narrows `exec`). The installer disk carries an identical copy. `saw-apply` fills a `saw-gate-*` podman volume on the host with this policy, the signed-in identity (`username` from `accessControl.owner`, `subject` from the resolved `ownerSubject`), and the plugin tree. Every OpenClaw and NemoClaw sandbox mounts it read-only at `/sandbox/.saw/trusted`. A generic toolbox sandbox gets no gate. OpenClaw loads `saw-tool-gate` from `/sandbox/.saw/trusted/plugin` through `plugins.load.paths`. The installer appends it to a restrictive `plugins.allow`, enables it, and verifies that OpenClaw reports it loaded from the trusted mount. Each policy read is hashed against a SHA-256 constant embedded in the mounted plugin. A mismatch denies the call with rule `policy-hash`. - The default action is `deny`. The explicit read-only allowlist covers `read`, memory reads, session inspection, and `exec` for `git status`, `git diff`, `git log`, and `git show`. `message`, `git push`, `gh pr merge`, `rm`, `kubectl delete`, and `oc delete` require approval. Unknown tools deny. -- The daily briefing allows exactly `slack-reader__new_messages`, `slack-reader__channels`, `gmail-reader__new_messages`, and `briefing-writer__save_briefing`. The writer saves only today's briefing; generic `write` stays denied. `exec` for `openclaw cron list` is allowed, while `openclaw cron add` and `openclaw cron rm` require approval. Scheduled updates use only the allowed readers and writer. +- The daily briefing allows exactly `slack-reader__new_messages`, `slack-reader__channels`, `gmail-reader__new_messages`, and `briefing-writer__save_briefing`. The writer saves only today's briefing; generic `write` stays denied. `exec` for `openclaw cron list` is allowed, as are `--help` and ` --help`, while `openclaw cron add`/`create`, `edit`, `rm`/`remove`/`delete`, `enable`, `disable` and `run` require approval (`openclaw automations` is the same). That card also offers **Allow always**: later automation changes then run without asking until the gateway restarts or the policy changes, and each is still audited (`approval.mode: remembered`). No other approval rule offers it. Scheduled updates use only the allowed readers and writer. - `openclaw agents set-identity` always requires approval. Its identity-file and avatar arguments can read outside the workspace or fetch remote content, and it rewrites `openclaw.json`; `tools.fs.workspaceOnly` does not constrain this CLI command. Denial, cancellation and timeout block execution. - `tool_search` and `tool_call` are allowed for discovery and dispatch. Live testing on OpenClaw 2026.9.2 (`3928bad`) with only these dispatcher rules produced separate `default`/`deny` audit records for `slack-reader__new_messages` and `gmail-reader__new_messages`. Every dispatched target therefore still needs its own rule. Recheck that behavior when upgrading OpenClaw; do not allow a dispatcher that bypasses target hooks. -- `exec` matches the command at its start after normalizing whitespace, leading assignments, and the executable basename. Empty commands deny as `exec-unreadable`; shell operators and opaque wrappers such as `sh -c` deny as `exec-opaque`. +- `exec` matches the command at its start after normalizing whitespace, leading assignments, and the executable basename. Empty commands deny as `exec-unreadable`; shell operators and opaque wrappers such as `sh -c` deny as `exec-opaque`. A trailing `2>&1` is ignored. Each denial tells the agent how to retry (one command per call), or that an unlisted command should not be retried in another form; an unlisted command also lists the accepted commands that start with the same two words, such as `openclaw automations`. - Every call appends one JSON line to `/sandbox/.saw/audit/tool-actions.jsonl`, a separate `saw-audit-*` volume. The directory is not writable by the sandbox user, and the log file is append-only (`chattr +a`). The same line goes to gateway stderr for `podman logs`. Each line includes the user, OpenClaw session task id, `policyHash`, rule, and decision. An optional `/sandbox/.saw/current-task.json` `title` is copied onto that record. - `allow` runs the tool after the audit append succeeds. - `deny` blocks it. diff --git a/docs/harness-bundles.md b/docs/harness-bundles.md index 09565e5e9..aa27b908a 100644 --- a/docs/harness-bundles.md +++ b/docs/harness-bundles.md @@ -191,6 +191,33 @@ in-cluster MCP services should use `credentialFree: true`, or expose keyed services through an HTTPS Route on port 443. HTTPS to a `.svc` host on another port is refused. Add any in-cluster peer to the proxy's NetworkPolicy too. +#### Tool actions for the bundle's MCP tools + +SAW's tool gate refuses any tool its policy does not name. A bundle names +what the gate may do with its own MCP tools, next to the server that +provides them: + +```yaml +spec: + mcpServers: + - name: mailpit_reader + governanceProfile: mailpit + tools: + - {name: saw_read_email, action: allow} # or approval +``` + +Each entry becomes a gate rule for `__`, the name OpenClaw +gives an MCP tool, and OpenClaw's tool allowlist gets the same tools. A +bundle can only name tools of servers in its own `mcp.json`, and only +`allow` or `approval`; it cannot change built-in tools such as `exec` or +another bundle's tools. The rules follow the base `tool-actions.yaml`, so +where the base policy names the same tool, the base rule decides. They are +part of the gate policy whose hash the gate checks, so changing them changes +the bundle digest and the gate, like any other edit to the bundle. + +Container workspaces apply these rules today. VM workspaces still take their +tool actions from the base `tool-actions.yaml` only. + ### Tool plugins (`plugins//`) Plain ES modules (`.mjs`, or `.js` with `"type": "module"`), self-contained: diff --git a/docs/kata-workspaces.md b/docs/kata-workspaces.md index cc87a4f31..a34e6194a 100644 --- a/docs/kata-workspaces.md +++ b/docs/kata-workspaces.md @@ -1,8 +1,11 @@ # Kata workspace qualification Kata is under private qualification. The application workload Pod uses the -stock OpenShell Kubernetes driver and a local Kata RuntimeClass. The gateway -and separate supervisor run as ordinary Pods. Each data-science slot is a +stock OpenShell Kubernetes driver and a local Kata RuntimeClass. Its separate +supervisor Pod runs in the same RuntimeClass, so every sandbox is two Kata VMs: +the supervisor, which handles the agent's network traffic and credentials, never +shares the workload's guest kernel (OpenShell 0.1.10 and later, +`supervisor_runtime_class_name`). The gateway runs as an ordinary Pod. Each data-science slot is a separate workload Pod. The workspace BOM, images, storage, credential routing, relay and audit flows are shared with container workspaces. @@ -11,10 +14,21 @@ relay and audit flows are shared with container workspaces. On 2026-11-17, one RHDH data-science Kata canary completed. Both workload Pods were Ready with the Kata RuntimeClass. Each Pod mapped to a different host QEMU process. The gateway and both supervisors used the default runtime. -Both owner chat links returned fresh model replies. This result does not yet -cover tool allow and deny rules, network denial, secret isolation, audit, -persistence, restart, stop/start, deletion, GitOps, Make, a container -regression, or two active owners. Keep the PR in draft until these checks pass. +Both owner chat links returned fresh model replies. + +On 2026-11-25, on OpenShell 0.1.10, a GitOps-deployed Kata workspace (a +custom-inference user bound to `saw-kata` automatically) passed +`make e2e-workspace DEPLOYMENT_MODE=kata`, next to a container workspace on +the same cluster: Argo CD healthy; the workload and the supervisor each in +`saw-kata`, so two VMs; a real model turn through the custom inference +endpoint; the tool gate denying and recording an `exec`; and OCSF events at +the pattern's collector. Removing and recreating both workspaces through GitOps +also worked. + +Not yet covered: network denial and secret isolation tests, persistence across +a Pod restart, stop/start, VM-mode regression, two simultaneous Kata owners on +one worker, and the self-service portal's Kata path (it still needs an +explicit RuntimeClass binding). ## Check worker KVM access before installing OSC @@ -41,12 +55,24 @@ before installing OSC. Creating a KataConfig can reboot workers. ## Prepare OpenShift sandboxed containers -The qualification cluster installed the Red Hat OpenShift sandboxed containers -Operator from OperatorHub in `openshift-sandboxed-containers-operator`. A GitOps -installation uses a Namespace, an OperatorGroup scoped to that namespace, and a -Subscription from `redhat-operators`. Select the channel supported by the -cluster. Keep these platform resources outside the SAW workspace charts. Check -that the Subscription has an installed CSV and that the CSV is `Succeeded`. +The pattern installs the Red Hat OpenShift sandboxed containers Operator in +`openshift-sandboxed-containers-operator` (`values-prod.yaml`: a Namespace, an +OperatorGroup scoped to it, and a Subscription from `redhat-operators` on the +`stable` channel). The operator alone changes no node. Check that the +Subscription has an installed CSV and that the CSV is `Succeeded`. + +The `saw-kata` application (`charts/saw-kata`) creates the KataConfig below +when enabled, selecting plain workers only (never control-plane nodes, even +where they are schedulable). It is off by default because it reboots the +selected nodes. Enable it per cluster with an override on that application: + +```yaml +clusterGroup: + applications: + saw-kata: + overrides: + - {name: enabled, value: "true"} +``` See the [Red Hat installation procedure](https://docs.redhat.com/en/documentation/openshift_sandboxed_containers/1.12/html/deploying_openshift_sandboxed_containers_on_bare-metal_servers/install-osc-overview_metal-osc). Install the local Kata runtime on an approved worker pool with a platform-owned @@ -68,11 +94,20 @@ spec: Wait for the selected nodes to complete their machine config updates and reboots. Check `oc get kataconfig`, `oc get mcp`, and -`oc get runtimeclass kata -o yaml`. The operator creates the `kata` class. SAW -uses a reviewed RuntimeClass YAML with the live handler, scheduling and overhead -fields. Bind that class's name, UID and placement digest in the site YAML below. -The class also needs `openshell.ai/sandbox-attachable=true`. Keep the class and -the owner approval under platform control. +`oc get runtimeclass kata saw-kata -o yaml`. The operator creates the `kata` +class. The `saw-kata` application also creates `saw-kata`, a copy of it (same +handler, pod overhead and `kata-oc` node selector) that carries the +`openshell.ai/sandbox-attachable=true` label OpenShell requires, so nobody +labels the operator's class by hand. + +Kata users run in `saw-kata` unless their site names another class +(`kata.runtimeClassName` in saw-users changes the default). On an +`autoApprove` site the workspace projector binds the user to that class's live +UID and placement digest when it first projects the workspace, after the same +checks a reviewed binding gets (Kata handler, attachable label, a node +selector); enrollment then fails closed if the class is later replaced or its +placement changes. A reviewed site binds the class explicitly, as shown in +[Standalone workspace on an existing Kata pool](#standalone-workspace-on-an-existing-kata-pool). ## Verify a deployed worker @@ -108,14 +143,14 @@ containing `handler`, `overhead` and `scheduling`. Missing optional fields hash as JSON null. The controller checks UID, the stock OpenShell attachable label, the `kata` handler and the placement digest before attaching resources. Ordinary container plans retain their original representation. The gateway reads only -the selected class, and the admission policies require that class on both the -Sandbox template and the workload Pod. The supervisor keeps the default -runtime. The portal advertises Kata only when the platform administrator enables the +the selected class, and the admission policies require that class on the +Sandbox template, the workload Pod and the supervisor Pod. The controller also +refuses a gateway whose configuration does not place the supervisor in it. The portal advertises Kata only when the platform administrator enables the mode and supplies a reviewed site class and approved profile. ### Allow time for Kata startup -OpenShell 0.1.6 uses 300-second startup windows by default. Kata VM startup can +OpenShell 0.1.10 uses 300-second startup windows by default. Kata VM startup can take longer. In Kata mode, the Kubernetes gateway chart sets the provisioning repair window, runtime bootstrap grace period and sandbox attach request timeout to 900 seconds. Set `kubernetes.startupTimeouts` to adjust these values. Each @@ -254,7 +289,9 @@ containerSites: sha256: ``` -Manage the class in platform GitOps. The class name used by OpenShell must have +A reviewed site (no `autoApprove`) must carry this binding; an `autoApprove` +site may leave out `uid` and `sha256` and the projector fills them from the +live class. Manage the class in platform GitOps. The class name used by OpenShell must have the label `openshell.ai/sandbox-attachable=true`. If you define a separate class for workspaces, copy the OSC class's handler, overhead and scheduling constraints when defining it. Inspect the live object before approving it. @@ -277,7 +314,8 @@ controller drive both slots through the stock gateway. For each slot, inspect the workload Pod's runtime class, UID, SCC, node and Ready condition. Match its UID to the host-side Kata handler as above. Verify -the associated supervisor Pod uses the default runtime. Finally sign in as the +the associated supervisor Pod uses the same Kata RuntimeClass and maps to its +own QEMU process. Finally sign in as the owner and send a fresh challenge through each slot's browser relay. Record the observed text independently for each slot. The CUDA slot name identifies a profile entry; this test exercises chat and does not qualify GPU passthrough. diff --git a/docs/openshell-016-release.md b/docs/openshell-016-release.md index 9a7c52d9e..09e3745bd 100644 --- a/docs/openshell-016-release.md +++ b/docs/openshell-016-release.md @@ -81,8 +81,9 @@ remove it to bypass recovery. A configured agent can resume without a usable provider while retaining its model/credentials; unchanged reapply leaves it running. In OpenClaw 2026.9.6, `automations` aliases `cron`. Only `list`, `status`, `get`, -`show` and `runs` need no approval; `add`, `edit`, `rm`, `enable`, `disable` and -`run` require it. Unsupported aliases, mixed read/write `scratch`, unknown +`show` and `runs` need no approval; `add`/`create`, `edit`, `rm`, `enable`, +`disable` and `run` require it. Unsupported aliases (`remove`, `delete`), mixed +read/write `scratch`, unknown commands and shell wrappers remain denied. Every `agents set-identity` call requires approval: its file/avatar inputs can reach outside the workspace and it rewrites configuration, beyond filesystem-tool confinement. Denial, diff --git a/docs/personal-assistant.md b/docs/personal-assistant.md index 881c84250..f7a6f3d26 100644 --- a/docs/personal-assistant.md +++ b/docs/personal-assistant.md @@ -4,7 +4,7 @@ The `personal-assistant` profile creates a NemoClaw sandbox with the `daily-briefing` harness enabled. It reads Slack and Gmail and saves a briefing under `/sandbox/briefing//briefing.md`. -Deploy with README [Option A: Validated Pattern](../README.md#option-a-validated-pattern-automated-gitops). +Deploy with README [Installation](../README.md#installation). The chart defaults to the published, digest-pinned credential proxy image; override it only for a mirror or custom build (see [container images](container-images.md)). Create the portal user's Keycloak account before signing in: @@ -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) From 51edb9106791918527b7b5e684fb7f05beb72851 Mon Sep 17 00:00:00 2001 From: mtalvi Date: Wed, 25 Nov 2026 12:22:11 +0200 Subject: [PATCH 6/9] ci: validate the saw-kata KataConfig against a vendored OSC schema Co-Authored-By: Claude Opus 5.5 --- docs/deployment-validation-ci.md | 1 + .../kataconfig_v1.json | 169 ++++++++++++++++++ scripts/ci/vendor_crd_schemas.py | 1 + .../scripts/test_deployment_validation_ci.py | 1 + 4 files changed, 172 insertions(+) create mode 100644 scripts/ci/schemas/kataconfiguration.openshift.io/kataconfig_v1.json diff --git a/docs/deployment-validation-ci.md b/docs/deployment-validation-ci.md index fbd7b666c..aa856a09e 100644 --- a/docs/deployment-validation-ci.md +++ b/docs/deployment-validation-ci.md @@ -163,5 +163,6 @@ served OpenAPI v3 schemas from their CRD files: - [RHDH Backstage CRD](https://github.com/redhat-developer/rhdh-operator/blob/82b4a840d12c06abb771bc6957b365c245477667/config/crd/bases/rhdh.redhat.com_backstages.yaml) - [HyperConverged CRD](https://github.com/kubevirt/hyperconverged-cluster-operator/blob/37b709d5d9400d47dc03f96fef5f6ac21dc70f8f/config/crd/bases/hco.kubevirt.io_hyperconvergeds.yaml) +- [KataConfig CRD](https://github.com/openshift/sandboxed-containers-operator/blob/891eadc9fa270c38b1d7040d05675636990058b8/config/crd/bases/kataconfiguration.openshift.io_kataconfigs.yaml) - [Tekton Pipeline CRD](https://github.com/tektoncd/pipeline/blob/592dfb840f02a0e9e2920f75b1737372ceb17c15/config/300-crds/300-pipeline.yaml) - [Tekton Task CRD](https://github.com/tektoncd/pipeline/blob/592dfb840f02a0e9e2920f75b1737372ceb17c15/config/300-crds/300-task.yaml) diff --git a/scripts/ci/schemas/kataconfiguration.openshift.io/kataconfig_v1.json b/scripts/ci/schemas/kataconfiguration.openshift.io/kataconfig_v1.json new file mode 100644 index 000000000..b7e76f95f --- /dev/null +++ b/scripts/ci/schemas/kataconfiguration.openshift.io/kataconfig_v1.json @@ -0,0 +1,169 @@ +{ + "properties": { + "apiVersion": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "metadata": { + "type": "object" + }, + "spec": { + "nullable": true, + "properties": { + "checkNodeEligibility": { + "type": "boolean" + }, + "enablePeerPods": { + "type": "boolean" + }, + "kataConfigPoolSelector": { + "nullable": true, + "properties": { + "matchExpressions": { + "items": { + "properties": { + "key": { + "type": "string" + }, + "operator": { + "type": "string" + }, + "values": { + "items": { + "type": "string" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + } + }, + "required": [ + "key", + "operator" + ], + "type": "object" + }, + "type": "array", + "x-kubernetes-list-type": "atomic" + }, + "matchLabels": { + "additionalProperties": { + "type": "string" + }, + "type": "object" + } + }, + "type": "object", + "x-kubernetes-map-type": "atomic" + }, + "logLevel": { + "type": "string" + } + }, + "required": [ + "checkNodeEligibility" + ], + "type": "object" + }, + "status": { + "properties": { + "conditions": { + "items": { + "properties": { + "lastTransitionTime": { + "format": "date-time", + "type": "string" + }, + "message": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "status": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": [ + "lastTransitionTime", + "message", + "reason", + "status", + "type" + ], + "type": "object" + }, + "type": "array" + }, + "kataNodes": { + "properties": { + "failedToInstall": { + "items": { + "type": "string" + }, + "type": "array" + }, + "failedToUninstall": { + "items": { + "type": "string" + }, + "type": "array" + }, + "installed": { + "items": { + "type": "string" + }, + "type": "array" + }, + "installing": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodeCount": { + "type": "integer" + }, + "readyNodeCount": { + "type": "integer" + }, + "uninstalling": { + "items": { + "type": "string" + }, + "type": "array" + }, + "waitingToInstall": { + "items": { + "type": "string" + }, + "type": "array" + }, + "waitingToUninstall": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + }, + "runtimeClasses": { + "items": { + "type": "string" + }, + "type": "array" + }, + "waitingForMcoToStart": { + "type": "boolean" + } + }, + "type": "object" + } + }, + "type": "object" +} diff --git a/scripts/ci/vendor_crd_schemas.py b/scripts/ci/vendor_crd_schemas.py index 9acd7b788..e47fd5697 100644 --- a/scripts/ci/vendor_crd_schemas.py +++ b/scripts/ci/vendor_crd_schemas.py @@ -8,6 +8,7 @@ import yaml TARGETS = { + ("kataconfiguration.openshift.io", "KataConfig"): "v1", ("rhdh.redhat.com", "Backstage"): "v1alpha5", ("hco.kubevirt.io", "HyperConverged"): "v1beta1", ("tekton.dev", "Pipeline"): "v1", diff --git a/tests/scripts/test_deployment_validation_ci.py b/tests/scripts/test_deployment_validation_ci.py index 9ceb1d069..91b7cf0fa 100644 --- a/tests/scripts/test_deployment_validation_ci.py +++ b/tests/scripts/test_deployment_validation_ci.py @@ -38,6 +38,7 @@ def test_vendored_schemas_have_no_upstream_sample_data(): def test_vendored_crd_schema_names_match_kubeconform_lookup(): expected = ( + ("kataconfiguration.openshift.io", "kataconfig_v1.json"), ("rhdh.redhat.com", "backstage_v1alpha5.json"), ("hco.kubevirt.io", "hyperconverged_v1beta1.json"), ("tekton.dev", "pipeline_v1.json"), From 561499dc6f34e0abc32af35c1551d8f8b8086cef Mon Sep 17 00:00:00 2001 From: mtalvi Date: Wed, 25 Nov 2026 12:22:51 +0200 Subject: [PATCH 7/9] ci: align NemoClaw's ca-certificates pin with Debian trixie Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build-nemoclaw-sandbox.yml | 22 +++++++++---------- tests/charts/test_nemoclaw_image_build.py | 23 +++++++++++++++----- 2 files changed, 27 insertions(+), 18 deletions(-) diff --git a/.github/workflows/build-nemoclaw-sandbox.yml b/.github/workflows/build-nemoclaw-sandbox.yml index 4296869ae..64463e34d 100644 --- a/.github/workflows/build-nemoclaw-sandbox.yml +++ b/.github/workflows/build-nemoclaw-sandbox.yml @@ -94,20 +94,18 @@ jobs: git checkout -q FETCH_HEAD echo "UPSTREAM_DIR=${UPSTREAM_DIR}" >> "${GITHUB_ENV}" - # NemoClaw v0.0.133 pins curl 8.14.1-2+deb13u5, but trixie-security now - # ships libcurl4t64 deb13u7, so apt cannot resolve the pair on a cold - # build cache. Apply NVIDIA/NemoClaw#13158 (released in v0.0.135); drop - # this step once source.git.ref is v0.0.135 or later. - - name: Align upstream curl pin with Debian security + # NemoClaw f4de239 and v0.0.133-v0.0.140 pin ca-certificates=20250419, + # which trixie replaced with 20250419+deb13u1. v0.0.133 also pins curl + # deb13u5, while trixie-security's libcurl4t64 requires deb13u7. + # Drop this step once source.git.ref pins ca-certificates=20250419+deb13u1 + # and the matching curl version (NVIDIA/NemoClaw#13158). + - name: Align upstream Debian package pins with Debian security run: | dockerfile="${UPSTREAM_DIR}/Dockerfile" - if grep -qF 'curl=8.14.1-2+deb13u5' "${dockerfile}"; then - sed 's/curl=8\.14\.1-2+deb13u5/curl=8.14.1-2+deb13u7/g' "${dockerfile}" > "${dockerfile}.saw" - mv "${dockerfile}.saw" "${dockerfile}" - grep -nF 'curl=8.14.1-2+deb13u7' "${dockerfile}" - else - echo "::notice::NemoClaw no longer pins curl deb13u5; drop this step." - fi + sed -e 's/curl=8\.14\.1-2+deb13u5/curl=8.14.1-2+deb13u7/g' \ + -e 's/ca-certificates=20250419\([[:space:]]\)/ca-certificates=20250419+deb13u1\1/g' \ + "${dockerfile}" > "${dockerfile}.saw" + mv "${dockerfile}.saw" "${dockerfile}" - name: Inject reviewed runtimes into build context run: | diff --git a/tests/charts/test_nemoclaw_image_build.py b/tests/charts/test_nemoclaw_image_build.py index 6b176df9b..e8968051e 100644 --- a/tests/charts/test_nemoclaw_image_build.py +++ b/tests/charts/test_nemoclaw_image_build.py @@ -34,21 +34,32 @@ def test_github_supplies_the_same_reviewed_runtime(tmp_path): @pytest.mark.ci_external -def test_ci_aligns_the_upstream_curl_pin_before_building(tmp_path): +@pytest.mark.parametrize("ca_version,curl_version", [ + ("20250419", "8.14.1-2+deb13u5"), + ("20250419", "8.14.1-2+deb13u7"), + ("20250419+deb13u1", "8.14.1-2+deb13u5"), + ("20250419+deb13u1", "8.14.1-2+deb13u7"), +]) +def test_ci_aligns_the_upstream_debian_pins_before_building(tmp_path, ca_version, curl_version): workflow = yaml.safe_load((ROOT / ".github/workflows/build-nemoclaw-sandbox.yml").read_text()) steps = workflow["jobs"]["build"]["steps"] - pin = next(i for i, s in enumerate(steps) if s.get("name") == "Align upstream curl pin with Debian security") + pin = next(i for i, s in enumerate(steps) + if s.get("name") == "Align upstream Debian package pins with Debian security") image_build = next(i for i, s in enumerate(steps) if s.get("uses") == "./.github/actions/build-push-image") assert pin < image_build dockerfile = tmp_path / "Dockerfile" - line = "RUN apt-get install -y ca-certificates=20250419 curl=8.14.1-2+deb13u5 && rm -rf /var/lib/apt/lists/*\n" + line = (f"RUN apt-get install -y ca-certificates={ca_version} curl={curl_version} " + "&& rm -rf /var/lib/apt/lists/*\n") dockerfile.write_text("FROM node AS npm12\n" + line) env = dict(os.environ, UPSTREAM_DIR=str(tmp_path), BASH_ENV="/dev/null") subprocess.run(["bash", "-eu", "-c", steps[pin]["run"]], env=env, check=True, capture_output=True) - assert dockerfile.read_text() == "FROM node AS npm12\n" + line.replace("deb13u5", "deb13u7") - # A later NemoClaw ref without the stale pin is left as is. + expected = ("FROM node AS npm12\n" + "RUN apt-get install -y ca-certificates=20250419+deb13u1 " + "curl=8.14.1-2+deb13u7 && rm -rf /var/lib/apt/lists/*\n") + assert dockerfile.read_text() == expected + # Both rewrites are idempotent, including already-correct upstream refs. subprocess.run(["bash", "-eu", "-c", steps[pin]["run"]], env=env, check=True, capture_output=True) - assert "deb13u5" not in dockerfile.read_text() + assert dockerfile.read_text() == expected @pytest.mark.ci_external From 838b8513bb26d91980c3b5cf6561699e943fa30d Mon Sep 17 00:00:00 2001 From: mtalvi Date: Wed, 25 Nov 2026 12:35:19 +0200 Subject: [PATCH 8/9] docs: keep per-user secret names unique during installation Co-Authored-By: Claude Opus 5.5 --- README.md | 28 ++++++++++++++++++++-------- values-secret.yaml.template | 21 ++++++++------------- 2 files changed, 28 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 2e84598e9..68a0fa0ed 100644 --- a/README.md +++ b/README.md @@ -208,21 +208,33 @@ history kept outside the workspace, see make keycloak-user-info KC_USER=alice ``` -2. Add the user's inference key to `~/values-secret.yaml`, and load it: +2. Create `~/values-secret-alice.yaml` for the user's inference key. Secret + names must be unique within a file, even with different `vaultPrefixes`; + do not append a second `inference` entry to the installation's secrets file. ```yaml - - name: inference - vaultPrefixes: - - hub/saw-alice - fields: - - name: api_key - path: ~/.alice-inference-key + version: "2.0" + secrets: + - name: inference + vaultPrefixes: + - hub/saw-alice + fields: + - name: api_key + path: ~/.alice-inference-key ``` + If web search is enabled, also copy the `web-search` entry from + `values-secret.yaml.template` into this file with `vaultPrefixes: + [hub/saw-alice]`. Then load the user's file explicitly: + ```bash - ./pattern.sh make load-secrets + VALUES_SECRET="$HOME/values-secret-alice.yaml" ./pattern.sh make load-secrets ``` + To share an existing key instead, add `hub/saw-alice` to that entry's + `vaultPrefixes` (for example, `[hub, hub/saw-alice]`) and load the installation's + secrets file. One entry writes the same fields to every listed prefix. + 3. Add the entry: ```yaml diff --git a/values-secret.yaml.template b/values-secret.yaml.template index 16fda4501..abd0437e9 100644 --- a/values-secret.yaml.template +++ b/values-secret.yaml.template @@ -108,19 +108,14 @@ secrets: vaultPolicy: validatedPatternDefaultPolicy # --- Per-user Vault prefix (optional) --- - # Secrets above go to the shared hub prefix (secret/data/hub) and every - # user's workspace reads them. The saw-users chart cannot create Vault - # entries. To give one person their own keys, load them here (vaultPrefixes - # is relative to secret/data) and set that user's vaultPrefix to - # secret/data/hub/saw-: - # - name: inference - # vaultPrefixes: - # - hub/saw-alice - # fields: - # - name: provider - # value: build - # - name: api_key - # path: ~/.nvidia-api-key + # Secrets above default to the shared hub prefix (secret/data/hub). + # The saw-users chart cannot create Vault entries. For container/Kata users, + # credentials live under hub/saw-; vaultPrefixes is relative to secret/data. + # Secret names must be unique within this file, even across different prefixes. + # To share the same key, add vaultPrefixes: [hub, hub/saw-alice] to the existing + # inference entry (and web-search when enabled). To use a different key, + # create a separate per-user values-secret file and load it with VALUES_SECRET. + # See README.md, "Container workspace", for the complete file and command. # Optional personal-assistant credentials for Git-listed users. # Use the matching per-user vaultPrefixes (for example hub/saw-dana). From 68246ced8d21dff62723ac717a696bf1b3919736 Mon Sep 17 00:00:00 2001 From: mtalvi Date: Wed, 25 Nov 2026 14:27:15 +0200 Subject: [PATCH 9/9] fix: preserve workspace telemetry and reject unsupported model audit settings Use detailed, unsampled collector output for the demonstration deployment. Require W6 to find a fresh OCSF JSON body and matching sandbox identity rather than shared batch summaries. Select the requested sandbox's own pod pair. Reject lifecycle model selection without receipts in shared projection, portal requests before credential writes, and direct chart rendering. Keep the compiler's receipt-key requirement intact. Co-Authored-By: Claude Opus 5.5 --- charts/openshell-rhdh/files/portal.py | 4 ++ charts/openshell-rhdh/files/workspace.py | 8 +++ .../templates/_helpers.tpl | 5 ++ charts/saw-telemetry/values.yaml | 10 +-- charts/saw-users/files/workspace.py | 8 +++ docs/container-installation.md | 13 +++- scripts/check-ocsf-record.py | 61 +++++++++++++++++++ scripts/e2e-workspace.sh | 22 +++++-- tests/charts/test_portal_container.py | 13 ++++ tests/portal/test_portal.py | 19 ++++++ tests/scripts/test_ocsf_record.py | 46 ++++++++++++++ tests/scripts/test_workspace_projection.py | 21 ++++++- 12 files changed, 217 insertions(+), 13 deletions(-) create mode 100644 scripts/check-ocsf-record.py create mode 100644 tests/scripts/test_ocsf_record.py diff --git a/charts/openshell-rhdh/files/portal.py b/charts/openshell-rhdh/files/portal.py index 83ebed6c9..812966d72 100644 --- a/charts/openshell-rhdh/files/portal.py +++ b/charts/openshell-rhdh/files/portal.py @@ -1801,6 +1801,10 @@ def handle(action, request_name): models = public_model_inputs(catalog[profile], secrets) previous = committed_entry(cm) lifecycle = previous.get("lifecycleVersion") == 1 if previous else container_site(user).get("modelLifecycle") is True + try: + _workspace.validate_model_audit(site, lifecycle, catalog[profile]) + except _workspace.WorkspaceError as exc: + raise PortalError(str(exc)) from exc if previous and not lifecycle and previous.get("modelInputs", {}) != models: raise PortalError("changing model selection requires a new container registration") check_namespace_is_ours(k8s, user) diff --git a/charts/openshell-rhdh/files/workspace.py b/charts/openshell-rhdh/files/workspace.py index 1addd71e3..a5703a21e 100644 --- a/charts/openshell-rhdh/files/workspace.py +++ b/charts/openshell-rhdh/files/workspace.py @@ -38,6 +38,13 @@ def enabled_catalog_sandboxes(profile): yield workspace["name"], sandbox +def validate_model_audit(site, lifecycle, profile): + """Reject mutable models without a receipt-backed gate before enrollment.""" + if (lifecycle and site.get("auditReceipts") is not True + and any(sb.get("modelInput") for _, sb in enabled_catalog_sandboxes(profile))): + raise WorkspaceError("model selection requires auditReceipts=true") + + def sandbox_targets(user, registration, profile, *, model_lifecycle=False): """Expand the shared BOM catalog into isolated Kubernetes attachments.""" enabled = list(enabled_catalog_sandboxes(profile)) @@ -283,6 +290,7 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): if overrides: ws["imageOverrides"] = overrides managed = ws.get("lifecycleVersion") == 1 + validate_model_audit(site, managed, catalog[selected]) site = {**site, "targets": sandbox_targets(ws["name"], ws["registration"], catalog[selected], model_lifecycle=managed), diff --git a/charts/saw-portal-container/templates/_helpers.tpl b/charts/saw-portal-container/templates/_helpers.tpl index 195f01797..f9b1a30c2 100644 --- a/charts/saw-portal-container/templates/_helpers.tpl +++ b/charts/saw-portal-container/templates/_helpers.tpl @@ -49,6 +49,11 @@ 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 -}} +{{- if and (eq (int ($site.lifecycleVersion | default 0)) 1) (not ($site.auditReceipts | default false)) -}} +{{- range $site.targets -}} +{{- if .modelInput -}}{{ fail "model selection requires auditReceipts=true" }}{{- end -}} +{{- end -}} +{{- end -}} {{- with $site.enrollment -}} {{- $a := $site.automaticEnrollment -}} {{- $_ := set . "relay" (include "portal.deepMerge" (dict "base" ($a.relay | default dict) "over" (.relay | default dict)) | fromJson) -}} diff --git a/charts/saw-telemetry/values.yaml b/charts/saw-telemetry/values.yaml index 6d311076f..77ea3bbb0 100644 --- a/charts/saw-telemetry/values.yaml +++ b/charts/saw-telemetry/values.yaml @@ -3,12 +3,14 @@ # container site's telemetry.ocsfEndpoint points at. name: saw-ocsf replicas: 1 -# Where the events go. The debug exporter writes them to the collector's log -# (oc logs deploy/saw-ocsf-collector); replace it with your SIEM or log store, -# for example an otlp or otlphttp exporter. +# Demonstration output: preserve event bodies, identities and trace details in +# oc logs deploy/saw-ocsf-collector. Pod logs are not durable audit storage; +# replace this exporter with your SIEM or log store for production. exporters: debug: - verbosity: basic + verbosity: detailed + sampling_thereafter: 1 + use_internal_logger: false resources: requests: {cpu: 50m, memory: 128Mi} limits: {memory: 512Mi} diff --git a/charts/saw-users/files/workspace.py b/charts/saw-users/files/workspace.py index 1addd71e3..a5703a21e 100644 --- a/charts/saw-users/files/workspace.py +++ b/charts/saw-users/files/workspace.py @@ -38,6 +38,13 @@ def enabled_catalog_sandboxes(profile): yield workspace["name"], sandbox +def validate_model_audit(site, lifecycle, profile): + """Reject mutable models without a receipt-backed gate before enrollment.""" + if (lifecycle and site.get("auditReceipts") is not True + and any(sb.get("modelInput") for _, sb in enabled_catalog_sandboxes(profile))): + raise WorkspaceError("model selection requires auditReceipts=true") + + def sandbox_targets(user, registration, profile, *, model_lifecycle=False): """Expand the shared BOM catalog into isolated Kubernetes attachments.""" enabled = list(enabled_catalog_sandboxes(profile)) @@ -283,6 +290,7 @@ def _project_workspace(workspace, defaults, site, catalog, read=None): if overrides: ws["imageOverrides"] = overrides managed = ws.get("lifecycleVersion") == 1 + validate_model_audit(site, managed, catalog[selected]) site = {**site, "targets": sandbox_targets(ws["name"], ws["registration"], catalog[selected], model_lifecycle=managed), diff --git a/docs/container-installation.md b/docs/container-installation.md index 9d79a7505..01e868b88 100644 --- a/docs/container-installation.md +++ b/docs/container-installation.md @@ -814,8 +814,13 @@ By default audit is best-effort, as in upstream OpenShell. The gateway and each sandbox's supervisor export OCSF events (authentication, refused API calls, network and request decisions) over OTLP/gRPC to the collector in `openshell-agents` (`charts/saw-telemetry`, Red Hat build of OpenTelemetry). -Its debug exporter writes them to the collector's log; replace it with your -SIEM or log store in `charts/saw-telemetry/values.yaml`. Set +The demonstration debug exporter writes complete event bodies, sandbox IDs and +trace details to the collector's log, with detailed output and sampling disabled. +Pod logs are not durable audit storage; replace the exporter with your SIEM or +log store in `charts/saw-telemetry/values.yaml` for production. W6 inspects the +demo collector's detailed logs and requires a fresh OCSF JSON body whose sandbox +ID matches both the body and the log record's `openshell.sandbox.id` attribute. +When using an external exporter, verify records in that backend separately. Set `telemetry.ocsfEndpoint: ""` in `containerDefaults` to turn export off. OpenShell drops events it cannot export, and nothing waits for the collector. OpenShell 0.1.6 does not export the agent's own tool calls; those are in the @@ -839,4 +844,8 @@ run until its receipt arrives. The sandbox reaches the writer through a shared as a copy of the cluster's shared-filesystem class (an existing `saw-shared` is kept; set `stack.audit.values.exchangeStorageClass` for another class). Changing the model at run time (`lifecycleVersion: 1`) requires receipts. +Static projection and portal requests reject model selection without +`auditReceipts: true` before enrollment. Direct composition-chart values are +rejected at render time. Fixed-model registrations using the default local +audit log omit `lifecycleVersion: 1` and leave `modelLifecycle` disabled. Changing `auditReceipts` changes the enrolled boundary: recreate the workspace. diff --git a/scripts/check-ocsf-record.py b/scripts/check-ocsf-record.py new file mode 100644 index 000000000..f3115f2a7 --- /dev/null +++ b/scripts/check-ocsf-record.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Find a fresh sandbox OCSF body in the demo collector's detailed debug log. + +The debug exporter is a demonstration output, not a stable ingestion API. Fail +closed if its format changes or only batch summaries/trace records are present. +""" +import argparse +from datetime import datetime +import json +import re +import sys + + +def find_record(text, sandbox_id, since_ms): + for block in re.split(r"(?m)^LogRecord #\d+\s*$", text)[1:]: + # Never borrow an attribute from the next resource/signal's header. + block = re.split(r"(?m)^(?:Resource|Scope)(?:Logs|Spans) #", block)[0] + identity = re.search(r"(?m)^\s*-> openshell\.sandbox\.id: Str\(([^\n]*)\)\s*$", block) + body = re.search(r"(?m)^Body: Str\(([^\n]*)\)\s*$", block) + if not identity or identity[1] != sandbox_id or not body: + continue + try: + event = json.loads(body[1]) + except ValueError: + continue + if not isinstance(event, dict): + continue + # OpenShell attributes identity from device.container, never from + # request-supplied resources that may name a different sandbox. + device = event.get("device") or {} + container = device.get("container") if isinstance(device, dict) else None + container = container if isinstance(container, dict) else {} + unmapped = event.get("unmapped") or {} + body_id = (container.get("uid") if isinstance(container, dict) else None) + if body_id is None and isinstance(unmapped, dict): + body_id = unmapped.get("sandbox_id") + if (body_id != sandbox_id or type(event.get("class_uid")) is not int + or event["class_uid"] <= 0 or type(event.get("activity_id")) is not int + or type(event.get("time")) is not int or event["time"] < since_ms): + continue + return event + return None + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--sandbox-id", required=True) + parser.add_argument("--since", required=True, help="UTC RFC3339 test start") + args = parser.parse_args() + since_ms = int(datetime.fromisoformat(args.since.replace("Z", "+00:00")).timestamp() * 1000) + event = find_record(sys.stdin.read(), args.sandbox_id, since_ms) + if event is None: + return 1 + # Only structural evidence is printed; request data remains in the collector. + print(f"sandbox={args.sandbox_id} class_uid={event['class_uid']} " + f"activity_id={event['activity_id']} time={event['time']}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/e2e-workspace.sh b/scripts/e2e-workspace.sh index c329d4d44..8eb7511f9 100755 --- a/scripts/e2e-workspace.sh +++ b/scripts/e2e-workspace.sh @@ -15,7 +15,7 @@ # the turn also asks for one tool call, which the gate may deny) # W5 container/kata: the tool gate recorded that turn's tool call # (local log by default; receipts mode is reported, not checked here) -# W6 container/kata: OCSF events reached the pattern's collector +# W6 container/kata: a fresh OCSF body for this sandbox reached the collector # # Usage: # scripts/e2e-workspace.sh --mode container|kata|vm --user NAME @@ -34,6 +34,7 @@ KATA_CLASS="${KATA_CLASS:-saw-kata}" ARGO_NS="${ARGO_NAMESPACE:-vp-gitops}" COLLECTOR_NS="${COLLECTOR_NS:-openshell-agents}" COLLECTOR_SELECTOR="${COLLECTOR_SELECTOR:-app.kubernetes.io/name=saw-ocsf-collector}" TURN_TIMEOUT="${TURN_TIMEOUT:-180}" +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" while [[ $# -gt 0 ]]; do case "$1" in @@ -121,7 +122,10 @@ if [[ "${MODE}" == vm ]]; then } else step "W2 sandbox Pods" - pod_of() { oc get pods -n "${NS}" -l "openshell.ai/boundary-role=$1" -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true; } + SANDBOX_ID="$(oc get sandboxes.agents.x-k8s.io -n "${NS}" "${WORKSPACE}--${SANDBOX}" \ + -o jsonpath='{.metadata.labels.openshell\.ai/sandbox-id}' 2>/dev/null || true)" + [[ -n "${SANDBOX_ID}" ]] || { fail "no sandbox identity for ${WORKSPACE}/${SANDBOX}"; exit 1; } + pod_of() { oc get pods -n "${NS}" -l "openshell.ai/boundary-role=$1,openshell.ai/boundary-pair=${SANDBOX_ID}" -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true; } WORKLOAD="$(pod_of workload)" SUPERVISOR="$(pod_of supervisor)" for pod in "${SUPERVISOR}" "${WORKLOAD}"; do if [[ -z "${pod}" ]]; then fail "missing supervisor or workload Pod in ${NS}"; continue; fi @@ -180,9 +184,17 @@ if [[ "${MODE}" != vm ]]; then if [[ -z "${collector}" ]]; then fail "no OCSF collector Pod in ${COLLECTOR_NS}" else - batches="$(oc logs -n "${COLLECTOR_NS}" "${collector}" --since-time="${START}" 2>/dev/null | grep -c 'Logs' || true)" - (( batches > 0 )) && pass "collector received ${batches} log batch(es) since ${START}" \ - || fail "collector received nothing since ${START}" + found=0 + for attempt in 1 2 3 4 5 6; do + if event="$(oc logs -n "${COLLECTOR_NS}" -l "${COLLECTOR_SELECTOR}" --tail=-1 --since-time="${START}" 2>/dev/null \ + | python3 "${SCRIPT_DIR}/check-ocsf-record.py" --sandbox-id "${SANDBOX_ID}" --since "${START}")"; then + pass "collector preserved a fresh OCSF body: ${event}" + found=1 + break + fi + (( attempt == 6 )) || sleep 5 + done + (( found )) || fail "no fresh OCSF body for sandbox ${SANDBOX_ID}; W6 requires detailed collector log output" fi fi diff --git a/tests/charts/test_portal_container.py b/tests/charts/test_portal_container.py index 0e4c67dc4..663ba0e58 100644 --- a/tests/charts/test_portal_container.py +++ b/tests/charts/test_portal_container.py @@ -236,6 +236,17 @@ def test_model_gate_claim_is_shared_only_for_the_publisher_and_agent(): assert claims["workspace-"+U]["accessModes"] == claims[U+"-history"]["accessModes"] == ["ReadWriteOnce"] +@pytest.mark.parametrize("receipts", [False, None]) +def test_model_selection_without_receipts_is_rejected_before_enrollment(receipts): + site = {**SITE, "lifecycleVersion": 1, "targets": { + "default/notebook": {"modelInput": "inference.model"}}} + site.pop("auditReceipts") + if receipts is not None: + site["auditReceipts"] = receipts + with pytest.raises(AssertionError, match="model selection requires auditReceipts=true"): + render("saw-portal-container", U, "saw-" + U, {"site": site}) + + def app_values(application): source = application["spec"]["source"]["helm"] return source.get("valuesObject") or yaml.safe_load(source["values"]) @@ -675,6 +686,8 @@ def test_the_pattern_installs_the_collector(): assert values["applications"]["saw-telemetry"]["path"] == "charts/saw-telemetry" collector, = render("saw-telemetry", "saw-telemetry", "openshell-agents", {}) assert collector["metadata"]["name"] == "saw-ocsf" # Service saw-ocsf-collector + assert collector["spec"]["config"]["exporters"]["debug"] == { + "verbosity": "detailed", "sampling_thereafter": 1, "use_internal_logger": False} pipelines = collector["spec"]["config"]["service"]["pipelines"] for signal in ("logs", "traces"): # OCSF events and relayed agent traces assert pipelines[signal]["receivers"] == ["otlp"] and pipelines[signal]["exporters"] == ["debug"] diff --git a/tests/portal/test_portal.py b/tests/portal/test_portal.py index 38c417a93..b0fb6c097 100644 --- a/tests/portal/test_portal.py +++ b/tests/portal/test_portal.py @@ -2301,6 +2301,25 @@ def state(name, operation, generation, **extra): assert json.dumps(fake.vault, sort_keys=True) == vault_before +@pytest.mark.parametrize("receipts", [False, True]) +def test_model_lifecycle_audit_is_checked_before_credentials_are_written(portal, world, monkeypatch, capsys, receipts): + fake, signer = world + site = synthetic_preflight_site(portal, { + "subject": "478fdd1f-8db9-41e8-97ad-b563215c89e9", "modelLifecycle": True, + "auditReceipts": receipts, + "automaticEnrollment": {"approvedProfiles": {"data-science": "a" * 64}}, + }) + monkeypatch.setenv("SAW_DEPLOYMENT_MODES", '["vm","container"]') + monkeypatch.setenv("SAW_CONTAINER_SITES", json.dumps({"alice": site})) + fake.request("saw-req-1", ds_request(signer, deploymentMode="container")) + assert (portal.main(["create", "saw-req-1"]) == 0) is receipts + if not receipts: + assert "model selection requires auditReceipts=true" in capsys.readouterr().out + assert not fake.vault and REGISTRY not in fake.objects + else: + assert portal.read_entry(fake.objects[REGISTRY])["lifecycleVersion"] == 1 + + def test_custom_endpoint_is_validated_before_writing_vault(portal, world, monkeypatch): fake, signer = world url="https://models.fixture.test/v1" diff --git a/tests/scripts/test_ocsf_record.py b/tests/scripts/test_ocsf_record.py new file mode 100644 index 000000000..9ca660ac4 --- /dev/null +++ b/tests/scripts/test_ocsf_record.py @@ -0,0 +1,46 @@ +"""W6 must reject shared-collector traffic without this sandbox's fresh body.""" +import importlib.util +import json +from pathlib import Path + +import pytest + +SPEC = importlib.util.spec_from_file_location( + "check_ocsf_record", Path(__file__).resolve().parents[2] / "scripts/check-ocsf-record.py") +check = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(check) +SANDBOX = "11111111-1111-4111-8111-111111111111" + + +def event(sandbox=SANDBOX, time=2000): + return {"class_uid": 4002, "activity_id": 1, "time": time, + "device": {"container": {"uid": sandbox}}, "message": "network decision"} + + +def record(body, sandbox=SANDBOX): + return ("ResourceLogs #0\nScopeLogs #0\nLogRecord #0\n" + "Body: Str(" + json.dumps(body) + ")\nAttributes:\n" + " -> openshell.sandbox.id: Str(" + sandbox + ")\n") + + +def test_accepts_a_fresh_complete_ocsf_body_for_the_exact_sandbox(): + body = event() + assert check.find_record(record(event("another-sandbox"), "another-sandbox") + record(body), SANDBOX, 1000) == body + body["unmapped"] = {"sandbox_id": body.pop("device")["container"]["uid"]} + assert check.find_record(record(body), SANDBOX, 1000) == body + + +@pytest.mark.parametrize("text", [ + 'Logs {"resource logs": 1, "log records": 80}\n', + record(event("another-sandbox"), "another-sandbox"), + record(event("another-sandbox")), + record(event(), "another-sandbox"), + record(event(time=999)), + record({**event("another-sandbox"), "resources": [{"uid": SANDBOX}]}), + record({"message": "unstructured text", "container": {"uid": SANDBOX}}), + record(event()).replace("Body: Str(", "Body: Str(broken-json"), + record(event()).replace("LogRecord #0", "Span #0"), + record(event()).split("Attributes:")[0] + record(event("another-sandbox")), +]) +def test_rejects_summaries_other_sandboxes_stale_and_incomplete_records(text): + assert check.find_record(text, SANDBOX, 1000) is None diff --git a/tests/scripts/test_workspace_projection.py b/tests/scripts/test_workspace_projection.py index c7f5fbf5c..e9d94909b 100644 --- a/tests/scripts/test_workspace_projection.py +++ b/tests/scripts/test_workspace_projection.py @@ -19,7 +19,8 @@ def inputs(): profiles=["data-science"], values={"deployment": {"mode": "container"}}, lifecycleVersion=1, initialModelInputs={"inference.model": "first"}, modelInputs={"inference.model": "second"}, desiredState="Running", restartGeneration=2) - site = dict(subject=owner["ownerSubject"], automaticEnrollment={"approvedProfiles": {"data-science": "b"*64}}, + site = dict(subject=owner["ownerSubject"], auditReceipts=True, + automaticEnrollment={"approvedProfiles": {"data-science": "b"*64}}, profileImageOverrides={"data-science": {"default": {"notebook": "example/agent@sha256:"+"c"*64}}}) return owner, site @@ -84,7 +85,7 @@ def test_foundation_requires_no_synthetic_approval_hash(): def auto_site(owner): - return dict(subject=owner["ownerSubject"], automaticEnrollment={ + return dict(subject=owner["ownerSubject"], auditReceipts=True, automaticEnrollment={ "autoApprove": True, "revision": "main", "image": "example/runtime@sha256:" + "d"*64, "buildNamespace": "saw-builds", "relay": {"revision": "main"}}) @@ -145,6 +146,22 @@ def test_custom_inference_uses_the_owners_own_url(): workspace.project_workspace(owner, {}, site, CATALOG, lambda _: {}) +@pytest.mark.parametrize("receipts", [False, None]) +def test_mutable_models_are_rejected_before_reading_enrollment_without_receipts(receipts): + owner, site = inputs() + site.pop("auditReceipts") + if receipts is not None: + site["auditReceipts"] = receipts + def unexpected_read(_): + pytest.fail("invalid audit configuration must be rejected before enrollment reads") + with pytest.raises(workspace.WorkspaceError, match="model selection requires auditReceipts=true"): + workspace.project_workspace(owner, {}, site, CATALOG, unexpected_read) + # Fixed models keep the default best-effort audit path. + owner.pop("lifecycleVersion") + result = workspace.project_workspace(owner, {}, site, CATALOG) + assert all("modelInput" not in target for target in result["containerSites"]["alice"]["targets"].values()) + + def test_only_an_endpoint_profile_takes_a_custom_inference_url(): owner, _ = inputs() owner["customInferenceURL"] = "https://api.inference.example/v1"