feat(mariadb)!: issue user passwords through the credentials API

Tenant passwords lived in <release>-credentials next to root, which
every use-tier member and every ancestor tenant could read, and which
had no platform path to rotation. The chart now renders a
CredentialTemplate per user and points each User at its account
Secret through passwordHashSecretKeyRef, so the database stores only
the mysql_native_password hash the API writes, and the watch label
makes mariadb-operator apply a mint at once.

The reference is there from a User's first reconcile, because a User
created without one is locked for good; with the Secret missing the
operator only reports the User not ready. root stays chart-generated in
<release>-credentials, since rootPasswordSecretKeyRef cannot change once
set, and that Secret is now platform-only: the definition excludes it
and the chart labels it tenantresource=false. Users mapping to one
account name are refused on every path. A users.<name>.password left in
values draws an admission warning that points at a mint on the user's
Credential instead of <release>-credentials.

BREAKING CHANGE: tenants can no longer read MariaDB passwords from
<release>-credentials; a password is obtained by a mint on the
account's Credential and is shown once.

Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
This commit is contained in:
Andrei Kvapil committed 2026-12-01 14:30:32 +01:00
1 parent 170a25617c
commit 6c047a473d
20 files changed
+516 -218

No files matched your search

+1 -1
View File
@@ -42,7 +42,7 @@ type ConfigSpec struct {
// MariaDB major.minor version to deploy
// +kubebuilder:default:="v11.8"
Version Version `json:"version"`
// Users configuration map. Passwords (including the `root` account) are always auto-generated and stored in the `<release>-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret.
// Users configuration map. Each user is a MariaDB account 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 stores only its `mysql_native_password` hash, and a revoke retires the password without issuing one. A `password` key here is ignored and draws an admission warning. A password set inside MariaDB is reverted by the operator. `root` is the platform's own account: a `root` entry here is ignored, and its password is not readable by tenants.
// +kubebuilder:default:={}
Users map[string]User `json:"users,omitempty"`
// Databases configuration map.
+51 -8
View File
@@ -32,8 +32,7 @@ export BACKUPJOB_NAME="${BACKUPJOB_NAME:-mariadb-src-adhoc}"
export RESTOREJOB_TOCOPY_NAME="${RESTOREJOB_TOCOPY_NAME:-mariadb-src-to-mariadb-target}"
export PLAN_NAME="${PLAN_NAME:-mariadb-src-daily}"
# App user the demo writes and reads the sentinel row as. Its password is
# chart-generated (the charts no longer accept a plaintext password) and read
# from the release's <cr>-credentials Secret by mysql_exec at call time.
# minted through the credentials API by mysql_exec on first use.
export MARIADB_APP_USER="${MARIADB_APP_USER:-app}"
# S3 endpoint CA. cozystack's default seaweedfs serves its S3 endpoint with a
@@ -74,6 +73,31 @@ mariadb_primary_pod() {
-o jsonpath='{.status.currentPrimary}' 2>/dev/null
}
# Password of the application user, minted once through the credentials API
# and cached for the rest of the run: a mint replaces the account's password,
# so minting on every call would invalidate the previous one. The Credential is
# named <release>.<account>, where <account> is the user name lowercased with
# every character outside [a-z0-9-] replaced by "-", and the MariaDB CR is
# named after the release. The cache is a private run-scoped directory
# (mktemp -d is 0700), so a later run does not read a password a mint has
# since replaced, and no other user on the host can read it.
# Args: <cr-name> <user>
export COZY_PW_CACHE_DIR="${COZY_PW_CACHE_DIR:-$(mktemp -d "${TMPDIR:-/tmp}/cozy-pw.XXXXXXXX")}"
app_password() {
local cr="$1" user="$2"
local acct cache
acct=$(printf '%s' "$user" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9-]/-/g')
cache="${COZY_PW_CACHE_DIR}/${cr}-${acct}"
if [[ ! -s "$cache" ]]; then
kubectl create --raw "/apis/core.cozystack.io/v1alpha1/namespaces/${NAMESPACE}/credentials/${cr}.${acct}/mint" \
-f <(printf '{"apiVersion":"core.cozystack.io/v1alpha1","kind":"CredentialRequest"}') \
| jq -r '.status.password // empty' > "$cache"
fi
[[ -s "$cache" ]] || { log_error "no password minted for user '${user}' of ${cr}"; return 1; }
cat "$cache"
}
# Run a single SQL statement against a MariaDB CR's primary as the app user,
# routing through the operator-managed primary Service (mariadb-<app>-primary).
# Args: <cr-name> <sql>
@@ -82,15 +106,34 @@ mysql_exec() {
local pod pass
pod=$(mariadb_primary_pod "$cr")
[[ -n "$pod" ]] || { log_error "no primary pod for MariaDB CR '$cr'"; return 1; }
pass=$(kubectl -n "$NAMESPACE" get secret "${cr}-credentials" -o json \
| jq -r --arg u "$MARIADB_APP_USER" '.data[$u] // empty' | base64 -d)
[[ -n "$pass" ]] || { log_error "no password for '$MARIADB_APP_USER' in ${cr}-credentials"; return 1; }
kubectl -n "$NAMESPACE" exec "$pod" -c mariadb -- \
mariadb -u"$MARIADB_APP_USER" -p"$pass" -h "${cr}-primary" -e "$sql"
pass=$(app_password "$cr" "$MARIADB_APP_USER") || return 1
# The password goes to the client on stdin: exec arguments travel in the
# request URI, which the audit log records at any level.
printf '%s\n' "$pass" | kubectl -n "$NAMESPACE" exec -i "$pod" -c mariadb -- \
sh -c 'IFS= read -r MYSQL_PWD; export MYSQL_PWD; exec mariadb "$@"' sh \
-u"$MARIADB_APP_USER" -h "${cr}-primary" -e "$sql"
}
# Block until the app user authenticates against a CR, or fail after
# <timeout>s. The first mint rewrites the account Secret and mariadb-operator
# applies it through the Secret's watch label, asynchronously, so this is a
# readiness wait on an eventually consistent property, not a retry over a
# deterministic step. Args: <cr-name> [timeout]
wait_app_login() {
local cr="$1" timeout="${2:-120}" elapsed=0
until mysql_exec "$cr" "SELECT 1;" >/dev/null 2>&1; do
if [[ $elapsed -ge $timeout ]]; then
log_error "Timeout waiting for '${MARIADB_APP_USER}' to authenticate against ${cr}: the minted password never reached the account (is the User Ready?)"
return 1
fi
sleep 5
elapsed=$((elapsed + 5))
done
}
# Authenticate as root against a MariaDB CR's primary over TCP, using the
# chart-generated root password in <cr>-credentials. root is the sharp edge on a
# chart-generated root password in <cr>-credentials, a platform-only Secret
# that only a platform administrator can read. root is the sharp edge on a
# restore into a copy: the operator only applies rootPasswordSecretKeyRef at
# datadir bootstrap, so if a restore overwrote the grant table with the source's
# root hash the target's advertised root would be wrong for good. Args: <cr-name>
+2
View File
@@ -146,6 +146,7 @@ wait_hr_ready "mariadb-${MARIADB_SRC_NAME}" 660
wait_for_field mariadbs.k8s.mariadb.com "$MARIADB_SRC_CR" \
'{.status.conditions[?(@.type=="Ready")].status}' True "$NAMESPACE" 600
wait_app_grant_ready "$MARIADB_SRC_CR"
wait_app_login "$MARIADB_SRC_CR"
print_header "Step 05c: Write a sentinel row so the backup has something to prove"
SENTINEL_TOKEN="e2e-$(date +%s)-$$"
@@ -202,6 +203,7 @@ wait_for_field restorejobs.backups.cozystack.io "$RESTOREJOB_TOCOPY_NAME" \
# in the dump — it comes from the target chart. Wait for its grant before the
# read below so the SELECT authenticates.
wait_app_grant_ready "$MARIADB_TARGET_CR"
wait_app_login "$MARIADB_TARGET_CR"
print_header "Step 40 verify: the sentinel round-tripped through S3 into the copy"
GOT=$(mysql_exec "$MARIADB_TARGET_CR" "SELECT token FROM demo.e2e_sentinel WHERE id = 1;" \
+8 -6
View File
@@ -61,12 +61,14 @@ CHART="$REPO_ROOT/packages/system/mariadb-rd"
NORMALIZE='{exclude: (.exclude // [] | sort), include: (.include // [] | sort)}'
# The complete tenant-visible Secret surface: the credentials Secret by name,
# the trust anchor by label, every key-bearing and credential Secret withheld
# by name. mariadb-<name>.ca-tls holds the CA private key and mariadb-<name>.tls
# The complete tenant-visible Secret surface: the trust anchor by label, and
# nothing by name. Every key-bearing and credential Secret is withheld by name,
# <release>-credentials among them: it holds only root, the platform's own
# account, and tenant users are Credentials whose account Secrets no definition
# selects. mariadb-<name>.ca-tls holds the CA private key and mariadb-<name>.tls
# the server key; the operator's own -ca, -server-cert and -client-cert hold
# keys too. None of them may reach a tenant, by name or by a label they carry.
EXPECTED_SECRETS='{"exclude":[{"resourceNames":["mariadb-{{ .name }}.ca-tls","mariadb-{{ .name }}.tls","mariadb-{{ .name }}-ca","mariadb-{{ .name }}-server-cert","mariadb-{{ .name }}-client-cert","mariadb-{{ .name }}-root","mariadb-{{ .name }}-password","mariadb-{{ .name }}-repl-password","mariadb-{{ .name }}-metrics-password","mariadb-{{ .name }}-metrics-config","mariadb-{{ .name }}-backup","mariadb-{{ .name }}-regsecret"]}],"include":[{"matchLabels":{"internal.cozystack.io/tenant-ca":"true"}},{"resourceNames":["mariadb-{{ .name }}-credentials"]}]}'
EXPECTED_SECRETS='{"exclude":[{"resourceNames":["mariadb-{{ .name }}.ca-tls","mariadb-{{ .name }}.tls","mariadb-{{ .name }}-ca","mariadb-{{ .name }}-server-cert","mariadb-{{ .name }}-client-cert","mariadb-{{ .name }}-credentials","mariadb-{{ .name }}-root","mariadb-{{ .name }}-password","mariadb-{{ .name }}-repl-password","mariadb-{{ .name }}-metrics-password","mariadb-{{ .name }}-metrics-config","mariadb-{{ .name }}-backup","mariadb-{{ .name }}-regsecret"]}],"include":[{"matchLabels":{"internal.cozystack.io/tenant-ca":"true"}}]}'
# The Services an instance exposes, pinned for the same reason: a catch-all
# selector reaches this list too, and nothing else in the tree holds it.
@@ -133,7 +135,7 @@ EXPECTED_SERVICES='{"exclude":[],"include":[{"resourceNames":["mariadb-{{ .name
# cert-manager for are joined with a dot, everything else with a hyphen, so
# a loop that supplied the hyphen itself would look for names nothing renders.
for n in .ca-tls .tls -ca -server-cert -client-cert \
-root -password -repl-password -metrics-password -metrics-config \
-credentials -root -password -repl-password -metrics-password -metrics-config \
-backup -regsecret; do
hits=$(printf '%s\n' "$rendered" | yq eval-all \
"[.. | select(has(\"secrets\")) | .secrets.exclude[].resourceNames[]? | select(. == \"mariadb-{{ .name }}$n\")] | length" \
@@ -150,7 +152,7 @@ EXPECTED_SERVICES='{"exclude":[],"include":[{"resourceNames":["mariadb-{{ .name
# Whole-structure comparison. Anything added to the tenant's Secret surface --
# by name, by label, or by an unrestricted entry -- changes this string, and so
# does anything removed from the backstop.
@test "mariadb-rd grants exactly the credentials Secret and the trust anchor" {
@test "mariadb-rd grants exactly the trust anchor" {
rendered=$(helm template mariadb-rd "$CHART") || return 1
if [ -z "$rendered" ]; then
+113 -4
View File
@@ -128,6 +128,114 @@ spec:
status:
replicas: 1
# No second disclosure: the minted password logs in over TCP as the user,
# the Credential records the mint, no read path the design names carries
# the password (the audit log aside, which the sandbox does not collect),
# root's Secret is out of the tenant's reach, and a second mint replaces
# the first once mariadb-operator applies it.
- name: verify-minted-credential
try:
- assert:
timeout: 2m
resource:
apiVersion: core.cozystack.io/v1alpha1
kind: Credential
metadata:
name: mariadb-test.testuser
spec:
application:
kind: MariaDB
name: test
user: testuser
status:
password:
origin: NotIssued
# bash for pipefail and process substitution; the sandbox's /bin/sh is dash.
- script:
timeout: 5m
shell: bash
content: |
set -euo pipefail
cred=mariadb-test.testuser
as="--as=e2e-mariadb-probe --as-group=system:authenticated --as-group=${NAMESPACE}-super-admin"
mint() {
kubectl create --raw "/apis/core.cozystack.io/v1alpha1/namespaces/$NAMESPACE/credentials/$cred/mint" \
-f <(printf '{"apiVersion":"core.cozystack.io/v1alpha1","kind":"CredentialRequest"}') \
| jq -r '.status.password'
}
# The password goes to the client on stdin: exec arguments travel in
# the request URI, which the audit log records at any level.
login() {
printf '%s\n' "$1" | kubectl -n "$NAMESPACE" exec -i mariadb-test-0 -c mariadb -- \
sh -c 'IFS= read -r MYSQL_PWD; export MYSQL_PWD; exec mariadb "$@"' sh \
-h mariadb-test -u testuser -D testdb -N -e 'SELECT 1' 2>/dev/null | tr -d '[:space:]' || true
}
# Fails when any of the named texts carries the password.
refuse() {
local what=$1 text=$2
if printf '%s' "$text" | grep -qF -- "$first"; then
echo "$what carries the minted password" >&2
exit 1
fi
}
first=$(mint)
[ "${#first}" -eq 32 ] || { echo "minted password has ${#first} characters, want 32" >&2; exit 1; }
# mariadb-operator applies the changed account Secret live through
# the watch label; a readiness wait on that eventually consistent
# property, not a retry.
until [ "$(login "$first")" = "1" ]; do sleep 5; done
view=$(kubectl -n "$NAMESPACE" get credentials.core.cozystack.io "$cred" -o json)
[ "$(printf '%s' "$view" | jq -r .status.password.origin)" = "Minted" ] || { echo "origin is not Minted: $view" >&2; exit 1; }
[ "$(printf '%s' "$view" | jq -r '.status.history[0].operation')" = "Mint" ] || { echo "history lacks the mint: $view" >&2; exit 1; }
refuse "the Credential" "$view"
# The account Secret holds the mysql_native_password hash, never the
# password.
stored=$(kubectl -n "$NAMESPACE" get secret "$cred.account" -o json | jq -r '.data.password' | base64 -d)
if ! printf '%s' "$stored" | grep -Eqx '\*[0-9A-F]{40}'; then
echo "the account Secret does not hold a mysql_native_password hash" >&2; exit 1
fi
refuse "the account Secret" "$stored"
# Capture each read in an assignment first: under set -e a failing
# command substitution in an argument does not stop the script.
events=$(kubectl -n "$NAMESPACE" get events -o json)
refuse "an Event" "$events"
application=$(kubectl -n "$NAMESPACE" get mariadbs.apps.cozystack.io test -o json)
refuse "the application" "$application"
rels=$(kubectl -n "$NAMESPACE" get secret -l owner=helm,name=mariadb-test -o name)
[ -n "$rels" ] || { echo "no Helm release Secret for mariadb-test to inspect" >&2; exit 1; }
for rel in $rels; do
decoded=$(kubectl -n "$NAMESPACE" get "$rel" -o jsonpath='{.data.release}' | base64 -d | base64 -d | gunzip)
refuse "Helm release $rel" "$decoded"
done
# Neither the account Secret nor root's Secret is listed through
# tenantsecrets, and neither is granted by name.
visible=$(kubectl -n "$NAMESPACE" get tenantsecrets.core.cozystack.io $as -o json)
for s in "$cred.account" mariadb-test-credentials; do
if printf '%s' "$visible" | jq -r '.items[].metadata.name' | grep -Fqx "$s"; then
echo "$s is listed through tenantsecrets" >&2; exit 1
fi
# can-i exits 1 when it answers no, so the answer is read from its
# output; anything but a plain "no" fails, an error included.
answer=$(kubectl -n "$NAMESPACE" auth can-i get "secret/$s" $as 2>&1) || true
if [ "$answer" != no ]; then
echo "the tenant super-admin group can read $s, or can-i did not answer: $answer" >&2
exit 1
fi
done
decoded_visible=$(printf '%s' "$visible" | jq -r '.items[].data // {} | .[] | @base64d')
refuse "tenantsecrets" "$decoded_visible"
second=$(mint)
[ "$second" != "$first" ] || { echo "a second mint returned the same password" >&2; exit 1; }
until [ "$(login "$second")" = "1" ]; do sleep 5; done
if [ "$(login "$first")" = "1" ]; then echo "the replaced password still logs in" >&2; exit 1; fi
check:
($error == null): true
# The trust anchor a client verifies against, read off the live operator
# rather than off this repo's beliefs about it. The unit suite pins what the
# chart renders — the sentinel, its source name and its key — from the same
@@ -148,9 +256,10 @@ spec:
# a kind that never reconciled. Without a witness that the mechanism is
# live, they would all pass while asserting nothing.
#
# The credentials Secret is the witness: the chart renders it, its lineage
# resolves to this instance, and the ApplicationDefinition grants it by
# name, so it MUST be stamped.
# The tenant-ca projection below is the witness: it must read "true",
# which only the webhook writes. <release>-credentials cannot serve: it
# holds only root, the platform's account, and the chart renders it with
# "false" itself, which this step pins.
- assert:
timeout: 2m
resource:
@@ -159,7 +268,7 @@ spec:
metadata:
name: mariadb-test-credentials
labels:
internal.cozystack.io/tenantresource: "true"
internal.cozystack.io/tenantresource: "false"
# tenant-ca is stamped by the CA-extraction controller; tenantresource is
# the LINEAGE WEBHOOK's verdict, computed from the ApplicationDefinition's
# secrets.include matchLabels. It reads "true" only if the whole chain held:
+8 -8
View File
@@ -203,14 +203,14 @@ Uninstalling the instance does this for you; only the turn-it-off-and-keep-runni
### Application-specific parameters
| Name | Description | Type | Value |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ----- |
| `users` | Users configuration map. Passwords (including the `root` account) are always auto-generated and stored in the `<release>-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret. | `map[string]object` | `{}` |
| `users[name].maxUserConnections` | Maximum number of connections. | `int` | `0` |
| `databases` | Databases configuration map. | `map[string]object` | `{}` |
| `databases[name].roles` | Roles assigned to users. | `object` | `{}` |
| `databases[name].roles.admin` | List of users with admin privileges. | `[]string` | `[]` |
| `databases[name].roles.readonly` | List of users with read-only privileges. | `[]string` | `[]` |
| Name | Description | Type | Value |
| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ----- |
| `users` | Users configuration map. Each user is a MariaDB account 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 stores only its `mysql_native_password` hash, and a revoke retires the password without issuing one. A `password` key here is ignored and draws an admission warning. A password set inside MariaDB is reverted by the operator. `root` is the platform's own account: a `root` entry here is ignored, and its password is not readable by tenants. | `map[string]object` | `{}` |
| `users[name].maxUserConnections` | Maximum number of connections. | `int` | `0` |
| `databases` | Databases configuration map. | `map[string]object` | `{}` |
| `databases[name].roles` | Roles assigned to users. | `object` | `{}` |
| `databases[name].roles.admin` | List of users with admin privileges. | `[]string` | `[]` |
| `databases[name].roles.readonly` | List of users with read-only privileges. | `[]string` | `[]` |
### Backup parameters (DEPRECATED)
@@ -0,0 +1,51 @@
{{/*
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 "-".
*/}}
{{- define "mariadb.accountName" -}}
{{- regexReplaceAll "[^a-z0-9-]" (lower .) "-" -}}
{{- end -}}
{{- define "mariadb.accountSecret" -}}
{{- $root := index . 0 -}}
{{- $user := index . 1 -}}
{{- printf "%s.%s.account" $root.Release.Name (include "mariadb.accountName" $user) -}}
{{- end -}}
{{/*
Tenant accounts: every key of users except root, which is the platform's
own account in <release>-credentials and which user.yaml has always
skipped.
*/}}
{{- define "mariadb.tenantUsers" -}}
{{- $users := dict -}}
{{- range $user, $u := .Values.users -}}
{{- if ne $user "root" -}}
{{- $_ := set $users $user $u -}}
{{- end -}}
{{- end -}}
{{- toJson $users -}}
{{- end -}}
{{/*
Two users that map to one account would make both User resources read the
same account Secret, so a mint for one would change the other's password.
The API refuses such a pair; this covers a HelmRelease written around it.
Unlike the "_"/"-" User-name collision in secret.yaml, it fails on upgrade
too: a release carrying such a pair keeps its previous revision, and the
conversion leaves it out until one user is renamed.
*/}}
{{- define "mariadb.accountsGuard" -}}
{{- $seen := dict -}}
{{- range $user, $_ := (include "mariadb.tenantUsers" $ | fromJson) -}}
{{- $mapped := include "mariadb.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 -}}
{{- end -}}
{{- end -}}
@@ -0,0 +1,25 @@
{{- /*
One CredentialTemplate per tenant user: the account the Cozystack
credentials API mints and revokes through. cozystack-controller keeps its
account Secret, <release>.<account>.account, holding the user name and the
mysql_native_password hash; the User in user.yaml reads the hash through
passwordHashSecretKeyRef, and the k8s.mariadb.com/watch label makes
mariadb-operator re-run ALTER USER as soon as a mint rewrites the Secret.
The chart renders no tenant password. root is a platform account and gets
no template.
*/ -}}
{{- include "mariadb.accountsGuard" $ }}
{{- range $user, $_ := (include "mariadb.tenantUsers" $ | fromJson) }}
---
apiVersion: cozystack.io/v1alpha1
kind: CredentialTemplate
metadata:
name: {{ printf "%s.%s" $.Release.Name (include "mariadb.accountName" $user) | quote }}
spec:
username: {{ $user | quote }}
format:
name: mysql-native
secret:
labels:
k8s.mariadb.com/watch: ""
{{- end }}
+37 -68
View File
@@ -1,19 +1,18 @@
{{- $existingSecret := lookup "v1" "Secret" .Release.Namespace (printf "%s-credentials" .Release.Name) }}
{{- $passwords := dict }}
{{- $existingRoot := "" }}
{{- with (index $existingSecret "data") }}
{{- range $k, $v := . }}
{{- $_ := set $passwords $k (b64dec $v) }}
{{- with .root }}
{{- $existingRoot = b64dec . }}
{{- end }}
{{- end }}
{{/*
Reject a username outside the Secret-key charset before it becomes a Secret
data key, the spec.name of a mariadb-operator User CR and (with "_" mapped to
"-") that User's metadata.name. The apiserver would reject such a name later
as an invalid Secret key or resource name, but only once Flux applies the
render, as an opaque error; failing here names the offending username. The
check mirrors k8s IsConfigMapKey (the charset plus its rejection of ".", of any
Reject a username outside the safe charset before it becomes the spec.name
of a mariadb-operator User CR and (with "_" mapped to "-") that User's
metadata.name. The apiserver would reject such a name later as an invalid
resource name, but only once Flux applies the render, as an opaque error;
failing here names the offending username. The check mirrors k8s
IsConfigMapKey (the charset plus its rejection of ".", of any
name starting with ".."). The length cap is 80 because the mariadb-operator
User CRD caps spec.name at 80 (the server itself allows 128): the apiserver
rejects a longer User at apply, so capping here names it at render instead. So
@@ -23,7 +22,7 @@
*/}}
{{- range $user, $u := .Values.users }}
{{- if or (not (regexMatch "^[-._a-zA-Z0-9]+$" $user)) (eq $user ".") (hasPrefix ".." $user) (gt (len $user) 80) }}
{{- fail (printf "invalid username %q: a username may contain only letters, digits and the characters -._ , must not be \".\" or start with \"..\", and must be at most 80 characters (the mariadb-operator User resource caps its name at 80, and the name also becomes a Kubernetes Secret key)" $user) }}
{{- fail (printf "invalid username %q: a username may contain only letters, digits and the characters -._ , must not be \".\" or start with \"..\", and must be at most 80 characters (the mariadb-operator User resource caps its name at 80)" $user) }}
{{- end }}
{{- end }}
@@ -31,8 +30,8 @@
The username also names the User CR: user.yaml renders
{{ .Release.Name }}-{{ replace "_" "-" $name }} as metadata.name, and Kubernetes
requires that to be a DNS-1123 subdomain (lowercase, alnum start/end) — a
stricter charset than the Secret key above, which permits uppercase and a
leading/trailing "-"/".". A name like "Bob", "foo-" or "foo." passes the Secret
stricter charset than the one above, which permits uppercase and a
leading/trailing "-"/".". A name like "Bob", "foo-" or "foo." passes that
charset yet renders an invalid User name that the apiserver rejects at apply with
an opaque error. Validate the rendered User name against the DNS-1123 subdomain
rule so such a username is named here instead. Checked on the full rendered name
@@ -46,60 +45,34 @@
{{- end }}
{{/*
user.yaml renders each User CR as {{ .Release.Name }}-{{ replace "_" "-" $name }},
so two usernames that differ only in "_" vs "-" (e.g. "a_b" and "a-b") collide on
one User resource name. range sorts keys, so the later one silently overwrites the
earlier User CR on apply — one user ends up with a credentials-Secret entry but no
backing mariadb-operator User (no error, no warning). Reject the collision on a
fresh install, naming both offenders, rather than create a half-configured user.
Gated to install: an existing release that already carries the pair took the
overwrite when it was first applied, so a platform-driven chart upgrade must not
wedge it into a failed reconcile it cannot clear without editing users — blocking
the upgrade would only make a running release worse, since one of the two Users is
live. The charset and DNS-1123 guards above stay on both paths because an invalid
name never applied at all.
Two usernames that differ only in "_" vs "-" (e.g. "a_b" and "a-b") would
also share one User resource name; they map to one account name as well, so
mariadb.accountsGuard (credentials.yaml) refuses the pair on every path.
*/}}
{{- $seenDNS := dict }}
{{- range $user, $u := .Values.users }}
{{- $dns := replace "_" "-" $user }}
{{- if and $.Release.IsInstall (hasKey $seenDNS $dns) }}
{{- fail (printf "usernames %q and %q both map to the User resource name %q (\"_\" renders as \"-\"); rename one of them" (index $seenDNS $dns) $user (printf "%s-%s" $.Release.Name $dns)) }}
{{- end }}
{{- $_ := set $seenDNS $dns $user }}
{{- end }}
{{/*
Distinguish a first install from an upgrade whose lookup came back empty. Every
password below (root included) is minted only when the lookup did not already
carry it, so an upgrade that finds NO credentials Secret at all -- deleted, or
the release renamed out from under it -- would silently re-mint all of them.
Helm's lookup returns empty only on a genuine NotFound, so a normal upgrade finds
the Secret and this never fires; when it does, the Secret is really gone and
re-minting would rotate every account. root is the sharp edge: mariadb-operator
writes rootPasswordSecretKeyRef only at datadir bootstrap, so a fresh root value
on an existing cluster is advertised but never applied and the real root password
is lost for good. Fail instead, and let a first install (no Secret expected)
through.
Distinguish a first install from an upgrade whose lookup came back empty.
root is minted only when the lookup did not already carry it, so an upgrade
that finds NO credentials Secret at all -- deleted, or the release renamed
out from under it -- would silently re-mint it. Helm's lookup returns empty
only on a genuine NotFound, so a normal upgrade finds the Secret and this
never fires. mariadb-operator applies rootPasswordSecretKeyRef only at
datadir bootstrap, so a fresh root value on an existing cluster is
advertised but never applied and the real root password is lost for good.
Fail instead, and let a first install (no Secret expected) through.
*/}}
{{- if and .Release.IsUpgrade (not $existingSecret) }}
{{- fail (printf "%s-credentials Secret not found while upgrading: refusing to mint fresh passwords, which would rotate every account and, because mariadb-operator applies root only at datadir bootstrap, leave the cluster advertising a root password it never set. If the Secret was deleted, restore it before upgrading (a first install does not hit this path)." .Release.Name) }}
{{- fail (printf "%s-credentials Secret not found while upgrading: refusing to mint a fresh root password, which mariadb-operator applies only at datadir bootstrap, so the cluster would advertise a root password it never set. If the Secret was deleted, restore it before upgrading (a first install does not hit this path)." .Release.Name) }}
{{- end }}
{{/* root is always chart-managed and never accepts a value-supplied password. */}}
{{- $usersWithRoot := deepCopy .Values.users }}
{{- $_ := set $usersWithRoot "root" dict }}
{{/*
Passwords (root included) are always chart-generated and preserved across
reconciles via the lookup above: a user keeps whatever password is already
stored in the Secret, and only a user without one yet gets a freshly generated
value.
root is the platform's own account: mariadb-operator logs in with it on
every SQL reconcile, and rootPasswordSecretKeyRef cannot change once set,
so it stays here, chart-generated and preserved across reconciles by the
lookup above. Tenant users have no password in this chart: each one is an
account Secret the credentials API mints into (credentials.yaml).
*/}}
{{- range $user, $u := $usersWithRoot }}
{{- if not (index $passwords $user) }}
{{- $_ := set $passwords $user (randAlphaNum 16) }}
{{- end }}
{{- end }}
{{- $rootPassword := $existingRoot | default (randAlphaNum 16) }}
---
apiVersion: v1
@@ -108,15 +81,11 @@ metadata:
name: {{ .Release.Name }}-credentials
labels:
{{- /*
mariadb-operator only re-applies a User password from its
passwordSecretKeyRef when the referenced Secret carries this label; without
it a change to this Secret (e.g. a newly added user's generated password)
reaches the server only on the operator's --requeue-sql tick (10h + up to 1h
of jitter) instead of promptly. (root is not indexed on the Secret at all -
MariaDB.spec.rootPasswordSecretKeyRef lands only at datadir bootstrap.)
Platform-only. The ApplicationDefinition no longer selects this Secret
and no Role grants it; the explicit "false" also closes the
tenantsecrets route for a Secret the lineage webhook stamped "true" at
first admission and skips since.
*/}}
k8s.mariadb.com/watch: ""
internal.cozystack.io/tenantresource: "false"
stringData:
{{- range $name, $u := $usersWithRoot }}
{{ $name | quote }}: {{ index $passwords $name | quote }}
{{- end }}
root: {{ $rootPassword | quote }}
+14 -5
View File
@@ -1,6 +1,15 @@
{{- /*
Each User reads the mysql_native_password hash from its account Secret,
which cozystack-controller keeps for the CredentialTemplate in
credentials.yaml. The hash reference is there from the first reconcile: a
User with no credential reference is created ACCOUNT LOCK PASSWORD EXPIRE
and never unlocked. While the Secret does not exist yet, mariadb-operator
fails the reconcile on the missing reference, sets the User Ready=False and
leaves the SQL account untouched.
*/ -}}
{{- range $name, $u := .Values.users }}
{{ if not (eq $name "root") }}
{{ $dnsName := replace "_" "-" $name }}
{{- if ne $name "root" }}
{{- $dnsName := replace "_" "-" $name }}
---
apiVersion: k8s.mariadb.com/v1alpha1
kind: User
@@ -10,9 +19,9 @@ spec:
name: {{ $name | quote }}
mariaDbRef:
name: {{ $.Release.Name }}
passwordSecretKeyRef:
name: {{ $.Release.Name }}-credentials
key: {{ $name | quote }}
passwordHashSecretKeyRef:
name: {{ include "mariadb.accountSecret" (list $ $name) | quote }}
key: password
maxUserConnections: {{ $u.maxUserConnections }}
{{- end }}
{{- end }}
@@ -0,0 +1,136 @@
suite: one CredentialTemplate per tenant user, naming the account Secret the User reads
# The template is the account the credentials API mints through; its name plus
# ".account" must be the Secret user.yaml's passwordHashSecretKeyRef names, or
# mariadb-operator reads a Secret nobody writes and the User stays Ready=False.
templates:
- templates/credentials.yaml
- templates/user.yaml
release:
name: mariadb-test
namespace: tenant-test
tests:
- it: renders nothing without users
asserts:
- hasDocuments:
count: 0
- it: renders a template per user, named for the account Secret's mapping
template: templates/credentials.yaml
set:
users:
web: {maxUserConnections: 10}
app.v2: {maxUserConnections: 10}
asserts:
- hasDocuments:
count: 2
- isKind:
of: CredentialTemplate
- equal:
path: apiVersion
value: cozystack.io/v1alpha1
- equal:
path: metadata.name
value: mariadb-test.app-v2
documentIndex: 0
- equal:
path: spec.username
value: app.v2
documentIndex: 0
- equal:
path: metadata.name
value: mariadb-test.web
documentIndex: 1
- it: points each User at its template's account Secret
template: templates/user.yaml
set:
users:
app.v2: {maxUserConnections: 10}
asserts:
- equal:
path: spec.passwordHashSecretKeyRef
value:
name: mariadb-test.app-v2.account
key: password
# Exactly one credential reference, from the first reconcile: the
# operator's webhook refuses two, and a User with none is created
# ACCOUNT LOCK PASSWORD EXPIRE for good.
- notExists:
path: spec.passwordSecretKeyRef
- notExists:
path: spec.passwordPlugin
- it: stores the mysql_native_password hash and asks for the watch label
template: templates/credentials.yaml
set:
users:
web: {maxUserConnections: 10}
asserts:
- equal:
path: spec.format.name
value: mysql-native
- equal:
path: spec.secret.labels
value:
k8s.mariadb.com/watch: ""
- notExists:
path: spec.valuesPath
- it: renders no template and no User for root, the platform's account
set:
users:
root: {maxUserConnections: 10}
web: {maxUserConnections: 10}
asserts:
- hasDocuments:
count: 1
template: templates/credentials.yaml
- equal:
path: spec.username
value: web
template: templates/credentials.yaml
- hasDocuments:
count: 1
template: templates/user.yaml
- equal:
path: spec.name
value: web
template: templates/user.yaml
- it: refuses two users that map to one account
template: templates/credentials.yaml
set:
users:
a.b: {maxUserConnections: 10}
a-b: {maxUserConnections: 10}
asserts:
- failedTemplate:
errorPattern: both map to the account name "a-b"
- it: refuses a user whose account name is longer than a DNS label
template: templates/credentials.yaml
set:
users:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: {maxUserConnections: 10}
asserts:
- failedTemplate:
errorPattern: at most 63 characters
# "a_b" and "a-b" also share one User resource name. The pair fails on
# upgrade as well as on install: such a release keeps its previous revision,
# and the conversion leaves it out until one user is renamed.
- it: refuses the "_"/"-" pair on upgrade too
template: templates/credentials.yaml
release:
upgrade: true
set:
users:
a_b: {maxUserConnections: 10}
a-b: {maxUserConnections: 10}
asserts:
- failedTemplate:
errorMessage: 'users "a-b" and "a_b" both map to the account name "a-b"; rename one of them'
@@ -1,14 +1,14 @@
suite: MariaDB credentials lookup-backed preservation
suite: MariaDB root password preserved across renders, tenant keys dropped
release:
name: mariadb-test
namespace: tenant-test
templates:
- templates/secret.yaml
tests:
- it: preserves existing passwords (including root) across renders
# The lookup in secret.yaml reads back the current Secret, so each user keeps
# the password already stored rather than getting a fresh one on every
# reconcile. kubernetesProvider mocks that existing Secret.
- it: preserves root and renders no key for a tenant user the old Secret held
# The lookup in secret.yaml reads back root only. A tenant key left from
# before the conversion is not rendered again; the conversion's finish Job
# removes it from the live Secret's data.
kubernetesProvider:
scheme:
"v1/Secret":
@@ -33,9 +33,8 @@ tests:
path: metadata.name
value: mariadb-test-credentials
asserts:
- equal:
path: stringData.testuser
value: existingpassword
- equal:
path: stringData.root
value: existingroot
- notExists:
path: stringData.testuser
@@ -1,10 +1,11 @@
suite: MariaDB credentials generation
suite: MariaDB credentials Secret holds only root
# Passwords (including root) are always chart-generated (no plaintext input) and
# preserved across reconciles by the lookup in secret.yaml. This suite renders
# without a kubernetesProvider, so lookup() returns nothing and every render
# generates fresh passwords; the lookup-backed preserve path is covered in
# credentials_lookup_test.yaml.
# root is the platform's own account: mariadb-operator logs in with it, and
# rootPasswordSecretKeyRef cannot change once set, so it stays chart-generated
# in <release>-credentials. Tenant users have no password in this chart; each
# is a CredentialTemplate whose account Secret the platform keeps. This suite
# renders without a kubernetesProvider, so lookup() returns nothing; the
# preserve path is covered in credentials_lookup_test.yaml.
release:
name: mariadb-test
@@ -14,44 +15,42 @@ templates:
- templates/secret.yaml
tests:
- it: always generates a root password even with no users
- it: generates a root password even with no users
asserts:
- matchRegex:
path: stringData.root
pattern: ^[a-zA-Z0-9]{16}$
- equal:
# The watch label makes mariadb-operator react to a change on this
# Secret (e.g. a newly added user's generated password) promptly rather
# than on its --requeue-sql tick.
path: metadata.labels["k8s.mariadb.com/watch"]
value: ""
- it: generates a 16-char alphanumeric password for each defined user
- it: renders no tenant user's password
set:
users:
testuser:
maxUserConnections: 1000
asserts:
- matchRegex:
- notExists:
path: stringData.testuser
pattern: ^[a-zA-Z0-9]{16}$
- matchRegex:
path: stringData.root
pattern: ^[a-zA-Z0-9]{16}$
- it: ignores a value-supplied password and generates one instead
# Pins the breaking-change contract: the schema no longer declares
# `password`, but nothing rejects a leftover key, so prove it is dropped
# rather than honoured.
- it: ignores a value-supplied password
set:
users:
testuser:
maxUserConnections: 1000
password: value-supplied-secret
asserts:
- matchRegex:
- notExists:
path: stringData.testuser
pattern: ^[a-zA-Z0-9]{16}$
- notMatchRegex:
path: stringData.testuser
path: stringData.root
pattern: value-supplied-secret
# The Secret is platform-only: the explicit "false" closes the tenantsecrets
# route for a Secret the lineage webhook stamped "true" at first admission
# and skips since, and nothing in it needs mariadb-operator's watch label,
# since no User reads it.
- it: is hidden from tenants and carries no watch label
asserts:
- equal:
path: metadata.labels["internal.cozystack.io/tenantresource"]
value: "false"
- notExists:
path: metadata.labels["k8s.mariadb.com/watch"]
@@ -1,10 +1,9 @@
suite: MariaDB User CR quotes a YAML-special username
# The credentials Secret quotes each key (secret.yaml), so a Secret key is always
# a string. The User CR must reference the same string. A username that is a bare
# YAML scalar — a number like `123`, or `true`/`false`/`no` — renders unquoted to a
# non-string, so spec.name and passwordSecretKeyRef.key diverge from the quoted
# Secret key and the operator cannot find the password. Both must be quoted.
# A username that is a bare YAML scalar — a number like `123`, or
# `true`/`false`/`no` — would render unquoted to a non-string, so spec.name
# would no longer be the account the CredentialTemplate names. It must be
# quoted.
release:
name: mariadb-test
@@ -14,8 +13,7 @@ templates:
- templates/user.yaml
tests:
- it: renders a numeric username as a string in name and passwordSecretKeyRef.key
template: templates/user.yaml
- it: renders a numeric username as a string and reads the account Secret's hash
set:
users:
"123":
@@ -25,5 +23,7 @@ tests:
path: spec.name
value: "123"
- equal:
path: spec.passwordSecretKeyRef.key
value: "123"
path: spec.passwordHashSecretKeyRef
value:
name: mariadb-test.123.account
key: password
@@ -1,9 +1,8 @@
suite: secret rejects a username outside the safe charset
# A MariaDB username becomes a Kubernetes Secret data key, the spec.name of a
# mariadb-operator User CR, and (with "_" mapped to "-") the User CR's own
# metadata.name. A name outside the Secret-key charset renders a Secret and a
# User the apiserver later rejects with an opaque error; ".", ".." and names
# A MariaDB username becomes the spec.name of a mariadb-operator User CR and
# (with "_" mapped to "-") the User CR's own metadata.name. A name outside the
# safe charset renders a User the apiserver later rejects with an opaque error; ".", ".." and names
# over 253 chars match the charset yet k8s IsConfigMapKey still rejects them.
# Postgres already guards this at render time; MariaDB must too, for parity and
# to name the offending username instead of failing opaquely at apply. There is
@@ -26,7 +25,7 @@ tests:
maxUserConnections: 10
asserts:
- failedTemplate:
errorMessage: 'invalid username "a b": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 80 characters (the mariadb-operator User resource caps its name at 80, and the name also becomes a Kubernetes Secret key)'
errorMessage: 'invalid username "a b": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 80 characters (the mariadb-operator User resource caps its name at 80)'
- it: fails the render for a username with a slash
set:
@@ -35,7 +34,7 @@ tests:
maxUserConnections: 10
asserts:
- failedTemplate:
errorMessage: 'invalid username "a/b": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 80 characters (the mariadb-operator User resource caps its name at 80, and the name also becomes a Kubernetes Secret key)'
errorMessage: 'invalid username "a/b": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 80 characters (the mariadb-operator User resource caps its name at 80)'
- it: fails the render for the reserved name "."
set:
@@ -44,7 +43,7 @@ tests:
maxUserConnections: 10
asserts:
- failedTemplate:
errorMessage: 'invalid username ".": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 80 characters (the mariadb-operator User resource caps its name at 80, and the name also becomes a Kubernetes Secret key)'
errorMessage: 'invalid username ".": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 80 characters (the mariadb-operator User resource caps its name at 80)'
- it: fails the render for the reserved name ".."
set:
@@ -53,7 +52,7 @@ tests:
maxUserConnections: 10
asserts:
- failedTemplate:
errorMessage: 'invalid username "..": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 80 characters (the mariadb-operator User resource caps its name at 80, and the name also becomes a Kubernetes Secret key)'
errorMessage: 'invalid username "..": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 80 characters (the mariadb-operator User resource caps its name at 80)'
# IsConfigMapKey rejects ANY name starting with ".." (hasChDirPrefix), not just
# the literal "..", so "..foo" is charset-legal yet cannot install.
@@ -64,7 +63,7 @@ tests:
maxUserConnections: 10
asserts:
- failedTemplate:
errorMessage: 'invalid username "..foo": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 80 characters (the mariadb-operator User resource caps its name at 80, and the name also becomes a Kubernetes Secret key)'
errorMessage: 'invalid username "..foo": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 80 characters (the mariadb-operator User resource caps its name at 80)'
# The username names a mariadb-operator User, whose CRD caps spec.name at 80, so a
# longer name is rejected by the apiserver at apply; cap it here (81 chars)
@@ -76,7 +75,7 @@ tests:
maxUserConnections: 10
asserts:
- failedTemplate:
errorMessage: 'invalid username "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 80 characters (the mariadb-operator User resource caps its name at 80, and the name also becomes a Kubernetes Secret key)'
errorMessage: 'invalid username "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 80 characters (the mariadb-operator User resource caps its name at 80)'
# The username also names the User CR (<release>-<name>, "_"->"-"), which k8s
@@ -112,68 +111,23 @@ tests:
# "a_b" and "a-b" both render the User CR name <release>-a-b ("_" -> "-"), so
# one silently overwrites the other on apply. The guard must reject the pair.
- it: fails the render when two usernames collide after the "_"->"-" mapping
set:
users:
a_b:
maxUserConnections: 10
a-b:
maxUserConnections: 10
asserts:
- failedTemplate:
errorMessage: 'usernames "a-b" and "a_b" both map to the User resource name "mdb-test-a-b" ("_" renders as "-"); rename one of them'
# "a_b" and "a-b" share one User resource name and one account name; the
# account guard refuses the pair on every path (credential_templates_test).
- it: renders normally for names using the full safe charset (root always added)
- it: renders normally for names using the full safe charset, with no tenant password
set:
users:
a-b.c_1:
maxUserConnections: 10
asserts:
- matchRegex:
path: stringData.root
pattern: ^[a-zA-Z0-9]{16}$
- notExists:
path: stringData["a-b.c_1"]
pattern: ^[a-zA-Z0-9]{16}$
# The "_"/"-" collision guard is gated to install. An existing release that
# already carries the pair took the silent overwrite when it was first applied;
# a platform-driven chart upgrade must not then wedge it into a failed reconcile
# it cannot clear without editing users. On upgrade the colliding pair renders
# instead of failing. Dropping ".Release.IsInstall" from the guard turns this
# test red (the render fails on upgrade), the mutation signal that the gate is
# load-bearing.
- it: renders on upgrade for a colliding pair the install path rejects
release:
name: mdb-test
namespace: tenant-test
upgrade: true
# A real upgrade finds the credentials Secret, so seed it: otherwise the
# upgrade-with-missing-Secret guard fires first and this would not exercise the
# collision gate at all.
kubernetesProvider:
scheme:
"v1/Secret":
gvr: {version: v1, resource: secrets}
namespaced: true
objects:
- apiVersion: v1
kind: Secret
metadata:
name: mdb-test-credentials
namespace: tenant-test
data:
root: cm9vdHNlZWRwYXNzd29yZDA=
set:
users:
a_b:
maxUserConnections: 10
a-b:
maxUserConnections: 10
asserts:
- matchRegex:
path: stringData["a-b"]
pattern: ^[a-zA-Z0-9]{16}$
# On a first install there is no credentials Secret yet, so minting fresh
# passwords is correct and the render succeeds (lookup returns nothing here).
# On a first install there is no credentials Secret yet, so minting a fresh
# root password is correct and the render succeeds (lookup returns nothing here).
- it: mints on a first install when no credentials Secret exists
set:
users:
@@ -185,8 +139,8 @@ tests:
pattern: ^[a-zA-Z0-9]{16}$
# On an upgrade the Secret must exist; a lookup that finds nothing means it was
# deleted or the release renamed, and re-minting would rotate every account (root
# unrecoverable after bootstrap), so the render fails loudly. Removing the
# deleted or the release renamed, and re-minting root would advertise a password
# the server never set (root is applied only at datadir bootstrap), so the render fails loudly. Removing the
# .Release.IsUpgrade guard lets it mint instead — the mutation signal.
- it: fails an upgrade when the credentials Secret is missing
release:
@@ -199,7 +153,7 @@ tests:
maxUserConnections: 10
asserts:
- failedTemplate:
errorMessage: 'mdb-test-credentials Secret not found while upgrading: refusing to mint fresh passwords, which would rotate every account and, because mariadb-operator applies root only at datadir bootstrap, leave the cluster advertising a root password it never set. If the Secret was deleted, restore it before upgrading (a first install does not hit this path).'
errorMessage: 'mdb-test-credentials Secret not found while upgrading: refusing to mint a fresh root password, which mariadb-operator applies only at datadir bootstrap, so the cluster would advertise a root password it never set. If the Secret was deleted, restore it before upgrading (a first install does not hit this path).'
# A charset/DNS-invalid name never applied at all, so its guard stays on the
# upgrade path too: gating it would only defer the same failure to the apiserver
+1 -1
View File
@@ -159,7 +159,7 @@
]
},
"users": {
"description": "Users configuration map. Passwords (including the `root` account) are always auto-generated and stored in the `\u003crelease\u003e-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret.",
"description": "Users configuration map. Each user is a MariaDB account 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 stores only its `mysql_native_password` hash, and a revoke retires the password without issuing one. A `password` key here is ignored and draws an admission warning. A password set inside MariaDB is reverted by the operator. `root` is the platform's own account: a `root` entry here is ignored, and its password is not readable by tenants.",
"type": "object",
"default": {},
"additionalProperties": {
+1 -1
View File
@@ -112,7 +112,7 @@ version: v11.8
## @typedef {struct} User - User configuration.
## @field {int} maxUserConnections - Maximum number of connections.
## @param {map[string]User} users - Users configuration map. Passwords (including the `root` account) are always auto-generated and stored in the `<release>-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret.
## @param {map[string]User} users - Users configuration map. Each user is a MariaDB account 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 stores only its `mysql_native_password` hash, and a revoke retires the password without issuing one. A `password` key here is ignored and draws an admission warning. A password set inside MariaDB is reverted by the operator. `root` is the platform's own account: a `root` entry here is ignored, and its password is not readable by tenants.
users: {}
## Example:
## users:
+5 -5
View File
@@ -8,7 +8,7 @@ spec:
plural: mariadbs
singular: mariadb
openAPISchema: |-
{"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MariaDB replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each MariaDB 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.nano","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},"tls":{"description":"TLS configuration. Selects who issues the certificates and whether plaintext is refused; TLS itself is always served.","type":"object","default":{},"properties":{"issuer":{"description":"Who issues the server certificate: `operator` uses the CA mariadb-operator manages itself, `cert-manager` gives the instance its own CA and is what covers the external hostname. Named for the issuer because TLS is served under both, unlike the similarly-spelled `tls.enabled` in some other charts, which does switch TLS on and off.","type":"string","default":"operator","enum":["operator","cert-manager"]},"required":{"description":"Refuse plaintext connections (sets MariaDB require_secure_transport=ON). Applies under either issuer. Opt-in: turn it on once every client connects over TLS, since it disconnects those that do not.","type":"boolean"}}},"version":{"description":"MariaDB major.minor version to deploy","type":"string","default":"v11.8","enum":["v11.8","v11.4","v10.11","v10.6"]},"users":{"description":"Users configuration map. Passwords (including the `root` account) are always auto-generated and stored in the `<release>-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret.","type":"object","default":{},"additionalProperties":{"type":"object","required":["maxUserConnections"],"properties":{"maxUserConnections":{"description":"Maximum number of connections.","type":"integer"}}}},"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.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"DEPRECATED: Backup configuration. Prefer the BackupClass / Plan flow under examples/backups/mariadb/.","type":"object","default":{},"required":["cleanupStrategy","enabled","resticPassword","s3AccessKey","s3Bucket","s3Region","s3SecretKey","schedule"],"properties":{"cleanupStrategy":{"description":"DEPRECATED: Retention strategy for cleaning up old backups.","type":"string","default":"--Line truncated
{"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MariaDB replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each MariaDB 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.nano","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},"tls":{"description":"TLS configuration. Selects who issues the certificates and whether plaintext is refused; TLS itself is always served.","type":"object","default":{},"properties":{"issuer":{"description":"Who issues the server certificate: `operator` uses the CA mariadb-operator manages itself, `cert-manager` gives the instance its own CA and is what covers the external hostname. Named for the issuer because TLS is served under both, unlike the similarly-spelled `tls.enabled` in some other charts, which does switch TLS on and off.","type":"string","default":"operator","enum":["operator","cert-manager"]},"required":{"description":"Refuse plaintext connections (sets MariaDB require_secure_transport=ON). Applies under either issuer. Opt-in: turn it on once every client connects over TLS, since it disconnects those that do not.","type":"boolean"}}},"version":{"description":"MariaDB major.minor version to deploy","type":"string","default":"v11.8","enum":["v11.8","v11.4","v10.11","v10.6"]},"users":{"description":"Users configuration map. Each user is a MariaDB account 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 stores only its `mysql_native_password` hash, and a revoke retires the password without issuing one. A `password` key here is ignored and draws an admission warning. A password set inside MariaDB is reverted by the operator. `root` is the platform's own account: a `root` entry here is ignored, and its password is not readable by tenants.","type":"object","default":{},"additionalProperties":{"type":"object","required":["maxUserConnections"],"properties":{"maxUserConnections":{"description":"Maximum number of connections.","type":"integer"}}}},"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.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"DEPRECATED: Backup configuration. Prefer the BackupClass / Plan flow under examples/backups/mariadb/.","type":"object","default":{},"required":["cleanupStrategy","enabled","resticPassword","s3AccessKey","s3Bucket","s3Region","s3SecretKey","schedule"],"properties":{"cleanupStrategy":{"description":"DEPRECATED: Retention strategy for cleaning up old backups.","type":"string","default":"--keep-last=3 --keep-daily=3 --keep-within-weekly=1m"},"enabled":{"descriLine truncated
release:
prefix: mariadb-
labels:
@@ -58,8 +58,10 @@ spec:
- mariadb-{{ .name }}-ca
- mariadb-{{ .name }}-server-cert
- mariadb-{{ .name }}-client-cert
# Database credentials. -credentials is the tenant's own and is
# included below; these are the internal ones it must not also get.
# Database credentials. -credentials holds only root, the
# platform's own account; tenant users are Credentials whose
# account Secrets no definition selects.
- mariadb-{{ .name }}-credentials
- mariadb-{{ .name }}-root
- mariadb-{{ .name }}-password
- mariadb-{{ .name }}-repl-password
@@ -74,8 +76,6 @@ spec:
# Registry pull credentials.
- mariadb-{{ .name }}-regsecret
include:
- resourceNames:
- mariadb-{{ .name }}-credentials
# The key-free trust anchor the CA-extraction controller publishes from
# the chart's TenantProjection. The selector is deliberately specific: an
# empty one compiles to match-everything, and the lineage webhook
+1 -1
View File
@@ -2366,7 +2366,7 @@ func (r *REST) warnRemovedKubernetesFields(ctx context.Context, app *appsv1alpha
// getting a silent 200, and where the password comes from now.
var removedUserPasswordKinds = map[string]string{
postgresKind: mintedPasswordWarning,
mariadbKind: "spec.users[%q].password is ignored: passwords are auto-generated into the <release>-credentials Secret and cannot be set from values. Read the current password from that Secret; editing this field has no effect.",
mariadbKind: mintedPasswordWarning,
clickhouseKind: mintedPasswordWarning,
}
@@ -196,7 +196,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} {
for _, kind := range []string{postgresKind, clickhouseKind, mariadbKind} {
t.Run(kind, func(t *testing.T) {
r := &REST{kindName: kind}
app := &appsv1alpha1.Application{Spec: &apiextv1.JSON{Raw: []byte(`{"users":{"app":{"password":"hackme"}}}`)}}