diff --git a/api/apps/v1alpha1/mongodb/types.go b/api/apps/v1alpha1/mongodb/types.go index ff23bc560..d0c522406 100644 --- a/api/apps/v1alpha1/mongodb/types.go +++ b/api/apps/v1alpha1/mongodb/types.go @@ -45,7 +45,7 @@ type ConfigSpec struct { // Configuration for sharded cluster mode. // +kubebuilder:default:={} ShardingConfig ShardingConfig `json:"shardingConfig"` - // Users configuration map. + // Users configuration map. Each user is a MongoDB user the operator manages from an account Secret the platform keeps. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. A `password` key here is ignored. The names of the MongoDB system users (`backup`, `clusterAdmin`, `clusterMonitor`, `databaseAdmin`, `userAdmin`) are refused. // +kubebuilder:default:={} Users map[string]User `json:"users,omitempty"` // Databases configuration map. @@ -149,8 +149,6 @@ type ShardingConfig struct { } type User struct { - // Password for the user (auto-generated if omitted). - Password string `json:"password,omitempty"` } // +kubebuilder:validation:Enum="t1.nano";"t1.micro";"t1.small";"t1.medium";"t1.large";"t1.xlarge";"t1.2xlarge";"t1.4xlarge";"c1.nano";"c1.micro";"c1.small";"c1.medium";"c1.large";"c1.xlarge";"c1.2xlarge";"c1.4xlarge";"s1.nano";"s1.micro";"s1.small";"s1.medium";"s1.large";"s1.xlarge";"s1.2xlarge";"s1.4xlarge";"u1.nano";"u1.micro";"u1.small";"u1.medium";"u1.large";"u1.xlarge";"u1.2xlarge";"u1.4xlarge";"m1.nano";"m1.micro";"m1.small";"m1.medium";"m1.large";"m1.xlarge";"m1.2xlarge";"m1.4xlarge";"nano";"micro";"small";"medium";"large";"xlarge";"2xlarge" diff --git a/cmd/credentials-migrate/main.go b/cmd/credentials-migrate/main.go index bdec40687..07004d01a 100644 --- a/cmd/credentials-migrate/main.go +++ b/cmd/credentials-migrate/main.go @@ -72,23 +72,25 @@ const ( // options is the kind's credentials block and the migration's identity, as // the hook and the Job pass them. type options struct { - migration int - kind string - formatName string - accountsPath string - refuseFlags stringFlags - reservedUsers stringFlags - skipAccounts stringFlags - labels labelFlags - valuesPath string - sourceSuffix string - platformKeys stringFlags - rotateKeys stringFlags - stateNamespace string - actor string - timeout time.Duration - holdRollouts stringFlags - holdTimeout time.Duration + migration int + kind string + formatName string + accountsPath string + refuseFlags stringFlags + reservedUsers stringFlags + skipAccounts stringFlags + labels labelFlags + valuesPath string + sourceSuffix string + sourceKey string + sourcePerAccount bool + platformKeys stringFlags + rotateKeys stringFlags + stateNamespace string + actor string + timeout time.Duration + holdRollouts stringFlags + holdTimeout time.Duration } type labelFlags map[string]string @@ -156,6 +158,8 @@ func run(args []string) error { 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") + fs.StringVar(&o.sourceKey, "source-key", "", "key of the source Secret holding an account's password; empty means the user name") + fs.BoolVar(&o.sourcePerAccount, "source-per-account", false, "the chart kept one source Secret per account, named , with the password under --source-key") fs.Var(&o.platformKeys, "platform-key", "key of the source Secret that belongs to a platform account and stays; repeatable") fs.Var(&o.rotateKeys, "rotate-key", "finish: platform key of the source Secret to replace with a new random password once, followed by a forced upgrade of the release; repeatable") fs.StringVar(&o.stateNamespace, "state-namespace", "cozy-system", "namespace of the state ConfigMap") @@ -169,6 +173,9 @@ func run(args []string) error { if o.migration == 0 || o.kind == "" || !format.Known(o.formatName) { return errors.New("--migration, --kind and a built-in --format are required") } + if o.sourcePerAccount && o.sourceKey == "" { + return errors.New("--source-per-account needs --source-key: a per-account Secret is not keyed by user name") + } for _, k := range o.rotateKeys { if !slices.Contains(o.platformKeys, k) { return fmt.Errorf("--rotate-key %q is not a --platform-key, and finish would delete it from the source Secret", k) @@ -384,14 +391,17 @@ func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) erro if err != nil { return fmt.Errorf("%w: %v", errUnresolvable, err) } - source := &corev1.Secret{} - if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name + m.o.sourceSuffix}, source); err != nil { - if !apierrors.IsNotFound(err) { - return err - } - if len(accounts) > 0 { - fmt.Printf("%s/%s: %s%s is gone; its accounts get a Secret at their first mint\n", hr.Namespace, hr.Name, hr.Name, m.o.sourceSuffix) - return nil + var source *corev1.Secret + if !m.o.sourcePerAccount { + source = &corev1.Secret{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name + m.o.sourceSuffix}, source); err != nil { + if !apierrors.IsNotFound(err) { + return err + } + if len(accounts) > 0 { + fmt.Printf("%s/%s: %s%s is gone; its accounts get a Secret at their first mint\n", hr.Namespace, hr.Name, hr.Name, m.o.sourceSuffix) + return nil + } } } now := metav1.NewTime(m.now()) @@ -417,9 +427,12 @@ func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) erro case !apierrors.IsNotFound(err): return err } - plaintext, ok := source.Data[acc.Username] + plaintext, from, ok, err := m.plaintext(ctx, hr, source, acc.Username) + if err != nil { + return err + } if !ok { - fmt.Printf("%s/%s: no password for %q in %s%s; the account gets a Secret at its first mint\n", hr.Namespace, hr.Name, acc.Username, hr.Name, m.o.sourceSuffix) + fmt.Printf("%s/%s: no password for %q in %s; the account gets a Secret at its first mint\n", hr.Namespace, hr.Name, acc.Username, from) complete = false continue } @@ -427,7 +440,7 @@ func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) erro // A verifier built from this password would not authenticate it // after the engine's login-time normalization, so the account is // re-minted instead of carried over with a Secret nobody can use. - fmt.Printf("%s/%s: the password for %q in %s%s does not carry into a %s verifier unchanged; the account gets a Secret at its first mint\n", hr.Namespace, hr.Name, acc.Username, hr.Name, m.o.sourceSuffix, m.o.formatName) + fmt.Printf("%s/%s: the password for %q in %s does not carry into a %s verifier unchanged; the account gets a Secret at its first mint\n", hr.Namespace, hr.Name, acc.Username, from, m.o.formatName) complete = false continue } @@ -504,6 +517,37 @@ func (m *migrator) addValuesFrom(ctx context.Context, hr *helmv2.HelmRelease, ac return m.c.Patch(ctx, hr, patch) } +// plaintext returns the chart-generated password of one account and the name +// of the Secret it was looked up in: the release's single source Secret or, +// with --source-per-account, the account's own Secret +// , as charts that render one Secret per user +// keep it. The password is under --source-key, or under the user name when +// that is empty. A missing Secret or key is reported as not found. +func (m *migrator) plaintext(ctx context.Context, hr *helmv2.HelmRelease, source *corev1.Secret, user string) ([]byte, string, bool, error) { + key := m.o.sourceKey + if key == "" { + key = user + } + if !m.o.sourcePerAccount { + v, ok := source.Data[key] + return v, source.Name, ok, nil + } + name := m.perAccountSource(hr, user) + sec := &corev1.Secret{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: name}, sec); err != nil { + if apierrors.IsNotFound(err) { + return nil, name, false, nil + } + return nil, name, false, err + } + v, ok := sec.Data[key] + return v, name, ok, nil +} + +func (m *migrator) perAccountSource(hr *helmv2.HelmRelease, user string) string { + return hr.Name + m.o.sourceSuffix + user +} + // resolveAccounts returns the accounts the release declares: the keys of its // 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, @@ -607,6 +651,9 @@ func (m *migrator) stripPasswords(ctx context.Context, hr *helmv2.HelmRelease) e // stay in its data otherwise, and the Secret itself when no platform key // remains. func (m *migrator) retireSource(ctx context.Context, hr *helmv2.HelmRelease) error { + if m.o.sourcePerAccount { + return m.retirePerAccountSources(ctx, hr) + } source := &corev1.Secret{} if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name + m.o.sourceSuffix}, source); err != nil { if apierrors.IsNotFound(err) { @@ -765,6 +812,31 @@ func (m *migrator) rotatePlatformKeys(ctx context.Context, hr *helmv2.HelmReleas return nil } +// retirePerAccountSources deletes the per-account source Secrets of the +// declared accounts. The converted chart no longer renders them, so Helm has +// usually pruned them at the switch; this removes one Helm left behind. +func (m *migrator) retirePerAccountSources(ctx context.Context, hr *helmv2.HelmRelease) error { + accounts, err := m.o.resolveAccounts(hr) + if err != nil { + return err + } + for _, acc := range accounts { + sec := &corev1.Secret{} + name := m.perAccountSource(hr, acc.Username) + if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: name}, sec); err != nil { + if apierrors.IsNotFound(err) { + continue + } + return err + } + if err := m.c.Delete(ctx, sec, client.Preconditions{UID: &sec.UID}); err != nil && !apierrors.IsNotFound(err) { + return err + } + fmt.Printf("%s/%s: deleted %s\n", hr.Namespace, hr.Name, name) + } + return nil +} + func (m *migrator) releases(ctx context.Context) ([]helmv2.HelmRelease, error) { list := &helmv2.HelmReleaseList{} if err := m.c.List(ctx, list, client.MatchingLabels{ diff --git a/cmd/credentials-migrate/main_test.go b/cmd/credentials-migrate/main_test.go index 73c3556ff..02ecc618b 100644 --- a/cmd/credentials-migrate/main_test.go +++ b/cmd/credentials-migrate/main_test.go @@ -802,3 +802,86 @@ func TestResolveAccountsSkipsBeforeMapping(t *testing.T) { t.Fatalf("accounts = %+v, want only web", got) } } + +// A chart that renders one Secret per user, as MongoDB's does, is migrated +// from under --source-per-account, and finish +// deletes what Helm left of those Secrets while the platform Secret stays. +func TestSeedAndRetirePerAccountSources(t *testing.T) { + ctx := context.Background() + perUser := func(user, pass string) *corev1.Secret { + return &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: "postgres-orders-user-" + user, Namespace: "tenant-foo"}, + Data: map[string][]byte{"password": []byte(pass)}, + } + } + hr := release(`{"users":{"web":{},"api":{},"ghost":{}}}`, "0.1.0", true) + m := newMigrator(t, hr, perUser("web", "hunter2"), perUser("api", "s3cret"), sourceSecret(map[string]string{"username": "databaseAdmin", "password": "adm"})) + m.o.formatName = format.Plaintext + m.o.sourceSuffix = "-user-" + m.o.sourceKey = "password" + m.o.sourcePerAccount = true + m.o.labels = labelFlags{} + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + for _, c := range []struct{ secret, user, plain string }{{"postgres-orders.web.account", "web", "hunter2"}, {"postgres-orders.api.account", "api", "s3cret"}} { + sec, ok := m.secret(t, c.secret) + if !ok { + t.Fatalf("%s not written", c.secret) + } + if string(sec.Data[account.UsernameKey]) != c.user || string(sec.Data[account.PasswordKey]) != c.plain || sec.Annotations[account.FormatAnnotation] != format.Plaintext { + t.Fatalf("%s = %+v %q", c.secret, sec.ObjectMeta, sec.Data) + } + } + if _, ok := m.secret(t, "postgres-orders.ghost.account"); ok { + t.Fatal("an account without a per-user Secret waits for a mint") + } + cur := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil { + t.Fatal(err) + } + if cur.Annotations[account.SeedAnnotation] == "true" { + t.Fatal("a release with an account left without a Secret must not be marked for seeding") + } + + if err := m.retireSource(ctx, cur); err != nil { + t.Fatal(err) + } + for _, name := range []string{"postgres-orders-user-web", "postgres-orders-user-api"} { + if _, ok := m.secret(t, name); ok { + t.Fatalf("%s must be deleted", name) + } + } + if _, ok := m.secret(t, "postgres-orders-credentials"); !ok { + t.Fatal("the platform Secret is not a per-account source and must stay") + } + if _, ok := m.secret(t, "postgres-orders.web.account"); !ok { + t.Fatal("the account Secret must stay") + } +} + +func TestSeedMarksAReleaseWithoutUsersFromPerAccountSources(t *testing.T) { + ctx := context.Background() + m := newMigrator(t, release(`{"users":{}}`, "0.1.0", true)) + m.o.formatName = format.Plaintext + m.o.sourceSuffix = "-user-" + m.o.sourceKey = "password" + m.o.sourcePerAccount = true + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + 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 release without users must be marked, or its first user never gets a Secret") + } +} + +func TestRunRefusesPerAccountSourcesWithoutAKey(t *testing.T) { + err := run([]string{"seed", "--migration=67", "--kind=MongoDB", "--format=plaintext", "--source-per-account"}) + if err == nil || !strings.Contains(err.Error(), "--source-key") { + t.Fatalf("err = %v", err) + } +} diff --git a/hack/check-mongodb-rd-secrets.bats b/hack/check-mongodb-rd-secrets.bats index 23f2d255e..ca3e5df57 100644 --- a/hack/check-mongodb-rd-secrets.bats +++ b/hack/check-mongodb-rd-secrets.bats @@ -55,8 +55,9 @@ SELF="$REPO_ROOT/hack/check-mongodb-rd-secrets.bats" # grep-based tests would not notice either, since the strings stay in the # file. Deleting `include` outright is already caught by the label grep; this # covers the rename. + # One entry since the credentials Secret left include: the label selector. n="$(yq '.spec.secrets.include // [] | length' "$COZYRDS")" - if [ "$n" -lt 2 ]; then + if [ "$n" -lt 1 ]; then echo "spec.secrets.include has $n entries; the structural checks would be vacuous" >&2 exit 1 fi @@ -126,21 +127,19 @@ SELF="$REPO_ROOT/hack/check-mongodb-rd-secrets.bats" done } -@test "mongodb-rd cozyrds still delivers the credentials secret" { - # The exclude list added alongside the trust anchor is evaluated BEFORE - # include and wins outright, so it now sits upstream of this pre-existing - # grant. Every other line in that block is about withholding a Secret, which - # makes adding this one to it a plausible edit — and one that would silently - # revoke the tenant's access to their own connection string. Assert both - # directions. +@test "mongodb-rd cozyrds hides the databaseAdmin credentials secret" { + # -credentials holds the databaseAdmin system user, a platform + # account since tenant users became Credentials minted through the + # Cozystack API. It must be excluded and never included: an include entry + # would hand the platform password back to every tenant reader. inc="$(yq '[.spec.secrets.include[].resourceNames[]? | select(. == "mongodb-{{ .name }}-credentials")] | length' "$COZYRDS")" - if [ "$inc" != "1" ]; then - echo "credentials is not granted via include (found $inc entries)" >&2 + if [ "$inc" != "0" ]; then + echo "credentials is still granted via include (found $inc entries)" >&2 exit 1 fi exc="$(yq '[.spec.secrets.exclude[].resourceNames[]? | select(. == "mongodb-{{ .name }}-credentials")] | length' "$COZYRDS")" - if [ "$exc" != "0" ]; then - echo "credentials appears in exclude, which wins over include" >&2 + if [ "$exc" != "1" ]; then + echo "credentials is not excluded (found $exc entries)" >&2 exit 1 fi } diff --git a/hack/e2e-chainsaw/mongodb/chainsaw-test.yaml b/hack/e2e-chainsaw/mongodb/chainsaw-test.yaml index 8ebdd384b..b38ba2e9e 100644 --- a/hack/e2e-chainsaw/mongodb/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/mongodb/chainsaw-test.yaml @@ -155,11 +155,19 @@ spec: # the mechanism is live, all three would pass while asserting nothing about # the CA private key. # - # The credentials Secret is the right witness: the chart renders it, it - # traces to the MongoDB CR, and the ApplicationDefinition grants it by name - # — so it MUST be stamped. This also catches the regression the exclude - # list makes newly possible, since exclude is evaluated before include and - # would silently revoke the tenant's own connection string. + # The tenant-ca projection is the witness: the ApplicationDefinition + # selects it by label, so the lineage webhook MUST stamp it. The + # credentials Secret no longer qualifies: it holds the databaseAdmin + # platform account and must stay hidden, which the second assert checks. + - assert: + timeout: 2m + resource: + apiVersion: v1 + kind: Secret + metadata: + name: mongodb-test.tenant-ca + labels: + internal.cozystack.io/tenantresource: "true" - assert: timeout: 2m resource: @@ -168,7 +176,7 @@ spec: metadata: name: mongodb-test-credentials labels: - internal.cozystack.io/tenantresource: "true" + internal.cozystack.io/tenantresource: "false" - assert: timeout: 2m resource: diff --git a/hack/migration-67-mongodb-credentials.bats b/hack/migration-67-mongodb-credentials.bats new file mode 100644 index 000000000..ef53bbb2d --- /dev/null +++ b/hack/migration-67-mongodb-credentials.bats @@ -0,0 +1,201 @@ +#!/usr/bin/env bats +# ----------------------------------------------------------------------------- +# Unit tests for platform migration 67 --> 68 (convert MongoDB users to +# platform-minted credentials, first part). +# +# The migration seeds the account Secrets of every MongoDB release, then +# creates the cozystack-credentials-migration-67 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/67. +# +# 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-67-mongodb-credentials.bats +# ----------------------------------------------------------------------------- + +load test_helper + +FAKEBIN="$PWD/hack/testdata/migration-67-mongodb-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-migration67-test:$(printf '%s' "$ALPINE" | sed 's/[^a-zA-Z0-9]/-/g')" +WORKROOT="${TMPDIR:-/tmp}/cozy-migration-67-$$" +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 67 inside a build of" >&2 + echo "$ALPINE, the migrations image's base." >&2 + return 1 + } + docker build -q -t "$TESTIMG" - >/dev/null < "$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 67 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -eq 0 ] + + # The seed runs for migration 67, for MongoDB, storing the plaintext, and + # reads each user's password from its own -user- Secret. + grep -qE "^CREDMIGRATE seed --migration 67 --kind MongoDB --format plaintext --accounts-path users --source-suffix -user- --source-key password --source-per-account$" "$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$" "$FAKE_CMDLOG" + + # The Job owns its ServiceAccount, so the cluster-admin 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 68$") + [ -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 67 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + grep -qE "^CREDMIGRATE seed --migration 67 " "$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 67 >"$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 67 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + grep -qE "^CREDMIGRATE seed --migration 67 " "$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 67 >"$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 67 >"$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 67 >"$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-67\" not found" + rc=0 + run_migration 67 >"$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" +} diff --git a/hack/testdata/migration-67-mongodb-credentials/credentials-migrate b/hack/testdata/migration-67-mongodb-credentials/credentials-migrate new file mode 100755 index 000000000..c2f3975cb --- /dev/null +++ b/hack/testdata/migration-67-mongodb-credentials/credentials-migrate @@ -0,0 +1,22 @@ +#!/bin/sh +# Fake credentials-migrate for hack/migration-67-mongodb-credentials.bats. +# Migration 67 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 diff --git a/hack/testdata/migration-67-mongodb-credentials/kubectl b/hack/testdata/migration-67-mongodb-credentials/kubectl new file mode 100755 index 000000000..daf8fb332 --- /dev/null +++ b/hack/testdata/migration-67-mongodb-credentials/kubectl @@ -0,0 +1,112 @@ +#!/bin/sh +# Fake kubectl for hack/migration-67-mongodb-credentials.bats, modelled on +# hack/testdata/migration-58-http-cache/kubectl. It serves only the calls +# migration 67 and lib/cozystack-version.sh make, and logs each one to +# $FAKE_CMDLOG. +# +# Migration 67 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-67"*) + # The hook deletes a Job left by an earlier run before recreating it. + log "DELETE-JOB" + exit 0 + ;; + + *"delete serviceaccount cozystack-credentials-migration-67"*) + # 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-67"*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-67"*) + # The ownerReference tying the ServiceAccount to the Job. + if [ -n "${FAKE_PATCH_FAIL:-}" ]; then + printf '%s\n' "$FAKE_PATCH_FAIL" >&2 + exit 1 + fi + # The ServiceAccount shares the Job's name, so match the owner reference + # itself rather than the bare name. + owner=$(printf '%s' "$args" | grep -c '"kind":"Job","name":"cozystack-credentials-migration-67"') + 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 + # count the name only in the Job's own metadata. + jobname=$(printf '%s\n' "$manifest" | awk '/^kind: Job$/ { j = 1 } j && /^ name: cozystack-credentials-migration-67$/ { c++; j = 0 } END { print c + 0 }') + mig=$(printf '%s\n' "$manifest" | grep -c -- '--migration=67') + img=$(printf '%s\n' "$manifest" | grep -c "^ image: ${IMAGE}$") + sacc=$(printf '%s\n' "$manifest" | grep -c '^ serviceAccountName: cozystack-credentials-migration-67$') + log "APPLY-FINISH role=$role sa=$sa crb=$crb admin=$admin jobname=$jobname migration=$mig image=$img serviceaccount=$sacc" + 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 diff --git a/packages/apps/mongodb/README.md b/packages/apps/mongodb/README.md index 7790b3b75..b16989407 100644 --- a/packages/apps/mongodb/README.md +++ b/packages/apps/mongodb/README.md @@ -229,10 +229,9 @@ Releases with `external: false`, and sharded releases in any configuration, are ### Users configuration -| Name | Description | Type | Value | -| ---------------------- | -------------------------------------------------- | ------------------- | ----- | -| `users` | Users configuration map. | `map[string]object` | `{}` | -| `users[name].password` | Password for the user (auto-generated if omitted). | `string` | `""` | +| Name | Description | Type | Value | +| ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ----- | +| `users` | Users configuration map. Each user is a MongoDB user the operator manages from an account Secret the platform keeps. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. A `password` key here is ignored. The names of the MongoDB system users (`backup`, `clusterAdmin`, `clusterMonitor`, `databaseAdmin`, `userAdmin`) are refused. | `map[string]object` | `{}` | ### Databases configuration diff --git a/packages/apps/mongodb/templates/_accounts.tpl b/packages/apps/mongodb/templates/_accounts.tpl new file mode 100644 index 000000000..bfa9360de --- /dev/null +++ b/packages/apps/mongodb/templates/_accounts.tpl @@ -0,0 +1,53 @@ +{{/* + Account Secret naming, which must match pkg/credentials/account.MapName: the + API writes ..account, where is the user name + lowercased with every character outside [a-z0-9-] replaced by "-". The API + refuses two users that map to one account; the guard here covers a + HelmRelease written around it, where the operator would read one Secret for + both. +*/}} +{{- define "mongodb.accountName" -}} +{{- regexReplaceAll "[^a-z0-9-]" (lower .) "-" -}} +{{- end -}} + +{{- define "mongodb.accountSecret" -}} +{{- $root := index . 0 -}} +{{- $user := index . 1 -}} +{{- printf "%s.%s.account" $root.Release.Name (include "mongodb.accountName" $user) -}} +{{- end -}} + +{{/* + Refusals for user names the operator would not apply. The system users are + platform accounts kept in -percona-server-mongodb-users; the + operator skips a custom user that reuses one of their names, so a template + for it would mint a password that never reaches the engine. +*/}} +{{- define "mongodb.accountsGuard" -}} +{{- $reserved := include "mongodb.systemUserNames" . | fromJsonArray -}} +{{- $seen := dict -}} +{{- range $user, $_ := .Values.users -}} + {{- $mapped := include "mongodb.accountName" $user -}} + {{- if or (gt (len $mapped) 63) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $mapped)) -}} + {{- fail (printf "user %q maps to the account name %q, which must be at most 63 characters and start and end with a letter or a digit; rename the user" $user $mapped) -}} + {{- end -}} + {{- with index $seen $mapped -}} + {{- fail (printf "users %q and %q both map to the account name %q; rename one of them" . $user $mapped) -}} + {{- end -}} + {{- $_ := set $seen $mapped $user -}} + {{- if has $user $reserved -}} + {{- fail (printf "user %q is reserved: it is the name of a MongoDB system user the platform manages; rename the user" $user) -}} + {{- end -}} +{{- end -}} +{{- end -}} + +{{/* + The role every user the chart declares holds, and nothing else does: only + the operator, through spec.users, grants it. +*/}} +{{- define "mongodb.managedRole" -}} +cozystack-managed +{{- end -}} + +{{- define "mongodb.systemUserNames" -}} +{{- list "backup" "clusterAdmin" "clusterMonitor" "databaseAdmin" "userAdmin" | toJson -}} +{{- end -}} diff --git a/packages/apps/mongodb/templates/accounts.yaml b/packages/apps/mongodb/templates/accounts.yaml new file mode 100644 index 000000000..928b8b786 --- /dev/null +++ b/packages/apps/mongodb/templates/accounts.yaml @@ -0,0 +1,23 @@ +{{- /* + One CredentialTemplate per user: the account the Cozystack credentials API + mints and revokes through. cozystack-controller keeps its account Secret, + ..account, which spec.users[].passwordSecretRef names in + mongodb.yaml. MongoDB computes its SCRAM credentials from the plaintext, so + the Secret stores the password itself. The Percona operator re-reads it on + every reconcile, every five seconds while the cluster is ready, and runs + updateUser when its digest differs from the one the operator annotated, so + the Secret needs no label. The chart renders no password: a user exists in + the database once its Secret does, and nobody can log in until a mint. +*/ -}} +{{- include "mongodb.accountsGuard" $ }} +{{- range $user, $_ := .Values.users }} +--- +apiVersion: cozystack.io/v1alpha1 +kind: CredentialTemplate +metadata: + name: {{ printf "%s.%s" $.Release.Name (include "mongodb.accountName" $user) | quote }} +spec: + username: {{ $user | quote }} + format: + name: plaintext +{{- end }} diff --git a/packages/apps/mongodb/templates/credentials.yaml b/packages/apps/mongodb/templates/credentials.yaml index 1cf8dc7d8..078f682f0 100644 --- a/packages/apps/mongodb/templates/credentials.yaml +++ b/packages/apps/mongodb/templates/credentials.yaml @@ -66,11 +66,20 @@ stringData: {{ $key }}: {{ index $resolved $key | quote }} {{- end }} {{- end }} +{{- /* + The databaseAdmin system user is a platform account: tenant users are + CredentialTemplates (accounts.yaml), and this copy is not tenant-visible. + The label is the closure for a Secret the lineage webhook stamped before the + conversion, since the webhook keeps an explicit "false"; the + ApplicationDefinition no longer selects it. +*/}} --- apiVersion: v1 kind: Secret metadata: name: {{ .Release.Name }}-credentials + labels: + internal.cozystack.io/tenantresource: "false" type: Opaque stringData: username: {{ $adminUser | quote }} diff --git a/packages/apps/mongodb/templates/hooks/drop-users-job.yaml b/packages/apps/mongodb/templates/hooks/drop-users-job.yaml new file mode 100644 index 000000000..b462e87c5 --- /dev/null +++ b/packages/apps/mongodb/templates/hooks/drop-users-job.yaml @@ -0,0 +1,141 @@ +{{- /* + Drops the users this chart created that values no longer declare. The + Percona operator creates and updates the users in spec.users but never drops + one that leaves it, so a removed user would keep its last password in + MongoDB after its CredentialTemplate and account Secret are gone, with no + Credential left to revoke it through. + + A user is dropped only when it holds the marker role, which only the + operator grants and only to the users in spec.users (mongodb.yaml), is not + declared, and is not a system user. A user without the marker, created by + hand or by an earlier chart, is never touched. The Job logs in as the + userAdmin system user, a platform account, never as a tenant user. + + post-upgrade only: on install nothing carries the marker yet. Skipped while + the chart restores from a backup, where the cluster is busy and the restored + users are not this release's to judge until the restore is done. A failure + fails the upgrade, so a user that should be gone is reported, and the next + upgrade retries. +*/}} +{{- if not .Values.bootstrap.enabled }} +{{- $clusterDomain := (index .Values._cluster "cluster-domain") | default "cozy.local" }} +{{- $usersSecret := printf "%s-percona-server-mongodb-users" .Release.Name }} +{{- $uri := printf "mongodb://%s-rs0.%s.svc.%s:27017/admin?replicaSet=rs0" .Release.Name .Release.Namespace $clusterDomain }} +{{- if .Values.sharding }} +{{- $uri = printf "mongodb://%s-mongos.%s.svc.%s:27017/admin" .Release.Name .Release.Namespace $clusterDomain }} +{{- end }} +apiVersion: batch/v1 +kind: Job +metadata: + name: {{ .Release.Name }}-drop-users + annotations: + "helm.sh/hook": post-upgrade + "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded +spec: + {{- /* Under the platform's 10m hook budget, so the Job's own deadline names the failure. */}} + activeDeadlineSeconds: 540 + backoffLimit: 0 + ttlSecondsAfterFinished: 3600 + template: + spec: + restartPolicy: Never + containers: + - name: drop-users + image: percona/percona-server-mongodb:{{ include "mongodb.versionMap" $ }} + command: + - sh + - -ec + - | + # The password stays out of the pod spec: it reaches mongosh from + # the environment, inside the container only. + sh_mongo() { + mongosh "$MONGO_URI" --quiet --norc \ + --username "$MONGO_USER" --password "$MONGO_PASSWORD" \ + --authenticationDatabase admin "$@" + } + # An upgrade may roll the pods; wait for a primary rather than fail + # on the first refused connection. + i=0 + until sh_mongo --eval 'db.hello().isWritablePrimary || db.hello().msg === "isdbgrid" || quit(1)' >/dev/null 2>&1; do + i=$((i + 1)) + if [ "$i" -ge 60 ]; then + echo "MongoDB did not accept the userAdmin login with a writable primary in 5 minutes" >&2 + exit 1 + fi + sleep 5 + done + sh_mongo --eval "$DROP_JS" + env: + - name: HOME + value: /tmp + - name: MONGO_URI + value: {{ $uri | quote }} + - name: MONGO_USER + valueFrom: + secretKeyRef: + name: {{ $usersSecret }} + key: MONGODB_USER_ADMIN_USER + - name: MONGO_PASSWORD + valueFrom: + secretKeyRef: + name: {{ $usersSecret }} + key: MONGODB_USER_ADMIN_PASSWORD + {{- range $key := list "MONGODB_BACKUP_USER" "MONGODB_CLUSTER_ADMIN_USER" "MONGODB_CLUSTER_MONITOR_USER" "MONGODB_DATABASE_ADMIN_USER" "MONGODB_USER_ADMIN_USER" }} + - name: SYS_{{ $key }} + valueFrom: + secretKeyRef: + name: {{ $usersSecret }} + key: {{ $key }} + optional: true + {{- end }} + - name: DECLARED_USERS + value: {{ keys (.Values.users | default dict) | sortAlpha | toJson | quote }} + - name: DEFAULT_SYSTEM_USERS + value: {{ include "mongodb.systemUserNames" . | quote }} + - name: MANAGED_ROLE + value: {{ include "mongodb.managedRole" . | quote }} + - name: DROP_JS + value: | + const env = process.env; + const declared = new Set(JSON.parse(env.DECLARED_USERS)); + const system = new Set(JSON.parse(env.DEFAULT_SYSTEM_USERS)); + for (const [k, v] of Object.entries(env)) { + if (k.startsWith("SYS_") && v) system.add(v); + } + const admin = db.getSiblingDB("admin"); + const res = admin.runCommand({ usersInfo: 1 }); + if (res.ok !== 1) throw new Error("usersInfo failed: " + tojson(res)); + for (const u of res.users) { + const marked = (u.roles || []).some(r => r.role === env.MANAGED_ROLE && r.db === "admin"); + if (u.db !== "admin" || !marked || declared.has(u.user) || system.has(u.user)) continue; + const out = admin.runCommand({ dropUser: u.user }); + if (out.ok !== 1) throw new Error("dropUser " + u.user + " failed: " + tojson(out)); + print("dropped user " + u.user + ", no longer declared"); + } + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + privileged: false + readOnlyRootFilesystem: true + runAsNonRoot: true + resources: + requests: + cpu: 50m + memory: 128Mi + limits: + memory: 256Mi + volumeMounts: + - mountPath: /tmp + name: tmp + securityContext: + runAsNonRoot: true + runAsUser: 1001 + runAsGroup: 1001 + seccompProfile: + type: RuntimeDefault + volumes: + - name: tmp + emptyDir: {} +{{- end }} diff --git a/packages/apps/mongodb/templates/mongodb.yaml b/packages/apps/mongodb/templates/mongodb.yaml index 26e23054e..f541f0501 100644 --- a/packages/apps/mongodb/templates/mongodb.yaml +++ b/packages/apps/mongodb/templates/mongodb.yaml @@ -207,25 +207,46 @@ spec: {{- $_ := set $userRoles $user $roles }} {{- end }} {{- end }} + {{- /* + Each user reads its password from the account Secret the platform keeps + (accounts.yaml). With the Secret missing the operator skips the user, so an + account nobody seeded or minted for keeps whatever password it had. + */}} + {{- include "mongodb.accountsGuard" $ }} users: {{- range $username, $user := .Values.users }} {{- $roles := index $userRoles $username }} {{- if not $roles }} {{- fail (printf "user '%s' is not assigned to any database role in databases.*.roles" $username) }} {{- end }} - - name: {{ $username }} + - name: {{ $username | quote }} db: admin passwordSecretRef: - name: {{ $.Release.Name }}-user-{{ $username }} + name: {{ include "mongodb.accountSecret" (list $ $username) | quote }} key: password roles: {{- range $roles }} - name: {{ .name }} db: {{ .db }} {{- end }} + - name: {{ include "mongodb.managedRole" $ }} + db: admin {{- end }} {{- end }} + {{- /* + The marker role grants nothing. It tells the users this chart declared + from every other user in the database, so the post-upgrade hook + (hooks/drop-users-job.yaml) drops a user once it leaves values, which the + operator never does, and leaves alone the system users and any user the + chart did not create. Rendered with no users too, so it outlives the last + one. + */}} + roles: + - role: {{ include "mongodb.managedRole" $ }} + db: admin + privileges: [] + backup: enabled: {{ .Values.backup.enabled | default false }} image: percona/percona-backup-mongodb:2.11.0 diff --git a/packages/apps/mongodb/templates/user-secrets.yaml b/packages/apps/mongodb/templates/user-secrets.yaml deleted file mode 100644 index 8212e95f8..000000000 --- a/packages/apps/mongodb/templates/user-secrets.yaml +++ /dev/null @@ -1,17 +0,0 @@ -{{- range $username, $user := .Values.users }} -{{- $existingSecret := lookup "v1" "Secret" $.Release.Namespace (printf "%s-user-%s" $.Release.Name $username) }} ---- -apiVersion: v1 -kind: Secret -metadata: - name: {{ $.Release.Name }}-user-{{ $username }} -type: Opaque -stringData: - {{- if $user.password }} - password: {{ $user.password | quote }} - {{- else if and $existingSecret (hasKey $existingSecret.data "password") }} - password: {{ index $existingSecret.data "password" | b64dec | quote }} - {{- else }} - password: {{ randAlphaNum 16 | quote }} - {{- end }} -{{- end }} diff --git a/packages/apps/mongodb/tests/account_secret_ref_test.yaml b/packages/apps/mongodb/tests/account_secret_ref_test.yaml new file mode 100644 index 000000000..f852c2f8d --- /dev/null +++ b/packages/apps/mongodb/tests/account_secret_ref_test.yaml @@ -0,0 +1,56 @@ +suite: users read their passwords from the account Secrets + +# mongodb.yaml must name the Secret accounts.yaml's template gets, and nothing +# a value can set. + +templates: + - templates/mongodb.yaml + +release: + name: test-mongodb + namespace: tenant-test + +set: + _cluster: + cluster-domain: cozy.local + databases: + app: + roles: + admin: + - web + - Bob.Smith + +tests: + - it: points each user's passwordSecretRef at its account Secret + documentSelector: + path: kind + value: PerconaServerMongoDB + set: + users: + Bob.Smith: {} + asserts: + - equal: + path: spec.users[0].name + value: Bob.Smith + - equal: + path: spec.users[0].passwordSecretRef + value: + name: test-mongodb.bob-smith.account + key: password + + - it: ignores a password left in values + documentSelector: + path: kind + value: PerconaServerMongoDB + set: + users: + web: + password: leftover-from-values + asserts: + - equal: + path: spec.users[0].passwordSecretRef.name + value: test-mongodb.web.account + - notMatchRegex: + path: spec.users[0].passwordSecretRef.name + pattern: leftover + diff --git a/packages/apps/mongodb/tests/credential_templates_test.yaml b/packages/apps/mongodb/tests/credential_templates_test.yaml new file mode 100644 index 000000000..ab23a7246 --- /dev/null +++ b/packages/apps/mongodb/tests/credential_templates_test.yaml @@ -0,0 +1,102 @@ +suite: one CredentialTemplate per user, naming the account Secret the CR reads + +# The template is the account the credentials API mints through; its name plus +# ".account" must be the passwordSecretRef mongodb.yaml gives the user, or the +# operator reads a Secret nobody writes. + +templates: + - templates/accounts.yaml + +release: + name: test-mongodb + namespace: tenant-test + +set: + _cluster: + cluster-domain: cozy.local + databases: + app: + roles: + admin: + - web + - Bob.Smith + +tests: + - it: renders nothing without users + set: + databases: {} + asserts: + - hasDocuments: + count: 0 + + - it: renders a template per user, named for the account Secret's mapping + set: + users: + web: {} + Bob.Smith: {} + asserts: + - hasDocuments: + count: 2 + - isKind: + of: CredentialTemplate + - equal: + path: apiVersion + value: cozystack.io/v1alpha1 + - equal: + path: metadata.name + value: test-mongodb.bob-smith + documentIndex: 0 + - equal: + path: spec.username + value: Bob.Smith + documentIndex: 0 + - equal: + path: metadata.name + value: test-mongodb.web + documentIndex: 1 + + - it: stores the plaintext, with no label and no valuesPath + set: + users: + web: {} + asserts: + - equal: + path: spec.format.name + value: plaintext + - notExists: + path: spec.secret + - notExists: + path: spec.valuesPath + + - it: refuses two users that map to one account + set: + users: + web: {} + Web: {} + asserts: + - failedTemplate: + errorPattern: map to + + - it: refuses a user named like a system user + set: + users: + databaseAdmin: {} + asserts: + - failedTemplate: + errorPattern: reserved + + - it: refuses a user whose account name cannot be a Secret name + set: + users: + _web: {} + asserts: + - failedTemplate: + errorPattern: start and end with a letter or a digit + + - it: refuses a user whose account name is longer than a DNS label + set: + users: + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: {} + asserts: + - failedTemplate: + errorPattern: at most 63 characters diff --git a/packages/apps/mongodb/tests/drop_users_job_test.yaml b/packages/apps/mongodb/tests/drop_users_job_test.yaml new file mode 100644 index 000000000..9012208d8 --- /dev/null +++ b/packages/apps/mongodb/tests/drop_users_job_test.yaml @@ -0,0 +1,207 @@ +suite: users no longer declared are dropped, and only those the chart marked + +# The operator never drops a user that leaves spec.users. The chart marks the +# users it declares with a role that grants nothing, and a post-upgrade hook +# drops marked users that are no longer declared, logging in as the userAdmin +# platform account. + +templates: + - templates/hooks/drop-users-job.yaml + - templates/mongodb.yaml + +release: + name: test-mongodb + namespace: tenant-test + upgrade: true + +set: + _cluster: + cluster-domain: cozy.local + users: + web: {} + databases: + app: + roles: + admin: + - web + +tests: + - it: marks every declared user with the role that grants nothing + template: templates/mongodb.yaml + documentSelector: + path: kind + value: PerconaServerMongoDB + asserts: + - contains: + path: spec.users[0].roles + content: + name: cozystack-managed + db: admin + - equal: + path: spec.roles + value: + - role: cozystack-managed + db: admin + privileges: [] + + - it: keeps the marker role when no user is left + template: templates/mongodb.yaml + documentSelector: + path: kind + value: PerconaServerMongoDB + set: + # null rather than {}: the suite's users would be merged into an empty map. + users: null + databases: null + asserts: + - notExists: + path: spec.users + - equal: + path: spec.roles[0].role + value: cozystack-managed + + - it: runs as a post-upgrade hook bounded under the hook budget + template: templates/hooks/drop-users-job.yaml + asserts: + - isKind: + of: Job + - equal: + path: metadata.annotations["helm.sh/hook"] + value: post-upgrade + - equal: + path: spec.activeDeadlineSeconds + value: 540 + - equal: + path: spec.backoffLimit + value: 0 + + - it: logs in as the userAdmin platform account, never a tenant account + template: templates/hooks/drop-users-job.yaml + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: MONGO_USER + valueFrom: + secretKeyRef: + name: test-mongodb-percona-server-mongodb-users + key: MONGODB_USER_ADMIN_USER + - contains: + path: spec.template.spec.containers[0].env + content: + name: MONGO_PASSWORD + valueFrom: + secretKeyRef: + name: test-mongodb-percona-server-mongodb-users + key: MONGODB_USER_ADMIN_PASSWORD + - notMatchRegex: + path: spec.template.spec.containers[0].command[2] + pattern: \.account + + - it: passes the declared users and protects the system users + template: templates/hooks/drop-users-job.yaml + set: + users: + web: {} + api: {} + databases: + app: + roles: + admin: [web, api] + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: DECLARED_USERS + value: '["api","web"]' + - contains: + path: spec.template.spec.containers[0].env + content: + name: DEFAULT_SYSTEM_USERS + value: '["backup","clusterAdmin","clusterMonitor","databaseAdmin","userAdmin"]' + - contains: + path: spec.template.spec.containers[0].env + content: + name: SYS_MONGODB_DATABASE_ADMIN_USER + valueFrom: + secretKeyRef: + name: test-mongodb-percona-server-mongodb-users + key: MONGODB_DATABASE_ADMIN_USER + optional: true + + # A name YAML would read differently unquoted ("foo #bar" is "foo" and a + # comment) must reach the operator as declared, or the drop job, which + # compares against the raw keys, drops the user it sees as undeclared. + - it: declares a user to the operator under the name the drop job keeps + template: templates/mongodb.yaml + documentSelector: + path: kind + value: PerconaServerMongoDB + set: + users: + "foo #bar": {} + databases: + app: + roles: + admin: [web, "foo #bar"] + asserts: + - equal: + path: spec.users[0].name + value: "foo #bar" + + - it: keeps the declared name that the operator gets + template: templates/hooks/drop-users-job.yaml + set: + users: + "foo #bar": {} + databases: + app: + roles: + admin: [web, "foo #bar"] + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: DECLARED_USERS + value: '["foo #bar","web"]' + + - it: drops only marked, undeclared, non-system users in admin + template: templates/hooks/drop-users-job.yaml + asserts: + - matchRegex: + path: spec.template.spec.containers[0].env[?(@.name == "DROP_JS")].value + pattern: 'u\.db !== "admin" \|\| !marked \|\| declared\.has\(u\.user\) \|\| system\.has\(u\.user\)\) continue' + + - it: declares an empty list when every user is removed + template: templates/hooks/drop-users-job.yaml + set: + # null rather than {}: the suite's users would be merged into an empty map. + users: null + databases: null + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: DECLARED_USERS + value: "[]" + + - it: connects through mongos on a sharded cluster + template: templates/hooks/drop-users-job.yaml + set: + sharding: true + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: MONGO_URI + value: mongodb://test-mongodb-mongos.tenant-test.svc.cozy.local:27017/admin + + - it: is skipped while restoring from a backup + template: templates/hooks/drop-users-job.yaml + set: + bootstrap: + enabled: true + backupName: b1 + asserts: + - hasDocuments: + count: 0 diff --git a/packages/apps/mongodb/tests/mongodb_test.yaml b/packages/apps/mongodb/tests/mongodb_test.yaml index 6b48a0a5c..3a66ae43a 100644 --- a/packages/apps/mongodb/tests/mongodb_test.yaml +++ b/packages/apps/mongodb/tests/mongodb_test.yaml @@ -582,7 +582,7 @@ tests: documentIndex: 0 - equal: path: spec.users[0].passwordSecretRef.name - value: test-mongodb-user-appuser + value: test-mongodb.appuser.account documentIndex: 0 - equal: path: spec.users[0].passwordSecretRef.key diff --git a/packages/apps/mongodb/tests/no_tenant_password_test.yaml b/packages/apps/mongodb/tests/no_tenant_password_test.yaml new file mode 100644 index 000000000..5ecb61543 --- /dev/null +++ b/packages/apps/mongodb/tests/no_tenant_password_test.yaml @@ -0,0 +1,58 @@ +suite: no tenant password is rendered and the platform Secret is hidden + +# Tenant passwords come from mints only. A value left under users..password +# must not reach any rendered object, and no per-user Secret is rendered. + +templates: + - templates/accounts.yaml + - templates/credentials.yaml + - templates/mongodb.yaml + +release: + name: test-mongodb + namespace: tenant-test + +set: + _cluster: + cluster-domain: cozy.local + users: + web: + password: leftover-from-values + databases: + app: + roles: + admin: + - web + +tests: + - it: renders no per-user Secret + template: templates/credentials.yaml + asserts: + - hasDocuments: + count: 2 + - containsDocument: + apiVersion: v1 + kind: Secret + name: test-mongodb-user-web + not: true + + - it: keeps the leftover password out of the platform Secrets + template: templates/credentials.yaml + asserts: + - notMatchRegex: + path: stringData.password + pattern: leftover + documentSelector: + path: metadata.name + value: test-mongodb-credentials + + - it: renders the databaseAdmin copy as not tenant-visible + template: templates/credentials.yaml + documentSelector: + path: metadata.name + value: test-mongodb-credentials + asserts: + - equal: + path: metadata.labels + value: + internal.cozystack.io/tenantresource: "false" diff --git a/packages/apps/mongodb/tests/user-secrets_test.yaml b/packages/apps/mongodb/tests/user-secrets_test.yaml deleted file mode 100644 index 6d9fb3889..000000000 --- a/packages/apps/mongodb/tests/user-secrets_test.yaml +++ /dev/null @@ -1,78 +0,0 @@ -suite: user secrets tests - -templates: - - templates/user-secrets.yaml - -tests: - # No users configured - - it: does not render when no users defined - release: - name: test-mongodb - namespace: tenant-test - set: - users: {} - asserts: - - hasDocuments: - count: 0 - - # Single user - - it: creates secret for single user - release: - name: test-mongodb - namespace: tenant-test - set: - users: - myuser: {} - asserts: - - hasDocuments: - count: 1 - - isKind: - of: Secret - - equal: - path: metadata.name - value: test-mongodb-user-myuser - - equal: - path: type - value: Opaque - - exists: - path: stringData.password - - # Multiple users - - it: creates separate secrets for multiple users - release: - name: test-mongodb - namespace: tenant-test - set: - users: - user1: {} - user2: {} - asserts: - - hasDocuments: - count: 2 - - # User with explicit password - - it: uses explicit password when provided - release: - name: test-mongodb - namespace: tenant-test - set: - users: - myuser: - password: "mysecretpassword" - asserts: - - equal: - path: stringData.password - value: "mysecretpassword" - - # Secret naming convention - - it: follows naming convention release-user-username - release: - name: prod-db - namespace: tenant-prod - set: - users: - admin: {} - asserts: - - equal: - path: metadata.name - value: prod-db-user-admin diff --git a/packages/apps/mongodb/values.schema.json b/packages/apps/mongodb/values.schema.json index bb9e4c7f8..a8f698fe7 100644 --- a/packages/apps/mongodb/values.schema.json +++ b/packages/apps/mongodb/values.schema.json @@ -221,17 +221,11 @@ } }, "users": { - "description": "Users configuration map.", + "description": "Users configuration map. Each user is a MongoDB user the operator manages from an account Secret the platform keeps. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. A `password` key here is ignored. The names of the MongoDB system users (`backup`, `clusterAdmin`, `clusterMonitor`, `databaseAdmin`, `userAdmin`) are refused.", "type": "object", "default": {}, "additionalProperties": { - "type": "object", - "properties": { - "password": { - "description": "Password for the user (auto-generated if omitted).", - "type": "string" - } - } + "type": "object" } }, "databases": { diff --git a/packages/apps/mongodb/values.yaml b/packages/apps/mongodb/values.yaml index 7161074a8..956831ac9 100644 --- a/packages/apps/mongodb/values.yaml +++ b/packages/apps/mongodb/values.yaml @@ -116,15 +116,13 @@ shardingConfig: ## @section Users configuration ## -## @typedef {struct} User - User configuration. -## @field {string} [password] - Password for the user (auto-generated if omitted). +## @typedef {struct} User - User configuration. Users have no settings of their own; their roles come from `databases`. -## @param {map[string]User} users - Users configuration map. +## @param {map[string]User} users - Users configuration map. Each user is a MongoDB user the operator manages from an account Secret the platform keeps. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. A `password` key here is ignored. The names of the MongoDB system users (`backup`, `clusterAdmin`, `clusterMonitor`, `databaseAdmin`, `userAdmin`) are refused. users: {} ## Example: ## users: -## user1: -## password: strongpassword +## user1: {} ## user2: {} ## diff --git a/packages/core/platform/images/migrations/migrations/67 b/packages/core/platform/images/migrations/migrations/67 new file mode 100755 index 000000000..c18ebf7ff --- /dev/null +++ b/packages/core/platform/images/migrations/migrations/67 @@ -0,0 +1,177 @@ +#!/bin/sh +# Migration 67 --> 68 +# Convert MongoDB users to platform-minted credentials, first part. +# +# The converted mongodb chart renders a CredentialTemplate per user, and each +# user of the PerconaServerMongoDB reads its password from the template's +# account Secret, which cozystack-controller seeds with a random password only +# on a release marked for seeding. MongoDB computes SCRAM from the plaintext, +# so the account Secret stores the password itself (format plaintext). The old +# chart kept each user's password in its own Secret, -user-, +# under the key password, so the source is per account rather than +# -credentials, which holds only the databaseAdmin platform account +# and is left alone. This hook runs before any component chart changes version +# and writes the account Secrets, unowned, for every existing MongoDB release +# from those per-user Secrets, 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. +# +# The second part is the cozystack-credentials-migration-67 Job, which waits +# per release for its chart to switch, then strips users.*.password from the +# values and deletes any per-user Secret Helm did not prune. This hook creates +# that Job directly rather than rendering it from the platform chart: a +# chart-rendered Job has a fixed name and an image that changes every release, +# so the next platform upgrade cannot patch its immutable pod template, and +# helm-controller would wait on a Job that runs for up to 30 minutes and exits +# non-zero while any release is left out. It runs the image this hook runs as, +# read from its own pod, and is deleted and recreated rather than patched. +# +# The Job's ServiceAccount, ClusterRole and ClusterRoleBinding carry the +# migration number. Each conversion migration creates its own: one platform +# upgrade can run several of them back to back, and a shared ServiceAccount +# deleted by a later hook would cut off an earlier Job still running as it. +# The ServiceAccount is owned by the Job, so the garbage collector removes it +# with the Job; the ClusterRoleBinding and ClusterRole cannot be owned by a +# namespaced Job and are left, granting to no subject once the ServiceAccount +# is gone. 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 67 \ + --kind MongoDB \ + --format plaintext \ + --accounts-path users \ + --source-suffix -user- \ + --source-key password \ + --source-per-account + +# 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-67 \ + --namespace "$NAMESPACE" \ + --ignore-not-found +kubectl delete serviceaccount cozystack-credentials-migration-67 \ + --namespace "$NAMESPACE" \ + --ignore-not-found + +kubectl apply --filename - <&2 + exit 1 +fi +kubectl patch serviceaccount cozystack-credentials-migration-67 \ + --namespace "$NAMESPACE" \ + --type merge \ + --patch "{\"metadata\":{\"ownerReferences\":[{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\"name\":\"cozystack-credentials-migration-67\",\"uid\":\"${job_uid}\"}]}}" + +stamp_cozystack_version 68 diff --git a/packages/core/platform/values.yaml b/packages/core/platform/values.yaml index ba5ce2385..eb764c949 100644 --- a/packages/core/platform/values.yaml +++ b/packages/core/platform/values.yaml @@ -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: 67 + targetVersion: 68 # 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 diff --git a/packages/system/mongodb-rd/cozyrds/mongodb.yaml b/packages/system/mongodb-rd/cozyrds/mongodb.yaml index 83cce41dd..4c4da37e7 100644 --- a/packages/system/mongodb-rd/cozyrds/mongodb.yaml +++ b/packages/system/mongodb-rd/cozyrds/mongodb.yaml @@ -8,7 +8,7 @@ spec: singular: mongodb plural: mongodbs openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user (auto-generated if omitted).","type":"string"}}}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint).","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\"). Ignored when useSystemBucket is true (no engine-side retention on that flow).","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan).","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see https://cozystack.io/docs/v1/operations/services/backup-classes/). Requires `backup.enabled: true` (the pbm agents run on that flag); the chart refuses the combination with `enabled: false` at render time; the schema carries the same rule as a marker for the UI and for the day the apiserver enforces CEL on application schemas (cozystack/cozystack#2657), which it does not yet. A release that has not yet rendered this flag (its cluster still carries the chart's scheduled tasks and PITR) holds a BackupJob until it does, so the tenant's own storage is never injected over.","type":"boolean","default":false}},"x-kubernetes-validations":[{"message":"backup.useSystemBucket requires backup.enabled: the percona-backup-mongodb agents only run when backups are enabled","rule":"!(has(self.useSystemBucket) && self.useSystemBucket) || (has(self.enabled) && self.enabled)"}]},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of MongoDB replicas in replica set.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each MongoDB replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"MongoDB major version to deploy.","type":"string","default":"v8","enum":["v8","v7","v6"]},"sharding":{"description":"Enable sharded cluster mode. When disabled, deploys a replica set.","type":"boolean","default":false},"shardingConfig":{"description":"Configuration for sharded cluster mode.","type":"object","default":{},"required":["configServerSize","configServers","mongos"],"properties":{"configServerSize":{"description":"PVC size for config servers.","default":"3Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"configServers":{"description":"Number of config server replicas.","type":"integer","default":3},"mongos":{"description":"Number of mongos router replicas.","type":"integer","default":2},"shards":{"description":"List of shard configurations.","type":"array","default":[{"name":"rs0","replicas":3,"size":"10Gi"}],"items":{"type":"object","required":["name","replicas","size"],"properties":{"name":{"description":"Shard name.","type":"string"},"replicas":{"description":"Number of replicas in this shard.","type":"integer"},"size":{"description":"PVC size for this shard.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}}}}},"users":{"description":"Users configuration map. Each user is a MongoDB user the operator manages from an account Secret the platform keeps. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. A `password` key here is ignored. The names of the MongoDB system users (`backup`, `clusterAdmin`, `clusterMonitor`, `databaseAdmin`, `userAdmin`) are refused.","type":"object","default":{},"additionalProperties":{"type":"object"}},"databases":{"description":"Databases configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"roles":{"description":"Roles assigned to users.","type":"object","properties":{"admin":{"description":"List of users with admin privileges (readWrite + dbAdmin).","type":"array","items":{"type":"string"}},"readonly":{"description":"List of users with read-only privileges.","type":"array","items":{"type":"string"}}}}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"destinationPath":{"description":"Destination path for backups (e.g. s3://bucket/path/). Ignored when useSystemBucket is true (the driver injects the platform bucket).","type":"string","default":"s3://bucket/path/to/folder/"},"enabled":{"description":"Enable regular backups.","type":"boolean","default":false},"endpointURL":{"description":"S3 endpoint URL for uploads. Ignored when useSystemBucket is true (the strategy supplies the platform endpoint).","type":"string","default":"http://minio-gateway-service:9000"},"insecureSkipTLSVerify":{"description":"Skip TLS verification for the S3 endpoint (self-signed, e.g. in-cluster seaweedfs). Ignored when useSystemBucket is true (the platform backupStorage knob applies instead).","type":"boolean","default":false},"retentionPolicy":{"description":"Retention policy (e.g. \"30d\"). Ignored when useSystemBucket is true (no engine-side retention on that flow).","type":"string","default":"30d"},"s3AccessKey":{"description":"Access key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"s3SecretKey":{"description":"Secret key for S3 authentication. Ignored when useSystemBucket is true (credentials come from the projected cozy-backups-creds).","type":"string","default":""},"schedule":{"description":"Cron schedule for automated backups. Ignored when useSystemBucket is true (scheduling moves to the BackupClass Plan).","type":"string","default":"0 2 * * *"},"useSystemBucket":{"description":"Opt-in: back up to the platform system bucket without supplying S3 credentials. The cozy-default MongoDB BackupClass injects the storage at BackupJob time; tenants do not set s3AccessKey/s3SecretKey/destinationPath/endpointURL, and backups scope to `/`. Scheduling moves to a BackupClass Plan; `schedule`, `retentionPolicy` and PITR are ignored while this is on, and this flow has no retention yet (see https://cozystack.io/docs/v1/operations/services/backup-classes/). Requires `backup.enabled: true` (the pbm agents run on that flag); the chart refuses the combination with `enabled: false` at render time; the schema carries the same rule as a marker for the UI and for the day the apiserver enforces CEL on application schemas (cozystack/cozystack#2657), which it does not yet. A release that has not yet rendered this flag (its cluster still carries the chart's scheduled tasks and PITR) holds a BackupJob until it does, so the tenant's own storage is never injected over.","type":"boolean","default":false}},"x-kubernetes-validations":[{"message":"backup.useSystemBucket requires backup.enabled: the percona-backup-mongodb agents only run when backups are enabled","rule":"!(has(self.useSystemBucket) && self.useSystemBucket) || (has(self.enabled) && self.enabled)"}]},"bootstrap":{"description":"Bootstrap configuration.","type":"object","default":{},"required":["backupName","enabled"],"properties":{"backupName":{"description":"Name of backup to restore from.","type":"string","default":""},"enabled":{"description":"Whether to restore from a backup.","type":"boolean","default":false},"recoveryTime":{"description":"Timestamp for point-in-time recovery; empty means latest.","type":"string","default":""}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}} release: prefix: mongodb- labels: @@ -34,10 +34,9 @@ spec: # # Bounded by the enumeration, not absolute — matching is by exact name with # no globs, so a Secret a future operator version introduces stays in scope - # of the label-only include. The per-user Secrets carry the username in - # their name and cannot be enumerated at all; they and the backup - # credentials hold tenant-supplied values, so surfacing one back to its own - # tenant crosses no privilege boundary. + # of the label-only include. The account Secrets of tenant users carry the + # username in their name and cannot be enumerated; nothing selects them, + # since passwords reach tenants only through a mint on the Credential. exclude: - resourceNames: - mongodb-{{ .name }}-ca-cert @@ -58,9 +57,11 @@ spec: # enumerates the bare name alongside the -users one. - internal-mongodb-{{ .name }} - internal-mongodb-{{ .name }}-users - include: - - resourceNames: + # The databaseAdmin platform account. The chart renders it with + # internal.cozystack.io/tenantresource "false"; listing it here keeps + # it hidden should a label selector below ever match it. - mongodb-{{ .name }}-credentials + include: # The key-free trust anchor the CA-extraction controller publishes. This # is the single, engine-agnostic selector every converged engine shares; # it carries no per-release name templating. diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index 612c100ba..9afac7902 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -2368,6 +2368,7 @@ var removedUserPasswordKinds = map[string]string{ postgresKind: mintedPasswordWarning, mariadbKind: mintedPasswordWarning, clickhouseKind: mintedPasswordWarning, + mongodbKind: mintedPasswordWarning, } // mintedPasswordWarning is the warning of a kind whose user passwords the @@ -2377,6 +2378,7 @@ const mintedPasswordWarning = "spec.users[%q].password is ignored: passwords are const ( clickhouseKind = "ClickHouse" + mongodbKind = "MongoDB" postgresKind = "Postgres" mariadbKind = "MariaDB" ) diff --git a/pkg/registry/apps/application/rest_serversideapply_test.go b/pkg/registry/apps/application/rest_serversideapply_test.go index 798e7bafe..427241271 100644 --- a/pkg/registry/apps/application/rest_serversideapply_test.go +++ b/pkg/registry/apps/application/rest_serversideapply_test.go @@ -53,7 +53,7 @@ func TestConvertApplicationToHelmRelease_ServerSideApplyOverride(t *testing.T) { cases := []struct { name string ssa *bool - wantInstall *bool // Install.ServerSideApply + wantInstall *bool // Install.ServerSideApply wantUpgrade helmv2.ServerSideApplyMode // Upgrade.ServerSideApply }{ { diff --git a/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go b/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go index 8ea31055b..399c4816a 100644 --- a/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go +++ b/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go @@ -164,6 +164,7 @@ func TestWarnRemovedUserPasswords(t *testing.T) { }{ {"postgres warns", postgresKind, rawWithPassword, true}, {"mariadb warns", mariadbKind, rawWithPassword, true}, + {"mongodb warns", mongodbKind, rawWithPassword, true}, {"clickhouse warns", clickhouseKind, rawWithPassword, true}, {"other kind stays quiet", "Redis", rawWithPassword, false}, {"no password stays quiet", postgresKind, `{"users":{"app":{}}}`, false}, @@ -196,7 +197,7 @@ func TestWarnRemovedUserPasswords(t *testing.T) { // mint on the user's Credential: its -credentials Secret holds no user // password a tenant can read, so naming it sends the reader to a dead end. func TestWarnRemovedUserPasswords_PointsAtMint(t *testing.T) { - for _, kind := range []string{postgresKind, clickhouseKind, mariadbKind} { + for _, kind := range []string{postgresKind, clickhouseKind, mariadbKind, mongodbKind} { t.Run(kind, func(t *testing.T) { r := &REST{kindName: kind} app := &appsv1alpha1.Application{Spec: &apiextv1.JSON{Raw: []byte(`{"users":{"app":{"password":"hackme"}}}`)}}