feat(postgres)!: mint tenant passwords through the credentials API (#4922)

## What this PR does

Postgres passwords are no longer readable from `<release>-credentials`,
which every `use` member and every parent tenant can read today, and
`users.<name>.password` is ignored. An administrator mints a password on
the user's `Credential` and sees it once. The account Secret stores only
the SCRAM verifier, CloudNativePG applies it, and the next mint or a
revoke kills the previous password. This is the Postgres part of the
user secrets API design (cozystack/community#137) on top of #4921.

- The chart renders one `scram-sha-256` CredentialTemplate per user and
points each managed role at its account Secret.
- The CloudNativePG bootstrap secret of the `app` owner is now that
user's account Secret, so the chart no longer generates a password into
`<release>-app-owner`.
- `users.<name>.createRole: true` is refused at render. A CREATEROLE
user becomes a member of each role it creates, CloudNativePG revokes
every membership a managed role does not declare, and that revoke fails
on the dependent grant, so the role gets stuck in `cannotReconcile`.
CloudNativePG has no per-role switch to leave memberships alone.
- `credentials-migrate` and migration 64 convert existing releases. The
pre-upgrade hook applies the CredentialTemplate CRD, writes each account
Secret from the current password as a verifier, and marks the release
for seeding only when every account got one. The finish Job runs under
its own `cozystack-credentials-migration-64` identity and removes
`<release>-credentials` once the controller adopted the accounts. A
transient API error is retried before a release is recorded as left out.

Live results, on a three-node test cluster upgraded from 1.7.1, with a
client logging in every second:

- Upgrade: the migration wrote the verifiers, the controller adopted
them, the finish Job removed the old Secret, and the client logged in
1014 times with no failure. A later run that upgraded all converted
engines at once (migrations 64-71) also had no Postgres failure, for
`web` and for the database owner `app`.
- A mint returns a password that logs in over TCP; the next mint and a
revoke each kill the previous password within 2 s. A stale precondition
gets 409 with no password, and a tenant viewer can't mint.
- Removing a user removes its template, Secret and role. `createRole:
true` fails at render.
- After a mint on `app`, the password survived a primary failover and
two restarts: CloudNativePG did not reset it from the bootstrap Secret.

Breaking for users: passwords can't be read any more, so clients switch
to a minted one after the upgrade. A release with `users.*.createRole:
true` is left out of the conversion: it keeps its previous chart
version, raises `CredentialsMigrationIncomplete`, and fails every
upgrade until the flag is set to `false`.

The red `E2E (in-tree)` comes from `mariadb-2-backup-roundtrip`, where
SeaweedFS rejected a freshly granted BucketAccess key before any
Postgres code ran; the three postgres tests pass.

### 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 Postgres note for the credentials API docs
(cozystack/website#753) and an upgrade note that clients must mint and
`createRole` must be off
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up: needed, `cozystack_postgres` still sends
`users.<name>.password`
- [ ]
[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:

### Release note

```release-note
feat(postgres)!: Postgres passwords are issued through the credentials API and are no longer readable from `<release>-credentials`; `users.<name>.password` is ignored. An administrator mints a password on the user's Credential; it is shown once and applies within seconds. Existing passwords keep working through the upgrade: migration 64 converts every Postgres release and then removes the old Secret. `users.<name>.createRole: true` is no longer supported: a release that sets it is not converted, raises `CredentialsMigrationIncomplete` and fails its upgrades until the flag is set to `false`. Switch clients to minted passwords after the upgrade.
```
This commit is contained in:
Timofei Larkin authored and GitHub committed 2026-12-01 00:44:53 +03:00
commit fa9b8f07a2
53 files changed
+3617 -1041

No files matched your search

+1
View File
@@ -19,6 +19,7 @@ _repos
/cozystack-api
/cozystack-controller
/cozystack-operator
/credentials-migrate
/flux-plunger
/flux-shard-operator
/kubeovn-plunger
+3 -3
View File
@@ -65,7 +65,7 @@ type ConfigSpec struct {
// Read-replica autoscaling configuration.
// +kubebuilder:default:={}
Autoscaling Autoscaling `json:"autoscaling"`
// Users configuration map. Passwords 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 PostgreSQL role 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 SCRAM verifier, and a revoke retires the password without issuing one. A `password` key here is ignored and draws an admission warning. A password set inside PostgreSQL is reverted by the operator.
// +kubebuilder:default:={}
Users map[string]User `json:"users,omitempty"`
// Databases configuration map. The PostgreSQL system databases `postgres`, `template0` and `template1` are refused.
@@ -243,9 +243,9 @@ type TLS struct {
}
type User struct {
// Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role.
// Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself.
BypassRls bool `json:"bypassRls,omitempty"`
// Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role.
// Not supported while users are CloudNativePG managed roles: the chart refuses to render when it is true, and a release that sets it keeps its previous chart version until it is false. CloudNativePG revokes every membership a managed role is not declared to hold, including the one PostgreSQL gives a CREATEROLE user in each role it creates. Setting it to false withdraws CREATEROLE from a role that held it.
CreateRole bool `json:"createRole,omitempty"`
// Whether the user has replication privileges.
Replication bool `json:"replication,omitempty"`
+623
View File
@@ -0,0 +1,623 @@
// SPDX-License-Identifier: Apache-2.0
// Command credentials-migrate converts the accounts of an application kind
// to platform-minted credentials: "seed" from the pre-upgrade hook, "finish"
// from a Job once the charts have switched. Both take the kind's format and
// accounts map from flags, because the hook runs before the converted chart
// renders the CredentialTemplates. See design-proposals/user-secrets-api in
// cozystack/community.
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"sort"
"strings"
"time"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
apimeta "k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1"
"github.com/cozystack/cozystack/pkg/credentials/account"
"github.com/cozystack/cozystack/pkg/credentials/format"
)
// errUnresolvable marks a release whose accounts cannot be resolved from its
// values: the one cause the hook leaves a release out for. Every other error
// fails the hook, so the upgrade retries instead of switching a release whose
// Secrets were not written.
var errUnresolvable = errors.New("accounts cannot be resolved")
const (
reasonSkipped = "CredentialsMigrationSkipped"
defaultActor = "system:serviceaccount:cozy-system:cozystack-migration-hook"
// incompleteLabel on the state ConfigMap is the durable signal behind the
// CredentialsMigrationIncomplete alert: the ConfigMap outlives the finish
// Job, so an alert keyed on this label fires until the conversion is
// finished, not only for the Job's TTL. "true" while any release is left
// out, "false" once none is.
incompleteLabel = "credentials.cozystack.io/incomplete"
)
// 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
labels labelFlags
sourceSuffix string
platformKeys stringFlags
stateNamespace string
actor string
timeout time.Duration
}
type labelFlags map[string]string
func (l labelFlags) String() string { return fmt.Sprint(map[string]string(l)) }
func (l labelFlags) Set(v string) error {
k, val, ok := strings.Cut(v, "=")
if !ok || k == "" {
return fmt.Errorf("label %q is not key=value", v)
}
l[k] = val
return nil
}
type stringFlags []string
func (s *stringFlags) String() string { return strings.Join(*s, ",") }
func (s *stringFlags) Set(v string) error { *s = append(*s, v); return nil }
func (o *options) stateName() string {
return fmt.Sprintf("credentials-migration-%d", o.migration)
}
// state is what the migration keeps between the hook and the Job, in a
// ConfigMap in cozy-system named for the migration.
type state struct {
// Releases maps namespace/name to the record of the release.
Releases map[string]*releaseState `json:"releases"`
// Skipped maps namespace/name to the reason and time it was left out on
// the last run. A release leaves the map once a later run finishes it.
Skipped map[string]string `json:"skipped,omitempty"`
}
type releaseState struct {
// ChartVersion the release rendered when the hook recorded it; the Job
// acts once the release is Ready on another one.
ChartVersion string `json:"chartVersion"`
Done bool `json:"done,omitempty"`
}
func main() {
if err := run(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, "credentials-migrate:", err)
os.Exit(1)
}
}
func run(args []string) error {
if len(args) < 1 {
return errors.New("usage: credentials-migrate seed|finish [flags]")
}
cmd := args[0]
o := &options{labels: labelFlags{}}
fs := flag.NewFlagSet(cmd, flag.ContinueOnError)
fs.IntVar(&o.migration, "migration", 0, "number of the platform migration that converts the kind")
fs.StringVar(&o.kind, "kind", "", "application kind, as the HelmRelease label names it")
fs.StringVar(&o.formatName, "format", "", "password format of the kind's credentials block")
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.labels, "label", "label every account Secret carries, key=value; repeatable")
fs.StringVar(&o.sourceSuffix, "source-suffix", "-credentials", "suffix of the chart-generated Secret holding the plaintext passwords, after the release name")
fs.Var(&o.platformKeys, "platform-key", "key of the source Secret that belongs to a platform account and stays; repeatable")
fs.StringVar(&o.stateNamespace, "state-namespace", "cozy-system", "namespace of the state ConfigMap")
fs.StringVar(&o.actor, "actor", envOr("CREDENTIALS_MIGRATE_ACTOR", defaultActor), "who the record names for the migrated password")
fs.DurationVar(&o.timeout, "timeout", 10*time.Minute, "finish: how long to wait per release for the switched chart to be Ready")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if o.migration == 0 || o.kind == "" || !format.Known(o.formatName) {
return errors.New("--migration, --kind and a built-in --format are required")
}
scheme := runtime.NewScheme()
if err := corev1.AddToScheme(scheme); err != nil {
return err
}
if err := helmv2.AddToScheme(scheme); err != nil {
return err
}
c, err := client.New(ctrl.GetConfigOrDie(), client.Options{Scheme: scheme})
if err != nil {
return fmt.Errorf("build client: %w", err)
}
m := &migrator{c: c, o: o, now: time.Now}
ctx := context.Background()
switch cmd {
case "seed":
return m.seed(ctx)
case "finish":
return m.finish(ctx)
}
return fmt.Errorf("unknown command %q: want seed or finish", cmd)
}
func envOr(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
type migrator struct {
c client.Client
o *options
now func() time.Time
}
// seed records every release of the kind and writes the account Secrets it
// still lacks from the chart-generated passwords. A release whose accounts
// cannot be resolved is left out with an Event; one whose source Secret is
// gone is recorded, since the Job still has to switch it, and its accounts
// get their Secrets from the first mint.
func (m *migrator) seed(ctx context.Context) error {
st, err := m.loadState(ctx)
if err != nil {
return err
}
releases, err := m.releases(ctx)
if err != nil {
return err
}
for i := range releases {
hr := &releases[i]
key := hr.Namespace + "/" + hr.Name
rec, known := st.Releases[key]
if !known {
rec = &releaseState{ChartVersion: chartVersion(hr)}
st.Releases[key] = rec
}
if err := m.seedRelease(ctx, hr); err != nil {
if !errors.Is(err, errUnresolvable) {
if serr := m.saveState(ctx, st); serr != nil {
return errors.Join(fmt.Errorf("%s: %w", key, err), serr)
}
return fmt.Errorf("%s: %w", key, err)
}
m.skip(ctx, st, hr, err)
continue
}
delete(st.Skipped, key)
fmt.Printf("%s: recorded chart version %q\n", key, rec.ChartVersion)
}
return m.saveState(ctx, st)
}
// finish converts every recorded release once its chart has switched, and
// exits non-zero while any is left out, so one place shows what remains.
func (m *migrator) finish(ctx context.Context) error {
st, err := m.loadState(ctx)
if err != nil {
return err
}
keys := make([]string, 0, len(st.Releases))
for k := range st.Releases {
keys = append(keys, k)
}
sort.Strings(keys)
for _, key := range keys {
rec := st.Releases[key]
if rec.Done {
continue
}
ns, name, _ := strings.Cut(key, "/")
hr := &helmv2.HelmRelease{}
if err := m.c.Get(ctx, types.NamespacedName{Namespace: ns, Name: name}, hr); err != nil {
if apierrors.IsNotFound(err) {
// Deleted since the hook: nothing left to convert.
rec.Done = true
delete(st.Skipped, key)
continue
}
return err
}
if err := m.finishReleaseRetrying(ctx, hr, rec); err != nil {
m.leaveOut(ctx, st, hr, err)
if err := m.saveState(ctx, st); err != nil {
return err
}
continue
}
rec.Done = true
delete(st.Skipped, key)
fmt.Printf("%s: converted\n", key)
if err := m.saveState(ctx, st); err != nil {
return err
}
}
if err := m.saveState(ctx, st); err != nil {
return err
}
if len(st.Skipped) > 0 {
var left []string
for k, why := range st.Skipped {
left = append(left, k+": "+why)
}
sort.Strings(left)
return fmt.Errorf("%d release(s) left out:\n %s", len(left), strings.Join(left, "\n "))
}
return nil
}
func (m *migrator) finishRelease(ctx context.Context, hr *helmv2.HelmRelease, rec *releaseState) error {
// Seed again first: an account whose Secret is still missing, as after an
// interrupted hook, gets it here while the plaintext still exists.
if err := m.seedRelease(ctx, hr); err != nil {
return err
}
// Without a recorded version nothing tells the old chart from the new
// one, and retiring the source under the old chart takes its passwords.
if rec.ChartVersion == "" {
return errors.New("no chart version was recorded before the upgrade, so the switch cannot be confirmed; check that the release renders the converted chart and finish it by hand")
}
deadline := m.now().Add(m.o.timeout)
for {
if apimeta.IsStatusConditionTrue(hr.Status.Conditions, "Ready") && chartVersion(hr) != "" && chartVersion(hr) != rec.ChartVersion {
break
}
if m.now().After(deadline) {
return fmt.Errorf("not Ready on a chart version other than %q after %s (current %q)", rec.ChartVersion, m.o.timeout, chartVersion(hr))
}
time.Sleep(10 * time.Second)
if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), hr); err != nil {
return err
}
}
if err := m.stripPasswords(ctx, hr); err != nil {
return fmt.Errorf("strip passwords from values: %w", err)
}
return m.retireSource(ctx, hr)
}
// seedRelease writes the account Secrets the release lacks, unowned: the
// CredentialTemplate controller adopts them once the converted chart renders
// the templates. Once every declared account has its Secret, it marks the
// release for seeding, so accounts added later get theirs from the
// controller. A release where an account is left without a Secret, its
// plaintext missing or one that would not carry over, stays unmarked: a seeded
// random password would lock out the clients that use the old one, so that
// account waits for a mint. A release that declares no account has no
// plaintext to lose, so it is marked whether or not its source exists: the
// chart renders the source only once there is a user, and without the mark
// 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)
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
}
}
now := metav1.NewTime(m.now())
complete := true
for _, acc := range accounts {
name := account.SecretName(hr.Name, acc.Mapped)
cur := &corev1.Secret{}
err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: name}, cur)
switch {
case err == nil && account.IsAccountSecret(cur) && string(cur.Data[account.UsernameKey]) == acc.Username:
continue
case err == nil && metav1.GetControllerOf(cur) == nil:
// Left from a deleted application of the same name, or not an
// account Secret at all: the operator would apply whatever it
// holds, so this one replaces it.
if err := m.c.Delete(ctx, cur, client.Preconditions{UID: &cur.UID}); err != nil && !apierrors.IsNotFound(err) {
return fmt.Errorf("replace stale %s: %w", name, err)
}
case err == nil:
fmt.Printf("%s/%s: %s exists and is not an account Secret this conversion wrote; leaving it and the account %q alone\n", hr.Namespace, hr.Name, name, acc.Username)
complete = false
continue
case !apierrors.IsNotFound(err):
return err
}
plaintext, ok := source.Data[acc.Username]
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)
complete = false
continue
}
if !format.CarriesOver(m.o.formatName, string(plaintext)) {
// 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)
complete = false
continue
}
stored, err := format.Encode(m.o.formatName, string(plaintext))
if err != nil {
return err
}
sec := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: hr.Namespace,
Labels: account.Labels(m.o.labels),
Annotations: map[string]string{account.FormatAnnotation: m.o.formatName},
},
Type: corev1.SecretTypeBasicAuth,
Data: map[string][]byte{
account.UsernameKey: []byte(acc.Username),
account.PasswordKey: []byte(stored),
},
}
account.WriteRecord(sec, account.Record{}.Apply(corev1alpha1.CredentialOperationMigrate, now, m.o.actor))
if err := m.c.Create(ctx, sec); err != nil {
return fmt.Errorf("create %s: %w", name, err)
}
fmt.Printf("%s/%s: migrated account %q into %s\n", hr.Namespace, hr.Name, acc.Username, name)
}
if !complete || hr.Annotations[account.SeedAnnotation] == "true" {
return nil
}
patch := client.MergeFrom(hr.DeepCopy())
if hr.Annotations == nil {
hr.Annotations = map[string]string{}
}
hr.Annotations[account.SeedAnnotation] = "true"
if err := m.c.Patch(ctx, hr, patch); err != nil {
return fmt.Errorf("mark for seeding: %w", err)
}
return nil
}
// 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,
// which the converted chart would not render, leave the release unresolvable.
func resolveAccounts(hr *helmv2.HelmRelease, path string, refuse []string) ([]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)
names := make([]string, 0, len(users))
for name := range users {
names = append(names, name)
}
sort.Strings(names)
var accounts []account.Account
byMapped := map[string]string{}
for _, name := range names {
if u, ok := users[name].(map[string]any); ok {
for _, field := range refuse {
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)
}
}
}
mapped, err := account.MapName(name)
if err != nil {
return nil, err
}
if other, dup := byMapped[mapped]; dup {
return nil, fmt.Errorf("users %q and %q both map to the name %q", other, name, mapped)
}
byMapped[mapped] = name
accounts = append(accounts, account.Account{Username: name, Mapped: mapped})
}
return accounts, nil
}
// lookup walks a dotted path through nested maps.
func lookup(values map[string]any, path string) any {
var cur any = values
for _, key := range strings.Split(path, ".") {
m, ok := cur.(map[string]any)
if !ok {
return nil
}
cur, ok = m[key]
if !ok {
return nil
}
}
return cur
}
// stripPasswords removes a password left under any key of the accounts map in
// the release's values.
func (m *migrator) stripPasswords(ctx context.Context, hr *helmv2.HelmRelease) error {
if hr.Spec.Values == nil || len(hr.Spec.Values.Raw) == 0 {
return nil
}
var values map[string]any
if err := json.Unmarshal(hr.Spec.Values.Raw, &values); err != nil {
return err
}
users, _ := lookup(values, m.o.accountsPath).(map[string]any)
changed := false
for name, raw := range users {
u, ok := raw.(map[string]any)
if !ok {
continue
}
if _, has := u["password"]; has {
delete(u, "password")
changed = true
fmt.Printf("%s/%s: removed %s.%s.password from the values\n", hr.Namespace, hr.Name, m.o.accountsPath, name)
}
}
if !changed {
return nil
}
raw, err := json.Marshal(values)
if err != nil {
return err
}
patch := client.MergeFrom(hr.DeepCopy())
hr.Spec.Values.Raw = raw
return m.c.Patch(ctx, hr, patch)
}
// retireSource removes the tenant keys from the chart-generated Secret, which
// 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 {
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 nil
}
return err
}
keep := map[string]bool{}
for _, k := range m.o.platformKeys {
keep[k] = true
}
remaining := map[string][]byte{}
for k, v := range source.Data {
if keep[k] {
remaining[k] = v
}
}
if len(remaining) == 0 {
if err := m.c.Delete(ctx, source, client.Preconditions{UID: &source.UID}); err != nil && !apierrors.IsNotFound(err) {
return err
}
fmt.Printf("%s/%s: deleted %s\n", hr.Namespace, hr.Name, source.Name)
return nil
}
if len(remaining) == len(source.Data) {
return nil
}
patch := client.MergeFrom(source.DeepCopy())
source.Data = remaining
if err := m.c.Patch(ctx, source, patch); err != nil {
return err
}
fmt.Printf("%s/%s: removed the tenant keys from %s\n", hr.Namespace, hr.Name, source.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{
appsv1alpha1.ApplicationGroupLabel: appsv1alpha1.GroupName,
appsv1alpha1.ApplicationKindLabel: m.o.kind,
}); err != nil {
return nil, err
}
return list.Items, nil
}
// skip leaves a release out: logged, recorded in the state, and announced
// with an Event on the HelmRelease, so the cause is visible where the
// release is.
func (m *migrator) skip(ctx context.Context, st *state, hr *helmv2.HelmRelease, cause error) {
key := hr.Namespace + "/" + hr.Name
why := fmt.Sprintf("%s at %s", cause.Error(), m.now().UTC().Format(time.RFC3339))
st.Skipped[key] = why
fmt.Fprintf(os.Stderr, "%s: left out: %v\n", key, cause)
ev := &corev1.Event{
ObjectMeta: metav1.ObjectMeta{GenerateName: hr.Name + ".", Namespace: hr.Namespace},
InvolvedObject: corev1.ObjectReference{
APIVersion: helmv2.GroupVersion.String(), Kind: helmv2.HelmReleaseKind,
Name: hr.Name, Namespace: hr.Namespace, UID: hr.UID,
},
Reason: reasonSkipped,
Message: fmt.Sprintf("credentials migration %d left this release out: %v", m.o.migration, cause),
Type: corev1.EventTypeWarning,
Source: corev1.EventSource{Component: "credentials-migrate"},
FirstTimestamp: metav1.NewTime(m.now()),
LastTimestamp: metav1.NewTime(m.now()),
Count: 1,
}
if err := m.c.Create(ctx, ev); err != nil {
fmt.Fprintf(os.Stderr, "%s: failed to record event: %v\n", key, err)
}
}
func (m *migrator) loadState(ctx context.Context) (*state, error) {
st := &state{Releases: map[string]*releaseState{}, Skipped: map[string]string{}}
cm := &corev1.ConfigMap{}
err := m.c.Get(ctx, types.NamespacedName{Namespace: m.o.stateNamespace, Name: m.o.stateName()}, cm)
if apierrors.IsNotFound(err) {
return st, nil
}
if err != nil {
return nil, err
}
if raw := cm.Data["state"]; raw != "" {
if err := json.Unmarshal([]byte(raw), st); err != nil {
return nil, fmt.Errorf("decode state ConfigMap %s: %w", cm.Name, err)
}
}
if st.Releases == nil {
st.Releases = map[string]*releaseState{}
}
if st.Skipped == nil {
st.Skipped = map[string]string{}
}
return st, nil
}
func (m *migrator) saveState(ctx context.Context, st *state) error {
raw, err := json.MarshalIndent(st, "", " ")
if err != nil {
return err
}
cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: m.o.stateNamespace, Name: m.o.stateName()}}
_, err = ctrl.CreateOrUpdate(ctx, m.c, cm, func() error {
if cm.Data == nil {
cm.Data = map[string]string{}
}
cm.Data["state"] = string(raw)
if cm.Labels == nil {
cm.Labels = map[string]string{}
}
if len(st.Skipped) > 0 {
cm.Labels[incompleteLabel] = "true"
} else {
cm.Labels[incompleteLabel] = "false"
}
return nil
})
return err
}
func chartVersion(hr *helmv2.HelmRelease) string {
if s := hr.Status.History.Latest(); s != nil {
return s.ChartVersion
}
return ""
}
+458
View File
@@ -0,0 +1,458 @@
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
corev1 "k8s.io/api/core/v1"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1"
"github.com/cozystack/cozystack/pkg/credentials/account"
"github.com/cozystack/cozystack/pkg/credentials/format"
)
func newMigrator(t *testing.T, objs ...client.Object) *migrator {
t.Helper()
return newMigratorWith(t, nil, objs...)
}
// newMigratorWith builds the migrator on a client whose calls go through funcs.
func newMigratorWith(t *testing.T, funcs *interceptor.Funcs, objs ...client.Object) *migrator {
t.Helper()
scheme := runtime.NewScheme()
if err := corev1.AddToScheme(scheme); err != nil {
t.Fatal(err)
}
if err := helmv2.AddToScheme(scheme); err != nil {
t.Fatal(err)
}
b := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objs...).WithStatusSubresource(&helmv2.HelmRelease{})
if funcs != nil {
b = b.WithInterceptorFuncs(*funcs)
}
c := b.Build()
o := &options{
migration: 64, kind: "Postgres", formatName: format.ScramSHA256, accountsPath: "users",
labels: labelFlags{"cnpg.io/reload": "true"}, sourceSuffix: "-credentials",
stateNamespace: "cozy-system", actor: "migration", timeout: -time.Second,
}
return &migrator{c: c, o: o, now: func() time.Time { return time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC) }}
}
func release(values string, chartVersion string, ready bool) *helmv2.HelmRelease {
hr := &helmv2.HelmRelease{
ObjectMeta: metav1.ObjectMeta{Name: "postgres-orders", Namespace: "tenant-foo", UID: "hr-uid", Labels: map[string]string{
appsv1alpha1.ApplicationGroupLabel: appsv1alpha1.GroupName,
appsv1alpha1.ApplicationKindLabel: "Postgres",
appsv1alpha1.ApplicationNameLabel: "orders",
}},
Spec: helmv2.HelmReleaseSpec{Values: &apiextv1.JSON{Raw: []byte(values)}},
}
if chartVersion != "" {
hr.Status.History = helmv2.Snapshots{{Version: 1, ChartVersion: chartVersion, Status: "deployed"}}
}
if ready {
hr.Status.Conditions = []metav1.Condition{{Type: "Ready", Status: metav1.ConditionTrue, Reason: "x", LastTransitionTime: metav1.Now()}}
}
return hr
}
func sourceSecret(data map[string]string) *corev1.Secret {
sec := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "postgres-orders-credentials", Namespace: "tenant-foo"}, Data: map[string][]byte{}}
for k, v := range data {
sec.Data[k] = []byte(v)
}
return sec
}
func (m *migrator) secret(t *testing.T, name string) (*corev1.Secret, bool) {
t.Helper()
sec := &corev1.Secret{}
err := m.c.Get(context.Background(), types.NamespacedName{Namespace: "tenant-foo", Name: name}, sec)
if apierrors.IsNotFound(err) {
return nil, false
}
if err != nil {
t.Fatal(err)
}
return sec, true
}
func TestSeedRecordsAndMigrates(t *testing.T) {
ctx := context.Background()
m := newMigrator(t, release(`{"users":{"web":{},"Api.1":{}}}`, "0.1.0", true), sourceSecret(map[string]string{"web": "hunter2", "Api.1": "secret"}))
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
st, err := m.loadState(ctx)
if err != nil {
t.Fatal(err)
}
rec := st.Releases["tenant-foo/postgres-orders"]
if rec == nil || rec.ChartVersion != "0.1.0" || rec.Done || len(st.Skipped) != 0 {
t.Fatalf("state = %+v", st)
}
for _, c := range []struct{ secret, user, plain string }{{"postgres-orders.web.account", "web", "hunter2"}, {"postgres-orders.api-1.account", "Api.1", "secret"}} {
sec, ok := m.secret(t, c.secret)
if !ok {
t.Fatalf("%s not written", c.secret)
}
if string(sec.Data[account.UsernameKey]) != c.user || !strings.HasPrefix(string(sec.Data[account.PasswordKey]), "SCRAM-SHA-256$4096:") {
t.Fatalf("%s data = %q", c.secret, sec.Data)
}
if strings.Contains(string(sec.Data[account.PasswordKey]), c.plain) {
t.Fatal("the plaintext must not be stored")
}
// Unowned: the CredentialTemplate controller adopts it once the
// converted chart renders the template.
if sec.Labels["cnpg.io/reload"] != "true" || sec.Labels[account.AccountLabel] != "true" || len(sec.OwnerReferences) != 0 || sec.Annotations[account.FormatAnnotation] != "scram-sha-256" {
t.Fatalf("%s meta = %+v", c.secret, sec.ObjectMeta)
}
r := account.ReadRecord(sec)
if r.Origin != corev1alpha1.CredentialOriginMigrated || r.By != "migration" || len(r.History) != 1 || r.History[0].Operation != corev1alpha1.CredentialOperationMigrate {
t.Fatalf("%s record = %+v", c.secret, r)
}
}
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 whose accounts all got a Secret must be marked for seeding")
}
// A second run keeps what it wrote.
before, _ := m.secret(t, "postgres-orders.web.account")
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
after, _ := m.secret(t, "postgres-orders.web.account")
if string(after.Data[account.PasswordKey]) != string(before.Data[account.PasswordKey]) {
t.Fatal("seed must be idempotent")
}
}
func TestSeedLeavesOutUnresolvableAndRecordsMissingSource(t *testing.T) {
ctx := context.Background()
colliding := release(`{"users":{"web_app":{},"web-app":{}}}`, "0.1.0", true)
m := newMigrator(t, colliding)
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
st, _ := m.loadState(ctx)
if why := st.Skipped["tenant-foo/postgres-orders"]; !strings.Contains(why, "both map to the name") {
t.Fatalf("skipped = %v", st.Skipped)
}
evs := &corev1.EventList{}
if err := m.c.List(ctx, evs, client.InNamespace("tenant-foo")); err != nil || len(evs.Items) != 1 || evs.Items[0].Reason != reasonSkipped {
t.Fatalf("events = %+v err=%v", evs.Items, err)
}
// No source Secret: recorded, nothing seeded, not skipped.
m = newMigrator(t, release(`{"users":{"web":{}}}`, "0.1.0", true))
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
st, _ = m.loadState(ctx)
if st.Releases["tenant-foo/postgres-orders"] == nil || len(st.Skipped) != 0 {
t.Fatalf("state = %+v", st)
}
if _, ok := m.secret(t, "postgres-orders.web.account"); ok {
t.Fatal("nothing to seed from")
}
}
func TestSeedMarksAReleaseWithoutUsersAndWithoutASource(t *testing.T) {
ctx := context.Background()
// The chart renders the source only once there is a user.
m := newMigrator(t, release(`{"users":{}}`, "0.1.0", 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 TestFinishWaitsForTheSwitchThenStripsAndRetires(t *testing.T) {
ctx := context.Background()
hr := release(`{"users":{"web":{"password":"leftover"}},"size":"10Gi"}`, "0.1.0", true)
m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2"}))
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
// Still on the recorded chart version: left out, reported, state kept.
err := m.finish(ctx)
if err == nil || !strings.Contains(err.Error(), "1 release(s) left out") {
t.Fatalf("finish on an unswitched release: %v", err)
}
if _, ok := m.secret(t, "postgres-orders-credentials"); !ok {
t.Fatal("the source must survive until the chart has switched")
}
// Switched and Ready.
cur := &helmv2.HelmRelease{}
if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil {
t.Fatal(err)
}
cur.Status.History = helmv2.Snapshots{{Version: 2, ChartVersion: "0.2.0", Status: "deployed"}}
if err := m.c.Status().Update(ctx, cur); err != nil {
t.Fatal(err)
}
if err := m.finish(ctx); err != nil {
t.Fatal(err)
}
st, _ := m.loadState(ctx)
if rec := st.Releases["tenant-foo/postgres-orders"]; rec == nil || !rec.Done || len(st.Skipped) != 0 {
t.Fatalf("state = %+v", st)
}
if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil {
t.Fatal(err)
}
var values map[string]any
if err := json.Unmarshal(cur.Spec.Values.Raw, &values); err != nil {
t.Fatal(err)
}
if _, has := values["users"].(map[string]any)["web"].(map[string]any)["password"]; has || values["size"] != "10Gi" {
t.Fatalf("values = %v", values)
}
if _, ok := m.secret(t, "postgres-orders-credentials"); ok {
t.Fatal("the source Secret of a kind without platform accounts must be deleted")
}
if _, ok := m.secret(t, "postgres-orders.web.account"); !ok {
t.Fatal("the account Secret must stay")
}
}
func TestRetireSourceKeepsPlatformKeys(t *testing.T) {
ctx := context.Background()
hr := release(`{"users":{"web":{}}}`, "0.1.0", true)
m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2", "root": "toor"}))
m.o.platformKeys = stringFlags{"root"}
if err := m.retireSource(ctx, hr); err != nil {
t.Fatal(err)
}
sec, ok := m.secret(t, "postgres-orders-credentials")
if !ok || string(sec.Data["root"]) != "toor" || len(sec.Data) != 1 {
t.Fatalf("source = %v", sec)
}
}
// A transient API error must fail the hook, so the upgrade retries: left out
// as a skip, the chart would switch and take the plaintext with it.
func TestSeedFailsClosedOnAnAPIError(t *testing.T) {
ctx := context.Background()
m := newMigratorWith(t, &interceptor.Funcs{
Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error {
if sec, ok := obj.(*corev1.Secret); ok && strings.HasSuffix(sec.Name, ".account") {
return apierrors.NewServiceUnavailable("etcd is busy")
}
return cl.Create(ctx, obj, opts...)
},
}, release(`{"users":{"web":{}}}`, "0.1.0", true), sourceSecret(map[string]string{"web": "hunter2"}))
if err := m.seed(ctx); err == nil || !strings.Contains(err.Error(), "etcd is busy") {
t.Fatalf("seed = %v, want the API error", err)
}
st, err := m.loadState(ctx)
if err != nil {
t.Fatal(err)
}
if len(st.Skipped) != 0 {
t.Fatalf("a transient error must not be recorded as a skip: %v", st.Skipped)
}
}
func TestFinishHoldsAReleaseWithNoRecordedVersion(t *testing.T) {
ctx := context.Background()
m := newMigrator(t, release(`{"users":{"web":{}}}`, "", true), sourceSecret(map[string]string{"web": "hunter2"}))
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
m.switchChart(t, "0.2.0", true)
if err := m.finish(ctx); err == nil {
t.Fatal("finish must report a release it cannot confirm switched")
}
if _, ok := m.secret(t, "postgres-orders-credentials"); !ok {
t.Fatal("the source must stay while the switch cannot be confirmed")
}
}
func TestFinishWaitsForReady(t *testing.T) {
ctx := context.Background()
m := newMigrator(t, release(`{"users":{"web":{"password":"leftover"}}}`, "0.1.0", true), sourceSecret(map[string]string{"web": "hunter2"}))
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
// On the new chart, but the upgrade has not succeeded.
m.switchChart(t, "0.2.0", false)
if err := m.finish(ctx); err == nil {
t.Fatal("finish must hold a release that is not Ready")
}
if _, ok := m.secret(t, "postgres-orders-credentials"); !ok {
t.Fatal("the source must stay until the release is Ready on the new chart")
}
}
func TestFinishTreatsADeletedReleaseAsDone(t *testing.T) {
ctx := context.Background()
hr := release(`{"users":{"web":{}}}`, "0.1.0", true)
m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2"}))
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
if err := m.c.Delete(ctx, hr); err != nil {
t.Fatal(err)
}
if err := m.finish(ctx); err != nil {
t.Fatalf("finish = %v, want nothing left to convert", err)
}
}
func TestSeedKeepsTheFirstRecordedVersion(t *testing.T) {
ctx := context.Background()
m := newMigrator(t, release(`{"users":{"web":{}}}`, "0.1.0", true), sourceSecret(map[string]string{"web": "hunter2"}))
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
// The hook runs again after the chart has moved on, as a retried upgrade does.
m.switchChart(t, "0.2.0", true)
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
st, _ := m.loadState(ctx)
if v := st.Releases["tenant-foo/postgres-orders"].ChartVersion; v != "0.1.0" {
t.Fatalf("recorded version = %q, want the first one", v)
}
}
func TestSeedReplacesAForeignSecretAndSkipsAMissingPlaintext(t *testing.T) {
ctx := context.Background()
foreign := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "postgres-orders.web.account", Namespace: "tenant-foo"},
Data: map[string][]byte{account.UsernameKey: []byte("web"), account.PasswordKey: []byte("planted")}}
m := newMigrator(t, release(`{"users":{"web":{},"api":{}}}`, "0.1.0", true), foreign, sourceSecret(map[string]string{"web": "hunter2"}))
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
sec, _ := m.secret(t, "postgres-orders.web.account")
if string(sec.Data[account.PasswordKey]) == "planted" || !account.IsAccountSecret(sec) {
t.Fatal("a Secret that is not the release's own must be replaced, or the operator applies its verifier")
}
if _, ok := m.secret(t, "postgres-orders.api.account"); ok {
t.Fatal("an account with no plaintext to migrate is left to its first mint")
}
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 with an account left for a mint must stay unmarked, or the controller seeds over the password its clients use")
}
}
func TestSeedSkipsAPasswordThatDoesNotCarryOver(t *testing.T) {
ctx := context.Background()
// PostgreSQL runs SASLprep on the presented password at login, and it
// removes a soft hyphen (U+00AD), so a SCRAM verifier built here from the
// raw bytes would never authenticate the password. The account is left to
// its first mint rather than stored as a verifier nobody can log in with.
m := newMigrator(t, release(`{"users":{"ascii":{},"weird":{}}}`, "0.1.0", true), sourceSecret(map[string]string{"ascii": "hunter2", "weird": "I­X"}))
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
if _, ok := m.secret(t, "postgres-orders.ascii.account"); !ok {
t.Fatal("a printable-ASCII password must carry over")
}
if _, ok := m.secret(t, "postgres-orders.weird.account"); ok {
t.Fatal("a password SASLprep would rewrite must be left to its first mint, not stored")
}
st, _ := m.loadState(ctx)
if st.Releases["tenant-foo/postgres-orders"] == nil || len(st.Skipped) != 0 {
t.Fatalf("the release is recorded and not skipped: %+v", st)
}
}
// switchChart moves the release to another chart version, Ready or not.
func (m *migrator) switchChart(t *testing.T, version string, ready bool) {
t.Helper()
ctx := context.Background()
cur := &helmv2.HelmRelease{}
if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, cur); err != nil {
t.Fatal(err)
}
cur.Status.History = helmv2.Snapshots{{Version: 2, ChartVersion: version, Status: "deployed"}}
status := metav1.ConditionFalse
if ready {
status = metav1.ConditionTrue
}
cur.Status.Conditions = []metav1.Condition{{Type: "Ready", Status: status, Reason: "x", LastTransitionTime: metav1.Now()}}
if err := m.c.Status().Update(ctx, cur); err != nil {
t.Fatal(err)
}
}
func TestSaveStateLabelsIncompleteForTheAlert(t *testing.T) {
ctx := context.Background()
m := newMigrator(t)
readLabel := func() string {
cm := &corev1.ConfigMap{}
if err := m.c.Get(ctx, types.NamespacedName{Namespace: "cozy-system", Name: m.o.stateName()}, cm); err != nil {
t.Fatalf("get state ConfigMap: %v", err)
}
return cm.Labels[incompleteLabel]
}
// A release left out marks the conversion incomplete, so the durable
// CredentialsMigrationIncomplete alert fires on the ConfigMap label.
if err := m.saveState(ctx, &state{Releases: map[string]*releaseState{}, Skipped: map[string]string{"tenant-foo/postgres-orders": "left out at 2026-10-14T12:00:00Z"}}); err != nil {
t.Fatal(err)
}
if got := readLabel(); got != "true" {
t.Fatalf("%s = %q, want true while a release is skipped", incompleteLabel, got)
}
// None left out clears the label, so the alert resolves.
if err := m.saveState(ctx, &state{Releases: map[string]*releaseState{}, Skipped: map[string]string{}}); err != nil {
t.Fatal(err)
}
if got := readLabel(); got != "false" {
t.Fatalf("%s = %q, want false once none is skipped", incompleteLabel, got)
}
}
func TestSeedLeavesOutAReleaseWithARefusedFlag(t *testing.T) {
ctx := context.Background()
m := newMigrator(t, release(`{"users":{"web":{},"migrator":{"createRole":true}}}`, "0.1.0", true), sourceSecret(map[string]string{"web": "hunter2", "migrator": "secret"}))
m.o.refuseFlags = stringFlags{"createRole"}
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
st, err := m.loadState(ctx)
if err != nil {
t.Fatal(err)
}
if _, left := st.Skipped["tenant-foo/postgres-orders"]; !left {
t.Fatalf("state = %+v, want the release left out", st)
}
if _, ok := m.secret(t, "postgres-orders.web.account"); ok {
t.Fatal("a release the converted chart refuses must not be converted in part")
}
}
+99
View File
@@ -0,0 +1,99 @@
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"errors"
"fmt"
"io"
"net"
"os"
"strings"
"syscall"
"time"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// reasonRetrying names an Event for a release that hit a transient error and
// is converted on a later attempt, unlike reasonSkipped, which needs a person.
const reasonRetrying = "CredentialsMigrationRetrying"
// transientAttempts and transientDelay bound the in-process retries of a
// release that hit a transient error, before the Job's own restart retries it.
var (
transientAttempts = 3
transientDelay = 10 * time.Second
)
// isTransient reports whether err comes from the API server or the
// connection to it rather than from the release: retrying the same release
// can succeed without anyone changing anything.
func isTransient(err error) bool {
switch {
case apierrors.IsServerTimeout(err), apierrors.IsTimeout(err), apierrors.IsTooManyRequests(err),
apierrors.IsServiceUnavailable(err), apierrors.IsInternalError(err), apierrors.IsUnexpectedServerError(err),
apierrors.IsConflict(err):
return true
case errors.Is(err, io.EOF), errors.Is(err, io.ErrUnexpectedEOF),
errors.Is(err, syscall.ECONNRESET), errors.Is(err, syscall.ECONNREFUSED), errors.Is(err, syscall.EPIPE):
return true
}
var netErr net.Error
if errors.As(err, &netErr) {
return true
}
// client-go wraps a body read that failed mid-response this way.
return strings.Contains(err.Error(), "unexpected error when reading response body")
}
// finishReleaseRetrying runs finishRelease, retrying a transient error on a
// fresh read of the release.
func (m *migrator) finishReleaseRetrying(ctx context.Context, hr *helmv2.HelmRelease, rec *releaseState) error {
var err error
for attempt := 1; ; attempt++ {
if err = m.finishRelease(ctx, hr, rec); err == nil || !isTransient(err) || attempt >= transientAttempts {
return err
}
fmt.Fprintf(os.Stderr, "%s/%s: transient error, retrying: %v\n", hr.Namespace, hr.Name, err)
time.Sleep(transientDelay)
if gerr := m.c.Get(ctx, client.ObjectKeyFromObject(hr), hr); gerr != nil && !isTransient(gerr) {
return gerr
}
}
}
// leaveOut records a release finish could not convert. A transient error is
// recorded for the alert like any other, but announced as a retry rather
// than as a release left out, since the Job's restart converts it.
func (m *migrator) leaveOut(ctx context.Context, st *state, hr *helmv2.HelmRelease, cause error) {
if !isTransient(cause) {
m.skip(ctx, st, hr, cause)
return
}
key := hr.Namespace + "/" + hr.Name
st.Skipped[key] = fmt.Sprintf("transient error, retried by the Job: %s at %s", cause.Error(), m.now().UTC().Format(time.RFC3339))
fmt.Fprintf(os.Stderr, "%s: transient error, retried at the next attempt: %v\n", key, cause)
ev := &corev1.Event{
ObjectMeta: metav1.ObjectMeta{GenerateName: hr.Name + ".", Namespace: hr.Namespace},
InvolvedObject: corev1.ObjectReference{
APIVersion: helmv2.GroupVersion.String(), Kind: helmv2.HelmReleaseKind,
Name: hr.Name, Namespace: hr.Namespace, UID: hr.UID,
},
Reason: reasonRetrying,
Message: fmt.Sprintf("credentials migration %d hit a transient error on this release and retries it: %v", m.o.migration, cause),
Type: corev1.EventTypeNormal,
Source: corev1.EventSource{Component: "credentials-migrate"},
FirstTimestamp: metav1.NewTime(m.now()),
LastTimestamp: metav1.NewTime(m.now()),
Count: 1,
}
if err := m.c.Create(ctx, ev); err != nil {
fmt.Fprintf(os.Stderr, "%s: failed to record event: %v\n", key, err)
}
}
+126
View File
@@ -0,0 +1,126 @@
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"fmt"
"syscall"
"testing"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
)
// readReset is what client-go returns when the connection drops mid-body.
var readReset = fmt.Errorf("unexpected error when reading response body. Please retry. Original error: %w", syscall.ECONNRESET)
func eventReasons(t *testing.T, m *migrator) map[string]int {
t.Helper()
evs := &corev1.EventList{}
if err := m.c.List(context.Background(), evs); err != nil {
t.Fatal(err)
}
out := map[string]int{}
for _, e := range evs.Items {
out[e.Reason]++
}
return out
}
// switchedFixture is a seeded release on the converted chart whose source
// Secret reads fail `fails` times with a dropped connection.
func switchedFixture(t *testing.T, fails int) *migrator {
t.Helper()
transientDelay = 0
left := fails
funcs := &interceptor.Funcs{Patch: func(ctx context.Context, c client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error {
if _, ok := obj.(*helmv2.HelmRelease); ok && left > 0 && obj.GetAnnotations()["test/switched"] == "true" {
left--
return readReset
}
return c.Patch(ctx, obj, patch, opts...)
}}
hr := release(`{"users":{"web":{"password":"leftover"}}}`, "0.1.0", true)
m := newMigratorWith(t, funcs, hr, sourceSecret(map[string]string{"web": "hunter2"}))
ctx := context.Background()
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
cur := &helmv2.HelmRelease{}
if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil {
t.Fatal(err)
}
cur.Status.History = helmv2.Snapshots{{Version: 2, ChartVersion: "0.2.0", Status: "deployed"}}
if err := m.c.Status().Update(ctx, cur); err != nil {
t.Fatal(err)
}
// Mark it so only finish's patches fail, not the seed's.
cur.Annotations["test/switched"] = "true"
if err := m.c.Update(ctx, cur); err != nil {
t.Fatal(err)
}
return m
}
func TestFinishRetriesATransientErrorWithoutASkipEvent(t *testing.T) {
m := switchedFixture(t, 1)
if err := m.finish(context.Background()); err != nil {
t.Fatal(err)
}
if r := eventReasons(t, m); r[reasonSkipped] != 0 || r[reasonRetrying] != 0 {
t.Fatalf("events = %v: a release converted on retry must not be announced as left out", r)
}
if st, _ := m.loadState(context.Background()); !st.Releases["tenant-foo/postgres-orders"].Done {
t.Fatalf("state = %+v", st)
}
}
func TestFinishAnnouncesAPersistentTransientErrorAsARetry(t *testing.T) {
m := switchedFixture(t, 100)
if err := m.finish(context.Background()); err == nil {
t.Fatal("finish must fail so the Job retries")
}
r := eventReasons(t, m)
if r[reasonSkipped] != 0 || r[reasonRetrying] != 1 {
t.Fatalf("events = %v", r)
}
// Still recorded, so the incomplete alert fires if it never converts.
if st, _ := m.loadState(context.Background()); st.Skipped["tenant-foo/postgres-orders"] == "" {
t.Fatalf("state = %+v", st)
}
}
func TestFinishStillSkipsAFinalError(t *testing.T) {
transientDelay = 0
hr := release(`{"users":{"web":{}}}`, "0.1.0", true)
m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2"}))
if err := m.seed(context.Background()); err != nil {
t.Fatal(err)
}
// Never switches: the wait times out, which no retry fixes.
if err := m.finish(context.Background()); err == nil {
t.Fatal("finish must fail")
}
if r := eventReasons(t, m); r[reasonSkipped] != 1 || r[reasonRetrying] != 0 {
t.Fatalf("events = %v", r)
}
}
func TestIsTransient(t *testing.T) {
for _, c := range []struct {
err error
want bool
}{
{readReset, true},
{fmt.Errorf("get x: %w", syscall.ECONNRESET), true},
{fmt.Errorf("not Ready on a chart version other than %q", "0.1.0"), false},
{fmt.Errorf("%w: users.x", errUnresolvable), false},
} {
if got := isTransient(c.err); got != c.want {
t.Errorf("isTransient(%v) = %v, want %v", c.err, got, c.want)
}
}
}
+40 -23
View File
@@ -84,40 +84,57 @@ psql_exec() {
psql -U postgres -d "$db" -tAc "$sql"
}
# Password of an 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 login would invalidate the previous attempt. The Credential
# is named <release>.<account>, where <account> is the user name lowercased
# with every character outside [a-z0-9-] replaced by "-", and the chart names
# the CNPG Cluster after the release, so the cluster IS the release here.
# Args: <cluster> <user>
# Minted passwords are cached for this run only, in 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 the cache.
export COZY_PW_CACHE_DIR="${COZY_PW_CACHE_DIR:-$(mktemp -d "${TMPDIR:-/tmp}/cozy-pw.XXXXXXXX")}"
app_password() {
local cluster="$1" user="$2"
local acct cache
acct=$(printf '%s' "$user" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9-]/-/g')
cache="${COZY_PW_CACHE_DIR}/${cluster}-${acct}"
if [[ ! -s "$cache" ]]; then
kubectl create --raw "/apis/core.cozystack.io/v1alpha1/namespaces/${NAMESPACE}/credentials/${cluster}.${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 ${cluster}"; return 1; }
cat "$cache"
}
# Run a psql statement AS the application user over TCP (via the cluster's -rw
# Service), forcing password authentication. psql_exec above connects as the
# in-pod postgres superuser through the local socket (peer auth) and so never
# exercises a user's password; only this path proves the password the
# <release>-credentials Secret advertises actually authenticates. The password is
# read from that chart-managed Secret with jq, not a jsonpath: a username may
# contain a '.', and jsonpath's `{.data['a.b']}` treats the dot as a path step
# and returns nothing, so a dotted user would read an empty password and time out
# on a credential that is fine. jq indexes the key as a literal string. The chart
# names the CNPG Cluster, the -rw Service and the credentials Secret all after the
# release, so the cluster IS the release here - derive the Secret from it rather
# than taking a separate name that a caller can get wrong (a release/app-name
# mix-up read a Secret that never exists and made every login time out).
# exercises a user's password.
# Args: <cluster> <user> <db> <sql>
psql_app_exec() {
local cluster="$1" user="$2" db="$3" sql="$4"
local pod pw
pod=$(cnpg_primary_pod "$cluster")
[[ -n "$pod" ]] || { log_error "no primary pod for cnpg cluster '$cluster'"; return 1; }
pw=$(kubectl -n "$NAMESPACE" get secret "${cluster}-credentials" -o json \
| jq -r --arg u "$user" '.data[$u] // empty' | base64 -d)
[[ -n "$pw" ]] || { log_error "no password for user '${user}' in ${cluster}-credentials"; return 1; }
kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \
env PGPASSWORD="$pw" psql -h "${cluster}-rw" -U "$user" -d "$db" -tAc "$sql"
pw=$(app_password "$cluster" "$user") || return 1
# The password goes to psql on stdin: exec arguments travel in the request
# URI, which the audit log records at any level.
printf '%s\n' "$pw" | kubectl -n "$NAMESPACE" exec -i "$pod" -c postgres -- \
sh -c 'IFS= read -r PGPASSWORD; export PGPASSWORD; exec psql "$@"' sh \
-h "${cluster}-rw" -U "$user" -d "$db" -tAc "$sql"
}
# Block until the application user can authenticate against a cluster, or fail
# after <timeout>s. Needed after a to-copy restore: the driver clears
# bootstrap.enabled once recovery converges so the chart's init-job re-runs
# ALTER ROLE ... WITH PASSWORD, converging the recovered roles (which carry the
# source's password hashes) onto the freshly generated <release>-credentials
# Secret. That convergence is asynchronous - a HelmRelease upgrade plus its
# post-upgrade init-job hook - so this is a readiness wait on an eventually
# consistent property, not a retry over a deterministic step.
# after <timeout>s. Needed after a to-copy restore: the recovered roles carry
# the source's password hashes until CloudNativePG applies the verifier from
# the account Secret, which it does once the restored primary is up and the
# release has left bootstrap. That convergence is asynchronous, so this is a
# readiness wait on an eventually consistent property, not a retry over a
# deterministic step.
# Args: <cluster> <user> <db> <timeout>
wait_for_app_login() {
local cluster="$1" user="$2" db="$3" timeout="${4:-300}"
@@ -137,7 +154,7 @@ wait_for_app_login() {
return 0
fi
if [[ $elapsed -ge $timeout ]]; then
log_error "Timeout waiting for user '${user}' to authenticate against ${cluster}: the credentials Secret advertises a password the roles never received (bootstrap not cleared, or the init-job did not reconcile). Last attempt: $(cat "$errfile")"
log_error "Timeout waiting for user '${user}' to authenticate against ${cluster}: the minted password never reached the role (bootstrap not cleared, or CloudNativePG did not apply the account Secret). Last attempt: $(cat "$errfile")"
rm -f "$errfile"
return 1
fi
+4 -5
View File
@@ -264,11 +264,10 @@ if [[ "$GOT" != "$SENTINEL_TOKEN" ]]; then
fi
log_success "Round-trip verified: '${PG_TARGET_NAME}' restored sentinel '${GOT}' from S3."
# The passwords in <target>-credentials are chart-generated and do not match the
# password hashes recovery brought back with the roles; the driver clears
# bootstrap.enabled so the init-job reconciles them. Prove the app user can
# actually log in against the restored copy - psql_exec above only ever used the
# in-pod postgres superuser, so a broken credential would otherwise pass silently.
# The roles recovery brought back carry the source's password hashes until
# CloudNativePG applies the target's account Secret. Prove the app user can
# log in against the restored copy - psql_exec above only ever used the in-pod
# postgres superuser, so a broken credential would otherwise pass silently.
print_header "Step 40 verify: the app user authenticates against the restored copy"
wait_for_app_login "$PG_TARGET_CLUSTER" app demo 360
APP_GOT=$(psql_app_exec "$PG_TARGET_CLUSTER" app demo \
@@ -1,25 +0,0 @@
#!/usr/bin/env bats
# Unit test: on a fresh install, packages/apps/postgres hands CNPG the same
# users.app password it stores in <release>-credentials.
#
# The password is generated at render time, so the two Secrets can only be
# compared within one render. helm-unittest asserts each document against a
# fixed value and has no way to compare one document with another, so a chart
# generating two independent passwords would still pass the chart's own suite.
load test_helper
REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)"
CHART="$REPO_ROOT/packages/apps/postgres"
@test "a fresh users.app gets one generated password in both Secrets" {
rendered="$BATS_TEST_TMPDIR/init-script.yaml"
helm template pg "$CHART" --namespace tenant-test \
--set-json '_cluster={"scheduling":{}}' --set-json 'users={"app":{}}' \
--show-only templates/init-script.yaml > "$rendered"
app=$(yq -e 'select(.kind == "Secret" and .metadata.name == "pg-credentials").stringData.app' "$rendered")
owner=$(yq -e 'select(.kind == "Secret" and .metadata.name == "pg-app-owner").stringData.password' "$rendered")
[ -n "$app" ] || { echo "no generated password for app in pg-credentials" >&2; return 1; }
[ "$app" = "$owner" ] || { printf 'pg-credentials app: %s\npg-app-owner password: %s\n' "$app" "$owner" >&2; return 1; }
}
@@ -68,6 +68,26 @@ spec:
metadata:
name: postgres-ea-b-rw
(subsets[0].addresses[0].ip != null): true
# The probes below mint testuser's password, which needs the Credential
# cozystack-controller keeps for each application user.
- assert:
timeout: 2m
resource:
apiVersion: core.cozystack.io/v1alpha1
kind: Credential
metadata:
name: postgres-ea-a.testuser
spec:
user: testuser
- assert:
timeout: 2m
resource:
apiVersion: core.cozystack.io/v1alpha1
kind: Credential
metadata:
name: postgres-ea-b.testuser
spec:
user: testuser
# Lineage: ea-b's primary is tenant-facing, but not ea-a's, so an attachment
# naming ea-a is refused and renders nothing.
@@ -121,18 +141,17 @@ spec:
(addresses[0] != null): true
(claimName != null): true
- script:
timeout: 2m
timeout: 4m
content: |
set -eu
ip=$(kubectl -n "$NAMESPACE" get endpointattachments.local.sdn.cozystack.io ea-a-ro -o jsonpath='{.status.addresses[0]}')
pod=$(kubectl -n "$NAMESPACE" get pod -l cnpg.io/cluster=postgres-ea-a,cnpg.io/instanceRole=primary -o name | head -n1)
# The chart generates each user's password into its credentials Secret.
pw=$(kubectl get secret postgres-ea-a-credentials --namespace "$NAMESPACE" --output jsonpath='{.data.testuser}' | base64 -d)
# The attached address must answer as a replica, not as the primary
# the pod itself is: "t" from pg_is_in_recovery() proves the
# -ro selector was mirrored, not the -rw one.
kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \
env PGPASSWORD="$pw" psql -h "$ip" -U testuser -d testdb -tAc 'SELECT pg_is_in_recovery()'
# -ro selector was mirrored, not the -rw one. The wait is on the
# application's own -ro Service, so the replica already has the
# minted password when the address is asked.
./query-as-testuser.sh postgres-ea-a "$pod" postgres-ea-a-ro "$ip" 'SELECT pg_is_in_recovery()'
check:
($error == null): true
(trim_space($stdout)): "t"
@@ -207,7 +226,7 @@ spec:
phase: Attached
claimName: ea-held
- script:
timeout: 2m
timeout: 4m
content: |
set -eu
ip=$(kubectl get ipaddressclaims.local.sdn.cozystack.io ea-held --namespace "$NAMESPACE" --output jsonpath='{.metadata.annotations.e2e\.cozystack\.io/reserved-address}')
@@ -217,9 +236,7 @@ spec:
pod=$(kubectl -n "$NAMESPACE" get pod -l cnpg.io/cluster=postgres-ea-b -o name | head -n1)
# Probe from ea-b's pod so the answer cannot come from the local
# instance: the reserved address must reach ea-a's primary.
pw=$(kubectl get secret postgres-ea-a-credentials --namespace "$NAMESPACE" --output jsonpath='{.data.testuser}' | base64 -d)
kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \
env PGPASSWORD="$pw" psql -h "$ip" -U testuser -d testdb -tAc "SELECT current_setting('cluster_name') || ' ' || pg_is_in_recovery()"
./query-as-testuser.sh postgres-ea-a "$pod" postgres-ea-a-rw "$ip" "SELECT current_setting('cluster_name') || ' ' || pg_is_in_recovery()"
check:
($error == null): true
(trim_space($stdout)): "postgres-ea-a false"
@@ -277,7 +294,7 @@ spec:
phase: Attached
claimName: ea-held
- script:
timeout: 2m
timeout: 4m
content: |
set -eu
ip=$(kubectl get ipaddressclaims.local.sdn.cozystack.io ea-held --namespace "$NAMESPACE" --output jsonpath='{.metadata.annotations.e2e\.cozystack\.io/reserved-address}')
@@ -285,9 +302,7 @@ spec:
got=$(kubectl -n "$NAMESPACE" get endpointattachments.local.sdn.cozystack.io ea-b-rw-held -o jsonpath='{.status.addresses[0]}')
[ "$got" = "$ip" ]
pod=$(kubectl -n "$NAMESPACE" get pod -l cnpg.io/cluster=postgres-ea-a,cnpg.io/instanceRole=primary -o name | head -n1)
pw=$(kubectl get secret postgres-ea-b-credentials --namespace "$NAMESPACE" --output jsonpath='{.data.testuser}' | base64 -d)
kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \
env PGPASSWORD="$pw" psql -h "$ip" -U testuser -d testdb -tAc "SELECT current_setting('cluster_name') || ' ' || pg_is_in_recovery()"
./query-as-testuser.sh postgres-ea-b "$pod" postgres-ea-b-rw "$ip" "SELECT current_setting('cluster_name') || ' ' || pg_is_in_recovery()"
check:
($error == null): true
(trim_space($stdout)): "postgres-ea-b false"
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env bash
# Usage: query-as-testuser.sh <release> <pod> <ready-host> <host> <query>
#
# Mints a password for testuser of <release>, waits until <ready-host> accepts
# it, then runs <query> once against <host> from <pod> and prints the answer.
#
# The chart keeps no password a tenant can read back, so each probe mints its
# own. A mint replaces the previous password, and CloudNativePG applies it
# live, on a replica once replay reaches it; the wait is on the application's
# own Service, so the address under test is queried exactly once and a wrong
# answer from it is never retried away. The wait carries its own deadline: the
# step's ceiling kills only the calling shell, which would leave this loop
# running and holding the step's output open.
set -euo pipefail
release=$1 pod=$2 ready=$3 host=$4 query=$5
pw=$(kubectl create --raw "/apis/core.cozystack.io/v1alpha1/namespaces/$NAMESPACE/credentials/$release.testuser/mint" \
--filename <(printf '{"apiVersion":"core.cozystack.io/v1alpha1","kind":"CredentialRequest"}') \
| jq --raw-output '.status.password')
[ "${#pw}" -eq 32 ] || { echo "minted password has ${#pw} characters, want 32" >&2; exit 1; }
# The password goes to psql on stdin: exec arguments travel in the request
# URI, which the audit log records at any level.
psql_on() {
printf '%s\n' "$pw" | kubectl --namespace "$NAMESPACE" exec --stdin "$pod" --container postgres -- \
sh -c 'IFS= read -r PGPASSWORD; export PGPASSWORD; exec psql "$@"' sh \
-h "$1" -U testuser -d testdb -tAc "$2"
}
deadline=$((SECONDS + 180))
until [ "$(psql_on "$ready" 'SELECT 1' 2>/dev/null | tr -d '[:space:]')" = 1 ]; do
if [ "$SECONDS" -ge "$deadline" ]; then
echo "$ready did not accept the password minted for $release.testuser within 180s" >&2
exit 1
fi
sleep 5
done
psql_on "$host" "$query"
@@ -127,6 +127,116 @@ spec:
kind: Job
name: postgres-test-init-job
# 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),
# and a second mint replaces the first once CloudNativePG applies it.
- name: verify-minted-credential
try:
- assert:
timeout: 2m
resource:
apiVersion: core.cozystack.io/v1alpha1
kind: Credential
metadata:
name: postgres-test.testuser
spec:
application:
kind: Postgres
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=postgres-test.testuser
as="--as=e2e-postgres-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 psql 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 "$pod" -c postgres -- \
sh -c 'IFS= read -r PGPASSWORD; export PGPASSWORD; exec psql "$@"' sh \
-h postgres-test-rw -U testuser -d testdb -tAc '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
}
pod=$(kubectl -n "$NAMESPACE" get pod \
-l cnpg.io/cluster=postgres-test,cnpg.io/instanceRole=primary -o name | head -n1)
first=$(mint)
[ "${#first}" -eq 32 ] || { echo "minted password has ${#first} characters, want 32" >&2; exit 1; }
# CloudNativePG applies the changed account Secret live; 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 verifier, decoded, never the password.
stored=$(kubectl -n "$NAMESPACE" get secret "$cred.account" -o json | jq -r '.data.password' | base64 -d)
case "$stored" in
'SCRAM-SHA-256$4096:'*) ;;
*) echo "the account Secret does not hold a SCRAM verifier" >&2; exit 1 ;;
esac
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 (the
# argument just comes out empty and the check passes without reading).
events=$(kubectl -n "$NAMESPACE" get events -o json)
refuse "an Event" "$events"
application=$(kubectl -n "$NAMESPACE" get postgreses.apps.cozystack.io test -o json)
refuse "the application" "$application"
# Every revision of the release, decoded: Helm stores each as base64
# of gzipped JSON inside the Secret's base64. Require at least one, so
# an empty match cannot pass the check without reading anything.
rels=$(kubectl -n "$NAMESPACE" get secret -l owner=helm,name=postgres-test -o name)
[ -n "$rels" ] || { echo "no Helm release Secret for postgres-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
# Everything the tenant's own super-admins can read through
# tenantsecrets, decoded; the account Secret is not among it.
visible=$(kubectl -n "$NAMESPACE" get tenantsecrets.core.cozystack.io $as -o json)
if printf '%s' "$visible" | jq -r '.items[].metadata.name' | grep -Fqx "$cred.account"; then
echo "the account Secret is listed through tenantsecrets" >&2; exit 1
fi
decoded_visible=$(printf '%s' "$visible" | jq -r '.items[].data // {} | .[] | @base64d')
refuse "tenantsecrets" "$decoded_visible"
# 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/$cred.account" $as 2>&1) || true
if [ "$answer" != no ]; then
echo "the tenant super-admin group can read the account Secret, or can-i did not answer: $answer" >&2
exit 1
fi
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, checked against the live
# operator rather than against our own beliefs about it.
#
+220
View File
@@ -0,0 +1,220 @@
#!/usr/bin/env bats
# -----------------------------------------------------------------------------
# Unit tests for platform migration 64 --> 65 (convert Postgres accounts to
# platform-minted credentials, first part).
#
# The migration seeds the account Secrets of every Postgres release, then
# creates the cozystack-credentials-migration-64 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/64.
#
# 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-64-postgres-credentials.bats
# -----------------------------------------------------------------------------
load test_helper
FAKEBIN="$PWD/hack/testdata/migration-64-postgres-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-migration64-test:$(printf '%s' "$ALPINE" | sed 's/[^a-zA-Z0-9]/-/g')"
WORKROOT="${TMPDIR:-/tmp}/cozy-migration-64-$$"
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_CRD_FAIL="${FAKE_CRD_FAIL-}" \
-e CREDENTIAL_CRD_FILE=/work/credentialtemplates.yaml \
-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 64 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_CRD_FAIL 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 64 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -eq 0 ]
# The seed runs for migration 64.
grep -qE "^CREDMIGRATE seed --migration 64 " "$FAKE_CMDLOG"
# The CRD is applied, owned by the cozystack-controller release, and
# established before the seed, since the converted chart renders it.
_crd=$(cmdlog_line "^CRD established$")
_seed=$(cmdlog_line "^CREDMIGRATE seed")
[ -n "$_crd" ] && [ "$_crd" -lt "$_seed" ]
grep -qE "^CRD label$" "$FAKE_CMDLOG"
grep -qE "^CRD annotate$" "$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 65$")
[ -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 64 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
grep -qE "^CREDMIGRATE seed --migration 64 " "$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 64 >"$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 64 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
grep -qE "^CREDMIGRATE seed --migration 64 " "$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 64 >"$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 64 >"$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 64 >"$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-64\" not found"
rc=0
run_migration 64 >"$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"
}
@test "a CRD that fails to apply stops before the seed and the stamp" {
prep
export FAKE_CRD_FAIL=1
rc=0
run_migration 64 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qE "^CREDMIGRATE seed" "$FAKE_CMDLOG"; then echo "seeded without the CRD" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped without the CRD" >&2; return 1; fi
}
+54 -32
View File
@@ -1,92 +1,114 @@
#!/usr/bin/env bats
# Unit tests for the app-login helpers the postgres backup example uses to prove
# the restored copy authenticates. The bug they pin: the credentials Secret is
# named after the release (== the CNPG cluster, `postgres-<name>`), not the short
# app name, so resolving it from anything but the cluster reads a Secret that
# does not exist and the login can never pass. Others: a genuine failure names
# the Secret on timeout; a login printing '1' is a success even with stderr
# noise; and a username with a dot reads its password (jq, not jsonpath).
# the restored copy authenticates. The password comes from a mint on the
# account's Credential, named <release>.<account> after the release (== the CNPG
# cluster, `postgres-<name>`), not the short app name: resolving it from anything
# but the cluster mints on a credential that does not exist, and the login can
# never pass. Others: a genuine failure names the credential on timeout; a login
# printing '1' is a success even with stderr noise; a username with a dot maps to
# its account name; and a run mints once, since a second mint replaces the
# password the first one returned.
#
# The helper reads the Secret with `get secret ... -o json | jq`, so the kubectl
# stub returns JSON. 00-helpers.sh is `#!/bin/bash` (it uses arrays), so it is
# exercised in a bash subshell rather than sourced into this runner, which is
# 00-helpers.sh is `#!/bin/bash` (it uses arrays and process substitution), so it
# is exercised in a bash subshell rather than sourced into this runner, which is
# /bin/sh (dash in CI). It is sourced first, then the stubs override its
# cluster-touching functions.
# cluster-touching functions. Each test gets its own TMPDIR, where the helper
# caches the minted password.
load test_helper
@test "psql_app_exec reads the credentials Secret named after the cluster, not the app name" {
MINT=/apis/core.cozystack.io/v1alpha1/namespaces/tenant-test/credentials
@test "psql_app_exec mints on the credential named after the cluster, not the app name" {
calls=$(mktemp)
CALLS="$calls" bash -uc '
CALLS="$calls" MINT="$MINT" TMPDIR=$(mktemp -d) bash -uc '
NAMESPACE=tenant-test
. examples/backups/postgres/00-helpers.sh
cnpg_primary_pod() { echo "${1}-1"; }
kubectl() {
printf "kubectl %s\n" "$*" >> "$CALLS"
case "$*" in
*"get secret postgres-pg-target-credentials -o json"*) printf "%s" "{\"data\":{\"app\":\"cGFzcw==\"}}" ;;
*"get secret "*) echo "WRONG secret queried: $*" >&2; return 1 ;;
*"create --raw $MINT/postgres-pg-target.app/mint"*) printf "%s" "{\"status\":{\"password\":\"pass\"}}" ;;
*"create --raw "*) echo "WRONG credential minted: $*" >&2; return 1 ;;
*" exec "*) echo 1 ;;
*) return 0 ;;
esac
}
psql_app_exec postgres-pg-target app demo "SELECT 1;" >/dev/null
'
grep -q 'get secret postgres-pg-target-credentials -o json' "$calls"
if grep -q 'get secret pg-target-credentials ' "$calls"; then
echo "resolved the Secret from the app name, not the cluster" >&2
grep -q "create --raw $MINT/postgres-pg-target.app/mint" "$calls"
if grep -q "credentials/pg-target.app/" "$calls"; then
echo "resolved the credential from the app name, not the cluster" >&2
exit 1
fi
}
@test "wait_for_app_login names the failing Secret on timeout instead of swallowing it" {
@test "wait_for_app_login names the failing credential on timeout instead of swallowing it" {
out=$(mktemp)
bash -uc '
TMPDIR=$(mktemp -d) bash -uc '
NAMESPACE=tenant-test
. examples/backups/postgres/00-helpers.sh
cnpg_primary_pod() { echo "${1}-1"; }
kubectl() {
case "$*" in
# Secret exists but has no password for app; the helper log_errors
# naming it, and the wait loop must surface that on timeout.
*"get secret postgres-pg-target-credentials -o json"*) printf "%s" "{\"data\":{}}" ;;
# The mint answers without a password; the helper log_errors
# naming the user, and the wait loop must surface that on timeout.
*"create --raw "*) printf "%s" "{\"status\":{}}" ;;
*) return 0 ;;
esac
}
wait_for_app_login postgres-pg-target app demo 0
' >"$out" 2>&1 && { echo "wait_for_app_login unexpectedly passed with no password" >&2; exit 1; }
grep -q "no password for user 'app' in postgres-pg-target-credentials" "$out"
grep -q "no password minted for user 'app' of postgres-pg-target" "$out"
}
@test "psql_app_exec reads the password for a username containing a dot" {
@test "psql_app_exec maps a username containing a dot to its account name" {
calls=$(mktemp)
CALLS="$calls" bash -uc '
CALLS="$calls" MINT="$MINT" TMPDIR=$(mktemp -d) bash -uc '
NAMESPACE=tenant-test
. examples/backups/postgres/00-helpers.sh
cnpg_primary_pod() { echo "${1}-1"; }
kubectl() {
printf "kubectl %s\n" "$*" >> "$CALLS"
case "$*" in
# A dotted key is why jsonpath fails and jq is used; return the
# Secret as JSON so jq can index the literal "app.user" key.
*"get secret postgres-pg-target-credentials -o json"*) printf "%s" "{\"data\":{\"app.user\":\"cGFzcw==\"}}" ;;
*"create --raw $MINT/postgres-pg-target.app-user/mint"*) printf "%s" "{\"status\":{\"password\":\"pass\"}}" ;;
*" exec "*) echo 1 ;;
*) return 0 ;;
esac
}
psql_app_exec postgres-pg-target app.user demo "SELECT 1;" >/dev/null
psql_app_exec postgres-pg-target app.User demo "SELECT 1;" >/dev/null
'
grep -q 'get secret postgres-pg-target-credentials -o json' "$calls"
grep -q "create --raw $MINT/postgres-pg-target.app-user/mint" "$calls"
}
@test "psql_app_exec mints once per run" {
calls=$(mktemp)
CALLS="$calls" TMPDIR=$(mktemp -d) bash -uc '
NAMESPACE=tenant-test
. examples/backups/postgres/00-helpers.sh
cnpg_primary_pod() { echo "${1}-1"; }
kubectl() {
printf "kubectl %s\n" "$*" >> "$CALLS"
case "$*" in
*"create --raw "*) printf "%s" "{\"status\":{\"password\":\"pass\"}}" ;;
*" exec "*) echo 1 ;;
*) return 0 ;;
esac
}
psql_app_exec postgres-pg-target app demo "SELECT 1;" >/dev/null
psql_app_exec postgres-pg-target app demo "SELECT 1;" >/dev/null
'
[ "$(grep -c 'create --raw ' "$calls")" -eq 1 ]
}
@test "wait_for_app_login treats a login that prints '1' as success even with stderr noise" {
bash -uc '
TMPDIR=$(mktemp -d) bash -uc '
NAMESPACE=tenant-test
. examples/backups/postgres/00-helpers.sh
cnpg_primary_pod() { echo "${1}-1"; }
kubectl() {
case "$*" in
*"get secret postgres-pg-target-credentials -o json"*) printf "%s" "{\"data\":{\"app\":\"cGFzcw==\"}}" ;;
*"create --raw "*) printf "%s" "{\"status\":{\"password\":\"pass\"}}" ;;
# A successful SELECT 1 prints 1 on stdout; a NOTICE on stderr
# must not be read as a failure (success is stdout-only).
*" exec "*) echo 1; echo "NOTICE: something" >&2 ;;
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
# Fake credentials-migrate for hack/migration-64-postgres-credentials.bats.
# Migration 64 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
+127
View File
@@ -0,0 +1,127 @@
#!/bin/sh
# Fake kubectl for hack/migration-64-postgres-credentials.bats, modelled on
# hack/testdata/migration-58-http-cache/kubectl. It serves only the calls
# migration 64 and lib/cozystack-version.sh make, and logs each one to
# $FAKE_CMDLOG.
#
# Migration 64 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
*"apply --server-side --force-conflicts --filename "*credentialtemplates*)
log "CRD apply"
[ -n "${FAKE_CRD_FAIL-}" ] && exit 1
exit 0
;;
*"label crd credentialtemplates.cozystack.io app.kubernetes.io/managed-by=Helm"*)
log "CRD label"
exit 0
;;
*"annotate crd credentialtemplates.cozystack.io"*"meta.helm.sh/release-name=cozystack-controller"*)
log "CRD annotate"
exit 0
;;
*"wait --for=condition=established crd/credentialtemplates.cozystack.io"*)
log "CRD established"
exit 0
;;
*"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-64"*)
# The hook deletes a Job left by an earlier run before recreating it.
log "DELETE-JOB"
exit 0
;;
*"delete serviceaccount cozystack-credentials-migration-64"*)
# 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-64"*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-64"*)
# 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-64')
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')
# Count the name only inside the Job document: the ClusterRole, the
# ServiceAccount and the binding share it.
jobname=$(printf '%s\n' "$manifest" | sed -n '/^kind: Job$/,/^spec:$/p' | grep -c '^ name: cozystack-credentials-migration-64$')
mig=$(printf '%s\n' "$manifest" | grep -c -- '--migration=64')
img=$(printf '%s\n' "$manifest" | grep -c "^ image: ${IMAGE}$")
sacc=$(printf '%s\n' "$manifest" | grep -c '^ serviceAccountName: cozystack-credentials-migration-64$')
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
+16 -7
View File
@@ -277,12 +277,12 @@ For `sslmode=verify-full` to work, the CA bundle retrieved above must be saved t
### Users configuration
| Name | Description | Type | Value |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ------- |
| `users` | Users configuration map. Passwords 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].replication` | Whether the user has replication privileges. | `bool` | `false` |
| `users[name].createRole` | Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role. | `bool` | `false` |
| `users[name].bypassRls` | Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role. | `bool` | `false` |
| Name | Description | Type | Value |
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ------- |
| `users` | Users configuration map. Each user is a PostgreSQL role 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 SCRAM verifier, and a revoke retires the password without issuing one. A `password` key here is ignored and draws an admission warning. A password set inside PostgreSQL is reverted by the operator. | `map[string]object` | `{}` |
| `users[name].replication` | Whether the user has replication privileges. | `bool` | `false` |
| `users[name].createRole` | Not supported while users are CloudNativePG managed roles: the chart refuses to render when it is true, and a release that sets it keeps its previous chart version until it is false. CloudNativePG revokes every membership a managed role is not declared to hold, including the one PostgreSQL gives a CREATEROLE user in each role it creates. Setting it to false withdraws CREATEROLE from a role that held it. | `bool` | `false` |
| `users[name].bypassRls` | Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself. | `bool` | `false` |
### Databases configuration
@@ -363,7 +363,16 @@ users:
replication: true
```
Passwords cannot be set here — they are auto-generated and stored in the `<release>-credentials` Secret. Read a user's password with `kubectl get tenantsecret <release>-credentials -o json | jq -r '.data["user1"]' | base64 -d` (a username may contain a `.`, which `jsonpath` would treat as a path step and return nothing).
Passwords cannot be set here. Each user is an account of the Cozystack credentials API: a `Credential` named `<release>.<account>` in `core.cozystack.io/v1alpha1`, where `<account>` is the user name lowercased with every character outside `[a-z0-9-]` replaced by `-`. A mint returns a new password once and replaces the previous one; only its SCRAM verifier is stored, so the password cannot be read back:
```bash
kubectl create --raw "/apis/core.cozystack.io/v1alpha1/namespaces/<namespace>/credentials/postgres-<name>.user1/mint" \
-f <(echo '{"apiVersion":"core.cozystack.io/v1alpha1","kind":"CredentialRequest"}') | jq -r .status.password
```
A user added to an existing application has no password until the first mint. Names PostgreSQL or CloudNativePG reserve (`postgres`, `streaming_replica`, `pg_*`, `cnpg_*`), the name of a database role (`<db>_admin`, `<db>_readonly`), and two users mapping to one account name are refused.
Downgrading the platform past the conversion to minted passwords is not supported: the previous chart generates a new password for every account. A manual `helm rollback` of a release to a revision from before the conversion is undone at its next reconcile, and meanwhile the old revision's `<release>-credentials` shows a password that no longer works; mint again once the release is back.
### databases
+7 -16
View File
@@ -1,20 +1,11 @@
{{- if and .Values.bootstrap.enabled .Values.users }}
WARNING: this PostgreSQL was provisioned as a restore (bootstrap.enabled=true).
The roles recovered from the backup keep their original password hashes, but the
{{ .Release.Name }}-credentials Secret now holds freshly generated passwords that
are NOT yet applied to the database — the init-job that runs ALTER ROLE is skipped
while bootstrap is on. While bootstrap is on the credentials Secret carries the
annotation postgres.cozystack.io/credentials-pending: "true". That flag tracks only
the bootstrap phase, not the whole convergence: the restore driver REMOVES it when
it clears bootstrap.enabled, and that same reconcile is what triggers the init-job
— so the flag is already gone for the short window before the init-job has finished
applying the passwords. Do not read a missing flag as "converged".
The restore driver clears bootstrap.enabled automatically once recovery is healthy,
and the next reconcile runs the init-job to apply the Secret's passwords onto the
recovered roles — no action is required. Confirm convergence by logging in as an
application user rather than by the flag; until a login with the Secret's password
succeeds, do not treat the advertised application passwords as usable — the database
is reachable as the CloudNativePG superuser in the meantime.
The roles recovered from the backup keep the password hashes of the source. Each
declared user is a managed role of the Cluster pointing at its account Secret,
and CloudNativePG applies the stored value from that Secret once the recovered
primary is up, so a password minted on this application's credentials
(core.cozystack.io) takes effect without any action here. A restored account
whose Secret was seeded with this application has no issued password yet: mint
one, and poll a login with it until it succeeds.
{{- end }}
@@ -0,0 +1,62 @@
{{/*
Account Secret naming, which must match pkg/credentials/account.MapName:
each user's CredentialTemplate is named <release>.<account>, where
<account> is the user name lowercased with every character outside
[a-z0-9-] replaced by "-", and the controller writes its account Secret as
<template>.account. Two users that map to one account would make CNPG read
one Secret for both; the guard below refuses them, and it is the only check
on every path a release is written by.
*/}}
{{- define "postgres.accountName" -}}
{{- regexReplaceAll "[^a-z0-9-]" (lower .) "-" -}}
{{- end -}}
{{- define "postgres.accountSecret" -}}
{{- $root := index . 0 -}}
{{- $user := index . 1 -}}
{{- printf "%s.%s.account" $root.Release.Name (include "postgres.accountName" $user) -}}
{{- end -}}
{{/*
Refusals for names the managed roles would otherwise hand to CNPG. They
render with the Cluster on every path, recovery included, where the
init-script does not render.
*/}}
{{- define "postgres.accountsGuard" -}}
{{- $derived := dict -}}
{{- range $database, $d := .Values.databases -}}
{{- $adminRole := printf "%s_admin" $database -}}
{{- if or (hasPrefix "pg_" $adminRole) (hasPrefix "cnpg_" $adminRole) -}}
{{- fail (printf "database %q is reserved: its roles %s_admin and %s_readonly would start with pg_ or cnpg_, which PostgreSQL and CloudNativePG reserve and the CloudNativePG webhook rejects; rename the database" $database $database $database) -}}
{{- end -}}
{{- $_ := set $derived $adminRole $database -}}
{{- $_ := set $derived (printf "%s_readonly" $database) $database -}}
{{- end -}}
{{- $seen := dict -}}
{{- range $user, $u := .Values.users -}}
{{- $mapped := include "postgres.accountName" $user -}}
{{- if not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $mapped) -}}
{{- fail (printf "user %q maps to the account name %q, which must 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 or (eq $user "streaming_replica") (hasPrefix "pg_" $user) (hasPrefix "cnpg_" $user) -}}
{{- fail (printf "user %q is reserved: streaming_replica and names starting with pg_ or cnpg_ belong to PostgreSQL and CloudNativePG; rename the user" $user) -}}
{{- end -}}
{{- with index $derived $user -}}
{{- fail (printf "user %q is the name of a role of database %q; rename the user" $user .) -}}
{{- end -}}
{{- /*
A role a CREATEROLE user creates makes that user a member of it, which
CloudNativePG revokes from a managed role and fails to, on the dependent
self-grant, leaving the user stuck in cannotReconcile. CloudNativePG has
no per-role switch to leave memberships alone, so the attribute is
refused while users are managed roles.
*/ -}}
{{- if default false $u.createRole -}}
{{- fail (printf "users.%s.createRole is not supported: users are CloudNativePG managed roles, which revoke the membership PostgreSQL gives a CREATEROLE user in each role it creates. Set createRole to false; an existing release with it keeps its previous chart version until then" $user) -}}
{{- end -}}
{{- end -}}
{{- end -}}
@@ -0,0 +1,23 @@
{{- /*
One CredentialTemplate per user: the account the Cozystack credentials API
mints and revokes through. cozystack-controller keeps its account Secret,
<release>.<account>.account, which managed.roles[].passwordSecret names in
db.yaml, and CloudNativePG applies a changed Secret live through the reload
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 "postgres.accountsGuard" $ }}
{{- range $user, $_ := .Values.users }}
---
apiVersion: cozystack.io/v1alpha1
kind: CredentialTemplate
metadata:
name: {{ printf "%s.%s" $.Release.Name (include "postgres.accountName" $user) | quote }}
spec:
username: {{ $user | quote }}
format:
name: scram-sha-256
secret:
labels:
cnpg.io/reload: "true"
{{- end }}
+52 -4
View File
@@ -264,9 +264,11 @@ spec:
instance manager re-applies the owner's password from the bootstrap secret
on every reconcile whose secret version it has not seen, so on every pod
restart: left on CNPG's own <release>-app, with its generated password, the
role silently loses the password the init-job set from <release>-credentials.
Point the bootstrap at the chart-rendered <release>-app-owner, which holds that
same password. It goes on the method the live Cluster was bootstrapped with,
role silently loses the password its managed role sets from the account
Secret. Point the bootstrap at that account Secret, so both writers apply
the one stored password: CNPG passes a SCRAM verifier through unchanged,
and skips the owner while the Secret does not exist yet, as the initdb job
waits for it. It goes on the method the live Cluster was bootstrapped with,
because CNPG rejects a second one, and a restored Cluster keeps its recovery
block. Changing bootstrap on an existing Cluster is accepted, and the
remaining fields come from the live object or CNPG's defaults (app/app).
@@ -280,7 +282,7 @@ spec:
bootstrap:
{{ ternary "recovery" "initdb" (hasKey $liveBootstrap "recovery") }}:
secret:
name: {{ .Release.Name }}-app-owner
name: {{ include "postgres.accountSecret" (list $ "app") }}
{{- end }}
resources: {{- include "cozy-lib.resources.defaultingSanitize" (list .Values.resourcesPreset .Values.resources $) | nindent 4 }}
@@ -288,6 +290,52 @@ spec:
{{- include "postgres.flavorGuard" $ }}
imageName: {{ include "postgres.imageName" $ }}
enableSuperuserAccess: true
{{- /*
Each role is rendered as the init-script created it: CNPG reverts an
attribute that differs, revokes a parent role missing from inRoles and
clears a comment the spec leaves unset, and the init-script finds the roles
to drop by that comment and by membership in the marker. CNPG grants the
marker with the default options; the init-script narrows them after each
run, which CNPG leaves alone. An account whose Secret is missing is left as
it is by CNPG, so nothing here fails the render for it.
*/}}
{{- include "postgres.accountsGuard" $ }}
managed:
roles:
- name: "cozystack:managed"
login: false
{{- range $database, $d := .Values.databases }}
{{- range $suffix := list "admin" "readonly" }}
- name: {{ printf "%s_%s" $database $suffix | quote }}
login: false
inherit: false
comment: role managed by helm
inRoles:
- "cozystack:managed"
{{- end }}
{{- end }}
{{- range $user, $u := .Values.users }}
- name: {{ $user | quote }}
login: true
inherit: true
replication: {{ default false $u.replication }}
createrole: {{ default false $u.createRole }}
bypassrls: {{ default false $u.bypassRls }}
comment: user managed by helm
inRoles:
- "cozystack:managed"
{{- range $database, $d := $.Values.databases }}
{{- $roles := $d.roles | default dict }}
{{- if has $user $roles.admin }}
- {{ printf "%s_admin" $database | quote }}
{{- end }}
{{- if has $user $roles.readonly }}
- {{ printf "%s_readonly" $database | quote }}
{{- end }}
{{- end }}
passwordSecret:
name: {{ include "postgres.accountSecret" (list $ $user) | quote }}
{{- end }}
{{- if .Values._cluster.scheduling }}
{{- $rawConstraints := get .Values._cluster.scheduling "globalAppTopologySpreadConstraints" }}
{{- if $rawConstraints }}
@@ -0,0 +1,245 @@
{{- /*
Refuses to adopt a role the chart did not mark, which a CREATEROLE holder
can have planted under a name values declare later. It runs pre-upgrade
because CNPG adopts a managed role within seconds of the spec reaching it,
so the post-upgrade init-job would find it adopted. Only a name CNPG does
not manage yet can be planted ahead of its adoption, so the check reads the
live Cluster first, at run time, and connects to the database only when the
upgrade adds such a name; an upgrade that adds none passes with the database
down. Reading the Cluster here rather than through a template lookup keeps
the render free of cluster state. The chart refuses createRole, so it never
sets the flag the check reads; a release where an earlier chart granted it
keeps the flag, and with it the refusal. Fails closed: a Cluster
that cannot be read counts as managing nothing, and no catalog query tells a
planted role from an administrator's. A Cluster that does not exist holds no
database to plant a role in, so the check passes without one, and a Cluster
deleted after that read fails the check at once rather than at the Job
deadline: its superuser Secret goes with it, and a container waiting for a
missing Secret would hold the release in this hook for the full deadline. A
restore purges the Cluster under an upgrade in flight exactly this way.
Skipped under bootstrap.recovery, for the reason init-job.yaml gives, and on
install, where there is no cluster.
*/ -}}
{{- if and .Release.IsUpgrade (not .Values.bootstrap.enabled) (or .Values.users .Values.databases) }}
{{- $pgMajor := atoi (trimPrefix "v" .Values.version) }}
{{- $markOptions := ternary " WITH INHERIT FALSE, SET FALSE" "" (ge $pgMajor 16) }}
apiVersion: v1
kind: ServiceAccount
metadata:
name: {{ .Release.Name }}-preflight
annotations:
"helm.sh/hook": pre-upgrade
"helm.sh/hook-weight": "-10"
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: {{ .Release.Name }}-preflight
annotations:
"helm.sh/hook": pre-upgrade
"helm.sh/hook-weight": "-10"
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
rules:
- apiGroups: ["postgresql.cnpg.io"]
resources: ["clusters"]
resourceNames: [{{ .Release.Name | quote }}]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: {{ .Release.Name }}-preflight
annotations:
"helm.sh/hook": pre-upgrade
"helm.sh/hook-weight": "-10"
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: {{ .Release.Name }}-preflight
subjects:
- kind: ServiceAccount
name: {{ .Release.Name }}-preflight
namespace: {{ .Release.Namespace }}
---
apiVersion: v1
kind: ConfigMap
metadata:
name: {{ .Release.Name }}-preflight-script
annotations:
"helm.sh/hook": pre-upgrade
"helm.sh/hook-weight": "-10"
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
data:
new-roles.sh: |
set -u
# Writes to /work/new each declared role the live Cluster does not manage
# yet.
live=" "
if out=$(kubectl -n {{ .Release.Namespace }} get clusters.postgresql.cnpg.io {{ .Release.Name }} --ignore-not-found -o jsonpath='{"found "}{range .spec.managed.roles[*]}{.name}{" "}{end}'); then
if [ -z "$out" ]; then
echo "Cluster {{ .Release.Name }} does not exist; there is no database to check"
: > /work/new
exit 0
fi
live=" ${out#found } "
else
echo "cannot read Cluster {{ .Release.Name }}; checking every declared name" >&2
fi
: > /work/new
check() {
case "$live" in
*" $3 "*) ;;
*) echo "$1 $2 $3" >> /work/new ;;
esac
}
{{- range $user, $u := .Values.users }}
check user {{ $user }} {{ $user }}
{{- end }}
{{- range $database, $d := .Values.databases }}
check database {{ $database }} {{ $database }}_admin
check database {{ $database }} {{ $database }}_readonly
{{- end }}
echo "new to the Cluster:"
cat /work/new
preflight.sh: |
#!/bin/bash
set -e
if [ ! -s /work/new ]; then
echo "the upgrade adds no role; nothing to check"
exit 0
fi
if [ -z "${PGPASSWORD:-}" ]; then
echo "the superuser Secret is gone, so the Cluster is being deleted; the upgrade adds roles that must be checked first, so it cannot proceed now" >&2
exit 1
fi
until pg_isready ; do
if [ "$SECONDS" -ge 250 ]; then
echo "postgres did not become ready in time; the upgrade adds roles that must be checked first, so it cannot proceed" >&2
exit 1
fi
sleep 5
done
echo "== refuse to adopt unmarked roles"
# The refusal and the create-and-mark run in one psql session per role, so a
# role that appears between them cannot slip through: the create keys on a
# snapshot of whether the role existed, taken at the top of the session, and
# is unconditional, so a role a concurrent CREATEROLE holder plants after the
# snapshot collides with the CREATE and stops the hook rather than being left
# for CNPG to adopt. A declared database role the Cluster does not manage yet
# is created and marked, as the superuser, before the Cluster applies, so the
# name is taken by a role no tenant controls. Users are left to CNPG; only
# database roles are created here.
while read -r kind key role; do
psql -v ON_ERROR_STOP=1 --echo-all -v kind="$kind" -v key="$key" -v role="$role" <<\EOT
SELECT NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = :'role') AS role_absent\gset
SELECT 'CREATE ROLE "cozystack:managed" NOLOGIN'
WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'cozystack:managed')\gexec
SELECT format('DO $$BEGIN RAISE EXCEPTION %L; END$$', format('role "%s" already exists and this chart did not create it; a user of this instance has held createRole, so the role may be controlled by that user and %ss.%s will not adopt it. A platform administrator must inspect the role and drop it as the superuser, or declare the %s under another name', r.rolname, :'kind', :'key', :'kind'))
FROM pg_catalog.pg_roles r
WHERE r.rolname = :'role'
AND current_setting('cozystack.createrole_granted', true) = 'on'
AND NOT EXISTS (SELECT FROM pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed' AND m.member = r.oid)\gexec
SELECT format('CREATE ROLE %I NOINHERIT; COMMENT ON ROLE %I IS %L; GRANT %I TO %I{{ $markOptions }}', :'role', :'role', 'role managed by helm', 'cozystack:managed', :'role')
WHERE :'kind' = 'database' AND :'role_absent'::boolean\gexec
EOT
done < /work/new
---
apiVersion: batch/v1
kind: Job
metadata:
name: {{ .Release.Name }}-preflight
annotations:
"helm.sh/hook": pre-upgrade
"helm.sh/hook-weight": "-5"
"helm.sh/hook-delete-policy": before-hook-creation
spec:
activeDeadlineSeconds: 300
backoffLimit: 0
ttlSecondsAfterFinished: 3600
template:
metadata:
name: {{ .Release.Name }}-preflight
labels:
policy.cozystack.io/allow-to-apiserver: "true"
spec:
restartPolicy: Never
serviceAccountName: {{ .Release.Name }}-preflight
initContainers:
- name: new-roles
image: {{ include "cozy-lib.image" (list "clastix/kubectl:v1.32@sha256:b9ef7d8dbe65bcc81a46c09b8dc7543103055021c4f43287bf59e92a8f4fe05c" $) }}
command:
- /bin/sh
- /scripts/new-roles.sh
env:
- name: HOME
value: /work
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
privileged: false
readOnlyRootFilesystem: true
runAsNonRoot: true
volumeMounts:
- mountPath: /scripts
name: scripts
- mountPath: /work
name: work
{{- include "postgresjobs.resources" . | nindent 8 }}
containers:
- name: postgres
image: {{ include "postgres.imageName" $ }}
command:
- bash
- /scripts/preflight.sh
env:
- name: PGUSER
valueFrom:
secretKeyRef:
name: {{ .Release.Name }}-superuser
key: username
optional: true
- name: PGPASSWORD
valueFrom:
secretKeyRef:
name: {{ .Release.Name }}-superuser
key: password
optional: true
- name: PGHOST
value: {{ .Release.Name }}-rw
- name: PGPORT
value: "5432"
- name: PGDATABASE
value: postgres
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
privileged: false
readOnlyRootFilesystem: true
runAsNonRoot: true
volumeMounts:
- mountPath: /scripts
name: scripts
- mountPath: /work
name: work
{{- include "postgresjobs.resources" . | nindent 8 }}
securityContext:
fsGroup: 26
runAsGroup: 26
runAsNonRoot: true
runAsUser: 26
seccompProfile:
type: RuntimeDefault
volumes:
- name: scripts
configMap:
name: {{ .Release.Name }}-preflight-script
- name: work
emptyDir: {}
{{- end }}
@@ -94,16 +94,6 @@ spec:
name: secret
- mountPath: /scripts
name: scripts
{{- if .Values.users }}
# The init script reads each user's password from this mount at run time
# so the credential is never rendered into the init-script Secret. Gated
# on .Values.users to match the <release>-credentials Secret, which is
# only rendered when there are users: mounting it unconditionally would
# FailedMount a userless release and hang the post-upgrade hook.
- mountPath: /credentials
name: credentials
readOnly: true
{{- end }}
{{- include "postgresjobs.resources" . | nindent 8 }}
securityContext:
fsGroup: 26
@@ -119,9 +109,4 @@ spec:
- name: scripts
secret:
secretName: {{ .Release.Name }}-init-script
{{- if .Values.users }}
- name: credentials
secret:
secretName: {{ .Release.Name }}-credentials
{{- end }}
{{- end }}
+40 -176
View File
@@ -1,34 +1,18 @@
{{- $existingSecret := lookup "v1" "Secret" .Release.Namespace (printf "%s-credentials" .Release.Name) }}
{{- $passwords := dict }}
{{- with (index $existingSecret "data") }}
{{- range $k, $v := . }}
{{- $_ := set $passwords $k (b64dec $v) }}
{{- end }}
{{- end }}
{{/*
Reject a username outside the Secret-key charset before it is interpolated
into the credentials Secret key, the init-script shell (pw=$(cat "/credentials/<user>"))
and the role SQL. The charset mirrors k8s IsConfigMapKey (rejecting ".", any name
starting with "..", and the metacharacters that would reach the shell). The
length cap is 63, NOT the 253-char Secret-key limit: the username is also a
PostgreSQL role name, and an identifier over NAMEDATALEN-1 (63 bytes) is silently
TRUNCATED by CREATE ROLE with a NOTICE, not an error, so ON_ERROR_STOP never sees
it: the role exists under its 63-byte prefix, two long names sharing that prefix
become one role, and the stored name is not the one the tenant declared. Cap at
63 so a too-long name is named here instead. A release that installed before the
cap still carries such a user's key in the credentials Secret read above and its
role under the truncated name; failing its upgrade would wedge the whole release,
so on upgrade the cap applies only to a user that Secret does not already carry,
i.e. a new one. The charset holds on both paths: a name
outside it is not a valid Secret key, so it never installed. The charset is
ASCII-only, so len (bytes) equals characters.
Reject a username outside the charset before it is interpolated into the role
SQL and the Cluster's managed roles. The charset mirrors k8s IsConfigMapKey
(rejecting ".", any name starting with "..", and the metacharacters that would
reach the shell). The length cap is 63: the username is a PostgreSQL role name,
and an identifier over NAMEDATALEN-1 (63 bytes) is silently TRUNCATED by CREATE
ROLE with a NOTICE, not an error, so the role exists under its 63-byte prefix,
two long names sharing that prefix become one role, and the stored name is not
the one the tenant declared. The account name the API derives from it is a DNS
label with the same cap, so the API refuses such a user before the chart sees
it. The charset is ASCII-only, so len (bytes) equals characters.
*/}}
{{- range $user, $u := .Values.users }}
{{- $tooLong := and (gt (len $user) 63) (or $.Release.IsInstall (not (hasKey $passwords $user))) }}
{{- if or (not (regexMatch "^[-._a-zA-Z0-9]+$" $user)) (eq $user ".") (hasPrefix ".." $user) $tooLong }}
{{- 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 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and it becomes a Kubernetes Secret key)" $user) }}
{{- if or (not (regexMatch "^[-._a-zA-Z0-9]+$" $user)) (eq $user ".") (hasPrefix ".." $user) (gt (len $user) 63) }}
{{- 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 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and the account name derived from it is a Kubernetes object name)" $user) }}
{{- end }}
{{- end }}
@@ -81,50 +65,6 @@
{{- fail "`users.postgres` is forbidden by policy. Use a different username." }}
{{- end }}
{{/*
Unlike MariaDB (secret.yaml carries the same lookup with a guard), postgres does
NOT reject an upgrade whose credentials lookup came back empty. The credentials
Secret here is gated on .Values.users, so a release installed with the default
`users: {}` has no Secret at all; adding its FIRST user is an upgrade whose
lookup is legitimately empty, and a guard on `IsUpgrade and not $existingSecret`
cannot tell that apart from a deleted Secret (both are empty). Postgres also has
no equivalent of MariaDB's bootstrap-only root: every role's password is applied
by the post-upgrade init-job (ALTER ROLE), so a re-mint on a genuinely deleted
Secret self-heals on the next reconcile rather than desyncing forever. So mint on
an empty lookup, and let the common first-user-on-upgrade path through.
*/}}
{{/*
Passwords 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.
*/}}
{{- range $user, $u := .Values.users }}
{{- if not (index $passwords $user) }}
{{- $_ := set $passwords $user (randAlphaNum 16) }}
{{- end }}
{{- end }}
{{- if .Values.users }}
apiVersion: v1
kind: Secret
metadata:
name: {{ .Release.Name }}-credentials
{{- if .Values.bootstrap.enabled }}
annotations:
# During a restore the roles recovered from the backup keep their original
# password hashes, but this Secret holds freshly generated passwords and the
# init-job that would apply them (ALTER ROLE) is skipped while bootstrap is
# on. So the values below do NOT authenticate yet; they converge once the app
# leaves bootstrap and the init-job runs. Flag it so a reader (dashboard,
# tenant) does not treat the advertised password as usable mid-restore.
postgres.cozystack.io/credentials-pending: "true"
{{- end }}
stringData:
{{- range $user, $u := .Values.users }}
{{ quote $user }}: {{ quote (index $passwords $user) }}
{{- end }}
{{- end }}
{{/*
Skip the init-script Secret while bootstrap.recovery is in effect.
It only feeds the init-job Job, which is also skipped in that mode
@@ -132,7 +72,6 @@ stringData:
Secret without a consumer; dropping it keeps the chart output minimal.
*/}}
{{- if not .Values.bootstrap.enabled }}
---
apiVersion: v1
kind: Secret
metadata:
@@ -224,77 +163,37 @@ stringData:
END$$;
EOT
echo "== create users"
echo "== mark users"
{{- if .Values.users }}
{{- /*
A CREATEROLE holder can create a role under a name values will declare later,
plant objects owned by it, role settings and default privileges, then drop the
intermediate role it did this through, so the squatted role shows no member at
all by the time it is declared. No catalog check can tell that apart from a
role a platform administrator created, so once any user has held createRole
the chart refuses to adopt a role it did not mark. Before that, adopting is
safe, and it is what a declared users.app does on install with the role CNPG
bootstraps. The flag is read at the start of this session and set only after
it, so the run that first grants createRole still adopts, and every user is
created and marked before any of them holds CREATEROLE.
CNPG creates, passwords and alters each account from the Cluster's
managed roles; a second writer here would fight it. Two things it has no
field for stay: the marker membership, which CNPG grants with the default
options and this re-grant narrows to a record, leaving the options of an
existing membership alone; and the reset of createrole_self_grant, which
an earlier chart set for a createRole user. Both need the role, which
CNPG creates within seconds of the spec but possibly after this hook
starts, so the pass waits for it a bounded time; a role still missing
then keeps CNPG's defaults until the next run.
*/}}
{{- $grantsCreateRole := false }}
{{- $declared := list }}
{{- range $user, $u := .Values.users }}{{ $declared = append $declared (printf "'%s'" $user) }}{{ end }}
roles_from=$SECONDS
until [ "$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT count(*) FROM pg_catalog.pg_roles WHERE rolname IN ({{ join ", " $declared }})")" = "{{ len $declared }}" ]; do
if [ "$SECONDS" -ge $((roles_from + 60)) ]; then
echo "not every declared role exists yet; marking those that do, the next run marks the rest" >&2
break
fi
sleep 2
done
psql -v ON_ERROR_STOP=1 --echo-all <<\EOT
{{- range $user, $u := .Values.users }}
{{- if and (default false $u.createRole) (lt $pgMajor 16) }}
{{- fail (printf "SECURITY: users.%s.createRole requires PostgreSQL 16 or newer. On PostgreSQL 15 and older, a role holding CREATEROLE can grant itself any non-superuser role, including pg_execute_server_program, which escalates to command execution on the instance." $user) }}
{{- end }}
{{- if default false $u.createRole }}
{{- $grantsCreateRole = true }}
{{- end }}
SELECT format('DO $$BEGIN RAISE EXCEPTION %L; END$$', 'role "{{ $user }}" already exists and this chart did not create it; a user of this instance has held createRole, so the role may be controlled by that user and users.{{ $user }} will not adopt it. A platform administrator must inspect the role and drop it as the superuser, or declare the user under another name')
FROM pg_catalog.pg_roles r
WHERE r.rolname = '{{ $user }}'
AND current_setting('cozystack.createrole_granted', true) = 'on'
AND NOT EXISTS (SELECT FROM pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed' AND m.member = r.oid)\gexec
SELECT 'CREATE ROLE "{{ $user }}" LOGIN INHERIT;'
WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '{{ $user }}')\gexec
GRANT "cozystack:managed" TO "{{ $user }}"{{ $markOptions }};
SELECT 'GRANT "cozystack:managed" TO "{{ $user }}"{{ $markOptions }};'
WHERE EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '{{ $user }}')\gexec
SELECT 'ALTER ROLE "{{ $user }}" RESET createrole_self_grant;'
WHERE EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '{{ $user }}')\gexec
{{- end }}
EOT
{{- if $grantsCreateRole }}
psql -v ON_ERROR_STOP=1 --echo-all -c "ALTER DATABASE postgres SET cozystack.createrole_granted = 'on';"
{{- end }}
{{- /*
Each password is read from the mounted <release>-credentials Secret at run
time rather than rendered into this script: the init-script Secret is stored
verbatim in the Helm release manifest and kept for MaxHistory revisions, so a
literal password here would linger in cleartext history a tenant cannot scrub.
psql's :'pw' quotes and escapes the value, so it applies safely whatever
characters it holds. The password does reach psql through -v, i.e. its argv,
readable via /proc/<pid>/cmdline to a process sharing this container's PID
namespace -- but this init container runs alone, and any code with that reach
can already read the mounted /credentials/* files directly, so the argv path
widens no exposure. This rationale is a template comment so it ships ONCE, not
once per user, into the rendered init.sh.
*/}}
{{- range $user, $u := .Values.users }}
pw=$(cat "/credentials/{{ $user }}")
psql -v ON_ERROR_STOP=1 -v pw="$pw" <<\EOT
ALTER ROLE "{{ $user }}" WITH PASSWORD :'pw' LOGIN INHERIT {{ ternary "REPLICATION" "NOREPLICATION" (default false $u.replication) }} {{ ternary "CREATEROLE" "NOCREATEROLE" (default false $u.createRole) }} {{ ternary "BYPASSRLS" "NOBYPASSRLS" (default false $u.bypassRls) }};
{{- /*
PostgreSQL 16 grants a CREATEROLE holder only ADMIN OPTION on the roles it
creates, governed by createrole_self_grant, whose default is empty. ADMIN
OPTION alone allows granting the role onward but not SET ROLE to it, and
creating an object owned by another role requires SET. Without this the
attribute looks functional — CREATE ROLE succeeds — yet the very next
statement a tenant writes, CREATE SCHEMA ... AUTHORIZATION <new role>,
fails with "must be able to SET ROLE". Set as a role-level default so it
applies to every session, and reset when the attribute is withdrawn.
*/}}
{{- if default false $u.createRole }}
ALTER ROLE "{{ $user }}" SET createrole_self_grant = 'set, inherit';
{{- else }}
ALTER ROLE "{{ $user }}" RESET createrole_self_grant;
{{- end }}
COMMENT ON ROLE "{{ $user }}" IS 'user managed by helm';
EOT
{{- end }}
{{- end }}
echo "== delete users"
@@ -479,17 +378,13 @@ stringData:
echo "== create databases and roles"
{{- if .Values.databases }}
{{- /*
The same adoption check as for users. This session starts after the create
users pass has recorded createRole, so the run that first grants it already
refuses: its CREATEROLE holders exist from that pass on.
The database roles are declared in the Cluster's managed roles as well,
but ALTER DATABASE ... OWNER below needs them in this run, so they are
still created here, idempotently, and CNPG then finds them as its spec
says. The refusal to adopt an unmarked role runs in the pre-upgrade hook.
*/}}
psql -v ON_ERROR_STOP=1 --echo-all <<\EOT
{{- range $database, $d := .Values.databases }}
SELECT format('DO $$BEGIN RAISE EXCEPTION %L; END$$', format('role "%s" already exists and this chart did not create it; a user of this instance has held createRole, so the role may be controlled by that user and databases.{{ $database }} will not adopt it. A platform administrator must inspect the role and drop it as the superuser, or declare the database under another name', r.rolname))
FROM pg_catalog.pg_roles r
WHERE r.rolname IN ('{{ $database }}_admin', '{{ $database }}_readonly')
AND current_setting('cozystack.createrole_granted', true) = 'on'
AND NOT EXISTS (SELECT FROM pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed' AND m.member = r.oid)\gexec
SELECT 'CREATE DATABASE "{{ $database }}"'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '{{ $database }}')\gexec
COMMENT ON DATABASE "{{ $database }}" IS 'database managed by helm';
@@ -584,25 +479,6 @@ stringData:
EOT
{{- end }}
echo "== assign roles to users"
psql -v ON_ERROR_STOP=1 --echo-all <<\EOT
{{- range $database, $d := .Values.databases }}
{{- $roles := $d.roles | default dict }}
{{- range $user, $u := $.Values.users }}
{{- if has $user $roles.admin }}
GRANT "{{ $database }}_admin" TO "{{ $user }}";
{{- else }}
REVOKE "{{ $database }}_admin" FROM "{{ $user }}";
{{- end }}
{{- if has $user $roles.readonly }}
GRANT "{{ $database }}_readonly" TO "{{ $user }}";
{{- else }}
REVOKE "{{ $database }}_readonly" FROM "{{ $user }}";
{{- end }}
{{- end }}
{{- end }}
EOT
echo "== create extensions"
{{- range $database, $d := .Values.databases }}
{{- if $d.extensions }}
@@ -1056,15 +932,3 @@ stringData:
{{- end }}
[ -z "$COLLATION_FAILED" ] || exit 1
{{- end }}
{{- if hasKey (.Values.users | default dict) "app" }}
---
{{- /* The bootstrap secret db.yaml gives CNPG for its "app" owner; see there. */}}
apiVersion: v1
kind: Secret
metadata:
name: {{ .Release.Name }}-app-owner
type: kubernetes.io/basic-auth
stringData:
username: app
password: {{ quote (index $passwords "app") }}
{{- end }}
@@ -2,8 +2,8 @@ suite: users.app keeps its password across pod restarts
# "app" is the owner CNPG bootstraps, and CNPG's instance manager re-applies the
# owner's password from the bootstrap secret on every pod restart. A declared
# users.app must therefore hand CNPG a secret holding the very password stored
# in <release>-credentials, or the role reverts to CNPG's generated one.
# users.app must therefore hand CNPG its account Secret, the one its managed
# role reads, or the role reverts to CNPG's generated password.
release:
name: pg-test
@@ -14,81 +14,18 @@ set:
scheduling: {}
tests:
- it: gives CNPG the password users.app has in the credentials Secret
templates:
- templates/init-script.yaml
kubernetesProvider:
scheme:
"v1/Secret":
gvr:
version: v1
resource: secrets
namespaced: true
objects:
- apiVersion: v1
kind: Secret
metadata:
name: pg-test-credentials
namespace: tenant-test
data:
app: Y29uc29sZS1wYXNzd29yZA==
set:
users:
app: {}
asserts:
- equal:
path: stringData.app
value: console-password
documentSelector:
path: metadata.name
value: pg-test-credentials
- equal:
path: stringData.password
value: console-password
documentSelector:
path: metadata.name
value: pg-test-app-owner
- equal:
path: stringData.username
value: app
documentSelector:
path: metadata.name
value: pg-test-app-owner
- equal:
path: type
value: kubernetes.io/basic-auth
documentSelector:
path: metadata.name
value: pg-test-app-owner
# Both Secrets sharing this password is checked by
# hack/check-postgres-app-owner-password.bats, which compares them in one render.
- it: generates a 16-character password for a fresh app owner
- it: renders no owner secret of its own
templates:
- templates/init-script.yaml
set:
users:
app: {}
asserts:
- matchRegex:
path: stringData.password
pattern: ^[a-zA-Z0-9]{16}$
documentSelector:
path: metadata.name
value: pg-test-app-owner
- it: renders no owner secret when no user is named app
templates:
- templates/init-script.yaml
set:
users:
other: {}
asserts:
# pg-test-credentials and pg-test-init-script only
# pg-test-init-script only
- hasDocuments:
count: 2
count: 1
- it: points a new Cluster's initdb at the owner secret
- it: points a new Cluster's initdb at the account Secret
templates:
- templates/db.yaml
set:
@@ -103,9 +40,9 @@ tests:
value:
initdb:
secret:
name: pg-test-app-owner
name: pg-test.app.account
- it: points a live initdb Cluster at the owner secret
- it: points a live initdb Cluster at the account Secret
templates:
- templates/db.yaml
kubernetesProvider:
@@ -136,7 +73,7 @@ tests:
asserts:
- equal:
path: spec.bootstrap.initdb.secret.name
value: pg-test-app-owner
value: pg-test.app.account
- notExists:
path: spec.bootstrap.recovery
@@ -174,7 +111,7 @@ tests:
asserts:
- equal:
path: spec.bootstrap.recovery.secret.name
value: pg-test-app-owner
value: pg-test.app.account
- notExists:
path: spec.bootstrap.initdb
@@ -192,8 +129,8 @@ tests:
path: spec.bootstrap
- it: leaves an in-progress restore's recovery block untouched
# While bootstrap.enabled is on the init-job is skipped and the credentials
# are flagged pending, so the owner password is not taken over mid-restore.
# While bootstrap.enabled is on the init-job is skipped, so the owner
# password is not taken over mid-restore.
templates:
- templates/db.yaml
set:
@@ -265,6 +202,6 @@ tests:
value:
recovery:
secret:
name: pg-test-app-owner
name: pg-test.app.account
- notExists:
path: spec.externalClusters
@@ -0,0 +1,72 @@
suite: one CredentialTemplate per user, naming the account Secret the Cluster reads
# The template is the account the credentials API mints through; its name plus
# ".account" must be the passwordSecret db.yaml gives the managed role, or
# CloudNativePG reads a Secret nobody writes.
templates:
- templates/credentials.yaml
release:
name: pg-test
namespace: tenant-test
set:
_cluster:
scheduling: {}
tests:
- it: renders nothing without users
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: pg-test.bob-smith
documentIndex: 0
- equal:
path: spec.username
value: Bob.Smith
documentIndex: 0
- equal:
path: metadata.name
value: pg-test.web
documentIndex: 1
- it: stores SCRAM verifiers and asks for the reload label
set:
users:
web: {}
asserts:
- equal:
path: spec.format.name
value: scram-sha-256
- equal:
path: spec.secret.labels
value:
cnpg.io/reload: "true"
- notExists:
path: spec.valuesPath
- it: refuses two users that map to one account
set:
users:
web: {}
Web: {}
asserts:
- failedTemplate:
errorPattern: map to
@@ -1,36 +0,0 @@
suite: postgres credentials lookup-backed preservation
release:
name: pg-test
namespace: tenant-test
templates:
- templates/init-script.yaml
tests:
- it: preserves an existing password across renders
# The lookup in init-script.yaml reads back the current Secret, so a user
# keeps the password already stored rather than getting a fresh one on every
# reconcile. kubernetesProvider mocks that existing Secret.
kubernetesProvider:
scheme:
"v1/Secret":
gvr:
version: v1
resource: secrets
namespaced: true
objects:
- apiVersion: v1
kind: Secret
metadata:
name: pg-test-credentials
namespace: tenant-test
data:
testuser: ZXhpc3RpbmdwYXNzd29yZA==
set:
users:
testuser: {}
documentSelector:
path: metadata.name
value: pg-test-credentials
asserts:
- equal:
path: stringData.testuser
value: existingpassword
@@ -1,71 +0,0 @@
suite: postgres credentials generation
# Passwords are always chart-generated (no plaintext input) and preserved across
# reconciles by the lookup in init-script.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.
release:
name: pg-test
namespace: tenant-test
templates:
- templates/init-script.yaml
tests:
- it: generates a 16-char alphanumeric password for each defined user
set:
users:
testuser: {}
documentSelector:
path: metadata.name
value: pg-test-credentials
asserts:
- matchRegex:
path: stringData.testuser
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.
set:
users:
testuser:
password: value-supplied-secret
documentSelector:
path: metadata.name
value: pg-test-credentials
asserts:
- matchRegex:
path: stringData.testuser
pattern: ^[a-zA-Z0-9]{16}$
- notMatchRegex:
path: stringData.testuser
pattern: value-supplied-secret
- it: flags the credentials Secret as pending during a restore
set:
users:
testuser: {}
bootstrap:
enabled: true
oldName: pg-old
documentSelector:
path: metadata.name
value: pg-test-credentials
asserts:
- equal:
path: metadata.annotations["postgres.cozystack.io/credentials-pending"]
value: "true"
- it: does not flag the credentials Secret as pending outside a restore
set:
users:
testuser: {}
documentSelector:
path: metadata.name
value: pg-test-credentials
asserts:
- notExists:
path: metadata.annotations["postgres.cozystack.io/credentials-pending"]
@@ -282,10 +282,7 @@ tests:
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: 'REVOKE "mydb_admin" FROM "app";'
- matchRegex:
path: stringData["init.sh"]
pattern: 'REVOKE "mydb_readonly" FROM "app";'
pattern: 'CREATE EXTENSION IF NOT EXISTS "pg_trgm"'
# Past 54 bytes the name's <db>_admin/<db>_readonly roles truncate past 63
# bytes. The next init-job run orphan-drops the truncated role, DROP OWNED only
@@ -38,27 +38,10 @@ tests:
# name would call it undeclared and drop it on every run, so the declared names
# are compared truncated the same way.
- it: compares declared users truncated to 63 bytes
release:
name: pg-test
namespace: tenant-test
upgrade: true
kubernetesProvider:
scheme:
"v1/Secret":
gvr: {version: v1, resource: secrets}
namespaced: true
objects:
- apiVersion: v1
kind: Secret
metadata:
name: pg-test-credentials
namespace: tenant-test
data:
uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu: ZXhpc3RpbmdwYXNzd29yZA==
set:
users:
app: {}
uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu: {}
uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu: {}
documentSelector:
path: metadata.name
value: pg-test-init-script
@@ -1,195 +0,0 @@
suite: init-script applies user passwords at run time, never in cleartext SQL
# The generated password must NOT be rendered into the init-script SQL. That Secret
# is stored verbatim in the Helm release manifest and retained for MaxHistory
# revisions, so a password baked into `ALTER ROLE ... WITH PASSWORD '<literal>'`
# lingers in cleartext history that a tenant cannot scrub. The init Job must read
# each password from the <release>-credentials Secret at run time instead.
#
# A known password is seeded through kubernetesProvider so the assertions can prove
# that exact value never appears in the rendered init.sh, while the SQL still
# applies it through a psql variable (:'pw'), which psql quotes and escapes safely.
templates:
- templates/init-script.yaml
- templates/init-job.yaml
release:
name: pg-test
namespace: tenant-test
set:
_cluster:
scheduling: {}
tests:
- it: does not write the seeded user password into the init-script SQL
template: templates/init-script.yaml
kubernetesProvider:
scheme:
"v1/Secret":
gvr:
version: v1
resource: secrets
namespaced: true
objects:
- apiVersion: v1
kind: Secret
metadata:
name: pg-test-credentials
namespace: tenant-test
data:
testuser: ZXhpc3RpbmdwYXNzd29yZA==
set:
users:
testuser: {}
documentSelector:
path: metadata.name
value: pg-test-init-script
asserts:
- notMatchRegex:
path: stringData["init.sh"]
pattern: existingpassword
- notMatchRegex:
path: stringData["init.sh"]
pattern: "WITH PASSWORD '"
- it: applies the password through a psql variable read from the mounted Secret
template: templates/init-script.yaml
set:
users:
testuser: {}
documentSelector:
path: metadata.name
value: pg-test-init-script
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: "WITH PASSWORD :'pw'"
- matchRegex:
path: stringData["init.sh"]
pattern: /credentials/testuser
- it: reads every user's password at run time and keeps their replication flag
# Each user gets its own run-time read and psql call; prove the per-user
# wiring holds for more than one user and that the replication attribute still
# rides alongside the run-time password (not lost in the rewrite).
template: templates/init-script.yaml
set:
users:
alice:
replication: true
bob: {}
documentSelector:
path: metadata.name
value: pg-test-init-script
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: 'pw=\$\(cat "/credentials/alice"\)'
- matchRegex:
path: stringData["init.sh"]
pattern: 'pw=\$\(cat "/credentials/bob"\)'
- matchRegex:
path: stringData["init.sh"]
pattern: 'ALTER ROLE "alice" WITH PASSWORD :''pw'' LOGIN INHERIT REPLICATION'
- matchRegex:
path: stringData["init.sh"]
pattern: 'ALTER ROLE "bob" WITH PASSWORD :''pw'' LOGIN INHERIT NOREPLICATION'
- notMatchRegex:
path: stringData["init.sh"]
pattern: "WITH PASSWORD '"
# The runtime-read rationale is a {{/* */}} template comment, so it is stripped
# from the rendered init.sh rather than copied once per user. Reverting it to a
# per-user `#` block makes "cleartext history" reappear (twice, for alice+bob).
- notMatchRegex:
path: stringData["init.sh"]
pattern: cleartext history
- it: still stores each password in the credentials Secret, the single place it lives
# The point of the change is to remove the password from the init-script, NOT
# from the credentials Secret the tenant reads. Pin that it still lands there.
template: templates/init-script.yaml
set:
users:
alice: {}
documentSelector:
path: metadata.name
value: pg-test-credentials
asserts:
- matchRegex:
path: stringData.alice
pattern: ^[a-zA-Z0-9]{16}$
- it: mounts the credentials Secret into the init Job read-only at run time
template: templates/init-job.yaml
set:
users:
testuser: {}
asserts:
- contains:
path: spec.template.spec.volumes
content:
name: credentials
secret:
secretName: pg-test-credentials
- contains:
path: spec.template.spec.containers[0].volumeMounts
content:
name: credentials
mountPath: /credentials
readOnly: true
- it: does not mount the credentials Secret when no users are defined
# The <release>-credentials Secret is rendered only when .Values.users is
# non-empty (init-script.yaml). A userless release (the default users: {}, or
# a databases-only deployment) must therefore NOT mount it, or the init Job
# FailedMounts on a Secret that does not exist and the post-upgrade hook times
# out, failing the release. The create-users loop is already empty here, so
# nothing reads /credentials.
template: templates/init-job.yaml
set:
users: {}
asserts:
- hasDocuments:
count: 1
- notContains:
path: spec.template.spec.volumes
content:
name: credentials
secret:
secretName: pg-test-credentials
- notContains:
path: spec.template.spec.containers[0].volumeMounts
content:
name: credentials
mountPath: /credentials
readOnly: true
# The delete-users loop interpolates a role name into SQL. The username charset
# guard admits "-", "." and uppercase (a valid role name CREATE ROLE quotes), so
# the identifier MUST be quoted in REASSIGN/DROP too, or removing a user named
# e.g. "my-app" emits a syntax error that fails this post-upgrade hook under
# ON_ERROR_STOP and wedges every later reconcile. psql's :"user" quotes it; the
# bare :user form, or the shell splicing $user into the SQL, reddens this.
- it: quotes the identifier in the delete-users SQL
template: templates/init-script.yaml
set:
users:
app: {}
documentSelector:
path: metadata.name
value: pg-test-init-script
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: 'REASSIGN OWNED BY :"user" TO'
- matchRegex:
path: stringData["init.sh"]
pattern: 'DROP OWNED BY :"user"'
- matchRegex:
path: stringData["init.sh"]
pattern: 'DROP USER :"user"'
- notMatchRegex:
path: stringData["init.sh"]
pattern: 'OWNED BY (:user|"?\$user)'
@@ -0,0 +1,241 @@
suite: the Cluster declares every role as CloudNativePG managed roles
# Pins the managed roles render (see the comment in db.yaml for why each role
# is rendered as the init-script created it) and the account Secret naming the
# API shares.
templates:
- templates/db.yaml
release:
name: pg-test
namespace: tenant-test
set:
_cluster:
scheduling: {}
tests:
- it: declares the marker with no login and no comment
set:
users:
app: {}
documentSelector:
path: kind
value: Cluster
asserts:
- contains:
path: spec.managed.roles
content:
name: "cozystack:managed"
login: false
- it: declares the database roles with no login, no inherit, the comment and the marker
set:
databases:
shop: {}
documentSelector:
path: kind
value: Cluster
asserts:
- contains:
path: spec.managed.roles
content:
name: shop_admin
login: false
inherit: false
comment: role managed by helm
inRoles:
- "cozystack:managed"
- contains:
path: spec.managed.roles
content:
name: shop_readonly
login: false
inherit: false
comment: role managed by helm
inRoles:
- "cozystack:managed"
- it: gives an account its database roles through inRoles and its Secret by the account name
set:
users:
Web.App: {}
reporter: {}
databases:
shop:
roles:
admin: [Web.App]
readonly: [reporter]
logs:
roles:
readonly: [Web.App, reporter]
documentSelector:
path: kind
value: Cluster
asserts:
- contains:
path: spec.managed.roles
content:
name: Web.App
login: true
inherit: true
replication: false
createrole: false
bypassrls: false
comment: user managed by helm
inRoles:
- "cozystack:managed"
- logs_readonly
- shop_admin
passwordSecret:
name: pg-test.web-app.account
- contains:
path: spec.managed.roles
content:
name: reporter
inRoles:
- "cozystack:managed"
- logs_readonly
- shop_readonly
passwordSecret:
name: pg-test.reporter.account
any: true
# The same refusal the API makes, for a HelmRelease written around it.
- it: refuses two users that map to one account name
set:
users:
web_app: {}
web-app: {}
asserts:
- failedTemplate:
errorMessage: 'users "web-app" and "web_app" both map to the account name "web-app"; rename one of them'
- it: renders no managed roles beyond the marker for a release without users or databases
documentSelector:
path: kind
value: Cluster
asserts:
- lengthEqual:
path: spec.managed.roles
count: 1
# The account Secret name must be the one the API derives; the same rows are
# pinned for account.MapName in pkg/credentials/account/account_test.go.
- it: names each account Secret as the API does
set:
users:
web: {}
Bob.Smith: {}
app_user: {}
UPPER: {}
x-1: {}
db.user_2: {}
documentSelector:
path: kind
value: Cluster
asserts:
- contains: {path: spec.managed.roles, content: {name: web, passwordSecret: {name: pg-test.web.account}}, any: true}
- contains: {path: spec.managed.roles, content: {name: Bob.Smith, passwordSecret: {name: pg-test.bob-smith.account}}, any: true}
- contains: {path: spec.managed.roles, content: {name: app_user, passwordSecret: {name: pg-test.app-user.account}}, any: true}
- contains: {path: spec.managed.roles, content: {name: UPPER, passwordSecret: {name: pg-test.upper.account}}, any: true}
- contains: {path: spec.managed.roles, content: {name: x-1, passwordSecret: {name: pg-test.x-1.account}}, any: true}
- contains: {path: spec.managed.roles, content: {name: db.user_2, passwordSecret: {name: pg-test.db-user-2.account}}, any: true}
- it: refuses a user whose account name does not start and end with a letter or digit
set:
users:
app_: {}
asserts:
- failedTemplate:
errorMessage: 'user "app_" maps to the account name "app-", which must start and end with a letter or a digit; rename the user'
- it: refuses a user whose account name starts with a dash
set:
users:
_svc: {}
asserts:
- failedTemplate:
errorMessage: 'user "_svc" maps to the account name "-svc", which must start and end with a letter or a digit; rename the user'
- it: refuses a user whose account name ends with a dash
set:
users:
x.: {}
asserts:
- failedTemplate:
errorMessage: 'user "x." maps to the account name "x-", which must start and end with a letter or a digit; rename the user'
- it: refuses the CloudNativePG replication user
set:
users:
streaming_replica: {}
asserts:
- failedTemplate:
errorMessage: 'user "streaming_replica" is reserved: streaming_replica and names starting with pg_ or cnpg_ belong to PostgreSQL and CloudNativePG; rename the user'
- it: refuses names PostgreSQL reserves
set:
users:
pg_owner: {}
asserts:
- failedTemplate:
errorMessage: 'user "pg_owner" is reserved: streaming_replica and names starting with pg_ or cnpg_ belong to PostgreSQL and CloudNativePG; rename the user'
- it: refuses names CloudNativePG reserves
set:
users:
cnpg_pooler: {}
asserts:
- failedTemplate:
errorMessage: 'user "cnpg_pooler" is reserved: streaming_replica and names starting with pg_ or cnpg_ belong to PostgreSQL and CloudNativePG; rename the user'
- it: refuses a user named as a role of a declared database
set:
users:
shop_admin: {}
databases:
shop: {}
asserts:
- failedTemplate:
errorMessage: 'user "shop_admin" is the name of a role of database "shop"; rename the user'
- it: refuses a database whose derived roles PostgreSQL reserves
set:
databases:
pg_stat: {}
asserts:
- failedTemplate:
errorMessage: 'database "pg_stat" is reserved: its roles pg_stat_admin and pg_stat_readonly would start with pg_ or cnpg_, which PostgreSQL and CloudNativePG reserve and the CloudNativePG webhook rejects; rename the database'
- it: refuses a database whose derived roles CloudNativePG reserves
set:
databases:
cnpg_x: {}
asserts:
- failedTemplate:
errorMessage: 'database "cnpg_x" is reserved: its roles cnpg_x_admin and cnpg_x_readonly would start with pg_ or cnpg_, which PostgreSQL and CloudNativePG reserve and the CloudNativePG webhook rejects; rename the database'
- it: refuses a database named pg because pg_admin is reserved
set:
databases:
pg: {}
asserts:
- failedTemplate:
errorMessage: 'database "pg" is reserved: its roles pg_admin and pg_readonly would start with pg_ or cnpg_, which PostgreSQL and CloudNativePG reserve and the CloudNativePG webhook rejects; rename the database'
- it: refuses a database named cnpg because cnpg_admin is reserved
set:
databases:
cnpg: {}
asserts:
- failedTemplate:
errorMessage: 'database "cnpg" is reserved: its roles cnpg_admin and cnpg_readonly would start with pg_ or cnpg_, which PostgreSQL and CloudNativePG reserve and the CloudNativePG webhook rejects; rename the database'
- it: allows a database whose name merely begins with pg
set:
databases:
pgdata: {}
asserts:
- notFailedTemplate: {}
@@ -87,7 +87,10 @@ tests:
path: stringData["init.sh"]
pattern: 'INHERIT FALSE'
- it: refuses to adopt an unmarked user role once createRole has been granted, before creating it
# The refusal to adopt an unmarked role lives in the pre-upgrade hook
# (preflight_test.yaml); the init-script creates no account and marks only a
# role that exists.
- it: no longer refuses or creates user roles itself
set:
users:
debezium:
@@ -96,41 +99,17 @@ tests:
path: metadata.name
value: pg-test-init-script
asserts:
- notMatchRegex:
path: stringData["init.sh"]
pattern: 'already exists and this chart did not create it'
- notMatchRegex:
path: stringData["init.sh"]
pattern: 'CREATE ROLE "debezium"'
- matchRegex:
path: stringData["init.sh"]
pattern: "SELECT format\\('DO \\$\\$BEGIN RAISE EXCEPTION %L; END\\$\\$', 'role \"debezium\" already exists and this chart did not create it; [^']*'\\)\\nFROM pg_catalog.pg_roles r\\nWHERE r.rolname = 'debezium'\\n AND current_setting\\('cozystack.createrole_granted', true\\) = 'on'\\n AND NOT EXISTS \\(SELECT FROM pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed' AND m.member = r.oid\\)\\\\gexec\\nSELECT 'CREATE ROLE \"debezium\" LOGIN INHERIT;'"
pattern: "SELECT 'GRANT \"cozystack:managed\" TO \"debezium\" WITH INHERIT FALSE, SET FALSE;'\nWHERE EXISTS \\(SELECT FROM pg_catalog.pg_roles WHERE rolname = 'debezium'\\)\\\\gexec"
- it: refuses to adopt unmarked database roles once createRole has been granted, before creating the database
set:
databases:
newdb: {}
documentSelector:
path: metadata.name
value: pg-test-init-script
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: "WHERE r.rolname IN \\('newdb_admin', 'newdb_readonly'\\)\\n AND current_setting\\('cozystack.createrole_granted', true\\) = 'on'\\n AND NOT EXISTS \\(SELECT FROM pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed' AND m.member = r.oid\\)\\\\gexec\\nSELECT 'CREATE DATABASE \"newdb\"'"
# The flag is set after every user is created and marked, so the run that first
# grants createRole still adopts a role that predates it, such as the one CNPG
# bootstraps for users.app, and before any CREATEROLE is granted, so no holder
# exists while it is unset.
- it: records createRole after creating and marking the users and before granting the attribute
set:
users:
app: {}
migrator:
createRole: true
documentSelector:
path: metadata.name
value: pg-test-init-script
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: "(?s)GRANT \"cozystack:managed\" TO \"migrator\" WITH INHERIT FALSE, SET FALSE;\\nEOT\\npsql -v ON_ERROR_STOP=1 --echo-all -c \"ALTER DATABASE postgres SET cozystack.createrole_granted = 'on';\".*ALTER ROLE \"migrator\" WITH PASSWORD :'pw' LOGIN INHERIT NOREPLICATION CREATEROLE"
- it: does not record createRole when no user holds it
- it: never records createRole
set:
users:
app: {}
@@ -141,3 +120,18 @@ tests:
- notMatchRegex:
path: stringData["init.sh"]
pattern: 'SET cozystack.createrole_granted'
# CNPG creates the roles from the spec, possibly after this hook starts; the
# marking pass waits for every declared one, bounded, before it runs.
- it: waits a bounded time for the declared roles before marking them
set:
users:
web: {}
Bob.Smith: {}
documentSelector:
path: metadata.name
value: pg-test-init-script
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: "roles_from=\\$SECONDS\\nuntil \\[ \"\\$\\(psql -v ON_ERROR_STOP=1 -t -A -c \"SELECT count\\(\\*\\) FROM pg_catalog.pg_roles WHERE rolname IN \\('Bob.Smith', 'web'\\)\"\\)\" = \"2\" \\]; do\\n if \\[ \"\\$SECONDS\" -ge \\$\\(\\(roles_from \\+ 60\\)\\) \\]; then"
@@ -0,0 +1,60 @@
suite: no tenant password in any rendered object
# After the conversion the chart renders only references to the account Secrets
# the Cozystack API writes: no <release>-credentials Secret, no password in the
# init-script, no Role granting a credentials Secret, and the init-job mounts
# none. A tenant obtains a password by a mint on the account's Credential, once.
release:
name: pg-test
namespace: tenant-test
set:
_cluster:
scheduling: {}
users:
app: {}
reporter:
replication: true
databases:
shop:
roles:
admin: [app]
readonly: [reporter]
tests:
- it: renders only the init-script Secret from the template that rendered the credentials Secret
template: templates/init-script.yaml
asserts:
- hasDocuments:
count: 1
- isKind:
of: Secret
- equal:
path: metadata.name
value: pg-test-init-script
- it: writes no password statement into the init-script
template: templates/init-script.yaml
documentSelector:
path: metadata.name
value: pg-test-init-script
asserts:
- notMatchRegex:
path: stringData["init.sh"]
pattern: 'PASSWORD'
- notMatchRegex:
path: stringData["init.sh"]
pattern: '/credentials/'
- it: mounts no credentials into the init-job
template: templates/init-job.yaml
documentSelector:
path: kind
value: Job
asserts:
- notContains:
path: spec.template.spec.volumes
content:
name: credentials
any: true
@@ -14,28 +14,18 @@ tests:
asserts:
- matchRegexRaw:
pattern: 'provisioned as a restore'
# The passwords of a restored application come from its account Secrets,
# applied by CloudNativePG once the primary is up, and a seeded account
# has none issued until a mint. The note must say that, and must not
# describe a chart-rendered Secret or a pending-credentials flag, which
# the conversion removed.
- matchRegexRaw:
pattern: 'pg-test-credentials Secret now holds freshly generated passwords'
- matchRegexRaw:
pattern: 'postgres\.cozystack\.io/credentials-pending'
# The flag is gated on bootstrap.enabled (init-script.yaml), which the
# restore driver clears at the START of convergence, so it is absent for
# the window before the init-job finishes. NOTES must not claim the flag
# persists "until this converges" and must point at an application login as
# the real check. Restoring that overclaim turns this red.
pattern: 'mint'
- notMatchRegexRaw:
pattern: 'until this converges'
- matchRegexRaw:
pattern: 'That flag tracks only'
- matchRegexRaw:
pattern: 'Do not read a missing flag as "converged"'
- matchRegexRaw:
pattern: 'Confirm convergence by logging in as an'
pattern: 'credentials-pending'
- notMatchRegexRaw:
pattern: 'pg-test-credentials'
# The credentials Secret is gated on .Values.users in init-script.yaml, so a
# users-less restore never renders it. NOTES must not then describe that Secret
# and its pending-credentials annotation, or an operator chases a nonexistent
# object. Reverting the gate to bootstrap-only turns this red.
- it: stays quiet during a restore when there are no users
set:
bootstrap:
@@ -44,8 +34,6 @@ tests:
asserts:
- notMatchRegexRaw:
pattern: 'provisioned as a restore'
- notMatchRegexRaw:
pattern: 'credentials-pending'
- it: stays quiet for a normal install
set:
@@ -0,0 +1,262 @@
suite: pre-upgrade hook refuses to adopt a role the chart did not mark
# Pins the pre-upgrade refusal (see preflight-job.yaml for why it runs before
# the upgrade and reads the live Cluster at run time): the declared names the
# run compares, the database check only for what is new, the gates on install
# and bootstrap, and that the createRole flag an earlier chart set is read but
# never set.
templates:
- templates/hooks/preflight-job.yaml
release:
name: pg-test
namespace: tenant-test
set:
_cluster:
scheduling: {}
tests:
- it: renders nothing on install
set:
users:
app: {}
asserts:
- hasDocuments:
count: 0
- it: renders nothing while bootstrap.recovery is in effect
release:
name: pg-test
namespace: tenant-test
upgrade: true
set:
users:
app: {}
bootstrap:
enabled: true
oldName: pg-old
asserts:
- hasDocuments:
count: 0
- it: renders nothing for a release without users or databases
release:
name: pg-test
namespace: tenant-test
upgrade: true
asserts:
- hasDocuments:
count: 0
- it: hands every declared user and database role to the comparison with the live Cluster
release:
name: pg-test
namespace: tenant-test
upgrade: true
set:
version: v18
users:
debezium: {}
migrator: {}
databases:
newdb: {}
documentSelector:
path: metadata.name
value: pg-test-preflight-script
asserts:
- matchRegex:
path: data["new-roles.sh"]
pattern: "kubectl -n tenant-test get clusters.postgresql.cnpg.io pg-test --ignore-not-found -o jsonpath='\\{\"found \"\\}\\{range .spec.managed.roles\\[\\*\\]\\}\\{.name\\}\\{\" \"\\}\\{end\\}'"
- matchRegex:
path: data["new-roles.sh"]
pattern: "\\ncheck user debezium debezium\\ncheck user migrator migrator\\ncheck database newdb newdb_admin\\ncheck database newdb newdb_readonly\\n"
# The point of reading the Cluster first: an upgrade that adds no role never
# waits for the database, so a database that is down does not block it.
- it: leaves before waiting for the database when nothing is new
release:
name: pg-test
namespace: tenant-test
upgrade: true
set:
users:
web: {}
documentSelector:
path: metadata.name
value: pg-test-preflight-script
asserts:
- matchRegex:
path: data["preflight.sh"]
pattern: "(?s)if \\[ ! -s /work/new \\]; then\\n[^\\n]*\\n exit 0\\nfi\\n.*until pg_isready"
# A restore purges the Cluster under an upgrade in flight. Without a Cluster
# there is no database to plant a role in, and once its superuser Secret is
# gone a container that required it would wait out the Job deadline, holding
# the release in this hook.
- it: passes without a Cluster and fails at once when the Cluster goes away mid-check
release:
name: pg-test
namespace: tenant-test
upgrade: true
set:
users:
web: {}
documentSelector:
path: metadata.name
value: pg-test-preflight-script
asserts:
- matchRegex:
path: data["new-roles.sh"]
pattern: "(?s)if \\[ -z \"\\$out\" \\]; then\\n.*: > /work/new\\n exit 0\\n fi\\n live=\" \\$\\{out#found \\} \""
- matchRegex:
path: data["preflight.sh"]
pattern: "(?s)if \\[ ! -s /work/new \\]; then\\n.*exit 0\\nfi\\nif \\[ -z \"\\$\\{PGPASSWORD:-\\}\" \\]; then\\n.*exit 1\\nfi\\nuntil pg_isready"
- it: starts the check container when the superuser Secret is missing
release:
name: pg-test
namespace: tenant-test
upgrade: true
set:
users:
web: {}
documentSelector:
path: kind
value: Job
asserts:
- equal:
path: spec.template.spec.containers[0].env[0].valueFrom.secretKeyRef
value:
name: pg-test-superuser
key: username
optional: true
- equal:
path: spec.template.spec.containers[0].env[1].valueFrom.secretKeyRef
value:
name: pg-test-superuser
key: password
optional: true
- it: refuses an unmarked role only for the names the run found new
release:
name: pg-test
namespace: tenant-test
upgrade: true
set:
users:
debezium: {}
documentSelector:
path: metadata.name
value: pg-test-preflight-script
asserts:
- matchRegex:
path: data["preflight.sh"]
pattern: "while read -r kind key role; do\\n psql -v ON_ERROR_STOP=1 --echo-all -v kind=\"\\$kind\" -v key=\"\\$key\" -v role=\"\\$role\""
- matchRegex:
path: data["preflight.sh"]
pattern: "WHERE r.rolname = :'role'\\n AND current_setting\\('cozystack.createrole_granted', true\\) = 'on'\\n AND NOT EXISTS \\(SELECT FROM pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed' AND m.member = r.oid\\)\\\\gexec"
- notMatchRegex:
path: data["preflight.sh"]
pattern: "cozystack.createrole_granted = 'on'"
- it: may read only its own Cluster
release:
name: pg-test
namespace: tenant-test
upgrade: true
set:
users:
web: {}
documentSelector:
path: kind
value: Role
asserts:
- equal:
path: rules
value:
- apiGroups: ["postgresql.cnpg.io"]
resources: ["clusters"]
resourceNames: ["pg-test"]
verbs: ["get"]
- equal:
path: metadata.annotations["helm.sh/hook"]
value: pre-upgrade
- it: runs as a bounded pre-upgrade Job that can reach the API server
release:
name: pg-test
namespace: tenant-test
upgrade: true
set:
users:
app: {}
documentSelector:
path: kind
value: Job
asserts:
- equal:
path: metadata.annotations["helm.sh/hook"]
value: pre-upgrade
- equal:
path: spec.activeDeadlineSeconds
value: 300
- equal:
path: spec.backoffLimit
value: 0
- equal:
path: spec.template.spec.serviceAccountName
value: pg-test-preflight
- equal:
path: spec.template.metadata.labels["policy.cozystack.io/allow-to-apiserver"]
value: "true"
- equal:
path: spec.template.spec.initContainers[0].command
value: ["/bin/sh", "/scripts/new-roles.sh"]
- equal:
path: spec.template.spec.containers[0].env[2].value
value: pg-test-rw
- it: creates and marks each absent declared database role as the superuser on pg16+
release:
upgrade: true
set:
version: v18
databases:
shop: {}
documentSelector:
path: metadata.name
value: pg-test-preflight-script
asserts:
# The refusal and the create-and-mark run in one psql session, keyed on a
# snapshot of whether the role existed, so a role planted between them
# collides with the unconditional CREATE and stops the hook.
- matchRegex:
path: data["preflight.sh"]
pattern: "SELECT NOT EXISTS \\(SELECT FROM pg_catalog.pg_roles WHERE rolname = :'role'\\) AS role_absent\\\\gset"
# The create and mark run as a top-level SELECT format(...) + \gexec, not a
# DO block: psql does not substitute :'role' inside a dollar-quoted body,
# so it would reach PostgreSQL literally and the hook would fail to parse.
- matchRegex:
path: data["preflight.sh"]
pattern: "SELECT format\\('CREATE ROLE %I NOINHERIT; COMMENT ON ROLE %I IS %L; GRANT %I TO %I WITH INHERIT FALSE, SET FALSE', :'role', :'role', 'role managed by helm', 'cozystack:managed', :'role'\\)"
# The create is gated on the snapshot, not a live NOT EXISTS, so it is
# unconditional and fails closed on a concurrent plant.
- matchRegex:
path: data["preflight.sh"]
pattern: "WHERE :'kind' = 'database' AND :'role_absent'::boolean"
- it: marks a hook-created database role without the pg16 options on older PostgreSQL
release:
upgrade: true
set:
version: v15
databases:
shop: {}
documentSelector:
path: metadata.name
value: pg-test-preflight-script
asserts:
- matchRegex:
path: data["preflight.sh"]
pattern: "SELECT format\\('CREATE ROLE %I NOINHERIT; COMMENT ON ROLE %I IS %L; GRANT %I TO %I', :'role', :'role', 'role managed by helm', 'cozystack:managed', :'role'\\)"
@@ -1,22 +1,17 @@
suite: per-user CREATEROLE attribute
# users.<name>.createRole grants the CREATEROLE role attribute to a managed login
# user, so a tenant can create and manage its own roles without the postgres
# superuser. Role attributes are not inherited through role membership, so the
# attribute cannot be carried by the generated <db>_admin group role and has to be
# set on the login user itself.
#
# The attribute is reconciled on every run of the init script: flipping createRole
# back to false emits NOCREATEROLE and revokes it.
#
# The guard on PostgreSQL 16 is a security boundary, not a cosmetic check. Before
# PostgreSQL 16, CREATEROLE allowed granting membership in any non-superuser role,
# so a user holding it could grant itself pg_execute_server_program and reach
# command execution on the instance. PostgreSQL 16 restricted CREATEROLE to roles
# the grantee administers, which is what makes the attribute safe to expose.
# users.<name>.createRole is refused while users are CloudNativePG managed
# roles. A role a CREATEROLE user creates makes that user a member of it;
# CloudNativePG revokes every membership a managed role is not declared to hold,
# and the revoke fails on the dependent self-grant, which leaves the user stuck
# in cannotReconcile on ordinary use. CloudNativePG has no per-role switch to
# leave memberships alone. The refusal renders with the Cluster, on every path,
# recovery included, so an existing release that grants it keeps its previous
# chart version until the flag is set to false.
templates:
- templates/init-script.yaml
- templates/db.yaml
release:
name: pg-test
@@ -31,104 +26,126 @@ tests:
set:
users:
app: {}
documentIndex: 1
template: templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: 'ALTER ROLE "app" WITH PASSWORD .* NOREPLICATION NOCREATEROLE NOBYPASSRLS;'
- contains:
path: spec.managed.roles
content:
name: app
login: true
inherit: true
replication: false
createrole: false
bypassrls: false
comment: user managed by helm
inRoles:
- "cozystack:managed"
passwordSecret:
name: pg-test.app.account
- it: "createRole=true emits CREATEROLE"
- it: "createRole=true is refused while users are managed roles"
set:
version: v18
users:
app:
createRole: true
documentIndex: 1
template: templates/db.yaml
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: 'ALTER ROLE "app" WITH PASSWORD .* NOREPLICATION CREATEROLE NOBYPASSRLS;'
- failedTemplate:
errorMessage: "users.app.createRole is not supported: users are CloudNativePG managed roles, which revoke the membership PostgreSQL gives a CREATEROLE user in each role it creates. Set createRole to false; an existing release with it keeps its previous chart version until then"
- it: "createRole=false emits NOCREATEROLE so the attribute is revoked"
- it: "createRole=false renders createrole false, so a role that held it loses it"
set:
version: v18
users:
app:
createRole: false
documentIndex: 1
template: templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: 'ALTER ROLE "app" WITH PASSWORD .* NOCREATEROLE NOBYPASSRLS;'
- contains:
path: spec.managed.roles
content:
name: app
createrole: false
any: true
- it: "createRole composes with replication"
set:
version: v18
users:
app:
replication: true
createRole: true
documentIndex: 1
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: 'ALTER ROLE "app" WITH PASSWORD .* REPLICATION CREATEROLE NOBYPASSRLS;'
- it: "createRole on PostgreSQL 15 fails fast"
- it: "createRole on PostgreSQL 15 is refused"
set:
version: v15
users:
app:
createRole: true
template: templates/db.yaml
asserts:
- failedTemplate:
errorMessage: "SECURITY: users.app.createRole requires PostgreSQL 16 or newer. On PostgreSQL 15 and older, a role holding CREATEROLE can grant itself any non-superuser role, including pg_execute_server_program, which escalates to command execution on the instance."
errorMessage: "users.app.createRole is not supported: users are CloudNativePG managed roles, which revoke the membership PostgreSQL gives a CREATEROLE user in each role it creates. Set createRole to false; an existing release with it keeps its previous chart version until then"
- it: "createRole on PostgreSQL 13 fails fast"
- it: "createRole on PostgreSQL 13 is refused"
set:
version: v13
users:
app:
createRole: true
template: templates/db.yaml
asserts:
- failedTemplate:
errorMessage: "SECURITY: users.app.createRole requires PostgreSQL 16 or newer. On PostgreSQL 15 and older, a role holding CREATEROLE can grant itself any non-superuser role, including pg_execute_server_program, which escalates to command execution on the instance."
errorMessage: "users.app.createRole is not supported: users are CloudNativePG managed roles, which revoke the membership PostgreSQL gives a CREATEROLE user in each role it creates. Set createRole to false; an existing release with it keeps its previous chart version until then"
# The refusal renders with the Cluster, so a restore cannot get past it.
# roles do, so the guard sits with them.
- it: "createRole on PostgreSQL 15 is refused on recovery too"
set:
version: v15
bootstrap:
enabled: true
oldName: pg-old
backup:
s3AccessKey: a
s3SecretKey: b
users:
migrator:
createRole: true
template: templates/db.yaml
asserts:
- failedTemplate:
errorMessage: "users.migrator.createRole is not supported: users are CloudNativePG managed roles, which revoke the membership PostgreSQL gives a CREATEROLE user in each role it creates. Set createRole to false; an existing release with it keeps its previous chart version until then"
- it: "createRole on PostgreSQL 13 is refused on recovery too"
set:
version: v13
bootstrap:
enabled: true
oldName: pg-old
backup:
s3AccessKey: a
s3SecretKey: b
users:
migrator:
createRole: true
template: templates/db.yaml
asserts:
- failedTemplate:
errorMessage: "users.migrator.createRole is not supported: users are CloudNativePG managed roles, which revoke the membership PostgreSQL gives a CREATEROLE user in each role it creates. Set createRole to false; an existing release with it keeps its previous chart version until then"
- it: "PostgreSQL 15 renders fine as long as createRole is not requested"
set:
version: v15
users:
app: {}
documentIndex: 1
template: templates/init-script.yaml
documentSelector:
path: metadata.name
value: pg-test-init-script
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: 'ALTER ROLE "app" WITH PASSWORD .* NOCREATEROLE NOBYPASSRLS;'
- it: "bypassRls=true emits BYPASSRLS"
set:
version: v18
users:
app:
bypassRls: true
documentIndex: 1
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: 'ALTER ROLE "app" WITH PASSWORD .* NOCREATEROLE BYPASSRLS;'
- it: "bypassRls composes with createRole, which is what provisioning a privileged service role needs"
set:
version: v18
users:
app:
createRole: true
bypassRls: true
documentIndex: 1
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: 'ALTER ROLE "app" WITH PASSWORD .* CREATEROLE BYPASSRLS;'
pattern: 'GRANT "cozystack:managed" TO "app";'
- it: "bypassRls is allowed on PostgreSQL 15, it carries no escalation path of its own"
set:
@@ -136,32 +153,45 @@ tests:
users:
app:
bypassRls: true
documentIndex: 1
template: templates/db.yaml
documentSelector:
path: kind
value: Cluster
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: 'ALTER ROLE "app" WITH PASSWORD .* NOCREATEROLE BYPASSRLS;'
- it: "createRole sets createrole_self_grant so the attribute is usable"
set:
version: v18
users:
app:
createRole: true
documentIndex: 1
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: "ALTER ROLE \"app\" SET createrole_self_grant = 'set, inherit';"
- contains:
path: spec.managed.roles
content:
name: app
bypassrls: true
any: true
# A role that held createRole under an earlier chart keeps its
# createrole_self_grant until this reset, which runs once the role exists.
- it: "withdrawing createRole resets createrole_self_grant"
set:
version: v18
users:
app:
createRole: false
documentIndex: 1
template: templates/init-script.yaml
documentSelector:
path: metadata.name
value: pg-test-init-script
asserts:
- matchRegex:
path: stringData["init.sh"]
pattern: 'ALTER ROLE "app" RESET createrole_self_grant;'
pattern: "SELECT 'ALTER ROLE \"app\" RESET createrole_self_grant;'\\nWHERE EXISTS \\(SELECT FROM pg_catalog.pg_roles WHERE rolname = 'app'\\)\\\\gexec"
- it: "does not fail the wait when no user holds createRole"
set:
version: v18
users:
app: {}
template: templates/init-script.yaml
documentSelector:
path: metadata.name
value: pg-test-init-script
asserts:
- notMatchRegex:
path: stringData["init.sh"]
pattern: "createRole users still absent"
@@ -1,15 +1,14 @@
suite: init-script rejects a username outside the safe charset
# The username becomes a Kubernetes Secret data key AND is interpolated into the
# init-script shell (pw=$(cat "/credentials/<user>")) and role SQL. A name with a
# shell metacharacter is a command-injection shape; the apiserver would reject it
# later as an invalid Secret key with an opaque error. The chart must reject it at
# render time, naming the offending username, so the metacharacter never reaches
# the script. Reverting the guard in init-script.yaml lets the render succeed,
# so the first test fails.
# The username is interpolated into the init-script shell and role SQL and into
# the Cluster's managed roles. A name with a shell metacharacter is a
# command-injection shape. The chart must reject it at render time, naming the
# offending username, so the metacharacter never reaches the script. Reverting
# the guard in init-script.yaml lets the render succeed, so the first test fails.
templates:
- templates/init-script.yaml
- templates/db.yaml
release:
name: pg-test
@@ -21,50 +20,55 @@ set:
tests:
- it: fails the render for a username carrying a shell metacharacter
template: templates/init-script.yaml
set:
users:
'evil";id;echo "x': {}
asserts:
- failedTemplate:
errorMessage: 'invalid username "evil\";id;echo \"x": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and it becomes a Kubernetes Secret key)'
errorMessage: 'invalid username "evil\";id;echo \"x": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and the account name derived from it is a Kubernetes object name)'
- it: fails the render for a username with a space
template: templates/init-script.yaml
set:
users:
'a b': {}
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 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and it 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 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and the account name derived from it is a Kubernetes object name)'
# "." and ".." match the charset regex but are rejected by k8s IsConfigMapKey as
# Secret keys, so the guard rejects them explicitly (the length cap is a separate,
# PostgreSQL-driven concern pinned by the 63/64 boundary tests below). These pin
# the guard to the full IsConfigMapKey contract.
- it: fails the render for the reserved name "."
template: templates/init-script.yaml
set:
users:
'.': {}
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 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and it 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 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and the account name derived from it is a Kubernetes object name)'
- it: fails the render for the reserved name ".."
template: templates/init-script.yaml
set:
users:
'..': {}
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 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and it 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 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and the account name derived from it is a Kubernetes object name)'
# IsConfigMapKey rejects ANY name starting with ".." (hasChDirPrefix), not just
# the literal "..", so "..foo" is charset-legal yet cannot install.
- it: fails the render for a name starting with ".."
template: templates/init-script.yaml
set:
users:
'..foo': {}
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 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and it 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 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and the account name derived from it is a Kubernetes object name)'
# A username is a PostgreSQL role name: CREATE ROLE silently truncates past 63
# bytes (NAMEDATALEN-1) with a NOTICE, not an error, so a 64-char name would be
@@ -73,36 +77,45 @@ tests:
# 253-char Secret-key limit. 64 chars fails; 63 renders. Reverting the cap to 253
# lets the 64-char case through.
- it: fails the render for a username of 64 characters (past the 63-byte role limit)
template: templates/init-script.yaml
set:
users:
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa': {}
asserts:
- failedTemplate:
errorMessage: 'invalid username "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and it becomes a Kubernetes Secret key)'
errorMessage: 'invalid username "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and the account name derived from it is a Kubernetes object name)'
- it: renders normally for a username at the 63-character boundary
set:
users:
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa': {}
template: templates/db.yaml
documentSelector:
path: metadata.name
value: pg-test-credentials
path: kind
value: Cluster
asserts:
- matchRegex:
path: stringData["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]
pattern: ^[a-zA-Z0-9]{16}$
- contains:
path: spec.managed.roles
content:
name: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
any: true
- it: renders normally for names using the full safe charset
set:
users:
a-b.c_1: {}
template: templates/db.yaml
documentSelector:
path: metadata.name
value: pg-test-credentials
path: kind
value: Cluster
asserts:
- matchRegex:
path: stringData["a-b.c_1"]
pattern: ^[a-zA-Z0-9]{16}$
- contains:
path: spec.managed.roles
content:
name: a-b.c_1
passwordSecret:
name: pg-test.a-b-c-1.account
any: true
# `postgres` is the CNPG-managed superuser and is forbidden as an app role. The
# rejection must not depend on bootstrap.enabled: while it is true the
@@ -114,6 +127,7 @@ tests:
# one. Moving the guard back inside the `not .Values.bootstrap.enabled` block
# lets the bootstrap case render, so this test fails.
- it: rejects users.postgres even while bootstrap.enabled is true
template: templates/init-script.yaml
set:
bootstrap:
enabled: true
@@ -125,6 +139,7 @@ tests:
errorMessage: '`users.postgres` is forbidden by policy. Use a different username.'
- it: rejects users.postgres on the normal (non-bootstrap) path too
template: templates/init-script.yaml
set:
users:
postgres:
@@ -132,115 +147,3 @@ tests:
asserts:
- failedTemplate:
errorMessage: '`users.postgres` is forbidden by policy. Use a different username.'
# The credentials Secret is gated on .Values.users, so a release installed with
# the default `users: {}` has none. Adding its FIRST user is an upgrade whose
# lookup is legitimately empty — indistinguishable at render time from a deleted
# Secret — so postgres must NOT reject an empty-lookup upgrade (that would hard-
# block the common first-user path). It mints instead; the post-upgrade init-job
# applies the password. Re-adding a `not $existingSecret` fail on IsUpgrade turns
# this red — the regression this pins (a userless release could no longer gain a
# user). MariaDB is the opposite case (its Secret always exists via root, and
# root desyncs permanently), so its guard stays; see mariadb secret.yaml.
- it: mints when the first user is added to a userless release on upgrade
release:
name: pg-test
namespace: tenant-test
upgrade: true
set:
users:
app: {}
documentSelector:
path: metadata.name
value: pg-test-credentials
asserts:
- matchRegex:
path: stringData.app
pattern: ^[a-zA-Z0-9]{16}$
# A username of 64+ bytes installed before the 63 cap: its credentials Secret
# key was written, while the role itself was truncated and dropped in the same
# hook. Failing the render on the next upgrade would wedge the whole release
# over a user that never worked, so on upgrade the cap applies only to a user
# the existing credentials Secret does not already carry, i.e. a NEW user.
# Applying the cap on upgrade regardless of the Secret makes the first case
# fail to render; dropping the Secret-key conjunct lets the second render, so
# it fails.
- it: renders on upgrade for a 64-character user the credentials Secret already carries
release:
name: pg-test
namespace: tenant-test
upgrade: true
kubernetesProvider:
scheme:
"v1/Secret":
gvr: {version: v1, resource: secrets}
namespaced: true
objects:
- apiVersion: v1
kind: Secret
metadata:
name: pg-test-credentials
namespace: tenant-test
data:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: ZXhpc3RpbmdwYXNzd29yZA==
set:
users:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: {}
documentSelector:
path: metadata.name
value: pg-test-credentials
asserts:
- equal:
path: stringData["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]
value: existingpassword
- it: still fails on upgrade for a NEW 64-character user
release:
name: pg-test
namespace: tenant-test
upgrade: true
kubernetesProvider:
scheme:
"v1/Secret":
gvr: {version: v1, resource: secrets}
namespaced: true
objects:
- apiVersion: v1
kind: Secret
metadata:
name: pg-test-credentials
namespace: tenant-test
data:
app: ZXhpc3RpbmdwYXNzd29yZA==
set:
users:
app: {}
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: {}
asserts:
- failedTemplate:
errorMessage: 'invalid username "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and it becomes a Kubernetes Secret key)'
# A fresh install has no release to protect, so the cap holds even when a stale
# credentials Secret left in the namespace happens to carry the key. Dropping
# the ".Release.IsInstall" conjunct lets the render succeed, so this fails.
- it: still fails on install for a 64-character user a stale Secret carries
kubernetesProvider:
scheme:
"v1/Secret":
gvr: {version: v1, resource: secrets}
namespaced: true
objects:
- apiVersion: v1
kind: Secret
metadata:
name: pg-test-credentials
namespace: tenant-test
data:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: ZXhpc3RpbmdwYXNzd29yZA==
set:
users:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: {}
asserts:
- failedTemplate:
errorMessage: 'invalid username "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": a username may contain only letters, digits and the characters -._ , must not be "." or start with "..", and must be at most 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and it becomes a Kubernetes Secret key)'
+3 -3
View File
@@ -320,18 +320,18 @@
}
},
"users": {
"description": "Users configuration map. Passwords 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 PostgreSQL role 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 SCRAM verifier, and a revoke retires the password without issuing one. A `password` key here is ignored and draws an admission warning. A password set inside PostgreSQL is reverted by the operator.",
"type": "object",
"default": {},
"additionalProperties": {
"type": "object",
"properties": {
"bypassRls": {
"description": "Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role.",
"description": "Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself.",
"type": "boolean"
},
"createRole": {
"description": "Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role.",
"description": "Not supported while users are CloudNativePG managed roles: the chart refuses to render when it is true, and a release that sets it keeps its previous chart version until it is false. CloudNativePG revokes every membership a managed role is not declared to hold, including the one PostgreSQL gives a CREATEROLE user in each role it creates. Setting it to false withdraws CREATEROLE from a role that held it.",
"type": "boolean"
},
"replication": {
+3 -4
View File
@@ -280,10 +280,10 @@ autoscaling:
## @typedef {struct} User - User configuration.
## @field {bool} [replication] - Whether the user has replication privileges.
## @field {bool} [createRole] - Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role.
## @field {bool} [bypassRls] - Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role.
## @field {bool} [createRole] - Not supported while users are CloudNativePG managed roles: the chart refuses to render when it is true, and a release that sets it keeps its previous chart version until it is false. CloudNativePG revokes every membership a managed role is not declared to hold, including the one PostgreSQL gives a CREATEROLE user in each role it creates. Setting it to false withdraws CREATEROLE from a role that held it.
## @field {bool} [bypassRls] - Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself.
## @param {map[string]User} users - Users configuration map. Passwords 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 PostgreSQL role 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 SCRAM verifier, and a revoke retires the password without issuing one. A `password` key here is ignored and draws an admission warning. A password set inside PostgreSQL is reverted by the operator.
users: {}
## Example:
## users:
@@ -293,7 +293,6 @@ users: {}
## debezium:
## replication: true
## migrator:
## createRole: true
## bypassRls: true
##
+1 -1
View File
@@ -56,7 +56,7 @@ image-migrations:
# yq exits 0 on empty input, so a failed render would otherwise ship an
# image whose migration 62 deletes the old CRDs and cannot recreate them.
test "$$(ls images/migrations/snapshot-controller-crds | wc -l)" -eq 3
docker buildx build images/migrations \
docker buildx build -f images/migrations/Dockerfile ../../.. \
$(call image-tags,platform-migrations,v$(COZYSTACK_VERSION)) \
$(call cache-args,platform-migrations) \
--metadata-file images/migrations.json \
@@ -5,6 +5,22 @@
# target arch and verify it against the release's cli-SHA256SUMS.txt. Bump
# ETCD_OPERATOR_VERSION (and the pinned checksums below) together, keeping it in
# sync with packages/system/etcd-operator (Chart appVersion).
# credentials-migrate shares the password format functions with the API, so
# it is built from this repository: the build context is the repository root,
# and every path below is relative to it.
FROM --platform=$BUILDPLATFORM golang:1.27-alpine@sha256:f92b6ef800e499660581efdabdf25d9d817a9d124eaf900924f0504e7e27e12d AS builder
ARG GOPROXY
ARG TARGETOS
ARG TARGETARCH
WORKDIR /workspace
COPY go.mod go.sum ./
RUN for attempt in 1 2 3; do GOOS=$TARGETOS GOARCH=$TARGETARCH go mod download && break; [ "$attempt" = 3 ] && exit 1; sleep $((attempt * 10)); done
COPY api api/
COPY pkg pkg/
COPY cmd cmd/
COPY internal internal/
RUN GOOS=$TARGETOS GOARCH=$TARGETARCH CGO_ENABLED=0 go build -ldflags="-extldflags=-static" -o /credentials-migrate ./cmd/credentials-migrate
FROM alpine:3.24@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6
ARG TARGETOS
@@ -29,6 +45,8 @@ RUN set -eux; \
echo "${sha256} /usr/bin/etcd-migrate" | sha256sum -c -; \
chmod +x /usr/bin/etcd-migrate
COPY --from=builder /credentials-migrate /usr/bin/credentials-migrate
# CRDs of Strimzi 0.51.0, the last release serving both v1beta2 and v1.
# Migration 61 applies them so Strimzi's conversion tool can move every stored
# object to v1 before the kafka-operator release installs the v1-only CRDs.
@@ -37,16 +55,20 @@ RUN mkdir /strimzi-crds && \
https://github.com/strimzi/strimzi-kafka-operator/releases/download/0.51.0/strimzi-crds-0.51.0.yaml && \
echo "a11257e67985a946a6facfb17d729aac5670b89675d410d13162fe455a5ac7a8 /strimzi-crds/strimzi-crds-0.51.0.yaml" | sha256sum -c -
COPY migrations /migrations
# The CredentialTemplate CRD, which migration 64 applies before the converted
# charts render templates: it ships with cozystack-controller, whose release
# can upgrade after the tenant releases switch charts.
COPY packages/system/cozystack-controller/definitions/cozystack.io_credentialtemplates.yaml /credential-crds/
COPY packages/core/platform/images/migrations/migrations /migrations
# v1alpha2 etcd CRDs, vendored into the build context by `make image-migrations`.
# migration 50 applies these before adoption so it does not deadlock waiting for
# the etcd-operator-crds HelmRelease (which only reconciles after the migration
# pre-upgrade hook completes).
COPY etcd-operator-crds /etcd-operator-crds
COPY packages/core/platform/images/migrations/etcd-operator-crds /etcd-operator-crds
# v1beta2 group snapshot CRDs, rendered by `make image-migrations`; migration 62
# creates them before the snapshot-controller HelmRelease upgrades.
COPY snapshot-controller-crds /snapshot-controller-crds
COPY run-migrations.sh /usr/bin/run-migrations.sh
COPY packages/core/platform/images/migrations/snapshot-controller-crds /snapshot-controller-crds
COPY packages/core/platform/images/migrations/run-migrations.sh /usr/bin/run-migrations.sh
WORKDIR /migrations
+190
View File
@@ -0,0 +1,190 @@
#!/bin/sh
# Migration 64 --> 65
# Convert PostgreSQL accounts to platform-minted credentials, first part.
#
# The converted postgres chart renders a CredentialTemplate per user, and
# each managed role reads its verifier 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 Postgres
# 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.
#
# The second part is the cozystack-credentials-migration-64 Job, which waits
# per release for its chart to switch, then strips the plaintext and retires
# the source Secret. 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. A Job
# created here runs outside the platform HelmRelease, so it holds up no
# upgrade. It runs the image this hook runs as, read from its own pod. The Job
# is deleted and recreated rather than patched, so a hook that reruns on a
# newer image does not fault on the immutable pod template.
#
# The Job's ServiceAccount is bound to a least-privilege ClusterRole, not
# cluster-admin: finish needs only CRUD on Secrets, get/list/patch on
# HelmReleases, create on Events, and its state ConfigMap (pods/exec, which a
# later wave's MariaDB rotation needs, is not granted here). The ServiceAccount
# is owned by the Job, so the garbage collector removes it whenever the Job is
# (its TTL, a rerun, or by hand), on the success and the failure path alike, so
# no standing identity outlives the Job. A ClusterRoleBinding cannot be owned by
# a namespaced Job, so the binding is left; once the ServiceAccount is gone it
# grants to no subject that exists. On a conversion a stuck release leaves
# permanently failed, an operator clearing that release should delete the
# ClusterRoleBinding and ClusterRole by hand. While any release is left out,
# credentials-migrate labels its state ConfigMap credentials.cozystack.io/incomplete=true,
# which the CredentialsMigrationIncomplete alert fires on: the ConfigMap outlives
# the Job, so a release whose plaintext was never retired is seen until the
# conversion is finished, not only for the Job's TTL. 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}"
# The converted postgres chart renders CredentialTemplates, whose CRD ships
# with cozystack-controller. That release can upgrade minutes after the tenant
# releases switch charts, and every render in between fails on the unknown
# kind, so apply the CRD baked into this image first, owned by the
# cozystack-controller release as its later upgrade expects to find it.
CRD_FILE="${CREDENTIAL_CRD_FILE:-/credential-crds/cozystack.io_credentialtemplates.yaml}"
kubectl apply --server-side --force-conflicts --filename "$CRD_FILE"
kubectl label crd credentialtemplates.cozystack.io app.kubernetes.io/managed-by=Helm --overwrite
kubectl annotate crd credentialtemplates.cozystack.io \
meta.helm.sh/release-name=cozystack-controller \
meta.helm.sh/release-namespace=cozy-system --overwrite
kubectl wait --for=condition=established crd/credentialtemplates.cozystack.io --timeout=60s
credentials-migrate seed \
--migration 64 \
--kind Postgres \
--format scram-sha-256 \
--accounts-path users \
--refuse-flag createRole \
--label 'cnpg.io/reload=true'
# 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-64 \
--namespace "$NAMESPACE" \
--ignore-not-found
kubectl delete serviceaccount cozystack-credentials-migration-64 \
--namespace "$NAMESPACE" \
--ignore-not-found
kubectl apply --filename - <<YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: cozystack-credentials-migration-64
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-64
namespace: ${NAMESPACE}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: cozystack-credentials-migration-64
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cozystack-credentials-migration-64
subjects:
- kind: ServiceAccount
name: cozystack-credentials-migration-64
namespace: ${NAMESPACE}
---
apiVersion: batch/v1
kind: Job
metadata:
name: cozystack-credentials-migration-64
namespace: ${NAMESPACE}
spec:
backoffLimit: 6
ttlSecondsAfterFinished: 604800
template:
metadata:
labels:
policy.cozystack.io/allow-to-apiserver: "true"
spec:
serviceAccountName: cozystack-credentials-migration-64
restartPolicy: OnFailure
containers:
- name: migration
image: ${image}
command:
- credentials-migrate
- finish
- --migration=64
- --kind=Postgres
- --format=scram-sha-256
- --accounts-path=users
- --refuse-flag=createRole
- --label=cnpg.io/reload=true
- --timeout=30m
env:
- name: CREDENTIALS_MIGRATE_ACTOR
value: system:serviceaccount:${NAMESPACE}:cozystack-credentials-migration-64
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-64 \
--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-64 \
--namespace "$NAMESPACE" \
--type merge \
--patch "{\"metadata\":{\"ownerReferences\":[{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\"name\":\"cozystack-credentials-migration-64\",\"uid\":\"${job_uid}\"}]}}"
stamp_cozystack_version 65
+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: 64
targetVersion: 65
# 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
@@ -0,0 +1,25 @@
apiVersion: operator.victoriametrics.com/v1beta1
kind: VMRule
metadata:
name: alerts-cozystack-credentials
spec:
groups:
- name: cozystack-credentials
params: {}
rules:
- alert: CredentialsMigrationIncomplete
annotations:
description: The credentials conversion recorded in ConfigMap {{ $labels.namespace
}}/{{ $labels.configmap }} left one or more releases unconverted, so their
tenant passwords may still be readable through the old <release>-credentials
Secret until the conversion is finished. Read the credentials-migration state
ConfigMap in cozy-system for the releases left out and the finish Job's log
for why, fix the cause, then delete the Job and re-apply its manifest from
the migration. This alert clears when the next finish run leaves none out.
summary: A credentials conversion left releases with tenant-readable passwords.
expr: kube_configmap_labels{job="kube-state-metrics", namespace="cozy-system", configmap=~"credentials-migration-.+", label_credentials_cozystack_io_incomplete="true"} > 0
for: 15m
labels:
severity: warning
exported_instance: '{{ $labels.namespace }}/{{ $labels.configmap }}'
service: cozystack-credentials
@@ -8,8 +8,8 @@ suite: kube-state-metrics exports the labels of pods, deployments and PVCs
templates:
- charts/kube-state-metrics/templates/deployment.yaml
tests:
- it: allowlists all labels of pods, deployments and persistentvolumeclaims
- it: allowlists all labels of pods, deployments and persistentvolumeclaims, and the credentials-migration incomplete key on configmaps
asserts:
- contains:
path: spec.template.spec.containers[0].args
content: --metric-labels-allowlist=pods=[*],deployments=[*],persistentvolumeclaims=[*]
content: --metric-labels-allowlist=pods=[*],deployments=[*],persistentvolumeclaims=[*],configmaps=[credentials.cozystack.io/incomplete]
@@ -33,7 +33,14 @@ kube-state-metrics:
# lineage labels. kube-state-metrics emits that metric only for resources on
# this list, one series per PVC; naming only the lineage keys would emit the
# same number of series.
- --metric-labels-allowlist=pods=[*],deployments=[*],persistentvolumeclaims=[*]
#
# configmaps names only the credentials.cozystack.io/incomplete key, which
# the credentials migration sets on its state ConfigMap: that ConfigMap
# outlives the finish Job, so the CredentialsMigrationIncomplete alert keys
# on kube_configmap_labels and fires until the conversion is finished, not
# only for the Job's TTL. Only the one key is named, so this adds a single
# series per credentials-migration ConfigMap, not one per ConfigMap label.
- --metric-labels-allowlist=pods=[*],deployments=[*],persistentvolumeclaims=[*],configmaps=[credentials.cozystack.io/incomplete]
rbac:
extraRules:
- apiGroups:
+1 -3
View File
@@ -30,7 +30,7 @@ spec:
singular: postgres
plural: postgreses
openAPISchema: |-
{"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each PostgreSQL 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.micro","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},"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},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"flavor":{"description":"PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases.<name>.extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore).","type":"string","default":"postgresql","enum":["postgresql","postgis"]},"allowCollationChange":{"description":"Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new iLine truncated
{"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via `/scale`. Disabling autoscaling does NOT automatically bring the live count back to `replicas`: the client-side merge writes `instances` only when the rendered value changes, so a cluster KEDA grew past `replicas` stays there with no autoscaler left to reduce it — lower `replicas` to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and `kubectl scale` if needed) to avoid a transient. Must stay greater than `quorum.maxSyncReplicas`.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each PostgreSQL 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.micro","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},"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},"version":{"description":"PostgreSQL major version to deploy","type":"string","default":"v18","enum":["v18","v17","v16","v15","v14","v13"]},"flavor":{"description":"PostgreSQL image flavor, fixed when the cluster is created. `postgresql` uses the CloudNativePG PostgreSQL image. `postgis` uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in `databases.<name>.extensions`. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore).","type":"string","default":"postgresql","enum":["postgresql","postgis"]},"allowCollationChange":{"description":"Allow a cluster created on a Debian bullseye image (before the move to standard-trixie) to move to the new image without a clean locale check. Such a cluster is checked before each upgrade, except while `bootstrap.enabled` is set (set it back to false once a restore set up by hand has finished), and stays on its current image until the check finds nothing that depends on a collation other than C, POSIX or builtin: while this is false, a cluster the check found affected (an ICU or libc locale, or C.UTF-8) or could not finish on stays put, because glibc and ICU on the new iLine truncated
release:
prefix: postgres-
labels:
@@ -78,8 +78,6 @@ spec:
secrets:
exclude: []
include:
- resourceNames:
- postgres-{{ .name }}-credentials
# 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.
+9
View File
@@ -14,6 +14,9 @@ import (
corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1"
)
// The rows from "web" to "x." are pinned for the postgres chart's account-name
// helper too (packages/apps/postgres/tests/managed_roles_cluster_test.yaml):
// the chart names each managed role's Secret and must name it as the API does.
func TestMapName(t *testing.T) {
tests := []struct {
in, want string
@@ -22,6 +25,12 @@ func TestMapName(t *testing.T) {
{in: "web", want: "web"},
{in: "Bob.Smith", want: "bob-smith"},
{in: "app_user", want: "app-user"},
{in: "UPPER", want: "upper"},
{in: "x-1", want: "x-1"},
{in: "db.user_2", want: "db-user-2"},
{in: "app_", wantErr: true},
{in: "_svc", wantErr: true},
{in: "x.", wantErr: true},
{in: "-leading", wantErr: true},
{in: "", wantErr: true},
{in: strings.Repeat("a", 64), wantErr: true},
+24
View File
@@ -57,6 +57,30 @@ func Known(name string) bool {
return false
}
// CarriesOver reports whether a legacy plaintext password encoded under name
// still authenticates that same plaintext at login. For scram-sha-256,
// PostgreSQL runs the password through SASLprep (RFC 4013) before it builds or
// checks a SCRAM verifier, but pg_saslprep returns an all-ASCII input unchanged
// through an ASCII fast path (pg_is_ascii) before its mapping and
// prohibited-character steps run, so every all-ASCII password, ASCII controls
// included, is hashed over its raw bytes at both ALTER ROLE and login, and a
// verifier built here from the same bytes matches. A password with any
// non-ASCII byte reaches SASLprep's mapping and may come out as different bytes
// (a soft hyphen U+00AD, say, maps to nothing), so it is re-minted rather than
// stored as a verifier that would silently fail login. Every other format
// hashes or stores the raw bytes, which authenticate as they are.
func CarriesOver(name, password string) bool {
if name != ScramSHA256 {
return true
}
for i := 0; i < len(password); i++ {
if password[i] > 0x7f {
return false
}
}
return true
}
// GeneratePassword draws PasswordLength characters uniformly from the
// alphabet with crypto/rand. Rejection sampling keeps the draw unbiased: a
// byte is accepted only below the largest multiple of the alphabet size.
+26
View File
@@ -107,6 +107,32 @@ func TestEncodeFixedVectors(t *testing.T) {
}
}
func TestCarriesOver(t *testing.T) {
tests := []struct {
name, format, password string
want bool
}{
// PostgreSQL returns an all-ASCII password unchanged through pg_saslprep's
// ASCII fast path, so every all-ASCII password, ASCII controls included,
// carries over; a non-ASCII byte reaches SASLprep's mapping and may be
// rewritten, so it does not.
{"scram printable ASCII", ScramSHA256, "pa55-word_ABC xyz", true},
{"scram space is printable", ScramSHA256, "two words", true},
{"scram ASCII control is still ASCII", ScramSHA256, "tab\there", true},
{"scram soft hyphen rewritten by SASLprep", ScramSHA256, "I­X", false},
{"scram non-ASCII", ScramSHA256, "café", false},
// Other formats hash or store the raw bytes, which authenticate as is.
{"sha256 non-ASCII", SHA256, "café", true},
{"mysql-native soft hyphen", MySQLNative, "I­X", true},
{"plaintext non-ASCII", Plaintext, "café", true},
}
for _, tt := range tests {
if got := CarriesOver(tt.format, tt.password); got != tt.want {
t.Errorf("%s: CarriesOver(%q, %q) = %v, want %v", tt.name, tt.format, tt.password, got, tt.want)
}
}
}
func TestEncodeUnknownFormat(t *testing.T) {
if _, err := Encode("apr1", "x"); err == nil {
t.Fatal("expected an error for an unknown format")
+20 -15
View File
@@ -2357,28 +2357,34 @@ func (r *REST) warnRemovedKubernetesFields(ctx context.Context, app *appsv1alpha
}
}
// removedUserPasswordKinds are the Application kinds whose per-user `password`
// field was removed from the chart render -- passwords are chart-generated into
// the <release>-credentials Secret. Like the Kubernetes fields above the key is
// still accepted and stored (the user object's schema keeps additionalProperties
// open, and the render preserves an existing password through lookup), so a value
// left from before the upgrade stays the LIVE credential and there is no longer a
// values knob to change it. Warn so an operator editing it is told it has no
// effect instead of getting a silent 200.
var removedUserPasswordKinds = map[string]bool{
postgresKind: true,
mariadbKind: true,
// removedUserPasswordKinds maps each Application kind whose per-user `password`
// field was removed from the chart render to the warning that field draws. Like
// the Kubernetes fields above the key is still accepted and stored (the user
// object's schema keeps additionalProperties open), and a value left from before
// the upgrade can still be the LIVE credential, with no values knob left to
// change it. Warn so an operator editing it is told it has no effect instead of
// 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.",
}
// mintedPasswordWarning is the warning of a kind whose user passwords the
// credentials API issues: the tenant cannot read <release>-credentials, so the
// warning names the operation that sets a password instead.
const mintedPasswordWarning = "spec.users[%q].password is ignored: passwords are issued through the credentials API and cannot be set from values. Mint a new password on the user's Credential (credentials.core.cozystack.io, mint subresource); editing this field has no effect."
const (
postgresKind = "Postgres"
mariadbKind = "MariaDB"
)
// warnRemovedUserPasswords emits a client-facing admission warning for every
// spec.users[<name>].password still present on a Postgres or MariaDB resource.
// spec.users[<name>].password still present on a kind removedUserPasswordKinds
// lists.
func (r *REST) warnRemovedUserPasswords(ctx context.Context, app *appsv1alpha1.Application) {
if !removedUserPasswordKinds[r.kindName] || app == nil || app.Spec == nil || len(app.Spec.Raw) == 0 {
message, removed := removedUserPasswordKinds[r.kindName]
if !removed || app == nil || app.Spec == nil || len(app.Spec.Raw) == 0 {
return
}
// Decode the users map leniently, then each user on its own, so one malformed
@@ -2411,8 +2417,7 @@ func (r *REST) warnRemovedUserPasswords(ctx context.Context, app *appsv1alpha1.A
continue
}
if _, present := u["password"]; present {
warning.AddWarning(ctx, "", fmt.Sprintf(
"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.", user))
warning.AddWarning(ctx, "", fmt.Sprintf(message, user))
}
}
// MariaDB force-generates root's password (root is chart-managed), silently
@@ -36,14 +36,14 @@ import (
"github.com/cozystack/cozystack/pkg/config"
)
// Postgres and MariaDB dropped users[].password from the chart render but the
// key is still accepted and stored, and a leftover value stays the live
// credential. The warning telling an operator that editing it has no effect is
// only useful if wired into the write path; deleting either call site
// (rest.go Create / Update) must fail loudly. These tests drive Create and
// Update end to end and assert the warning surfaces; TestWarnRemovedUserPasswords
// below pins the helper in isolation (which kinds warn, and that a missing
// password stays quiet).
// The kinds removedUserPasswordKinds lists dropped users[].password from the
// chart render but the key is still accepted and stored, and a leftover value
// can stay the live credential. The warning telling an operator that editing
// it has no effect is only useful if wired into the write path; deleting either
// call site (rest.go Create / Update) must fail loudly. These tests drive
// Create and Update end to end and assert the warning surfaces;
// TestWarnRemovedUserPasswords below pins the helper in isolation (which kinds
// warn, and that a missing password stays quiet).
func newPostgresWarnREST(t *testing.T, objects ...client.Object) *REST {
t.Helper()
@@ -191,6 +191,31 @@ func TestWarnRemovedUserPasswords(t *testing.T) {
}
}
// A kind whose passwords the credentials API issues points the warning at a
// 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} {
t.Run(kind, func(t *testing.T) {
r := &REST{kindName: kind}
app := &appsv1alpha1.Application{Spec: &apiextv1.JSON{Raw: []byte(`{"users":{"app":{"password":"hackme"}}}`)}}
rec := &fakeWarningRecorder{}
ctx := warning.WithWarningRecorder(context.Background(), rec)
r.warnRemovedUserPasswords(ctx, app)
if len(rec.warnings) != 1 {
t.Fatalf("want one warning, got %v", rec.warnings)
}
w := rec.warnings[0]
if !strings.Contains(w, `spec.users["app"].password is ignored`) || !strings.Contains(w, "credentials.core.cozystack.io, mint subresource") {
t.Errorf("warning does not point at a mint on the Credential: %q", w)
}
if strings.Contains(w, "<release>-credentials") {
t.Errorf("warning still names <release>-credentials: %q", w)
}
})
}
}
// A "_"/"-" collision that an UPDATE INTRODUCES (present in the new spec, absent
// from the old) must draw an admission warning in each namespace MariaDB renders
// with a "_"→"-" mapping — usernames, database names, and (database,user) Grant