diff --git a/.tekton/odh-openshell-e2e-branch.yaml b/.tekton/odh-openshell-e2e-branch.yaml new file mode 100644 index 0000000000..72a854d650 --- /dev/null +++ b/.tekton/odh-openshell-e2e-branch.yaml @@ -0,0 +1,65 @@ +apiVersion: tekton.dev/v1 +kind: PipelineRun +# Builds quay.io/opendatahub/odh-openshell-e2e: on push to versioned +# e2e-N.N branches (and e2e-N.N-ea.N). +# +metadata: + annotations: + build.appstudio.openshift.io/repo: https://github.com/opendatahub-io/openshell?rev={{revision}} + build.appstudio.redhat.com/commit_sha: '{{revision}}' + build.appstudio.redhat.com/target_branch: '{{target_branch}}' + pipelinesascode.tekton.dev/cancel-in-progress: "false" + pipelinesascode.tekton.dev/max-keep-runs: "3" + pipelinesascode.tekton.dev/on-cel-expression: | + event == "push" + && target_branch.matches("^e2e-[0-9]+\\.[0-9]+(-ea\\.[0-9]+)?$") + creationTimestamp: null + labels: + appstudio.openshift.io/application: opendatahub-builds + appstudio.openshift.io/component: odh-openshell-e2e-ci + pipelines.appstudio.openshift.io/type: build + name: odh-openshell-e2e-on-branch + namespace: open-data-hub-tenant +spec: + params: + - name: git-url + value: '{{source_url}}' + - name: revision + value: '{{revision}}' + - name: output-image + value: quay.io/opendatahub/odh-openshell-e2e:{{target_branch}} + - name: dockerfile + value: deploy/docker/Dockerfile.konflux.e2e-odh + - name: path-context + value: . + - name: hermetic + value: "true" + - name: build-platforms + value: + - linux-m2xlarge/amd64 + - linux-m2xlarge/arm64 + - name: prefetch-input + value: | + [ + {"type": "cargo", "path": "."}, + {"type": "cargo", "path": "e2e/rust"}, + {"type": "pip", "path": "odh", "requirements_files": ["requirements.txt"], "binary": {"packages": ":all:", "arch": "x86_64,aarch64", "os": "linux", "py_version": 311, "py_impl": "cp"}}, + {"type": "rpm", "path": "deploy/konflux/e2e-odh"}, + {"type": "generic", "path": "deploy/konflux/e2e-odh", "lockfile": "generic-fetcher.yaml"} + ] + pipelineRef: + resolver: git + params: + - name: url + value: https://github.com/opendatahub-io/odh-konflux-central.git + - name: revision + value: main + - name: pathInRepo + value: pipeline/multi-arch-container-build.yaml + taskRunTemplate: + serviceAccountName: build-pipeline-odh-openshell-e2e-ci + workspaces: + - name: git-auth + secret: + secretName: '{{ git_auth_secret }}' +status: {} diff --git a/deploy/docker/Dockerfile.konflux.e2e-odh b/deploy/docker/Dockerfile.konflux.e2e-odh index dbd431069d..8de4bb9caa 100644 --- a/deploy/docker/Dockerfile.konflux.e2e-odh +++ b/deploy/docker/Dockerfile.konflux.e2e-odh @@ -18,15 +18,15 @@ # `deploy/konflux/e2e-odh/sync-generic-fetcher.py --update all` to refresh the # amd64 and arm64 checksums. # renovate: datasource=docker depName=quay.io/openshift-release-dev/ocp-release extractVersion=^(?4\.\d+\.\d+)-x86_64$ -ARG OC_VERSION=4.22.22 +ARG OC_VERSION=4.22.24 # renovate: datasource=github-releases depName=helm/helm extractVersion=^v(?.+)$ -ARG HELM_VERSION=4.3.1 +ARG HELM_VERSION=4.3.2 # renovate: datasource=github-releases depName=nextest-rs/nextest extractVersion=^cargo-nextest-(?.+)$ -ARG NEXTEST_VERSION=0.9.151 +ARG NEXTEST_VERSION=0.9.152 # renovate: datasource=github-releases depName=astral-sh/uv -ARG UV_VERSION=0.13.7 +ARG UV_VERSION=0.13.10 -FROM registry.redhat.io/rust-builder-image/rust-rhel9:1.99.1@sha256:cf69dc550002a80c8af670bf9ca3068ed6c9ddc8d94fd99513b06ecaac297921 AS builder +FROM registry.redhat.io/rust-builder-image/rust-rhel9:1.100.0@sha256:54e9eebf1609beb0d13126fcd54faa2c7330478b17302afe4c2123a38b4dbf56 AS builder # The builder image runs as 1001 and already ships gcc, gcc-c++, make, # cmake, openssl-devel, git and tar. Install Python for the locked E2E test diff --git a/deploy/konflux/cli/rpms.lock.yaml b/deploy/konflux/cli/rpms.lock.yaml index 0d578e523f..ae219bb3d9 100644 --- a/deploy/konflux/cli/rpms.lock.yaml +++ b/deploy/konflux/cli/rpms.lock.yaml @@ -694,13 +694,13 @@ arches: name: gawk-all-langpacks evr: 5.1.0-7.el9 sourcerpm: gawk-5.1.0-7.el9.src.rpm - - url: https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi9/9/x86_64/appstream/os/Packages/g/git-core-2.52.0-1.el9.x86_64.rpm + - url: https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi9/9/x86_64/appstream/os/Packages/g/git-core-2.52.1-1.el9_9.x86_64.rpm repoid: ubi-9-for-x86_64-appstream-rpms - size: 5293286 - checksum: sha256:6264aa556d583604f34def3674f5830a70cfee0aac283719e4df295db38acb53 + size: 5296855 + checksum: sha256:6ba3fae1010b62fd3f59bbc143dc9eac4b42a000747419090222c793bb71489f name: git-core - evr: 2.52.0-1.el9 - sourcerpm: git-2.52.0-1.el9.src.rpm + evr: 2.52.1-1.el9_9 + sourcerpm: git-2.52.1-1.el9_9.src.rpm - url: https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi9/9/x86_64/appstream/os/Packages/l/libtool-ltdl-2.4.6-46.el9.x86_64.rpm repoid: ubi-9-for-x86_64-appstream-rpms size: 38043 diff --git a/deploy/konflux/e2e-odh/README.md b/deploy/konflux/e2e-odh/README.md index 8dc888f8bf..805290988e 100644 --- a/deploy/konflux/e2e-odh/README.md +++ b/deploy/konflux/e2e-odh/README.md @@ -72,8 +72,9 @@ Python dependencies at `odh`: } ``` -The image name is `odh-openshell-e2e`; Konflux automation generates the -Tekton YAML files. +The image name is `odh-openshell-e2e`. Pushes to `main` publish `:odh-stable`. +Pushes to versioned `e2e-*` branches are documented in +[odh/e2e-images.md](../../../odh/e2e-images.md). Before merging, validate the local hermetic build on both `linux/amd64` and `linux/arm64` using `PLATFORM` with `deploy/konflux/build-local.sh e2e-odh`. diff --git a/deploy/konflux/e2e-odh/generic-fetcher.yaml b/deploy/konflux/e2e-odh/generic-fetcher.yaml index 1f7dae9230..e4e0668ec4 100644 --- a/deploy/konflux/e2e-odh/generic-fetcher.yaml +++ b/deploy/konflux/e2e-odh/generic-fetcher.yaml @@ -5,30 +5,30 @@ metadata: version: "1.0" artifacts: - - download_url: https://github.com/astral-sh/uv/releases/download/0.13.7/uv-x86_64-unknown-linux-gnu.tar.gz + - download_url: https://github.com/astral-sh/uv/releases/download/0.13.10/uv-x86_64-unknown-linux-gnu.tar.gz checksum: "sha256:c5221ff41b7892bfc223543883600125f6a47fe845093e0f5bdff4f359196d83" - filename: uv-0.13.7-x86_64-unknown-linux-gnu.tar.gz - - download_url: https://github.com/astral-sh/uv/releases/download/0.13.7/uv-aarch64-unknown-linux-gnu.tar.gz + filename: uv-0.13.10-x86_64-unknown-linux-gnu.tar.gz + - download_url: https://github.com/astral-sh/uv/releases/download/0.13.10/uv-aarch64-unknown-linux-gnu.tar.gz checksum: "sha256:71279f8d3c67241e807b9d8db872d1bf541579fb9f08b7d1eb1682196d1e57dc" - filename: uv-0.13.7-aarch64-unknown-linux-gnu.tar.gz + filename: uv-0.13.10-aarch64-unknown-linux-gnu.tar.gz - - download_url: https://mirror.openshift.com/pub/openshift-v4/clients/ocp/4.22.22/openshift-client-linux-amd64-rhel9-4.22.22.tar.gz + - download_url: https://mirror.openshift.com/pub/openshift-v4/clients/ocp/4.22.24/openshift-client-linux-amd64-rhel9-4.22.24.tar.gz checksum: "sha256:fa41d39396f22e8b0f46a3634244cf53bec368bb254107a5bf9701547c39fb58" - filename: openshift-client-linux-amd64-rhel9-4.22.22.tar.gz - - download_url: https://mirror.openshift.com/pub/openshift-v4/clients/ocp/4.22.22/openshift-client-linux-arm64-rhel9-4.22.22.tar.gz + filename: openshift-client-linux-amd64-rhel9-4.22.24.tar.gz + - download_url: https://mirror.openshift.com/pub/openshift-v4/clients/ocp/4.22.24/openshift-client-linux-arm64-rhel9-4.22.24.tar.gz checksum: "sha256:b84bd5c6700ab48a84ab0b3cbbab4c3b8ffc45539ad05b57dd02f6cf1c3dc982" - filename: openshift-client-linux-arm64-rhel9-4.22.22.tar.gz + filename: openshift-client-linux-arm64-rhel9-4.22.24.tar.gz - - download_url: https://get.helm.sh/helm-v4.3.1-linux-amd64.tar.gz + - download_url: https://get.helm.sh/helm-v4.3.2-linux-amd64.tar.gz checksum: "sha256:0403a88ae20913d11b10a2467b50087721fea7581736da6b9d3992f5357fe54b" - filename: helm-v4.3.1-linux-amd64.tar.gz - - download_url: https://get.helm.sh/helm-v4.3.1-linux-arm64.tar.gz + filename: helm-v4.3.2-linux-amd64.tar.gz + - download_url: https://get.helm.sh/helm-v4.3.2-linux-arm64.tar.gz checksum: "sha256:8cf8f66ecbc252ac8f7f06cca68aba88508ddfde3a6a34feb1678ad1694b4f88" - filename: helm-v4.3.1-linux-arm64.tar.gz + filename: helm-v4.3.2-linux-arm64.tar.gz - - download_url: https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-0.9.151/cargo-nextest-0.9.151-x86_64-unknown-linux-gnu.tar.gz + - download_url: https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-0.9.152/cargo-nextest-0.9.152-x86_64-unknown-linux-gnu.tar.gz checksum: "sha256:1d4ce302b820c41f4b89c5fb9bce45f0f0c94882c1cf08fc360caf08be6e7df4" - filename: cargo-nextest-0.9.151-x86_64-unknown-linux-gnu.tar.gz - - download_url: https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-0.9.151/cargo-nextest-0.9.151-aarch64-unknown-linux-gnu.tar.gz + filename: cargo-nextest-0.9.152-x86_64-unknown-linux-gnu.tar.gz + - download_url: https://github.com/nextest-rs/nextest/releases/download/cargo-nextest-0.9.152/cargo-nextest-0.9.152-aarch64-unknown-linux-gnu.tar.gz checksum: "sha256:3e35e8f6913af92558ba09d7155f74e35dd1f0024ef3cd891637433ae4eacbdd" - filename: cargo-nextest-0.9.151-aarch64-unknown-linux-gnu.tar.gz + filename: cargo-nextest-0.9.152-aarch64-unknown-linux-gnu.tar.gz diff --git a/deploy/konflux/e2e-odh/rpms.lock.yaml b/deploy/konflux/e2e-odh/rpms.lock.yaml index b6a4b8ed3e..b32bcdbb39 100644 --- a/deploy/konflux/e2e-odh/rpms.lock.yaml +++ b/deploy/konflux/e2e-odh/rpms.lock.yaml @@ -785,13 +785,13 @@ arches: module_metadata: [] - arch: x86_64 packages: - - url: https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi9/9/x86_64/appstream/os/Packages/g/git-core-2.52.0-1.el9.x86_64.rpm + - url: https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi9/9/x86_64/appstream/os/Packages/g/git-core-2.52.1-1.el9_9.x86_64.rpm repoid: ubi-9-appstream-rpms - size: 5293286 - checksum: sha256:6264aa556d583604f34def3674f5830a70cfee0aac283719e4df295db38acb53 + size: 5296855 + checksum: sha256:6ba3fae1010b62fd3f59bbc143dc9eac4b42a000747419090222c793bb71489f name: git-core - evr: 2.52.0-1.el9 - sourcerpm: git-2.52.0-1.el9.src.rpm + evr: 2.52.1-1.el9_9 + sourcerpm: git-2.52.1-1.el9_9.src.rpm - url: https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi9/9/x86_64/appstream/os/Packages/l/libnsl2-2.0.0-1.el9.x86_64.rpm repoid: ubi-9-appstream-rpms size: 33287 @@ -1506,13 +1506,13 @@ arches: name: shadow-utils evr: 2:4.9-17.el9 sourcerpm: shadow-utils-4.9-17.el9.src.rpm - - url: https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi9/9/x86_64/baseos/os/Packages/s/sqlite-libs-3.34.1-11.el9_8.x86_64.rpm + - url: https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi9/9/x86_64/baseos/os/Packages/s/sqlite-libs-3.34.1-12.el9_9.x86_64.rpm repoid: ubi-9-baseos-rpms - size: 665095 - checksum: sha256:e5c20e933ec01f746a6c59a94cb99f46c6138dab3f387f0d02dab47f356e2e98 + size: 665692 + checksum: sha256:05db28a5bed8569e71f3a9259451c59f4c224238708e440ee7b93f06425d2529 name: sqlite-libs - evr: 3.34.1-11.el9_8 - sourcerpm: sqlite-3.34.1-11.el9_8.src.rpm + evr: 3.34.1-12.el9_9 + sourcerpm: sqlite-3.34.1-12.el9_9.src.rpm - url: https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi9/9/x86_64/baseos/os/Packages/s/systemd-libs-252-79.el9_9.1.x86_64.rpm repoid: ubi-9-baseos-rpms size: 663424 diff --git a/deploy/konflux/openclaw/rpms.lock.yaml b/deploy/konflux/openclaw/rpms.lock.yaml index a10f99e117..7e3b991da7 100644 --- a/deploy/konflux/openclaw/rpms.lock.yaml +++ b/deploy/konflux/openclaw/rpms.lock.yaml @@ -694,13 +694,13 @@ arches: name: setup evr: 2.13.7-10.el9 sourcerpm: setup-2.13.7-10.el9.src.rpm - - url: https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi9/9/x86_64/baseos/os/Packages/s/sqlite-libs-3.34.1-11.el9_8.x86_64.rpm + - url: https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi9/9/x86_64/baseos/os/Packages/s/sqlite-libs-3.34.1-12.el9_9.x86_64.rpm repoid: ubi-9-for-x86_64-baseos-rpms - size: 665095 - checksum: sha256:e5c20e933ec01f746a6c59a94cb99f46c6138dab3f387f0d02dab47f356e2e98 + size: 665692 + checksum: sha256:05db28a5bed8569e71f3a9259451c59f4c224238708e440ee7b93f06425d2529 name: sqlite-libs - evr: 3.34.1-11.el9_8 - sourcerpm: sqlite-3.34.1-11.el9_8.src.rpm + evr: 3.34.1-12.el9_9 + sourcerpm: sqlite-3.34.1-12.el9_9.src.rpm - url: https://cdn-ubi.redhat.com/content/public/ubi/dist/ubi9/9/x86_64/baseos/os/Packages/t/tzdata-2026f-1.el9_9.noarch.rpm repoid: ubi-9-for-x86_64-baseos-rpms size: 937173 diff --git a/deploy/rhoai/README.md b/deploy/rhoai/README.md index 2ea6275e1f..041a530bbc 100644 --- a/deploy/rhoai/README.md +++ b/deploy/rhoai/README.md @@ -1,672 +1,705 @@ -# Install OpenShell and the OpenShell Dashboard admin UI on OpenShift - -This guide walks you through installing -[OpenShell](https://github.com/NVIDIA/openshell) and the -[OpenShell Dashboard admin UI](https://github.com/ai-openshell/console) on an -existing OpenShift cluster. OpenShell provides safe, sandboxed runtimes for -autonomous AI agents; the admin UI is its browser console. - -The installer deploys two Helm releases, `openshell` for the gateway and -`openshell-dashboard` for the admin UI, as one pair per namespace. The -deployment uses OIDC only: users sign in through an external identity provider, -and the gateway serves its own TLS with a private CA. After the install you -register the gateway with the OpenShell CLI. You can then sign in through OIDC -and create sandboxes and open terminals from the admin UI. - -This guide is for development and evaluation, not production. It is not a -qualified RHOAI deployment: it does not cover FIPS compliance, certificate -renewal, or isolation guarantees beyond the workspace access checks described -here. - -## Table of contents - -- [Prerequisites](#prerequisites) -- [Choose a configuration](#choose-a-configuration) -- [Copy the configuration](#copy-the-configuration) -- [Edit the configuration](#edit-the-configuration) - - [Required](#required) - - [Optional](#optional) - - [OIDC issuer certificate](#oidc-issuer-certificate) - - [Chart and image pins](#chart-and-image-pins) - - [Operational values overrides](#operational-values-overrides) - - [Database backend](#database-backend) -- [Save the client secret](#save-the-client-secret) -- [Validate, preflight, and install](#validate-preflight-and-install) -- [Register the gateway and log in](#register-the-gateway-and-log-in) -- [Create and use a sandbox](#create-and-use-a-sandbox) -- [Using the OpenShell Dashboard UI](#using-the-openshell-dashboard-ui) -- [Verify workspace authorization](#verify-workspace-authorization) -- [Rerun and upgrade](#rerun-and-upgrade) -- [Remove an installation](#remove-an-installation) -- [Troubleshoot common failures](#troubleshoot-common-failures) -- [Contributor checks](#contributor-checks) -- [Related documentation](#related-documentation) +# Install OpenShell on OpenShift + +OpenShell provides sandboxed runtimes for AI agents, and the Dashboard is its +web UI for managing workspaces and sandboxes. + +`install.py` installs the OpenShell gateway and Dashboard into an OpenShift +namespace using Helm. This guide uses the RHOAI 3.6 image pins and PostgreSQL +configuration in `config-examples/config.example-rhoai-3.6-postgresql-keycloak.json`. + +The installer is an interim tool until an OpenShift Operator deploys OpenShell. +It first ships with RHOAI 3.6 GA. Rerunning it against an existing installation +works only for installations made with the RHOAI 3.6 GA version or later. +The installer refuses installations made with earlier development versions, +or asks for `--adopt-existing`; reinstall those into a new namespace. + +To move an OpenShell installation to newer releases, see [Upgrade an installation](#upgrade-an-installation); to remove it, see [Uninstall](#uninstall). ## Prerequisites -- `uv`, Helm 3.17.3 or later, and `kubectl` for installation and preflight on - the administrator's workstation. `--check` needs only Helm. -- OpenShift 4.20 or newer. -- amd64 nodes only. Mixed amd64/arm64 clusters are not supported because the - Red Hat Build of Agent Sandbox Operator is not available on arm64. -- [Red Hat Build of Agent Sandbox - Operator](https://docs.redhat.com/en/documentation/openshift_sandboxed_containers/1.13/html/deploying_red_hat_build_of_agent_sandbox/index) - deployed in the cluster. -- OpenShift's default OVN-Kubernetes network plugin (NetworkPolicy support) - and a default StorageClass that provisions block volumes for the gateway's - SQLite database. -- An OIDC provider with a confidential browser client that uses PKCE S256. For - development, set one up with the - [Keycloak development guide](keycloak-dev-guide.md). -- Registry access: `ghcr.io` from the workstation or server where the - installer is being run for both Helm charts, and from the cluster nodes the - registries your images come from: `quay.io` for ODH builds and - `registry.redhat.io` for RHOAI builds (requires a pull secret). - `registry.access.redhat.com` is only needed when you use a Red Hat base image. - -The installer does not install an identity provider, Agent Sandbox, RHOAI, or -console integration. It targets the current kubeconfig context unless you pass -`--context`, and never changes it. Configurations do not select a context. -`--check` reads neither the context nor the cluster. - -## Choose a configuration - -Start with `config-examples/config.example-rhoai-3.6-keycloak.json`. It pins the -RHOAI 3.6 builds by digest and pairs them with the Keycloak realm that -[keycloak-dev-guide.md](keycloak-dev-guide.md) creates. - -For the latest OpenShell builds, use -`config-examples/config.example-odh-keycloak.json`. It pins gateway chart -`0.1.7` and the `v0.1.7-rhaiv.0` images. It uses only `quay.io` images, so it -can test Open Data Hub community builds without `registry.redhat.io` access or -a pull secret. - -[config-examples/README.md](config-examples/README.md) describes all five -examples, including the generic and non-Keycloak variants. - -## Copy the configuration - -Copy the example outside the checkout so local credentials cannot be committed. -The commands below keep the configuration and its files in `CONFIG_DIR`; set it -to the directory that contains `config.json` if you keep it elsewhere: +- OpenShift 4.20 or newer on amd64 nodes, with the Red Hat Build of Agent + Sandbox Operator installed and the default OVN-Kubernetes network plugin. +- A default StorageClass for sandbox workspace volumes. +- `uv`, `oc`, `openssl`, Helm 3.17.3 or newer, and `kubectl` on the machine + running the installer. That machine needs access to the OpenShift API and to + the gateway and Dashboard chart registries, `ghcr.io` and `quay.io`. +- Cluster nodes must be able to pull the configured images. RHOAI images from + `registry.redhat.io` require cluster pull credentials. For disconnected + clusters, see [Disconnected clusters](#disconnected-clusters) for image mirroring guidance. +- A PostgreSQL database reachable from the OpenShell namespace, and an OIDC + provider reachable from the workloads and users, with a confidential browser + client using PKCE S256. The example uses Keycloak and PostgreSQL. For a + development Keycloak deployment, follow the [Keycloak development guide](keycloak-dev-guide.md). +- Permission to create resources in the target namespace. Cluster-scoped + permission to create namespaces when the installer creates it, read the + Namespace object, the Agent Sandbox CRD, the ClusterVersion, StorageClasses, + and Nodes, create and patch ClusterRoles and ClusterRoleBindings, and list + ConfigMaps in all namespaces. +- When the target namespace already exists, preflight also reads its ConfigMaps and Secrets. The installer also reads the cluster ingress domain unless you set both hosts explicitly in the config. Preflight checks the write permissions with `kubectl auth can-i` and fails on a denied read. + +The installer does not install the Agent Sandbox Operator, provision a database, +or deploy an identity provider. + +Choose one installation method below: `install.py` automates chart values, +Secrets, and preflight; the direct Helm path requires you to prepare them. + +## Install with `install.py` + +### Configure + +From the repository root, copy the example and its credential files outside +the checkout: ```shell export CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/openshell-rhoai" mkdir -p "$CONFIG_DIR" chmod 700 "$CONFIG_DIR" -cp deploy/rhoai/config-examples/config.example-rhoai-3.6-keycloak.json \ +cp deploy/rhoai/config-examples/config.example-rhoai-3.6-postgresql-keycloak.json \ "$CONFIG_DIR/config.json" chmod 600 "$CONFIG_DIR/config.json" ``` -Users who want operational overrides also copy -`config-examples/gateway-values.example.yaml` and/or -`config-examples/dashboard-values.example.yaml` beside the configuration. The -[Operational values overrides](#operational-values-overrides) section explains -how to wire them. - -## Edit the configuration - -Review the required fields first. They describe the deployment target and the -identity provider registration. The examples already pin published charts and -images; check them against [Chart and image pins](#chart-and-image-pins). - -### Required - -- `namespace` is the application namespace, for example `openshell-team`. The - installer rejects `default`, `kube-*`, and `openshift-*`. It deploys one - gateway and dashboard pair per namespace, and each pair needs distinct hosts - and OIDC identifiers: the OpenShift router does not admit the same host from - two namespaces. -- `gateway.chart`, `gateway.version`, `dashboard.chart`, and `dashboard.version` - are required. The examples pin published versions; replace the - `REPLACE_WITH_*` placeholders when you copy `config.example.json`. -- `oidc.issuer` is the provider's issuer URL. -- `oidc.client_id` is the dashboard browser client, conventionally - `openshell-dashboard-`. The Keycloak examples use - `openshell-dashboard-openshell-team`. -- `oidc.audience` is the gateway API audience, conventionally - `openshell-api-`, for example `openshell-api-openshell-team`. It - must differ from the client ID. -- `oidc.roles_claim` names the claim path the provider emits. Use - `realm_access.roles` for the Keycloak walkthrough; the generic examples use - `roles`. -- `oidc.admin_role` and `oidc.user_role` are the role names the gateway and - dashboard recognize. -- `oidc.client_secret_file` names the browser client secret file. It is required - for the first install, and paths in this field and `oidc.ca_file` resolve - relative to the configuration file. - -### Optional - -- `gateway.host` and `dashboard.host` are optional. When omitted, the installer - derives `gateway-.` and - `dashboard-.` from the cluster ingress domain - (`ingresses.config.openshift.io/cluster` `.spec.domain`), using the effective - namespace including `--namespace`. Set them explicitly to use a different - router domain; explicit hosts do not follow `--namespace`. Both hosts must be - distinct and sit under the router's `*.apps.` wildcard so DNS - resolves. The dashboard's edge Route uses the router certificate; the gateway - serves its own certificate through a passthrough Route. -- `context` is not a configuration field. Pass `--context` to select a kube - context; otherwise the installer uses the current kubeconfig context. -- `oidc.allowed_roles` is a dashboard login filter. The installer accepts it only - when `oidc.provider` is `keycloak-oidc`; for generic `oidc`, use - `oidc.allowed_groups`. The Keycloak examples list both roles that - [keycloak-dev-guide.md](keycloak-dev-guide.md) creates, as an example choice, - not a requirement; with `keycloak-oidc`, any role list the provider emits works. -- `oidc.scope` is the space-separated OAuth scope request, for example - `openid email profile`. Omit it to keep the provider defaults. -- `oidc.cli_client_id` is the public client the `openshell` CLI registers as. - It defaults to `openshell-cli-`; keep that default so each - gateway's CLI client carries only its own audience. - -Register `https:///oauth2/callback` with the identity provider. -With the default configuration, `` is -`dashboard-.`. - -### OIDC issuer certificate - -Set `ca_file` in the config file only when the OIDC issuer's certificate is not publicly trusted, -for example a self-signed certificate or a private CA. The Keycloak examples -set `"ca_file": "ingress-ca.crt"` because the development Keycloak serves -through an OpenShift Route that uses the cluster's default ingress certificate, -which is self-signed. - -Create that file before `--check`: +Edit `config.json` before installing: -```shell -oc -n openshift-config-managed get configmap default-ingress-cert \ - -o jsonpath='{.data.ca-bundle\.crt}' \ - > "$CONFIG_DIR/ingress-ca.crt" -``` - -When `ca_file` is set, the installer creates the `openshell-oidc-ca` ConfigMap -and mounts it in both releases so the gateway and dashboard trust the issuer. -Leave the field unset for publicly trusted issuers, such as an external -identity provider or a cluster with custom router certificates; the installer -then creates no ConfigMap and both workloads use the system trust roots. - -### Chart and image pins - -- `version` in each section is the OpenShell Helm chart version, not the image tag. -- RHOAI image digests come from the rhods-operator.3.6.0 CSV. Refresh them with the command - in [config-examples/README.md](config-examples/README.md), or use the - `rhoai-3.6` tag instead. -- The ODH examples use `v0.1.7-rhaiv.0` images. -- When both are present, `digest` takes precedence over `tag`. -- `gateway.images.sandbox` uses a full repository path and has no separate - registry key. The image must provide a shell at `/bin/bash`, `/usr/bin/bash`, - or `/bin/sh`. -- Supported architectures: the installer runs on amd64-only clusters. Mixed - amd64/arm64 clusters are not supported because the Red Hat Build of Agent - Sandbox Operator is not available on arm64. The RHOAI 3.6 images and the ODH - gateway, supervisor, and sandbox images are already multi-arch, but the ODH - dashboard image is amd64-only and pairs with dashboard chart `0.1.5`. -- Use the `vX.Y.Z-rhaiv.N` tagged images for ODH, not the moving `odh-stable` - tag. - -### Operational values overrides - -`gateway.values_files` and `dashboard.values_files` list YAML or JSON files -whose paths resolve relative to the configuration. The installer merges the -files in order and re-applies the result on every install and rerun. See -[Chart values](config-examples/README.md#chart-values) for the allowed -override set. - -`config-examples/gateway-values.example.yaml` and -`config-examples/dashboard-values.example.yaml` are optional, ready-to-edit -values overrides for the operational knobs the installer allows: resource -requests and limits, `imagePullSecrets`, gateway -`server.workspaceStorageClass`, dashboard `authProxy` settings, and router -NetworkPolicy peers. Copy a file beside the private configuration, edit the -sizes and fields for the workload, and add its filename to the matching chart's -`values_files` list, for example: - -```json -"values_files": ["gateway-values.yaml"] -``` - -Skipping them installs the chart defaults. Keep the same files on reruns so the -upgrade applies the intended values. - -### Database backend - -This installer always deploys the gateway with its default SQLite database. -Preflight requires a default block-backed StorageClass for the gateway's PVC, -and the values allowlist rejects database settings. This is a limitation of the -installer script, not of OpenShell: the gateway chart accepts -`server.externalDbSecret` with a Secret that holds a PostgreSQL connection URI. -Using PostgreSQL requires extending the installer or installing the chart -directly. - -## Save the client secret - -Save the secret of the dashboard browser client from Keycloak or your OIDC -provider beside the configuration: +- Set `namespace` to the OpenShell namespace you will use. +- Set `oidc.issuer` to your provider's issuer URL. The example uses + `https://keycloak.apps.example.com/realms/openshell`. +- Register `https://dashboard-./oauth2/callback` as + the browser client's callback URL. The example's client ID, audience, role + claim, and role names match the Keycloak development guide; keep them aligned + with your provider. +- The example pins RHOAI 3.6 images by digest. For another RHOAI build, use the + image digests for that build. + +Save the browser client secret in the file named by `oidc.client_secret_file` +(`dashboard-client-secret.txt` in the example): ```shell umask 077 -mkdir -p "$CONFIG_DIR" -printf 'Dashboard client secret: ' -IFS= read -rs SECRET -echo -printf '%s' "$SECRET" > "$CONFIG_DIR/dashboard-client-secret.txt" -unset SECRET +read -rsp 'OIDC client secret: ' OIDC_SECRET +printf '\n' +printf '%s' "$OIDC_SECRET" > "$CONFIG_DIR/dashboard-client-secret.txt" +unset OIDC_SECRET chmod 600 "$CONFIG_DIR/dashboard-client-secret.txt" ``` -The `printf` prompt and `read -rs` keep the secret off the screen and out of the -shell history. When the -[Keycloak client helper](keycloak-dev-guide-create-openshell-clients.sh) created -the client, it already wrote this file; skip this step in that case. Do not put -the secret in the JSON, Helm values, or command arguments. +For an existing PostgreSQL database, save its URI in the file named by +`gateway.database.uri_file` (`gateway-db-uri.txt`). If you want to run a +development database in the OpenShell namespace, skip this and use the next +section, which creates the file for you. + +```shell +umask 077 +read -rsp 'PostgreSQL URI: ' DB_URI +printf '\n' +printf '%s' "$DB_URI" > "$CONFIG_DIR/gateway-db-uri.txt" +unset DB_URI +chmod 600 "$CONFIG_DIR/gateway-db-uri.txt" +``` + +Use a URI such as `postgresql://user:password@host:5432/database?sslmode=verify-full`. Keep the database password out of `config.json`. Without `sslmode`, the gateway uses +TLS only when the server offers it and does not verify the certificate. With +`verify-full`, the server certificate must chain to a CA in the gateway +image's system trust store. The installer does not mount a separate database +CA, so a database signed by a private CA cannot use `verify-full` yet; +`sslmode=require` encrypts the connection but does not verify the server. -## Validate, preflight, and install +The database outlives the namespace. The gateway encrypts stored provider +credentials with the key in the `openshell-credential-storage-key-encryption-key` +Secret, so back up that Secret together with the database (see [Upgrade an installation](#upgrade-an-installation)). If you reinstall into a recreated namespace with the same name against the same database, create the namespace, restore the Secret with +`oc apply -f "$CONFIG_DIR/key-encryption-key-secret.json"`, and run the +installer with `--adopt-existing`: the restored key counts as existing key material, and deleting it as the installer's error suggests makes the chart generate a new key that cannot +decrypt the stored credentials. -The script's shebang runs it through `uv`, which installs its pinned PyYAML -dependency, so `uv` must be on your `PATH`. +The Keycloak development guide uses the cluster's default ingress certificate. +For that setup, create the CA file referenced by `oidc.ca_file` in the example: -Validate both charts without touching the cluster: +```shell +oc -n openshift-config-managed get configmap default-ingress-cert \ + -o jsonpath='{.data.ca-bundle\.crt}' > "$CONFIG_DIR/ingress-ca.crt" +``` + +For an issuer with a publicly trusted certificate, remove `ca_file` from the +config instead. + +### Set up PostgreSQL for development + +For development, you can run PostgreSQL in the OpenShell namespace. This +single-instance database is not a production setup. Set `NS` to the namespace +in `config.json` and use the `CONFIG_DIR` from above: ```shell -./deploy/rhoai/install.py \ - --config "$CONFIG_DIR/config.json" --check +export NS=openshell-team +if ! oc get namespace "$NS" >/dev/null 2>&1; then + oc create namespace "$NS" && + oc label namespace "$NS" openshell.ai/installer=odh-dashboard +fi ``` -Expect `Both charts rendered successfully. This does not verify cluster or API -compatibility.` The check downloads the pinned charts but does not access the -cluster. +The label marks the new, empty namespace as created for the installer, so +reruns do not need `--adopt-existing`. Do not add it to a namespace that +already existed; see [Reinstalling into an existing namespace](#reinstalling-into-an-existing-namespace). -When a configuration omits the hosts, `--check` renders them as -`gateway-.apps.example.com` and -`dashboard-.apps.example.com`; the install derives the real hosts -from the cluster. Pass `--apps-domain ` to render the real derived hosts -offline. +Labeling the namespace requires permission to patch namespaces. If `oc create +namespace` succeeds but `oc label` fails, have an administrator add the label: +without it, the installer finds its state but not the namespace marker, and a +rerun requires `--adopt-existing`. -Run cluster preflight without installing: +Create a password Secret and a persistent volume claim: ```shell -./deploy/rhoai/install.py \ - --config "$CONFIG_DIR/config.json" --preflight +openssl rand -hex 16 | tr -d '\n' | \ + oc -n "$NS" create secret generic openshell-db-secret \ + --from-literal=username=openshell --from-file=password=/dev/stdin + +oc -n "$NS" apply -f - <<'EOF' +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: openshell-db-data +spec: + accessModes: [ReadWriteOnce] + resources: + requests: + storage: 5Gi +EOF ``` -Expect `Cluster preflight passed; no installation resources were changed.` -Preflight prints the target context and namespace. When a host is omitted, it -also resolves the ingress apps domain and uses the derived hosts for the -installer's identity checks. +Create the database Deployment and Service from the Red Hat PostgreSQL image, +then add the password Secret and persistent storage: + +```shell +oc -n "$NS" new-app \ + registry.access.redhat.com/hi/postgresql@sha256:67599d73c3dae0e8685c2f9ba31c11028477816bbc254cf862543cfb11c2dc3f \ + -e POSTGRES_USER=openshell \ + -e POSTGRES_DATABASE=openshell \ + -e PGDATA=/var/lib/postgresql/data/pgdata \ + --name=openshell-db + +oc -n "$NS" patch deployment/openshell-db --type=json -p \ + '[{"op":"add","path":"/spec/template/spec/containers/0/env/-","value":{"name":"POSTGRES_PASSWORD","valueFrom":{"secretKeyRef":{"name":"openshell-db-secret","key":"password"}}}}]' + +oc -n "$NS" set volume deployment/openshell-db \ + --add --overwrite --name=openshell-db-volume-1 \ + --type=persistentVolumeClaim --claim-name=openshell-db-data \ + --mount-path=/var/lib/postgresql + +oc -n "$NS" rollout status deployment/openshell-db +``` + +If the image version uses a different volume name, inspect the Deployment and +use its volume name with `oc set volume`. Once PostgreSQL is ready, create the +URI file used by the installer without printing the password: + +```shell +umask 077 +DB_PASSWORD="$(oc -n "$NS" get secret openshell-db-secret \ + -o jsonpath='{.data.password}' | base64 -d)" +printf 'postgresql://openshell:%s@openshell-db.%s.svc.cluster.local:5432/openshell' \ + "$DB_PASSWORD" "$NS" > "$CONFIG_DIR/gateway-db-uri.txt" +unset DB_PASSWORD +chmod 600 "$CONFIG_DIR/gateway-db-uri.txt" +``` + +The installer copies this URI into its gateway Secret; it does not create or validate the database. If the namespace has default-deny egress policies, allow the gateway to reach the database Service on port 5432. + +### Run the installer + +Validate the chart templates, then check cluster prerequisites: + +```shell +./deploy/rhoai/install.py --config "$CONFIG_DIR/config.json" --check +./deploy/rhoai/install.py --config "$CONFIG_DIR/config.json" --preflight +``` Install: ```shell -./deploy/rhoai/install.py \ - --config "$CONFIG_DIR/config.json" +./deploy/rhoai/install.py --config "$CONFIG_DIR/config.json" ``` -The installer prints the dashboard and gateway URLs. `--namespace` overrides the -namespace; when hosts are omitted, the derived hosts follow it. Explicit hosts -and OIDC identifiers do not change, so keep the provider registrations in sync. -`--context` overrides the kube context. Set `--timeout 15m` for a slower -cluster. On failure, the installer leaves the created resources for diagnosis; -correct the cause and rerun the same command. +Pass `--context CONTEXT` to target a kubeconfig context other than the current +one, or `--namespace NAME` to override the configured namespace. The installer +prints the gateway and Dashboard URLs and the next steps for registering the +gateway with the OpenShell CLI. -When the install finishes, the installer also prints the next steps with your -configuration values: install the matching OpenShell CLI, register the gateway -with its CA, check the connection with `openshell status`, and create a sandbox -with `openshell sandbox create`. The printed `kubectl` command includes the kube -context the install targeted, so it reads the CA Secret from the same cluster. -The following sections describe the same steps in more detail, including the -trust setup for custom identity providers. +### Reinstalling into an existing namespace -## Register the gateway and log in +When the namespace already exists and holds installer state (the `openshell-installer` ConfigMap) or gateway key material (`openshell-server-tls`, `openshell-client-tls`, `openshell-jwt-keys`, `openshell-credential-storage-key-encryption-key`, `openshell-dashboard-oidc`), the installer reuses it only when the namespace proves the installer created the deployment: the Namespace carries the `openshell.ai/installer:odh-dashboard` label and the installer state is present. The installer sets the label when it creates the namespace. Namespace editors cannot set it on a namespace they do not administer, so the installer does not trust the ConfigMap label alone. -The installer prints these commands with the values from your configuration; use -its output when it differs from the examples below. +Do not add the label to a namespace that other users could already write to, such as an existing Data Science Project: anyone with edit access could have planted these objects, and the gateway would reuse their keys. Instead, inspect the listed objects and pass `--adopt-existing` only if they come from a previous installation of this gateway; otherwise delete them first. -Install the OpenShell CLI. The examples in this guide use `v0.1.7`; install the -version that matches the gateway release you deployed: +## Install directly with Helm + +Use this alternative when you want to manage the gateway and Dashboard Helm +releases yourself. The configuration and PostgreSQL sections above still +apply, but Helm does not create the database, credentials, issuer CA ConfigMap, +or validate the cluster prerequisites for you. + +Set `NS` to the target namespace. Use the same namespace and Route hosts in the +values files below, and register the Dashboard callback URL with your OIDC +provider: ```shell -curl -LsSf https://raw.githubusercontent.com/NVIDIA/OpenShell/main/install.sh \ - | OPENSHELL_VERSION=v0.1.7 sh +export NS=openshell-team +oc get namespace "$NS" >/dev/null 2>&1 || oc create namespace "$NS" ``` -The upstream installer also deploys and starts a local gateway on the -workstation that runs it: a user service on Linux and a Homebrew service on -macOS. This is a limitation of the upstream installer. The local gateway is -separate from the cluster gateway deployed above and is not used by this -guide's remote-cluster workflow. If it conflicts with an existing local -installation, remove its registration with `openshell gateway remove openshell`. +Create the Secrets consumed by the charts. The gateway Secret needs a `uri` +key; the Dashboard Secret needs `client-secret` and `cookie-secret` keys: -The gateway Route is TLS passthrough serving a private CA, and OIDC discovery -uses the ingress CA. Trust both paths before adding the gateway. +```shell +oc -n "$NS" create secret generic openshell-gateway-db \ + --from-file=uri="$CONFIG_DIR/gateway-db-uri.txt" -Set `CTX` to the context you installed with — the value passed to `--context`, -or the current kubeconfig context when `--context` was not passed — so the -certificate commands below read from the same cluster: +openssl rand -base64 32 | tr '+/' '-_' | tr -d '=\n' \ + > "$CONFIG_DIR/dashboard-cookie-secret.txt" +chmod 600 "$CONFIG_DIR/dashboard-cookie-secret.txt" +oc -n "$NS" create secret generic openshell-dashboard-oidc \ + --from-file=client-secret="$CONFIG_DIR/dashboard-client-secret.txt" \ + --from-file=cookie-secret="$CONFIG_DIR/dashboard-cookie-secret.txt" +``` + +If the OIDC issuer uses a private CA, create the ConfigMap referenced by both +charts. Omit `caConfigMapName` from both values files below when the issuer is +publicly trusted: ```shell -CTX=YOUR_INSTALL_CONTEXT +oc -n "$NS" create configmap openshell-oidc-ca \ + --from-file=ca.crt="$CONFIG_DIR/ingress-ca.crt" +``` + +Create `gateway-values.yaml` and `dashboard-values.yaml` in `$CONFIG_DIR`. Set +the OIDC fields and hosts to match your provider and Routes. These values show +the Keycloak development guide defaults: + +```yaml +# gateway-values.yaml +fullnameOverride: openshell +podSecurityContext: null +securityContext: + runAsUser: null + seccompProfile: + type: RuntimeDefault +workload: + kind: deployment +server: + disableTls: false + sandboxNamespace: openshell-team + auth: + allowUnauthenticatedUsers: false + tls: + enableMtls: false + clientCaSecretName: "" + certSecretName: openshell-server-tls + clientTlsSecretName: openshell-client-tls + externalDbSecret: openshell-gateway-db + oidc: + issuer: https://keycloak.apps.example.com/realms/openshell + audience: openshell-api-openshell-team + rolesClaim: realm_access.roles + adminRole: openshell-admin + userRole: openshell-user + caConfigMapName: openshell-oidc-ca +pkiInitJob: + enabled: true + serverDnsNames: + - gateway-openshell-team.apps.example.com + - openshell.openshell-team.svc + - openshell.openshell-team.svc.cluster.local +openshiftRoute: + enabled: true + host: gateway-openshell-team.apps.example.com ``` -Copy the gateway server CA into the CLI's per-gateway TLS directory. The -directory name must match the `--name` value you use below: +```yaml +# dashboard-values.yaml +fullnameOverride: openshell-dashboard +podSecurityContext: null +securityContext: + runAsUser: null + seccompProfile: + type: RuntimeDefault +gateway: + url: grpcs://openshell.openshell-team.svc.cluster.local:8080 + caSecretName: openshell-client-tls +oidc: + provider: keycloak-oidc + issuer: https://keycloak.apps.example.com/realms/openshell + clientId: openshell-dashboard-openshell-team + existingSecret: openshell-dashboard-oidc + audience: openshell-api-openshell-team + rolesClaim: realm_access.roles + adminRole: openshell-admin + userRole: openshell-user + codeChallengeMethod: S256 + allowedRoles: [openshell-admin, openshell-user] + caConfigMapName: openshell-oidc-ca + scope: openid email profile +openshiftRoute: + enabled: true + host: dashboard-openshell-team.apps.example.com + termination: edge +networkPolicy: + ingressNamespace: openshift-ingress +``` + +For a publicly trusted issuer, remove `caConfigMapName` from both values +files. For the RHOAI images in the example config, copy each `registry`, +`repository`, and `digest` into the corresponding chart image values: + +| Installer config field | Helm values path | +| ------------------------------- | --------------------------------------------------- | +| `gateway.images.gateway` | `gateway.image` | +| `gateway.images.supervisor` | `supervisor.image` | +| `gateway.images.sandboxRuntime` | `sandboxRuntime.image` | +| `gateway.images.sandbox` | `sandbox.image` (`repository` is a full image path) | +| `dashboard.images.dashboard` | `dashboard.image` | +| `dashboard.images.authProxy` | `authProxy.image` | + +Install the gateway first so it creates the TLS Secrets used by the Dashboard, +then install the Dashboard: ```shell -mkdir -p "${XDG_CONFIG_HOME:-$HOME/.config}/openshell/gateways/openshell-team/mtls" -oc --context "$CTX" -n openshell-team get secret openshell-client-tls \ - -o jsonpath='{.data.ca\.crt}' | base64 -d \ - > "${XDG_CONFIG_HOME:-$HOME/.config}/openshell/gateways/openshell-team/mtls/ca.crt" +helm upgrade --install openshell \ + oci://ghcr.io/nvidia/openshell/helm-chart --version 0.1.3 \ + --namespace "$NS" --values "$CONFIG_DIR/gateway-values.yaml" \ + --wait --wait-for-jobs --timeout 15m + +helm upgrade --install openshell-dashboard \ + oci://quay.io/ai-openshell/charts/console --version 0.1.5 \ + --namespace "$NS" --values "$CONFIG_DIR/dashboard-values.yaml" \ + --wait --timeout 15m ``` -The CLI stores gateway metadata under `${XDG_CONFIG_HOME:-$HOME/.config}/openshell`. +The values shown target the example's chart versions and namespace. If you +change either version or the namespace, update the chart versions, image pins, +OIDC identifiers, Service URL, and certificate DNS names together. For other +chart options, see the [gateway chart values](../helm/openshell/values.yaml) and inspect the Dashboard chart values with +`helm show values oci://quay.io/ai-openshell/charts/console --version 0.1.5`. -OIDC bearer authentication needs only `ca.crt` in this directory. +## After installation: install the CLI and create a sandbox -Build an `SSL_CERT_FILE` bundle from the system roots plus the ingress CA. -Skip this and the ConfigMap command below when your OIDC issuer's certificate -is publicly trusted (`oidc.ca_file` unset): the installer creates no -`openshell-oidc-ca` ConfigMap, no ingress CA file exists, and the CLI uses the -system trust roots unchanged. Setting `SSL_CERT_FILE` replaces the default -bundle, so never point it at the ingress CA alone: +Install the CLI version that matches the gateway chart version. This example +uses `0.1.3`: ```shell -cat /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem \ - "$CONFIG_DIR/ingress-ca.crt" \ - > "$CONFIG_DIR/ca-bundle.pem" -export SSL_CERT_FILE="$CONFIG_DIR/ca-bundle.pem" +curl -LsSf https://raw.githubusercontent.com/NVIDIA/OpenShell/main/install.sh \ + | OPENSHELL_VERSION=v0.1.3 sh ``` -The installer prints the system bundle path it detects for the host it runs -on. If you run these commands on another host, substitute the matching path: -`/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem` on Fedora and RHEL, -`/etc/ssl/certs/ca-certificates.crt` on Debian and Ubuntu, and -`/etc/ssl/cert.pem` on macOS. You may also source the ingress CA from the -installer-created ConfigMap: +The upstream installer also starts a separate local gateway on this machine; +the commands below use the gateway deployed in OpenShift. On a disconnected +workstation, bring over the matching CLI binary instead. + +Set `NS` to the installed namespace and `CTX` to the kubeconfig context used +during installation (`--context`, or the current context if omitted). Copy the +gateway CA into the CLI's per-gateway trust directory: ```shell -oc --context "$CTX" -n openshell-team get configmap openshell-oidc-ca \ - -o jsonpath='{.data.ca\.crt}' > "$CONFIG_DIR/ingress-ca.crt" +export NS=openshell-team +export CTX=YOUR_INSTALL_CONTEXT +GATEWAY_MTLS_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/openshell/gateways/$NS/mtls" +mkdir -p "$GATEWAY_MTLS_DIR" +oc --context "$CTX" -n "$NS" get secret openshell-client-tls \ + -o jsonpath='{.data.ca\.crt}' | base64 -d > "$GATEWAY_MTLS_DIR/ca.crt" ``` -Register the gateway: +If `oidc.ca_file` is set for a private or self-signed identity provider, +combine that CA with the workstation's system CA bundle and set +`SSL_CERT_FILE`. This example uses the Fedora/RHEL bundle path; use the path +reported by the installer on other systems: + +```shell +cat /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem \ + "$CONFIG_DIR/ingress-ca.crt" > "$CONFIG_DIR/ca-bundle.pem" +export SSL_CERT_FILE="$CONFIG_DIR/ca-bundle.pem" +``` + +Register the gateway, replacing the example OIDC values and URL with those in +`config.json` and the URL printed by the installer. The CLI client ID defaults +to `openshell-cli-` if `oidc.cli_client_id` is not set: ```shell openshell gateway add \ - --name openshell-team \ + --name "$NS" \ --oidc-issuer "https://keycloak.apps.example.com/realms/openshell" \ - --oidc-client-id openshell-cli-openshell-team \ - --oidc-audience openshell-api-openshell-team \ + --oidc-client-id "openshell-cli-$NS" \ + --oidc-audience "openshell-api-$NS" \ "https://gateway-openshell-team.apps.example.com:443" +openshell status ``` -Replace the issuer with your configuration value. The gateway URL is the derived -default `gateway-.`; use the URL the installer printed. -The command opens a browser for the Authorization Code + PKCE login. +Sign in with an identity that has the configured admin or user role and access +to a workspace. The CLI uses the `default` workspace unless you select another +one with `--workspace` or `OPENSHELL_WORKSPACE`. -Sign in as a user that holds the gateway's admin role or user role. The admin -role is configured in `oidc.admin_role` (`openshell-admin` in the Keycloak -examples), and the user role in `oidc.user_role` (`openshell-user`). A user who -holds neither role can complete the login, but the gateway rejects their API -calls. A user with the admin role creates workspaces and must add users as -members before those users can work there; a user with the user role works only -in workspaces where they are a member. +Create a sandbox: -The CLI targets the `default` workspace unless you select another one. If an -administrator assigned you to a different workspace, pass `--workspace ` -to each command or export `OPENSHELL_WORKSPACE=`; your account may not be -authorized for the `default` workspace. See -[Workspaces](https://docs.nvidia.com/openshell/latest/how-it-works/workspaces) -for workspace creation and membership. +```shell +openshell sandbox create --timeout 600 +``` -Verify the registration and login: +The gateway assigns the sandbox a name and opens a shell. `--timeout` is the +provisioning idle timeout; the first create after a fresh install can spend +longer than the 300-second default pulling the supervisor and sandbox images. +Exit with Control+D to leave it running; use `openshell sandbox list` and +`openshell sandbox connect ` to return to it. + +## Upgrade an installation + +To move an installation to newer OpenShell releases, rerun the installer with a +configuration that pins the new chart versions and images. The installer runs +`helm upgrade` on both releases and keeps the gateway's TLS, JWT, and +credential-storage keys. It does not compare the old and new versions, so it +does not stop a downgrade or an untested version pair; check the release notes +before you change versions. + +Copy your current `config.json` and change only `gateway.chart`, +`gateway.version`, `dashboard.chart`, `dashboard.version`, and the `images` +pins, for example from a newer file in `config-examples/`. Keep the namespace, +hosts, `oidc` settings, `gateway.database.mode`, and the client secret and +database URI files. The installer refuses a change to the gateway host, the +OIDC issuer, audience, or client ID, or the database backend, and it refuses +secret files that differ from the Secrets in the namespace. It accepts a +dashboard host change, but re-register the dashboard callback URL with the +identity provider first. + +The new gateway migrates the database schema when it starts, and an older +gateway cannot start against the migrated schema. Before you upgrade, back up +the database with your database's tooling, and save the key-encryption key +Secret, without which the provider credentials in the backup cannot be +decrypted. Run the backup and upgrade commands in the kubeconfig context you +installed into; the installer's `--context` is not remembered. + +Set `NS` to the installed namespace and `CONFIG_DIR` to the directory that +holds your configuration and credential files: ```shell -openshell status +export NS=openshell-team +export CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/openshell-rhoai" ``` -Expect `Status: Connected` and `Authentication: Authenticated (OIDC)`. - -`--gateway-insecure` skips gateway certificate verification for local testing -only; do not use it beyond development. For the identity-provider side, see -[keycloak-dev-guide.md](keycloak-dev-guide.md). +This command requires `jq`: -## Create and use a sandbox +```shell +umask 077 +oc -n "$NS" get secret openshell-credential-storage-key-encryption-key -o json \ + | jq 'del(.metadata.uid, .metadata.resourceVersion, + .metadata.creationTimestamp, .metadata.managedFields)' \ + > "$CONFIG_DIR/key-encryption-key-secret.json" +``` -List the sandbox subcommands: +For the development database from +[Set up PostgreSQL for development](#set-up-postgresql-for-development): ```shell -openshell sandbox --help +oc -n "$NS" exec deployment/openshell-db -- \ + pg_dump -U openshell openshell > "$CONFIG_DIR/openshell-db.sql" ``` -Create a sandbox: +In SQLite mode the data lives in the gateway's persistent volume claim; back it +up with your storage tooling instead. + +Store the backups somewhere safe; the Secret file contains the key in clear +text. Then validate and upgrade: ```shell -openshell sandbox create +./deploy/rhoai/install.py --config "$CONFIG_DIR/config-new.json" --check +./deploy/rhoai/install.py --config "$CONFIG_DIR/config-new.json" --preflight +./deploy/rhoai/install.py --config "$CONFIG_DIR/config-new.json" ``` -The gateway assigns the sandbox an auto-generated name, for example -`juicy-lacewing`. Exit the initial shell with Control+D to keep the sandbox -running; pass `--no-keep` to delete it when the shell exits instead. +After the upgrade: + +- Install the CLI version that matches the new gateway chart version, as in + [After installation](#after-installation-install-the-cli-and-create-a-sandbox). +- Existing sandboxes keep their supervisor and sandbox images until they are + recreated. Create a new sandbox to check the new images, and check that the + existing sandboxes still respond. + +You cannot roll back in place. To return to the previous versions, stop the +gateway first so no writes reach the database during the restore +(`oc -n "$NS" scale deployment/openshell --replicas=0`, or +`statefulset/openshell` in SQLite mode). Restore the backup into the database +the previous configuration points at after emptying it, then rerun the +installer with the previous configuration. The installer requires the URI in +`gateway-db-uri.txt` to match the existing `openshell-gateway-db` Secret, so +restoring into a different database also requires updating that Secret and the +URI file first. -List the sandboxes in the workspace: +## Uninstall + +Uninstalling deletes the sandboxes, the gateway's keys, and in SQLite mode the +gateway data. To reinstall later with the same data, back up the database and +the key-encryption key Secret first, as described in +[Upgrade an installation](#upgrade-an-installation). + +The commands in this section use the current kubeconfig context. Select the +context you installed into first if you used `--context`; `$NS` can also exist +in another cluster. + +Set `NS` to the installed namespace and `CONFIG_DIR` to the directory that +holds your configuration and credential files: ```shell -openshell sandbox list +export NS=openshell-team +export CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/openshell-rhoai" ``` -Stop, start, and reconnect to a sandbox by name: +While the gateway is still running, delete the sandboxes in each workspace and +remove the CLI registration: ```shell -openshell sandbox stop juicy-lacewing -openshell sandbox start juicy-lacewing -openshell sandbox connect juicy-lacewing -``` - -For more comprehensive sandbox and agent examples, see -[Run Your First Agent](https://docs.nvidia.com/openshell/latest/about/run-your-first-agent) -and [How it works](https://docs.nvidia.com/openshell/how-it-works). - -## Using the OpenShell Dashboard UI - -The installer deploys the dashboard beside the gateway and prints its URL. With -omitted hosts, the URL is `https://dashboard-.`; when -hosts are set explicitly, use the value the installer printed. Open the URL and -sign in through the configured OIDC provider. - -The dashboard shows different features depending on the signed-in user's role. -With `oidc.provider: "keycloak-oidc"`, the account must hold a role listed in -`oidc.allowed_roles`; the Keycloak examples list `openshell-admin` and -`openshell-user`. With generic `oidc`, list the provider's group in -`oidc.allowed_groups` instead. When neither filter is set, any authenticated -identity-provider user can reach the UI, but the gateway still enforces its -roles and workspace access. A user with the admin role -(`oidc.admin_role`) can create workspaces and add users to them. A user with the -user role (`oidc.user_role`) sees the workspaces they were added to and manages -them, including creating sandboxes. - -Use the dashboard to: - -- Create and delete workspaces and manage their members (admin role). -- Create sandboxes with a policy or from a workspace template, then stop, start, - and delete them. -- Open a sandbox to view its logs, use an interactive terminal, upload and - download files, inspect exposed services and attached providers, and review - its settings. -- Manage network policy with revision history, a network-rule editor, and - proposed policy changes per sandbox. -- Register provider credentials and manage provider profiles. -- View gateway status, version, compute drivers, settings, and resources across - all workspaces. - -For more information about the dashboard, see -[ai-openshell/console](https://github.com/ai-openshell/console). - -## Verify workspace authorization - -Use the read-only verifier after provisioning two distinct identities and two -existing workspaces. The administrator must access both workspaces; the -ordinary user must belong only to the allowed workspace. Save fresh access -tokens in files with mode `0600` outside the checkout, using your identity -provider's supported login flow: +openshell workspace list +openshell sandbox delete --all --workspace +openshell gateway remove "$NS" +``` -```shell -uv run --script --python 3.12 deploy/rhoai/verify.py \ - --namespace research-team \ - --dashboard-url https://dashboard-research-team.apps.example.com \ - --admin-role openshell-admin \ - --admin-token-file /secure/admin-token.txt \ - --user-token-file /secure/user-token.txt \ - --allowed-workspace team-a --denied-workspace team-b -``` - -`--context` defaults to the current kubeconfig context; pass it to check -another context. The verifier checks unauthenticated rejection, gateway -identity and roles, administrator access to both workspaces, and ordinary-user -access to one workspace and denial in the other. It opens a temporary -loopback-only port-forward to the dashboard BFF, so it requires -`pods/portforward` permission. It performs GET requests only and does not -change users, memberships, or workloads. - -Optional `--other-gateway-token-file` checks rejection of a token for another -gateway. Confirm that token works on its intended gateway first: an expired or -otherwise invalid token cannot prove audience isolation. Optional -`--session-cookie-file` checks the public session endpoint with the Cookie -header value from an already logged-in browser. `--ca-file` adds a private -Route CA to system trust. The verifier closes its port-forward on success or -failure and never follows redirects with credentials or prints tokens. -Confirm denied cross-workspace access before sharing the deployment; readiness -and Route admission alone do not prove workspace isolation. - -## Rerun and upgrade - -Rerun the same command after correcting a failure. Both releases receive the -generated values with `--reset-values`, including the configured values files, -so out-of-band Helm value edits are not preserved. - -Changing the gateway host, issuer, audience, or client ID is rejected by the -`openshell-installer` state and needs an explicit identity migration. When hosts -are omitted, changing the namespace or the cluster apps domain changes the -derived gateway host and triggers the same check. - -A changed client secret or OIDC CA requires explicit rotation. Set `CTX` to the -context used for the installation (the `--context` value, or the current -kubeconfig context when `--context` was not passed), then update the Secret -while preserving `cookie-secret` and restart the dashboard: +Uninstall both releases. This also removes the gateway's cluster-scoped RBAC, +which deleting the namespace alone would leave behind: ```shell -CTX=YOUR_INSTALL_CONTEXT -COOKIE_FILE=$(mktemp) -oc --context "$CTX" -n openshell-team get secret openshell-dashboard-oidc \ - -o jsonpath='{.data.cookie-secret}' | base64 -d > "$COOKIE_FILE" -oc --context "$CTX" -n openshell-team create secret generic openshell-dashboard-oidc \ - --from-file=client-secret="$CONFIG_DIR/dashboard-client-secret.txt" \ - --from-file=cookie-secret="$COOKIE_FILE" \ - --dry-run=client -o yaml | oc --context "$CTX" apply -f - -rm -f "$COOKIE_FILE" -oc --context "$CTX" -n openshell-team rollout restart deployment openshell-dashboard +helm uninstall openshell-dashboard -n "$NS" +helm uninstall openshell -n "$NS" ``` -When the OIDC issuer's CA changes and `oidc.ca_file` is set, also rotate the -`openshell-oidc-ca` ConfigMap that both releases mount. The Secret commands -above do not update it, so the gateway and dashboard keep trusting the old CA -and fail issuer TLS verification; the installer also rejects a rerun until the -ConfigMap matches the new `ca_file`. Update the ConfigMap and restart both -workloads: +Helm keeps the objects that the installer created and the key material the +gateway chart reuses on reinstall. If the installer created the namespace for +this deployment, delete the namespace. This also removes the development +PostgreSQL database if you deployed it there: ```shell -oc --context "$CTX" -n openshell-team create configmap openshell-oidc-ca \ - --from-file=ca.crt="$CONFIG_DIR/ingress-ca.crt" \ - --dry-run=client -o yaml | oc --context "$CTX" apply -f - -oc --context "$CTX" -n openshell-team rollout restart \ - "$(oc --context "$CTX" -n openshell-team get statefulset,deployment \ - -l app.kubernetes.io/name=openshell,app.kubernetes.io/instance=openshell -o name)" -oc --context "$CTX" -n openshell-team rollout restart deployment openshell-dashboard +oc delete namespace "$NS" ``` -The gateway runs as StatefulSet `openshell` with the default SQLite backend and -as Deployment `openshell` when `server.externalDbSecret` is configured. The -selector restarts whichever object the release uses without naming its kind. - -There is no cross-release transaction or automatic rollback: a gateway success -followed by a dashboard failure leaves the upgraded gateway in place. +In a namespace that also holds other workloads, delete the remaining objects +and the ownership label instead: -## Remove an installation +```shell +oc -n "$NS" delete configmap openshell-installer openshell-oidc-ca --ignore-not-found +oc -n "$NS" delete secret openshell-gateway-db openshell-dashboard-oidc \ + openshell-server-tls openshell-client-tls openshell-jwt-keys \ + openshell-credential-storage-key-encryption-key --ignore-not-found +oc -n "$NS" delete pvc openshell-data-openshell-0 --ignore-not-found +oc label namespace "$NS" openshell.ai/installer- +``` -The installer has no uninstall subcommand. Set `CTX` to the context used for the -installation (the `--context` value, or the current kubeconfig context when -`--context` was not passed), then remove the dashboard first, then the gateway: +For the development database, also run: ```shell -CTX=YOUR_INSTALL_CONTEXT -helm uninstall openshell-dashboard -n openshell-team --kube-context "$CTX" -helm uninstall openshell -n openshell-team --kube-context "$CTX" +oc -n "$NS" delete all -l app=openshell-db +oc -n "$NS" delete pvc openshell-db-data +oc -n "$NS" delete secret openshell-db-secret ``` -The gateway chart's certificate hook creates three Secrets outside the release -manifest, so `helm uninstall` does not remove them. Delete them and the -installer-owned authentication objects: +Check `oc -n "$NS" get pvc` for leftover sandbox workspace claims. + +The installer does not manage an external database or the identity provider: +drop the OpenShell database with your database's tooling, and remove the OIDC +clients as described in the [Keycloak development guide](keycloak-dev-guide.md#cleanup). + +Delete `$CONFIG_DIR` when you no longer need it; it holds the client secret and the +database URI. + +## Disconnected clusters + +Skip this section if your cluster nodes can pull from `registry.redhat.io` and +`registry.access.redhat.com`, and the machine running `install.py` can reach +`ghcr.io` and `quay.io`. + +Otherwise, mirror the images with the [`oc-mirror` plugin v2](https://docs.redhat.com/en/documentation/openshift_container_platform/4.22/html/disconnected_environments/about-installing-oc-mirror-v2), which also creates the `ImageDigestMirrorSet` (IDMS) that redirects pulls to your mirror. + +IDMS redirects digest references only, so the configuration must pin every image by digest, as the RHOAI example does. `install.py` warns about any rendered image without a digest. Complete this section before installing. + +### What to mirror + +- The gateway, supervisor, sandbox, and Dashboard images from + `registry.redhat.io/rhoai`. If you mirrored OpenShift AI as described in + [Deploy OpenShift AI in a disconnected environment](https://docs.redhat.com/en/documentation/red_hat_openshift_ai_self-managed/3.5/html-single/installing_and_uninstalling_openshift_ai_self-managed_in_a_disconnected_environment/index#deploying-openshift-ai-in-a-disconnected-environment_install), + they are already in your mirror as related images of the operator. To + confirm: + + ```shell + oc get csv rhods-operator.3.6.0 -n redhat-ods-operator \ + -o jsonpath='{range .spec.relatedImages[*]}{.image}{"\n"}{end}' | grep openshell + ``` + +- The Dashboard's oauth2-proxy image, `registry.access.redhat.com/hi/oauth2-proxy`. + It is not part of OpenShift AI. + +- The development PostgreSQL image, `registry.access.redhat.com/hi/postgresql`, + if the cluster uses [Set up PostgreSQL for development](#set-up-postgresql-for-development). + +- Any other sandbox image that users pass to `openshell sandbox create --from`. + Mirror it, make sure an IDMS covers its repository, and reference it by + digest, for example `--from quay.io/example/agent@sha256:`. + +Add the images that are not mirrored yet, by digest, to the `additionalImages` +of your `ImageSetConfiguration`. Then mirror the image set and apply the +generated cluster resources, as described in the `oc-mirror` guide. + +### ImageDigestMirrorSet entries + +List the image sources your cluster already redirects: ```shell -oc --context "$CTX" -n openshell-team delete secret \ - openshell-server-tls openshell-client-tls openshell-jwt-keys -oc --context "$CTX" -n openshell-team delete secret openshell-dashboard-oidc -oc --context "$CTX" -n openshell-team delete configmap openshell-oidc-ca +oc get imagedigestmirrorset \ + -o jsonpath='{range .items[*].spec.imageDigestMirrors[*]}{.source}{"\n"}{end}' | sort -u ``` -Optionally delete the installer state ConfigMap and the namespace: +The list must include `registry.redhat.io/rhoai`, +`registry.access.redhat.com/hi`, and the repositories of any other sandbox +images. The Machine Config Operator rolls an IDMS out to every node without +rebooting it, and also drains the nodes when you change an existing IDMS; see +[image registry repository mirroring](https://docs.redhat.com/en/documentation/openshift_container_platform/4.20/html/images/image-configuration-classic). Wait until `oc get mcp` shows `UPDATED=True` for every pool before installing. The cluster pull secret must include credentials for the mirror. + +### Agent Sandbox Operator + +Mirror the Agent Sandbox Operator package from the Red Hat Operator catalog +for your OpenShift version, as described in +[Using Operator Lifecycle Manager in disconnected environments](https://docs.redhat.com/en/documentation/openshift_container_platform/4.20/html/disconnected_environments/olm-restricted-networks). +Then install it from the mirrored catalog with **All namespaces on the +cluster** and `agent-sandbox-system` as the installed namespace, following the +[Agent Sandbox Operator installation procedure](https://docs.redhat.com/en/documentation/openshift_sandboxed_containers/1.13/html/deploying_red_hat_build_of_agent_sandbox/install-agent-sandbox-overview_agent-sandbox). + +### OpenShell Charts + +If the machine running `install.py` cannot reach `ghcr.io` and `quay.io`, copy +both charts to an OCI registry it can reach. On a machine that can reach both +the public registries and the mirror registry, log in with +`helm registry login registry.example.com`, then pull and push each chart, +using the chart versions in your configuration. Set `gateway.chart` and +`dashboard.chart` to the mirrored URLs: ```shell -oc --context "$CTX" -n openshell-team delete configmap openshell-installer -oc --context "$CTX" delete namespace openshell-team +helm pull oci://ghcr.io/nvidia/openshell/helm-chart --version 0.1.3 +helm push helm-chart-0.1.3.tgz oci://registry.example.com/charts +helm pull oci://quay.io/ai-openshell/charts/console --version 0.1.5 +helm push console-0.1.5.tgz oci://registry.example.com/charts ``` -Remaining Secrets block a later reinstall and can be reused by a new gateway if -you keep the same names. PersistentVolumeClaims are not deleted by any of these -commands; inspect and remove them deliberately. The installer never deletes the -namespace for you. - -## Troubleshoot common failures +If the mirror registry requires authentication, run +`helm registry login registry.example.com` on the machine that runs +`install.py` before installing. Helm stores registry credentials per machine, +so the login on the copying machine does not apply. -| Symptom | Cause and fix | -|---|---| -| `oidc.client_secret_file is required for the first install` | Create the client secret file before `--check`, or reuse installer state from an earlier successful install. | -| No default StorageClass | Mark a StorageClass that provisions block volumes as default; the gateway's SQLite database needs it. | -| Preflight fails with `This installer supports amd64 clusters only` | The cluster has non-amd64 nodes, including a mixed amd64/arm64 cluster. Mixed clusters are not supported because the Red Hat Build of Agent Sandbox Operator is not available on arm64; run the installer against an amd64-only cluster. | -| Agent Sandbox readiness fails | Install or start the Agent Sandbox controller, or override `agent_sandbox_namespace` and `agent_sandbox_deployment`. | -| `x509` error during `openshell gateway add` | Distinguish the two trust paths: copy the gateway CA into the CLI mtls directory, and build the `SSL_CERT_FILE` bundle for OIDC discovery. | -| `dns error` from `openshell status` after `gateway add` succeeds | The gateway host is outside the router's `*.apps.` wildcard, so it has no DNS record. Registration only contacts the OIDC issuer; `status` is the first gateway connection. Correct `gateway.host`, or remove it to derive `gateway-.` from the ingress domain. Reinstall when the installer already recorded the old host. | -| `Could not resolve the OpenShift apps domain` | Grant read access to `ingresses.config.openshift.io/cluster`, or set `gateway.host` and `dashboard.host` explicitly. | -| HTTP 403 after login | The user holds no role in `allowed_roles`, or no group in `allowed_groups` for generic OIDC. Add a listed role or group to the user, then rerun the install command. | -| Gateway host or issuer change is rejected | The installer state records the original identity. With omitted hosts, a namespace or ingress-domain change also changes the gateway host. Migrate the certificate and endpoint explicitly instead of editing state. | +The machine also needs Python 3.12 and the installer's pinned PyYAML dependency +available to `uv`. -For Keycloak-specific failures, see -[Troubleshooting](keycloak-dev-guide.md#troubleshooting) in the Keycloak -development guide. +## Troubleshooting -## Contributor checks +| Symptom | What to check | +| -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--check` reports a missing client secret or database URI | Create the files named by `oidc.client_secret_file` and `gateway.database.uri_file`. Their paths are relative to `config.json`. | +| Preflight cannot find the Agent Sandbox controller or a StorageClass | Install the operator and confirm a default class is available for workspace volumes. | +| The gateway is not ready | Inspect `oc -n logs deployment/openshell` for PostgreSQL or `statefulset/openshell` for SQLite, and check the PostgreSQL URI, credentials, network access, and any egress policy. | +| OIDC login fails or reports an `x509` error | Confirm `oidc.issuer`, the browser callback URL, and the client settings. For a private or self-signed issuer certificate, configure `oidc.ca_file` as described above. | +| Pods show `ImagePullBackOff` | On a disconnected cluster, confirm the image is in the mirror, an IDMS covers its repository, the configuration pins it by digest, the Machine Config Pool update finished, and the pull secret has mirror credentials. | +| The first sandbox create after a fresh install fails with `Error 127` | The supervisor and sandbox images may still be pulling on the node. Retry the create; later creates succeed once the images are cached. | +| Helm cannot pull a chart | The machine running `install.py` or Helm must reach `ghcr.io` and `quay.io`, or the charts must be mirrored and their URLs updated in the installer config or Helm command. | -The `RHOAI Installer` workflow runs both suites for changes under -`deploy/rhoai/`. Run the same checks locally: +## Related guide -```shell -uv run --script --python 3.12 deploy/rhoai/test_install.py -uv run --no-project --python 3.12 deploy/rhoai/test_verify.py -uvx ruff==0.14.14 check deploy/rhoai -uvx ruff==0.14.14 format --check deploy/rhoai -mise run markdown:lint -``` - -The installer and verifier tests need no cluster credentials or identity -provider. For source-chart rendering, use `--check` with -`--gateway-chart-directory` and `--dashboard-chart-directory`; the installer -rejects those overrides for installation. - -## Related documentation - -- [config-examples/README.md](config-examples/README.md): example - configurations and values files. -- [keycloak-dev-guide.md](keycloak-dev-guide.md): development Keycloak - deployment for OpenShell. -- [verify.py](verify.py): read-only authorization verification with - administrator and ordinary-user tokens. +- [Keycloak development guide](keycloak-dev-guide.md): deploy Keycloak for + development and configure its OpenShell clients. diff --git a/deploy/rhoai/config-examples/README.md b/deploy/rhoai/config-examples/README.md index e5cda151b9..2289a7c087 100644 --- a/deploy/rhoai/config-examples/README.md +++ b/deploy/rhoai/config-examples/README.md @@ -9,22 +9,63 @@ Copy an example outside the checkout, then replace the chart, version, image, and OIDC placeholders before installing: ```shell -cp deploy/rhoai/config-examples/config.example-odh-keycloak.json \ +cp deploy/rhoai/config-examples/config.example-rhoai-3.6-postgresql-keycloak.json \ "${XDG_CONFIG_HOME:-$HOME/.config}/openshell-rhoai/config.json" ``` -Paths in `oidc.client_secret_file` and `oidc.ca_file` resolve relative to the -configuration file. Create the client secret file before `--check`; the -installer validates that the file exists and is not empty. The Keycloak -examples also set `"ca_file": "ingress-ca.crt"`, so create that file with the -command in [../README.md](../README.md#oidc-issuer-certificate) before running -`--check`. +The filenames name the gateway database backend. The `-sqlite` examples need +no database; the `-postgresql` examples use external PostgreSQL and need +`gateway-db-uri.txt`. The generic and ODH examples use SQLite, except the ODH +Keycloak example, which is also provided with PostgreSQL. See +[Database backend](#database-backend). + +Paths in `oidc.client_secret_file`, `oidc.ca_file`, and +`gateway.database.uri_file` resolve relative to the configuration file. Create +the client secret file before `--check`; the installer validates that the file +exists and is not empty. The Keycloak examples also set +`"ca_file": "ingress-ca.crt"`, so create that file with the command in +[../README.md](../README.md#configure) before running `--check`. The examples omit the hosts. The installer targets the current kubeconfig context (`--context` selects another one) and derives `gateway-.` and `dashboard-.` from the cluster ingress domain. +## Database backend + +PostgreSQL is the installer default and the recommended backend for production +deployments. SQLite is for development and evaluation only. + +```json +"database": { "mode": "postgresql", "uri_file": "gateway-db-uri.txt" } +``` + +```json +"database": { "mode": "sqlite" } +``` + +When `gateway.database` is omitted, the installer uses PostgreSQL and reads +`gateway-db-uri.txt` relative to the configuration. Create that file with mode +`0600` before `--check`: + +```shell +export CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/openshell-rhoai" +umask 077 +printf 'Database URI: ' +IFS= read -rs DB_URI +echo +printf '%s' "$DB_URI" > "$CONFIG_DIR/gateway-db-uri.txt" +unset DB_URI +chmod 600 "$CONFIG_DIR/gateway-db-uri.txt" +``` + +The URI uses `postgresql://user:password@host:5432/database`; add +`?sslmode=verify-full` for a database outside the cluster. The installer +validates ASCII, the scheme, the host, and the absence of a fragment; it does +not test connectivity. SQLite mode rejects `uri_file`. Switching the recorded +backend in either direction is rejected by installer state; migrate the data +explicitly. + ## Example values files `gateway-values.example.yaml` and `dashboard-values.example.yaml` are optional @@ -48,15 +89,18 @@ so keep the same files. Omitting them installs the chart defaults. ## Example table -| File | Images | Gateway chart | Dashboard chart | OIDC | Use when | -|---|---|---|---|---|---| -| `config.example.json` | ODH repositories, digest placeholders | placeholder | placeholder | generic | custom registries or versions | -| `config.example-odh.json` | ODH `v0.1.7-rhaiv.0` | `0.1.7` | `0.1.5` | generic | latest OpenShell with your own IdP | -| `config.example-odh-keycloak.json` | ODH `v0.1.7-rhaiv.0` | `0.1.7` | `0.1.5` | Keycloak | latest OpenShell with Keycloak | -| `config.example-rhoai-3.6.json` | RHOAI 3.6 digests | `0.1.3` | `0.1.5` | generic | match the RHOAI 3.6 operator CSV | -| `config.example-rhoai-3.6-keycloak.json` | RHOAI 3.6 digests | `0.1.3` | `0.1.5` | Keycloak | default README walkthrough | +| File | Images | Gateway chart | Dashboard chart | OIDC | Database | Use when | +|---|---|---|---|---|---|---| +| `config.example-sqlite.json` | ODH repositories, digest placeholders | placeholder | placeholder | generic | SQLite | custom registries or versions | +| `config.example-odh-sqlite.json` | ODH `v0.1.7-rhaiv.0` | `0.1.7` | `0.1.5` | generic | SQLite | latest OpenShell with your own IdP | +| `config.example-odh-sqlite-keycloak.json` | ODH `v0.1.7-rhaiv.0` | `0.1.7` | `0.1.5` | Keycloak | SQLite | latest OpenShell with Keycloak, no database | +| `config.example-odh-postgresql-keycloak.json` | ODH `v0.1.7-rhaiv.0` | `0.1.7` | `0.1.5` | Keycloak | PostgreSQL | latest OpenShell with Keycloak and a database | +| `config.example-rhoai-3.6-postgresql.json` | RHOAI 3.6 digests | `0.1.3` | `0.1.5` | generic | PostgreSQL | match the RHOAI 3.6 operator CSV | +| `config.example-rhoai-3.6-postgresql-keycloak.json` | RHOAI 3.6 digests | `0.1.3` | `0.1.5` | Keycloak | PostgreSQL | default README walkthrough | -All examples omit the hosts and rely on the defaults described below. +All examples omit the hosts and rely on the defaults described below. Every +example sets `gateway.database.mode` explicitly; only the PostgreSQL examples +need a `gateway-db-uri.txt`. ## OIDC identifiers @@ -77,6 +121,7 @@ These fields are optional; the installer derives or defaults them: | Field | Default | |---|---| | `gateway.host`, `dashboard.host` | `gateway-.` and `dashboard-.` | +| `gateway.database` | PostgreSQL with `uri_file: gateway-db-uri.txt` | | `oidc.cli_client_id` | `openshell-cli-` | | `gateway.values_files`, `dashboard.values_files` | `[]` | | `gateway.images`, `dashboard.images` | Chart defaults | @@ -132,6 +177,19 @@ amd64-only and tagged with their commit; do not use the moving `odh-stable` tag. The ODH examples pin `sha256:cfb3b592c5909c7c1a5d5622f98a20bf8c503554d53b3441abb189140254450b`. +The dashboard chart's default oauth2-proxy image is pinned by tag, which an +`ImageDigestMirrorSet` cannot rewrite on a disconnected cluster. The RHOAI +examples therefore pin `dashboard.images.authProxy` by digest to the public +Red Hat `hi/oauth2-proxy` image (oauth2-proxy 7.15.6, multi-arch), which works +on connected and disconnected clusters. The `hi` repository publishes no +version tags, so refresh the digest from `:latest` and check the version label +when you update it: + +```shell +skopeo inspect --format '{{.Digest}}' \ + docker://registry.access.redhat.com/hi/oauth2-proxy:latest +``` + ## Tags and digests - `digest` takes precedence when an image sets both `digest` and `tag`. @@ -140,6 +198,8 @@ tag. The ODH examples pin tags, and ranges are rejected. - `gateway.images.sandbox` has no registry key and uses a full repository path. The image must provide a shell at `/bin/bash`, `/usr/bin/bash`, or `/bin/sh`. +- `dashboard.images.authProxy` accepts `registry`, `repository`, and `digest` +or `tag` like the other images; see [Dashboard pairing](#dashboard-pairing). ## Chart values @@ -153,11 +213,14 @@ operational overrides are: | Dashboard | `authProxy.resources`, `authProxy.cookie.refresh`, `authProxy.upstreamTimeout`, `networkPolicy.ingressNamespace`, `networkPolicy.ingressFrom` | Reference existing image-pull Secrets by name; do not put credentials in -values files. Authentication, TLS, release names, service ports, and namespace -wiring remain owned by the installer. Unsupported overrides fail before cluster -access. Extending this set requires checking the pinned charts' contracts. -The gateway chart's SQLite PVC still requires a default block-backed -StorageClass; `workspaceStorageClass` affects sandbox workspace PVCs only. +values files. Authentication, TLS, release names, service ports, database +wiring (`server.externalDbSecret`, `server.dbUrl`, `workload.*`), and namespace +wiring remain owned by the installer; select the database backend with +`gateway.database`. Unsupported overrides fail before cluster access. Extending +this set requires checking the pinned charts' contracts. In SQLite mode the +gateway PVC requires a default block-backed StorageClass; in PostgreSQL mode +only sandbox workspace volumes need storage, and `workspaceStorageClass` can +satisfy that requirement. ## Local files diff --git a/deploy/rhoai/config-examples/config.example-odh-postgresql-keycloak.json b/deploy/rhoai/config-examples/config.example-odh-postgresql-keycloak.json new file mode 100644 index 0000000000..fa1ccb3f45 --- /dev/null +++ b/deploy/rhoai/config-examples/config.example-odh-postgresql-keycloak.json @@ -0,0 +1,61 @@ +{ + "namespace": "openshell-team", + "gateway": { + "chart": "oci://ghcr.io/nvidia/openshell/helm-chart", + "version": "0.1.7", + "values_files": [], + "database": { + "mode": "postgresql", + "uri_file": "gateway-db-uri.txt" + }, + "images": { + "gateway": { + "registry": "quay.io", + "repository": "opendatahub/odh-openshell-gateway", + "tag": "v0.1.7-rhaiv.0" + }, + "supervisor": { + "registry": "quay.io", + "repository": "opendatahub/odh-openshell-supervisor", + "tag": "v0.1.7-rhaiv.0" + }, + "sandboxRuntime": { + "registry": "quay.io", + "repository": "opendatahub/odh-openshell-sandbox", + "tag": "v0.1.7-rhaiv.0" + }, + "sandbox": { + "repository": "quay.io/opendatahub/odh-openshell-sandbox", + "tag": "v0.1.7-rhaiv.0" + } + } + }, + "dashboard": { + "chart": "oci://quay.io/ai-openshell/charts/console", + "version": "0.1.5", + "values_files": [], + "images": { + "dashboard": { + "registry": "quay.io", + "repository": "opendatahub/odh-openshell-dashboard", + "digest": "sha256:cfb3b592c5909c7c1a5d5622f98a20bf8c503554d53b3441abb189140254450b" + } + } + }, + "oidc": { + "provider": "keycloak-oidc", + "issuer": "https://keycloak.apps.example.com/realms/openshell", + "client_id": "openshell-dashboard-openshell-team", + "client_secret_file": "dashboard-client-secret.txt", + "ca_file": "ingress-ca.crt", + "audience": "openshell-api-openshell-team", + "roles_claim": "realm_access.roles", + "admin_role": "openshell-admin", + "user_role": "openshell-user", + "allowed_roles": [ + "openshell-admin", + "openshell-user" + ], + "scope": "openid email profile" + } +} diff --git a/deploy/rhoai/config-examples/config.example-odh-keycloak.json b/deploy/rhoai/config-examples/config.example-odh-sqlite-keycloak.json similarity index 97% rename from deploy/rhoai/config-examples/config.example-odh-keycloak.json rename to deploy/rhoai/config-examples/config.example-odh-sqlite-keycloak.json index 5fb807b280..d1af90d3c1 100644 --- a/deploy/rhoai/config-examples/config.example-odh-keycloak.json +++ b/deploy/rhoai/config-examples/config.example-odh-sqlite-keycloak.json @@ -4,6 +4,9 @@ "chart": "oci://ghcr.io/nvidia/openshell/helm-chart", "version": "0.1.7", "values_files": [], + "database": { + "mode": "sqlite" + }, "images": { "gateway": { "registry": "quay.io", diff --git a/deploy/rhoai/config-examples/config.example-odh.json b/deploy/rhoai/config-examples/config.example-odh-sqlite.json similarity index 96% rename from deploy/rhoai/config-examples/config.example-odh.json rename to deploy/rhoai/config-examples/config.example-odh-sqlite.json index b0ce3d0ce6..f485800c57 100644 --- a/deploy/rhoai/config-examples/config.example-odh.json +++ b/deploy/rhoai/config-examples/config.example-odh-sqlite.json @@ -4,6 +4,9 @@ "chart": "oci://ghcr.io/nvidia/openshell/helm-chart", "version": "0.1.7", "values_files": [], + "database": { + "mode": "sqlite" + }, "images": { "gateway": { "registry": "quay.io", diff --git a/deploy/rhoai/config-examples/config.example-rhoai-3.6-keycloak.json b/deploy/rhoai/config-examples/config.example-rhoai-3.6-postgresql-keycloak.json similarity index 66% rename from deploy/rhoai/config-examples/config.example-rhoai-3.6-keycloak.json rename to deploy/rhoai/config-examples/config.example-rhoai-3.6-postgresql-keycloak.json index 8583839017..b54f51ae95 100644 --- a/deploy/rhoai/config-examples/config.example-rhoai-3.6-keycloak.json +++ b/deploy/rhoai/config-examples/config.example-rhoai-3.6-postgresql-keycloak.json @@ -4,25 +4,29 @@ "chart": "oci://ghcr.io/nvidia/openshell/helm-chart", "version": "0.1.3", "values_files": [], + "database": { + "mode": "postgresql", + "uri_file": "gateway-db-uri.txt" + }, "images": { "gateway": { "registry": "registry.redhat.io", "repository": "rhoai/odh-openshell-gateway-rhel9", - "digest": "sha256:e44fcae68918499143d4f2e6b19690d1209b5448e37d25258efdf6c928c1d35e" + "digest": "sha256:047f6737c921fc5f8c38140af9dd052d9c494c295eca52f91bd7f5c2cba0f079" }, "supervisor": { "registry": "registry.redhat.io", "repository": "rhoai/odh-openshell-supervisor-rhel9", - "digest": "sha256:421aea28a9e233ad94a8223fbc2015a8f1f20022436f1855c5ac76c6277963d3" + "digest": "sha256:74730d0078db3eb39ba7b88e027100d49fa09018a8c048b85e07dcdde8cb579e" }, "sandboxRuntime": { "registry": "registry.redhat.io", "repository": "rhoai/odh-openshell-sandbox-rhel9", - "digest": "sha256:d865fc8781cbdefca785def85fd75bdda6e2bc7ff8962670f80619e45b675292" + "digest": "sha256:f3edb7c938d7fdacc05ae40dd83656d6b737304aa3c29a55157bfad5719d8595" }, "sandbox": { "repository": "registry.redhat.io/rhoai/odh-openshell-sandbox-rhel9", - "digest": "sha256:d865fc8781cbdefca785def85fd75bdda6e2bc7ff8962670f80619e45b675292" + "digest": "sha256:f3edb7c938d7fdacc05ae40dd83656d6b737304aa3c29a55157bfad5719d8595" } } }, @@ -34,7 +38,12 @@ "dashboard": { "registry": "registry.redhat.io", "repository": "rhoai/odh-openshell-dashboard-rhel9", - "digest": "sha256:f4a254f6e03739af244758c22b05a3ef87061cf52ef51d4530e7375218317962" + "digest": "sha256:b1c4ae0e112ae974a7e61f62c7a5f6ed806585dec584e5289157d3c10ac12aa7" + }, + "authProxy": { + "registry": "registry.access.redhat.com", + "repository": "hi/oauth2-proxy", + "digest": "sha256:fa4516e1c5bf6be0a7fc5291adc536e867951deee3449422a8bcfdef173c8edf" } } }, diff --git a/deploy/rhoai/config-examples/config.example-rhoai-3.6.json b/deploy/rhoai/config-examples/config.example-rhoai-3.6-postgresql.json similarity index 63% rename from deploy/rhoai/config-examples/config.example-rhoai-3.6.json rename to deploy/rhoai/config-examples/config.example-rhoai-3.6-postgresql.json index 77fea3a44b..8404cff874 100644 --- a/deploy/rhoai/config-examples/config.example-rhoai-3.6.json +++ b/deploy/rhoai/config-examples/config.example-rhoai-3.6-postgresql.json @@ -4,25 +4,29 @@ "chart": "oci://ghcr.io/nvidia/openshell/helm-chart", "version": "0.1.3", "values_files": [], + "database": { + "mode": "postgresql", + "uri_file": "gateway-db-uri.txt" + }, "images": { "gateway": { "registry": "registry.redhat.io", "repository": "rhoai/odh-openshell-gateway-rhel9", - "digest": "sha256:e44fcae68918499143d4f2e6b19690d1209b5448e37d25258efdf6c928c1d35e" + "digest": "sha256:047f6737c921fc5f8c38140af9dd052d9c494c295eca52f91bd7f5c2cba0f079" }, "supervisor": { "registry": "registry.redhat.io", "repository": "rhoai/odh-openshell-supervisor-rhel9", - "digest": "sha256:421aea28a9e233ad94a8223fbc2015a8f1f20022436f1855c5ac76c6277963d3" + "digest": "sha256:74730d0078db3eb39ba7b88e027100d49fa09018a8c048b85e07dcdde8cb579e" }, "sandboxRuntime": { "registry": "registry.redhat.io", "repository": "rhoai/odh-openshell-sandbox-rhel9", - "digest": "sha256:d865fc8781cbdefca785def85fd75bdda6e2bc7ff8962670f80619e45b675292" + "digest": "sha256:f3edb7c938d7fdacc05ae40dd83656d6b737304aa3c29a55157bfad5719d8595" }, "sandbox": { "repository": "registry.redhat.io/rhoai/odh-openshell-sandbox-rhel9", - "digest": "sha256:d865fc8781cbdefca785def85fd75bdda6e2bc7ff8962670f80619e45b675292" + "digest": "sha256:f3edb7c938d7fdacc05ae40dd83656d6b737304aa3c29a55157bfad5719d8595" } } }, @@ -34,7 +38,12 @@ "dashboard": { "registry": "registry.redhat.io", "repository": "rhoai/odh-openshell-dashboard-rhel9", - "digest": "sha256:f4a254f6e03739af244758c22b05a3ef87061cf52ef51d4530e7375218317962" + "digest": "sha256:b1c4ae0e112ae974a7e61f62c7a5f6ed806585dec584e5289157d3c10ac12aa7" + }, + "authProxy": { + "registry": "registry.access.redhat.com", + "repository": "hi/oauth2-proxy", + "digest": "sha256:fa4516e1c5bf6be0a7fc5291adc536e867951deee3449422a8bcfdef173c8edf" } } }, diff --git a/deploy/rhoai/config-examples/config.example.json b/deploy/rhoai/config-examples/config.example-sqlite.json similarity index 97% rename from deploy/rhoai/config-examples/config.example.json rename to deploy/rhoai/config-examples/config.example-sqlite.json index f10d7339ff..d1a900e6f1 100644 --- a/deploy/rhoai/config-examples/config.example.json +++ b/deploy/rhoai/config-examples/config.example-sqlite.json @@ -4,6 +4,9 @@ "chart": "oci://ghcr.io/nvidia/openshell/helm-chart", "version": "REPLACE_WITH_EXACT_GATEWAY_VERSION", "values_files": [], + "database": { + "mode": "sqlite" + }, "images": { "gateway": { "registry": "quay.io", diff --git a/deploy/rhoai/install.py b/deploy/rhoai/install.py index 6b6c3387e1..362cbbeb15 100755 --- a/deploy/rhoai/install.py +++ b/deploy/rhoai/install.py @@ -27,10 +27,16 @@ OWNER = "openshell.ai/installer" OWNER_VALUE = "odh-dashboard" -GATEWAY_HOST = "openshell.ai/installer-gateway-host" INSTALL_STATE = "openshell-installer" +# Material the charts create once and reuse on later runs. The PKI secrets are +# reused by the certgen hook when all three exist; the key-encryption key is +# reused by a `lookup` in the credential-storage template. +PKI_SECRETS = ("openshell-server-tls", "openshell-client-tls", "openshell-jwt-keys") +CREDENTIAL_KEK_SECRET = "openshell-credential-storage-key-encryption-key" OIDC_SECRET = "openshell-dashboard-oidc" OIDC_CA = "openshell-oidc-ca" +DB_SECRET = "openshell-gateway-db" +DB_URI_FILE = "gateway-db-uri.txt" MIN_DASHBOARD_USER_ROLE_CHART = (0, 1, 2) CLI_CLIENT_ID = "openshell-cli" CLI_INSTALL_URL = "https://raw.githubusercontent.com/NVIDIA/OpenShell/main/install.sh" @@ -235,6 +241,36 @@ def resolve_main_hosts(config, check, apps_domain, cluster_domain): return False +def database_uri_from_file(path): + """Read and validate the PostgreSQL URI shared by --check and install.""" + uri = Path(path).read_bytes().rstrip(b"\r\n") + require(uri, "Database URI file contains no URI") + try: + text = uri.decode("ascii") + except UnicodeDecodeError: + raise ValueError("Database URI must be ASCII") from None + # urlsplit() drops tab, CR, and LF before parsing, so an embedded separator + # would pass validation while the Secret keeps the raw multi-line bytes. + require( + not any(separator in text for separator in "\t\r\n"), + "Database URI must be a single line", + ) + parsed = None + try: + parsed = urlsplit(text) + hostname = parsed.hostname + except ValueError: + hostname = None + require( + parsed is not None + and parsed.scheme in ("postgresql", "postgres") + and hostname + and not parsed.fragment, + "Database URI must be a postgresql:// or postgres:// URL with a host", + ) + return uri + + def load_config(path, namespace=None): config = json.loads(path.read_text()) if namespace is not None: @@ -265,7 +301,10 @@ def load_config(path, namespace=None): ) for name in ("gateway", "dashboard"): item = config[name] - fields(item, ("chart", "version"), ("host", "images", "values_files")) + optional = ["host", "images", "values_files"] + if name == "gateway": + optional.append("database") + fields(item, ("chart", "version"), tuple(optional)) require( isinstance(item["chart"], str) and item["chart"].startswith("oci://"), f"{name}.chart must be an OCI chart reference", @@ -324,6 +363,36 @@ def load_config(path, namespace=None): f"{name}.images.{component}.digest must be sha256: followed by " "64 lowercase hexadecimal characters", ) + if name == "gateway": + database = item.get("database") + if database is None: + database = {"mode": "postgresql"} + fields(database, (), ("mode", "uri_file")) + mode = database.get("mode", "postgresql") + require( + mode in ("sqlite", "postgresql"), + "gateway.database.mode must be sqlite or postgresql", + ) + if mode == "sqlite": + require( + "uri_file" not in database, + "gateway.database.uri_file is only valid for postgresql", + ) + else: + uri_file = database.get("uri_file", DB_URI_FILE) + require( + isinstance(uri_file, str) and uri_file.strip(), + "gateway.database.uri_file must be a nonempty path", + ) + source = (path.parent / uri_file).resolve() + require( + source.is_file() and source.stat().st_size > 0, + "Missing or empty gateway.database.uri_file", + ) + database_uri_from_file(source) + database["uri_file"] = str(source) + database["mode"] = mode + item["database"] = database oidc = config["oidc"] fields( oidc, @@ -441,6 +510,41 @@ def warn_if_dashboard_user_role_missing(manifest, role, chart_version): ) +# Image references in rendered manifests: container `image:` fields and the +# `*_image = "..."` settings of the gateway TOML ConfigMap. +RENDERED_IMAGE = re.compile( + r"""^\s*(?:-\s+)?image:\s*["']?([^"'\s]+)|\b\w+_image\s*=\s*"([^"]+)\"""", + re.MULTILINE, +) + + +def unpinned_images(manifest): + """Return rendered image references that are not pinned by digest.""" + images = {a or b for a, b in RENDERED_IMAGE.findall(manifest)} + return sorted(image for image in images if "@sha256:" not in image) + + +def warn_if_images_unpinned(images): + if not images: + return + listed = "".join(f"\n - {image}" for image in images) + print( + colorize( + f"Warning: {len(images)} rendered image(s) are not pinned by digest:" + f"{listed}\n" + "On a disconnected cluster the installation may fail with " + "ImagePullBackOff: an ImageDigestMirrorSet only redirects pulls by " + "digest, so tag-only images are pulled from their original registry. " + "Set images..digest in the configuration for each image " + "(see Disconnected clusters in deploy/rhoai/README.md).", + "33", + sys.stderr, + ), + file=sys.stderr, + flush=True, + ) + + def chart_values(config): ns, oidc = config["namespace"], config["oidc"] require( @@ -483,6 +587,9 @@ def chart_values(config): }, "openshiftRoute": {"enabled": True, "host": config["gateway"]["host"]}, } + if config["gateway"]["database"]["mode"] == "postgresql": + gateway["workload"] = {"kind": "deployment"} + gateway["server"]["externalDbSecret"] = DB_SECRET dashboard = { "fullnameOverride": "openshell-dashboard", "podSecurityContext": None, @@ -542,23 +649,34 @@ def next_steps(config, context, config_dir): cli_client = cli_client_id(config) gateway_dir = f"${{XDG_CONFIG_HOME:-$HOME/.config}}/openshell/gateways/{ns}/mtls" gateway_url = f"https://{config['gateway']['host']}:443" + + def heading(text): + return colorize(text, "1;36") + + def command(*texts): + return [colorize(text, "32") for text in texts] + lines = [ - colorize("Next steps:", "1"), + heading("Next steps:"), "", - "1. Install the OpenShell CLI that matches this gateway release:", - f" curl -LsSf {CLI_INSTALL_URL} \\", - f" | OPENSHELL_VERSION=v{config['gateway']['version']} sh", + heading("1. Install the OpenShell CLI that matches this gateway release:"), + *command( + f" curl -LsSf {CLI_INSTALL_URL} \\", + f" | OPENSHELL_VERSION=v{config['gateway']['version']} sh", + ), "", " Note: the upstream installer also deploys and starts a local", " gateway on this workstation (a user service on Linux, a Homebrew", " service on macOS). This is a limitation of the upstream installer;", " this guide uses only the CLI. See the README for details.", "", - "2. Register the gateway with the OpenShell CLI:", - f' mkdir -p "{gateway_dir}"', - f" kubectl --context {shlex.quote(context)} -n {ns} get secret openshell-client-tls \\", - " -o jsonpath='{.data.ca\\.crt}' | base64 -d \\", - f' > "{gateway_dir}/ca.crt"', + heading("2. Register the gateway with the OpenShell CLI:"), + *command( + f' mkdir -p "{gateway_dir}"', + f" kubectl --context {shlex.quote(context)} -n {ns} get secret openshell-client-tls \\", + " -o jsonpath='{.data.ca\\.crt}' | base64 -d \\", + f' > "{gateway_dir}/ca.crt"', + ), ] if oidc.get("ca_file"): bundle = system_ca_bundle() @@ -573,11 +691,15 @@ def next_steps(config, context, config_dir): " your platform's path below.", ] lines += [ - f" mkdir -p {shlex.quote(str(config_dir))}", - f" cat {bundle or ''} \\", - f" {shlex.quote(oidc['ca_file'])} \\", - f" > {shlex.quote(str(bundle_file))}", - f" export SSL_CERT_FILE={shlex.quote(str(bundle_file))}", + *command( + f" mkdir -p {shlex.quote(str(config_dir))}", + f" cat {bundle or ''} \\", + f" {shlex.quote(oidc['ca_file'])} \\", + f" > {shlex.quote(str(bundle_file))}.tmp", + f" mv {shlex.quote(str(bundle_file))}.tmp \\", + f" {shlex.quote(str(bundle_file))}", + f" export SSL_CERT_FILE={shlex.quote(str(bundle_file))}", + ), "", " Platform paths: " + ", ".join(f"{label} {path}" for label, path in SYSTEM_CA_BUNDLES) @@ -585,12 +707,14 @@ def next_steps(config, context, config_dir): ] lines += [ "", - " openshell gateway add \\", - f" --name {ns} \\", - f" --oidc-issuer {shlex.quote(oidc['issuer'])} \\", - f" --oidc-client-id {shlex.quote(cli_client)} \\", - f" --oidc-audience {shlex.quote(oidc['audience'])} \\", - f' "{gateway_url}"', + *command( + " openshell gateway add \\", + f" --name {ns} \\", + f" --oidc-issuer {shlex.quote(oidc['issuer'])} \\", + f" --oidc-client-id {shlex.quote(cli_client)} \\", + f" --oidc-audience {shlex.quote(oidc['audience'])} \\", + f' "{gateway_url}"', + ), "", f" Use your provider's CLI client ID if it is not {cli_client}.", "", @@ -599,25 +723,28 @@ def next_steps(config, context, config_dir): f" ({oidc['user_role']}). The gateway rejects API calls from a", " user with neither role.", "", - "3. Check the connection:", - " openshell status", + heading("3. Check the connection:"), + *command(" openshell status"), "", - "4. Create a sandbox:", - " openshell sandbox create", + heading("4. Create a sandbox:"), + *command(" openshell sandbox create"), "", "An administrator must add users to a workspace before they can work there.", "The CLI targets the default workspace; pass --workspace or export", "OPENSHELL_WORKSPACE= to use the workspace you were added to.", - "See deploy/rhoai/README.md#register-the-gateway-and-log-in for details.", + "See deploy/rhoai/README.md#after-installation-install-the-cli-and-create-a-sandbox for details.", ] return "\n".join(lines) class Installer: - def __init__(self, config, timeout, context=None, config_dir=None): + def __init__( + self, config, timeout, context=None, config_dir=None, adopt_existing=False + ): self.config = config self.timeout = timeout self.config_dir = Path(config_dir) if config_dir is not None else Path.cwd() + self.adopt_existing = adopt_existing self._context = context require( self._context is None @@ -777,25 +904,44 @@ def cluster_checks(self, namespace): ) ) ] - require( - defaults, - "No default StorageClass; the gateway's SQLite database needs one " - "that provisions block storage", - ) - classes = ", ".join(defaults) - print( - f"{colorize('Default StorageClass:', '1')} {classes}\n" - " The gateway's SQLite database runs on a PersistentVolumeClaim, so the\n" - " default StorageClass must provision block volumes. The installer cannot\n" - " detect the volume type; verify the default class is block-backed (not NFS\n" - " or a shared filesystem) before installing." - ) + mode = self.config["gateway"]["database"]["mode"] custom = ( self.config["gateway"] .get("values", {}) .get("server", {}) .get("workspaceStorageClass") ) + if mode == "sqlite": + require( + defaults, + "No default StorageClass; the gateway's SQLite database needs one " + "that provisions block storage", + ) + print( + f"{colorize('Default StorageClass:', '1')} {', '.join(defaults)}\n" + " SQLite mode stores the gateway database on a PersistentVolumeClaim,\n" + " so the default StorageClass must provision block volumes. The\n" + " installer cannot detect the volume type; verify the default class is\n" + " block-backed (not NFS or a shared filesystem) before installing." + ) + else: + require( + defaults or custom, + "No default StorageClass and no server.workspaceStorageClass; " + "sandbox workspace volumes require one", + ) + line = ( + f"{colorize('Default StorageClass:', '1')} " + f"{', '.join(defaults) or 'none'}" + ) + if custom: + print( + f"{line}\n" + " Sandbox workspace volumes use the configured " + f"server.workspaceStorageClass: {custom}" + ) + else: + print(line) if custom: require( any(item["metadata"]["name"] == custom for item in storage["items"]), @@ -910,9 +1056,20 @@ def cluster_checks(self, namespace): + (f" in {self.ns}" if namespaced else " cluster-wide") ) from None + def namespace_owned(self, namespace): + """Whether the installer can prove it owns this namespace. + + A namespace editor cannot patch the Namespace object, so a marker on + it cannot be planted from inside the namespace. The ConfigMap label + alone can be, because any editor can create ConfigMaps. + """ + metadata = (namespace or {}).get("metadata") or {} + return (metadata.get("labels") or {}).get(OWNER) == OWNER_VALUE + def identity_state(self): return { "gateway-host": self.config["gateway"]["host"], + "database-mode": self.config["gateway"]["database"]["mode"], **{ f"oidc-{key.replace('_', '-')}": self.config["oidc"][key] for key in ("issuer", "audience", "client_id") @@ -921,10 +1078,28 @@ def identity_state(self): def check_identity(self, state): desired = self.identity_state() - for key, value in (state or {}).get("data", {}).items(): - if key in desired: + if state is not None: + data = state.get("data", {}) + missing = sorted(key for key in desired if key not in data) + require( + not missing, + f"ConfigMap {INSTALL_STATE} does not record {', '.join(missing)}; " + "it was not written by this installer version. Reinstall into a " + "new namespace, or delete the gateway and its state before " + "installing again", + ) + recorded = data["database-mode"] + require( + recorded == desired["database-mode"], + "Database backend differs from the installer state " + f"({recorded!r} recorded, {desired['database-mode']!r} " + "configured); set gateway.database.mode to the recorded " + "backend, or migrate the data explicitly before changing the " + "backend", + ) + for key, value in desired.items(): require( - value == desired[key], + data[key] == value, f"Installer identity {key} changed; explicit identity/certificate migration is required", ) states = json.loads( @@ -951,7 +1126,7 @@ def check_identity(self, state): if "oidc-issuer" not in data: print( colorize( - f"Note: legacy installer state in {other['metadata']['namespace']} " + f"Note: installer state in {other['metadata']['namespace']} " "has no identity metadata; verify audience isolation manually.", "33", ) @@ -1007,44 +1182,103 @@ def preflight(self): not state or state["metadata"].get("labels", {}).get(OWNER) == OWNER_VALUE, f"ConfigMap {INSTALL_STATE} already exists outside this installer", ) - # Preserve compatibility with installations made before state moved off - # the Namespace. Never modify administrator-owned Namespace metadata. - legacy_host = ( - (namespace or {}) - .get("metadata", {}) - .get("annotations", {}) - .get(GATEWAY_HOST) - ) - original_host = ( - state.get("data", {}).get("gateway-host") if state else legacy_host - ) require( - not (state or legacy_host) - or original_host == self.config["gateway"]["host"], + not state + or state.get("data", {}).get("gateway-host") + == self.config["gateway"]["host"], "Gateway hostname differs from the original install; certificate migration is required", ) + # The ConfigMap label is not proof of ownership: it is writable from + # inside the namespace. Collect every object the chart would otherwise + # reuse and make the administrator vouch for them when this installer + # cannot prove it created the namespace. + pre_existing = [] + if namespace: + if state: + pre_existing.append(f"configmap/{INSTALL_STATE}") + for secret in (*PKI_SECRETS, CREDENTIAL_KEK_SECRET, OIDC_SECRET): + if self.get("secret", secret): + pre_existing.append(f"secret/{secret}") + # The namespace marker alone is not enough: require the state record it + # should accompany, so a deleted state ConfigMap cannot leave orphaned + # key material that a rerun would silently reuse. + trusted = self.namespace_owned(namespace) and bool(state) + if pre_existing and not trusted: + require( + self.adopt_existing, + f"Namespace {self.ns} already contains installer state or " + f"gateway key material ({', '.join(pre_existing)}), and this " + "installer did not create the namespace, so it cannot tell a " + "previous installation of this gateway from objects created by " + "someone else. If you created them in an earlier installation, " + "re-run with --adopt-existing. Otherwise inspect them " + f"(kubectl -n {self.ns} get -o yaml) and delete " + "them before installing: the gateway reuses existing TLS, " + "JWT, and credential-storage key material instead of " + "generating new keys.", + ) self.check_identity(state) if namespace: - self.check_releases(managed=bool(state or legacy_host)) - # The chart's bootstrap hook reuses existing TLS material. Do not - # accidentally use certificates belonging to another gateway. - if not (state or legacy_host): - for secret in ( - "openshell-server-tls", - "openshell-client-tls", - "openshell-jwt-keys", - ): - require( - not self.get("secret", secret), - f"Existing gateway Secret {secret} requires explicit migration", - ) + self.check_releases(managed=bool(state)) require( - state or legacy_host or self.config["oidc"].get("client_secret_file"), + state or self.config["oidc"].get("client_secret_file"), "oidc.client_secret_file is required for the first install", ) + self.database(check_only=True, namespace_exists=bool(namespace)) self.credentials(check_only=True, namespace_exists=bool(namespace)) return namespace + def database_uri(self): + database = self.config["gateway"]["database"] + if database["mode"] != "postgresql": + return None + return database_uri_from_file(database["uri_file"]) + + def database(self, check_only=False, *, namespace_exists=True): + require( + namespace_exists or check_only, + "Create the namespace before the database Secret", + ) + uri = self.database_uri() + if uri is None: + return + if check_only: + print( + f"{colorize('Database:', '1')} external PostgreSQL via Secret {DB_SECRET}" + ) + if not namespace_exists: + return + existing = self.get("secret", DB_SECRET) + if existing is None: + if check_only: + print(f" Secret {DB_SECRET} will be created during the install.") + return + self.create( + { + "apiVersion": "v1", + "kind": "Secret", + "type": "Opaque", + "metadata": { + "name": DB_SECRET, + "namespace": self.ns, + "labels": {OWNER: OWNER_VALUE}, + }, + "data": {"uri": base64.b64encode(uri).decode()}, + } + ) + return + data = existing.get("data", {}) + require( + data.get("uri"), + f"Existing Secret {DB_SECRET} is missing the uri key", + ) + require( + base64.b64decode(data["uri"]) == uri, + f"Database URI differs from Secret {DB_SECRET}; rotate the Secret " + "explicitly, restart the gateway workload so it reads the new URI, " + "then rerun the installer", + ) + def credentials(self, check_only=False, *, namespace_exists=True): require( namespace_exists or check_only, "Create the namespace before credentials" @@ -1151,21 +1385,7 @@ def install(self, charts, values, total_steps=3): "data": self.identity_state(), } ) - else: - # Add identity metadata to legacy state only after preflight passed. - self.run( - [ - *self.kube, - "-n", - self.ns, - "patch", - "configmap", - INSTALL_STATE, - "--type=merge", - "-p", - json.dumps({"data": self.identity_state()}), - ] - ) + self.database() self.credentials() for index, release in enumerate(("openshell", "openshell-dashboard")): print( @@ -1245,6 +1465,12 @@ def main(): type=Path, help="Local source chart for --check only", ) + parser.add_argument( + "--adopt-existing", + action="store_true", + help="Adopt an existing installer state ConfigMap and gateway key " + "material in a namespace this installer did not create", + ) parser.add_argument( "--timeout", default="10m", help="Helm/controller wait timeout (default: 10m)" ) @@ -1266,7 +1492,11 @@ def main(): require(shutil.which(tool), f"Required tool not found: {tool}") config = load_config(args.config.resolve(), args.namespace) installer = Installer( - config, args.timeout, args.context, args.config.resolve().parent + config, + args.timeout, + args.context, + args.config.resolve().parent, + adopt_existing=args.adopt_existing, ) placeholders = resolve_main_hosts( config, args.check, args.apps_domain, installer.apps_domain @@ -1287,7 +1517,7 @@ def main(): step(1, total_steps, "Rendering the gateway and dashboard charts") with tempfile.TemporaryDirectory(prefix="openshell-install-") as temporary: root = Path(temporary) - charts, files = [], [] + charts, files, unpinned = [], [], set() for index, (name, values, local) in enumerate( zip( ("gateway", "dashboard"), @@ -1343,6 +1573,7 @@ def main(): warn_if_dashboard_user_role_missing( manifest, config["oidc"]["user_role"], config[name]["version"] ) + unpinned.update(unpinned_images(manifest)) charts.append(chart) files.append(value_file) print( @@ -1350,6 +1581,7 @@ def main(): "This does not verify cluster or API compatibility.", flush=True, ) + warn_if_images_unpinned(sorted(unpinned)) if args.preflight: step(2, total_steps, "Running cluster preflight") installer.preflight() diff --git a/deploy/rhoai/keycloak-dev-guide-create-openshell-clients.sh b/deploy/rhoai/keycloak-dev-guide-create-openshell-clients.sh index ad76c1d865..db63c4bce7 100755 --- a/deploy/rhoai/keycloak-dev-guide-create-openshell-clients.sh +++ b/deploy/rhoai/keycloak-dev-guide-create-openshell-clients.sh @@ -4,9 +4,9 @@ # # Create the OpenShell clients in a Keycloak realm. # -# Development helper only. It uses the operator bootstrap admin credentials and -# verifies the Keycloak Route against a bundle built from the system roots and -# the ingress CA at "${CONFIG_DIR}/ingress-ca.crt". Do not use it to manage a +# Development helper only. It prompts for a Keycloak administrator and verifies +# the Keycloak Route against a bundle built from the system roots and the +# ingress CA at "${CONFIG_DIR}/ingress-ca.crt". Do not use it to manage a # production realm. # # The script creates the realm and the openshell-admin/openshell-user realm @@ -16,9 +16,14 @@ # users separately; they need passwords and verified email addresses. # # Requires the environment variables set by the Keycloak development guide: -# KC_URL, KEYCLOAK_NS, REALM, API_ID, DASH_ID, CLI_ID, DASH_URL, CONFIG_DIR +# KC_URL, REALM, API_ID, DASH_ID, CLI_ID, DASH_URL, CONFIG_DIR # CONFIG_DIR must contain ingress-ca.crt, the CA bundle for the Keycloak Route. # +# The script authenticates to the master realm as an administrator. It prompts +# for that administrator's username and password at run time and never reads or +# writes them on disk, so it never depends on the operator bootstrap user. For +# non-interactive runs, set KEYCLOAK_ADMIN_USER and KEYCLOAK_ADMIN_PASSWORD. +# # Usage: keycloak-dev-guide-create-openshell-clients.sh [-y|--yes] # -y, --yes Skip the confirmation prompt. # @@ -29,7 +34,6 @@ set -euo pipefail umask 077 : "${KC_URL:?set KC_URL, for example https://keycloak.apps.example.com}" -: "${KEYCLOAK_NS:?set KEYCLOAK_NS, for example keycloak}" : "${REALM:?set REALM, for example openshell}" : "${API_ID:?set API_ID, for example openshell-api-openshell-team}" : "${DASH_ID:?set DASH_ID, for example openshell-dashboard-openshell-team}" @@ -37,6 +41,17 @@ umask 077 : "${DASH_URL:?set DASH_URL, for example https://dashboard-openshell-team.apps.example.com}" : "${CONFIG_DIR:?set CONFIG_DIR, for example ${HOME}/.config/openshell-rhoai}" +# Both URLs carry credentials or register OAuth origins, so refuse cleartext. +for name in KC_URL DASH_URL; do + case "${!name}" in + https://?*) ;; + *) + echo "error: ${name} must be an https:// URL." >&2 + exit 1 + ;; + esac +done + assume_yes=false case "${1:-}" in -y | --yes) assume_yes=true ;; @@ -47,12 +62,18 @@ case "${1:-}" in ;; esac +if [ -n "${KEYCLOAK_ADMIN_USER:-}" ] || [ -n "${KEYCLOAK_ADMIN_PASSWORD:-}" ]; then + ADMIN_SOURCE="user ${KEYCLOAK_ADMIN_USER:-} (from the environment)" +else + ADMIN_SOURCE="prompted when the script runs" +fi + cat <> "$CURL_CA" -echo "Reading Keycloak admin credentials from ${KEYCLOAK_NS}/keycloak-initial-admin..." -AU=$(oc -n "$KEYCLOAK_NS" get secret keycloak-initial-admin -o jsonpath='{.data.username}' | base64 -d) -AP=$(oc -n "$KEYCLOAK_NS" get secret keycloak-initial-admin -o jsonpath='{.data.password}' | base64 -d) +if [ -n "${KEYCLOAK_ADMIN_USER:-}" ] || [ -n "${KEYCLOAK_ADMIN_PASSWORD:-}" ]; then + : "${KEYCLOAK_ADMIN_USER:?set KEYCLOAK_ADMIN_USER together with KEYCLOAK_ADMIN_PASSWORD}" + : "${KEYCLOAK_ADMIN_PASSWORD:?set KEYCLOAK_ADMIN_PASSWORD together with KEYCLOAK_ADMIN_USER}" + AU="$KEYCLOAK_ADMIN_USER" + AP="$KEYCLOAK_ADMIN_PASSWORD" +else + if [ ! -t 0 ]; then + echo "error: no interactive terminal; set KEYCLOAK_ADMIN_USER and KEYCLOAK_ADMIN_PASSWORD." >&2 + exit 1 + fi + printf 'Keycloak master realm admin username: ' >&2 + read -r AU || AU="" + printf 'Keycloak master realm admin password: ' >&2 + IFS= read -rs AP || AP="" + printf '\n' >&2 +fi +if [ -z "$AU" ] || [ -z "$AP" ]; then + echo "error: a master realm administrator username and password are required." >&2 + exit 1 +fi echo "Requesting a Keycloak admin token from ${KC_URL}..." -# Keep the admin password out of the process argument list. -TOK=$(printf '%s' "$AP" | curl -fsS --cacert "$CURL_CA" -d client_id=admin-cli -d "username=$AU" \ - --data-urlencode "password@-" -d grant_type=password \ - "$KC_URL/realms/master/protocol/openid-connect/token" \ - | python3 -c "import sys,json;print(json.load(sys.stdin)['access_token'])") +# Keep the admin password out of the process argument list, and keep both the +# credentials and the token response in memory only. +response=$(printf '%s' "$AP" | curl -sS --cacert "$CURL_CA" -w '\n%{http_code}' \ + -d client_id=admin-cli --data-urlencode "username=$AU" --data-urlencode "password@-" -d grant_type=password \ + "$KC_URL/realms/master/protocol/openid-connect/token") || { + echo "error: cannot reach ${KC_URL}." >&2 + exit 1 +} +status="${response##*$'\n'}" +body="${response%$'\n'*}" +if [ "$status" != 200 ]; then + detail=$(printf '%s' "$body" | python3 -c 'import json,sys +try: + response = json.load(sys.stdin) +except Exception: + response = {} +print(response.get("error_description") or response.get("error") or "unexpected response")' \ + 2>/dev/null) || detail="unexpected response" + echo "error: Keycloak rejected the admin token request for user \"${AU}\"" \ + "(HTTP ${status}): ${detail}" >&2 + echo "hint: use a master realm administrator that can log in; the operator" \ + "bootstrap user is disabled or deleted after the guide's hardening step." >&2 + exit 1 +fi +TOK=$(printf '%s' "$body" | python3 -c 'import sys,json;print(json.load(sys.stdin)["access_token"])') # Keep the admin token out of the process argument list. WORK_DIR is created by # mktemp and the script sets umask 077, so the file is private. HDR_FILE="${WORK_DIR}/auth.hdr" diff --git a/deploy/rhoai/keycloak-dev-guide.md b/deploy/rhoai/keycloak-dev-guide.md index 864421c2c3..0496d24d31 100644 --- a/deploy/rhoai/keycloak-dev-guide.md +++ b/deploy/rhoai/keycloak-dev-guide.md @@ -1,14 +1,14 @@ # Install Keycloak for OpenShell development on OpenShift -This guide is for development only. It is not a production Keycloak -deployment: it runs one PostgreSQL instance and one Keycloak instance with -bootstrap credentials, and the client helper verifies the Keycloak Route -against the cluster ingress CA. +This guide sets up Keycloak for development on OpenShift. It is not for +production: it runs one PostgreSQL instance and one Keycloak instance, uses +temporary bootstrap credentials, and the client setup helper checks the +Keycloak Route against the cluster's ingress CA. -This guide deploys and removes a development Keycloak instance only. Use -[README.md](README.md) to install OpenShell and the OpenShell Dashboard admin UI. -Follow this guide first when you need a local identity provider; skip it when -your cluster already has an OIDC provider. +Use [README.md](README.md) to install OpenShell and the OpenShell Dashboard +admin UI. Follow this guide if you need a local identity provider. Skip it if +your cluster already has an OIDC provider. If your cluster cannot reach public +registries, first follow the [disconnected-cluster instructions](#disconnected-clusters-mirror-the-images). Set the environment used throughout the guide: @@ -25,20 +25,21 @@ export KC_URL="https://keycloak.${APPS_DOMAIN}" export CONFIG_DIR="${XDG_CONFIG_HOME:-${HOME}/.config}/openshell-rhoai" ``` -The client IDs are namespace-qualified and match the example configurations, so -the commands work unchanged for the default namespace. `DASH_URL` also matches -the host the installer derives from the namespace and ingress domain, so the -example configurations need no host changes. Changing `NS` changes the client -IDs, `DASH_URL`, and both derived hosts; update the OIDC identifiers in the -OpenShell configuration from [README.md](README.md) and re-register -`https:///oauth2/callback` with Keycloak. If the -configuration sets explicit hosts, register that dashboard URL instead. +These namespace-qualified client IDs match the examples, so the commands work +with the default namespace. `DASH_URL` also matches the host the installer +builds from the namespace and ingress domain. -Realm roles are realm-wide. In a shared realm, a user with `openshell-admin` is -an administrator for every gateway in that realm, regardless of the client IDs. -Use one realm per trust boundary when gateways serve different teams. +If you change `NS`, update the OIDC identifiers in the OpenShell configuration +from [README.md](README.md), then register the new dashboard callback URL +(`https:///oauth2/callback`) in Keycloak. If your +configuration sets a dashboard host directly, register that URL instead. -## Part 1 — PostgreSQL and Keycloak +Realm roles apply to the whole realm. Anyone with `openshell-admin` can +administer every gateway in that realm, whatever the client IDs are. Use a +separate realm for each group of gateways that should have its own access +boundary. + +## Part 1: PostgreSQL and Keycloak ### Create the namespace and database secret @@ -49,8 +50,7 @@ openssl rand -base64 24 | tr -d '\n' | \ --from-literal=username=keycloak --from-file=password=/dev/stdin ``` -Reading the generated password from stdin keeps it out of the process argument -list. +Passing the generated password through stdin keeps it out of the process list. ### Deploy PostgreSQL with persistent storage @@ -71,29 +71,36 @@ spec: EOF ``` -Deploy PostgreSQL from the Red Hat hardened image. `PGDATA` points to a -subdirectory to avoid the `lost+found` conflict at the mount point: +Deploy PostgreSQL from Red Hat's hardened image and pin it by digest. The image +is public. To use a newer build, get the current digest for the `18.4` tag: ```shell -oc -n "$KEYCLOAK_NS" new-app registry.access.redhat.com/hi/postgresql:18.4 \ +skopeo inspect --format '{{.Digest}}' \ + docker://registry.access.redhat.com/hi/postgresql:18.4 +oc -n "$KEYCLOAK_NS" new-app registry.access.redhat.com/hi/postgresql@sha256:67599d73c3dae0e8685c2f9ba31c11028477816bbc254cf862543cfb11c2dc3f \ -e POSTGRES_USER=keycloak \ -e POSTGRES_DATABASE=keycloak \ -e PGDATA=/var/lib/postgresql/data/pgdata \ --name=keycloak-db ``` -Do not pass the database password through `oc new-app`: it would appear in the -process table and as a literal Deployment value. Add the reference from -`keycloak-db-secret` instead: +Use the digest form on disconnected clusters. An `ImageDigestMirrorSet` can +redirect digest pulls to your mirror, but tag pulls still go to the original +registry and fail. + +Keep the database password out of the `oc new-app` command. Otherwise it can +appear in the process list and as plain text in the Deployment. Add a reference +to `keycloak-db-secret` instead: ```shell oc -n "$KEYCLOAK_NS" patch deployment/keycloak-db --type=json -p \ '[{"op":"add","path":"/spec/template/spec/containers/0/env/-","value":{"name":"POSTGRES_PASSWORD","valueFrom":{"secretKeyRef":{"name":"keycloak-db-secret","key":"password"}}}}]' ``` -Replace the image's emptyDir volume with the claim. The image names its volume -`keycloak-db-volume-1` at `/var/lib/postgresql`; inspect the Deployment if the -name differs in your image version: +Use the claim instead of the image's temporary `emptyDir` volume. The image +usually names its volume `keycloak-db-volume-1` and mounts it at +`/var/lib/postgresql`. Check the Deployment if your image uses a different +volume name: ```shell oc -n "$KEYCLOAK_NS" set volume deployment/keycloak-db \ @@ -106,29 +113,29 @@ oc -n "$KEYCLOAK_NS" rollout status deployment/keycloak-db ### Install the Red Hat build of Keycloak Operator -Use either the console or a Subscription. In the console, open -**Operators** → **OperatorHub**, search for **Red Hat build of Keycloak**, -install it in the `keycloak` namespace or all namespaces, and wait until the -operator pod is ready: +Install the operator from the OpenShift console or with a Subscription. In the +console, go to **Operators** → **OperatorHub**, search for **Red Hat build of +Keycloak**, and install it in the `keycloak` namespace or in all namespaces. +Then wait for the operator to start: ```shell oc -n "$KEYCLOAK_NS" rollout status deployment/rhbk-operator ``` -If you installed the operator for all namespaces, its Deployment runs in -`openshift-operators`; use `-n openshift-operators` for that command instead. +If you installed it for all namespaces, the Deployment is in +`openshift-operators`. Use `-n openshift-operators` in the command above. -To install with a Subscription instead, first list the channels your cluster -offers and pick a version channel from the output: +To install with a Subscription, first list the available channels and choose +one from the output: ```shell oc get packagemanifest rhbk-operator -n openshift-marketplace \ -o jsonpath='{.status.channels[*].name}' ``` -The manifests below use `stable-v26.6` and expand `KEYCLOAK_NS`. Channel names -change with operator releases, so substitute a channel from the command output -when needed. +The example uses `stable-v26.6` and the `KEYCLOAK_NS` value you set earlier. +Channel names can change between releases, so replace the example channel if +your cluster lists a different one. ```shell oc apply -f - < \ + docker://$MIRROR/rhbk/keycloak-rhel9:v26.6.9 + ``` + +Push each image to a tag in the mirror, not to a bare digest. Quay and some +other registries may accept a digest-only push but fail to serve it later, +causing `manifest unknown` errors. The tag does not change the image; the +cluster still pulls it by digest. + +### Operator catalog + +The Subscription in the [operator installation section](#install-the-red-hat-build-of-keycloak-operator) +gets operator manifests from a CatalogSource. Check that the package is in your cluster's +catalogs: + +```shell +oc get packagemanifest rhbk-operator -n openshift-marketplace +``` + +If it is missing, your catalog mirror does not include the RHBK operator. Add +the package with +[oc-mirror](https://docs.redhat.com/en/documentation/openshift_container_platform/4.20/html/disconnected_environments/olm-restricted-networks) +and wait for the updated catalog. If your CatalogSource has a different name, +use that name in the Subscription's `source` field. + +### ImageDigestMirrorSet entries + +List the image sources your cluster already redirects: + +```shell +oc get imagedigestmirrorset \ + -o jsonpath='{range .items[*].spec.imageDigestMirrors[*]}{.source}{"\n"}{end}' | sort -u +``` + +This guide needs `registry.access.redhat.com/hi` and `registry.redhat.io/rhbk`. +Add only sources that are missing from the list above, and include just those +entries in the new set. If an oc-mirror set already covers a source, reuse or +extend it; do not create a second set for the same source. For example, when +neither source is covered yet: + +```shell +oc apply -f - <<'EOF' +apiVersion: config.openshift.io/v1 +kind: ImageDigestMirrorSet +metadata: + name: hi-mirror +spec: + imageDigestMirrors: + - source: registry.access.redhat.com/hi + mirrors: + - registry.example.com:8443/hi + mirrorSourcePolicy: NeverContactSource + - source: registry.redhat.io/rhbk + mirrors: + - registry.example.com:8443/rhbk + mirrorSourcePolicy: NeverContactSource +EOF +``` + +`mirrorSourcePolicy: NeverContactSource` prevents nodes from falling back to +the public registry. The Machine Config Operator rolls an IDMS out to every +node without rebooting it, and also drains the nodes when you change an +existing IDMS. Wait until both pools show `UPDATED=True` before deploying: + +```shell +oc get mcp +``` + ## Troubleshooting ### "Client not found" -The browser redirected with a client ID that does not exist in the realm. -Confirm `openshell-dashboard-${NS}` exists and matches `oidc.client_id`. The -API client is only a token audience and does not produce this page. +The browser was redirected with a client ID that Keycloak cannot find. Check +that `openshell-dashboard-${NS}` exists and matches `oidc.client_id`. The API +client is only used as a token audience, so it does not cause this error. ### Login fails because the email is not verified -oauth2-proxy rejects ID tokens with `email_verified: false`. Enable **Email -verified** for the user in the console and save. The change applies on the next +oauth2-proxy rejects ID tokens when `email_verified` is `false`. In the console, +enable **Email verified** for the user and save. It takes effect at the next login. ### The operator is not ready Check the Subscription channel from Part 1, the installed CSV, and the operator -pod: +pod status: ```shell oc -n "$KEYCLOAK_NS" get subscription rhbk-operator @@ -379,11 +527,32 @@ oc -n "$KEYCLOAK_NS" get csv oc -n "$KEYCLOAK_NS" get pods ``` +### `ImagePullBackOff` or `BundleUnpackFailed` on a disconnected cluster + +The mirror may be missing the image or operator manifest, or the +`ImageDigestMirrorSet` may not redirect its registry. Using a tag where a digest +is required causes the same error. Compare the failing pod's image and the IDMS +sources with the [disconnected-cluster instructions](#disconnected-clusters-mirror-the-images). + +OLM keeps failed unpack results in `openshift-marketplace`. After fixing the +mirror or IDMS, delete the failed Job and the ConfigMap with the same name. +Then restart the catalog operator in +`openshift-operator-lifecycle-manager`: + +```shell +oc -n openshift-marketplace get jobs +oc -n openshift-marketplace delete job +oc -n openshift-marketplace delete configmap +oc -n openshift-operator-lifecycle-manager rollout restart deployment catalog-operator +``` + ## Cleanup -Remove Keycloak and PostgreSQL. These commands delete only the resources this -guide creates, so they are safe when `KEYCLOAK_NS` is a shared or pre-existing -namespace: +Remove Keycloak and PostgreSQL with these commands. They assume this guide +created the listed objects, so before you run them in a shared or existing +`KEYCLOAK_NS` namespace, confirm each object came from this guide and omit the +ones it did not create. In particular, `keycloak-db-data` may be a claim that +already existed, and the `app=keycloak-db` selector may match other workloads: ```shell oc delete keycloak keycloak -n "$KEYCLOAK_NS" @@ -395,11 +564,14 @@ oc delete pvc keycloak-db-data -n "$KEYCLOAK_NS" oc delete secret keycloak-db-secret -n "$KEYCLOAK_NS" ``` -Optionally delete the namespace as well. This is a separate step because it -deletes every workload, PersistentVolumeClaim, and resource in `KEYCLOAK_NS`, -not only the Keycloak resources. Run it only when the namespace was created -for this guide; skip it when the namespace is shared or already existed: +You can also delete the namespace, but that removes everything in +`KEYCLOAK_NS`, including workloads and persistent volume claims. Do this only +if you created the namespace for this guide. Skip it for a shared or existing +namespace: ```shell oc delete namespace "$KEYCLOAK_NS" ``` + +These commands leave mirrored images and `ImageDigestMirrorSet` entries in +place because other workloads may use them. diff --git a/deploy/rhoai/test_install.py b/deploy/rhoai/test_install.py index 16358c2655..b2b7adf7b6 100644 --- a/deploy/rhoai/test_install.py +++ b/deploy/rhoai/test_install.py @@ -11,6 +11,7 @@ import importlib.util import io import json +import re import tempfile import unittest from contextlib import redirect_stderr, redirect_stdout @@ -25,7 +26,9 @@ def configuration(with_hosts=True): - config_path = Path(__file__).with_name("config-examples") / "config.example.json" + config_path = ( + Path(__file__).with_name("config-examples") / "config.example-sqlite.json" + ) config = json.loads(config_path.read_text()) if with_hosts: # Keep the existing suite deterministic; the examples omit these. @@ -97,11 +100,6 @@ def run(self, args, payload=None): return json.dumps({"items": self.nodes}) if "--all-namespaces" in args: return json.dumps({"items": self.other_states}) - if "patch" in args: - self.objects[("configmap", installer.INSTALL_STATE)]["data"].update( - json.loads(args[args.index("-p") + 1])["data"] - ) - return "" if args[:2] == ["helm", "pull"]: destination = Path(args[args.index("--destination") + 1]) (destination / "chart.tgz").write_bytes(b"fake") @@ -164,6 +162,19 @@ def cluster(self): self.config["oidc"]["client_secret_file"] = str(secret) return FakeCluster(self.load()) + def database_config(self, mode="postgresql", uri=None): + if mode == "postgresql": + value = ( + uri + if uri is not None + else "postgresql://openshell:secret@db.example.com:5432/openshell" + ) + (self.root / "gateway-db-uri.txt").write_text(value + "\n") + self.config["gateway"]["database"] = {"mode": mode} + if mode == "postgresql": + self.config["gateway"]["database"]["uri_file"] = "gateway-db-uri.txt" + return self.config + def test_rejects_unpinned_versions_and_unknown_keys(self): for version in ( "latest", @@ -329,6 +340,276 @@ def test_preflight_storage_and_permissions_fail_before_mutation(self): any(args[:2] == ["helm", "upgrade"] for args, _ in cluster.calls) ) + def test_postgresql_is_the_default_and_renders_a_deployment(self): + (self.root / installer.DB_URI_FILE).write_text( + "postgresql://openshell:secret@db.example.com:5432/openshell\n" + ) + self.config["gateway"].pop("database") + config = self.load() + self.assertEqual(config["gateway"]["database"]["mode"], "postgresql") + self.assertEqual( + config["gateway"]["database"]["uri_file"], + # load_config() resolves the path, which differs from the TMPDIR + # alias on macOS (/var/folders -> /private/var/folders). + str((self.root / installer.DB_URI_FILE).resolve()), + ) + gateway, _ = installer.chart_values(config) + self.assertEqual(gateway["workload"], {"kind": "deployment"}) + self.assertEqual(gateway["server"]["externalDbSecret"], installer.DB_SECRET) + self.assertNotIn("dbUrl", gateway["server"]) + self.assertEqual(gateway["replicaCount"], 1) + + def test_sqlite_mode_keeps_chart_defaults_and_needs_no_uri_file(self): + config = self.load() + self.assertEqual(config["gateway"]["database"], {"mode": "sqlite"}) + gateway, _ = installer.chart_values(config) + self.assertNotIn("workload", gateway) + self.assertNotIn("externalDbSecret", gateway["server"]) + cluster = self.cluster() + self.assertIsNone(cluster.database_uri()) + cluster.install(["g.tgz", "d.tgz"], ["g.json", "d.json"]) + self.assertNotIn(("secret", installer.DB_SECRET), cluster.objects) + + def test_database_configuration_validation(self): + (self.root / installer.DB_URI_FILE).write_text( + "postgresql://openshell:secret@db.example.com:5432/openshell\n" + ) + cases = ( + ({"mode": "mysql"}, "must be sqlite or postgresql"), + ( + {"mode": "sqlite", "uri_file": installer.DB_URI_FILE}, + "only valid for postgresql", + ), + ( + { + "mode": "postgresql", + "uri": "postgresql://openshell:secret@db.example.com/db", + }, + "Unknown configuration fields", + ), + ( + {"mode": "postgresql", "uri_file": "missing.txt"}, + "Missing or empty", + ), + ({"mode": None}, "must be sqlite or postgresql"), + ) + for database, message in cases: + with self.subTest(database=database): + self.config = configuration() + self.config["gateway"]["database"] = database + with self.assertRaisesRegex(ValueError, message): + self.load() + # `database` is optional for gateway alone; keep it rejected elsewhere. + with self.subTest(database="dashboard"): + self.config = configuration() + self.config["dashboard"]["database"] = {"mode": "sqlite"} + with self.assertRaisesRegex(ValueError, "Unknown configuration fields"): + self.load() + + def test_database_uri_validation(self): + accepted = ( + "postgres://openshell:secret@db.example.com:5432/openshell", + "postgresql://openshell:secret@db.example.com/openshell?sslmode=require", + ) + url_error = "must be a postgresql:// or postgres:// URL with a host" + rejected = { + "mysql://openshell:secret@db.example.com/openshell": url_error, + "": "contains no URI", + "\n": "contains no URI", + "postgresql://openshell:secret@db.example.com/openshell#fragment": url_error, + "postgresql://openshell:sécrét@db.example.com/openshell": "must be ASCII", + "postgresql:///openshell": url_error, + "postgresql://": url_error, + "postgresql://[::1/openshell": url_error, + "postgresql://openshell:secret@db.example.com/openshell\nsecond line": ( + "must be a single line" + ), + "postgresql://openshell:secret@db.example.com/openshell\rsecond": ( + "must be a single line" + ), + "postgresql://openshell:secret@db.example.com/openshell\tsecond": ( + "must be a single line" + ), + } + for uri in accepted: + with self.subTest(uri=uri): + self.config = configuration() + self.database_config(uri=uri) + self.assertEqual(self.cluster().database_uri(), uri.encode()) + # --check renders charts without calling preflight, so load_config must + # reject a bad URI before the install would. + for uri, message in rejected.items(): + with self.subTest(uri=uri): + self.config = configuration() + self.database_config(uri=uri) + with self.assertRaisesRegex(ValueError, re.escape(message)): + self.load() + # The file can change between load and install; the install path + # validates it again. + self.config = configuration() + self.database_config() + cluster = self.cluster() + uri_path = Path(cluster.config["gateway"]["database"]["uri_file"]) + for uri, message in rejected.items(): + with self.subTest(phase="install", uri=uri): + uri_path.write_text(uri) + with self.assertRaisesRegex(ValueError, re.escape(message)): + cluster.database_uri() + + def test_database_secret_is_stdin_only_and_rotation_is_explicit(self): + self.database_config() + cluster = self.cluster() + cluster.objects[("namespace", cluster.ns)] = {"metadata": {}} + cluster.install(["g.tgz", "d.tgz"], ["g.json", "d.json"]) + secret = cluster.objects[("secret", installer.DB_SECRET)] + uri = "postgresql://openshell:secret@db.example.com:5432/openshell" + self.assertEqual(base64.b64decode(secret["data"]["uri"]), uri.encode()) + self.assertEqual( + secret["metadata"]["labels"][installer.OWNER], installer.OWNER_VALUE + ) + self.assertEqual( + cluster.objects[("configmap", installer.INSTALL_STATE)]["data"][ + "database-mode" + ], + "postgresql", + ) + for args, _payload in cluster.calls: + self.assertNotIn("openshell:secret", " ".join(args)) + self.assertNotIn("db.example.com", " ".join(args)) + + cluster.calls.clear() + cluster.adopt_existing = True + cluster.install(["g.tgz", "d.tgz"], ["g.json", "d.json"]) + self.assertFalse( + any("create" in args and "can-i" not in args for args, _ in cluster.calls) + ) + + Path(cluster.config["gateway"]["database"]["uri_file"]).write_text( + "postgresql://openshell:other@db.example.com:5432/openshell\n" + ) + before = copy.deepcopy(cluster.objects) + with self.assertRaisesRegex(ValueError, "differs"): + cluster.install(["g.tgz", "d.tgz"], ["g.json", "d.json"]) + self.assertEqual(cluster.objects, before) + + def test_existing_database_secret_without_uri_key_is_rejected(self): + self.database_config() + cluster = self.cluster() + cluster.objects[("namespace", cluster.ns)] = {"metadata": {}} + cluster.objects[("secret", installer.DB_SECRET)] = {"data": {}} + before = copy.deepcopy(cluster.objects) + with self.assertRaisesRegex(ValueError, "missing the uri key"): + cluster.preflight() + self.assertEqual(cluster.objects, before) + + def test_postgresql_install_into_new_namespace_creates_the_secret(self): + self.database_config() + cluster = self.cluster() + output = io.StringIO() + with redirect_stdout(output): + cluster.install(["g.tgz", "d.tgz"], ["g.json", "d.json"]) + secret = cluster.objects[("secret", installer.DB_SECRET)] + self.assertEqual( + base64.b64decode(secret["data"]["uri"]), + b"postgresql://openshell:secret@db.example.com:5432/openshell", + ) + self.assertEqual( + secret["metadata"]["labels"][installer.OWNER], installer.OWNER_VALUE + ) + self.assertEqual(output.getvalue().count("Database:"), 1) + + def test_postgresql_storage_requirements(self): + self.database_config() + cluster = self.cluster() + cluster.storage = [] + with self.assertRaisesRegex(ValueError, "workspaceStorageClass"): + cluster.preflight() + cluster.config["gateway"]["values"] = { + "server": {"workspaceStorageClass": "nfs"} + } + cluster.storage = [{"metadata": {"name": "nfs"}}] + cluster.preflight() + + self.config = configuration() + cluster = self.cluster() + cluster.config["gateway"]["values"] = { + "server": {"workspaceStorageClass": "nfs"} + } + cluster.storage = [{"metadata": {"name": "nfs"}}] + with self.assertRaisesRegex(ValueError, "SQLite"): + cluster.preflight() + + def test_postgresql_preflight_reports_storage_class_without_explaining(self): + self.database_config() + cluster = self.cluster() + output = io.StringIO() + with redirect_stdout(output): + cluster.cluster_checks(None) + self.assertIn("Default StorageClass: block\n", output.getvalue()) + self.assertNotIn("workspace", output.getvalue().lower()) + + cluster.storage = [{"metadata": {"name": "custom"}}] + cluster.config["gateway"]["values"] = { + "server": {"workspaceStorageClass": "custom"} + } + output = io.StringIO() + with redirect_stdout(output): + cluster.cluster_checks(None) + self.assertIn("Default StorageClass: none\n", output.getvalue()) + self.assertIn("server.workspaceStorageClass: custom", output.getvalue()) + + def test_database_state_blocks_switching(self): + cluster = self.cluster() + cluster.install(["g.tgz", "d.tgz"], ["g.json", "d.json"]) + self.database_config() + cluster.config = self.load() + with self.assertRaisesRegex(ValueError, "Database backend differs"): + cluster.preflight() + + def test_incomplete_installer_state_is_rejected(self): + # State without the full identity (for example from a pre-release + # installer) must not pass as a match: a missing database-mode would + # otherwise let a rerun switch backends without the guard. + self.config["gateway"].pop("database") + (self.root / installer.DB_URI_FILE).write_text( + "postgresql://openshell:secret@db.example.com:5432/openshell\n" + ) + cluster = self.cluster() + cluster.objects[("namespace", cluster.ns)] = { + "metadata": {"labels": {installer.OWNER: installer.OWNER_VALUE}} + } + cluster.objects[("configmap", installer.INSTALL_STATE)] = { + "metadata": {"labels": {installer.OWNER: installer.OWNER_VALUE}}, + "data": {"gateway-host": cluster.config["gateway"]["host"]}, + } + before = copy.deepcopy(cluster.objects) + with self.assertRaisesRegex(ValueError, "does not record database-mode"): + cluster.preflight() + self.assertEqual(cluster.objects, before) + for key in cluster.identity_state(): + if key == "gateway-host": + continue # checked earlier, as the hostname guard + data = cluster.identity_state() + del data[key] + cluster.objects[("configmap", installer.INSTALL_STATE)]["data"] = data + before = copy.deepcopy(cluster.objects) + with ( + self.subTest(key=key), + self.assertRaisesRegex(ValueError, f"does not record {key}"), + ): + cluster.preflight() + self.assertEqual(cluster.objects, before) + + def test_database_preflight_reports_without_creating_the_secret(self): + self.database_config() + cluster = self.cluster() + cluster.objects[("namespace", cluster.ns)] = {"metadata": {}} + output = io.StringIO() + with redirect_stdout(output): + cluster.preflight() + self.assertIn("will be created", output.getvalue()) + self.assertNotIn(("secret", installer.DB_SECRET), cluster.objects) + def test_cross_namespace_identity_reuse_is_rejected(self): for field in ("oidc-audience", "oidc-client-id"): cluster = self.cluster() @@ -377,7 +658,7 @@ def test_uninstalled_other_release_history_does_not_block_install(self): any(args[:3] == ["helm", "get", "manifest"] for args, _ in cluster.calls) ) cluster.objects[("secret", "openshell-server-tls")] = {"data": {}} - with self.assertRaisesRegex(ValueError, "explicit migration"): + with self.assertRaisesRegex(ValueError, "--adopt-existing"): cluster.preflight() def test_preflight_rejects_credential_drift_without_changing_state(self): @@ -509,6 +790,8 @@ def test_existing_admin_namespace_preserves_metadata_and_targets_releases(self): } cluster.objects[("namespace", cluster.ns)] = copy.deepcopy(namespace) cluster.install(["gateway.tgz", "dashboard.tgz"], ["g.json", "d.json"]) + # The admin namespace carries no installer marker, so reruns adopt it. + cluster.adopt_existing = True cluster.install(["gateway.tgz", "dashboard.tgz"], ["g.json", "d.json"]) self.assertEqual(cluster.objects[("namespace", cluster.ns)], namespace) self.assertEqual( @@ -659,29 +942,131 @@ def test_preexisting_gateway_certificate_is_not_reused(self): cluster.objects[("secret", "openshell-server-tls")] = { "data": {"tls.crt": "old"} } - with self.assertRaisesRegex(ValueError, "explicit migration"): + with self.assertRaisesRegex(ValueError, "--adopt-existing"): cluster.install([], []) - def test_legacy_install_migrates_without_modifying_namespace(self): + def test_forged_installer_state_in_preexisting_namespace_requires_adoption(self): cluster = self.cluster() - namespace = { + cluster.objects[("namespace", cluster.ns)] = {"metadata": {}} + cluster.objects[("configmap", installer.INSTALL_STATE)] = { + "metadata": {"labels": {installer.OWNER: installer.OWNER_VALUE}}, + "data": cluster.identity_state(), + } + reusable = (*installer.PKI_SECRETS, installer.CREDENTIAL_KEK_SECRET) + for name in reusable: + cluster.objects[("secret", name)] = {"data": {"planted": "MQ=="}} + before = copy.deepcopy(cluster.objects) + with self.assertRaisesRegex(ValueError, "--adopt-existing") as raised: + cluster.preflight() + self.assertIn(f"configmap/{installer.INSTALL_STATE}", str(raised.exception)) + for name in reusable: + self.assertIn(f"secret/{name}", str(raised.exception)) + self.assertEqual(cluster.objects, before) + # The explicit flag is the administrator's assertion of ownership. + cluster.adopt_existing = True + cluster.preflight() + + def test_preexisting_dashboard_oidc_secret_alone_requires_adoption(self): + # A planted cookie secret would otherwise be reused by the dashboard. + cluster = self.cluster() + cluster.objects[("namespace", cluster.ns)] = {"metadata": {}} + cluster.objects[("secret", installer.OIDC_SECRET)] = { + "data": {"planted": "MQ=="} + } + before = copy.deepcopy(cluster.objects) + with self.assertRaisesRegex(ValueError, "--adopt-existing") as raised: + cluster.preflight() + self.assertIn(f"secret/{installer.OIDC_SECRET}", str(raised.exception)) + self.assertEqual(cluster.objects, before) + + def test_namespace_owner_label_grants_ownership_without_adoption(self): + cluster = self.cluster() + cluster.objects[("namespace", cluster.ns)] = { + "metadata": {"labels": {installer.OWNER: installer.OWNER_VALUE}} + } + cluster.objects[("configmap", installer.INSTALL_STATE)] = { + "metadata": {"labels": {installer.OWNER: installer.OWNER_VALUE}}, + "data": cluster.identity_state(), + } + cluster.preflight() + + def test_namespace_annotation_does_not_grant_ownership(self): + # Only the owner label on the Namespace proves the installer created it. + cluster = self.cluster() + cluster.objects[("namespace", cluster.ns)] = { "metadata": { - "labels": {installer.OWNER: installer.OWNER_VALUE}, "annotations": { - installer.GATEWAY_HOST: cluster.config["gateway"]["host"] - }, + "openshell.ai/installer-gateway-host": cluster.config["gateway"][ + "host" + ] + } } } - cluster.objects[("namespace", cluster.ns)] = copy.deepcopy(namespace) - cluster.releases = [{"name": "openshell", "chart": "helm-chart-0.1.3"}] + cluster.objects[("configmap", installer.INSTALL_STATE)] = { + "metadata": {"labels": {installer.OWNER: installer.OWNER_VALUE}}, + "data": cluster.identity_state(), + } + with self.assertRaisesRegex(ValueError, "--adopt-existing"): + cluster.preflight() + + def test_owned_namespace_without_state_requires_adoption(self): + # A deleted state ConfigMap must not let a rerun reuse orphaned certs. + cluster = self.cluster() + cluster.objects[("namespace", cluster.ns)] = { + "metadata": {"labels": {installer.OWNER: installer.OWNER_VALUE}} + } + cluster.objects[("secret", "openshell-server-tls")] = {"data": {"old": "MQ=="}} + with self.assertRaisesRegex(ValueError, "--adopt-existing"): + cluster.preflight() + cluster.adopt_existing = True + cluster.preflight() + + def test_installer_created_namespace_carries_the_ownership_label(self): + cluster = self.cluster() cluster.install(["g.tgz", "d.tgz"], ["g.json", "d.json"]) - self.assertEqual(cluster.objects[("namespace", cluster.ns)], namespace) + namespace = cluster.objects[("namespace", cluster.ns)] self.assertEqual( - cluster.objects[("configmap", installer.INSTALL_STATE)]["data"][ - "gateway-host" - ], - cluster.config["gateway"]["host"], + namespace["metadata"]["labels"][installer.OWNER], installer.OWNER_VALUE ) + # The rerun finds reusable objects, which would require adoption in an + # unowned namespace; the label proves ownership, so no flag is needed. + self.assertIn(("configmap", installer.INSTALL_STATE), cluster.objects) + self.assertIn(("secret", installer.OIDC_SECRET), cluster.objects) + cluster.install(["g.tgz", "d.tgz"], ["g.json", "d.json"]) + + def test_adopt_existing_flag_is_forwarded_to_preflight(self): + path = self.root / "config.json" + path.write_text(json.dumps(self.config)) + seen = [] + + def run(_instance, args, _payload=None): + if args[:2] == ["helm", "pull"]: + (Path(args[args.index("--destination") + 1]) / "chart.tgz").write_bytes( + b"fake" + ) + return "" + + def preflight(instance): + seen.append(instance.adopt_existing) + + with ( + patch( + "sys.argv", + [ + "install.py", + "--config", + str(path), + "--preflight", + "--adopt-existing", + ], + ), + patch.object(installer.shutil, "which", return_value="tool"), + patch.object(installer.Installer, "run", run), + patch.object(installer.Installer, "preflight", preflight), + redirect_stdout(io.StringIO()), + ): + installer.main() + self.assertEqual(seen, [True]) def test_missing_prerequisite_stops_before_mutation(self): cluster = self.cluster() @@ -738,6 +1123,7 @@ def test_first_install_requires_supplied_secret_even_with_existing_secret(self): cluster.objects[("secret", installer.OIDC_SECRET)] = copy.deepcopy( existing ) + cluster.adopt_existing = True path = Path(cluster.config["oidc"]["client_secret_file"]) if supplied is None: cluster.config["oidc"].pop("client_secret_file") @@ -906,8 +1292,11 @@ def test_check_only_never_calls_kubectl(self): args = call.args[0] self.assertEqual(args[args.index("--namespace") + 1], "render-project") - def check_render(self, extra=()): - """Run --check with local source charts and return rendered value files.""" + def check_render(self, extra=(), manifest=""): + """Run --check with local source charts and return rendered value files. + + Each chart renders as ``manifest``; stderr is kept in self.check_errors. + """ path = self.root / "config.json" path.write_text(json.dumps(self.config)) for chart in ("gateway", "dashboard"): @@ -921,7 +1310,7 @@ def run(_instance, args, payload=None): rendered.append( json.loads(Path(args[args.index("--values") + 1]).read_text()) ) - return "" + return manifest argv = [ "install.py", @@ -934,7 +1323,7 @@ def run(_instance, args, payload=None): str(self.root / "dashboard"), *extra, ] - output = io.StringIO() + output, errors = io.StringIO(), io.StringIO() with ( patch("sys.argv", argv), patch.object(installer.shutil, "which", return_value="helm"), @@ -950,8 +1339,10 @@ def run(_instance, args, payload=None): side_effect=AssertionError("--check accessed the cluster"), ), redirect_stdout(output), + redirect_stderr(errors), ): installer.main() + self.check_errors = errors.getvalue() return rendered, output.getvalue() def test_example_configs_omit_context_and_hosts(self): @@ -966,17 +1357,31 @@ def test_example_configs_omit_context_and_hosts(self): def test_pinned_example_configs_load(self): examples = Path(__file__).with_name("config-examples") for path in sorted(examples.glob("config.example-*.json")): + # The generic example keeps placeholders; only pinned examples load. + if "REPLACE_WITH" in path.read_text(): + continue with self.subTest(path=path.name): target = self.root / path.name target.write_text(path.read_text()) (self.root / "dashboard-client-secret.txt").write_text("secret\n") (self.root / "ingress-ca.crt").write_text("test CA\n") + (self.root / "gateway-db-uri.txt").write_text( + "postgresql://openshell:secret@db.example.com:5432/openshell\n" + ) config = installer.load_config(target) installer.resolve_hosts(config, "apps.example.com") self.assertNotEqual( config["gateway"]["host"], config["dashboard"]["host"] ) + def test_example_filenames_name_the_database_mode(self): + examples = Path(__file__).with_name("config-examples") + for path in sorted(examples.glob("config.example*.json")): + database = json.loads(path.read_text())["gateway"]["database"] + expected = "sqlite" if "sqlite" in path.name else "postgresql" + with self.subTest(path=path.name): + self.assertEqual(database["mode"], expected) + def test_resolve_hosts_derives_namespace_qualified_hosts(self): self.config = configuration(with_hosts=False) config = self.load() @@ -1064,9 +1469,12 @@ def test_main_install_derives_hosts_and_passes_cli_context(self): path.write_text(json.dumps(self.config)) clusters = [] - def factory(config, _timeout, context=None, _config_dir=None): + def factory( + config, _timeout, context=None, _config_dir=None, adopt_existing=False + ): cluster = FakeCluster(config) cluster._context = context + cluster.adopt_existing = adopt_existing clusters.append(cluster) return cluster @@ -1289,6 +1697,63 @@ def test_check_omits_placeholder_note_with_apps_domain(self): _, output = self.check_render(["--apps-domain", "apps.cluster.example.com"]) self.assertNotIn("rendered hosts are derived from", output) + def test_unpinned_images_reads_container_and_gateway_config_images(self): + pinned = "registry.example.com/rhoai/gateway@sha256:" + "a" * 64 + manifest = ( + "kind: ConfigMap\n" + "data:\n" + " gateway.toml: |\n" + f' supervisor_image = "{pinned}"\n' + ' default_image = "quay.io/example/sandbox:v1"\n' + ' supervisor_image_pull_policy = "if_not_present"\n' + "---\n" + "kind: Deployment\n" + "spec:\n" + " template:\n" + " spec:\n" + " containers:\n" + f' - image: "{pinned}"\n' + " imagePullPolicy: IfNotPresent\n" + " - name: proxy\n" + " image: quay.io/oauth2-proxy/oauth2-proxy:v7.6.0\n" + ) + self.assertEqual( + installer.unpinned_images(manifest), + [ + "quay.io/example/sandbox:v1", + "quay.io/oauth2-proxy/oauth2-proxy:v7.6.0", + ], + ) + + def test_check_warns_about_images_without_digest(self): + manifest = ( + "kind: Deployment\n" + "spec:\n" + " template:\n" + " spec:\n" + " containers:\n" + " - image: quay.io/opendatahub/odh-openshell-gateway:v0.1.7\n" + ) + _, output = self.check_render(manifest=manifest) + self.assertIn("Both charts rendered successfully.", output) + self.assertIn("1 rendered image(s) are not pinned by digest", self.check_errors) + self.assertIn( + "- quay.io/opendatahub/odh-openshell-gateway:v0.1.7", self.check_errors + ) + self.assertIn("disconnected cluster", self.check_errors) + + def test_check_does_not_warn_when_every_image_has_a_digest(self): + manifest = ( + "kind: Deployment\n" + "spec:\n" + " template:\n" + " spec:\n" + " containers:\n" + " - image: registry.example.com/gateway@sha256:" + "b" * 64 + "\n" + ) + self.check_render(manifest=manifest) + self.assertNotIn("not pinned by digest", self.check_errors) + def test_colorize_keeps_ansi_out_of_non_tty_output(self): class Tty(io.StringIO): def isatty(self): diff --git a/e2e/rust/tests/odh/README.md b/e2e/rust/tests/odh/README.md index 631b447e3b..a4f970c0e2 100644 --- a/e2e/rust/tests/odh/README.md +++ b/e2e/rust/tests/odh/README.md @@ -510,6 +510,9 @@ podman run --rm \ quay.io/opendatahub/odh-openshell-e2e:odh-stable smoke ``` +Versioned RHOAI releases use `quay.io/opendatahub/odh-openshell-e2e:e2e-3.6` +(and matching branch tags). See [odh/e2e-images.md](../../../../odh/e2e-images.md). + The image runs as UID/GID `1001:1001` and owns `/home/odh`, including the OpenShell CLI configuration directory. Keep the pipeline's `--user` setting at `1001:1001` so gateway registration and client mTLS material can be written. diff --git a/odh/e2e-images.md b/odh/e2e-images.md new file mode 100644 index 0000000000..d39de621e1 --- /dev/null +++ b/odh/e2e-images.md @@ -0,0 +1,52 @@ +# Create an e2e image for a RHOAI version + +These images run OpenShell e2e against RHOAI builds in downstream testing. +Create a branch per RHOAI version by hand: `e2e-3.6` is the image for +`rhoai-3.6`, `e2e-3.7-ea.1` for `rhoai-3.7-ea.1`, and so on. + +Pushes to those branches rebuild `odh-openshell-e2e` and publish to Quay. +Creating the branch is a push, so it builds too. + +## Branches that build + +The PipelineRun in `.tekton/odh-openshell-e2e-branch.yaml` matches `e2e-` +plus a RHOAI version, optionally an EA suffix: + +- `e2e-3.6`, `e2e-3.8`, `e2e-3.11`, `e2e-4.1` +- `e2e-3.7-ea.1` + +Other `e2e-` names such as `e2e-test` do not build. Pushes to `main` continue +to publish `odh-stable`. + +## How to create a branch from a tag + +Pick the ODH tag that pins OpenShell for that RHOAI version, then create the +e2e branch from that tag in GitHub. + +1. Open [opendatahub-io/openshell](https://github.com/opendatahub-io/openshell). +2. Open the branch/tag switcher and select the **Tags** tab. +3. Choose the pin, for example `v0.1.3-rhaiv.3`. +4. Open the switcher again and select the **Branches** tab. +5. Enter a name that matches [Branches that build](#branches-that-build), for + example `e2e-3.6`. +6. Create the branch. GitHub creates it from the tag you selected. + +The branch name is the Quay tag. After the branch exists, Konflux builds and +pushes `quay.io/opendatahub/odh-openshell-e2e:e2e-3.6`. Confirm the tag on +[Quay](https://quay.io/repository/opendatahub/odh-openshell-e2e?tab=tags). + +Note: If the tag is older than this PipelineRun, commit +`.tekton/odh-openshell-e2e-branch.yaml` on the new branch so Konflux has +something to run. + +## Image + +```text +quay.io/opendatahub/odh-openshell-e2e:e2e-3.6 +``` + +## Use + +Pass that image to the same `podman run` as in the +[e2e container image](../e2e/rust/tests/odh/README.md#e2e-container-image) +section, in place of `:odh-stable`.