From 0eb96ac8726b055a29596c2aceab734242481b06 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Mon, 23 Nov 2026 16:40:18 +0100 Subject: [PATCH] feat(mongodb)!: render a CredentialTemplate per user Tenant passwords move to the Cozystack credentials API: the chart renders one CredentialTemplate per user and each user of the PerconaServerMongoDB reads its password from the account Secret the controller keeps, so a password is shown once, at mint, instead of being generated at render time. MongoDB computes SCRAM from the plaintext, so the account Secret stores the password itself. The operator re-reads that Secret on every reconcile and runs updateUser when its digest changes, so a mint applies without a restart and the Secret needs no label. The per-user Secrets and users..password are gone; a password left in values is ignored and draws an admission warning that points at a mint on the user's Credential. -credentials keeps the databaseAdmin system user, a platform account: it is rendered not tenant-visible and the ApplicationDefinition excludes it instead of including it. Users named like a system user, or mapping to one account name or to one longer than 63 characters, are refused. The Percona operator creates and updates the users in spec.users but never drops one that leaves it, so a removed user would lose its CredentialTemplate and account Secret yet keep its last password in MongoDB, with no Credential left to revoke it through. Every declared user therefore also holds a marker role that grants nothing, and only the operator grants it. A post-upgrade hook logs in as the userAdmin platform account and drops the users in admin that hold the marker, are no longer declared, and are not system users. A user without the marker, created by hand or before the marker existed, is never touched. The hook is skipped while restoring from a backup. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- api/apps/v1alpha1/mongodb/types.go | 4 +- hack/check-mongodb-rd-secrets.bats | 23 +- hack/e2e-chainsaw/mongodb/chainsaw-test.yaml | 20 +- packages/apps/mongodb/README.md | 7 +- packages/apps/mongodb/templates/_accounts.tpl | 53 +++++ packages/apps/mongodb/templates/accounts.yaml | 23 ++ .../apps/mongodb/templates/credentials.yaml | 9 + .../templates/hooks/drop-users-job.yaml | 141 ++++++++++++ packages/apps/mongodb/templates/mongodb.yaml | 25 ++- .../apps/mongodb/templates/user-secrets.yaml | 17 -- .../tests/account_secret_ref_test.yaml | 56 +++++ .../tests/credential_templates_test.yaml | 102 +++++++++ .../mongodb/tests/drop_users_job_test.yaml | 207 ++++++++++++++++++ packages/apps/mongodb/tests/mongodb_test.yaml | 2 +- .../tests/no_tenant_password_test.yaml | 58 +++++ .../apps/mongodb/tests/user-secrets_test.yaml | 78 ------- packages/apps/mongodb/values.schema.json | 10 +- packages/apps/mongodb/values.yaml | 8 +- .../system/mongodb-rd/cozyrds/mongodb.yaml | 15 +- pkg/registry/apps/application/rest.go | 2 + .../application/rest_serversideapply_test.go | 2 +- ...est_warn_removed_password_callsite_test.go | 3 +- 22 files changed, 720 insertions(+), 145 deletions(-) create mode 100644 packages/apps/mongodb/templates/_accounts.tpl create mode 100644 packages/apps/mongodb/templates/accounts.yaml create mode 100644 packages/apps/mongodb/templates/hooks/drop-users-job.yaml delete mode 100644 packages/apps/mongodb/templates/user-secrets.yaml create mode 100644 packages/apps/mongodb/tests/account_secret_ref_test.yaml create mode 100644 packages/apps/mongodb/tests/credential_templates_test.yaml create mode 100644 packages/apps/mongodb/tests/drop_users_job_test.yaml create mode 100644 packages/apps/mongodb/tests/no_tenant_password_test.yaml delete mode 100644 packages/apps/mongodb/tests/user-secrets_test.yaml diff --git a/api/apps/v1alpha1/mongodb/types.go b/api/apps/v1alpha1/mongodb/types.go index ff23bc560..d0c522406 100644 --- a/api/apps/v1alpha1/mongodb/types.go +++ b/api/apps/v1alpha1/mongodb/types.go @@ -45,7 +45,7 @@ type ConfigSpec struct { // Configuration for sharded cluster mode. // +kubebuilder:default:={} ShardingConfig ShardingConfig `json:"shardingConfig"` - // Users configuration map. + // Users configuration map. Each user is a MongoDB user the operator manages from an account Secret the platform keeps. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. A `password` key here is ignored. The names of the MongoDB system users (`backup`, `clusterAdmin`, `clusterMonitor`, `databaseAdmin`, `userAdmin`) are refused. // +kubebuilder:default:={} Users map[string]User `json:"users,omitempty"` // Databases configuration map. @@ -149,8 +149,6 @@ type ShardingConfig struct { } type User struct { - // Password for the user (auto-generated if omitted). - Password string `json:"password,omitempty"` } // +kubebuilder:validation:Enum="t1.nano";"t1.micro";"t1.small";"t1.medium";"t1.large";"t1.xlarge";"t1.2xlarge";"t1.4xlarge";"c1.nano";"c1.micro";"c1.small";"c1.medium";"c1.large";"c1.xlarge";"c1.2xlarge";"c1.4xlarge";"s1.nano";"s1.micro";"s1.small";"s1.medium";"s1.large";"s1.xlarge";"s1.2xlarge";"s1.4xlarge";"u1.nano";"u1.micro";"u1.small";"u1.medium";"u1.large";"u1.xlarge";"u1.2xlarge";"u1.4xlarge";"m1.nano";"m1.micro";"m1.small";"m1.medium";"m1.large";"m1.xlarge";"m1.2xlarge";"m1.4xlarge";"nano";"micro";"small";"medium";"large";"xlarge";"2xlarge" diff --git a/hack/check-mongodb-rd-secrets.bats b/hack/check-mongodb-rd-secrets.bats index 23f2d255e..ca3e5df57 100644 --- a/hack/check-mongodb-rd-secrets.bats +++ b/hack/check-mongodb-rd-secrets.bats @@ -55,8 +55,9 @@ SELF="$REPO_ROOT/hack/check-mongodb-rd-secrets.bats" # grep-based tests would not notice either, since the strings stay in the # file. Deleting `include` outright is already caught by the label grep; this # covers the rename. + # One entry since the credentials Secret left include: the label selector. n="$(yq '.spec.secrets.include // [] | length' "$COZYRDS")" - if [ "$n" -lt 2 ]; then + if [ "$n" -lt 1 ]; then echo "spec.secrets.include has $n entries; the structural checks would be vacuous" >&2 exit 1 fi @@ -126,21 +127,19 @@ SELF="$REPO_ROOT/hack/check-mongodb-rd-secrets.bats" done } -@test "mongodb-rd cozyrds still delivers the credentials secret" { - # The exclude list added alongside the trust anchor is evaluated BEFORE - # include and wins outright, so it now sits upstream of this pre-existing - # grant. Every other line in that block is about withholding a Secret, which - # makes adding this one to it a plausible edit — and one that would silently - # revoke the tenant's access to their own connection string. Assert both - # directions. +@test "mongodb-rd cozyrds hides the databaseAdmin credentials secret" { + # -credentials holds the databaseAdmin system user, a platform + # account since tenant users became Credentials minted through the + # Cozystack API. It must be excluded and never included: an include entry + # would hand the platform password back to every tenant reader. inc="$(yq '[.spec.secrets.include[].resourceNames[]? | select(. == "mongodb-{{ .name }}-credentials")] | length' "$COZYRDS")" - if [ "$inc" != "1" ]; then - echo "credentials is not granted via include (found $inc entries)" >&2 + if [ "$inc" != "0" ]; then + echo "credentials is still granted via include (found $inc entries)" >&2 exit 1 fi exc="$(yq '[.spec.secrets.exclude[].resourceNames[]? | select(. == "mongodb-{{ .name }}-credentials")] | length' "$COZYRDS")" - if [ "$exc" != "0" ]; then - echo "credentials appears in exclude, which wins over include" >&2 + if [ "$exc" != "1" ]; then + echo "credentials is not excluded (found $exc entries)" >&2 exit 1 fi } diff --git a/hack/e2e-chainsaw/mongodb/chainsaw-test.yaml b/hack/e2e-chainsaw/mongodb/chainsaw-test.yaml index 8ebdd384b..b38ba2e9e 100644 --- a/hack/e2e-chainsaw/mongodb/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/mongodb/chainsaw-test.yaml @@ -155,11 +155,19 @@ spec: # the mechanism is live, all three would pass while asserting nothing about # the CA private key. # - # The credentials Secret is the right witness: the chart renders it, it - # traces to the MongoDB CR, and the ApplicationDefinition grants it by name - # — so it MUST be stamped. This also catches the regression the exclude - # list makes newly possible, since exclude is evaluated before include and - # would silently revoke the tenant's own connection string. + # The tenant-ca projection is the witness: the ApplicationDefinition + # selects it by label, so the lineage webhook MUST stamp it. The + # credentials Secret no longer qualifies: it holds the databaseAdmin + # platform account and must stay hidden, which the second assert checks. + - assert: + timeout: 2m + resource: + apiVersion: v1 + kind: Secret + metadata: + name: mongodb-test.tenant-ca + labels: + internal.cozystack.io/tenantresource: "true" - assert: timeout: 2m resource: @@ -168,7 +176,7 @@ spec: metadata: name: mongodb-test-credentials labels: - internal.cozystack.io/tenantresource: "true" + internal.cozystack.io/tenantresource: "false" - assert: timeout: 2m resource: diff --git a/packages/apps/mongodb/README.md b/packages/apps/mongodb/README.md index 7790b3b75..b16989407 100644 --- a/packages/apps/mongodb/README.md +++ b/packages/apps/mongodb/README.md @@ -229,10 +229,9 @@ Releases with `external: false`, and sharded releases in any configuration, are ### Users configuration -| Name | Description | Type | Value | -| ---------------------- | -------------------------------------------------- | ------------------- | ----- | -| `users` | Users configuration map. | `map[string]object` | `{}` | -| `users[name].password` | Password for the user (auto-generated if omitted). | `string` | `""` | +| Name | Description | Type | Value | +| ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ----- | +| `users` | Users configuration map. Each user is a MongoDB user the operator manages from an account Secret the platform keeps. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. A `password` key here is ignored. The names of the MongoDB system users (`backup`, `clusterAdmin`, `clusterMonitor`, `databaseAdmin`, `userAdmin`) are refused. | `map[string]object` | `{}` | ### Databases configuration diff --git a/packages/apps/mongodb/templates/_accounts.tpl b/packages/apps/mongodb/templates/_accounts.tpl new file mode 100644 index 000000000..bfa9360de --- /dev/null +++ b/packages/apps/mongodb/templates/_accounts.tpl @@ -0,0 +1,53 @@ +{{/* + Account Secret naming, which must match pkg/credentials/account.MapName: the + API writes ..account, where is the user name + lowercased with every character outside [a-z0-9-] replaced by "-". The API + refuses two users that map to one account; the guard here covers a + HelmRelease written around it, where the operator would read one Secret for + both. +*/}} +{{- define "mongodb.accountName" -}} +{{- regexReplaceAll "[^a-z0-9-]" (lower .) "-" -}} +{{- end -}} + +{{- define "mongodb.accountSecret" -}} +{{- $root := index . 0 -}} +{{- $user := index . 1 -}} +{{- printf "%s.%s.account" $root.Release.Name (include "mongodb.accountName" $user) -}} +{{- end -}} + +{{/* + Refusals for user names the operator would not apply. The system users are + platform accounts kept in -percona-server-mongodb-users; the + operator skips a custom user that reuses one of their names, so a template + for it would mint a password that never reaches the engine. +*/}} +{{- define "mongodb.accountsGuard" -}} +{{- $reserved := include "mongodb.systemUserNames" . | fromJsonArray -}} +{{- $seen := dict -}} +{{- range $user, $_ := .Values.users -}} + {{- $mapped := include "mongodb.accountName" $user -}} + {{- if or (gt (len $mapped) 63) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $mapped)) -}} + {{- fail (printf "user %q maps to the account name %q, which must be at most 63 characters and start and end with a letter or a digit; rename the user" $user $mapped) -}} + {{- end -}} + {{- with index $seen $mapped -}} + {{- fail (printf "users %q and %q both map to the account name %q; rename one of them" . $user $mapped) -}} + {{- end -}} + {{- $_ := set $seen $mapped $user -}} + {{- if has $user $reserved -}} + {{- fail (printf "user %q is reserved: it is the name of a MongoDB system user the platform manages; rename the user" $user) -}} + {{- end -}} +{{- end -}} +{{- end -}} + +{{/* + The role every user the chart declares holds, and nothing else does: only + the operator, through spec.users, grants it. +*/}} +{{- define "mongodb.managedRole" -}} +cozystack-managed +{{- end -}} + +{{- define "mongodb.systemUserNames" -}} +{{- list "backup" "clusterAdmin" "clusterMonitor" "databaseAdmin" "userAdmin" | toJson -}} +{{- end -}} diff --git a/packages/apps/mongodb/templates/accounts.yaml b/packages/apps/mongodb/templates/accounts.yaml new file mode 100644 index 000000000..928b8b786 --- /dev/null +++ b/packages/apps/mongodb/templates/accounts.yaml @@ -0,0 +1,23 @@ +{{- /* + One CredentialTemplate per user: the account the Cozystack credentials API + mints and revokes through. cozystack-controller keeps its account Secret, + ..account, which spec.users[].passwordSecretRef names in + mongodb.yaml. MongoDB computes its SCRAM credentials from the plaintext, so + the Secret stores the password itself. The Percona operator re-reads it on + every reconcile, every five seconds while the cluster is ready, and runs + updateUser when its digest differs from the one the operator annotated, so + the Secret needs no label. The chart renders no password: a user exists in + the database once its Secret does, and nobody can log in until a mint. +*/ -}} +{{- include "mongodb.accountsGuard" $ }} +{{- range $user, $_ := .Values.users }} +--- +apiVersion: cozystack.io/v1alpha1 +kind: CredentialTemplate +metadata: + name: {{ printf "%s.%s" $.Release.Name (include "mongodb.accountName" $user) | quote }} +spec: + username: {{ $user | quote }} + format: + name: plaintext +{{- end }} diff --git a/packages/apps/mongodb/templates/credentials.yaml b/packages/apps/mongodb/templates/credentials.yaml index 1cf8dc7d8..078f682f0 100644 --- a/packages/apps/mongodb/templates/credentials.yaml +++ b/packages/apps/mongodb/templates/credentials.yaml @@ -66,11 +66,20 @@ stringData: {{ $key }}: {{ index $resolved $key | quote }} {{- end }} {{- end }} +{{- /* + The databaseAdmin system user is a platform account: tenant users are + CredentialTemplates (accounts.yaml), and this copy is not tenant-visible. + The label is the closure for a Secret the lineage webhook stamped before the + conversion, since the webhook keeps an explicit "false"; the + ApplicationDefinition no longer selects it. +*/}} --- apiVersion: v1 kind: Secret metadata: name: {{ .Release.Name }}-credentials + labels: + internal.cozystack.io/tenantresource: "false" type: Opaque stringData: username: {{ $adminUser | quote }} diff --git a/packages/apps/mongodb/templates/hooks/drop-users-job.yaml b/packages/apps/mongodb/templates/hooks/drop-users-job.yaml new file mode 100644 index 000000000..b462e87c5 --- /dev/null +++ b/packages/apps/mongodb/templates/hooks/drop-users-job.yaml @@ -0,0 +1,141 @@ +{{- /* + Drops the users this chart created that values no longer declare. The + Percona operator creates and updates the users in spec.users but never drops + one that leaves it, so a removed user would keep its last password in + MongoDB after its CredentialTemplate and account Secret are gone, with no + Credential left to revoke it through. + + A user is dropped only when it holds the marker role, which only the + operator grants and only to the users in spec.users (mongodb.yaml), is not + declared, and is not a system user. A user without the marker, created by + hand or by an earlier chart, is never touched. The Job logs in as the + userAdmin system user, a platform account, never as a tenant user. + + post-upgrade only: on install nothing carries the marker yet. Skipped while + the chart restores from a backup, where the cluster is busy and the restored + users are not this release's to judge until the restore is done. A failure + fails the upgrade, so a user that should be gone is reported, and the next + upgrade retries. +*/}} +{{- if not .Values.bootstrap.enabled }} +{{- $clusterDomain := (index .Values._cluster "cluster-domain") | default "cozy.local" }} +{{- $usersSecret := printf "%s-percona-server-mongodb-users" .Release.Name }} +{{- $uri := printf "mongodb://%s-rs0.%s.svc.%s:27017/admin?replicaSet=rs0" .Release.Name .Release.Namespace $clusterDomain }} +{{- if .Values.sharding }} +{{- $uri = printf "mongodb://%s-mongos.%s.svc.%s:27017/admin" .Release.Name .Release.Namespace $clusterDomain }} +{{- end }} +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ .Release.Name }}-drop-users + annotations: + "helm.sh/hook": post-upgrade + "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded +spec: + {{- /* Under the platform's 10m hook budget, so the Job's own deadline names the failure. */}} + activeDeadlineSeconds: 540 + backoffLimit: 0 + ttlSecondsAfterFinished: 3600 + template: + spec: + restartPolicy: Never + containers: + - name: drop-users + image: percona/percona-server-mongodb:{{ include "mongodb.versionMap" $ }} + command: + - sh + - -ec + - | + # The password stays out of the pod spec: it reaches mongosh from + # the environment, inside the container only. + sh_mongo() { + mongosh "$MONGO_URI" --quiet --norc \ + --username "$MONGO_USER" --password "$MONGO_PASSWORD" \ + --authenticationDatabase admin "$@" + } + # An upgrade may roll the pods; wait for a primary rather than fail + # on the first refused connection. + i=0 + until sh_mongo --eval 'db.hello().isWritablePrimary || db.hello().msg === "isdbgrid" || quit(1)' >/dev/null 2>&1; do + i=$((i + 1)) + if [ "$i" -ge 60 ]; then + echo "MongoDB did not accept the userAdmin login with a writable primary in 5 minutes" >&2 + exit 1 + fi + sleep 5 + done + sh_mongo --eval "$DROP_JS" + env: + - name: HOME + value: /tmp + - name: MONGO_URI + value: {{ $uri | quote }} + - name: MONGO_USER + valueFrom: + secretKeyRef: + name: {{ $usersSecret }} + key: MONGODB_USER_ADMIN_USER + - name: MONGO_PASSWORD + valueFrom: + secretKeyRef: + name: {{ $usersSecret }} + key: MONGODB_USER_ADMIN_PASSWORD + {{- range $key := list "MONGODB_BACKUP_USER" "MONGODB_CLUSTER_ADMIN_USER" "MONGODB_CLUSTER_MONITOR_USER" "MONGODB_DATABASE_ADMIN_USER" "MONGODB_USER_ADMIN_USER" }} + - name: SYS_{{ $key }} + valueFrom: + secretKeyRef: + name: {{ $usersSecret }} + key: {{ $key }} + optional: true + {{- end }} + - name: DECLARED_USERS + value: {{ keys (.Values.users | default dict) | sortAlpha | toJson | quote }} + - name: DEFAULT_SYSTEM_USERS + value: {{ include "mongodb.systemUserNames" . | quote }} + - name: MANAGED_ROLE + value: {{ include "mongodb.managedRole" . | quote }} + - name: DROP_JS + value: | + const env = process.env; + const declared = new Set(JSON.parse(env.DECLARED_USERS)); + const system = new Set(JSON.parse(env.DEFAULT_SYSTEM_USERS)); + for (const [k, v] of Object.entries(env)) { + if (k.startsWith("SYS_") && v) system.add(v); + } + const admin = db.getSiblingDB("admin"); + const res = admin.runCommand({ usersInfo: 1 }); + if (res.ok !== 1) throw new Error("usersInfo failed: " + tojson(res)); + for (const u of res.users) { + const marked = (u.roles || []).some(r => r.role === env.MANAGED_ROLE && r.db === "admin"); + if (u.db !== "admin" || !marked || declared.has(u.user) || system.has(u.user)) continue; + const out = admin.runCommand({ dropUser: u.user }); + if (out.ok !== 1) throw new Error("dropUser " + u.user + " failed: " + tojson(out)); + print("dropped user " + u.user + ", no longer declared"); + } + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + privileged: false + readOnlyRootFilesystem: true + runAsNonRoot: true + resources: + requests: + cpu: 50m + memory: 128Mi + limits: + memory: 256Mi + volumeMounts: + - mountPath: /tmp + name: tmp + securityContext: + runAsNonRoot: true + runAsUser: 1001 + runAsGroup: 1001 + seccompProfile: + type: RuntimeDefault + volumes: + - name: tmp + emptyDir: {} +{{- end }} diff --git a/packages/apps/mongodb/templates/mongodb.yaml b/packages/apps/mongodb/templates/mongodb.yaml index 26e23054e..f541f0501 100644 --- a/packages/apps/mongodb/templates/mongodb.yaml +++ b/packages/apps/mongodb/templates/mongodb.yaml @@ -207,25 +207,46 @@ spec: {{- $_ := set $userRoles $user $roles }} {{- end }} {{- end }} + {{- /* + Each user reads its password from the account Secret the platform keeps + (accounts.yaml). With the Secret missing the operator skips the user, so an + account nobody seeded or minted for keeps whatever password it had. + */}} + {{- include "mongodb.accountsGuard" $ }} users: {{- range $username, $user := .Values.users }} {{- $roles := index $userRoles $username }} {{- if not $roles }} {{- fail (printf "user '%s' is not assigned to any database role in databases.*.roles" $username) }} {{- end }} - - name: {{ $username }} + - name: {{ $username | quote }} db: admin passwordSecretRef: - name: {{ $.Release.Name }}-user-{{ $username }} + name: {{ include "mongodb.accountSecret" (list $ $username) | quote }} key: password roles: {{- range $roles }} - name: {{ .name }} db: {{ .db }} {{- end }} + - name: {{ include "mongodb.managedRole" $ }} + db: admin {{- end }} {{- end }} + {{- /* + The marker role grants nothing. It tells the users this chart declared + from every other user in the database, so the post-upgrade hook + (hooks/drop-users-job.yaml) drops a user once it leaves values, which the + operator never does, and leaves alone the system users and any user the + chart did not create. Rendered with no users too, so it outlives the last + one. + */}} + roles: + - role: {{ include "mongodb.managedRole" $ }} + db: admin + privileges: [] + backup: enabled: {{ .Values.backup.enabled | default false }} image: percona/percona-backup-mongodb:2.11.0 diff --git a/packages/apps/mongodb/templates/user-secrets.yaml b/packages/apps/mongodb/templates/user-secrets.yaml deleted file mode 100644 index 8212e95f8..000000000 --- a/packages/apps/mongodb/templates/user-secrets.yaml +++ /dev/null @@ -1,17 +0,0 @@ -{{- range $username, $user := .Values.users }} -{{- $existingSecret := lookup "v1" "Secret" $.Release.Namespace (printf "%s-user-%s" $.Release.Name $username) }} ---- -apiVersion: v1 -kind: Secret -metadata: - name: {{ $.Release.Name }}-user-{{ $username }} -type: Opaque -stringData: - {{- if $user.password }} - password: {{ $user.password | quote }} - {{- else if and $existingSecret (hasKey $existingSecret.data "password") }} - password: {{ index $existingSecret.data "password" | b64dec | quote }} - {{- else }} - password: {{ randAlphaNum 16 | quote }} - {{- end }} -{{- end }} diff --git a/packages/apps/mongodb/tests/account_secret_ref_test.yaml b/packages/apps/mongodb/tests/account_secret_ref_test.yaml new file mode 100644 index 000000000..f852c2f8d --- /dev/null +++ b/packages/apps/mongodb/tests/account_secret_ref_test.yaml @@ -0,0 +1,56 @@ +suite: users read their passwords from the account Secrets + +# mongodb.yaml must name the Secret accounts.yaml's template gets, and nothing +# a value can set. + +templates: + - templates/mongodb.yaml + +release: + name: test-mongodb + namespace: tenant-test + +set: + _cluster: + cluster-domain: cozy.local + databases: + app: + roles: + admin: + - web + - Bob.Smith + +tests: + - it: points each user's passwordSecretRef at its account Secret + documentSelector: + path: kind + value: PerconaServerMongoDB + set: + users: + Bob.Smith: {} + asserts: + - equal: + path: spec.users[0].name + value: Bob.Smith + - equal: + path: spec.users[0].passwordSecretRef + value: + name: test-mongodb.bob-smith.account + key: password + + - it: ignores a password left in values + documentSelector: + path: kind + value: PerconaServerMongoDB + set: + users: + web: + password: leftover-from-values + asserts: + - equal: + path: spec.users[0].passwordSecretRef.name + value: test-mongodb.web.account + - notMatchRegex: + path: spec.users[0].passwordSecretRef.name + pattern: leftover + diff --git a/packages/apps/mongodb/tests/credential_templates_test.yaml b/packages/apps/mongodb/tests/credential_templates_test.yaml new file mode 100644 index 000000000..ab23a7246 --- /dev/null +++ b/packages/apps/mongodb/tests/credential_templates_test.yaml @@ -0,0 +1,102 @@ +suite: one CredentialTemplate per user, naming the account Secret the CR reads + +# The template is the account the credentials API mints through; its name plus +# ".account" must be the passwordSecretRef mongodb.yaml gives the user, or the +# operator reads a Secret nobody writes. + +templates: + - templates/accounts.yaml + +release: + name: test-mongodb + namespace: tenant-test + +set: + _cluster: + cluster-domain: cozy.local + databases: + app: + roles: + admin: + - web + - Bob.Smith + +tests: + - it: renders nothing without users + set: + databases: {} + asserts: + - hasDocuments: + count: 0 + + - it: renders a template per user, named for the account Secret's mapping + set: + users: + web: {} + Bob.Smith: {} + asserts: + - hasDocuments: + count: 2 + - isKind: + of: CredentialTemplate + - equal: + path: apiVersion + value: cozystack.io/v1alpha1 + - equal: + path: metadata.name + value: test-mongodb.bob-smith + documentIndex: 0 + - equal: + path: spec.username + value: Bob.Smith + documentIndex: 0 + - equal: + path: metadata.name + value: test-mongodb.web + documentIndex: 1 + + - it: stores the plaintext, with no label and no valuesPath + set: + users: + web: {} + asserts: + - equal: + path: spec.format.name + value: plaintext + - notExists: + path: spec.secret + - notExists: + path: spec.valuesPath + + - it: refuses two users that map to one account + set: + users: + web: {} + Web: {} + asserts: + - failedTemplate: + errorPattern: map to + + - it: refuses a user named like a system user + set: + users: + databaseAdmin: {} + asserts: + - failedTemplate: + errorPattern: reserved + + - it: refuses a user whose account name cannot be a Secret name + set: + users: + _web: {} + asserts: + - failedTemplate: + errorPattern: start and end with a letter or a digit + + - it: refuses a user whose account name is longer than a DNS label + set: + users: + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: {} + asserts: + - failedTemplate: + errorPattern: at most 63 characters diff --git a/packages/apps/mongodb/tests/drop_users_job_test.yaml b/packages/apps/mongodb/tests/drop_users_job_test.yaml new file mode 100644 index 000000000..9012208d8 --- /dev/null +++ b/packages/apps/mongodb/tests/drop_users_job_test.yaml @@ -0,0 +1,207 @@ +suite: users no longer declared are dropped, and only those the chart marked + +# The operator never drops a user that leaves spec.users. The chart marks the +# users it declares with a role that grants nothing, and a post-upgrade hook +# drops marked users that are no longer declared, logging in as the userAdmin +# platform account. + +templates: + - templates/hooks/drop-users-job.yaml + - templates/mongodb.yaml + +release: + name: test-mongodb + namespace: tenant-test + upgrade: true + +set: + _cluster: + cluster-domain: cozy.local + users: + web: {} + databases: + app: + roles: + admin: + - web + +tests: + - it: marks every declared user with the role that grants nothing + template: templates/mongodb.yaml + documentSelector: + path: kind + value: PerconaServerMongoDB + asserts: + - contains: + path: spec.users[0].roles + content: + name: cozystack-managed + db: admin + - equal: + path: spec.roles + value: + - role: cozystack-managed + db: admin + privileges: [] + + - it: keeps the marker role when no user is left + template: templates/mongodb.yaml + documentSelector: + path: kind + value: PerconaServerMongoDB + set: + # null rather than {}: the suite's users would be merged into an empty map. + users: null + databases: null + asserts: + - notExists: + path: spec.users + - equal: + path: spec.roles[0].role + value: cozystack-managed + + - it: runs as a post-upgrade hook bounded under the hook budget + template: templates/hooks/drop-users-job.yaml + asserts: + - isKind: + of: Job + - equal: + path: metadata.annotations["helm.sh/hook"] + value: post-upgrade + - equal: + path: spec.activeDeadlineSeconds + value: 540 + - equal: + path: spec.backoffLimit + value: 0 + + - it: logs in as the userAdmin platform account, never a tenant account + template: templates/hooks/drop-users-job.yaml + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: MONGO_USER + valueFrom: + secretKeyRef: + name: test-mongodb-percona-server-mongodb-users + key: MONGODB_USER_ADMIN_USER + - contains: + path: spec.template.spec.containers[0].env + content: + name: MONGO_PASSWORD + valueFrom: + secretKeyRef: + name: test-mongodb-percona-server-mongodb-users + key: MONGODB_USER_ADMIN_PASSWORD + - notMatchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: \.account + + - it: passes the declared users and protects the system users + template: templates/hooks/drop-users-job.yaml + set: + users: + web: {} + api: {} + databases: + app: + roles: + admin: [web, api] + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: DECLARED_USERS + value: '["api","web"]' + - contains: + path: spec.template.spec.containers[0].env + content: + name: DEFAULT_SYSTEM_USERS + value: '["backup","clusterAdmin","clusterMonitor","databaseAdmin","userAdmin"]' + - contains: + path: spec.template.spec.containers[0].env + content: + name: SYS_MONGODB_DATABASE_ADMIN_USER + valueFrom: + secretKeyRef: + name: test-mongodb-percona-server-mongodb-users + key: MONGODB_DATABASE_ADMIN_USER + optional: true + + # A name YAML would read differently unquoted ("foo #bar" is "foo" and a + # comment) must reach the operator as declared, or the drop job, which + # compares against the raw keys, drops the user it sees as undeclared. + - it: declares a user to the operator under the name the drop job keeps + template: templates/mongodb.yaml + documentSelector: + path: kind + value: PerconaServerMongoDB + set: + users: + "foo #bar": {} + databases: + app: + roles: + admin: [web, "foo #bar"] + asserts: + - equal: + path: spec.users[0].name + value: "foo #bar" + + - it: keeps the declared name that the operator gets + template: templates/hooks/drop-users-job.yaml + set: + users: + "foo #bar": {} + databases: + app: + roles: + admin: [web, "foo #bar"] + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: DECLARED_USERS + value: '["foo #bar","web"]' + + - it: drops only marked, undeclared, non-system users in admin + template: templates/hooks/drop-users-job.yaml + asserts: + - matchRegex: + path: spec.template.spec.containers[0].env[?(@.name == "DROP_JS")].value + pattern: 'u\.db !== "admin" \|\| !marked \|\| declared\.has\(u\.user\) \|\| system\.has\(u\.user\)\) continue' + + - it: declares an empty list when every user is removed + template: templates/hooks/drop-users-job.yaml + set: + # null rather than {}: the suite's users would be merged into an empty map. + users: null + databases: null + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: DECLARED_USERS + value: "[]" + + - it: connects through mongos on a sharded cluster + template: templates/hooks/drop-users-job.yaml + set: + sharding: true + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: MONGO_URI + value: mongodb://test-mongodb-mongos.tenant-test.svc.cozy.local:27017/admin + + - it: is skipped while restoring from a backup + template: templates/hooks/drop-users-job.yaml + set: + bootstrap: + enabled: true + backupName: b1 + asserts: + - hasDocuments: + count: 0 diff --git a/packages/apps/mongodb/tests/mongodb_test.yaml b/packages/apps/mongodb/tests/mongodb_test.yaml index 6b48a0a5c..3a66ae43a 100644 --- a/packages/apps/mongodb/tests/mongodb_test.yaml +++ b/packages/apps/mongodb/tests/mongodb_test.yaml @@ -582,7 +582,7 @@ tests: documentIndex: 0 - equal: path: spec.users[0].passwordSecretRef.name - value: test-mongodb-user-appuser + value: test-mongodb.appuser.account documentIndex: 0 - equal: path: spec.users[0].passwordSecretRef.key diff --git a/packages/apps/mongodb/tests/no_tenant_password_test.yaml b/packages/apps/mongodb/tests/no_tenant_password_test.yaml new file mode 100644 index 000000000..5ecb61543 --- /dev/null +++ b/packages/apps/mongodb/tests/no_tenant_password_test.yaml @@ -0,0 +1,58 @@ +suite: no tenant password is rendered and the platform Secret is hidden + +# Tenant passwords come from mints only. A value left under users..password +# must not reach any rendered object, and no per-user Secret is rendered. + +templates: + - templates/accounts.yaml + - templates/credentials.yaml + - templates/mongodb.yaml + +release: + name: test-mongodb + namespace: tenant-test + +set: + _cluster: + cluster-domain: cozy.local + users: + web: + password: leftover-from-values + databases: + app: + roles: + admin: + - web + +tests: + - it: renders no per-user Secret + template: templates/credentials.yaml + asserts: + - hasDocuments: + count: 2 + - containsDocument: + apiVersion: v1 + kind: Secret + name: test-mongodb-user-web + not: true + + - it: keeps the leftover password out of the platform Secrets + template: templates/credentials.yaml + asserts: + - notMatchRegex: + path: stringData.password + pattern: leftover + documentSelector: + path: metadata.name + value: test-mongodb-credentials + + - it: renders the databaseAdmin copy as not tenant-visible + template: templates/credentials.yaml + documentSelector: + path: metadata.name + value: test-mongodb-credentials + asserts: + - equal: + path: metadata.labels + value: + internal.cozystack.io/tenantresource: "false" diff --git a/packages/apps/mongodb/tests/user-secrets_test.yaml b/packages/apps/mongodb/tests/user-secrets_test.yaml deleted file mode 100644 index 6d9fb3889..000000000 --- a/packages/apps/mongodb/tests/user-secrets_test.yaml +++ /dev/null @@ -1,78 +0,0 @@ -suite: user secrets tests - -templates: - - templates/user-secrets.yaml - -tests: - # No users configured - - it: does not render when no users defined - release: - name: test-mongodb - namespace: tenant-test - set: - users: {} - asserts: - - hasDocuments: - count: 0 - - # Single user - - it: creates secret for single user - release: - name: test-mongodb - namespace: tenant-test - set: - users: - myuser: {} - asserts: - - hasDocuments: - count: 1 - - isKind: - of: Secret - - equal: - path: metadata.name - value: test-mongodb-user-myuser - - equal: - path: type - value: Opaque - - exists: - path: stringData.password - - # Multiple users - - it: creates separate secrets for multiple users - release: - name: test-mongodb - namespace: tenant-test - set: - users: - user1: {} - user2: {} - asserts: - - hasDocuments: - count: 2 - - # User with explicit password - - it: uses explicit password when provided - release: - name: test-mongodb - namespace: tenant-test - set: - users: - myuser: - password: "mysecretpassword" - asserts: - - equal: - path: stringData.password - value: "mysecretpassword" - - # Secret naming convention - - it: follows naming convention release-user-username - release: - name: prod-db - namespace: tenant-prod - set: - users: - admin: {} - asserts: - - equal: - path: metadata.name - value: prod-db-user-admin diff --git a/packages/apps/mongodb/values.schema.json b/packages/apps/mongodb/values.schema.json index bb9e4c7f8..a8f698fe7 100644 --- a/packages/apps/mongodb/values.schema.json +++ b/packages/apps/mongodb/values.schema.json @@ -221,17 +221,11 @@ } }, "users": { - "description": "Users configuration map.", + "description": "Users configuration map. Each user is a MongoDB user the operator manages from an account Secret the platform keeps. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. A `password` key here is ignored. The names of the MongoDB system users (`backup`, `clusterAdmin`, `clusterMonitor`, `databaseAdmin`, `userAdmin`) are refused.", "type": "object", "default": {}, "additionalProperties": { - "type": "object", - "properties": { - "password": { - "description": "Password for the user (auto-generated if omitted).", - "type": "string" - } - } + "type": "object" } }, "databases": { diff --git a/packages/apps/mongodb/values.yaml b/packages/apps/mongodb/values.yaml index 7161074a8..956831ac9 100644 --- a/packages/apps/mongodb/values.yaml +++ b/packages/apps/mongodb/values.yaml @@ -116,15 +116,13 @@ shardingConfig: ## @section Users configuration ## -## @typedef {struct} User - User configuration. -## @field {string} [password] - Password for the user (auto-generated if omitted). +## @typedef {struct} User - User configuration. Users have no settings of their own; their roles come from `databases`. -## @param {map[string]User} users - Users configuration map. +## @param {map[string]User} users - Users configuration map. Each user is a MongoDB user the operator manages from an account Secret the platform keeps. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. A `password` key here is ignored. The names of the MongoDB system users (`backup`, `clusterAdmin`, `clusterMonitor`, `databaseAdmin`, `userAdmin`) are refused. users: {} ## Example: ## users: -## user1: -## password: strongpassword +## user1: {} ## user2: {} ## diff --git a/packages/system/mongodb-rd/cozyrds/mongodb.yaml b/packages/system/mongodb-rd/cozyrds/mongodb.yaml index 83cce41dd..4c4da37e7 100644 --- a/packages/system/mongodb-rd/cozyrds/mongodb.yaml +++ b/packages/system/mongodb-rd/cozyrds/mongodb.yaml @@ -8,7 +8,7 @@ spec: singular: mongodb plural: mongodbs openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user (auto-generated if omitted).","type":"string"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint).","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\"). Ignored when useSystemBucket is true (no engine-side retention on that flow).","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan).","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see https://cozystack.io/docs/v1/operations/services/backup-classes/). Requires `backup.enabled: true` (the pbm agents run on that flag); the chart refuses the combination with `enabled: false` at render time; the schema carries the same rule as a marker for the UI and for the day the apiserver enforces CEL on application schemas (cozystack/cozystack#2657), which it does not yet. A release that has not yet rendered this flag (its cluster still carries the chart's scheduled tasks and PITR) holds a BackupJob until it does, so the tenant's own storage is never injected over.","type":"boolean","default":false}},"x-kubernetes-validations":[{"message":"backup.useSystemBucket requires backup.enabled: the percona-backup-mongodb agents only run when backups are enabled","rule":"!(has(self.useSystemBucket) && self.useSystemBucket) || (has(self.enabled) && self.enabled)"}]},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map. Each user is a MongoDB user the operator manages from an account Secret the platform keeps. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. A `password` key here is ignored. The names of the MongoDB system users (`backup`, `clusterAdmin`, `clusterMonitor`, `databaseAdmin`, `userAdmin`) are refused.","type":"object","default":{},"additionalProperties":{"type":"object"}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint).","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\"). Ignored when useSystemBucket is true (no engine-side retention on that flow).","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan).","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see https://cozystack.io/docs/v1/operations/services/backup-classes/). Requires `backup.enabled: true` (the pbm agents run on that flag); the chart refuses the combination with `enabled: false` at render time; the schema carries the same rule as a marker for the UI and for the day the apiserver enforces CEL on application schemas (cozystack/cozystack#2657), which it does not yet. A release that has not yet rendered this flag (its cluster still carries the chart's scheduled tasks and PITR) holds a BackupJob until it does, so the tenant's own storage is never injected over.","type":"boolean","default":false}},"x-kubernetes-validations":[{"message":"backup.useSystemBucket requires backup.enabled: the percona-backup-mongodb agents only run when backups are enabled","rule":"!(has(self.useSystemBucket) && self.useSystemBucket) || (has(self.enabled) && self.enabled)"}]},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}} release: prefix: mongodb- labels: @@ -34,10 +34,9 @@ spec: # # Bounded by the enumeration, not absolute — matching is by exact name with # no globs, so a Secret a future operator version introduces stays in scope - # of the label-only include. The per-user Secrets carry the username in - # their name and cannot be enumerated at all; they and the backup - # credentials hold tenant-supplied values, so surfacing one back to its own - # tenant crosses no privilege boundary. + # of the label-only include. The account Secrets of tenant users carry the + # username in their name and cannot be enumerated; nothing selects them, + # since passwords reach tenants only through a mint on the Credential. exclude: - resourceNames: - mongodb-{{ .name }}-ca-cert @@ -58,9 +57,11 @@ spec: # enumerates the bare name alongside the -users one. - internal-mongodb-{{ .name }} - internal-mongodb-{{ .name }}-users - include: - - resourceNames: + # The databaseAdmin platform account. The chart renders it with + # internal.cozystack.io/tenantresource "false"; listing it here keeps + # it hidden should a label selector below ever match it. - mongodb-{{ .name }}-credentials + include: # The key-free trust anchor the CA-extraction controller publishes. This # is the single, engine-agnostic selector every converged engine shares; # it carries no per-release name templating. diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index 612c100ba..9afac7902 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -2368,6 +2368,7 @@ var removedUserPasswordKinds = map[string]string{ postgresKind: mintedPasswordWarning, mariadbKind: mintedPasswordWarning, clickhouseKind: mintedPasswordWarning, + mongodbKind: mintedPasswordWarning, } // mintedPasswordWarning is the warning of a kind whose user passwords the @@ -2377,6 +2378,7 @@ const mintedPasswordWarning = "spec.users[%q].password is ignored: passwords are const ( clickhouseKind = "ClickHouse" + mongodbKind = "MongoDB" postgresKind = "Postgres" mariadbKind = "MariaDB" ) diff --git a/pkg/registry/apps/application/rest_serversideapply_test.go b/pkg/registry/apps/application/rest_serversideapply_test.go index 798e7bafe..427241271 100644 --- a/pkg/registry/apps/application/rest_serversideapply_test.go +++ b/pkg/registry/apps/application/rest_serversideapply_test.go @@ -53,7 +53,7 @@ func TestConvertApplicationToHelmRelease_ServerSideApplyOverride(t *testing.T) { cases := []struct { name string ssa *bool - wantInstall *bool // Install.ServerSideApply + wantInstall *bool // Install.ServerSideApply wantUpgrade helmv2.ServerSideApplyMode // Upgrade.ServerSideApply }{ { diff --git a/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go b/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go index 8ea31055b..399c4816a 100644 --- a/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go +++ b/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go @@ -164,6 +164,7 @@ func TestWarnRemovedUserPasswords(t *testing.T) { }{ {"postgres warns", postgresKind, rawWithPassword, true}, {"mariadb warns", mariadbKind, rawWithPassword, true}, + {"mongodb warns", mongodbKind, rawWithPassword, true}, {"clickhouse warns", clickhouseKind, rawWithPassword, true}, {"other kind stays quiet", "Redis", rawWithPassword, false}, {"no password stays quiet", postgresKind, `{"users":{"app":{}}}`, false}, @@ -196,7 +197,7 @@ func TestWarnRemovedUserPasswords(t *testing.T) { // mint on the user's Credential: its -credentials Secret holds no user // password a tenant can read, so naming it sends the reader to a dead end. func TestWarnRemovedUserPasswords_PointsAtMint(t *testing.T) { - for _, kind := range []string{postgresKind, clickhouseKind, mariadbKind} { + for _, kind := range []string{postgresKind, clickhouseKind, mariadbKind, mongodbKind} { t.Run(kind, func(t *testing.T) { r := &REST{kindName: kind} app := &appsv1alpha1.Application{Spec: &apiextv1.JSON{Raw: []byte(`{"users":{"app":{"password":"hackme"}}}`)}}