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.<name>.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. <release>-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 <kvapss@gmail.com>
This commit is contained in:
Andrei Kvapil committed 2026-12-01 14:30:33 +01:00
1 parent e6a7973185
commit 0eb96ac872
22 files changed
+720 -145

No files matched your search

+1 -3
View File
@@ -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"
+11 -12
View File
@@ -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" {
# <release>-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
}
+14 -6
View File
@@ -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:
+3 -4
View File
@@ -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
@@ -0,0 +1,53 @@
{{/*
Account Secret naming, which must match pkg/credentials/account.MapName: the
API writes <release>.<account>.account, where <account> 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 <release>-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 -}}
@@ -0,0 +1,23 @@
{{- /*
One CredentialTemplate per user: the account the Cozystack credentials API
mints and revokes through. cozystack-controller keeps its account Secret,
<release>.<account>.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 }}
@@ -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 }}
@@ -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 }}
+23 -2
View File
@@ -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
@@ -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 }}
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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.<name>.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"
@@ -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
+2 -8
View File
@@ -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": {
+3 -5
View File
@@ -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: {}
##
+8 -7
View File
@@ -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 Line truncated
{"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 whLine truncated
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.
+2
View File
@@ -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"
)
@@ -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
}{
{
@@ -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 <release>-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"}}}`)}}