feat(mariadb)!: mint tenant passwords through the credentials API (#5379)

## What this PR does

MariaDB passwords are no longer readable from `<release>-credentials`,
which every `use` member and every parent tenant can read today. An
administrator mints a password on the user's `Credential` and sees it
once. The database stores only its `mysql_native_password` hash, and the
next mint or a revoke kills it within seconds. `root` stays the
platform's account and is hidden from tenants. This is the MariaDB part
of the user secrets API design (cozystack/community#137).

Stacked on #5378. Review only the top three commits:

- `credentials-migrate` gets `--skip-account`, so no account is written
for `users.root`, which the chart always ignored.
- The chart renders a `mysql-native` CredentialTemplate per user and
points each `User` at its account Secret through
`passwordHashSecretKeyRef`.
- Migration 66 writes the hashed account Secrets before the chart
switches. Its finish Job removes the tenant keys from
`<release>-credentials` and keeps `root`.

Tested on a three-node cluster, fresh install: a minted password logs in
after 3 s, the old one gets `Access denied` 3 s after the next mint,
revoke works, and removing a user drops the `mysql.user` row too. Full
upgrade from 1.7.1 on the same cluster, all engines at once with a
client loop each: migrations 64-71 ran in order and every account was
adopted with its old password. The MariaDB client loop had no failures.

Breaking for users: passwords can't be read any more. A user name longer
than 63 characters, one that starts or ends with a character other than
a letter or digit (such as `_backup`), or two names that map to one
account (`a.b` and `a-b`), now fail the render; such a release is not
converted. A password changed inside MariaDB is reverted by the
operator.

Open questions:

1. `root` is not rotated, although the design says it should be. The
operator reads it on every reconcile and the pods take it as
`MARIADB_ROOT_PASSWORD` for their probes, so changing it needs a
coordinated restart. So the `root` password tenants could read stays
valid. Accept that and fix the design, or rotate it before merge?
2. Not from this diff: the backup CronJob reads `root-password` from a
Secret `<release>` that doesn't exist. It needs a separate fix.

### Screenshots

No UI change.

### Downstream repositories

- [ ] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up: needed, a MariaDB note for the credentials API docs
(cozystack/website#753), an upgrade note, and `backup-classes.md` still
points at credentials in `<release>-credentials`
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up: needed, `mariadb_schema.go` tells users the password is in
`mariadb-<name>-credentials`
- [ ]
[cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack)
- follow-up:
- [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up:
- [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up:
- [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) -
follow-up:
- [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) -
follow-up:
- [ ]
[cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server)
- follow-up:
- [ ]
[cozystack/external-apps-example](https://github.com/cozystack/external-apps-example)
- follow-up:
- [ ] [cozystack/examples](https://github.com/cozystack/examples) -
follow-up:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up: needed only if `root` stays unrotated, to fix the design

### Release note

```release-note
feat(mariadb)!: MariaDB passwords are issued through the credentials API and are no longer readable from `<release>-credentials`. An administrator mints a password on the user's Credential; it is shown once and applies within seconds. `root` is no longer visible to tenants. Existing passwords keep working through the upgrade. A user name longer than 63 characters, one that starts or ends with a character other than a letter or digit (such as `_backup`), or two names that map to one account name (such as `a.b` and `a-b`), now fail the render and keep the release unconverted until renamed. Switch clients to minted passwords after the upgrade.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* MariaDB tenant accounts now use individually issued credentials.
Passwords are returned when minted, while only password hashes are
stored; credentials can be rotated or revoked through the credentials
API.
* Existing MariaDB accounts are migrated to the new credential system.
The platform-managed `root` account remains separate from tenant
accounts.
* **Bug Fixes**
* Tenant-supplied `password` values and `root` entries are ignored, with
admission warnings for supplied passwords. Password changes made
directly in MariaDB are reverted during reconciliation.
  * Tenant access to MariaDB credentials Secrets is restricted.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
Andrei Kvapil authored and GitHub committed 2026-12-02 07:18:24 -05:00
commit 69f5d07c1d
27 files changed
+1086 -227

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.
+14 -8
View File
@@ -78,6 +78,7 @@ type options struct {
accountsPath string
refuseFlags stringFlags
reservedUsers stringFlags
skipAccounts stringFlags
labels labelFlags
valuesPath string
sourceSuffix string
@@ -151,6 +152,7 @@ func run(args []string) error {
fs.StringVar(&o.accountsPath, "accounts-path", "users", "values map whose keys are the tenant accounts")
fs.Var(&o.refuseFlags, "refuse-flag", "user field that leaves a release out when it is true, because the converted chart refuses it; repeatable")
fs.Var(&o.reservedUsers, "reserved-user", "user name that leaves a release out, because the converted chart refuses it as a platform or engine account; repeatable")
fs.Var(&o.skipAccounts, "skip-account", "key of the accounts map that the converted chart renders no CredentialTemplate for, such as a platform account the chart keeps out of the tenant's map; it gets no account Secret; repeatable")
fs.Var(o.labels, "label", "label every account Secret carries, key=value; repeatable")
fs.StringVar(&o.valuesPath, "values-path", "", "the kind's CredentialTemplate valuesPath: the hook adds the valuesFrom entry of every account to the release, so the first render of the converted chart already carries the stored values")
fs.StringVar(&o.sourceSuffix, "source-suffix", "-credentials", "suffix of the chart-generated Secret holding the plaintext passwords, after the release name")
@@ -378,7 +380,7 @@ func (m *migrator) finishRelease(ctx context.Context, hr *helmv2.HelmRelease, re
// the first user added later would never get a Secret. Every failure other
// than unresolvable accounts is an error.
func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) error {
accounts, err := resolveAccounts(hr, m.o.accountsPath, m.o.refuseFlags, m.o.reservedUsers)
accounts, err := m.o.resolveAccounts(hr)
if err != nil {
return fmt.Errorf("%w: %v", errUnresolvable, err)
}
@@ -506,30 +508,34 @@ func (m *migrator) addValuesFrom(ctx context.Context, hr *helmv2.HelmRelease, ac
// accounts map, in sorted order. Two users mapping to one name, a user whose
// name maps to an invalid one, or a user with a refused field set to true,
// which the converted chart would not render, or a reserved user name leave
// the release unresolvable.
func resolveAccounts(hr *helmv2.HelmRelease, path string, refuse, reserved []string) ([]account.Account, error) {
// the release unresolvable. A skipped key is not a tenant account: the
// converted chart renders no template for it, so it is left out of the result.
func (o *options) resolveAccounts(hr *helmv2.HelmRelease) ([]account.Account, error) {
var values map[string]any
if hr.Spec.Values != nil && len(hr.Spec.Values.Raw) > 0 {
if err := json.Unmarshal(hr.Spec.Values.Raw, &values); err != nil {
return nil, err
}
}
users, _ := lookup(values, path).(map[string]any)
users, _ := lookup(values, o.accountsPath).(map[string]any)
names := make([]string, 0, len(users))
for name := range users {
if slices.Contains(o.skipAccounts, name) {
continue
}
names = append(names, name)
}
sort.Strings(names)
var accounts []account.Account
byMapped := map[string]string{}
for _, name := range names {
if slices.Contains(reserved, name) {
return nil, fmt.Errorf("%s.%s is a name the converted chart reserves for a platform or engine account; rename the user", path, name)
if slices.Contains(o.reservedUsers, name) {
return nil, fmt.Errorf("%s.%s is a name the converted chart reserves for a platform or engine account; rename the user", o.accountsPath, name)
}
if u, ok := users[name].(map[string]any); ok {
for _, field := range refuse {
for _, field := range o.refuseFlags {
if on, _ := u[field].(bool); on {
return nil, fmt.Errorf("%s.%s.%s is true, which the converted chart refuses; set it to false", path, name, field)
return nil, fmt.Errorf("%s.%s.%s is true, which the converted chart refuses; set it to false", o.accountsPath, name, field)
}
}
}
+44
View File
@@ -758,3 +758,47 @@ func TestRunRefusesARotateKeyThatIsNotAPlatformKey(t *testing.T) {
t.Fatalf("err = %v", err)
}
}
func TestSeedSkipsAPlatformAccountInTheUsersMap(t *testing.T) {
ctx := context.Background()
// MariaDB keeps root in <release>-credentials and ignores users.root, so
// the converted chart renders no template for it: the conversion must
// neither write an account Secret holding root's verifier nor let the key
// stop the release from being marked for seeding.
m := newMigrator(t, release(`{"users":{"web":{},"root":{}}}`, "0.1.0", true), sourceSecret(map[string]string{"web": "hunter2", "root": "toor"}))
m.o.formatName = format.MySQLNative
m.o.skipAccounts = stringFlags{"root"}
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
if _, ok := m.secret(t, "postgres-orders.root.account"); ok {
t.Fatal("a skipped account must get no account Secret")
}
sec, ok := m.secret(t, "postgres-orders.web.account")
if !ok {
t.Fatal("the tenant account must still be migrated")
}
if got, want := string(sec.Data[account.PasswordKey]), "*58815970BE77B3720276F63DB198B1FA42E5CC02"; got != want {
t.Fatalf("stored = %q, want the mysql_native_password hash %q", got, want)
}
hr := &helmv2.HelmRelease{}
if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, hr); err != nil {
t.Fatal(err)
}
if hr.Annotations[account.SeedAnnotation] != "true" {
t.Fatal("a skipped key must not keep the release from being marked for seeding")
}
}
func TestResolveAccountsSkipsBeforeMapping(t *testing.T) {
// A skipped key is dropped before the name mapping, so it neither
// collides with a tenant account nor fails the mapping.
hr := release(`{"users":{"root":{},"web":{}}}`, "", false)
got, err := (&options{accountsPath: "users", skipAccounts: stringFlags{"root"}}).resolveAccounts(hr)
if err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0].Username != "web" {
t.Fatalf("accounts = %+v, want only web", got)
}
}
+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:
+201
View File
@@ -0,0 +1,201 @@
#!/usr/bin/env bats
# -----------------------------------------------------------------------------
# Unit tests for platform migration 66 --> 67 (convert MariaDB accounts to
# platform-minted credentials, first part).
#
# The migration seeds the account Secrets of every MariaDB release, then
# creates the cozystack-credentials-migration-66 finish Job directly (rather
# than rendering it from the platform chart) so a changing migrations image
# never collides with an immutable pod template and helm-controller waits on no
# long-running Job. See packages/core/platform/images/migrations/migrations/66.
#
# FAIL CLOSED is pinned for each path: a failed seed, a pod whose image cannot
# be read, and a failed apply of the Job must stop the migration before it
# stamps the version, because migrations never re-run.
#
# The harness (docker, the migrations image base, fake kubectl and
# credentials-migrate on PATH) is the one hack/migration-58-http-cache-freeze.bats
# describes; see there for why each piece is load-bearing.
#
# Run with: hack/cozytest.sh hack/migration-66-mariadb-credentials.bats
# -----------------------------------------------------------------------------
load test_helper
FAKEBIN="$PWD/hack/testdata/migration-66-mariadb-credentials"
MIG_DIR="$PWD/packages/core/platform/images/migrations/migrations"
ALPINE=$(sed -n 's/^FROM \(alpine:[^ ]*\).*$/\1/p' \
"$PWD/packages/core/platform/images/migrations/Dockerfile" | head -1)
TESTIMG="cozystack-migration66-test:$(printf '%s' "$ALPINE" | sed 's/[^a-zA-Z0-9]/-/g')"
WORKROOT="${TMPDIR:-/tmp}/cozy-migration-66-$$"
IMAGE=registry.example.org/cozystack/cozystack:v1.7.0
cozy_cleanup() {
rm -rf "$WORKROOT"
return 0
}
cmdlog_line() {
grep -nE -- "$1" "$FAKE_CMDLOG" | head -1 | cut -d: -f1
}
run_migration() {
_run_migration_rc=0
docker run --rm --network none \
--user "$(id -u):$(id -g)" \
-v "$MIG_DIR:/migrations:ro" \
-v "$FAKEBIN:/fakebin:ro" \
-v "$WORK:/work" \
-e PATH=/fakebin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
-e FAKE_CMDLOG=/work/cmdlog \
-e NAMESPACE="${NAMESPACE-}" \
-e FAKE_IMAGE="${FAKE_IMAGE-}" \
-e FAKE_IMAGE_EMPTY="${FAKE_IMAGE_EMPTY-}" \
-e FAKE_GETPOD_FAIL="${FAKE_GETPOD_FAIL-}" \
-e FAKE_APPLY_FAIL="${FAKE_APPLY_FAIL-}" \
-e FAKE_SEED_FAIL="${FAKE_SEED_FAIL-}" \
-e FAKE_GETJOB_FAIL="${FAKE_GETJOB_FAIL-}" \
-e FAKE_JOBUID_EMPTY="${FAKE_JOBUID_EMPTY-}" \
-e FAKE_PATCH_FAIL="${FAKE_PATCH_FAIL-}" \
"$TESTIMG" "/migrations/$1" || _run_migration_rc=$?
return "$_run_migration_rc"
}
prep() {
docker info >/dev/null 2>&1 || {
echo "docker is required: these tests run migration 66 inside a build of" >&2
echo "$ALPINE, the migrations image's base." >&2
return 1
}
docker build -q -t "$TESTIMG" - >/dev/null <<DOCKERFILE
FROM $ALPINE
DOCKERFILE
chmod +x "$FAKEBIN/kubectl" "$FAKEBIN/credentials-migrate"
mkdir -p "$WORKROOT"
WORK=$(mktemp -d "$WORKROOT/XXXXXX")
export FAKE_CMDLOG="$WORK/cmdlog"
: > "$FAKE_CMDLOG"
export NAMESPACE=cozy-system
export FAKE_IMAGE="$IMAGE"
unset FAKE_IMAGE_EMPTY FAKE_GETPOD_FAIL FAKE_APPLY_FAIL FAKE_SEED_FAIL FAKE_GETJOB_FAIL FAKE_JOBUID_EMPTY FAKE_PATCH_FAIL || true
return 0
}
@test "it seeds, creates the finish Job on its own image, and stamps" {
prep
rc=0
run_migration 66 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -eq 0 ]
# The seed runs for migration 66, on MariaDB, storing mysql_native_password
# hashes, skipping users.root and asking for the watch label.
grep -qE "^CREDMIGRATE seed --migration 66 --kind MariaDB --format mysql-native --accounts-path users --skip-account root --label k8s.mariadb.com/watch=$" "$FAKE_CMDLOG"
# The finish Job carries its least-privilege ClusterRole (never cluster-admin),
# ServiceAccount and binding, the migration number, and the image this hook
# runs as, read from its own pod rather than values.
grep -qE "^APPLY-FINISH role=1 sa=1 crb=1 admin=0 jobname=1 migration=1 image=1 serviceaccount=1 platformkey=1 skip=1$" "$FAKE_CMDLOG"
# The Job owns its ServiceAccount, so the least-privilege identity is collected
# with the Job and does not stand indefinitely.
grep -qE "^PATCH-SA-OWNER owner=1$" "$FAKE_CMDLOG"
# A stale Job from an earlier run is deleted before the apply, so a rerun on a
# newer image does not fault on the immutable pod template; the ownership is
# set after the Job exists; and only then, after the Job is created and owned,
# the version is stamped. A stamp before the Job would mark the migration done
# with no finisher.
_del=$(cmdlog_line "^DELETE-JOB$")
_apply=$(cmdlog_line "^APPLY-FINISH ")
_own=$(cmdlog_line "^PATCH-SA-OWNER ")
_stamp=$(cmdlog_line "^STAMP 67$")
[ -n "$_del" ] && [ "$_del" -lt "$_apply" ]
[ -n "$_own" ] && [ "$_apply" -lt "$_own" ]
[ -n "$_stamp" ] && [ "$_own" -lt "$_stamp" ]
rm -rf "$WORK"
}
@test "a pod whose image cannot be read, as a failed get, stops before the Job and the stamp" {
prep
export FAKE_GETPOD_FAIL="the server could not find the requested resource"
rc=0
run_migration 66 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
grep -qE "^CREDMIGRATE seed --migration 66 " "$FAKE_CMDLOG"
if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "created the Job after a failed image read" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed image read" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a failed seed stops before the Job and before stamping" {
prep
export FAKE_SEED_FAIL="apiserver is unavailable"
rc=0
run_migration 66 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "created the Job after a failed seed" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed seed" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a pod whose image cannot be read stops after the seed, before the Job and the stamp" {
prep
export FAKE_IMAGE_EMPTY=1
rc=0
run_migration 66 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
grep -qE "^CREDMIGRATE seed --migration 66 " "$FAKE_CMDLOG"
if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "created the Job with no image to run" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped with no image to run" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a failed apply of the Job stops before stamping" {
prep
export FAKE_APPLY_FAIL="admission webhook denied the request"
rc=0
run_migration 66 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after the Job failed to apply" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a Job whose uid cannot be read stops before owning the SA and before stamping" {
prep
export FAKE_GETJOB_FAIL="the server was unable to return a response"
rc=0
run_migration 66 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qE "^PATCH-SA-OWNER" "$FAKE_CMDLOG"; then echo "patched ownership with no uid" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped without owning the SA" >&2; return 1; fi
rm -rf "$WORK"
}
@test "an empty Job uid stops before owning the SA and before stamping" {
prep
export FAKE_JOBUID_EMPTY=1
rc=0
run_migration 66 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qE "^PATCH-SA-OWNER" "$FAKE_CMDLOG"; then echo "patched ownership with an empty uid" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped with an empty uid" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a failed ownership patch stops before stamping" {
prep
export FAKE_PATCH_FAIL="serviceaccounts \"cozystack-credentials-migration-66\" not found"
rc=0
run_migration 66 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after the ownership patch failed" >&2; return 1; fi
rm -rf "$WORK"
}
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
# Fake credentials-migrate for hack/migration-66-mariadb-credentials.bats.
# Migration 66 runs `credentials-migrate seed` in the hook; the real binary is
# exercised by cmd/credentials-migrate's Go tests, so this fake only records the
# call and fails on demand to pin the hook's fail-closed behaviour.
#
# FAKE_CMDLOG file to append a one-line record of each call to
# FAKE_SEED_FAIL non-empty => `seed` exits 1 with this stderr
set -u
[ -n "${FAKE_CMDLOG:-}" ] && printf 'CREDMIGRATE %s\n' "$*" >> "$FAKE_CMDLOG"
case "${1:-}" in
seed)
if [ -n "${FAKE_SEED_FAIL:-}" ]; then
printf '%s\n' "$FAKE_SEED_FAIL" >&2
exit 1
fi
exit 0
;;
esac
exit 0
+114
View File
@@ -0,0 +1,114 @@
#!/bin/sh
# Fake kubectl for hack/migration-66-mariadb-credentials.bats, modelled on
# hack/testdata/migration-58-http-cache/kubectl. It serves only the calls
# migration 66 and lib/cozystack-version.sh make, and logs each one to
# $FAKE_CMDLOG.
#
# Migration 66 reads its own pod's image, applies the finish Job (with its
# ServiceAccount and ClusterRoleBinding), and stamps the version. The Job
# manifest and the version stamp both arrive as `apply --filename -`, so this
# fake reads stdin and branches on the manifest's kind.
#
# FAKE_CMDLOG file to append a one-line record of each call to
# FAKE_IMAGE image the `get pod` call returns (default a test ref)
# FAKE_IMAGE_EMPTY non-empty => `get pod` returns an empty image
# FAKE_GETPOD_FAIL non-empty => `get pod` exits 1 with this stderr
# FAKE_APPLY_FAIL non-empty => applying the Job exits 1 with this stderr
set -u
log() { [ -n "${FAKE_CMDLOG:-}" ] && printf '%s\n' "$*" >> "$FAKE_CMDLOG"; }
log "KUBECTL $*"
args="$*"
IMAGE="${FAKE_IMAGE:-registry.example.org/cozystack/cozystack:v1.7.0}"
case "$args" in
*"get pod"*jsonpath*)
if [ -n "${FAKE_GETPOD_FAIL:-}" ]; then
printf '%s\n' "$FAKE_GETPOD_FAIL" >&2
exit 1
fi
[ -n "${FAKE_IMAGE_EMPTY:-}" ] || printf '%s' "$IMAGE"
exit 0
;;
*"delete job cozystack-credentials-migration-66"*)
# The hook deletes a Job left by an earlier run before recreating it.
log "DELETE-JOB"
exit 0
;;
*"delete serviceaccount cozystack-credentials-migration-66"*)
# The hook deletes a ServiceAccount left owned by the Job it just deleted,
# so the apply recreates a fresh, owner-less one.
log "DELETE-SA"
exit 0
;;
*"get job cozystack-credentials-migration-66"*jsonpath*)
# The hook reads the Job's uid to own its ServiceAccount.
if [ -n "${FAKE_GETJOB_FAIL:-}" ]; then
printf '%s\n' "$FAKE_GETJOB_FAIL" >&2
exit 1
fi
[ -n "${FAKE_JOBUID_EMPTY:-}" ] || printf '%s' "11111111-2222-3333-4444-555555555555"
exit 0
;;
*"patch serviceaccount cozystack-credentials-migration-66"*)
# The ownerReference tying the ServiceAccount to the Job.
if [ -n "${FAKE_PATCH_FAIL:-}" ]; then
printf '%s\n' "$FAKE_PATCH_FAIL" >&2
exit 1
fi
owner=$(printf '%s' "$args" | grep -c 'cozystack-credentials-migration-66')
log "PATCH-SA-OWNER owner=$owner"
exit 0
;;
*"apply --filename -"*)
manifest=$(cat)
case "$manifest" in
*"kind: ConfigMap"*)
v=$(printf '%s\n' "$manifest" | sed -n 's/^ version: "\{0,1\}\([0-9]\{1,\}\)"\{0,1\}$/\1/p' | head -1)
log "STAMP ${v:-unknown}"
exit 0
;;
*"kind: Job"*)
if [ -n "${FAKE_APPLY_FAIL:-}" ]; then
printf '%s\n' "$FAKE_APPLY_FAIL" >&2
exit 1
fi
# Record the fields the Job must carry, so a copy that drops the
# ServiceAccount, names the wrong migration, or renders the wrong image
# is caught.
role=$(printf '%s\n' "$manifest" | grep -c '^kind: ClusterRole$')
sa=$(printf '%s\n' "$manifest" | grep -c '^kind: ServiceAccount$')
crb=$(printf '%s\n' "$manifest" | grep -c '^kind: ClusterRoleBinding$')
# The binding must grant the least-privilege role, never cluster-admin.
admin=$(printf '%s\n' "$manifest" | grep -c 'cluster-admin')
# The ServiceAccount, ClusterRole and binding share the Job's name, so
# the Job's own metadata is read from its document alone.
jobname=$(printf '%s\n' "$manifest" | awk '/^kind: Job$/{f=1} f' | grep -c '^ name: cozystack-credentials-migration-66$')
mig=$(printf '%s\n' "$manifest" | grep -c -- '--migration=66')
img=$(printf '%s\n' "$manifest" | grep -c "^ image: ${IMAGE}$")
sacc=$(printf '%s\n' "$manifest" | grep -c '^ serviceAccountName: cozystack-credentials-migration-66$')
# The Job keeps root, MariaDB's platform account, in the source
# Secret and skips a users.root entry.
keep=$(printf '%s\n' "$manifest" | grep -c -- '--platform-key=root')
skip=$(printf '%s\n' "$manifest" | grep -c -- '--skip-account=root')
log "APPLY-FINISH role=$role sa=$sa crb=$crb admin=$admin jobname=$jobname migration=$mig image=$img serviceaccount=$sacc platformkey=$keep skip=$skip"
exit 0
;;
*)
log "APPLY-UNKNOWN"
printf 'fake kubectl: unmodelled apply\n' >&2
exit 1
;;
esac
;;
esac
log "UNHANDLED $args"
printf 'fake kubectl: unmodelled call: %s\n' "$args" >&2
exit 1
+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:
+174
View File
@@ -0,0 +1,174 @@
#!/bin/sh
# Migration 66 --> 67
# Convert MariaDB accounts to platform-minted credentials, first part.
#
# The converted mariadb chart renders a CredentialTemplate per user, and each
# mariadb-operator User reads its mysql_native_password hash from the
# template's account Secret, which cozystack-controller seeds with a random
# password only on a release marked for seeding. This hook runs before any
# component chart changes version and writes those Secrets, unowned, for
# every existing MariaDB release from the passwords in <release>-credentials,
# so clients keep logging in at every point of the upgrade; the controller
# adopts them once the templates exist. A release whose every account got its
# Secret is marked for seeding, so users added later are seeded too. A
# users.root entry is skipped: the chart has always ignored it, and root is
# the platform's own account.
#
# The second part is the cozystack-credentials-migration-66 Job, which waits
# per release for its chart to switch, then strips any leftover plaintext from
# the values and removes the tenant keys from <release>-credentials. root
# stays there, since rootPasswordSecretKeyRef cannot change once set, and the
# converted chart hides that Secret from tenants. This Job does not rotate
# root: mariadb-operator reads it on every SQL reconcile, the server pods take
# it as MARIADB_ROOT_PASSWORD at start and their probes log in with it, so an
# ALTER USER without a coordinated pod restart fails every probe. The root
# password tenants could read before the conversion keeps working until a
# platform administrator rotates it.
#
# The hook creates the Job directly rather than rendering it from the platform
# chart, for the reasons migration 64 gives, under names of its own: migration
# 64's Job may still be running when this hook deletes and recreates its own,
# and a shared ServiceAccount would be deleted out from under it. The Job's
# ServiceAccount is bound to a least-privilege ClusterRole (CRUD on Secrets,
# get/list/patch on HelmReleases, create on Events, its state ConfigMap) and
# owned by the Job, so the garbage collector removes it with the Job. While
# any release is left out, credentials-migrate labels its state ConfigMap
# credentials.cozystack.io/incomplete=true, which the
# CredentialsMigrationIncomplete alert fires on. To rerun it by hand, delete
# the Job and re-apply the manifest below.
#
# Fail-closed: migrations never re-run, so an error here stops the upgrade
# rather than stamping the version past a release that was not recorded.
set -euo pipefail
# shellcheck source=lib/cozystack-version.sh
. "$(dirname "$0")/lib/cozystack-version.sh"
NAMESPACE="${NAMESPACE:-cozy-system}"
credentials-migrate seed \
--migration 66 \
--kind MariaDB \
--format mysql-native \
--accounts-path users \
--skip-account root \
--label 'k8s.mariadb.com/watch='
# The finish Job runs the same image as this hook, so a release and its
# conversion share the credentials-migrate build. Read it from this pod's own
# container by name rather than render it from values, which the hook does not
# carry, and rather than by position, which a webhook-injected container shifts.
image=$(kubectl get pod "$(hostname)" \
--namespace "$NAMESPACE" \
--output 'jsonpath={.spec.containers[?(@.name=="migration")].image}')
if [ -z "$image" ]; then
echo "cannot read this pod's image to run the finish Job" >&2
exit 1
fi
# Delete any Job left by an earlier run of this hook: its pod template is
# immutable, so a rerun on a newer image would fault on apply. finish recovers
# its progress from the state ConfigMap, so recreating the Job loses nothing.
# Delete the ServiceAccount with it: an earlier run may have left it owned by
# the Job just deleted, and the apply below does not touch ownerReferences, so
# without this the garbage collector could remove the re-applied ServiceAccount
# out from under the ownerReference patch. A fresh, owner-less ServiceAccount is
# never collected before the patch names the new Job.
kubectl delete job cozystack-credentials-migration-66 \
--namespace "$NAMESPACE" \
--ignore-not-found
kubectl delete serviceaccount cozystack-credentials-migration-66 \
--namespace "$NAMESPACE" \
--ignore-not-found
kubectl apply --filename - <<YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: cozystack-credentials-migration-66
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "create", "patch", "delete"]
- apiGroups: [""]
resources: ["configmaps"]
verbs: ["get", "create", "update"]
- apiGroups: [""]
resources: ["events"]
verbs: ["create"]
- apiGroups: ["helm.toolkit.fluxcd.io"]
resources: ["helmreleases"]
verbs: ["get", "list", "patch"]
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: cozystack-credentials-migration-66
namespace: ${NAMESPACE}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: cozystack-credentials-migration-66
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cozystack-credentials-migration-66
subjects:
- kind: ServiceAccount
name: cozystack-credentials-migration-66
namespace: ${NAMESPACE}
---
apiVersion: batch/v1
kind: Job
metadata:
name: cozystack-credentials-migration-66
namespace: ${NAMESPACE}
spec:
backoffLimit: 6
ttlSecondsAfterFinished: 604800
template:
metadata:
labels:
policy.cozystack.io/allow-to-apiserver: "true"
spec:
serviceAccountName: cozystack-credentials-migration-66
restartPolicy: OnFailure
containers:
- name: migration
image: ${image}
command:
- credentials-migrate
- finish
- --migration=66
- --kind=MariaDB
- --format=mysql-native
- --accounts-path=users
- --skip-account=root
- --label=k8s.mariadb.com/watch=
- --platform-key=root
- --timeout=30m
env:
- name: CREDENTIALS_MIGRATE_ACTOR
value: system:serviceaccount:${NAMESPACE}:cozystack-credentials-migration-66
YAML
# Tie the ServiceAccount's lifetime to the Job: when the Job is deleted (its
# ttlSecondsAfterFinished, a rerun's delete above, or an operator by hand) the
# garbage collector removes the ServiceAccount, on the success and the failure
# path alike, so the least-privilege identity does not stand indefinitely after
# a release the conversion left out.
job_uid=$(kubectl get job cozystack-credentials-migration-66 \
--namespace "$NAMESPACE" \
--output 'jsonpath={.metadata.uid}')
if [ -z "$job_uid" ]; then
echo "cannot read the finish Job's uid to own its ServiceAccount" >&2
exit 1
fi
kubectl patch serviceaccount cozystack-credentials-migration-66 \
--namespace "$NAMESPACE" \
--type merge \
--patch "{\"metadata\":{\"ownerReferences\":[{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\"name\":\"cozystack-credentials-migration-66\",\"uid\":\"${job_uid}\"}]}}"
stamp_cozystack_version 67
+1 -1
View File
@@ -89,7 +89,7 @@ migrations:
# refuses to advance past a migration file missing from the image (exit 1), so
# a stale pin fails loudly rather than silently skipping the etcd adoption.
image: ghcr.io/cozystack/cozystack/platform-migrations:v1.6.0@sha256:6777042e3e9c6bad76e7d96fb64baa115061975f39061cb3ede84e21d0e2213f
targetVersion: 66
targetVersion: 67
# Adopt legacy etcd clusters onto the v1alpha2 operator WITHOUT the mandatory
# pre-adoption safety snapshot (migration 50). Leave false unless migration 50
# has actually refused to proceed and you accept the risk: adoption rewires
+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"}}}`)}}