diff --git a/rfc/0031-deployment-operator/README.md b/rfc/0031-deployment-operator/README.md new file mode 100644 index 0000000000..695766916c --- /dev/null +++ b/rfc/0031-deployment-operator/README.md @@ -0,0 +1,219 @@ +--- +authors: + - "@VaishnaviHire" + - "@rhuss" +state: review +links: + - https://github.com/ai-openshell/openshell/issues/5847 + - https://github.com/ai-openshell/openshell/issues/1719 + - https://github.com/ai-openshell/openshell/pull/4426 +--- + +# RFC 0031 - OpenShell Deployment Operator + +## Summary + +This RFC proposes an OpenShell Deployment Operator, maintained in a dedicated upstream repository. A namespaced `OpenShellGateway` resource declares one gateway installation; the operator deploys it, reports its health and performs supported upgrades. Clients continue to use the gateway API directly, and the operator is not in the request path. + +## Motivation + +Helm with Argo CD or Flux already installs the gateway and corrects drift. What it cannot do is make decisions that depend on the live state of an installation. Generating a missing key-encryption key (KEK) is correct for a new database, but for an existing database it makes stored credentials unreadable. An upgrade that migrates the database schema needs a verified backup and a single upgraded replica before the others start, not a rolling update. The operator makes these decisions, and reports when it cannot proceed safely, so platform teams do not each have to build them. + +## Non-goals + +- CRDs for sandboxes, templates and providers, which [RFC 0030](https://github.com/ai-openshell/openshell/issues/6073) proposes in the same `openshell.ai` API group, and CRDs for agents, logical workspaces, memberships or policies. +- Cross-namespace sandbox placement, or cluster-scoped RBAC created per gateway, in v1alpha1. +- Operating PostgreSQL, the identity provider, a certificate authority or Agent Sandbox. +- Adopting existing Helm releases, migrating between database engines, or guaranteeing zero-downtime upgrades. + +## Proposal + +### API + +One `OpenShellGateway` declares one gateway installation. This example uses single-replica SQLite, OIDC and dedicated supervisors: + +```yaml +apiVersion: openshell.ai/v1alpha1 +kind: OpenShellGateway +metadata: + name: openshell + namespace: openshell +spec: + gateway: + replicas: 1 + database: + type: SQLite + sqlite: + storage: + size: 10Gi + authentication: + oidc: + issuer: https://identity.example.com/realms/platform + audience: openshell-api + rolesClaim: realm_access.roles + adminRole: openshell-admin + userRole: openshell-user + security: + tls: + serverSecretRef: + name: openshell-server-tls + serverCASecretRef: + name: openshell-ca-tls + key: ca.crt + supervisor: + topology: Dedicated +``` + +The main types are shown below; validation markers and the full schema are left to implementation. + +```go +type OpenShellGatewaySpec struct { + Gateway GatewaySpec `json:"gateway,omitempty"` + Database DatabaseSpec `json:"database"` + Authentication AuthenticationSpec `json:"authentication"` + Security SecuritySpec `json:"security"` + Supervisor SupervisorSpec `json:"supervisor,omitempty"` + UpgradeStrategy UpgradeStrategy `json:"upgradeStrategy,omitempty"` // Automatic (default) | Hold +} + +type GatewaySpec struct { + Image string `json:"image,omitempty"` // Defaults to the operator's target release. + Replicas *int32 `json:"replicas,omitempty"` // Default 1; SQLite requires 1. + Service ServiceSpec `json:"service,omitempty"` // Type: ClusterIP (default) | LoadBalancer + Resources corev1.ResourceRequirements `json:"resources,omitempty"` + NodeSelector map[string]string `json:"nodeSelector,omitempty"` + Tolerations []corev1.Toleration `json:"tolerations,omitempty"` +} + +// Exactly one backend block, matching Type. Changing Type after installation is rejected. +type DatabaseSpec struct { + Type DatabaseType `json:"type"` // SQLite | PostgreSQL + SQLite *SQLiteSpec `json:"sqlite,omitempty"` // Storage for a retained PVC. + PostgreSQL *PostgreSQLSpec `json:"postgresql,omitempty"` // ConnectionSecretRef to an external database. +} + +// At least one mechanism is required. +type AuthenticationSpec struct { + OIDC *OIDCSpec `json:"oidc,omitempty"` + MTLS *MTLSSpec `json:"mtls,omitempty"` + AllowUnauthenticatedUsers bool `json:"allowUnauthenticatedUsers,omitempty"` // UNSAFE: trusted local development only. +} + +// All fields are required and non-empty. +type OIDCSpec struct { + Issuer string `json:"issuer"` + Audience string `json:"audience"` + RolesClaim string `json:"rolesClaim"` + AdminRole string `json:"adminRole"` + UserRole string `json:"userRole"` +} + +type MTLSSpec struct { + ClientCASecretRef SecretKeyRef `json:"clientCASecretRef"` +} + +type SecuritySpec struct { + TLS TLSSpec `json:"tls"` // ServerSecretRef and ServerCASecretRef; issued by the platform. + // Optional. When omitted, keys are generated once for a new installation. + SigningKeysSecretRef *SecretRef `json:"signingKeysSecretRef,omitempty"` + CredentialEncryptionKeySecretRef *SecretRef `json:"credentialEncryptionKeySecretRef,omitempty"` +} + +type SupervisorSpec struct { + Topology SupervisorTopology `json:"topology,omitempty"` // Dedicated (default) | Gateway + Image string `json:"image,omitempty"` // Required when gateway.image is set; must come from the same release. + Replicas *int32 `json:"replicas,omitempty"` // Gateway topology only. + Resources corev1.ResourceRequirements `json:"resources,omitempty"` // Gateway topology only. +} + +type OpenShellGatewayStatus struct { + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` // Ready, Progressing, Degraded, Available, UnauthenticatedAccess + GatewayID string `json:"gatewayID,omitempty"` + Endpoint string `json:"endpoint,omitempty"` + CABundleRef *SecretKeyRef `json:"caBundleRef,omitempty"` + InstalledRelease string `json:"installedRelease,omitempty"` + TargetRelease string `json:"targetRelease,omitempty"` + UpgradeHeld bool `json:"upgradeHeld,omitempty"` + Images ImageStatus `json:"images,omitempty"` // Effective gateway and supervisor images. + WorkspacePlacement PlacementStatus `json:"workspacePlacement,omitempty"` // Mode and sandbox namespace. +} +``` + +Secret references are resolved in the CR's namespace, and the operator never modifies or deletes referenced Secrets. Image overrides are owned by the administrator: operator upgrades do not replace them. Custom builds are allowed but are outside the upstream test matrix. + +### Reconciliation + +The controller owns the gateway workload, Service, configuration, namespace-scoped RBAC and supervisor resources. On each reconcile it: + +- **Checks prerequisites**, such as the Agent Sandbox API and referenced Secrets, and reports a blocker instead of disrupting a healthy installation. +- **Protects keys.** Signing and encryption keys are generated only for a new installation. If keys are missing and the database may contain encrypted credentials, the controller blocks and asks for a restore. +- **Applies changes deliberately.** The operator renders the gateway configuration file ([RFC 0003](../0003-gateway-configuration/README.md)) from the CR into a ConfigMap it owns. `database_url` is not allowed in the file, so the operator injects `OPENSHELL_DB_URL` from `database.postgresql.connectionSecretRef` for PostgreSQL, or sets a `sqlite:` path on the retained PVC for SQLite. Changing a setting the gateway reads at startup rolls the workload, and certificate renewals reload in place. +- **Respects ownership.** It does not adopt existing objects by name or modify platform-owned Secrets. + +An operator outage pauses reconciliation; running gateways keep serving. + +### Status + +`Ready` is the summary condition. A generation has converged when `Ready=True`, `Progressing=False` and `observedGeneration` matches `metadata.generation`; GitOps health checks should read that combination. `Degraded` explains actionable failures, and `Available` reports whether a gateway is still serving, possibly at its previous configuration. Status also publishes the endpoint and CA bundle reference, so clients and other components can find and trust the gateway. It never contains tokens, keys, connection strings or per-sandbox state. + +### Upgrades + +Each operator release targets one compatible OpenShell release. With `Automatic`, the operator upgrades eligible gateways; `Hold` keeps an installed gateway on its current release while health reporting and other reconciliation continue. Updating the operator without changing the target release or effective configuration does not restart gateways. + +A migration cannot be undone, and the operator cannot verify that a backup exists, so a release with a database migration waits for the administrator to confirm a recoverable backup. The operator pauses the upgrade, sets `upgradeHeld` and reports that the target release needs a backup. One approach builds on `Hold`: the administrator sets `upgradeStrategy: Hold`, takes the backup, and approves by switching back to `Automatic`. The exact mechanism, including how approval is tied to a specific target release, is left to implementation. Once approved, the operator stops the gateway replicas, starts one upgraded replica, verifies the migration and scales out. While the gateway is stopped, API clients see it as unavailable. Migrations are forward-only: on failure the operator stops and reports the recovery action instead of retrying or rolling back the image. + +### Deletion and recovery + +The database holds workspaces, memberships, templates, providers, policies and, by default, encrypted credentials. When the CR is deleted, the operator retains the data together with its matching KEK and signing keys; v1alpha1 has no destructive deletion option. External databases and supplied Secrets are never deleted, and deleting the namespace is outside these guarantees. Removing a gateway or shared supervisor pool can interrupt running sandboxes: retained records do not guarantee workload continuity. v1alpha1 does not reattach retained data to a new CR automatically, and in `shared` mode a gateway started on retained data relabels the old Sandboxes as its own. + +### Gateway configuration + +**Placement.** Each namespace hosts one gateway, which runs its sandboxes in the same namespace using the Kubernetes driver's `shared` mode. Gateways sharing a namespace currently interfere with each other's sandboxes, so the operator deploys only the oldest `OpenShellGateway` in a namespace and reports `Ready=False` on any other. Gateway workload permissions are namespace-scoped; the few cluster-scoped permissions the gateway needs are granted once when a cluster administrator installs the operator, and an `OpenShellGateway` cannot widen them. + +**Identity.** The gateway ID is derived from the CR UID, unique across the cluster and reported in status. Recreating the CR creates a new identity. + +**Authentication.** `oidc`, `mtls` and `allowUnauthenticatedUsers` can be combined, and at least one is required; the operator configures the gateway's existing [authentication](../../docs/how-it-works/gateways/authentication.mdx) accordingly. When `oidc` is set, its role fields are required, so the operator never creates an OIDC gateway without role checks. With `mtls` alone, every holder of a certificate from the client CA is a Platform Admin, as in the Helm chart's default installation. `allowUnauthenticatedUsers` matches the chart's development setting and opens the gateway to any caller, so the operator accepts it only if the cluster administrator allowed it when installing the operator, and the `OpenShellGateway` reports an `UnauthenticatedAccess=True` condition. + +**Supervisors.** `Dedicated` (the default) runs one supervisor per sandbox and is rendered by omitting `supervisor_topology`; `Gateway` renders `supervisor_topology = "gateway"` and selects the experimental shared pool from [RFC 0018](../0018-multi-sandbox-ha-supervisors/README.md). Changing topology applies only to new sandbox generations. `supervisor.replicas` must not exceed `gateway.replicas` × the pool's members per gateway. Before scaling the pool down, the operator refuses if the remaining members' `max_instances_per_member` cannot hold the current sandboxes. + +## Implementation plan + +1. Agree on the v1alpha1 API, status conditions and permission boundary. +2. Implement the reconciler with Go `controller-runtime` in the operator repository, with tests for preflight checks, identity, Secret handling and key reuse. +3. Run end-to-end tests on Kubernetes: OIDC alone, mTLS alone and both combined, unauthenticated mode with and without the operator-level opt-in, including workspace membership enforcement; rejection of a second gateway; and namespace-scoped permissions only. +4. Test upgrades and recovery: hold and release, backup approval before migration-bearing upgrades, failed migrations, missing keys, deletion and restore, and pool scale-down versus pool loss. +5. Publish the controller image and installation manifests with install, upgrade and restore documentation. Helm remains supported, and existing Helm installations are not migrated. + +## Risks + +- **Privilege expansion:** a namespace editor must not gain cluster-wide privileges through a gateway. Tests must check the actual ServiceAccounts and bindings. +- **False readiness:** a running Pod does not prove that authentication, trust or placement work. Conditions must reflect installation prerequisites, without creating sandboxes on every reconcile. +- **Unreadable credentials:** retained storage is not enough without its matching KEK. Recovery must be tested with both. +- **Unauthenticated gateways:** `allowUnauthenticatedUsers` grants admin roles to anyone who can reach the gateway. The operator-level opt-in and status reporting must make it impossible to enable silently. +- **Version skew:** held gateways extend the operator's support window, which must be defined and enforced. + +## Alternatives + +### Helm with GitOps only (status quo) + +Fits platforms that already handle backups, identity and migration sequencing. Doing nothing leaves each team to build the OpenShell-specific safety checks and status. + +### User-selected versions and workspace modes + +More flexible, but they widen the upgrade matrix and the privilege boundary. + +## Prior art + +- [OpenShell's Helm chart](../../deploy/helm/openshell) is the reference for database, identity, TLS and supervisor wiring. Its key reuse depends on a Helm `lookup`, which GitOps tools often render without cluster access; the operator replaces that with a live check. +- Strimzi's `deleteClaim` and ECK's `volumeClaimDeletePolicy` make storage retention explicit. OpenShell additionally has to keep data and its KEK together. +- [Draft RFC 0019](https://github.com/ai-openshell/openshell/pull/4426) discusses a separate repository for Kubernetes deployment assets; where the operator lives should follow that decision. + +## Open questions + +- **Repository and toolchain:** should the operator live in a separate repository planned by [draft RFC 0019](https://github.com/ai-openshell/openshell/pull/4426) together with the Helm chart? +- **Operator releases:** how do operator releases map to OpenShell releases, how long can a held gateway stay on an older release, and which distribution channels (installation manifests, OLM) are needed for the first release? +- **Compatibility matrix:** which gateway releases and database backends does each operator release support and test? +- **Configuration coverage:** v1alpha1 can't express gateway settings the CR doesn't model, such as private OIDC CAs and JWKS origins. Should these be typed fields, or should v1alpha1 offer a validated passthrough for the gateway configuration? +- **Cluster-scoped permissions:** how are the cluster-scoped read and TokenReview permissions bound to each gateway's ServiceAccount without creating a ClusterRoleBinding per gateway? +- **Restore:** how does an administrator restore retained storage and keys into a new `OpenShellGateway`, and does v1alpha1 need fields that reference an existing PVC?