feat(rabbitmq)!: mint tenant passwords through the credentials API (#5381)

## What this PR does

This PR now carries three conversions: RabbitMQ, Redis/Valkey (reviewed
in #5382) and Bucket (reviewed in #5383). Those two were merged into
this branch instead of main by mistake, and since each was already
reviewed and approved on its own, they land here together rather than
being split out again.

RabbitMQ passwords are no longer readable from the per-user Secrets, and
tenants lose the administrator login from the operator's
`<release>-default-user`. Every tenant tier can read both today. An
administrator mints a password on the user's `Credential` and sees it
once, the topology operator applies it within seconds, and the next mint
or a revoke kills it. The broker hashes passwords itself, so the account
Secret keeps the plaintext, readable only by the platform. This is the
RabbitMQ part of the user secrets API design (cozystack/community#137).

Stacked on #5380. Review only the top four commits:

- The chart renders a `plaintext` CredentialTemplate per user and points
each `User`'s `importCredentialsSecret` at its account Secret. Password
generation and the `lookup` are gone.
- The lineage webhook package gets a helper that tells whether a
definition shows a Secret, with tests that load the converted
definitions.
- `credentials-migrate` gets `--source-selector`, to find per-user
Secrets by label, and `--hide-secret-suffix`, to hide a Secret the
operator created once the kind's new definition is in the API.
- Migration 68 seeds the account Secrets before the chart switches. Its
finish Job deletes the old per-user Secrets and hides `-default-user`.
It waits for the new definition first: on the upgrade run the operator
rewrote the Secret 7 s before rabbitmq-rd upgraded, and the webhook
stamped it tenant-visible again from the old definition. The exclude in
the new definition keeps it hidden on every later rewrite.

The design assumed the topology operator imports a password only when it
creates a user. Version 1.20.2 re-imports on every reconcile and watches
the Secret, so a mint applies live.

Tested on a three-node cluster, fresh install: a minted password works
after 5 s, the old one is rejected right after the next mint, revoke
works, and removing a user removes the broker user too. Every fresh
install fails once: the operator's webhook rejects a `User` whose Secret
doesn't exist yet, and the retry 32 s later converges. Full upgrade from
1.7.1 on the same cluster, all engines at once with a client loop each:
migrations 64-71 ran in order and every account was adopted with its old
password. The RabbitMQ client loop had no failures. That run showed the
7 s window above; the last two commits close it and are covered by
tests, not by a second run.

Breaking for users: tenants lose the administrator login and the
management UI, since chart users carry no tags. Passwords can't be read
any more. A fresh install, or an upgrade that adds a user, shows one
failed attempt before it converges.

Open questions:

1. The first failed attempt: accept it, or seed the account Secret
before the chart renders?
2. Add `users.<name>.tags`, so tenants can have an admin user again?
3. Rotate `-default-user` in the finish Job? That needs `pods/exec` for
`rabbitmqctl`. Otherwise the value tenants could read stays valid.

### 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 RabbitMQ note for the credentials API docs
(cozystack/website#753) and an upgrade note that tenants lose the
administrator login
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up: needed, `cozystack_rabbitmq` 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: needed, the RabbitMQ row in the design, and a fix to its
claim that the operator imports a password only on user creation

### Release note

```release-note
feat(rabbitmq)!: RabbitMQ passwords are issued through the credentials API. The per-user Secrets are removed, `users.<name>.password` is ignored, and tenants can no longer read the administrator login in `<release>-default-user`. 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. Switch clients to minted passwords after the upgrade.
```



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

## Summary by CodeRabbit

* **New Features**
* Added credential templates for RabbitMQ, Redis, Valkey, and bucket
accounts, with credentials issued and managed through the credentials
API.
* Added platform-account settings for bucket users and support for
engine-issued bucket access keys.
* Credential mint responses now include an access key ID for services
that issue key pairs.
* **Improvements**
* Redis and Valkey passwords can be rotated without restarting; internal
accounts support replication and monitoring.
  * Tenant-visible access to platform credentials is more restricted.
* Added migrations for existing RabbitMQ, Redis, Valkey, and bucket
credentials.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
Andrei Kvapil authored and GitHub committed 2026-12-02 19:06:38 -05:00
commit 7fb2bc785a
94 files changed
+10276 -280

No files matched your search

+2
View File
@@ -41,6 +41,8 @@ type ConfigSpec struct {
}
type User struct {
// Marks a platform account, such as the `system` user of the backup bucket, which backupstrategy-controller sets. Its keys stay in the `<bucket>-<user>-credentials` Secret, which no tenant can read, and are never minted. Clearing it drops the chart-rendered BucketAccess, which revokes those keys, and the user becomes a normal account whose keys are minted through its Credential. Leave it unset for your own users.
Platform bool `json:"platform,omitempty"`
// Whether the user has read-only access.
Readonly bool `json:"readonly,omitempty"`
}
+1 -3
View File
@@ -46,7 +46,7 @@ type ConfigSpec struct {
// RabbitMQ major.minor version to deploy
// +kubebuilder:default:="v4.2"
Version Version `json:"version"`
// Users configuration map.
// Users configuration map. Each user is a RabbitMQ user that messaging-topology-operator keeps from an account Secret the platform holds. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. The operator applies either to the broker within seconds. A `password` key here is ignored. The administrator in `<release>-default-user` belongs to the platform and is not shown to tenants.
// +kubebuilder:default:={}
Users map[string]User `json:"users,omitempty"`
// Virtual hosts configuration map.
@@ -80,8 +80,6 @@ type TLS struct {
}
type User struct {
// Password for the user.
Password string `json:"password,omitempty"`
}
type Vhost struct {
+1 -1
View File
@@ -46,7 +46,7 @@ type ConfigSpec struct {
// TLS configuration. TLS is opt-in and is not inferred from `external`.
// +kubebuilder:default:={}
Tls TLS `json:"tls,omitempty"`
// Enable password generation.
// Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password.
// +kubebuilder:default:=true
AuthEnabled bool `json:"authEnabled"`
// Redis `min-replicas-to-write`: the master refuses writes unless at least this many replicas are connected and within `minReplicasMaxLag`. Unset by default, which leaves the Redis default (disabled). With `replicas: 2` and a value of 1 the master rejects writes while its only replica is down, trading availability for a bound on the writes lost if an isolated master is failed over. Replication stays asynchronous, so this bounds the loss, it does not remove it. Must be 0 or more and below `replicas` (a master with `replicas` pods has `replicas - 1` replicas), otherwise every write is refused; the chart refuses such a value.
+1 -1
View File
@@ -39,7 +39,7 @@ type ConfigSpec struct {
// Valkey major version to deploy
// +kubebuilder:default:="v8"
Version Version `json:"version"`
// Enable password generation.
// Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password.
// +kubebuilder:default:=true
AuthEnabled bool `json:"authEnabled"`
// 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.
+28
View File
@@ -9,6 +9,7 @@ import (
// CredentialTemplateSpec describes one account of an application and the
// Secret that stores its password. A kind's chart renders one per account; a
// tenant cannot write it.
// +kubebuilder:validation:XValidation:rule="!has(self.bucketAccess) || self.format.name == 'plaintext'",message="a template with bucketAccess stores its keys in the plaintext format"
type CredentialTemplateSpec struct {
// Username is the account name as the engine knows it.
// +kubebuilder:validation:MinLength=1
@@ -30,6 +31,29 @@ type CredentialTemplateSpec struct {
// +optional
// +kubebuilder:validation:Pattern=`^_[A-Za-z0-9_]*$`
ValuesPath string `json:"valuesPath,omitempty"`
// BucketAccess makes the account engine-issued: it names the BucketAccess
// whose COSI grant issues the account's keys, which the platform cannot
// choose. cozystack-controller creates and owns it, re-creates it on a
// mint, and deletes it on a revoke. The keys are stored as they are
// issued, so the format is plaintext.
// +optional
BucketAccess *CredentialTemplateBucketAccess `json:"bucketAccess,omitempty"`
}
// CredentialTemplateBucketAccess is the BucketAccess an engine-issued
// template stands for. Its credentials Secret carries the BucketAccess's own name.
// +kubebuilder:validation:XValidation:rule="self.name == oldSelf.name",message="bucketAccess.name is immutable"
type CredentialTemplateBucketAccess struct {
// Name of the BucketAccess and of the Secret the COSI sidecar writes.
// +kubebuilder:validation:MinLength=1
Name string `json:"name"`
// BucketClaimName is the BucketClaim the access is granted on.
// +kubebuilder:validation:MinLength=1
BucketClaimName string `json:"bucketClaimName"`
// BucketAccessClassName is the class that sets the access policy.
// +kubebuilder:validation:MinLength=1
BucketAccessClassName string `json:"bucketAccessClassName"`
}
// CredentialTemplateFormat names a stored form of a password.
@@ -103,6 +127,10 @@ const (
CredentialTemplateSecretConflict = "SecretConflict"
// CredentialTemplateUnknownFormat: the format names no built-in format.
CredentialTemplateUnknownFormat = "UnknownFormat"
// CredentialTemplateBucketAccessConflict: a BucketAccess at the name an
// engine-issued template names that the controller did not create or
// adopt; it is left alone.
CredentialTemplateBucketAccessConflict = "BucketAccessConflict"
)
// +kubebuilder:object:root=true
+20
View File
@@ -382,6 +382,21 @@ func (in *CredentialTemplate) DeepCopyObject() runtime.Object {
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *CredentialTemplateBucketAccess) DeepCopyInto(out *CredentialTemplateBucketAccess) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialTemplateBucketAccess.
func (in *CredentialTemplateBucketAccess) DeepCopy() *CredentialTemplateBucketAccess {
if in == nil {
return nil
}
out := new(CredentialTemplateBucketAccess)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *CredentialTemplateFormat) DeepCopyInto(out *CredentialTemplateFormat) {
*out = *in
@@ -491,6 +506,11 @@ func (in *CredentialTemplateSpec) DeepCopyInto(out *CredentialTemplateSpec) {
*out = *in
out.Format = in.Format
in.Secret.DeepCopyInto(&out.Secret)
if in.BucketAccess != nil {
in, out := &in.BucketAccess, &out.BucketAccess
*out = new(CredentialTemplateBucketAccess)
**out = **in
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialTemplateSpec.
+9
View File
@@ -361,6 +361,15 @@ func main() {
setupLog.Error(err, "unable to create controller", "controller", "CredentialTemplate")
os.Exit(1)
}
if err = (&controller.COSICredentialReconciler{
Client: mgr.GetClient(),
Reader: mgr.GetAPIReader(),
Scheme: mgr.GetScheme(),
Recorder: mgr.GetEventRecorderFor("credentialtemplate-cosi-controller"),
}).SetupWithManager(mgr, caSecretCluster.GetCache()); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "CredentialTemplateCOSI")
os.Exit(1)
}
if err = (&controller.CredentialValuesReconciler{
Client: mgr.GetClient(),
Reader: mgr.GetAPIReader(),
+51
View File
@@ -0,0 +1,51 @@
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"fmt"
"time"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
corev1 "k8s.io/api/core/v1"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
"github.com/cozystack/cozystack/internal/lineagecontrollerwebhook"
"github.com/cozystack/cozystack/internal/shared/appdefowner"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
)
// waitDefinitionHides waits until the ApplicationDefinition of the kind, as
// it stands in the API, no longer selects sec as tenant-visible. An operator
// that rewrites the Secret replaces its labels, and the lineage webhook then
// stamps it again from that definition, so a label written while the old
// definition is in place is undone by the next such write. The definition
// comes from the kind's rd chart, which upgrades only after the operator it
// depends on is Ready: a new operator rewriting the Secret on its first pass
// lands before it. Labelling only once the new definition hides the Secret
// leaves every later rewrite stamped not tenant-visible as well.
func (m *migrator) waitDefinitionHides(ctx context.Context, hr *helmv2.HelmRelease, sec *corev1.Secret) error {
appName := hr.Labels[appsv1alpha1.ApplicationNameLabel]
deadline := m.now().Add(m.o.timeout)
for {
defs := &cozyv1alpha1.ApplicationDefinitionList{}
if err := m.c.List(ctx, defs); err != nil {
return fmt.Errorf("list ApplicationDefinitions: %w", err)
}
owner := appdefowner.Owners(defs.Items)[m.o.kind]
var def *cozyv1alpha1.ApplicationDefinition
for i := range defs.Items {
if defs.Items[i].Name == owner {
def = &defs.Items[i]
}
}
if !lineagecontrollerwebhook.SecretTenantVisible(ctx, def, appName, hr.Namespace, sec.Name, sec.Labels) {
return nil
}
if m.now().After(deadline) {
return fmt.Errorf("ApplicationDefinition %s still selects %s as tenant-visible after %s; it would be stamped visible again at the operator's next write, so it is not labelled yet", owner, sec.Name, m.o.timeout)
}
time.Sleep(10 * time.Second)
}
}
+68
View File
@@ -0,0 +1,68 @@
// SPDX-License-Identifier: Apache-2.0
package main
import (
"context"
"strings"
"testing"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1"
)
// definition is the Postgres ApplicationDefinition with the admin Secret
// either included by name, as before a conversion, or excluded, as after.
func definition(adminVisible bool) *cozyv1alpha1.ApplicationDefinition {
sel := []*cozyv1alpha1.ApplicationDefinitionResourceSelector{{ResourceNames: []string{"postgres-{{ .name }}-default-user"}}}
def := &cozyv1alpha1.ApplicationDefinition{ObjectMeta: metav1.ObjectMeta{Name: "postgres"}}
def.Spec.Application.Kind = "Postgres"
if adminVisible {
def.Spec.Secrets.Include = sel
} else {
def.Spec.Secrets.Exclude = sel
}
return def
}
func TestHidePlatformSecretsWaitsForTheDefinitionToHideIt(t *testing.T) {
ctx := context.Background()
hr := release(`{}`, "0.2.0", true)
admin := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "postgres-orders-default-user", Namespace: "tenant-foo", Labels: map[string]string{
corev1alpha1.TenantResourceLabelKey: "true",
}}}
def := definition(true)
m := newMigrator(t, hr, admin, def)
m.o.hideSuffixes = stringFlags{"-default-user"}
// The old definition still selects it: a label now would be undone by
// the operator's next write, so none is written.
err := m.hidePlatformSecrets(ctx, hr)
if err == nil || !strings.Contains(err.Error(), "still selects postgres-orders-default-user") {
t.Fatalf("hide under the old definition = %v", err)
}
if sec, _ := m.secret(t, "postgres-orders-default-user"); sec.Labels[corev1alpha1.TenantResourceLabelKey] != "true" {
t.Fatal("labelled while the definition still selects the Secret")
}
// The rd chart upgrades and excludes it: labelled, and the webhook stamps
// every later rewrite the same.
cur := &cozyv1alpha1.ApplicationDefinition{}
if err := m.c.Get(ctx, client.ObjectKeyFromObject(def), cur); err != nil {
t.Fatal(err)
}
cur.Spec.Secrets = definition(false).Spec.Secrets
if err := m.c.Update(ctx, cur); err != nil {
t.Fatal(err)
}
if err := m.hidePlatformSecrets(ctx, hr); err != nil {
t.Fatal(err)
}
if sec, _ := m.secret(t, "postgres-orders-default-user"); sec.Labels[corev1alpha1.TenantResourceLabelKey] != "false" {
t.Fatalf("labels = %v", sec.Labels)
}
}
+216 -58
View File
@@ -34,6 +34,7 @@ import (
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
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"
@@ -84,8 +85,12 @@ type options struct {
sourceSuffix string
sourceKey string
sourcePerAccount bool
sourceSelector labelFlags
platformKeys stringFlags
rotateKeys stringFlags
hideSuffixes stringFlags
fixedAccounts stringFlags
enabledFlag string
stateNamespace string
actor string
timeout time.Duration
@@ -146,7 +151,7 @@ func run(args []string) error {
return errors.New("usage: credentials-migrate seed|finish [flags]")
}
cmd := args[0]
o := &options{labels: labelFlags{}}
o := &options{labels: labelFlags{}, sourceSelector: 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")
@@ -160,8 +165,12 @@ func run(args []string) error {
fs.StringVar(&o.sourceSuffix, "source-suffix", "-credentials", "suffix of the chart-generated Secret holding the plaintext passwords, after the release name")
fs.StringVar(&o.sourceKey, "source-key", "", "key of the source Secret holding an account's password; empty means the user name")
fs.BoolVar(&o.sourcePerAccount, "source-per-account", false, "the chart kept one source Secret per account, named <release><source-suffix><user>, with the password under --source-key")
fs.Var(o.sourceSelector, "source-selector", "label, key=value, of the chart's per-account source Secrets, found by label and by the Helm release that rendered them rather than by name; each holds the user name under username and the password under --source-key; repeatable")
fs.Var(&o.platformKeys, "platform-key", "key of the source Secret that belongs to a platform account and stays; repeatable")
fs.Var(&o.hideSuffixes, "hide-secret-suffix", "finish: suffix, after the release name, of a Secret the chart does not render that holds a platform account; it is labelled not tenant-visible; repeatable")
fs.Var(&o.rotateKeys, "rotate-key", "finish: platform key of the source Secret to replace with a new random password once, followed by a forced upgrade of the release; repeatable")
fs.Var(&o.fixedAccounts, "fixed-account", "user the chart renders a template for whatever the values hold, for a kind with no accounts map; used instead of --accounts-path; repeatable")
fs.StringVar(&o.enabledFlag, "enabled-flag", "", "boolean value, by dotted path, that switches the fixed accounts off when false; unset counts as true, the chart default")
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")
@@ -173,8 +182,11 @@ func run(args []string) error {
if o.migration == 0 || o.kind == "" || !format.Known(o.formatName) {
return errors.New("--migration, --kind and a built-in --format are required")
}
if o.sourcePerAccount && o.sourceKey == "" {
return errors.New("--source-per-account needs --source-key: a per-account Secret is not keyed by user name")
if (o.sourcePerAccount || len(o.sourceSelector) > 0) && o.sourceKey == "" {
return errors.New("--source-per-account and --source-selector need --source-key: a per-account Secret is not keyed by user name")
}
if o.sourcePerAccount && len(o.sourceSelector) > 0 {
return errors.New("--source-per-account and --source-selector are two ways to find the same Secrets; pass one")
}
for _, k := range o.rotateKeys {
if !slices.Contains(o.platformKeys, k) {
@@ -197,6 +209,9 @@ func run(args []string) error {
if err := appsv1.AddToScheme(scheme); err != nil {
return err
}
if err := cozyv1alpha1.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)
@@ -371,9 +386,47 @@ func (m *migrator) finishRelease(ctx context.Context, hr *helmv2.HelmRelease, re
if err := m.retireSource(ctx, hr); err != nil {
return err
}
if err := m.hidePlatformSecrets(ctx, hr); err != nil {
return err
}
return m.rotatePlatformKeys(ctx, hr)
}
// hidePlatformSecrets labels the platform Secrets the chart does not render,
// such as one an operator creates, not tenant-visible. The lineage webhook
// decided their visibility at admission and skips them while their lineage
// labels stay, so dropping them from the ApplicationDefinition does not
// reach a Secret that exists until the operator next rewrites it. The label
// goes on only once the definition hides the Secret too, since a rewrite
// before that would stamp it visible again.
func (m *migrator) hidePlatformSecrets(ctx context.Context, hr *helmv2.HelmRelease) error {
for _, suffix := range m.o.hideSuffixes {
sec := &corev1.Secret{}
if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name + suffix}, sec); err != nil {
if apierrors.IsNotFound(err) {
continue
}
return err
}
if err := m.waitDefinitionHides(ctx, hr, sec); err != nil {
return err
}
if sec.Labels[corev1alpha1.TenantResourceLabelKey] == "false" {
continue
}
patch := client.MergeFrom(sec.DeepCopy())
if sec.Labels == nil {
sec.Labels = map[string]string{}
}
sec.Labels[corev1alpha1.TenantResourceLabelKey] = "false"
if err := m.c.Patch(ctx, sec, patch); err != nil {
return fmt.Errorf("hide %s: %w", sec.Name, err)
}
fmt.Printf("%s/%s: labelled %s not tenant-visible\n", hr.Namespace, hr.Name, sec.Name)
}
return nil
}
// 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
@@ -391,18 +444,13 @@ func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) erro
if err != nil {
return fmt.Errorf("%w: %v", errUnresolvable, err)
}
var source *corev1.Secret
if !m.o.sourcePerAccount {
source = &corev1.Secret{}
if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name + m.o.sourceSuffix}, source); err != nil {
if !apierrors.IsNotFound(err) {
return err
}
if len(accounts) > 0 {
fmt.Printf("%s/%s: %s%s is gone; its accounts get a Secret at their first mint\n", hr.Namespace, hr.Name, hr.Name, m.o.sourceSuffix)
return nil
}
}
passwords, found, err := m.sourcePasswords(ctx, hr, accounts)
if err != nil {
return err
}
if !found && len(accounts) > 0 {
fmt.Printf("%s/%s: %s is gone; its accounts get a Secret at their first mint\n", hr.Namespace, hr.Name, m.sourceDesc(hr, ""))
return nil
}
now := metav1.NewTime(m.now())
complete := true
@@ -427,10 +475,8 @@ func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) erro
case !apierrors.IsNotFound(err):
return err
}
plaintext, from, ok, err := m.plaintext(ctx, hr, source, acc.Username)
if err != nil {
return err
}
plaintext, ok := passwords[acc.Username]
from := m.sourceDesc(hr, acc.Username)
if !ok {
fmt.Printf("%s/%s: no password for %q in %s; the account gets a Secret at its first mint\n", hr.Namespace, hr.Name, acc.Username, from)
complete = false
@@ -517,31 +563,92 @@ func (m *migrator) addValuesFrom(ctx context.Context, hr *helmv2.HelmRelease, ac
return m.c.Patch(ctx, hr, patch)
}
// plaintext returns the chart-generated password of one account and the name
// of the Secret it was looked up in: the release's single source Secret or,
// with --source-per-account, the account's own Secret
// <release><source-suffix><user>, as charts that render one Secret per user
// keep it. The password is under --source-key, or under the user name when
// that is empty. A missing Secret or key is reported as not found.
func (m *migrator) plaintext(ctx context.Context, hr *helmv2.HelmRelease, source *corev1.Secret, user string) ([]byte, string, bool, error) {
key := m.o.sourceKey
if key == "" {
key = user
}
if !m.o.sourcePerAccount {
v, ok := source.Data[key]
return v, source.Name, ok, nil
}
name := m.perAccountSource(hr, user)
sec := &corev1.Secret{}
if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: name}, sec); err != nil {
if apierrors.IsNotFound(err) {
return nil, name, false, nil
// sourcePasswords returns the chart-generated plaintext of the release's
// accounts by user name, and whether any source Secret exists. The chart kept
// either one Secret, <release><source-suffix>, or one Secret per account:
// named <release><source-suffix><user> with --source-per-account, or found by
// --source-selector and the Helm release that rendered it, for a chart whose
// name mapping is not worth re-deriving. The password is under --source-key,
// or, in the single Secret, under the user name when that is empty.
func (m *migrator) sourcePasswords(ctx context.Context, hr *helmv2.HelmRelease, accounts []account.Account) (map[string][]byte, bool, error) {
passwords := map[string][]byte{}
switch {
case len(m.o.sourceSelector) > 0:
sources, err := m.selectedSources(ctx, hr)
if err != nil {
return nil, false, err
}
return nil, name, false, err
for _, sec := range sources {
user := string(sec.Data[account.UsernameKey])
pw, ok := sec.Data[m.o.sourceKey]
if user == "" || !ok {
continue
}
passwords[user] = pw
}
return passwords, len(sources) > 0, nil
case m.o.sourcePerAccount:
for _, acc := range accounts {
sec := &corev1.Secret{}
if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: m.perAccountSource(hr, acc.Username)}, sec); err != nil {
if apierrors.IsNotFound(err) {
continue
}
return nil, false, err
}
if pw, ok := sec.Data[m.o.sourceKey]; ok {
passwords[acc.Username] = pw
}
}
return passwords, true, nil
}
v, ok := sec.Data[key]
return v, name, ok, nil
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, false, nil
}
return nil, false, err
}
for _, acc := range accounts {
key := m.o.sourceKey
if key == "" {
key = acc.Username
}
if pw, ok := source.Data[key]; ok {
passwords[acc.Username] = pw
}
}
return passwords, true, nil
}
// sourceDesc names where the plaintext of user, or of every account when user
// is empty, was looked up.
func (m *migrator) sourceDesc(hr *helmv2.HelmRelease, user string) string {
switch {
case len(m.o.sourceSelector) > 0:
return fmt.Sprintf("the Secrets labelled %s of release %s", m.o.sourceSelector, hr.GetReleaseName())
case m.o.sourcePerAccount && user != "":
return m.perAccountSource(hr, user)
case m.o.sourcePerAccount:
return hr.Name + m.o.sourceSuffix + "<user>"
}
return hr.Name + m.o.sourceSuffix
}
// selectedSources lists the per-account source Secrets that carry
// --source-selector and that the release's chart rendered.
func (m *migrator) selectedSources(ctx context.Context, hr *helmv2.HelmRelease) ([]corev1.Secret, error) {
list := &corev1.SecretList{}
if err := m.c.List(ctx, list, client.InNamespace(hr.Namespace), client.MatchingLabels(m.o.sourceSelector)); err != nil {
return nil, err
}
var out []corev1.Secret
for _, sec := range list.Items {
if sec.Annotations[account.ReleaseNameAnnotation] == hr.GetReleaseName() {
out = append(out, sec)
}
}
return out, nil
}
func (m *migrator) perAccountSource(hr *helmv2.HelmRelease, user string) string {
@@ -554,7 +661,13 @@ func (m *migrator) perAccountSource(hr *helmv2.HelmRelease, user string) string
// which the converted chart would not render, or a reserved user name leave
// the release unresolvable. A skipped key is not a tenant account: the
// converted chart renders no template for it, so it is left out of the result.
//
// A kind with fixed accounts has no accounts map: its accounts are the fixed
// ones, or none when the release turns them off through the enabled flag.
func (o *options) resolveAccounts(hr *helmv2.HelmRelease) ([]account.Account, error) {
if len(o.fixedAccounts) > 0 {
return resolveFixedAccounts(hr, o.fixedAccounts, o.enabledFlag)
}
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 {
@@ -596,6 +709,39 @@ func (o *options) resolveAccounts(hr *helmv2.HelmRelease) ([]account.Account, er
return accounts, nil
}
// resolveFixedAccounts returns the fixed accounts of a kind with no accounts
// map, such as the one default user of Redis, or none when the release turns
// them off through the enabled flag. A flag that is not a boolean leaves the
// release unresolvable rather than guessing what the chart renders.
func resolveFixedAccounts(hr *helmv2.HelmRelease, users []string, enabledFlag string) ([]account.Account, error) {
if enabledFlag != "" {
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
}
}
switch v := lookup(values, enabledFlag).(type) {
case nil:
case bool:
if !v {
return nil, nil
}
default:
return nil, fmt.Errorf("%s is %v, not a boolean", enabledFlag, v)
}
}
accounts := make([]account.Account, 0, len(users))
for _, name := range users {
mapped, err := account.MapName(name)
if err != nil {
return nil, err
}
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
@@ -651,7 +797,7 @@ func (m *migrator) stripPasswords(ctx context.Context, hr *helmv2.HelmRelease) e
// stay in its data otherwise, and the Secret itself when no platform key
// remains.
func (m *migrator) retireSource(ctx context.Context, hr *helmv2.HelmRelease) error {
if m.o.sourcePerAccount {
if m.o.sourcePerAccount || len(m.o.sourceSelector) > 0 {
return m.retirePerAccountSources(ctx, hr)
}
source := &corev1.Secret{}
@@ -812,27 +958,39 @@ func (m *migrator) rotatePlatformKeys(ctx context.Context, hr *helmv2.HelmReleas
return nil
}
// retirePerAccountSources deletes the per-account source Secrets of the
// declared accounts. The converted chart no longer renders them, so Helm has
// usually pruned them at the switch; this removes one Helm left behind.
// retirePerAccountSources deletes the release's per-account source Secrets.
// Each holds one tenant password and nothing else, and the converted chart no
// longer renders them, so Helm has usually pruned them at the switch; this
// removes what a release installed outside Helm, or a failed prune, left.
func (m *migrator) retirePerAccountSources(ctx context.Context, hr *helmv2.HelmRelease) error {
accounts, err := m.o.resolveAccounts(hr)
if err != nil {
return err
}
for _, acc := range accounts {
sec := &corev1.Secret{}
name := m.perAccountSource(hr, acc.Username)
if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: name}, sec); err != nil {
if apierrors.IsNotFound(err) {
continue
}
var sources []corev1.Secret
if len(m.o.sourceSelector) > 0 {
var err error
if sources, err = m.selectedSources(ctx, hr); err != nil {
return err
}
} else {
accounts, err := m.o.resolveAccounts(hr)
if err != nil {
return err
}
for _, acc := range accounts {
sec := &corev1.Secret{}
if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: m.perAccountSource(hr, acc.Username)}, sec); err != nil {
if apierrors.IsNotFound(err) {
continue
}
return err
}
sources = append(sources, *sec)
}
}
for i := range sources {
sec := &sources[i]
if err := m.c.Delete(ctx, sec, client.Preconditions{UID: &sec.UID}); err != nil && !apierrors.IsNotFound(err) {
return err
}
fmt.Printf("%s/%s: deleted %s\n", hr.Namespace, hr.Name, name)
fmt.Printf("%s/%s: deleted %s\n", hr.Namespace, hr.Name, sec.Name)
}
return nil
}
+253
View File
@@ -21,6 +21,7 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
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"
@@ -45,6 +46,9 @@ func newMigratorWith(t *testing.T, funcs *interceptor.Funcs, objs ...client.Obje
if err := appsv1.AddToScheme(scheme); err != nil {
t.Fatal(err)
}
if err := cozyv1alpha1.AddToScheme(scheme); err != nil {
t.Fatal(err)
}
b := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objs...).WithStatusSubresource(&helmv2.HelmRelease{})
if funcs != nil {
b = b.WithInterceptorFuncs(*funcs)
@@ -885,3 +889,252 @@ func TestRunRefusesPerAccountSourcesWithoutAKey(t *testing.T) {
t.Fatalf("err = %v", err)
}
}
func perAccountSource(name, release, user, password string) *corev1.Secret {
return &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name, Namespace: "tenant-foo",
Labels: map[string]string{"apps.cozystack.io/user-secret": "true"},
Annotations: map[string]string{account.ReleaseNameAnnotation: release},
},
Data: map[string][]byte{account.UsernameKey: []byte(user), account.PasswordKey: []byte(password)},
}
}
// A chart that kept one Secret per account is read by label and by the Helm
// release that rendered it, so a sibling release's Secrets in the same
// namespace never feed this one.
func TestSeedReadsPerAccountSources(t *testing.T) {
ctx := context.Background()
m := newMigrator(t,
release(`{"users":{"web":{},"Api.1":{}}}`, "0.1.0", true),
perAccountSource("postgres-orders-web-credentials", "postgres-orders", "web", "hunter2"),
perAccountSource("postgres-orders-api-1-credentials", "postgres-orders", "Api.1", "secret"),
perAccountSource("postgres-other-web-credentials", "postgres-other", "web", "sibling"),
)
m.o.formatName = format.Plaintext
m.o.labels = labelFlags{"rabbitmq.com/topology-operator": "true"}
m.o.sourceSelector = labelFlags{"apps.cozystack.io/user-secret": "true"}
m.o.sourceKey = account.PasswordKey
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
for _, c := range []struct{ secret, user, plain string }{{"postgres-orders.web.account", "web", "hunter2"}, {"postgres-orders.api-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 || string(sec.Data[account.PasswordKey]) != c.plain {
t.Fatalf("%s data = %q", c.secret, sec.Data)
}
if sec.Labels["rabbitmq.com/topology-operator"] != "true" || sec.Annotations[account.FormatAnnotation] != format.Plaintext {
t.Fatalf("%s meta = %+v", c.secret, sec.ObjectMeta)
}
}
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")
}
}
func TestSeedWithoutPerAccountSourcesLeavesTheReleaseUnmarked(t *testing.T) {
ctx := context.Background()
m := newMigrator(t, release(`{"users":{"web":{}}}`, "0.1.0", true))
m.o.formatName = format.Plaintext
m.o.sourceSelector = labelFlags{"apps.cozystack.io/user-secret": "true"}
m.o.sourceKey = account.PasswordKey
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
if _, ok := m.secret(t, "postgres-orders.web.account"); ok {
t.Fatal("no account Secret can be written without its plaintext")
}
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 passwords are gone must not be seeded with random ones")
}
}
// RabbitMQ's chart default is users: {}, which leaves no source to select.
func TestSeedMarksAReleaseWithoutUsersFromSelectedSources(t *testing.T) {
ctx := context.Background()
m := newMigrator(t, release(`{"users":{}}`, "0.1.0", true))
m.o.formatName = format.Plaintext
m.o.sourceSelector = labelFlags{"apps.cozystack.io/user-secret": "true"}
m.o.sourceKey = account.PasswordKey
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 TestRetireSourceDeletesPerAccountSourcesOfThisReleaseOnly(t *testing.T) {
ctx := context.Background()
hr := release(`{"users":{"web":{}}}`, "0.2.0", true)
m := newMigrator(t, hr,
perAccountSource("postgres-orders-web-credentials", "postgres-orders", "web", "hunter2"),
perAccountSource("postgres-other-web-credentials", "postgres-other", "web", "sibling"),
)
m.o.sourceSelector = labelFlags{"apps.cozystack.io/user-secret": "true"}
m.o.sourceKey = account.PasswordKey
if err := m.retireSource(ctx, hr); err != nil {
t.Fatal(err)
}
if _, ok := m.secret(t, "postgres-orders-web-credentials"); ok {
t.Fatal("the release's per-account source must be deleted")
}
if _, ok := m.secret(t, "postgres-other-web-credentials"); !ok {
t.Fatal("a sibling release's Secret must be left alone")
}
}
func TestHidePlatformSecretsLabelsAnOperatorSecret(t *testing.T) {
ctx := context.Background()
hr := release(`{}`, "0.2.0", true)
admin := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "postgres-orders-default-user", Namespace: "tenant-foo", Labels: map[string]string{
corev1alpha1.TenantResourceLabelKey: "true", "app.kubernetes.io/name": "orders",
}}}
m := newMigrator(t, hr, admin)
m.o.hideSuffixes = stringFlags{"-default-user", "-missing"}
if err := m.hidePlatformSecrets(ctx, hr); err != nil {
t.Fatal(err)
}
sec, ok := m.secret(t, "postgres-orders-default-user")
if !ok || sec.Labels[corev1alpha1.TenantResourceLabelKey] != "false" || sec.Labels["app.kubernetes.io/name"] != "orders" {
t.Fatalf("secret = %+v", sec)
}
}
func TestRunRefusesTwoWaysToFindPerAccountSources(t *testing.T) {
err := run([]string{"seed", "--migration=68", "--kind=RabbitMQ", "--format=plaintext", "--source-key=password", "--source-per-account", "--source-selector=apps.cozystack.io/user-secret=true"})
if err == nil || !strings.Contains(err.Error(), "pass one") {
t.Fatalf("err = %v", err)
}
}
// redisMigrator is set up as the Redis conversion runs: one fixed account
// whose password sits under one key of <release>-auth, switched by
// authEnabled.
func redisMigrator(t *testing.T, values string, auth map[string]string) (*migrator, *helmv2.HelmRelease) {
t.Helper()
hr := release(values, "0.1.0", true)
hr.Name = "redis-cache"
hr.Labels[appsv1alpha1.ApplicationKindLabel] = "Redis"
hr.Labels[appsv1alpha1.ApplicationNameLabel] = "cache"
objs := []client.Object{hr}
if auth != nil {
sec := sourceSecret(auth)
sec.Name = "redis-cache-auth"
objs = append(objs, sec)
}
m := newMigrator(t, objs...)
m.o.kind = "Redis"
m.o.formatName = format.Plaintext
m.o.labels = labelFlags{}
m.o.sourceSuffix = "-auth"
m.o.fixedAccounts = stringFlags{"default"}
m.o.sourceKey = "password"
m.o.enabledFlag = "authEnabled"
return m, hr
}
func TestSeedFixedAccountFromOneSourceKey(t *testing.T) {
ctx := context.Background()
for _, values := range []string{`{}`, `{"authEnabled":true}`} {
m, hr := redisMigrator(t, values, map[string]string{"password": "s3cret"})
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
sec, ok := m.secret(t, "redis-cache.default.account")
if !ok {
t.Fatalf("%s: the default account Secret was not written", values)
}
if string(sec.Data[account.UsernameKey]) != "default" || string(sec.Data[account.PasswordKey]) != "s3cret" || sec.Annotations[account.FormatAnnotation] != format.Plaintext {
t.Fatalf("%s: account Secret = %+v %q", values, sec.ObjectMeta, sec.Data)
}
cur := &helmv2.HelmRelease{}
if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil {
t.Fatal(err)
}
if cur.Annotations[account.SeedAnnotation] != "true" {
t.Fatalf("%s: a release whose account got its Secret must be marked for seeding", values)
}
}
}
func TestSeedFixedAccountSwitchedOff(t *testing.T) {
ctx := context.Background()
m, _ := redisMigrator(t, `{"authEnabled":false}`, nil)
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
if _, ok := m.secret(t, "redis-cache.default.account"); ok {
t.Fatal("a release with authentication off declares no account")
}
st, _ := m.loadState(ctx)
if st.Releases["tenant-foo/redis-cache"] == nil || len(st.Skipped) != 0 {
t.Fatalf("state = %+v", st)
}
// Turning authentication on later seeds the account, which no client
// holds a password for yet.
hr := &helmv2.HelmRelease{}
if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "redis-cache"}, hr); err != nil {
t.Fatal(err)
}
if hr.Annotations[account.SeedAnnotation] != "true" {
t.Fatal("a release with no account must be marked for seeding")
}
}
func TestSeedFixedAccountLeavesOutANonBooleanFlag(t *testing.T) {
ctx := context.Background()
m, _ := redisMigrator(t, `{"authEnabled":"yes"}`, map[string]string{"password": "s3cret"})
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
st, _ := m.loadState(ctx)
if why := st.Skipped["tenant-foo/redis-cache"]; !strings.Contains(why, "not a boolean") {
t.Fatalf("skipped = %v", st.Skipped)
}
if _, ok := m.secret(t, "redis-cache.default.account"); ok {
t.Fatal("an unresolvable release gets no account Secret")
}
}
func TestFinishFixedAccountRetiresTheSource(t *testing.T) {
ctx := context.Background()
m, hr := redisMigrator(t, `{}`, map[string]string{"password": "s3cret"})
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)
}
if err := m.finish(ctx); err != nil {
t.Fatal(err)
}
if _, ok := m.secret(t, "redis-cache-auth"); ok {
t.Fatal("the source Secret must be deleted")
}
sec, ok := m.secret(t, "redis-cache.default.account")
if !ok || string(sec.Data[account.PasswordKey]) != "s3cret" {
t.Fatal("the account Secret must keep the migrated password")
}
}
+9 -6
View File
@@ -80,13 +80,16 @@ print_header() {
source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh"
# The cozystack redis chart names its RedisFailover (hence the operator's rfr-/
# rfs- Services and the -auth Secret) redis-<app>, the valkey chart valkey-<app>,
# mirroring the strategy driver that derives the same base from .Release.Prefix
# and .Release.Name. So app X's password lives in <prefix>X-auth. The chart
# renders that Secret only with authEnabled, so its absence reads as no
# password; any other error still fails the read.
# rfs- Services) redis-<app>, the valkey chart valkey-<app>, mirroring the
# strategy driver that derives the same base from .Release.Prefix and
# .Release.Name. App X's password lives in the account Secret of its default
# CredentialTemplate, <prefix>X.default.account, which holds the password itself
# and which this walkthrough reads with the platform credentials it runs under;
# a tenant gets the password by minting it instead. The Secret exists only with
# authEnabled, so its absence reads as no password; any other error still fails
# the read.
redis_pw() {
kubectl -n "$NAMESPACE" get secret "${APP_PREFIX}$1-auth" --ignore-not-found -o jsonpath='{.data.password}' | base64 -d
kubectl -n "$NAMESPACE" get secret "${APP_PREFIX}$1.default.account" --ignore-not-found -o jsonpath='{.data.password}' | base64 -d
}
# Run a redis-cli command against an application's CURRENT master. Master
+1 -1
View File
@@ -51,7 +51,7 @@ spec:
- name: REDIS_PASSWORD
valueFrom:
secretKeyRef:
name: '{{ .Release.Prefix | default "redis-" }}{{ .Release.Name }}-auth'
name: '{{ .Release.Prefix | default "redis-" }}{{ .Release.Name }}.default.account'
key: password
optional: true
# S3 coordinates come from this demo's Bucket: the access keys are
+7 -3
View File
@@ -34,12 +34,16 @@ COZYRDS="$REPO_ROOT/packages/system/rabbitmq-rd/cozyrds/rabbitmq.yaml"
# label whitelist alone passes an added name. Either dimension reaches a
# key-bearing Secret -- controller.cert-manager.io/fao is stamped on both the CA
# and the leaf, so a selector on it is a one-line grant of the CA private key.
EXPECTED_RD_INCLUDE='[{"resourceNames":["rabbitmq-{{ .name }}-default-user"]},{"matchLabels":{"internal.cozystack.io/tenant-ca":"true"}},{"matchLabels":{"apps.cozystack.io/user-secret":"true"}}]'
#
# Since the credentials conversion the trust anchor is the only Secret a tenant
# reads here: -default-user is the platform administrator, and the tenant
# accounts live in account Secrets no definition selects.
EXPECTED_RD_INCLUDE='[{"matchLabels":{"internal.cozystack.io/tenant-ca":"true"}}]'
# exclude is evaluated before include and wins, so it is the structural backstop
# against a mis-stamped label on a key-bearing object. Asserted whole for the same
# reason as the include: dropping one entry is the edit that has to be caught.
EXPECTED_RD_EXCLUDE='[{"resourceNames":["rabbitmq-{{ .name }}-ca","rabbitmq-{{ .name }}-tls","rabbitmq-{{ .name }}-erlang-cookie"]}]'
EXPECTED_RD_EXCLUDE='[{"resourceNames":["rabbitmq-{{ .name }}-ca","rabbitmq-{{ .name }}-tls","rabbitmq-{{ .name }}-erlang-cookie","rabbitmq-{{ .name }}-default-user"]}]'
# Subsumed by the whitelist below, which cannot match without this entry. Kept
# because the runner stops at the first failing test, so this one fires first and
@@ -61,7 +65,7 @@ EXPECTED_RD_EXCLUDE='[{"resourceNames":["rabbitmq-{{ .name }}-ca","rabbitmq-{{ .
fi
}
@test "rabbitmq-rd cozyrds grants nothing beyond the default user, the trust anchor and user credentials" {
@test "rabbitmq-rd cozyrds grants nothing beyond the trust anchor" {
if [ ! -f "$COZYRDS" ]; then
echo "ResourceDefinition not found at $COZYRDS -- did it move?" >&2
exit 1
+6 -4
View File
@@ -44,11 +44,13 @@ load test_helper
REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)"
CHART="$REPO_ROOT/packages/system/redis-rd"
# The complete tenant-visible Secret surface. The generated password by name;
# the trust anchor by label. Nothing else. The two key-bearing Secrets are
# The complete tenant-visible Secret surface: the trust anchor by label, and
# nothing else. The password is issued through the credentials API, and its
# account Secret is the platform's. The operator's internal account joins the
# key-bearing Secrets in exclude. The two key-bearing Secrets are
# named in exclude, which is evaluated before include and so backstops the
# label-only entry against a mis-stamp.
EXPECTED_SECRETS='{"exclude":[{"resourceNames":["redis-{{ .name }}.ca-tls","redis-{{ .name }}.tls","redis-{{ .name }}.ca-cert"]}],"include":[{"resourceNames":["redis-{{ .name }}-auth"]},{"matchLabels":{"internal.cozystack.io/tenant-ca":"true"}}]}'
EXPECTED_SECRETS='{"exclude":[{"resourceNames":["redis-{{ .name }}.ca-tls","redis-{{ .name }}.tls","redis-{{ .name }}.ca-cert","rfr-redis-{{ .name }}-internal"]}],"include":[{"matchLabels":{"internal.cozystack.io/tenant-ca":"true"}}]}'
# Order within include is meaningless -- the matcher ORs across entries -- so
# both arrays are sorted before comparing, and a missing exclude is normalized
@@ -115,7 +117,7 @@ NORMALIZE='{exclude: ((.exclude // []) | sort), include: (.include | sort)}'
# Whole-structure comparison. Anything added to the tenant's Secret surface --
# by name, by label, or by an unrestricted entry -- changes this string.
@test "redis-rd exposes no Secret beyond the password and the trust anchor" {
@test "redis-rd exposes no Secret beyond the trust anchor" {
rendered=$(helm template redis-rd "$CHART") || return 1
if [ -z "$rendered" ]; then
+99 -16
View File
@@ -81,6 +81,87 @@ spec:
status:
readyReplicas: 2
# The password is the platform's to issue: a mint reaches every running
# server with CONFIG SET, restarts no pod and moves no master (replication,
# the Sentinels, the probes and the exporter use the operator's internal
# account, not this password), and a second mint replaces the first.
- name: verify-minted-credential
try:
- assert:
timeout: 2m
resource:
apiVersion: core.cozystack.io/v1alpha1
kind: Credential
metadata:
name: redis-test.default
spec:
application:
kind: Redis
name: test
user: default
status:
password:
origin: NotIssued
# bash for pipefail and process substitution; the sandbox's /bin/sh is dash.
- script:
timeout: 10m
shell: bash
content: |
set -euo pipefail
cred=redis-test.default
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 redis-cli on stdin: exec arguments travel in
# the request URI, which the audit log records at any level.
cli() {
local password=$1; shift
local pod
pod=$(kubectl -n "$NAMESPACE" get pod -l app.kubernetes.io/component=redis,app.kubernetes.io/instance=redis-test \
--field-selector status.phase=Running -o name | head -n1)
[ -n "$pod" ] || return 0
printf '%s\n' "$password" | kubectl -n "$NAMESPACE" exec -i "$pod" -c redis -- \
sh -c 'IFS= read -r REDISCLI_AUTH; export REDISCLI_AUTH; exec redis-cli -h rfrm-redis-test "$@"' sh \
"$@" 2>/dev/null | tr -d '\r' || true
}
login() { cli "$1" ping; }
# Every redis pod with its uid and restart count, and which one the
# master label is on: a mint must change none of it.
pods() {
kubectl -n "$NAMESPACE" get pod -l app.kubernetes.io/component=redis,app.kubernetes.io/instance=redis-test \
-o jsonpath='{range .items[*]}{.metadata.name} {.metadata.uid} {.status.containerStatuses[*].restartCount} {.metadata.labels.redisfailovers-role}{"\n"}{end}' | sort
}
before=$(pods)
[ "$(printf '%s\n' "$before" | grep -c ' master$')" = 1 ] || { echo "no single master before the mint: $before" >&2; exit 1; }
first=$(mint)
[ "${#first}" -eq 32 ] || { echo "minted password has ${#first} characters, want 32" >&2; exit 1; }
# The operator applies the changed account Secret on its next
# reconcile; a readiness wait on that, not a retry.
until [ "$(login "$first")" = "PONG" ]; 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; }
if printf '%s' "$view" | grep -qF -- "$first"; then echo "the Credential carries the minted password" >&2; exit 1; fi
second=$(mint)
[ "$second" != "$first" ] || { echo "a second mint returned the same password" >&2; exit 1; }
until [ "$(login "$second")" = "PONG" ]; do sleep 5; done
# The operator drops the replaced password once every server takes
# the new one, a pass after it applies it.
while [ "$(login "$first")" = "PONG" ]; do sleep 5; done
# Replication outlived both rotations, and nothing restarted or
# failed over to get there.
until cli "$second" info replication | grep -qx 'connected_slaves:1'; do sleep 5; done
after=$(pods)
if [ "$after" != "$before" ]; then
printf 'a mint restarted a pod or moved the master:\nbefore:\n%s\nafter:\n%s\n' "$before" "$after" >&2
exit 1
fi
check:
($error == null): true
# One replica runs one Sentinel with its PDB disabled. The PDB the operator
# created for the three Sentinels of two replicas has to go with it, or its
# minAvailable: 1 pins the only Sentinel against every eviction.
@@ -267,20 +348,10 @@ spec:
try:
# Positive control, and it comes first: the negatives below are satisfied
# by an ABSENT label, which is also what a webhook that stamped nothing
# this run looks like. The auth Secret is chart-rendered, traces to the
# Redis CR and is included by name, so it MUST be stamped.
- assert:
timeout: 2m
resource:
apiVersion: v1
kind: Secret
metadata:
name: redis-secure-auth
labels:
internal.cozystack.io/tenantresource: "true"
# tenant-ca is stamped by the CA-extraction controller; tenantresource is
# the lineage webhook's verdict from the redis ApplicationDefinition's
# matchLabels include. Both true means the whole chain held.
# this run looks like. tenant-ca is stamped by the CA-extraction
# controller; tenantresource is the lineage webhook's verdict from the
# redis ApplicationDefinition's matchLabels include. Both true means the
# whole chain held.
- assert:
timeout: 2m
resource:
@@ -320,6 +391,15 @@ spec:
metadata:
name: redis-secure.ca-cert
(metadata.labels."internal.cozystack.io/tenantresource" != 'true'): true
# The account Secret holds the password itself and is the platform's.
- assert:
timeout: 2m
resource:
apiVersion: v1
kind: Secret
metadata:
name: redis-secure.default.account
(metadata.labels."internal.cozystack.io/tenantresource" != 'true'): true
# No retry around this script. The replica link it reads is settled by
# none of the asserts above and carries its own bounded wait below. The
# whole step measured 3.0s on run 34711755303, so link_wait is wide
@@ -523,7 +603,10 @@ spec:
# unlinked, and a dropped link re-enters it. The topology is thus in
# motion here and one sampling would decide on it. Wait for it to
# settle, then assert the sentinels moved off the bootstrap address,
# which nothing above covers at all.
# which nothing above covers at all. The redis container's
# REDIS_PASSWORD belongs to REDIS_USER (rf-internal), not to
# default, so the dial names that user, as the operator's own
# scripts do.
link_wait=60
started=$(date +%s)
deadline=$(( started + link_wait ))
@@ -534,7 +617,7 @@ spec:
for i in 0 1; do
rc=0
info=$(k -n "$NAMESPACE" exec "rfr-redis-secure-$i" -c redis -- \
sh -c 'REDISCLI_AUTH="$REDIS_PASSWORD" timeout 15 redis-cli --tls --cacert /tls/ca.crt -h localhost -p 6379 info replication' 2>&1) || rc=$?
sh -c 'REDISCLI_AUTH="$REDIS_PASSWORD" timeout 15 redis-cli ${REDIS_USER:+--user "$REDIS_USER"} --tls --cacert /tls/ca.crt -h localhost -p 6379 info replication' 2>&1) || rc=$?
if [ "$rc" -ne 0 ]; then
echo "INFO replication on rfr-redis-secure-$i failed (exit $rc): $info" >&2
exit 1
+202
View File
@@ -0,0 +1,202 @@
#!/usr/bin/env bats
# -----------------------------------------------------------------------------
# Unit tests for platform migration 68 --> 69 (convert RabbitMQ users to
# platform-minted credentials, first part).
#
# The migration seeds the account Secrets of every RabbitMQ release, then
# creates the cozystack-credentials-migration-68 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/68.
#
# 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-68-rabbitmq-credentials.bats
# -----------------------------------------------------------------------------
load test_helper
FAKEBIN="$PWD/hack/testdata/migration-68-rabbitmq-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-migration68-test:$(printf '%s' "$ALPINE" | sed 's/[^a-zA-Z0-9]/-/g')"
WORKROOT="${TMPDIR:-/tmp}/cozy-migration-68-$$"
IMAGE=registry.example.org/cozystack/cozystack:v1.7.0
cozy_cleanup() {
rm -rf "$WORKROOT"
return 0
}
cmdlog_line() {
grep -nE -- "$1" "$FAKE_CMDLOG" | head -1 | cut -d: -f1
}
run_migration() {
_run_migration_rc=0
docker run --rm --network none \
--user "$(id -u):$(id -g)" \
-v "$MIG_DIR:/migrations:ro" \
-v "$FAKEBIN:/fakebin:ro" \
-v "$WORK:/work" \
-e PATH=/fakebin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
-e FAKE_CMDLOG=/work/cmdlog \
-e NAMESPACE="${NAMESPACE-}" \
-e FAKE_IMAGE="${FAKE_IMAGE-}" \
-e FAKE_IMAGE_EMPTY="${FAKE_IMAGE_EMPTY-}" \
-e FAKE_GETPOD_FAIL="${FAKE_GETPOD_FAIL-}" \
-e FAKE_APPLY_FAIL="${FAKE_APPLY_FAIL-}" \
-e FAKE_SEED_FAIL="${FAKE_SEED_FAIL-}" \
-e FAKE_GETJOB_FAIL="${FAKE_GETJOB_FAIL-}" \
-e FAKE_JOBUID_EMPTY="${FAKE_JOBUID_EMPTY-}" \
-e FAKE_PATCH_FAIL="${FAKE_PATCH_FAIL-}" \
"$TESTIMG" "/migrations/$1" || _run_migration_rc=$?
return "$_run_migration_rc"
}
prep() {
docker info >/dev/null 2>&1 || {
echo "docker is required: these tests run migration 68 inside a build of" >&2
echo "$ALPINE, the migrations image's base." >&2
return 1
}
docker build -q -t "$TESTIMG" - >/dev/null <<DOCKERFILE
FROM $ALPINE
DOCKERFILE
chmod +x "$FAKEBIN/kubectl" "$FAKEBIN/credentials-migrate"
mkdir -p "$WORKROOT"
WORK=$(mktemp -d "$WORKROOT/XXXXXX")
export FAKE_CMDLOG="$WORK/cmdlog"
: > "$FAKE_CMDLOG"
export NAMESPACE=cozy-system
export FAKE_IMAGE="$IMAGE"
unset FAKE_IMAGE_EMPTY FAKE_GETPOD_FAIL FAKE_APPLY_FAIL FAKE_SEED_FAIL FAKE_GETJOB_FAIL FAKE_JOBUID_EMPTY FAKE_PATCH_FAIL || true
return 0
}
@test "it seeds, creates the finish Job on its own image, and stamps" {
prep
rc=0
run_migration 68 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -eq 0 ]
# The seed runs for migration 68, reading the per-user Secrets by label and
# labelling the account Secrets for the topology operator.
grep -qE "^CREDMIGRATE seed --migration 68 --kind RabbitMQ --format plaintext .*--source-selector apps.cozystack.io/user-secret=true --source-key password --label rabbitmq.com/topology-operator=true$" "$FAKE_CMDLOG"
grep -qE "^APPLY-RABBITMQ selector=1 key=1 hide=1 list=1$" "$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 appdefs=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 69$")
[ -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 68 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
grep -qE "^CREDMIGRATE seed --migration 68 " "$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 68 >"$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 68 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
grep -qE "^CREDMIGRATE seed --migration 68 " "$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 68 >"$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 68 >"$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 68 >"$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\" not found"
rc=0
run_migration 68 >"$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"
}
@@ -0,0 +1,180 @@
#!/usr/bin/env bats
# -----------------------------------------------------------------------------
# Unit tests for platform migrations 69 --> 70 (Redis) and 70 --> 71 (Valkey):
# convert the default password to platform-minted credentials, first part.
#
# Each migration seeds the account Secret of the default user of every release
# of its kind from <release>-auth, then creates its finish Job directly, as
# migration 64 does. These pin what the two add over 64: the seed and the Job
# take the fixed account, its source key and the enabled flag, and the Job's
# ClusterRole, ServiceAccount and binding are named for the migration, so the
# two conversions running in one upgrade share none of them.
#
# FAIL CLOSED is pinned for each path: a failed seed, a pod whose image cannot
# be read, a failed apply of the Job, and a Job that cannot be owned 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-69-70-redis-valkey-credentials.bats
# -----------------------------------------------------------------------------
load test_helper
FAKEBIN="$PWD/hack/testdata/migration-69-70-redis-valkey-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-migration69-test:$(printf '%s' "$ALPINE" | sed 's/[^a-zA-Z0-9]/-/g')"
WORKROOT="${TMPDIR:-/tmp}/cozy-migration-69-$$"
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 FAKE_MIGRATION="$1" \
-e NAMESPACE="${NAMESPACE-}" \
-e FAKE_IMAGE="${FAKE_IMAGE-}" \
-e FAKE_IMAGE_EMPTY="${FAKE_IMAGE_EMPTY-}" \
-e FAKE_GETPOD_FAIL="${FAKE_GETPOD_FAIL-}" \
-e FAKE_APPLY_FAIL="${FAKE_APPLY_FAIL-}" \
-e FAKE_SEED_FAIL="${FAKE_SEED_FAIL-}" \
-e FAKE_GETJOB_FAIL="${FAKE_GETJOB_FAIL-}" \
-e FAKE_JOBUID_EMPTY="${FAKE_JOBUID_EMPTY-}" \
-e FAKE_PATCH_FAIL="${FAKE_PATCH_FAIL-}" \
"$TESTIMG" "/migrations/$1" || _run_migration_rc=$?
return "$_run_migration_rc"
}
prep() {
docker info >/dev/null 2>&1 || {
echo "docker is required: these tests run migrations 69 and 70 inside a" >&2
echo "build of $ALPINE, the migrations image's base." >&2
return 1
}
docker build -q -t "$TESTIMG" - >/dev/null <<DOCKERFILE
FROM $ALPINE
DOCKERFILE
chmod +x "$FAKEBIN/kubectl" "$FAKEBIN/credentials-migrate"
mkdir -p "$WORKROOT"
WORK=$(mktemp -d "$WORKROOT/XXXXXX")
export FAKE_CMDLOG="$WORK/cmdlog"
: > "$FAKE_CMDLOG"
export NAMESPACE=cozy-system
export FAKE_IMAGE="$IMAGE"
unset FAKE_IMAGE_EMPTY FAKE_GETPOD_FAIL FAKE_APPLY_FAIL FAKE_SEED_FAIL FAKE_GETJOB_FAIL FAKE_JOBUID_EMPTY FAKE_PATCH_FAIL || true
return 0
}
# check_converts <migration> <kind>
check_converts() {
prep
rc=0
run_migration "$1" >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -eq 0 ]
# The seed takes the one default user, its password from the password key
# of <release>-auth, and authEnabled as the switch.
# It holds the releases until the new redis-operator runs, which the
# finish Job reads the Deployment for: the old operator rolls the converted
# pod template by deleting the master.
grep -qxF "CREDMIGRATE seed --migration $1 --kind $2 --format plaintext --fixed-account default --source-key password --enabled-flag authEnabled --source-suffix=-auth --hold-until-rollout cozy-redis-operator/redis-operator" "$FAKE_CMDLOG"
# The finish Job carries its least-privilege ClusterRole (never
# cluster-admin), ServiceAccount and binding, all named for the migration
# (five names: the three objects, the roleRef and the Job), the same account
# flags as the seed, and the image this hook runs as.
grep -qxE "APPLY-FINISH role=1 sa=1 crb=1 admin=0 migration=1 image=1 serviceaccount=1 fixed=5 actor=1 named=5 deployments=1" "$FAKE_CMDLOG"
grep -qxE "PATCH-SA-OWNER owner=1" "$FAKE_CMDLOG"
# Stale Job deleted before the apply, owned after it, stamped last.
_del=$(cmdlog_line "^DELETE-JOB$")
_apply=$(cmdlog_line "^APPLY-FINISH ")
_own=$(cmdlog_line "^PATCH-SA-OWNER ")
_stamp=$(cmdlog_line "^STAMP $(($1 + 1))$")
[ -n "$_del" ] && [ "$_del" -lt "$_apply" ]
[ -n "$_own" ] && [ "$_apply" -lt "$_own" ]
[ -n "$_stamp" ] && [ "$_own" -lt "$_stamp" ]
rm -rf "$WORK"
}
# check_fails_closed <migration> <fake variable> <value>
check_fails_closed() {
prep
export "$2=$3"
rc=0
run_migration "$1" >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "migration $1 stamped after $2" >&2; return 1; fi
rm -rf "$WORK"
}
@test "69 converts Redis: seeds, creates its own finish Job, and stamps 70" {
check_converts 69 Redis
}
@test "70 converts Valkey: seeds, creates its own finish Job, and stamps 71" {
check_converts 70 Valkey
}
@test "a failed seed stops before the Job and the stamp" {
for n in 69 70; do
check_fails_closed "$n" FAKE_SEED_FAIL "apiserver is unavailable"
done
}
@test "a pod whose image cannot be read stops before the Job and the stamp" {
for n in 69 70; do
check_fails_closed "$n" FAKE_GETPOD_FAIL "the server could not find the requested resource"
check_fails_closed "$n" FAKE_IMAGE_EMPTY 1
done
}
@test "a seed that fails to hold a release stops before the Job and the stamp" {
# A release suspended with no finish Job to resume it would stay frozen.
for n in 69 70; do
prep
export FAKE_SEED_FAIL="tenant-a/redis-x: hold until the new components run: the object has been modified"
rc=0
run_migration "$n" >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
grep -qF "hold until the new components run" "$WORK/out"
if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "migration $n created the Job after a failed hold" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "migration $n stamped after a failed hold" >&2; return 1; fi
rm -rf "$WORK"
done
}
@test "a failed apply of the Job stops before stamping" {
for n in 69 70; do
check_fails_closed "$n" FAKE_APPLY_FAIL "admission webhook denied the request"
done
}
@test "a Job that cannot be owned stops before stamping" {
for n in 69 70; do
check_fails_closed "$n" FAKE_GETJOB_FAIL "the server was unable to return a response"
check_fails_closed "$n" FAKE_JOBUID_EMPTY 1
check_fails_closed "$n" FAKE_PATCH_FAIL "serviceaccounts not found"
done
}
+252
View File
@@ -0,0 +1,252 @@
#!/usr/bin/env bats
# -----------------------------------------------------------------------------
# Unit tests for platform migration 71 --> 72 (convert Bucket users to
# platform-minted credentials).
#
# The migration marks every tenant BucketAccess the bucket chart rendered with
# helm.sh/resource-policy=keep and credentials.cozystack.io/adopt=true, so the
# chart upgrade leaves it in place and cozystack-controller adopts it with its
# keys, and marks the backup bucket's system user platform. See
# packages/core/platform/images/migrations/migrations/71.
#
# FAIL CLOSED is pinned: a failed listing or a failed mark must stop the
# migration before it stamps the version, because migrations never re-run.
#
# The harness (docker, the migrations image base, fake kubectl on PATH) is the
# one hack/migration-58-http-cache-freeze.bats describes.
#
# Run with: hack/cozytest.sh hack/migration-71-bucket-credentials.bats
# -----------------------------------------------------------------------------
load test_helper
FAKEBIN="$PWD/hack/testdata/migration-71-bucket-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-migration71-test:$(printf '%s' "$ALPINE" | sed 's/[^a-zA-Z0-9]/-/g')"
WORKROOT="${TMPDIR:-/tmp}/cozy-migration-71-$$"
# namespace name release class controller-kind. bucket-docs-public-read is a
# tenant user named public-read in a bucket without publicRead, on the base
# class of a SeaweedFS in tenant-public, which ends in -public too;
# bucket-old-public-read is an anonymous access whose class is gone.
ACCESSES='tenant-foo bucket-photos-web bucket-photos tenant-foo
tenant-foo bucket-photos-reader bucket-photos tenant-foo-readonly
tenant-foo bucket-photos-public-read bucket-photos tenant-foo-public
tenant-public bucket-docs-public-read bucket-docs tenant-public
tenant-bar bucket-old-public-read bucket-old tenant-bar-public
tenant-root bucket-cozy-backups-system bucket-cozy-backups tenant-root
tenant-foo bucket-done-app bucket-done tenant-foo CredentialTemplate
tenant-foo unrelated some-release tenant-foo '
# name accessPolicy, as the SeaweedFS chart renders them.
CLASSES='tenant-foo readwrite
tenant-foo-readonly readonly
tenant-foo-public public-read
tenant-public readwrite
tenant-public-readonly readonly
tenant-public-public public-read
tenant-root readwrite'
cmdlog_line() {
grep -nE -- "$1" "$FAKE_CMDLOG" | head -1 | cut -d: -f1
}
cozy_cleanup() {
rm -rf "$WORKROOT"
return 0
}
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=cozy-system \
-e FAKE_ACCESSES="${FAKE_ACCESSES-}" \
-e FAKE_CLASSES="${FAKE_CLASSES-}" \
-e FAKE_CLASS_FAIL="${FAKE_CLASS_FAIL-}" \
-e FAKE_BACKUP_NS="${FAKE_BACKUP_NS-}" \
-e FAKE_BACKUP_BUCKET="${FAKE_BACKUP_BUCKET-}" \
-e FAKE_NO_SYSTEM="${FAKE_NO_SYSTEM-}" \
-e FAKE_NO_CRD="${FAKE_NO_CRD-}" \
-e FAKE_LIST_FAIL="${FAKE_LIST_FAIL-}" \
-e FAKE_LABEL_FAIL="${FAKE_LABEL_FAIL-}" \
-e FAKE_KEYLESS="${FAKE_KEYLESS-}" \
-e FAKE_STRIP_FAIL="${FAKE_STRIP_FAIL-}" \
-e FAKE_CRD_FAIL="${FAKE_CRD_FAIL-}" \
-e CREDENTIAL_CRD_FILE=/work/credentialtemplates.yaml \
"$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 71 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"
mkdir -p "$WORKROOT"
WORK=$(mktemp -d "$WORKROOT/XXXXXX")
export FAKE_CMDLOG="$WORK/cmdlog"
: > "$FAKE_CMDLOG"
export FAKE_ACCESSES="$ACCESSES"
export FAKE_CLASSES="$CLASSES"
unset FAKE_CLASS_FAIL FAKE_BACKUP_NS FAKE_BACKUP_BUCKET FAKE_NO_SYSTEM FAKE_NO_CRD FAKE_LIST_FAIL FAKE_LABEL_FAIL FAKE_CRD_FAIL FAKE_KEYLESS FAKE_STRIP_FAIL || true
return 0
}
@test "it marks tenant BucketAccesses, the backup user platform, and stamps" {
prep
rc=0
run_migration 71 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -eq 0 ]
grep -qxF "PATCH-PLATFORM tenant-root/bucket-cozy-backups platform=1" "$FAKE_CMDLOG"
# The CRD with spec.bucketAccess is applied, owned by the
# cozystack-controller release, and established before anything else.
_crd=$(cmdlog_line "^CRD established$")
_platform=$(cmdlog_line "^PATCH-PLATFORM ")
[ -n "$_crd" ] && [ "$_crd" -lt "$_platform" ]
grep -qxF "CRD label" "$FAKE_CMDLOG"
grep -qxF "CRD annotate" "$FAKE_CMDLOG"
for name in tenant-foo/bucket-photos-web tenant-foo/bucket-photos-reader tenant-public/bucket-docs-public-read; do
grep -qxF "KEEP $name keep=1" "$FAKE_CMDLOG"
grep -qxF "ADOPT $name adopt=1" "$FAKE_CMDLOG"
done
grep -qxF "STRIP tenant-public/bucket-docs-public-read-credentials strip=1" "$FAKE_CMDLOG"
# The anonymous public-read access has no keys, whether its class is there
# or gone; the backup user stays a platform account, an adopted
# BucketAccess is left alone, and nothing a bucket chart did not render is
# touched.
for name in bucket-photos-public-read bucket-old-public-read bucket-cozy-backups-system bucket-done-app unrelated; do
if grep -qE "^(KEEP|ADOPT) [^ ]*/$name " "$FAKE_CMDLOG"; then echo "marked $name" >&2; return 1; fi
done
# Each tenant user's readable Secret loses its keys; the platform user's
# keeps them, and nothing reads the key values out.
for name in bucket-photos-web bucket-photos-reader bucket-done-app; do
grep -qxF "STRIP tenant-foo/$name-credentials strip=1" "$FAKE_CMDLOG"
done
if grep -qE "^STRIP [^ ]*/bucket-cozy-backups-system-credentials " "$FAKE_CMDLOG"; then echo "stripped the platform user's keys" >&2; return 1; fi
if grep -qE "^READ-KEYS " "$FAKE_CMDLOG"; then echo "read the key values" >&2; return 1; fi
_strip=$(cmdlog_line "^STRIP ")
_stamp=$(cmdlog_line "^STAMP 72$")
[ -n "$_strip" ] && [ "$_strip" -lt "$_stamp" ]
rm -rf "$WORK"
}
@test "a Secret that holds no keys is not patched" {
prep
export FAKE_ACCESSES='tenant-foo bucket-photos-web bucket-photos tenant-foo '
export FAKE_KEYLESS=bucket-photos-web-credentials
rc=0
run_migration 71 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -eq 0 ]
if grep -qE "^STRIP " "$FAKE_CMDLOG"; then echo "patched a keyless Secret" >&2; return 1; fi
grep -qxF "ADOPT tenant-foo/bucket-photos-web adopt=1" "$FAKE_CMDLOG"
rm -rf "$WORK"
}
@test "a failed strip stops before stamping" {
prep
export FAKE_STRIP_FAIL="secrets is forbidden"
rc=0
run_migration 71 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed strip" >&2; return 1; fi
rm -rf "$WORK"
}
@test "it finds the backup bucket where backupstrategy-controller provisions it" {
prep
export FAKE_BACKUP_NS=tenant-ops FAKE_BACKUP_BUCKET=backups
export FAKE_ACCESSES='tenant-ops bucket-backups-system bucket-backups tenant-ops '
rc=0
run_migration 71 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -eq 0 ]
grep -qxF "PATCH-PLATFORM tenant-ops/bucket-backups platform=1" "$FAKE_CMDLOG"
if grep -qE "^(KEEP|ADOPT) " "$FAKE_CMDLOG"; then echo "marked the backup user" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a backup release without a system user is not given one" {
prep
export FAKE_NO_SYSTEM=1
rc=0
run_migration 71 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -eq 0 ]
if grep -qE "^PATCH-PLATFORM" "$FAKE_CMDLOG"; then echo "patched a release without a system user" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a cluster without the COSI API stamps without listing" {
prep
export FAKE_NO_CRD=1
rc=0
run_migration 71 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -eq 0 ]
if grep -qF "get bucketaccesses" "$FAKE_CMDLOG"; then echo "listed BucketAccesses without the CRD" >&2; return 1; fi
grep -qxF "STAMP 72" "$FAKE_CMDLOG"
rm -rf "$WORK"
}
@test "a failed listing stops before stamping" {
prep
export FAKE_LIST_FAIL="the server was unable to return a response"
rc=0
run_migration 71 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed listing" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a failed class listing stops before any mark and the stamp" {
prep
export FAKE_CLASS_FAIL="the server was unable to return a response"
rc=0
run_migration 71 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qE "^(KEEP|ADOPT|STRIP) " "$FAKE_CMDLOG"; then echo "marked without the classes" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed class listing" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a failed mark stops before stamping" {
prep
export FAKE_LABEL_FAIL="admission webhook denied the request"
rc=0
run_migration 71 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed mark" >&2; return 1; fi
rm -rf "$WORK"
}
@test "a CRD that fails to apply stops before any mark and the stamp" {
prep
export FAKE_CRD_FAIL=1
rc=0
run_migration 71 >"$WORK/out" 2>&1 || rc=$?
cat "$WORK/out"; cat "$FAKE_CMDLOG"
[ "$rc" -ne 0 ]
if grep -qE "^(PATCH-PLATFORM|KEEP|ADOPT) " "$FAKE_CMDLOG"; then echo "marked without the CRD" >&2; return 1; fi
if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped without the CRD" >&2; return 1; fi
rm -rf "$WORK"
}
+1 -1
View File
@@ -20,7 +20,7 @@ make_stubs() {
cat > "$stub/kubectl" <<'EOF'
#!/bin/bash
printf '%s\n' "$*" >> "$STUB_DIR/kubectl.argv"
if [ "$*" = "-n tenant-root get secret redis-demo-auth --ignore-not-found -o jsonpath={.data.password}" ]; then
if [ "$*" = "-n tenant-root get secret redis-demo.default.account --ignore-not-found -o jsonpath={.data.password}" ]; then
printf '%s' "${STUB_PW_B64:-}"
exit 0
fi
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
# Fake credentials-migrate for hack/migration-68-rabbitmq-credentials.bats.
# Migration 68 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
+119
View File
@@ -0,0 +1,119 @@
#!/bin/sh
# Fake kubectl for hack/migration-68-rabbitmq-credentials.bats, modelled on
# hack/testdata/migration-58-http-cache/kubectl. It serves only the calls
# migration 68 and lib/cozystack-version.sh make, and logs each one to
# $FAKE_CMDLOG.
#
# Migration 68 reads its own pod's image, applies the finish Job (with its
# ServiceAccount and ClusterRoleBinding), and stamps the version. The Job
# manifest and the version stamp both arrive as `apply --filename -`, so this
# fake reads stdin and branches on the manifest's kind.
#
# FAKE_CMDLOG file to append a one-line record of each call to
# FAKE_IMAGE image the `get pod` call returns (default a test ref)
# FAKE_IMAGE_EMPTY non-empty => `get pod` returns an empty image
# FAKE_GETPOD_FAIL non-empty => `get pod` exits 1 with this stderr
# FAKE_APPLY_FAIL non-empty => applying the Job exits 1 with this stderr
set -u
log() { [ -n "${FAKE_CMDLOG:-}" ] && printf '%s\n' "$*" >> "$FAKE_CMDLOG"; }
log "KUBECTL $*"
args="$*"
IMAGE="${FAKE_IMAGE:-registry.example.org/cozystack/cozystack:v1.7.0}"
case "$args" in
*"get pod"*jsonpath*)
if [ -n "${FAKE_GETPOD_FAIL:-}" ]; then
printf '%s\n' "$FAKE_GETPOD_FAIL" >&2
exit 1
fi
[ -n "${FAKE_IMAGE_EMPTY:-}" ] || printf '%s' "$IMAGE"
exit 0
;;
*"delete job cozystack-credentials-migration-68"*)
# The hook deletes a Job left by an earlier run before recreating it.
log "DELETE-JOB"
exit 0
;;
*"delete serviceaccount cozystack-credentials-migration-68"*)
# 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-68"*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-68"*)
# 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-68')
log "PATCH-SA-OWNER owner=$owner"
exit 0
;;
*"apply --filename -"*)
manifest=$(cat)
case "$manifest" in
*"kind: ConfigMap"*)
v=$(printf '%s\n' "$manifest" | sed -n 's/^ version: "\{0,1\}\([0-9]\{1,\}\)"\{0,1\}$/\1/p' | head -1)
log "STAMP ${v:-unknown}"
exit 0
;;
*"kind: Job"*)
if [ -n "${FAKE_APPLY_FAIL:-}" ]; then
printf '%s\n' "$FAKE_APPLY_FAIL" >&2
exit 1
fi
# Record the fields the Job must carry, so a copy that drops the
# ServiceAccount, names the wrong migration, or renders the wrong image
# is caught.
role=$(printf '%s\n' "$manifest" | grep -c '^kind: ClusterRole$')
sa=$(printf '%s\n' "$manifest" | grep -c '^kind: ServiceAccount$')
crb=$(printf '%s\n' "$manifest" | grep -c '^kind: ClusterRoleBinding$')
# The binding must grant the least-privilege role, never cluster-admin.
admin=$(printf '%s\n' "$manifest" | grep -c 'cluster-admin')
# The ServiceAccount, ClusterRole and binding share the Job's name, so
# count the name inside the Job document only.
jobname=$(printf '%s\n' "$manifest" | awk '/^kind: Job$/ { j = 1 } j && /^ name: cozystack-credentials-migration-68$/ { c++ } END { print c + 0 }')
mig=$(printf '%s\n' "$manifest" | grep -c -- '--migration=68')
img=$(printf '%s\n' "$manifest" | grep -c "^ image: ${IMAGE}$")
sacc=$(printf '%s\n' "$manifest" | grep -c '^ serviceAccountName: cozystack-credentials-migration-68$')
# RabbitMQ finish reads the per-user sources by label, hides the
# operator's administrator Secret, and needs list on Secrets for it.
selector=$(printf '%s\n' "$manifest" | grep -c -- '--source-selector=apps.cozystack.io/user-secret=true')
key=$(printf '%s\n' "$manifest" | grep -c -- '--source-key=password')
hide=$(printf '%s\n' "$manifest" | grep -c -- '--hide-secret-suffix=-default-user')
list=$(printf '%s\n' "$manifest" | grep -c 'verbs: \["get", "list", "create", "patch", "delete"\]')
log "APPLY-RABBITMQ selector=$selector key=$key hide=$hide list=$list"
# It reads the definitions to hide -default-user only once they do.
appdefs=$(printf '%s\n' "$manifest" | grep -c '^ resources: \["applicationdefinitions"\]$')
log "APPLY-FINISH role=$role sa=$sa crb=$crb admin=$admin jobname=$jobname migration=$mig image=$img serviceaccount=$sacc appdefs=$appdefs"
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
@@ -0,0 +1,22 @@
#!/bin/sh
# Fake credentials-migrate for hack/migration-69-70-redis-valkey-credentials.bats.
# Migrations 69 and 70 run `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
+119
View File
@@ -0,0 +1,119 @@
#!/bin/sh
# Fake kubectl for hack/migration-69-70-redis-valkey-credentials.bats, the
# one hack/testdata/migration-64-postgres-credentials/kubectl is with the
# migration number taken from $FAKE_MIGRATION. It serves only the calls
# migrations 69 and 70 and lib/cozystack-version.sh make, and logs each one
# to $FAKE_CMDLOG.
#
# Each migration 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_MIGRATION number of the migration under test
# 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}"
N="${FAKE_MIGRATION:?FAKE_MIGRATION is required}"
NAME="cozystack-credentials-migration-$N"
case "$args" in
*"get pod"*jsonpath*)
if [ -n "${FAKE_GETPOD_FAIL:-}" ]; then
printf '%s\n' "$FAKE_GETPOD_FAIL" >&2
exit 1
fi
[ -n "${FAKE_IMAGE_EMPTY:-}" ] || printf '%s' "$IMAGE"
exit 0
;;
*"delete job $NAME "*)
# The hook deletes a Job left by an earlier run before recreating it.
log "DELETE-JOB"
exit 0
;;
*"delete serviceaccount $NAME "*)
# 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 $NAME "*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 $NAME "*)
# 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 "\"name\":\"$NAME\"")
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')
mig=$(printf '%s\n' "$manifest" | grep -c -- "--migration=$N\$")
# The Job finishes the kind with the same accounts the hook seeded.
fixed=$(printf '%s\n' "$manifest" | grep -c -e '- --fixed-account=default$' -e '- --source-key=password$' -e '- --enabled-flag=authEnabled$' -e '- --source-suffix=-auth$' -e '- --format=plaintext$')
actor=$(printf '%s\n' "$manifest" | grep -c "value: system:serviceaccount:.*:$NAME\$")
img=$(printf '%s\n' "$manifest" | grep -c "^ image: ${IMAGE}$")
sacc=$(printf '%s\n' "$manifest" | grep -c "^ serviceAccountName: $NAME\$")
# ClusterRole, ServiceAccount, ClusterRoleBinding and Job, each named for
# the migration, so two conversions in one upgrade do not share them.
named=$(printf '%s\n' "$manifest" | grep -c "^ name: $NAME\$")
# It reads Deployments to resume the held releases after the rollout.
deploy=$(printf '%s\n' "$manifest" | grep -c '^ resources: \["deployments"\]$')
log "APPLY-FINISH role=$role sa=$sa crb=$crb admin=$admin migration=$mig image=$img serviceaccount=$sacc fixed=$fixed actor=$actor named=$named deployments=$deploy"
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
+111
View File
@@ -0,0 +1,111 @@
#!/bin/sh
# Fake kubectl for hack/migration-71-bucket-credentials.bats, modelled on
# hack/testdata/migration-64-postgres-credentials/kubectl. It serves only the
# calls migration 71, lib/credential-crd.sh and lib/cozystack-version.sh
# make, and logs each one to $FAKE_CMDLOG.
#
# FAKE_CMDLOG file to append a one-line record of each call to
# FAKE_BACKUP_NS backupStorage.namespace of backupstrategy-controller
# FAKE_BACKUP_BUCKET backupStorage.bucketName of backupstrategy-controller
# FAKE_NO_SYSTEM non-empty => the backup Bucket release has no system user
# FAKE_NO_CRD non-empty => the BucketAccess CRD is not installed
# FAKE_ACCESSES the BucketAccess listing, one line per object:
# namespace name release class controller-kind
# FAKE_CLASSES the BucketAccessClass listing, one line per object:
# name accessPolicy
# FAKE_CLASS_FAIL non-empty => listing BucketAccessClasses exits 1
# FAKE_LIST_FAIL non-empty => listing BucketAccesses exits 1
# FAKE_LABEL_FAIL non-empty => labelling a BucketAccess exits 1
# FAKE_KEYLESS space-separated Secret names that hold no keys
# FAKE_STRIP_FAIL non-empty => patching a credentials Secret exits 1
# FAKE_CRD_FAIL non-empty => applying the CredentialTemplate CRD exits 1
set -u
log() { [ -n "${FAKE_CMDLOG:-}" ] && printf '%s\n' "$*" >> "$FAKE_CMDLOG"; }
log "KUBECTL $*"
args="$*"
ns_of() { printf '%s\n' "$args" | sed -n 's/.*--namespace \([^ ]*\).*/\1/p'; }
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"*"meta.helm.sh/release-namespace=cozy-system"*)
log "CRD annotate"; exit 0 ;;
*"wait --for=condition=established crd/credentialtemplates.cozystack.io"*)
log "CRD established"; exit 0 ;;
*"get helmreleases.helm.toolkit.fluxcd.io backupstrategy-controller"*"backupStorage.namespace"*)
printf '%s' "${FAKE_BACKUP_NS:-}"; exit 0 ;;
*"get helmreleases.helm.toolkit.fluxcd.io backupstrategy-controller"*"backupStorage.bucketName"*)
printf '%s' "${FAKE_BACKUP_BUCKET:-}"; exit 0 ;;
*"get helmreleases.helm.toolkit.fluxcd.io backupstrategy-controller"*"backupStorage.provisionBucket"*)
exit 0 ;;
*"get helmreleases.helm.toolkit.fluxcd.io bucket-"*"users.system"*)
[ -n "${FAKE_NO_SYSTEM:-}" ] || printf '%s' '{"readonly":false}'
exit 0 ;;
*"patch helmreleases.helm.toolkit.fluxcd.io "*)
name=$(printf '%s\n' "$args" | sed -n 's/.*patch helmreleases.helm.toolkit.fluxcd.io \([^ ]*\).*/\1/p')
platform=$(printf '%s\n' "$args" | grep -c '"system":{"platform":true}')
log "PATCH-PLATFORM $(ns_of)/$name platform=$platform"
exit 0 ;;
*"get customresourcedefinitions.apiextensions.k8s.io bucketaccesses.objectstorage.k8s.io"*)
[ -n "${FAKE_NO_CRD:-}" ] || printf '%s\n' "customresourcedefinition.apiextensions.k8s.io/bucketaccesses.objectstorage.k8s.io"
exit 0 ;;
*"get bucketaccessclasses.objectstorage.k8s.io "*"parameters.accessPolicy"*)
if [ -n "${FAKE_CLASS_FAIL:-}" ]; then
printf '%s\n' "$FAKE_CLASS_FAIL" >&2; exit 1
fi
printf '%s\n' "${FAKE_CLASSES:-}"
exit 0 ;;
*"get bucketaccesses.objectstorage.k8s.io --all-namespaces"*"spec.bucketAccessClassName"*)
if [ -n "${FAKE_LIST_FAIL:-}" ]; then
printf '%s\n' "$FAKE_LIST_FAIL" >&2; exit 1
fi
printf '%s\n' "${FAKE_ACCESSES:-}"
exit 0 ;;
*"get secrets "*"go-template="*)
name=$(printf '%s\n' "$args" | sed -n 's/.*get secrets \([^ ]*\).*/\1/p')
# The check must not read the key values out.
case "$args" in *"jsonpath"*) log "READ-KEYS $name"; exit 1 ;; esac
case " ${FAKE_KEYLESS:-} " in *" $name "*) exit 0 ;; esac
printf '%s' held
exit 0 ;;
*"patch secrets "*)
if [ -n "${FAKE_STRIP_FAIL:-}" ]; then
printf '%s\n' "$FAKE_STRIP_FAIL" >&2; exit 1
fi
name=$(printf '%s\n' "$args" | sed -n 's/.*patch secrets \([^ ]*\).*/\1/p')
strip=$(printf '%s\n' "$args" | grep -c '"accessKey":null,"secretKey":null')
log "STRIP $(ns_of)/$name strip=$strip"
exit 0 ;;
*"annotate bucketaccesses.objectstorage.k8s.io "*)
name=$(printf '%s\n' "$args" | sed -n 's/.*annotate bucketaccesses.objectstorage.k8s.io \([^ ]*\).*/\1/p')
keep=$(printf '%s\n' "$args" | grep -c 'helm.sh/resource-policy=keep')
log "KEEP $(ns_of)/$name keep=$keep"
exit 0 ;;
*"label bucketaccesses.objectstorage.k8s.io "*)
if [ -n "${FAKE_LABEL_FAIL:-}" ]; then
printf '%s\n' "$FAKE_LABEL_FAIL" >&2; exit 1
fi
name=$(printf '%s\n' "$args" | sed -n 's/.*label bucketaccesses.objectstorage.k8s.io \([^ ]*\).*/\1/p')
adopt=$(printf '%s\n' "$args" | grep -c 'credentials.cozystack.io/adopt=true')
log "ADOPT $(ns_of)/$name adopt=$adopt"
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 ;;
esac
;;
esac
log "UNHANDLED $args"
printf 'fake kubectl: unmodelled call: %s\n' "$args" >&2
exit 1
@@ -49,6 +49,7 @@ const CredentialControllerActor = "system:serviceaccount:cozy-system:cozystack-c
const (
reasonCredentialReset = "CredentialReset"
reasonCredentialAdopted = "CredentialAdopted"
reasonCredentialRevoked = "CredentialRevoked"
)
// CredentialTemplateReconciler keeps each CredentialTemplate and its account
@@ -87,6 +88,10 @@ func (r *CredentialTemplateReconciler) Reconcile(ctx context.Context, req ctrl.R
if !tmpl.DeletionTimestamp.IsZero() {
return ctrl.Result{}, nil
}
if engineIssued(tmpl) {
// The engine issues these keys; COSICredentialReconciler keeps them.
return ctrl.Result{}, nil
}
status := tmpl.Status.DeepCopy()
status.ObservedGeneration = tmpl.Generation
@@ -312,12 +317,17 @@ func mirror(status *cozyv1alpha1.CredentialTemplateStatus, sec *corev1.Secret) {
}
func (r *CredentialTemplateReconciler) writeStatus(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, status *cozyv1alpha1.CredentialTemplateStatus) error {
return writeTemplateStatus(ctx, r.Client, tmpl, status)
}
// writeTemplateStatus writes a template's status when it changed.
func writeTemplateStatus(ctx context.Context, c client.Client, tmpl *cozyv1alpha1.CredentialTemplate, status *cozyv1alpha1.CredentialTemplateStatus) error {
if equality.Semantic.DeepEqual(&tmpl.Status, status) {
return nil
}
updated := tmpl.DeepCopy()
updated.Status = *status
return r.Status().Update(ctx, updated)
return c.Status().Update(ctx, updated)
}
// SetupWithManager registers the reconciler. accountSecrets is a metadata
@@ -0,0 +1,716 @@
// SPDX-License-Identifier: Apache-2.0
package controller
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"time"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/source"
cosiapi "sigs.k8s.io/container-object-storage-interface-api/apis"
cosiv1alpha1 "sigs.k8s.io/container-object-storage-interface-api/apis/objectstorage/v1alpha1"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1"
"github.com/cozystack/cozystack/pkg/credentials/account"
)
// +kubebuilder:rbac:groups=objectstorage.k8s.io,resources=bucketaccesses,verbs=get;list;watch;create;update;delete
// +kubebuilder:rbac:groups=objectstorage.k8s.io,resources=bucketaccessclasses;bucketclaims,verbs=get
const (
// cosiRequeue is how soon the reconciler looks again while the COSI
// sidecar revokes or grants. Both end in a BucketAccess change the
// reconciler watches; the requeue covers the Secret the sidecar writes,
// which it does not.
cosiRequeue = 2 * time.Second
// cosiGrantRequeue is how soon the reconciler looks again at a
// BucketAccess it waits to delete until the sidecar finishes granting it.
// Finishing adds a finalizer, a change the reconciler watches, so this
// only backs the watch up.
cosiGrantRequeue = 30 * time.Second
// bucketAccessFinalizer is what the COSI sidecar puts on a BucketAccess
// once the driver has granted it and the sidecar has written its Secret,
// before it reports AccessGranted; from then on a delete runs the driver
// revoke and removes that Secret (objectstorage-sidecar v0.2.2,
// sidecar/pkg/bucketaccess/bucketaccess_controller.go, Add and
// deleteBucketAccessOp; client/apis/objectstorage/consts BAFinalizer).
bucketAccessFinalizer = "cosi.objectstorage.k8s.io/bucketaccess-protection"
// bucketInfoKey is the one data key of the Secret the COSI sidecar
// writes for a BucketAccess.
bucketInfoKey = "BucketInfo"
// bucketInfoPrefix is how the sidecar names the BucketInfo it writes
// for a BucketAccess, followed by that BucketAccess's UID, which tells a
// Secret of the live grant from one a deleted BucketAccess left behind.
bucketInfoPrefix = "bc-"
// s3Protocol is the protocol the bucket chart has always requested.
s3Protocol = cosiv1alpha1.Protocol("s3")
// templateFinalizer holds a deleted engine-issued template until its
// BucketAccess can be deleted without leaving an identity behind.
templateFinalizer = "credentials.cozystack.io/bucket-access"
)
// COSICredentialReconciler keeps the account of an engine-issued
// CredentialTemplate, whose keys the COSI driver issues: it creates and owns
// the BucketAccess the template names, adopts one the conversion marked, and
// copies the keys of the live grant into the account Secret. A mint or a
// revoke reaches it as a request id the API writes with the Secret. A
// BucketAccess not created for the current mint is deleted, so the sidecar
// revokes its identity, and a new one is created for the mint. A revoke
// deletes it and creates none, so the account holds no keys until the next
// mint, and the Secret is marked served once the BucketAccess is gone. A
// BucketAccess is deleted only once the sidecar has finalized its grant, or
// once the sidecar can no longer grant it: a delete inside the grant window
// skips the driver revoke and leaves the identity behind. That holds for a
// deleted template too, which a finalizer keeps until its BucketAccess is
// deleted that way; the cleanup of a template that was deleted before it got
// the finalizer, and the garbage collection through the owner reference, do
// not check it. A revoke is recorded in the account Secret and mirrored into
// the template's status; an account Secret lost after a revoke is written
// again from that status as revoked, so the account gets no keys until the
// next mint. The template's status mirrors the account Secret as the latest request left it,
// granted or not, so a request that never completes does not block the next
// one. A grant the template's claim or class no longer matches, after a change
// of the user's readonly flag or of the storage pool, is recorded as a revoke
// by the controller: the BucketAccess goes, none replaces it, and the account
// holds no keys until the next mint, which is granted under the new class.
// CredentialTemplateReconciler skips these templates. See
// design-proposals/user-secrets-api in cozystack/community.
//
// Secrets are read through Reader, uncached, for the reason
// CredentialTemplateReconciler gives.
type COSICredentialReconciler struct {
client.Client
Reader client.Reader
Scheme *runtime.Scheme
Recorder record.EventRecorder
Now func() time.Time
}
func (r *COSICredentialReconciler) now() metav1.Time {
if r.Now != nil {
return metav1.NewTime(r.Now())
}
return metav1.Now()
}
// engineIssued reports whether the COSI driver issues a template's keys,
// which a template says by naming a BucketAccess, whatever its format.
func engineIssued(tmpl *cozyv1alpha1.CredentialTemplate) bool {
return tmpl.Spec.BucketAccess != nil
}
func (r *COSICredentialReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
tmpl := &cozyv1alpha1.CredentialTemplate{}
if err := r.Get(ctx, req.NamespacedName, tmpl); err != nil {
if apierrors.IsNotFound(err) {
return ctrl.Result{}, r.cleanup(ctx, req.NamespacedName)
}
return ctrl.Result{}, err
}
if !tmpl.DeletionTimestamp.IsZero() {
return r.finalize(ctx, tmpl)
}
if !engineIssued(tmpl) {
return ctrl.Result{}, nil
}
if !controllerutil.ContainsFinalizer(tmpl, templateFinalizer) {
patch := client.MergeFromWithOptions(tmpl.DeepCopy(), client.MergeFromWithOptimisticLock{})
controllerutil.AddFinalizer(tmpl, templateFinalizer)
if err := r.Patch(ctx, tmpl, patch); err != nil {
return ctrl.Result{}, err
}
}
status := tmpl.Status.DeepCopy()
status.ObservedGeneration = tmpl.Generation
sec, err := r.accountSecret(ctx, tmpl)
if err != nil {
return ctrl.Result{}, err
}
if sec != nil && !metav1.IsControlledBy(sec, tmpl) {
meta.SetStatusCondition(&status.Conditions, metav1.Condition{
Type: cozyv1alpha1.CredentialTemplateSecretConflict,
Status: metav1.ConditionTrue,
Reason: "ForeignSecret",
Message: fmt.Sprintf("Secret %s exists and was not created for this template; remove it to let the account be issued", sec.Name),
})
mirror(status, nil)
return ctrl.Result{}, writeTemplateStatus(ctx, r.Client, tmpl, status)
}
meta.RemoveStatusCondition(&status.Conditions, cozyv1alpha1.CredentialTemplateSecretConflict)
if sec == nil && tmpl.Status.Password.Origin == string(corev1alpha1.CredentialOriginRevoked) {
// The revoke the status mirrors is the account's latest request, and
// its Secret is gone: without it the create branch below would grant
// working keys nobody asked for. A mint writes the Secret, so none
// is pending.
if err := r.restoreRevoked(ctx, tmpl); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{Requeue: true}, nil
}
ba, err := r.bucketAccess(ctx, tmpl)
if err != nil {
return ctrl.Result{}, err
}
request := ""
switch {
case sec != nil:
request = sec.Annotations[account.RequestAnnotation]
case ba != nil && metav1.IsControlledBy(ba, tmpl):
// The account Secret is gone while its grant lives on: the Secret is
// written again from that grant, rather than the BucketAccess being
// re-created under the clients that hold its keys.
request = ba.Annotations[account.RequestAnnotation]
}
revoked := sec != nil && request != "" && account.ReadRecord(sec).Origin == corev1alpha1.CredentialOriginRevoked
// waiting mirrors the account Secret as the latest request left it, so
// the next mint or revoke writes over that version instead of failing on
// the one before a request that has not completed.
waiting := func(after time.Duration) (ctrl.Result, error) {
mirror(status, sec)
return ctrl.Result{RequeueAfter: after}, writeTemplateStatus(ctx, r.Client, tmpl, status)
}
switch {
case ba == nil && revoked:
served, err := r.store(ctx, tmpl, sec, nil, nil, request)
if err != nil {
return ctrl.Result{}, err
}
mirror(status, served)
return ctrl.Result{}, writeTemplateStatus(ctx, r.Client, tmpl, status)
case ba == nil:
if err := r.createBucketAccess(ctx, tmpl, request); err != nil {
return ctrl.Result{}, err
}
return waiting(cosiRequeue)
case !ba.DeletionTimestamp.IsZero():
// The sidecar is revoking it.
return waiting(cosiRequeue)
case !metav1.IsControlledBy(ba, tmpl):
if !bucketAccessAdoptable(ba, tmpl) {
meta.SetStatusCondition(&status.Conditions, metav1.Condition{
Type: cozyv1alpha1.CredentialTemplateBucketAccessConflict,
Status: metav1.ConditionTrue,
Reason: "ForeignBucketAccess",
Message: fmt.Sprintf("BucketAccess %s exists and was not created for this template", ba.Name),
})
mirror(status, sec)
return ctrl.Result{}, writeTemplateStatus(ctx, r.Client, tmpl, status)
}
if ba, err = r.adopt(ctx, tmpl, ba); err != nil {
return ctrl.Result{}, err
}
}
meta.RemoveStatusCondition(&status.Conditions, cozyv1alpha1.CredentialTemplateBucketAccessConflict)
if sec != nil && !revoked && ba.Annotations[account.RequestAnnotation] == request && grantChanged(ba, tmpl) {
revokedSec, err := r.revokeForChange(ctx, tmpl, sec)
if err != nil {
return ctrl.Result{}, err
}
sec = revokedSec
return waiting(cosiRequeue)
}
if revoked || stale(ba, tmpl, request) {
if !controllerutil.ContainsFinalizer(ba, bucketAccessFinalizer) {
// The driver may already have granted an identity the sidecar
// has not finalized yet; deleting now would skip its revoke.
return waiting(cosiGrantRequeue)
}
// Deleting it makes the sidecar revoke the identity behind the keys
// the account held; for a mint, the next pass creates one for the
// request.
if err := r.Delete(ctx, ba, client.Preconditions{UID: &ba.UID}); client.IgnoreNotFound(err) != nil {
return ctrl.Result{}, err
}
return waiting(cosiRequeue)
}
if !ba.Status.AccessGranted {
return waiting(cosiRequeue)
}
keys, err := r.issuedKeys(ctx, ba)
if err != nil {
return ctrl.Result{}, err
}
if keys == nil {
return waiting(cosiRequeue)
}
stored, err := r.store(ctx, tmpl, sec, ba, keys, request)
if err != nil {
return ctrl.Result{}, err
}
if stored == nil {
// A mint created the Secret in between; serve its request next.
return ctrl.Result{Requeue: true}, nil
}
mirror(status, stored)
return ctrl.Result{}, writeTemplateStatus(ctx, r.Client, tmpl, status)
}
func (r *COSICredentialReconciler) accountSecret(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate) (*corev1.Secret, error) {
sec := &corev1.Secret{}
err := r.Reader.Get(ctx, types.NamespacedName{Namespace: tmpl.Namespace, Name: tmpl.Name + account.SecretSuffix}, sec)
if apierrors.IsNotFound(err) {
return nil, nil
}
if err != nil {
return nil, err
}
return sec, nil
}
func (r *COSICredentialReconciler) bucketAccess(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate) (*cosiv1alpha1.BucketAccess, error) {
ba := &cosiv1alpha1.BucketAccess{}
err := r.Get(ctx, types.NamespacedName{Namespace: tmpl.Namespace, Name: tmpl.Spec.BucketAccess.Name}, ba)
if apierrors.IsNotFound(err) {
return nil, nil
}
if err != nil {
return nil, err
}
return ba, nil
}
// createBucketAccess creates the BucketAccess of a template for a request.
// The request annotation is present even when empty, which tells a
// BucketAccess the controller created from one it adopted.
func (r *COSICredentialReconciler) createBucketAccess(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, request string) error {
spec := tmpl.Spec.BucketAccess
ba := &cosiv1alpha1.BucketAccess{
ObjectMeta: metav1.ObjectMeta{
Name: spec.Name,
Namespace: tmpl.Namespace,
Annotations: map[string]string{account.RequestAnnotation: request},
},
Spec: cosiv1alpha1.BucketAccessSpec{
BucketClaimName: spec.BucketClaimName,
BucketAccessClassName: spec.BucketAccessClassName,
CredentialsSecretName: spec.Name,
Protocol: s3Protocol,
},
}
if err := controllerutil.SetControllerReference(tmpl, ba, r.Scheme); err != nil {
return err
}
if err := r.Create(ctx, ba); err != nil && !apierrors.IsAlreadyExists(err) {
return err
}
return nil
}
// bucketAccessAdoptable reports whether a BucketAccess the controller did not
// create is one the conversion marked for this template: the marker, no
// controller, and the template's own claim and class.
func bucketAccessAdoptable(ba *cosiv1alpha1.BucketAccess, tmpl *cozyv1alpha1.CredentialTemplate) bool {
return ba.Labels[account.AdoptLabel] == "true" &&
metav1.GetControllerOf(ba) == nil &&
ba.Spec.BucketClaimName == tmpl.Spec.BucketAccess.BucketClaimName &&
ba.Spec.BucketAccessClassName == tmpl.Spec.BucketAccess.BucketAccessClassName
}
// adopt takes over a BucketAccess the chart rendered before the conversion,
// keeping its grant and so its keys. It carries no request annotation, which
// is how the first copy of its keys is recorded as migrated.
func (r *COSICredentialReconciler) adopt(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, ba *cosiv1alpha1.BucketAccess) (*cosiv1alpha1.BucketAccess, error) {
updated := ba.DeepCopy()
if err := controllerutil.SetControllerReference(tmpl, updated, r.Scheme); err != nil {
return nil, err
}
if err := r.Update(ctx, updated); err != nil {
return nil, err
}
if r.Recorder != nil {
r.Recorder.Event(tmpl, corev1.EventTypeNormal, reasonCredentialAdopted, "adopted the BucketAccess the conversion marked, keeping its keys")
}
return updated, nil
}
// stale reports whether a BucketAccess no longer serves its template: it was
// created for another request than the account Secret's latest, or for
// another claim or class.
func stale(ba *cosiv1alpha1.BucketAccess, tmpl *cozyv1alpha1.CredentialTemplate, request string) bool {
return ba.Annotations[account.RequestAnnotation] != request || grantChanged(ba, tmpl)
}
// grantChanged reports whether a BucketAccess was created for another claim
// or class than the template now names, as after a change of the user's
// readonly flag or of the bucket's storage pool.
func grantChanged(ba *cosiv1alpha1.BucketAccess, tmpl *cozyv1alpha1.CredentialTemplate) bool {
return ba.Spec.BucketClaimName != tmpl.Spec.BucketAccess.BucketClaimName ||
ba.Spec.BucketAccessClassName != tmpl.Spec.BucketAccess.BucketAccessClassName
}
// revokeForChange records a grant the template no longer matches as a revoke
// by the controller and returns the Secret as written. The account Secret
// loses its keys and gets a request id of its own, as a revoke through the API
// writes it, so the revoke path deletes the BucketAccess and creates none:
// the new class takes effect with the next mint, whose keys are the first
// anyone is shown. Re-granting at once instead would leave keys nobody was
// shown behind a record that says the last mint issued the live ones. A
// request the Secret already carries is served first: a pending mint creates
// its BucketAccess with the new class anyway.
func (r *COSICredentialReconciler) revokeForChange(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, sec *corev1.Secret) (*corev1.Secret, error) {
id, err := requestID()
if err != nil {
return nil, err
}
updated := sec.DeepCopy()
updated.Data = map[string][]byte{account.UsernameKey: []byte(tmpl.Spec.Username)}
if updated.Annotations == nil {
updated.Annotations = map[string]string{}
}
updated.Annotations[account.RequestAnnotation] = id
account.WriteRecord(updated, account.ReadRecord(sec).Apply(corev1alpha1.CredentialOperationRevoke, r.now(), CredentialControllerActor))
// Written under the version read at the start of this pass: a mint in
// between fails it, and the next pass serves that mint instead.
if err := r.Update(ctx, updated); err != nil {
return nil, err
}
if r.Recorder != nil {
r.Recorder.Event(tmpl, corev1.EventTypeNormal, reasonCredentialRevoked,
"the bucket access class or claim changed: revoked the keys of the old grant; mint to get keys under the new one")
}
return updated, nil
}
func requestID() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
// s3Keys is one issued key pair.
type s3Keys struct {
accessKeyID string
secretKey string
}
// issuedKeys reads the keys of a granted BucketAccess from the Secret the
// sidecar wrote for it; nil while that Secret is missing, or is one an
// earlier BucketAccess of the same name left behind.
func (r *COSICredentialReconciler) issuedKeys(ctx context.Context, ba *cosiv1alpha1.BucketAccess) (*s3Keys, error) {
src := &corev1.Secret{}
err := r.Reader.Get(ctx, types.NamespacedName{Namespace: ba.Namespace, Name: ba.Spec.CredentialsSecretName}, src)
if apierrors.IsNotFound(err) {
return nil, nil
}
if err != nil {
return nil, err
}
info := cosiapi.BucketInfo{}
if err := json.Unmarshal(src.Data[bucketInfoKey], &info); err != nil {
return nil, fmt.Errorf("secret %s/%s: decode %s: %w", src.Namespace, src.Name, bucketInfoKey, err)
}
if info.Name != bucketInfoPrefix+string(ba.UID) || info.Spec.S3 == nil ||
info.Spec.S3.AccessKeyID == "" || info.Spec.S3.AccessSecretKey == "" {
return nil, nil
}
return &s3Keys{accessKeyID: info.Spec.S3.AccessKeyID, secretKey: info.Spec.S3.AccessSecretKey}, nil
}
// store writes the keys into the account Secret, marked as served for the
// request, and returns the Secret as written; nil when a mint created it in
// between. Without keys, for a revoke whose BucketAccess is gone, the Secret
// keeps the user name only. A new Secret records a Create, or a Migrate when
// the keys belong to an adopted BucketAccess, and carries the request of the
// BucketAccess it was written from; an existing one keeps the record the mint
// or revoke wrote.
func (r *COSICredentialReconciler) store(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, sec *corev1.Secret, ba *cosiv1alpha1.BucketAccess, keys *s3Keys, request string) (*corev1.Secret, error) {
data := map[string][]byte{account.UsernameKey: []byte(tmpl.Spec.Username)}
if keys != nil {
data[account.PasswordKey] = []byte(keys.secretKey)
data[account.AccessKeyIDKey] = []byte(keys.accessKeyID)
}
labels := account.Labels(tmpl.Spec.Secret.Labels)
if sec == nil {
op := corev1alpha1.CredentialOperationCreate
if _, created := ba.Annotations[account.RequestAnnotation]; !created {
op = corev1alpha1.CredentialOperationMigrate
}
sec = &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: tmpl.Name + account.SecretSuffix,
Namespace: tmpl.Namespace,
Labels: labels,
Annotations: map[string]string{
account.FormatAnnotation: tmpl.Spec.Format.Name,
account.BucketAccessAnnotation: tmpl.Spec.BucketAccess.Name,
account.GrantedAnnotation: request,
},
},
Type: corev1.SecretTypeBasicAuth,
Data: data,
}
if request != "" {
sec.Annotations[account.RequestAnnotation] = request
}
account.WriteRecord(sec, account.Record{}.Apply(op, r.now(), CredentialControllerActor))
if err := controllerutil.SetControllerReference(tmpl, sec, r.Scheme); err != nil {
return nil, err
}
if err := r.Create(ctx, sec); err != nil {
if apierrors.IsAlreadyExists(err) {
return nil, nil
}
return nil, err
}
return sec, nil
}
if sec.Annotations[account.GrantedAnnotation] == request && sec.Annotations[account.FormatAnnotation] == tmpl.Spec.Format.Name &&
sec.Annotations[account.BucketAccessAnnotation] == tmpl.Spec.BucketAccess.Name &&
equalData(sec.Data, data) && equalStrings(sec.Labels, labels) {
return sec, nil
}
updated := sec.DeepCopy()
updated.Data = data
updated.Labels = labels
if updated.Annotations == nil {
updated.Annotations = map[string]string{}
}
updated.Annotations[account.FormatAnnotation] = tmpl.Spec.Format.Name
updated.Annotations[account.BucketAccessAnnotation] = tmpl.Spec.BucketAccess.Name
updated.Annotations[account.GrantedAnnotation] = request
// Written under the version read at the start of this pass: a mint in
// between fails it, and the next pass serves that mint's request.
if err := r.Update(ctx, updated); err != nil {
return nil, err
}
return updated, nil
}
func equalData(a, b map[string][]byte) bool {
if len(a) != len(b) {
return false
}
for k, v := range a {
if w, ok := b[k]; !ok || string(v) != string(w) {
return false
}
}
return true
}
func equalStrings(a, b map[string]string) bool {
if len(a) != len(b) {
return false
}
for k, v := range a {
if w, ok := b[k]; !ok || v != w {
return false
}
}
return true
}
// restoreRevoked writes the account Secret of a revoked account again, from
// the record the template's status mirrors, without keys and with a request
// id of its own, as a revoke writes it. The revoke path then serves it:
// a BucketAccess still there is deleted once the sidecar has finalized it,
// and none is created, so the account holds no keys until the next mint.
func (r *COSICredentialReconciler) restoreRevoked(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate) error {
id, err := requestID()
if err != nil {
return err
}
sec := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: tmpl.Name + account.SecretSuffix,
Namespace: tmpl.Namespace,
Labels: account.Labels(tmpl.Spec.Secret.Labels),
Annotations: map[string]string{
account.FormatAnnotation: tmpl.Spec.Format.Name,
account.BucketAccessAnnotation: tmpl.Spec.BucketAccess.Name,
account.RequestAnnotation: id,
},
},
Type: corev1.SecretTypeBasicAuth,
Data: map[string][]byte{account.UsernameKey: []byte(tmpl.Spec.Username)},
}
account.WriteRecord(sec, statusRecord(&tmpl.Status))
if err := controllerutil.SetControllerReference(tmpl, sec, r.Scheme); err != nil {
return err
}
if err := r.Create(ctx, sec); err != nil {
// A mint created it in between; the next pass serves that.
if apierrors.IsAlreadyExists(err) {
return nil
}
return err
}
if r.Recorder != nil {
r.Recorder.Event(tmpl, corev1.EventTypeWarning, reasonCredentialRevoked,
"the account Secret of a revoked account was missing; wrote it again as revoked, mint to get keys")
}
return nil
}
// statusRecord returns the record a template's status mirrors.
func statusRecord(st *cozyv1alpha1.CredentialTemplateStatus) account.Record {
rec := account.Record{Origin: corev1alpha1.CredentialOrigin(st.Password.Origin), By: st.Password.By}
if st.Password.At != nil {
rec.At = *st.Password.At
}
for _, h := range st.History {
rec.History = append(rec.History, corev1alpha1.CredentialHistoryEntry{Operation: corev1alpha1.CredentialOperation(h.Operation), At: h.At, By: h.By})
}
return rec
}
// finalize releases a deleted template once no BucketAccess it owns can be
// left in the grant window: each is deleted once the sidecar has finalized
// it, or once the sidecar can no longer grant it. A template deleted before
// any grant owns none and is released at once. The account Secret goes with
// it.
func (r *COSICredentialReconciler) finalize(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate) (ctrl.Result, error) {
if !controllerutil.ContainsFinalizer(tmpl, templateFinalizer) {
return ctrl.Result{}, nil
}
accesses := &cosiv1alpha1.BucketAccessList{}
if err := r.List(ctx, accesses, client.InNamespace(tmpl.Namespace)); err != nil {
return ctrl.Result{}, err
}
granting := false
for i := range accesses.Items {
ba := &accesses.Items[i]
if !metav1.IsControlledBy(ba, tmpl) || !ba.DeletionTimestamp.IsZero() {
continue
}
if !controllerutil.ContainsFinalizer(ba, bucketAccessFinalizer) {
can, err := r.canGrant(ctx, ba)
if err != nil {
return ctrl.Result{}, err
}
if can {
granting = true
continue
}
}
if err := r.Delete(ctx, ba, client.Preconditions{UID: &ba.UID}); client.IgnoreNotFound(err) != nil {
return ctrl.Result{}, err
}
}
if granting {
return ctrl.Result{RequeueAfter: cosiGrantRequeue}, nil
}
if err := r.deleteAccountSecret(ctx, client.ObjectKeyFromObject(tmpl)); err != nil {
return ctrl.Result{}, err
}
patch := client.MergeFromWithOptions(tmpl.DeepCopy(), client.MergeFromWithOptimisticLock{})
controllerutil.RemoveFinalizer(tmpl, templateFinalizer)
return ctrl.Result{}, client.IgnoreNotFound(r.Patch(ctx, tmpl, patch))
}
// canGrant reports whether the sidecar may still have the driver grant a
// BucketAccess it has not finalized. It fetches the class and the claim and
// needs the claim's bucket ready before it calls the driver
// (objectstorage-sidecar, sidecar/pkg/bucketaccess/bucketaccess_controller.go
// Add), so without them it cannot grant, and a delete leaves nothing behind.
func (r *COSICredentialReconciler) canGrant(ctx context.Context, ba *cosiv1alpha1.BucketAccess) (bool, error) {
class := &cosiv1alpha1.BucketAccessClass{}
if err := r.Reader.Get(ctx, types.NamespacedName{Name: ba.Spec.BucketAccessClassName}, class); err != nil {
if apierrors.IsNotFound(err) {
return false, nil
}
return false, err
}
claim := &cosiv1alpha1.BucketClaim{}
if err := r.Reader.Get(ctx, types.NamespacedName{Namespace: ba.Namespace, Name: ba.Spec.BucketClaimName}, claim); err != nil {
if apierrors.IsNotFound(err) {
return false, nil
}
return false, err
}
return claim.Status.BucketReady && claim.Status.BucketName != "", nil
}
// cleanup removes what an engine-issued template deleted without the
// finalizer owned, as one deleted before this controller first reconciled it:
// its BucketAccess, whose deletion makes the sidecar revoke the identity, and
// its account Secret. The garbage collector would remove both through their
// owner reference; doing it here revokes the keys without waiting for it. It
// deletes a BucketAccess the sidecar has not finalized as well, since the
// garbage collector would.
func (r *COSICredentialReconciler) cleanup(ctx context.Context, nn types.NamespacedName) error {
accesses := &cosiv1alpha1.BucketAccessList{}
if err := r.List(ctx, accesses, client.InNamespace(nn.Namespace)); err != nil {
return err
}
for i := range accesses.Items {
ba := &accesses.Items[i]
if ownedByTemplate(ba, nn.Name) && ba.DeletionTimestamp.IsZero() {
if err := r.Delete(ctx, ba); client.IgnoreNotFound(err) != nil {
return err
}
}
}
return r.deleteAccountSecret(ctx, nn)
}
// deleteAccountSecret deletes the engine-issued account Secret of a template.
func (r *COSICredentialReconciler) deleteAccountSecret(ctx context.Context, nn types.NamespacedName) error {
sec := &corev1.Secret{}
err := r.Reader.Get(ctx, types.NamespacedName{Namespace: nn.Namespace, Name: nn.Name + account.SecretSuffix}, sec)
if apierrors.IsNotFound(err) {
return nil
}
if err != nil {
return err
}
if !ownedByTemplate(sec, nn.Name) || !account.IsEngineIssued(sec) {
return nil
}
return client.IgnoreNotFound(r.Delete(ctx, sec))
}
func ownedByTemplate(o metav1.Object, name string) bool {
ref := metav1.GetControllerOf(o)
return ref != nil && ref.Kind == "CredentialTemplate" && ref.APIVersion == cozyv1alpha1.GroupVersion.String() && ref.Name == name
}
// SetupWithManager registers the reconciler. accountSecrets is the same
// metadata cache of Secrets CredentialTemplateReconciler watches; only
// engine-issued account Secrets reach this reconciler.
func (r *COSICredentialReconciler) SetupWithManager(mgr ctrl.Manager, accountSecrets cache.Cache) error {
cosiTemplate := predicate.NewPredicateFuncs(func(o client.Object) bool {
tmpl, ok := o.(*cozyv1alpha1.CredentialTemplate)
return ok && (engineIssued(tmpl) || controllerutil.ContainsFinalizer(tmpl, templateFinalizer))
})
secretMeta := &metav1.PartialObjectMetadata{}
secretMeta.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("Secret"))
isCOSIAccount := predicate.NewTypedPredicateFuncs(func(o *metav1.PartialObjectMetadata) bool {
return o.GetLabels()[account.AccountLabel] == "true" && o.GetAnnotations()[account.BucketAccessAnnotation] != ""
})
owner := handler.TypedEnqueueRequestForOwner[*metav1.PartialObjectMetadata](
mgr.GetScheme(), mgr.GetRESTMapper(), &cozyv1alpha1.CredentialTemplate{}, handler.OnlyControllerOwner())
return ctrl.NewControllerManagedBy(mgr).
Named("credentialtemplate-cosi").
For(&cozyv1alpha1.CredentialTemplate{}, builder.WithPredicates(predicate.GenerationChangedPredicate{}, cosiTemplate)).
Owns(&cosiv1alpha1.BucketAccess{}).
WatchesRawSource(source.Kind(accountSecrets, secretMeta, owner, isCOSIAccount)).
Complete(r)
}
@@ -0,0 +1,868 @@
// SPDX-License-Identifier: Apache-2.0
package controller
import (
"context"
"encoding/json"
"testing"
"time"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
cosiapi "sigs.k8s.io/container-object-storage-interface-api/apis"
cosiv1alpha1 "sigs.k8s.io/container-object-storage-interface-api/apis/objectstorage/v1alpha1"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1"
"github.com/cozystack/cozystack/pkg/credentials/account"
"github.com/cozystack/cozystack/pkg/credentials/format"
)
const (
cosiRelease = "bucket-photos"
cosiName = cosiRelease + ".web"
cosiAccess = cosiRelease + "-web"
cosiClass = "seaweedfs"
)
type cosiFixture struct {
c client.Client
r *COSICredentialReconciler
recorder *record.FakeRecorder
uids int
}
func newCOSIFixture(t *testing.T, objs ...client.Object) *cosiFixture {
t.Helper()
scheme := runtime.NewScheme()
for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, cozyv1alpha1.AddToScheme, cosiv1alpha1.AddToScheme} {
if err := add(scheme); err != nil {
t.Fatal(err)
}
}
c := fake.NewClientBuilder().WithScheme(scheme).
WithObjects(objs...).
WithStatusSubresource(&cozyv1alpha1.CredentialTemplate{}, &cosiv1alpha1.BucketAccess{}).
Build()
rec := record.NewFakeRecorder(10)
return &cosiFixture{
c: c,
recorder: rec,
r: &COSICredentialReconciler{
Client: c, Reader: c, Scheme: scheme, Recorder: rec,
Now: func() time.Time { return time.Date(2026, 11, 21, 9, 0, 0, 0, time.UTC) },
},
}
}
func cosiTemplate() *cozyv1alpha1.CredentialTemplate {
return &cozyv1alpha1.CredentialTemplate{
ObjectMeta: metav1.ObjectMeta{
Name: cosiName, Namespace: ctNamespace, UID: "cosi-tmpl-uid",
Annotations: map[string]string{account.ReleaseNameAnnotation: cosiRelease},
},
Spec: cozyv1alpha1.CredentialTemplateSpec{
Username: "web",
Format: cozyv1alpha1.CredentialTemplateFormat{Name: format.Plaintext},
BucketAccess: &cozyv1alpha1.CredentialTemplateBucketAccess{
Name: cosiAccess, BucketClaimName: cosiRelease, BucketAccessClassName: cosiClass,
},
},
}
}
func (f *cosiFixture) reconcile(t *testing.T) reconcile.Result {
t.Helper()
res, err := f.r.Reconcile(context.Background(), reconcile.Request{NamespacedName: types.NamespacedName{Namespace: ctNamespace, Name: cosiName}})
if err != nil {
t.Fatalf("reconcile: %v", err)
}
return res
}
func (f *cosiFixture) bucketAccess(t *testing.T) *cosiv1alpha1.BucketAccess {
t.Helper()
ba := &cosiv1alpha1.BucketAccess{}
err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: cosiAccess}, ba)
if apierrors.IsNotFound(err) {
return nil
}
if err != nil {
t.Fatal(err)
}
return ba
}
func (f *cosiFixture) account(t *testing.T) *corev1.Secret {
t.Helper()
sec := &corev1.Secret{}
err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: cosiName + account.SecretSuffix}, sec)
if apierrors.IsNotFound(err) {
return nil
}
if err != nil {
t.Fatal(err)
}
return sec
}
// grant does what the COSI sidecar does for a BucketAccess: it writes the
// Secret holding the BucketInfo of the grant, puts its finalizer on the
// BucketAccess and reports access granted. The fake client assigns no UID, so
// grant gives the BucketAccess one.
func (f *cosiFixture) grant(t *testing.T, accessKey, secretKey string) {
t.Helper()
f.grantUnfinalized(t, accessKey, secretKey)
ctx := context.Background()
ba := f.bucketAccess(t)
ba.Finalizers = append(ba.Finalizers, bucketAccessFinalizer)
if err := f.c.Update(ctx, ba); err != nil {
t.Fatal(err)
}
ba.Status.AccessGranted = true
ba.Status.AccountID = "ba-" + string(ba.UID)
if err := f.c.Status().Update(ctx, ba); err != nil {
t.Fatal(err)
}
}
// grantUnfinalized stops the sidecar's grant where the driver has issued the
// keys and their Secret is written, before the finalizer goes on.
func (f *cosiFixture) grantUnfinalized(t *testing.T, accessKey, secretKey string) {
t.Helper()
ctx := context.Background()
ba := f.bucketAccess(t)
if ba == nil {
t.Fatal("no BucketAccess to grant")
}
if ba.UID == "" {
f.uids++
ba.UID = types.UID("ba-uid-" + string(rune('a'+f.uids)))
if err := f.c.Update(ctx, ba); err != nil {
t.Fatal(err)
}
}
info, _ := json.Marshal(cosiapi.BucketInfo{
ObjectMeta: metav1.ObjectMeta{Name: bucketInfoPrefix + string(ba.UID)},
Spec: cosiapi.BucketInfoSpec{
BucketName: "bucket-claim-uid",
S3: &cosiapi.SecretS3{Endpoint: "https://s3.example.org", AccessKeyID: accessKey, AccessSecretKey: secretKey},
},
})
src := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: ba.Spec.CredentialsSecretName, Namespace: ctNamespace}, Data: map[string][]byte{bucketInfoKey: info}}
_ = f.c.Delete(ctx, src)
if err := f.c.Create(ctx, src); err != nil {
t.Fatal(err)
}
}
// finalize does what the COSI sidecar does once a BucketAccess is being
// deleted: the driver revokes the identity, and the sidecar removes the
// Secret it wrote and its finalizer, which lets the deletion complete.
func (f *cosiFixture) finalize(t *testing.T) {
t.Helper()
ctx := context.Background()
ba := f.bucketAccess(t)
if ba == nil || ba.DeletionTimestamp.IsZero() {
t.Fatalf("BucketAccess = %+v, want one being deleted", ba)
}
_ = f.c.Delete(ctx, &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: ba.Spec.CredentialsSecretName, Namespace: ctNamespace}})
ba.Finalizers = nil
if err := f.c.Update(ctx, ba); err != nil {
t.Fatal(err)
}
if f.bucketAccess(t) != nil {
t.Fatal("the BucketAccess outlived its finalizer")
}
}
func (f *cosiFixture) template(t *testing.T) *cozyv1alpha1.CredentialTemplate {
t.Helper()
tmpl := &cozyv1alpha1.CredentialTemplate{}
if err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: cosiName}, tmpl); err != nil {
t.Fatal(err)
}
return tmpl
}
// request writes the account Secret the way a mint or a revoke does: rebuilt
// without keys, carrying a request id and the operation in its record.
func (f *cosiFixture) createRequest(t *testing.T, id string, op corev1alpha1.CredentialOperation) {
t.Helper()
controller := true
sec := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: cosiName + account.SecretSuffix, Namespace: ctNamespace,
Labels: account.Labels(nil),
Annotations: map[string]string{account.FormatAnnotation: format.Plaintext, account.BucketAccessAnnotation: cosiAccess, account.RequestAnnotation: id},
OwnerReferences: []metav1.OwnerReference{{
APIVersion: cozyv1alpha1.GroupVersion.String(), Kind: "CredentialTemplate",
Name: cosiName, UID: "cosi-tmpl-uid", Controller: &controller,
}},
},
Data: map[string][]byte{account.UsernameKey: []byte("web")},
}
account.WriteRecord(sec, account.Record{}.Apply(op, metav1.NewTime(time.Date(2026, 11, 21, 10, 0, 0, 0, time.UTC)), "jane@example.org"))
if err := f.c.Create(context.Background(), sec); err != nil {
t.Fatal(err)
}
}
func (f *cosiFixture) request(t *testing.T, id string, op corev1alpha1.CredentialOperation) {
t.Helper()
sec := f.account(t)
rec := account.ReadRecord(sec).Apply(op, metav1.NewTime(time.Date(2026, 11, 21, 10, 0, 0, 0, time.UTC)), "jane@example.org")
updated := sec.DeepCopy()
updated.Data = map[string][]byte{account.UsernameKey: []byte("web")}
updated.Annotations = map[string]string{account.FormatAnnotation: format.Plaintext, account.BucketAccessAnnotation: cosiAccess, account.RequestAnnotation: id}
account.WriteRecord(updated, rec)
if err := f.c.Update(context.Background(), updated); err != nil {
t.Fatal(err)
}
}
func TestCOSICreatesTheBucketAccessOfATemplate(t *testing.T) {
f := newCOSIFixture(t, cosiTemplate())
if res := f.reconcile(t); res.RequeueAfter == 0 {
t.Error("expected a requeue while the grant is pending")
}
ba := f.bucketAccess(t)
if ba == nil {
t.Fatal("no BucketAccess was created")
}
if ba.Spec.BucketClaimName != cosiRelease || ba.Spec.BucketAccessClassName != cosiClass || ba.Spec.CredentialsSecretName != cosiAccess || ba.Spec.Protocol != "s3" {
t.Errorf("spec = %+v", ba.Spec)
}
if ref := metav1.GetControllerOf(ba); ref == nil || ref.Name != cosiName || ref.Kind != "CredentialTemplate" {
t.Errorf("controller = %v, want the template", ref)
}
if v, ok := ba.Annotations[account.RequestAnnotation]; !ok || v != "" {
t.Errorf("request annotation = %q, %v; want present and empty", v, ok)
}
if f.account(t) != nil {
t.Error("an account Secret exists before the grant")
}
}
func TestCOSICopiesTheIssuedKeysIntoTheAccountSecret(t *testing.T) {
f := newCOSIFixture(t, cosiTemplate())
f.reconcile(t)
f.grant(t, "AKIAFIRST", "first-secret")
f.reconcile(t)
sec := f.account(t)
if sec == nil {
t.Fatal("no account Secret")
}
if string(sec.Data[account.UsernameKey]) != "web" || string(sec.Data[account.PasswordKey]) != "first-secret" || string(sec.Data[account.AccessKeyIDKey]) != "AKIAFIRST" {
t.Errorf("data = %v", sec.Data)
}
if sec.Labels[account.AccountLabel] != "true" || sec.Annotations[account.FormatAnnotation] != format.Plaintext || sec.Annotations[account.BucketAccessAnnotation] != cosiAccess {
t.Errorf("labels = %v, annotations = %v", sec.Labels, sec.Annotations)
}
if ref := metav1.GetControllerOf(sec); ref == nil || ref.Name != cosiName {
t.Errorf("controller = %v, want the template", ref)
}
if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginNotIssued || len(rec.History) != 1 || rec.History[0].Operation != corev1alpha1.CredentialOperationCreate {
t.Errorf("record = %+v, want one Create", rec)
}
tmpl := &cozyv1alpha1.CredentialTemplate{}
if err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: cosiName}, tmpl); err != nil {
t.Fatal(err)
}
if tmpl.Status.SecretResourceVersion != sec.ResourceVersion {
t.Errorf("status mirrors %q, Secret is at %q", tmpl.Status.SecretResourceVersion, sec.ResourceVersion)
}
}
func TestCOSIMintReCreatesTheBucketAccessAndStoresTheNewKeysForItsRequest(t *testing.T) {
f := newCOSIFixture(t, cosiTemplate())
f.reconcile(t)
f.grant(t, "AKIAFIRST", "first-secret")
f.reconcile(t)
firstUID := f.bucketAccess(t).UID
f.request(t, "req-1", corev1alpha1.CredentialOperationMint)
f.reconcile(t)
if ba := f.bucketAccess(t); ba == nil || ba.DeletionTimestamp.IsZero() {
t.Fatalf("BucketAccess = %+v, want the one of the old keys deleted", ba)
}
f.finalize(t)
f.reconcile(t)
ba := f.bucketAccess(t)
if ba == nil || ba.Annotations[account.RequestAnnotation] != "req-1" {
t.Fatalf("BucketAccess = %+v, want one created for req-1", ba)
}
if sec := f.account(t); sec.Annotations[account.GrantedAnnotation] == "req-1" {
t.Error("the Secret is marked issued before the new grant")
}
f.grant(t, "AKIASECOND", "second-secret")
if f.bucketAccess(t).UID == firstUID {
t.Fatal("the test grant reused the old UID")
}
f.reconcile(t)
sec := f.account(t)
if string(sec.Data[account.PasswordKey]) != "second-secret" || string(sec.Data[account.AccessKeyIDKey]) != "AKIASECOND" {
t.Errorf("data = %v, want the keys of the new grant", sec.Data)
}
if sec.Annotations[account.GrantedAnnotation] != "req-1" {
t.Errorf("granted = %q, want req-1", sec.Annotations[account.GrantedAnnotation])
}
if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginMinted || rec.By != "jane@example.org" {
t.Errorf("record = %+v, want the mint's", rec)
}
// A later pass leaves a served request alone.
f.reconcile(t)
if f.bucketAccess(t).Annotations[account.RequestAnnotation] != "req-1" {
t.Error("a served request was re-granted")
}
}
// A revoke locks the account out: the BucketAccess goes, none replaces it,
// and the Secret is served without keys until the next mint.
func TestCOSIRevokeDeletesTheBucketAccessAndIssuesNoKeys(t *testing.T) {
f := newCOSIFixture(t, cosiTemplate())
f.reconcile(t)
f.grant(t, "AKIAFIRST", "first-secret")
f.reconcile(t)
f.request(t, "req-r", corev1alpha1.CredentialOperationRevoke)
f.reconcile(t)
if sec := f.account(t); sec.Annotations[account.GrantedAnnotation] == "req-r" {
t.Error("the revoke is marked served while its BucketAccess lives")
}
f.finalize(t)
f.reconcile(t)
f.reconcile(t)
if ba := f.bucketAccess(t); ba != nil {
t.Fatalf("a revoke created BucketAccess %+v", ba)
}
sec := f.account(t)
if _, ok := sec.Data[account.PasswordKey]; ok || len(sec.Data[account.AccessKeyIDKey]) > 0 || string(sec.Data[account.UsernameKey]) != "web" {
t.Errorf("data = %v, want the user name only", sec.Data)
}
if sec.Annotations[account.GrantedAnnotation] != "req-r" {
t.Errorf("granted = %q, want req-r", sec.Annotations[account.GrantedAnnotation])
}
tmpl := f.template(t)
if tmpl.Status.Password.Origin != string(corev1alpha1.CredentialOriginRevoked) || tmpl.Status.SecretResourceVersion != sec.ResourceVersion {
t.Errorf("status = %+v, want Revoked at %s", tmpl.Status, sec.ResourceVersion)
}
// The next mint issues keys again.
f.request(t, "req-2", corev1alpha1.CredentialOperationMint)
f.reconcile(t)
if ba := f.bucketAccess(t); ba == nil || ba.Annotations[account.RequestAnnotation] != "req-2" {
t.Fatalf("BucketAccess = %+v, want one created for req-2", ba)
}
f.grant(t, "AKIATHIRD", "third-secret")
f.reconcile(t)
if sec := f.account(t); string(sec.Data[account.PasswordKey]) != "third-secret" || sec.Annotations[account.GrantedAnnotation] != "req-2" {
t.Errorf("data = %v, annotations = %v", sec.Data, sec.Annotations)
}
}
// The sidecar has the driver grant an identity before it puts its finalizer
// on the BucketAccess; a delete in between skips the driver revoke and leaves
// that identity behind, so the reconciler waits for the finalizer.
func TestCOSIWaitsForTheSidecarToFinalizeBeforeDeleting(t *testing.T) {
f := newCOSIFixture(t, cosiTemplate())
f.reconcile(t)
f.grantUnfinalized(t, "AKIAFIRST", "first-secret")
f.reconcile(t)
// A mint on an account that has no Secret yet creates it.
f.createRequest(t, "req-1", corev1alpha1.CredentialOperationMint)
if res := f.reconcile(t); res.RequeueAfter != cosiGrantRequeue {
t.Errorf("requeue = %v, want %v", res.RequeueAfter, cosiGrantRequeue)
}
if ba := f.bucketAccess(t); ba == nil || !ba.DeletionTimestamp.IsZero() {
t.Fatalf("BucketAccess = %+v, want it kept until the sidecar finalizes it", ba)
}
f.grant(t, "AKIAFIRST", "first-secret")
f.reconcile(t)
if ba := f.bucketAccess(t); ba == nil || ba.DeletionTimestamp.IsZero() {
t.Fatalf("BucketAccess = %+v, want it deleted once finalized", ba)
}
}
// The template's status follows the account Secret while a request waits,
// so a request that never completes leaves the next one a version to write
// over rather than a conflict on every attempt.
func TestCOSIStatusMirrorsAPendingRequest(t *testing.T) {
f := newCOSIFixture(t, cosiTemplate())
f.reconcile(t)
f.grant(t, "AKIAFIRST", "first-secret")
f.reconcile(t)
f.request(t, "req-1", corev1alpha1.CredentialOperationMint)
f.reconcile(t)
sec := f.account(t)
tmpl := f.template(t)
if tmpl.Status.SecretResourceVersion != sec.ResourceVersion || tmpl.Status.Password.Origin != string(corev1alpha1.CredentialOriginMinted) {
t.Fatalf("status = %+v, want the pending mint at %s", tmpl.Status, sec.ResourceVersion)
}
// A retry supersedes it, and the reconciler serves the retry.
f.request(t, "req-2", corev1alpha1.CredentialOperationMint)
f.finalize(t)
f.reconcile(t)
if ba := f.bucketAccess(t); ba == nil || ba.Annotations[account.RequestAnnotation] != "req-2" {
t.Fatalf("BucketAccess = %+v, want one created for req-2", ba)
}
}
// changeClass points the template at another class, as the chart renders it
// when a user's readonly flag or the bucket's storage pool changes.
func (f *cosiFixture) changeClass(t *testing.T, class string) {
t.Helper()
tmpl := f.template(t)
tmpl.Spec.BucketAccess.BucketAccessClassName = class
if err := f.c.Update(context.Background(), tmpl); err != nil {
t.Fatal(err)
}
}
// A class change re-grants the account, and nobody is shown the keys of that
// grant, so it is recorded as a revoke by the controller: the old grant goes,
// none replaces it, and the next mint is granted under the new class.
func TestCOSIClassChangeIsRecordedAsARevokeByTheController(t *testing.T) {
f := newCOSIFixture(t, cosiTemplate())
f.reconcile(t)
f.grant(t, "AKIAFIRST", "first-secret")
f.reconcile(t)
f.request(t, "req-1", corev1alpha1.CredentialOperationMint)
f.reconcile(t)
f.finalize(t)
f.reconcile(t)
f.grant(t, "AKIASECOND", "second-secret")
f.reconcile(t)
if rec := account.ReadRecord(f.account(t)); rec.Origin != corev1alpha1.CredentialOriginMinted {
t.Fatalf("record = %+v, want the mint before the change", rec)
}
f.changeClass(t, "seaweedfs-readonly")
f.reconcile(t)
sec := f.account(t)
if _, ok := sec.Data[account.PasswordKey]; ok || len(sec.Data[account.AccessKeyIDKey]) > 0 {
t.Errorf("data = %v, want the keys of the old grant gone", sec.Data)
}
id := sec.Annotations[account.RequestAnnotation]
if id == "" || id == "req-1" {
t.Errorf("request = %q, want a new one of the controller's", id)
}
rec := account.ReadRecord(sec)
if rec.Origin != corev1alpha1.CredentialOriginRevoked || rec.By != CredentialControllerActor ||
len(rec.History) < 2 || rec.History[0].Operation != corev1alpha1.CredentialOperationRevoke || rec.History[0].By != CredentialControllerActor ||
rec.History[1].Operation != corev1alpha1.CredentialOperationMint {
t.Errorf("record = %+v, want a revoke by the controller on top of the mint", rec)
}
if tmpl := f.template(t); tmpl.Status.Password.Origin != string(corev1alpha1.CredentialOriginRevoked) || tmpl.Status.Password.By != CredentialControllerActor {
t.Errorf("status = %+v, want Revoked by the controller", tmpl.Status.Password)
}
select {
case ev := <-f.recorder.Events:
if ev == "" {
t.Error("empty event")
}
default:
t.Error("no event for the revoke")
}
// The revoke path takes it from here: the old grant goes, none replaces it.
f.reconcile(t)
if ba := f.bucketAccess(t); ba == nil || ba.DeletionTimestamp.IsZero() {
t.Fatalf("BucketAccess = %+v, want the old grant deleted", ba)
}
f.finalize(t)
f.reconcile(t)
f.reconcile(t)
if ba := f.bucketAccess(t); ba != nil {
t.Fatalf("a class change created BucketAccess %+v before any mint", ba)
}
if sec := f.account(t); sec.Annotations[account.GrantedAnnotation] != id {
t.Errorf("granted = %q, want %q", sec.Annotations[account.GrantedAnnotation], id)
}
if rec := account.ReadRecord(f.account(t)); len(rec.History) != 3 {
t.Errorf("history = %+v, want one revoke recorded once", rec.History)
}
// The next mint is granted under the new class.
f.request(t, "req-2", corev1alpha1.CredentialOperationMint)
f.reconcile(t)
ba := f.bucketAccess(t)
if ba == nil || ba.Annotations[account.RequestAnnotation] != "req-2" || ba.Spec.BucketAccessClassName != "seaweedfs-readonly" {
t.Fatalf("BucketAccess = %+v, want one for req-2 under the new class", ba)
}
}
// A mint the Secret already carries is served under the new class and keeps
// its record: its caller is the one shown the keys.
func TestCOSIClassChangeDuringAMintServesTheMint(t *testing.T) {
f := newCOSIFixture(t, cosiTemplate())
f.reconcile(t)
f.grant(t, "AKIAFIRST", "first-secret")
f.reconcile(t)
f.request(t, "req-1", corev1alpha1.CredentialOperationMint)
f.changeClass(t, "seaweedfs-readonly")
f.reconcile(t)
if sec := f.account(t); sec.Annotations[account.RequestAnnotation] != "req-1" {
t.Fatalf("request = %q, want the mint's req-1 kept", sec.Annotations[account.RequestAnnotation])
}
f.finalize(t)
f.reconcile(t)
ba := f.bucketAccess(t)
if ba == nil || ba.Annotations[account.RequestAnnotation] != "req-1" || ba.Spec.BucketAccessClassName != "seaweedfs-readonly" {
t.Fatalf("BucketAccess = %+v, want one for req-1 under the new class", ba)
}
f.grant(t, "AKIASECOND", "second-secret")
f.reconcile(t)
sec := f.account(t)
if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginMinted || rec.By != "jane@example.org" {
t.Errorf("record = %+v, want the mint's", rec)
}
if string(sec.Data[account.PasswordKey]) != "second-secret" || sec.Annotations[account.GrantedAnnotation] != "req-1" {
t.Errorf("data = %v, annotations = %v", sec.Data, sec.Annotations)
}
}
// A revoked account has no grant to change: a class change adds no entry.
func TestCOSIClassChangeOnARevokedAccountAddsNoEntry(t *testing.T) {
f := newCOSIFixture(t, cosiTemplate())
f.reconcile(t)
f.grant(t, "AKIAFIRST", "first-secret")
f.reconcile(t)
f.request(t, "req-r", corev1alpha1.CredentialOperationRevoke)
f.reconcile(t)
f.finalize(t)
f.reconcile(t)
before := account.ReadRecord(f.account(t))
f.changeClass(t, "seaweedfs-readonly")
f.reconcile(t)
f.reconcile(t)
sec := f.account(t)
if rec := account.ReadRecord(sec); len(rec.History) != len(before.History) || rec.By != "jane@example.org" {
t.Errorf("record = %+v, want it unchanged from %+v", rec, before)
}
if sec.Annotations[account.RequestAnnotation] != "req-r" {
t.Errorf("request = %q, want req-r", sec.Annotations[account.RequestAnnotation])
}
if ba := f.bucketAccess(t); ba != nil {
t.Errorf("BucketAccess = %+v, want none", ba)
}
}
// A lost account Secret is written again from the live grant instead of
// rotating the keys its clients use.
func TestCOSIRewritesALostAccountSecretFromTheLiveGrant(t *testing.T) {
f := newCOSIFixture(t, cosiTemplate())
f.reconcile(t)
f.grant(t, "AKIAFIRST", "first-secret")
f.reconcile(t)
f.request(t, "req-1", corev1alpha1.CredentialOperationMint)
f.reconcile(t)
f.finalize(t)
f.reconcile(t)
f.grant(t, "AKIASECOND", "second-secret")
f.reconcile(t)
uid := f.bucketAccess(t).UID
if err := f.c.Delete(context.Background(), f.account(t)); err != nil {
t.Fatal(err)
}
f.reconcile(t)
f.reconcile(t)
ba := f.bucketAccess(t)
if ba == nil || ba.UID != uid || !ba.DeletionTimestamp.IsZero() {
t.Fatalf("BucketAccess = %+v, want the live grant kept", ba)
}
sec := f.account(t)
if sec == nil || string(sec.Data[account.PasswordKey]) != "second-secret" || sec.Annotations[account.RequestAnnotation] != "req-1" || sec.Annotations[account.GrantedAnnotation] != "req-1" {
t.Fatalf("account Secret = %+v, want the keys of the live grant for req-1", sec)
}
}
func TestCOSIAdoptsAMarkedBucketAccessKeepingItsKeys(t *testing.T) {
legacy := &cosiv1alpha1.BucketAccess{
ObjectMeta: metav1.ObjectMeta{
Name: cosiAccess, Namespace: ctNamespace, UID: "legacy-uid",
Labels: map[string]string{account.AdoptLabel: "true"},
Annotations: map[string]string{"meta.helm.sh/release-name": cosiRelease, "helm.sh/resource-policy": "keep"},
},
Spec: cosiv1alpha1.BucketAccessSpec{BucketClaimName: cosiRelease, BucketAccessClassName: cosiClass, CredentialsSecretName: cosiAccess, Protocol: "s3"},
}
f := newCOSIFixture(t, cosiTemplate(), legacy)
f.grant(t, "AKIALEGACY", "legacy-secret")
f.reconcile(t)
ba := f.bucketAccess(t)
if ba == nil || ba.UID != "legacy-uid" {
t.Fatalf("BucketAccess = %+v, want the legacy one kept", ba)
}
if ref := metav1.GetControllerOf(ba); ref == nil || ref.Name != cosiName {
t.Errorf("controller = %v, want the template", ref)
}
sec := f.account(t)
if sec == nil || string(sec.Data[account.PasswordKey]) != "legacy-secret" || string(sec.Data[account.AccessKeyIDKey]) != "AKIALEGACY" {
t.Fatalf("account Secret = %v, want the legacy keys", sec)
}
if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginMigrated {
t.Errorf("record = %+v, want Migrated", rec)
}
}
func TestCOSILeavesAnUnmarkedBucketAccessAlone(t *testing.T) {
foreign := &cosiv1alpha1.BucketAccess{
ObjectMeta: metav1.ObjectMeta{Name: cosiAccess, Namespace: ctNamespace, UID: "foreign-uid"},
Spec: cosiv1alpha1.BucketAccessSpec{BucketClaimName: cosiRelease, BucketAccessClassName: cosiClass, CredentialsSecretName: cosiAccess},
}
f := newCOSIFixture(t, cosiTemplate(), foreign)
f.reconcile(t)
if ba := f.bucketAccess(t); ba == nil || metav1.GetControllerOf(ba) != nil {
t.Errorf("BucketAccess = %+v, want it untouched", ba)
}
if f.account(t) != nil {
t.Error("keys of a foreign BucketAccess were copied")
}
tmpl := &cozyv1alpha1.CredentialTemplate{}
if err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: cosiName}, tmpl); err != nil {
t.Fatal(err)
}
if !meta.IsStatusConditionTrue(tmpl.Status.Conditions, cozyv1alpha1.CredentialTemplateBucketAccessConflict) {
t.Errorf("conditions = %v, want BucketAccessConflict", tmpl.Status.Conditions)
}
}
func TestCOSIRemovingTheUserRemovesItsBucketAccessAndSecret(t *testing.T) {
f := newCOSIFixture(t, cosiTemplate())
f.reconcile(t)
f.grant(t, "AKIAFIRST", "first-secret")
f.reconcile(t)
if err := f.c.Delete(context.Background(), cosiTemplate()); err != nil {
t.Fatal(err)
}
f.reconcile(t)
f.finalize(t)
if sec := f.account(t); sec != nil {
t.Error("the account Secret outlived its template")
}
}
func TestPasswordReconcilerSkipsACOSITemplate(t *testing.T) {
tmpl := cosiTemplate()
tmpl.Name = ctName
tmpl.Annotations[account.ReleaseNameAnnotation] = ctRelease
f := newCTFixture(t, true, tmpl)
f.reconcile(t)
sec := &corev1.Secret{}
if err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: ctName + account.SecretSuffix}, sec); !apierrors.IsNotFound(err) {
t.Errorf("the password reconciler seeded an engine-issued account: %v", err)
}
got := &cozyv1alpha1.CredentialTemplate{}
if err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: ctName}, got); err != nil {
t.Fatal(err)
}
if len(got.Status.Conditions) != 0 {
t.Errorf("conditions = %v, want none", got.Status.Conditions)
}
}
// A revoke is the account's latest request also once its Secret is lost:
// the Secret is written again as revoked, and no keys are granted until the
// next mint.
func TestCOSIALostSecretAfterARevokeGrantsNoKeys(t *testing.T) {
f := newCOSIFixture(t, cosiTemplate())
f.reconcile(t)
f.grant(t, "AKIAFIRST", "first-secret")
f.reconcile(t)
f.request(t, "req-r", corev1alpha1.CredentialOperationRevoke)
f.reconcile(t)
f.finalize(t)
f.reconcile(t)
f.reconcile(t)
if sec := f.account(t); sec.Annotations[account.GrantedAnnotation] != "req-r" {
t.Fatalf("annotations = %v, want the revoke served", sec.Annotations)
}
if err := f.c.Delete(context.Background(), f.account(t)); err != nil {
t.Fatal(err)
}
for range 3 {
f.reconcile(t)
}
if ba := f.bucketAccess(t); ba != nil {
t.Fatalf("BucketAccess = %+v, want none after a revoke", ba)
}
sec := f.account(t)
if sec == nil {
t.Fatal("the account Secret was not written again")
}
if _, ok := sec.Data[account.PasswordKey]; ok || len(sec.Data[account.AccessKeyIDKey]) > 0 {
t.Errorf("data = %v, want the user name only", sec.Data)
}
rec := account.ReadRecord(sec)
if rec.Origin != corev1alpha1.CredentialOriginRevoked || len(rec.History) == 0 || rec.History[0].Operation != corev1alpha1.CredentialOperationRevoke {
t.Errorf("record = %+v, want the revoke kept", rec)
}
if id := sec.Annotations[account.RequestAnnotation]; id == "" || sec.Annotations[account.GrantedAnnotation] != id {
t.Errorf("annotations = %v, want a served request of its own", sec.Annotations)
}
if tmpl := f.template(t); tmpl.Status.SecretResourceVersion != sec.ResourceVersion || tmpl.Status.Password.Origin != string(corev1alpha1.CredentialOriginRevoked) {
t.Errorf("status = %+v, want Revoked at %s", tmpl.Status, sec.ResourceVersion)
}
// The next mint grants keys again.
f.request(t, "req-2", corev1alpha1.CredentialOperationMint)
f.reconcile(t)
if ba := f.bucketAccess(t); ba == nil || ba.Annotations[account.RequestAnnotation] != "req-2" {
t.Fatalf("BucketAccess = %+v, want one created for req-2", ba)
}
}
// A Secret lost while a revoke waits for its BucketAccess to go still ends
// in the revoke: the live grant is deleted, not copied back.
func TestCOSIALostSecretDuringARevokeFinishesTheRevoke(t *testing.T) {
f := newCOSIFixture(t, cosiTemplate())
f.reconcile(t)
f.grant(t, "AKIAFIRST", "first-secret")
f.reconcile(t)
// The revoke is mirrored and its BucketAccess deleted; the sidecar has
// not revoked it yet.
f.request(t, "req-r", corev1alpha1.CredentialOperationRevoke)
f.reconcile(t)
if err := f.c.Delete(context.Background(), f.account(t)); err != nil {
t.Fatal(err)
}
f.reconcile(t)
f.reconcile(t)
if sec := f.account(t); sec == nil || len(sec.Data[account.PasswordKey]) > 0 || account.ReadRecord(sec).Origin != corev1alpha1.CredentialOriginRevoked {
t.Fatalf("account Secret = %+v, want it revoked without keys", sec)
}
f.finalize(t)
f.reconcile(t)
if ba := f.bucketAccess(t); ba != nil {
t.Fatalf("BucketAccess = %+v, want none after the revoke", ba)
}
if sec := f.account(t); len(sec.Data[account.PasswordKey]) > 0 {
t.Errorf("data = %v, want no keys", sec.Data)
}
}
// cosiStorage is the claim and class the sidecar needs before it can grant.
func cosiStorage(ready bool) []client.Object {
claim := &cosiv1alpha1.BucketClaim{ObjectMeta: metav1.ObjectMeta{Name: cosiRelease, Namespace: ctNamespace}}
if ready {
claim.Status = cosiv1alpha1.BucketClaimStatus{BucketReady: true, BucketName: "bc-claim-uid"}
}
return []client.Object{claim, &cosiv1alpha1.BucketAccessClass{ObjectMeta: metav1.ObjectMeta{Name: cosiClass}, DriverName: "seaweedfs"}}
}
func (f *cosiFixture) deleteTemplate(t *testing.T) {
t.Helper()
if err := f.c.Delete(context.Background(), f.template(t)); err != nil {
t.Fatal(err)
}
}
func (f *cosiFixture) templateGone(t *testing.T) bool {
t.Helper()
err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: cosiName}, &cozyv1alpha1.CredentialTemplate{})
if err != nil && !apierrors.IsNotFound(err) {
t.Fatal(err)
}
return apierrors.IsNotFound(err)
}
func TestCOSIPutsAFinalizerOnTheTemplate(t *testing.T) {
f := newCOSIFixture(t, cosiTemplate())
f.reconcile(t)
if tmpl := f.template(t); !controllerutil.ContainsFinalizer(tmpl, templateFinalizer) {
t.Errorf("finalizers = %v, want %s", tmpl.Finalizers, templateFinalizer)
}
}
// A template deleted while the sidecar may still be granting keeps its
// BucketAccess until the sidecar finalizes it, so the delete runs the driver
// revoke, and is released only then.
func TestCOSIDeletedTemplateWaitsOutTheGrantWindow(t *testing.T) {
f := newCOSIFixture(t, append(cosiStorage(true), cosiTemplate())...)
f.reconcile(t)
f.grantUnfinalized(t, "AKIAFIRST", "first-secret")
f.deleteTemplate(t)
if res := f.reconcile(t); res.RequeueAfter != cosiGrantRequeue {
t.Errorf("requeue = %v, want %v", res.RequeueAfter, cosiGrantRequeue)
}
if ba := f.bucketAccess(t); ba == nil || !ba.DeletionTimestamp.IsZero() {
t.Fatalf("BucketAccess = %+v, want it kept until the sidecar finalizes it", ba)
}
if f.templateGone(t) {
t.Fatal("the template was released inside the grant window")
}
f.grant(t, "AKIAFIRST", "first-secret")
f.reconcile(t)
if ba := f.bucketAccess(t); ba == nil || ba.DeletionTimestamp.IsZero() {
t.Fatalf("BucketAccess = %+v, want it deleted once finalized", ba)
}
if !f.templateGone(t) {
t.Fatal("the template was not released")
}
f.finalize(t)
}
// A BucketAccess the sidecar can no longer grant, its claim gone or not
// ready, is deleted without waiting: nothing was granted for it.
func TestCOSIDeletedTemplateDeletesABucketAccessThatCannotBeGranted(t *testing.T) {
for name, objs := range map[string][]client.Object{
"no claim": cosiStorage(true)[1:],
"claim not ready": cosiStorage(false),
"no class": cosiStorage(true)[:1],
} {
t.Run(name, func(t *testing.T) {
f := newCOSIFixture(t, append(objs, cosiTemplate())...)
f.reconcile(t)
if f.bucketAccess(t) == nil {
t.Fatal("no BucketAccess was created")
}
f.deleteTemplate(t)
if res := f.reconcile(t); res.RequeueAfter != 0 {
t.Errorf("requeue = %v, want none", res.RequeueAfter)
}
if ba := f.bucketAccess(t); ba != nil {
t.Fatalf("BucketAccess = %+v, want it deleted", ba)
}
if !f.templateGone(t) {
t.Fatal("the template was not released")
}
})
}
}
// A template deleted before it ever had a BucketAccess is released at once.
func TestCOSIDeletedTemplateWithoutAGrantIsReleased(t *testing.T) {
tmpl := cosiTemplate()
tmpl.Finalizers = []string{templateFinalizer}
f := newCOSIFixture(t, tmpl)
f.deleteTemplate(t)
f.reconcile(t)
if !f.templateGone(t) {
t.Fatal("the template was not released")
}
if ba := f.bucketAccess(t); ba != nil {
t.Fatalf("BucketAccess = %+v, want none", ba)
}
}
@@ -0,0 +1,76 @@
// SPDX-License-Identifier: Apache-2.0
package controller
import (
"context"
"os"
"testing"
apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
schemacel "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel"
"k8s.io/apimachinery/pkg/util/validation/field"
celconfig "k8s.io/apiserver/pkg/apis/cel"
"sigs.k8s.io/yaml"
)
// credentialTemplateCRD is the generated CRD cozystack-controller ships.
// Reading it rather than restating the rule catches a marker that did not
// generate.
const credentialTemplateCRD = "../../packages/system/cozystack-controller/definitions/cozystack.io_credentialtemplates.yaml"
// An engine-issued template, one that names a BucketAccess, stores the keys
// as they are issued, so its format must be plaintext; a template without a
// BucketAccess may use any format.
func TestCredentialTemplateCRDTiesBucketAccessToPlaintext(t *testing.T) {
raw, err := os.ReadFile(credentialTemplateCRD)
if err != nil {
t.Fatal(err)
}
var crd apiextensionsv1.CustomResourceDefinition
if err := yaml.Unmarshal(raw, &crd); err != nil {
t.Fatal(err)
}
var spec *apiextensionsv1.JSONSchemaProps
for i := range crd.Spec.Versions {
if v := crd.Spec.Versions[i]; v.Name == "v1alpha1" && v.Schema != nil && v.Schema.OpenAPIV3Schema != nil {
if p, ok := v.Schema.OpenAPIV3Schema.Properties["spec"]; ok {
spec = &p
}
}
}
if spec == nil || len(spec.XValidations) == 0 {
t.Fatal("v1alpha1 spec schema with x-kubernetes-validations not found in the CRD")
}
var internal apiextensions.JSONSchemaProps
if err := apiextensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(spec, &internal, nil); err != nil {
t.Fatal(err)
}
structural, err := schema.NewStructural(&internal)
if err != nil {
t.Fatal(err)
}
validator := schemacel.NewValidator(structural, true, celconfig.PerCallLimit)
access := map[string]any{"name": "bucket-photos-web", "bucketClaimName": "bucket-photos", "bucketAccessClassName": "seaweedfs"}
for _, tc := range []struct {
name string
spec map[string]any
accept bool
}{
{"bucketAccess with plaintext", map[string]any{"username": "web", "format": map[string]any{"name": "plaintext"}, "bucketAccess": access}, true},
{"bucketAccess with another format", map[string]any{"username": "web", "format": map[string]any{"name": "scram-sha-256"}, "bucketAccess": access}, false},
{"bucketAccess with a format named cosi", map[string]any{"username": "web", "format": map[string]any{"name": "cosi"}, "bucketAccess": access}, false},
{"plaintext without bucketAccess", map[string]any{"username": "web", "format": map[string]any{"name": "plaintext"}}, true},
{"another format without bucketAccess", map[string]any{"username": "web", "format": map[string]any{"name": "sha256"}}, true},
} {
t.Run(tc.name, func(t *testing.T) {
errs, _ := validator.Validate(context.TODO(), field.NewPath("spec"), structural, tc.spec, nil, celconfig.RuntimeCELCostBudget)
if accepted := len(errs) == 0; accepted != tc.accept {
t.Errorf("accepted = %v, want %v: %v", accepted, tc.accept, errs)
}
})
}
}
@@ -3,6 +3,7 @@ package lineagecontrollerwebhook
import (
"bytes"
"context"
"strings"
"text/template"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
@@ -71,3 +72,21 @@ func matchResourceToExcludeInclude(ctx context.Context, name string, templateCon
}
return matchResourceToSelectorArray(ctx, name, templateContext, l, resources.Include)
}
// SecretTenantVisible reports whether the webhook stamps a Secret of the
// named application tenant-visible under the definition's selectors, the way
// computeLabels evaluates them on admission. Callers outside the webhook use
// it to tell whether a definition already in the API hides a Secret before
// they label it, since the webhook re-evaluates on every write that drops the
// lineage labels.
func SecretTenantVisible(ctx context.Context, appDef *cozyv1alpha1.ApplicationDefinition, appName, namespace, secretName string, secretLabels map[string]string) bool {
if appDef == nil {
return false
}
templateContext := map[string]string{
"kind": strings.ToLower(appDef.Spec.Application.Kind),
"name": appName,
"namespace": namespace,
}
return matchResourceToExcludeInclude(ctx, secretName, templateContext, secretLabels, &appDef.Spec.Secrets)
}
@@ -0,0 +1,62 @@
package lineagecontrollerwebhook
import (
"context"
"os"
"testing"
"sigs.k8s.io/yaml"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
)
func loadDefinition(t *testing.T, path string) *cozyv1alpha1.ApplicationDefinition {
t.Helper()
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
def := &cozyv1alpha1.ApplicationDefinition{}
if err := yaml.Unmarshal(raw, def); err != nil {
t.Fatal(err)
}
return def
}
// The platform Secrets a converted engine keeps must stay hidden on every
// write that drops their lineage labels, not only until an operator rewrites
// them: the webhook stamps them from these definitions each time.
func TestConvertedDefinitionsHidePlatformSecrets(t *testing.T) {
ctx := context.Background()
for _, c := range []struct{ rd, secret string }{
{"rabbitmq", "rabbitmq-rmq-default-user"},
{"mongodb", "mongodb-rmq-credentials"},
{"mongodb", "mongodb-rmq-percona-server-mongodb-users"},
{"mariadb", "mariadb-rmq-credentials"},
{"clickhouse", "clickhouse-rmq-credentials"},
} {
def := loadDefinition(t, "../../packages/system/"+c.rd+"-rd/cozyrds/"+c.rd+".yaml")
// An operator's rewrite carries its own labels, none of the lineage ones.
if SecretTenantVisible(ctx, def, "rmq", "tenant-foo", c.secret, map[string]string{"app.kubernetes.io/name": "rmq"}) {
t.Errorf("%s: the definition stamps %s tenant-visible", c.rd, c.secret)
}
}
}
func TestSecretTenantVisibleFollowsIncludeAndExclude(t *testing.T) {
ctx := context.Background()
sel := []*cozyv1alpha1.ApplicationDefinitionResourceSelector{{ResourceNames: []string{"{{ .kind }}-{{ .name }}-default-user"}}}
def := &cozyv1alpha1.ApplicationDefinition{}
def.Spec.Application.Kind = "RabbitMQ"
def.Spec.Secrets.Include = sel
if !SecretTenantVisible(ctx, def, "rmq", "tenant-foo", "rabbitmq-rmq-default-user", nil) {
t.Fatal("an included Secret must be visible")
}
def.Spec.Secrets.Exclude = sel
if SecretTenantVisible(ctx, def, "rmq", "tenant-foo", "rabbitmq-rmq-default-user", nil) {
t.Fatal("exclude must win over include")
}
if SecretTenantVisible(ctx, nil, "rmq", "tenant-foo", "rabbitmq-rmq-default-user", nil) {
t.Fatal("a kind with no definition stamps nothing visible")
}
}
+1
View File
@@ -13,5 +13,6 @@
| `publicRead` | Serves the bucket's objects to anyone without credentials at `<endpoint>/<bucket>/<key>`. Anonymous callers can read objects but cannot list the bucket or write to it. | `bool` | `false` |
| `users` | Users configuration map. | `map[string]object` | `{}` |
| `users[name].readonly` | Whether the user has read-only access. | `bool` | `false` |
| `users[name].platform` | Marks a platform account, such as the `system` user of the backup bucket, which backupstrategy-controller sets. Its keys stay in the `<bucket>-<user>-credentials` Secret, which no tenant can read, and are never minted. Clearing it drops the chart-rendered BucketAccess, which revokes those keys, and the user becomes a normal account whose keys are minted through its Credential. Leave it unset for your own users. | `bool` | `false` |
| `schedulingClass` | 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. | `string` | `""` |
@@ -0,0 +1,52 @@
{{/*
Account naming, which must match pkg/credentials/account.MapName: the
credential of a user is <release>.<account>, where <account> is the user
name lowercased with every character outside [a-z0-9-] replaced by "-".
*/}}
{{- define "bucket.accountName" -}}
{{- regexReplaceAll "[^a-z0-9-]" (lower .) "-" -}}
{{- end -}}
{{/*
The BucketAccess of a tenant user, which also names the Secret the COSI
sidecar writes for it: <release>-<user>, as the chart named it before the
conversion, so that platform migration 71 hands the existing one, and its
keys, to the template; or <release>-<account> when <release>-<user> is not
a valid object name, since no BucketAccess was ever created under it.
*/}}
{{- define "bucket.accessName" -}}
{{- $root := index . 0 -}}
{{- $user := index . 1 -}}
{{- $legacy := printf "%s-%s" $root.Release.Name $user -}}
{{- if and (le (len $legacy) 253) (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$" $legacy) -}}
{{- $legacy -}}
{{- else -}}
{{- printf "%s-%s" $root.Release.Name (include "bucket.accountName" $user) -}}
{{- end -}}
{{- end -}}
{{/*
The BucketAccessClass a user's grant comes from: the storage pool's, and
its -readonly variant for a read-only user.
*/}}
{{- define "bucket.accessClass" -}}
{{- $root := index . 0 -}}
{{- $user := index . 1 -}}
{{- $root.Values._namespace.seaweedfs }}{{- if $root.Values.storagePool }}-{{ $root.Values.storagePool }}{{- end }}{{- if $user.readonly }}-readonly{{- end }}
{{- end -}}
{{- define "bucket.accountsGuard" -}}
{{- $seen := dict -}}
{{- range $user, $u := .Values.users -}}
{{- if not (default false $u.platform) -}}
{{- $mapped := include "bucket.accountName" $user -}}
{{- if or (gt (len $mapped) 63) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $mapped)) -}}
{{- fail (printf "user %q maps to the account name %q, which must be at most 63 characters and start and end with a letter or a digit; rename the user" $user $mapped) -}}
{{- end -}}
{{- with index $seen $mapped -}}
{{- fail (printf "users %q and %q both map to the account name %q; rename one of them" . $user $mapped) -}}
{{- end -}}
{{- $_ := set $seen $mapped $user -}}
{{- end -}}
{{- end -}}
{{- end -}}
@@ -44,18 +44,25 @@ spec:
bucketClassName: {{ $seaweedfs }}{{- if $pool }}-{{ $pool }}{{- end }}{{- if .Values.locking }}-lock{{- if eq (toString .Values.lockingDefaultRetention) "false" }}-noretention{{- end }}{{- end }}
protocols:
- s3
{{- /*
Only a platform user's BucketAccess is rendered here. A tenant user's is
created by cozystack-controller from its CredentialTemplate
(credentials.yaml), so that a mint can re-create it and a revoke delete it.
*/}}
{{- range $name, $user := .Values.users }}
{{- if default false $user.platform }}
---
apiVersion: objectstorage.k8s.io/v1alpha1
kind: BucketAccess
metadata:
name: {{ $.Release.Name }}-{{ $name }}
spec:
bucketAccessClassName: {{ $seaweedfs }}{{- if $pool }}-{{ $pool }}{{- end }}{{- if $user.readonly }}-readonly{{- end }}
bucketAccessClassName: {{ include "bucket.accessClass" (list $ $user) }}
bucketClaimName: {{ $.Release.Name }}
credentialsSecretName: {{ $.Release.Name }}-{{ $name }}
protocol: s3
{{- end }}
{{- end }}
{{- if .Values.publicRead }}
{{- if hasKey .Values.users "public-read" }}
{{- fail "publicRead creates the BucketAccess <bucket>-public-read, which the user \"public-read\" already owns: rename that user" }}
@@ -0,0 +1,29 @@
{{- /*
One CredentialTemplate per tenant user: the account the Cozystack
credentials API mints and revokes through. The COSI driver issues a user's
keys, so the template names the BucketAccess whose grant issues them, and
cozystack-controller creates that BucketAccess, copies its keys into the
account Secret <release>.<account>.account, re-creates it on a mint and
deletes it on a revoke. The keys are stored as the driver issues them, so
the format is plaintext. The chart renders no BucketAccess and no key for
these users. A platform user keeps its chart-rendered BucketAccess in
bucketclaim.yaml.
*/ -}}
{{- include "bucket.accountsGuard" $ }}
{{- range $user, $u := .Values.users }}
{{- if not (default false $u.platform) }}
---
apiVersion: cozystack.io/v1alpha1
kind: CredentialTemplate
metadata:
name: {{ printf "%s.%s" $.Release.Name (include "bucket.accountName" $user) | quote }}
spec:
username: {{ $user | quote }}
format:
name: plaintext
bucketAccess:
name: {{ include "bucket.accessName" (list $ $user) | quote }}
bucketClaimName: {{ $.Release.Name | quote }}
bucketAccessClassName: {{ include "bucket.accessClass" (list $ $u) | quote }}
{{- end }}
{{- end }}
@@ -0,0 +1,143 @@
suite: bucket credential templates
templates:
- templates/credentials.yaml
- templates/bucketclaim.yaml
release:
name: bucket-photos
namespace: tenant-foo
set:
_namespace:
seaweedfs: tenant-root
tests:
- it: renders one engine-issued template per tenant user, naming the BucketAccess the controller creates
template: templates/credentials.yaml
set:
users:
web: {}
asserts:
- hasDocuments:
count: 1
- isKind:
of: CredentialTemplate
- equal:
path: metadata.name
value: bucket-photos.web
- equal:
path: spec
value:
username: web
format:
name: plaintext
bucketAccess:
name: bucket-photos-web
bucketClaimName: bucket-photos
bucketAccessClassName: tenant-root
- it: takes the read-only class of the storage pool for a read-only user
template: templates/credentials.yaml
set:
storagePool: fast
users:
reader:
readonly: true
asserts:
- equal:
path: spec.bucketAccess.bucketAccessClassName
value: tenant-root-fast-readonly
- it: renders no BucketAccess for a tenant user
template: templates/bucketclaim.yaml
set:
users:
web: {}
asserts:
- hasDocuments:
count: 1
- isKind:
of: BucketClaim
- it: keeps a platform user's BucketAccess in the chart and gives it no template
set:
users:
system:
platform: true
asserts:
- hasDocuments:
count: 0
template: templates/credentials.yaml
- hasDocuments:
count: 2
template: templates/bucketclaim.yaml
- equal:
path: spec
value:
bucketAccessClassName: tenant-root
bucketClaimName: bucket-photos
credentialsSecretName: bucket-photos-system
protocol: s3
template: templates/bucketclaim.yaml
documentSelector:
path: kind
value: BucketAccess
# The pre-conversion chart named a user's BucketAccess <release>-<user>,
# and migration 71 hands that one over by name, so a user name that is a
# valid object name keeps it. Any other one never had a BucketAccess and
# takes the account name.
- it: names the BucketAccess as the pre-conversion chart did when that name is valid
template: templates/credentials.yaml
set:
users:
archive.v2: {}
asserts:
- equal:
path: metadata.name
value: bucket-photos.archive-v2
- equal:
path: spec.bucketAccess.name
value: bucket-photos-archive.v2
- it: names the BucketAccess after the account when the user name is not a valid object name
template: templates/credentials.yaml
set:
users:
Web_Uploads: {}
asserts:
- equal:
path: metadata.name
value: bucket-photos.web-uploads
- equal:
path: spec.bucketAccess.name
value: bucket-photos-web-uploads
- it: refuses a user whose account name is not a valid name
template: templates/credentials.yaml
set:
users:
"-web": {}
asserts:
- failedTemplate:
errorPattern: start and end with a letter or a digit
- it: refuses a user whose account name is longer than a DNS label
template: templates/credentials.yaml
set:
users:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: {}
asserts:
- failedTemplate:
errorPattern: at most 63 characters
- it: refuses two users that map to one account
template: templates/credentials.yaml
set:
users:
Web: {}
web: {}
asserts:
- failedTemplate:
errorPattern: both map to the account name "web"
@@ -61,16 +61,18 @@ tests:
path: spec.bucketAccessClassName
value: tenant-root-public
- it: keeps the users' BucketAccesses next to the public one
- it: renders only the platform users' BucketAccesses next to the public one
set:
publicRead: true
users:
app: {}
reader:
readonly: true
system:
platform: true
asserts:
- hasDocuments:
count: 4
count: 3
- it: refuses a user that would own the public BucketAccess name
set:
+4
View File
@@ -37,6 +37,10 @@
"additionalProperties": {
"type": "object",
"properties": {
"platform": {
"description": "Marks a platform account, such as the `system` user of the backup bucket, which backupstrategy-controller sets. Its keys stay in the `\u003cbucket\u003e-\u003cuser\u003e-credentials` Secret, which no tenant can read, and are never minted. Clearing it drops the chart-rendered BucketAccess, which revokes those keys, and the user becomes a normal account whose keys are minted through its Credential. Leave it unset for your own users.",
"type": "boolean"
},
"readonly": {
"description": "Whether the user has read-only access.",
"type": "boolean"
+1
View File
@@ -16,6 +16,7 @@ publicRead: false
## @typedef {struct} User - Bucket user configuration.
## @field {bool} [readonly] - Whether the user has read-only access.
## @field {bool} [platform] - Marks a platform account, such as the `system` user of the backup bucket, which backupstrategy-controller sets. Its keys stay in the `<bucket>-<user>-credentials` Secret, which no tenant can read, and are never minted. Clearing it drops the chart-rendered BucketAccess, which revokes those keys, and the user becomes a normal account whose keys are minted through its Credential. Leave it unset for your own users.
## @param {map[string]User} users - Users configuration map.
users: {}
+9 -10
View File
@@ -40,15 +40,14 @@ The scope is **definitions only** — vhosts, users, permissions, queues, exchan
### Application-specific parameters
| Name | Description | Type | Value |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ----- |
| `users` | Users configuration map. | `map[string]object` | `{}` |
| `users[name].password` | Password for the user. | `string` | `""` |
| `vhosts` | Virtual hosts configuration map. | `map[string]object` | `{}` |
| `vhosts[name].roles` | Virtual host roles list. | `object` | `{}` |
| `vhosts[name].roles.admin` | List of admin users. | `[]string` | `[]` |
| `vhosts[name].roles.readonly` | List of readonly users. | `[]string` | `[]` |
| `schedulingClass` | 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. | `string` | `""` |
| Name | Description | Type | Value |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ----- |
| `users` | Users configuration map. Each user is a RabbitMQ user that messaging-topology-operator keeps from an account Secret the platform holds. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. The operator applies either to the broker within seconds. A `password` key here is ignored. The administrator in `<release>-default-user` belongs to the platform and is not shown to tenants. | `map[string]object` | `{}` |
| `vhosts` | Virtual hosts configuration map. | `map[string]object` | `{}` |
| `vhosts[name].roles` | Virtual host roles list. | `object` | `{}` |
| `vhosts[name].roles.admin` | List of admin users. | `[]string` | `[]` |
| `vhosts[name].roles.readonly` | List of readonly users. | `[]string` | `[]` |
| `schedulingClass` | 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. | `string` | `""` |
## TLS scope
@@ -69,7 +68,7 @@ The broker pods roll once, because the operator mounts the new TLS Secret into t
And **the published metrics port changes**. The operator exposes *either* `prometheus` (15692) *or* `prometheus-tls` (15691) on its Service, never both — deliberately, so that a scrape config selecting every port does not count each node twice — and that choice keys off TLS alone. Enabling TLS therefore withdraws 15692 from the Service and publishes 15691 in its place. The broker itself keeps listening on 15692, but a `ServiceMonitor` or `VMServiceScrape` selecting the port by the name `prometheus` stops matching. Retarget it to `prometheus-tls`, which is HTTPS under the release CA and so needs a `tlsConfig` carrying the trust anchor described below. The chart does not paper over this by re-adding 15692 through `spec.override.service`: the operator drops any port name it does not own on each reconcile and the override would reinstate it without a NodePort, which on a LoadBalancer means a fresh allocation and another reconcile every round.
And **the connection details handed to clients change**. `<release>-default-user` is the Service Binding object this chart grants to the tenant, and the operator rewrites its `port` key from `5672` to `5671` as soon as `spec.tls.secretName` is set — gated on TLS alone, not on whether the plaintext listener is still open. A client that hardcodes `:5672` keeps working, because that listener does stay open. A client that resolves its endpoint from the binding — the documented way to consume it — follows the change to 5671 and must speak TLS from then on, and it cannot verify the certificate until the trust anchor below is obtainable. Per-plugin port keys (`mqtt-port`, `stomp-port`, `stream-port` and the web variants) move to their TLS values the same way. This is the main reason `tls.enabled` is opt-in rather than something `external` implies: it moves clients that read the binding correctly, and it moves them the instant the flag is set, before any of them has had a chance to pick up the trust anchor.
And **the connection details handed to clients change**. `<release>-default-user` is the operator's Service Binding object, read by platform components such as the backup strategy and no longer by tenants, and the operator rewrites its `port` key from `5672` to `5671` as soon as `spec.tls.secretName` is set — gated on TLS alone, not on whether the plaintext listener is still open. A client that hardcodes `:5672` keeps working, because that listener does stay open. A client that resolves its endpoint from the binding — the documented way to consume it — follows the change to 5671 and must speak TLS from then on, and it cannot verify the certificate until the trust anchor below is obtainable. Per-plugin port keys (`mqtt-port`, `stomp-port`, `stream-port` and the web variants) move to their TLS values the same way. This is the main reason `tls.enabled` is opt-in rather than something `external` implies: it moves clients that read the binding correctly, and it moves them the instant the flag is set, before any of them has had a chance to pick up the trust anchor.
**The plaintext management listener is load-bearing.** `messaging-topology-operator` is what reconciles the `User`, `Vhost` and `Permission` objects this chart creates from `users` and `vhosts`, and it talks to the broker over the management API. Once TLS is on it would switch to HTTPS on 15671 and verify the broker against the operator process's system certificate pool, which cannot contain a per-release self-signed CA — so every user and permission would fail to reconcile with `certificate signed by unknown authority`. The chart therefore annotates the cluster with `rabbitmq.com/operator-connection-uri` pointing at plaintext `http://…:15672`, keeping that operator on the in-cluster plaintext port. This affects only the operator's own management connection, never broker traffic, and it is why `tls.disableNonTLSListeners` cannot be combined with `users` or `vhosts`.
@@ -0,0 +1,32 @@
{{/*
Account Secret naming, which must match pkg/credentials/account.MapName: the
credentials API writes <release>.<account>.account, where <account> is the
user name lowercased with every character outside [a-z0-9-] replaced by "-".
*/}}
{{- define "rabbitmq.accountName" -}}
{{- regexReplaceAll "[^a-z0-9-]" (lower .) "-" -}}
{{- end -}}
{{- define "rabbitmq.accountSecret" -}}
{{- $root := index . 0 -}}
{{- $user := index . 1 -}}
{{- printf "%s.%s.account" $root.Release.Name (include "rabbitmq.accountName" $user) -}}
{{- end -}}
{{/*
Two users mapping to one account would share one Secret, so the topology
operator would import the same credentials for both User objects.
*/}}
{{- define "rabbitmq.accountsGuard" -}}
{{- $seen := dict -}}
{{- range $user, $_ := .Values.users -}}
{{- $mapped := include "rabbitmq.accountName" $user -}}
{{- if or (gt (len $mapped) 63) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $mapped)) -}}
{{- fail (printf "user %q maps to the account name %q, which must be at most 63 characters and start and end with a letter or a digit; rename the user" $user $mapped) -}}
{{- end -}}
{{- with index $seen $mapped -}}
{{- fail (printf "users %q and %q both map to the account name %q; rename one of them" . $user $mapped) -}}
{{- end -}}
{{- $_ := set $seen $mapped $user -}}
{{- end -}}
{{- end -}}
@@ -0,0 +1,25 @@
{{- /*
One CredentialTemplate per user: the account the Cozystack credentials API
mints and revokes through. cozystack-controller keeps its account Secret,
<release>.<account>.account, which the User's importCredentialsSecret names
in rabbitmq.yaml. messaging-topology-operator watches that Secret and puts
the password to the broker again whenever it changes, so a mint applies
without a Helm run. The operator reads the plaintext and hashes it itself,
hence the plaintext format; the label is the one its Secret cache and its
User admission webhook require. The chart renders no password.
*/ -}}
{{- include "rabbitmq.accountsGuard" $ }}
{{- range $user, $_ := .Values.users }}
---
apiVersion: cozystack.io/v1alpha1
kind: CredentialTemplate
metadata:
name: {{ printf "%s.%s" $.Release.Name (include "rabbitmq.accountName" $user) | quote }}
spec:
username: {{ $user | quote }}
format:
name: plaintext
secret:
labels:
rabbitmq.com/topology-operator: "true"
{{- end }}
+9 -29
View File
@@ -129,44 +129,24 @@ spec:
{{- end }}
storage: {{ .Values.size }}
{{- range $user, $u := .Values.users }}
{{- $password := $u.password }}
{{- if not $password }}
{{- with (dig "data" "password" "" (lookup "v1" "Secret" $.Release.Namespace (printf "%s-%s-credentials" $.Release.Name (kebabcase $user)))) }}
{{- $password = b64dec . }}
{{- end }}
{{- end }}
{{- if not $password }}
{{- $password = (randAlphaNum 16) }}
{{- end }}
{{- /* The User object keeps its pre-conversion name: renaming it would make
the operator delete the broker user and create it again. Its password
comes from the account Secret of credentials.yaml, which the operator
re-imports on every change. Until the Secret exists the operator's
admission webhook refuses the User, so a release that adds a user
converges on the retry after cozystack-controller has seeded it. */}}
{{- include "rabbitmq.accountsGuard" $ }}
{{- range $user, $_ := .Values.users }}
---
apiVersion: rabbitmq.com/v1beta1
kind: User
metadata:
name: {{ $.Release.Name }}-{{ kebabcase $user }}
annotations:
config: '{{ printf "%s %s" $user $password | sha256sum }}'
spec:
importCredentialsSecret:
name: {{ $.Release.Name }}-{{ kebabcase $user }}-credentials
name: {{ include "rabbitmq.accountSecret" (list $ $user) | quote }}
rabbitmqClusterReference:
name: {{ $.Release.Name }}
---
apiVersion: v1
kind: Secret
metadata:
name: {{ $.Release.Name }}-{{ kebabcase $user }}-credentials
labels:
apps.cozystack.io/user-secret: "true"
# Topology Operator >= 1.20 caches only Secrets carrying this label, and its User
# admission webhook rejects an importCredentialsSecret that lacks it.
rabbitmq.com/topology-operator: "true"
type: Opaque
stringData:
username: {{ $user }}
password: {{ $password }}
{{- end }}
{{- range $host, $h := .Values.vhosts }}
@@ -0,0 +1,84 @@
suite: one CredentialTemplate per user, naming the account Secret the User imports
# The template is the account the credentials API mints through; its name plus
# ".account" must be the importCredentialsSecret rabbitmq.yaml gives the User,
# or the topology operator reads a Secret nobody writes.
templates:
- templates/credentials.yaml
release:
name: rabbitmq-test
namespace: tenant-test
tests:
- it: renders nothing without users
asserts:
- hasDocuments:
count: 0
- it: renders a template per user, named for the account Secret's mapping
set:
users:
web: {}
Bob.Smith: {}
asserts:
- hasDocuments:
count: 2
- isKind:
of: CredentialTemplate
- equal:
path: apiVersion
value: cozystack.io/v1alpha1
- equal:
path: metadata.name
value: rabbitmq-test.bob-smith
documentIndex: 0
- equal:
path: spec.username
value: Bob.Smith
documentIndex: 0
- equal:
path: metadata.name
value: rabbitmq-test.web
documentIndex: 1
- it: stores the plaintext the operator hashes, labelled for its Secret cache
set:
users:
web: {}
asserts:
- equal:
path: spec.format.name
value: plaintext
- equal:
path: spec.secret.labels
value:
rabbitmq.com/topology-operator: "true"
- notExists:
path: spec.valuesPath
- it: refuses two users that map to one account
set:
users:
web: {}
Web: {}
asserts:
- failedTemplate:
errorPattern: map to
- it: refuses a user that maps to no valid account name
set:
users:
"-web": {}
asserts:
- failedTemplate:
errorPattern: start and end with a letter or a digit
- it: refuses a user whose account name is longer than a DNS label
set:
users:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: {}
asserts:
- failedTemplate:
errorPattern: at most 63 characters
@@ -1,4 +1,4 @@
suite: RabbitMQ user credentials Secrets
suite: RabbitMQ users read their password from the account Secret
templates:
- templates/rabbitmq.yaml
@@ -7,20 +7,19 @@ release:
name: myrabbitmq
namespace: tenant-test
# messaging-topology-operator >= 1.20 caches only Secrets labelled
# rabbitmq.com/topology-operator=true, and its User admission webhook rejects an
# importCredentialsSecret that lacks the label. Losing it rejects every User the
# chart renders.
# messaging-topology-operator re-imports importCredentialsSecret whenever the
# Secret changes, so pointing each User at the account Secret the credentials
# API writes is what makes a mint reach the broker. The User keeps its
# pre-conversion name: renaming it would make the operator delete the broker
# user and create it again.
set:
users:
alice:
password: alicepassword
bobSmith:
password: bobpassword
alice: {}
bobSmith: {}
tests:
- it: points each User at its own credentials Secret
- it: points each User at its account Secret and keeps its name
documentSelector:
path: metadata.name
value: myrabbitmq-bob-smith
@@ -29,15 +28,38 @@ tests:
of: User
- equal:
path: spec.importCredentialsSecret.name
value: myrabbitmq-bob-smith-credentials
value: myrabbitmq.bobsmith.account
- notExists:
path: metadata.annotations
- it: labels every credentials Secret for the topology operator's Secret cache
documentSelector:
path: kind
value: Secret
matchMany: true
- it: renders no Secret, so no password reaches the release
asserts:
- equal:
path: metadata.labels["rabbitmq.com/topology-operator"]
value: "true"
- containsDocument:
kind: Secret
apiVersion: v1
not: true
- it: ignores a password left in values
set:
users:
alice:
password: alicepassword
asserts:
- containsDocument:
kind: Secret
apiVersion: v1
not: true
- notExists:
path: metadata.annotations.config
documentSelector:
path: metadata.name
value: myrabbitmq-alice
- it: refuses two users that map to one account
set:
users:
web: {}
Web: {}
asserts:
- failedTemplate:
errorPattern: map to
+2 -8
View File
@@ -160,17 +160,11 @@
]
},
"users": {
"description": "Users configuration map.",
"description": "Users configuration map. Each user is a RabbitMQ user that messaging-topology-operator keeps from an account Secret the platform holds. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. The operator applies either to the broker within seconds. A `password` key here is ignored. The administrator in `\u003crelease\u003e-default-user` belongs to the platform and is not shown to tenants.",
"type": "object",
"default": {},
"additionalProperties": {
"type": "object",
"properties": {
"password": {
"description": "Password for the user.",
"type": "string"
}
}
"type": "object"
}
},
"vhosts": {
+3 -8
View File
@@ -102,18 +102,13 @@ version: v4.2
##
## @typedef {struct} User - User configuration.
## @field {string} [password] - Password for the user.
## @param {map[string]User} users - Users configuration map.
## @param {map[string]User} users - Users configuration map. Each user is a RabbitMQ user that messaging-topology-operator keeps from an account Secret the platform holds. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. The operator applies either to the broker within seconds. A `password` key here is ignored. The administrator in `<release>-default-user` belongs to the platform and is not shown to tenants.
users: {}
## Example:
## users:
## user1:
## password: strongpassword
## user2:
## password: hackme
## user3:
## password: testtest
## user1: {}
## user2: {}
## @typedef {struct} Roles - Virtual host roles.
## @field {[]string} [admin] - List of admin users.
+1 -1
View File
@@ -44,7 +44,7 @@ Service utilizes the freshworks-oss Redis Operator (a maintained fork of the arc
| Name | Description | Type | Value |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------ |
| `authEnabled` | Enable password generation. | `bool` | `true` |
| `authEnabled` | Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password. | `bool` | `true` |
| `minReplicasToWrite` | Redis `min-replicas-to-write`: the master refuses writes unless at least this many replicas are connected and within `minReplicasMaxLag`. Unset by default, which leaves the Redis default (disabled). With `replicas: 2` and a value of 1 the master rejects writes while its only replica is down, trading availability for a bound on the writes lost if an isolated master is failed over. Replication stays asynchronous, so this bounds the loss, it does not remove it. Must be 0 or more and below `replicas` (a master with `replicas` pods has `replicas - 1` replicas), otherwise every write is refused; the chart refuses such a value. | `*int` | `null` |
| `minReplicasMaxLag` | Redis `min-replicas-max-lag`, in seconds: a replica whose last acknowledgement is older than this does not count towards `minReplicasToWrite`. Unset by default, which leaves the Redis default (10). Has no effect unless `minReplicasToWrite` is set. Must be at least 1 when `minReplicasToWrite` is set: Redis treats 0 as disabling the check, so the chart refuses it. | `*int` | `null` |
| `maxmemory` | Redis `maxmemory`: the dataset size at which Redis applies `maxmemoryPolicy`. Unset by default, which renders `maxmemory 0` (no limit, the Redis default), so a value set by hand with `CONFIG SET` is reset on the next reconcile. Must be at most 90% of the memory request of each Redis pod (from `resources` or `resourcesPreset`): the operator silently drops a larger value, so the chart refuses it. Leave headroom below that for replication and snapshot buffers. | `quantity` | `""` |
@@ -0,0 +1,21 @@
{{- /*
The one account of this kind: the default user, whose password the
Cozystack credentials API mints and revokes. cozystack-controller keeps its
account Secret, <release>.default.account, which auth.secretPath names, and
the operator applies a changed password with CONFIG SET, restarting
nothing. The chart renders no password, and nobody can log in until a mint.
Replication, the Sentinels, the probes and the metrics exporter do not use
it: the operator gives them an internal account of their own. The backup
Job does, reading it when the Job starts.
*/ -}}
{{- if .Values.authEnabled }}
apiVersion: cozystack.io/v1alpha1
kind: CredentialTemplate
metadata:
name: {{ printf "%s.default" .Release.Name | quote }}
spec:
username: default
format:
name: plaintext
{{- end }}
@@ -30,20 +30,6 @@
{{- if or $sentinel.resources $sentinel.resourcesPreset -}}
{{- $sentinelResources = $sentinel.resources | default dict -}}
{{- end -}}
{{- if .Values.authEnabled }}
{{- $existingPassword := lookup "v1" "Secret" .Release.Namespace (printf "%s-auth" .Release.Name) }}
{{- $password := randAlphaNum 32 | b64enc }}
{{- if $existingPassword }}
{{- $password = index $existingPassword.data "password" }}
{{- end }}
---
apiVersion: v1
kind: Secret
metadata:
name: {{ .Release.Name }}-auth
data:
password: {{ $password }}
{{- end }}
---
@@ -214,8 +200,13 @@ spec:
- min-replicas-max-lag {{ .Values.minReplicasMaxLag | int }}
{{- end }}
{{- if .Values.authEnabled }}
{{- /* The account Secret of the default CredentialTemplate (credentials.yaml),
which cozystack-controller keeps and the credentials API rewrites on a
mint. The operator reads its password key on every reconcile and
applies a changed one to the running servers with CONFIG SET; nothing
else it runs authenticates with it. */}}
auth:
secretPath: {{ .Release.Name }}-auth
secretPath: {{ printf "%s.default.account" .Release.Name }}
{{- end }}
---
@@ -0,0 +1,80 @@
suite: the default account is a CredentialTemplate whose account Secret the operator reads
# The template is the account the credentials API mints through; its name plus
# ".account" must be the auth.secretPath of the RedisFailover, or the operator
# reads a Secret nobody writes. The chart itself renders no password.
release:
name: my-redis
namespace: tenant-test
tests:
- it: renders the default account while authentication is on
templates:
- templates/credentials.yaml
asserts:
- hasDocuments:
count: 1
- isKind:
of: CredentialTemplate
- equal:
path: apiVersion
value: cozystack.io/v1alpha1
- equal:
path: metadata.name
value: my-redis.default
- equal:
path: spec.username
value: default
# The operator reads the password itself from the account Secret.
- equal:
path: spec.format.name
value: plaintext
# The operator re-reads the Secret on its own resync and watches nothing
# a label would select.
- notExists:
path: spec.secret
- notExists:
path: spec.valuesPath
- it: renders no account without authentication
templates:
- templates/credentials.yaml
set:
authEnabled: false
asserts:
- hasDocuments:
count: 0
- it: points the operator at the account Secret
templates:
- templates/redisfailover.yaml
documentSelector:
path: kind
value: RedisFailover
asserts:
- equal:
path: spec.auth.secretPath
value: my-redis.default.account
- it: gives the operator no Secret without authentication
templates:
- templates/redisfailover.yaml
set:
authEnabled: false
documentSelector:
path: kind
value: RedisFailover
asserts:
- notExists:
path: spec.auth
- it: renders no password Secret
templates:
- templates/redisfailover.yaml
asserts:
- containsDocument:
kind: Secret
apiVersion: v1
name: my-redis-auth
not: true
+1 -1
View File
@@ -176,7 +176,7 @@
}
},
"authEnabled": {
"description": "Enable password generation.",
"description": "Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password.",
"type": "boolean",
"default": true
},
+1 -1
View File
@@ -119,7 +119,7 @@ tls: {}
## @section Application-specific parameters
##
## @param {bool} authEnabled - Enable password generation.
## @param {bool} authEnabled - Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password.
authEnabled: true
## @param {*int} [minReplicasToWrite] - Redis `min-replicas-to-write`: the master refuses writes unless at least this many replicas are connected and within `minReplicasMaxLag`. Unset by default, which leaves the Redis default (disabled). With `replicas: 2` and a value of 1 the master rejects writes while its only replica is down, trading availability for a bound on the writes lost if an isolated master is failed over. Replication stays asynchronous, so this bounds the loss, it does not remove it. Must be 0 or more and below `replicas` (a master with `replicas` pods has `replicas - 1` replicas), otherwise every write is refused; the chart refuses such a value.
+1 -1
View File
@@ -33,7 +33,7 @@ Service runs Valkey on the freshworks-oss redis-operator, which manages Sentinel
| Name | Description | Type | Value |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------ |
| `authEnabled` | Enable password generation. | `bool` | `true` |
| `authEnabled` | Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password. | `bool` | `true` |
| `schedulingClass` | 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. | `string` | `""` |
@@ -0,0 +1,21 @@
{{- /*
The one account of this kind: the default user, whose password the
Cozystack credentials API mints and revokes. cozystack-controller keeps its
account Secret, <release>.default.account, which auth.secretPath names, and
the operator applies a changed password with CONFIG SET, restarting
nothing. The chart renders no password, and nobody can log in until a mint.
Replication, the Sentinels, the probes and the metrics exporter do not use
it: the operator gives them an internal account of their own. The backup
Job does, reading it when the Job starts.
*/ -}}
{{- if .Values.authEnabled }}
apiVersion: cozystack.io/v1alpha1
kind: CredentialTemplate
metadata:
name: {{ printf "%s.default" .Release.Name | quote }}
spec:
username: default
format:
name: plaintext
{{- end }}
@@ -6,23 +6,7 @@
{{- fail (trim (printf "valkey: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list. %s" (get $policy "Error"))) }}
{{- end }}
{{- end }}
{{- if .Values.authEnabled }}
{{- $existingPassword := lookup "v1" "Secret" .Release.Namespace (printf "%s-auth" .Release.Name) }}
{{- $password := randAlphaNum 32 | b64enc }}
{{- if $existingPassword }}
{{- $password = index $existingPassword.data "password" }}
{{- end }}
---
apiVersion: v1
kind: Secret
metadata:
name: {{ .Release.Name }}-auth
data:
password: {{ $password }}
{{- end }}
---
apiVersion: databases.spotahome.com/v1
kind: RedisFailover
metadata:
@@ -113,8 +97,13 @@ spec:
- save ""
{{- end }}
{{- if .Values.authEnabled }}
{{- /* The account Secret of the default CredentialTemplate (credentials.yaml),
which cozystack-controller keeps and the credentials API rewrites on a
mint. The operator reads its password key on every reconcile and
applies a changed one to the running servers with CONFIG SET; nothing
else it runs authenticates with it. */}}
auth:
secretPath: {{ .Release.Name }}-auth
secretPath: {{ printf "%s.default.account" .Release.Name }}
{{- end }}
---
@@ -0,0 +1,80 @@
suite: the default account is a CredentialTemplate whose account Secret the operator reads
# The template is the account the credentials API mints through; its name plus
# ".account" must be the auth.secretPath of the RedisFailover, or the operator
# reads a Secret nobody writes. The chart itself renders no password.
release:
name: my-valkey
namespace: tenant-test
tests:
- it: renders the default account while authentication is on
templates:
- templates/credentials.yaml
asserts:
- hasDocuments:
count: 1
- isKind:
of: CredentialTemplate
- equal:
path: apiVersion
value: cozystack.io/v1alpha1
- equal:
path: metadata.name
value: my-valkey.default
- equal:
path: spec.username
value: default
# The operator reads the password itself from the account Secret.
- equal:
path: spec.format.name
value: plaintext
# The operator re-reads the Secret on its own resync and watches nothing
# a label would select.
- notExists:
path: spec.secret
- notExists:
path: spec.valuesPath
- it: renders no account without authentication
templates:
- templates/credentials.yaml
set:
authEnabled: false
asserts:
- hasDocuments:
count: 0
- it: points the operator at the account Secret
templates:
- templates/valkeyfailover.yaml
documentSelector:
path: kind
value: RedisFailover
asserts:
- equal:
path: spec.auth.secretPath
value: my-valkey.default.account
- it: gives the operator no Secret without authentication
templates:
- templates/valkeyfailover.yaml
set:
authEnabled: false
documentSelector:
path: kind
value: RedisFailover
asserts:
- notExists:
path: spec.auth
- it: renders no password Secret
templates:
- templates/valkeyfailover.yaml
asserts:
- containsDocument:
kind: Secret
apiVersion: v1
name: my-valkey-auth
not: true
+1 -1
View File
@@ -137,7 +137,7 @@
]
},
"authEnabled": {
"description": "Enable password generation.",
"description": "Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password.",
"type": "boolean",
"default": true
},
+1 -1
View File
@@ -86,7 +86,7 @@ version: v8
## @section Application-specific parameters
##
## @param {bool} authEnabled - Enable password generation.
## @param {bool} authEnabled - Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password.
authEnabled: true
## @param {string} schedulingClass - 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.
@@ -55,9 +55,10 @@ 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 -
# 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.
# The CredentialTemplate CRD, which the credentials conversions apply (see
# migrations/lib/credential-crd.sh) 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`.
@@ -48,21 +48,16 @@ set -euo pipefail
# shellcheck source=lib/cozystack-version.sh
. "$(dirname "$0")/lib/cozystack-version.sh"
# shellcheck source=lib/credential-crd.sh
. "$(dirname "$0")/lib/credential-crd.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
# kind, so apply the CRD baked into this image first.
apply_credential_crd
credentials-migrate seed \
--migration 64 \
+179
View File
@@ -0,0 +1,179 @@
#!/bin/sh
# Migration 68 --> 69
# Convert RabbitMQ users to platform-minted credentials, first part.
#
# The converted rabbitmq chart renders a CredentialTemplate per user and
# points each User's importCredentialsSecret at 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
# RabbitMQ release from the per-user <release>-<user>-credentials Secrets the
# old chart generated, so clients keep logging in at every point of the
# upgrade; the controller adopts them once the templates exist. The old
# chart kept one Secret per user, holding username and password, so they are
# found by label and by the Helm release that rendered them. A release whose
# every user got its Secret is marked for seeding, so users added later are
# seeded too. The account Secret carries the label messaging-topology-operator
# caches Secrets by; without it the operator's admission webhook refuses the
# User.
#
# The second part is the cozystack-credentials-migration-68 Job, which waits
# per release for its chart to switch, then strips any users.<name>.password
# left in the values, deletes a per-user Secret Helm did not prune, and labels
# the operator's <release>-default-user Secret not tenant-visible. That Secret
# holds the administrator messaging-topology-operator logs in with. The
# converted ApplicationDefinition excludes it, which keeps it hidden on every
# rewrite by the cluster operator: that rewrite replaces the Secret's labels,
# and the lineage webhook stamps it again from the definition. The label is
# still needed for the Secret as it stands, which the webhook stamped visible
# under the old definition and leaves alone until such a rewrite. It goes on
# only once the definition in the API excludes the Secret: the rabbitmq-rd
# chart upgrades after the new cluster operator is Ready, whose first pass
# rewrites the Secret, and a label written before would be undone by it. Its
# password is not rotated here: the broker takes the default user's password
# only at first boot, so a rotation is a broker operation this Job does not
# have.
#
# The Job is created directly rather than rendered from the platform chart,
# for the reasons migration 64 gives, and runs the image this hook runs as.
# Its ServiceAccount, ClusterRole and binding carry this migration's number,
# so a conversion running in the same upgrade never deletes or re-owns
# another's identity. The ClusterRole is least-privilege: finish needs CRUD
# and list on Secrets (list, for the per-user sources), get/list/patch on
# HelmReleases, create on Events, and its state ConfigMap. The ServiceAccount
# is owned by the Job, so the garbage collector removes it with the Job; the
# ClusterRoleBinding cannot be owned by a namespaced Job and is left, granting
# to no subject once the ServiceAccount is gone. To rerun the Job by hand,
# delete it 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}"
NAME=cozystack-credentials-migration-68
credentials-migrate seed \
--migration 68 \
--kind RabbitMQ \
--format plaintext \
--accounts-path users \
--source-selector 'apps.cozystack.io/user-secret=true' \
--source-key password \
--label 'rabbitmq.com/topology-operator=true'
# The finish Job runs the same image as this hook. Read it from this pod's
# own container by name, as migration 64 does.
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 and ServiceAccount left by an earlier run of this hook: the
# pod template is immutable, and a ServiceAccount still owned by the deleted
# Job could be collected after the apply below. finish recovers its progress
# from the state ConfigMap, so recreating the Job loses nothing.
kubectl delete job "$NAME" \
--namespace "$NAMESPACE" \
--ignore-not-found
kubectl delete serviceaccount "$NAME" \
--namespace "$NAMESPACE" \
--ignore-not-found
kubectl apply --filename - <<YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: ${NAME}
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "list", "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"]
- apiGroups: ["cozystack.io"]
resources: ["applicationdefinitions"]
verbs: ["list"]
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: ${NAME}
namespace: ${NAMESPACE}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: ${NAME}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: ${NAME}
subjects:
- kind: ServiceAccount
name: ${NAME}
namespace: ${NAMESPACE}
---
apiVersion: batch/v1
kind: Job
metadata:
name: ${NAME}
namespace: ${NAMESPACE}
spec:
backoffLimit: 6
ttlSecondsAfterFinished: 604800
template:
metadata:
labels:
policy.cozystack.io/allow-to-apiserver: "true"
spec:
serviceAccountName: ${NAME}
restartPolicy: OnFailure
containers:
- name: migration
image: ${image}
command:
- credentials-migrate
- finish
- --migration=68
- --kind=RabbitMQ
- --format=plaintext
- --accounts-path=users
- --source-selector=apps.cozystack.io/user-secret=true
- --source-key=password
- --label=rabbitmq.com/topology-operator=true
- --hide-secret-suffix=-default-user
- --timeout=30m
env:
- name: CREDENTIALS_MIGRATE_ACTOR
value: system:serviceaccount:${NAMESPACE}:${NAME}
YAML
# Tie the ServiceAccount's lifetime to the Job, as migration 64 does.
job_uid=$(kubectl get job "$NAME" \
--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 "$NAME" \
--namespace "$NAMESPACE" \
--type merge \
--patch "{\"metadata\":{\"ownerReferences\":[{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\"name\":\"${NAME}\",\"uid\":\"${job_uid}\"}]}}"
stamp_cozystack_version 69
+176
View File
@@ -0,0 +1,176 @@
#!/bin/sh
# Migration 69 --> 70
# Convert the Redis password to platform-minted credentials, first part.
#
# The converted redis chart renders one CredentialTemplate, for the default
# user, while authEnabled is on, and points the RedisFailover's
# auth.secretPath at its 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 that Secret, unowned,
# for every existing Redis release from the password in <release>-auth, so
# the clients keep the password they have at every point of the upgrade.
# (Replication, the Sentinels, the probes and the exporter move to the
# operator's own internal account when the operator is upgraded,
# independently of this migration.) The controller adopts the Secret once
# the template exists. A release whose Secret was written, or that has
# authentication off, is marked for seeding.
# The Redis backup strategy reads the same account Secret, so the next
# backup authenticates with the migrated password.
#
# The hook also suspends every Redis release until the redis-operator
# Deployment runs its new revision. Every application chart switches the
# moment the platform chart moves the packages source, while the operator
# rolls out later, and the converted chart changes the pod template: the
# old operator rolls such a change by deleting the master, failing writes
# for about a minute, where the new one moves the master off first and
# applies the password with no restart. The finish Job resumes the
# releases once the new operator runs, and may read Deployments for that.
#
# The second part is the cozystack-credentials-migration-69 Job, which waits
# per release for its chart to switch, then deletes whatever is left of
# <release>-auth, which the switched chart no longer renders. The hook creates
# the Job directly, with a least-privilege ServiceAccount the Job owns, for the
# reasons migration 64 gives: a chart-rendered Job would hold up the platform
# release and fault on its immutable pod template at the next upgrade. To
# rerun it by hand, delete the Job and re-apply the manifest below.
#
# Fail-closed: migrations never re-run, so an error here stops the upgrade
# rather than stamping the version past a release that was not recorded.
set -euo pipefail
# shellcheck source=lib/cozystack-version.sh
. "$(dirname "$0")/lib/cozystack-version.sh"
NAMESPACE="${NAMESPACE:-cozy-system}"
credentials-migrate seed \
--migration 69 \
--kind Redis \
--format plaintext \
--fixed-account default \
--source-key password \
--enabled-flag authEnabled \
--source-suffix=-auth \
--hold-until-rollout cozy-redis-operator/redis-operator
# 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-69 \
--namespace "$NAMESPACE" \
--ignore-not-found
kubectl delete serviceaccount cozystack-credentials-migration-69 \
--namespace "$NAMESPACE" \
--ignore-not-found
kubectl apply --filename - <<YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: cozystack-credentials-migration-69
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"]
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get"]
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: cozystack-credentials-migration-69
namespace: ${NAMESPACE}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: cozystack-credentials-migration-69
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cozystack-credentials-migration-69
subjects:
- kind: ServiceAccount
name: cozystack-credentials-migration-69
namespace: ${NAMESPACE}
---
apiVersion: batch/v1
kind: Job
metadata:
name: cozystack-credentials-migration-69
namespace: ${NAMESPACE}
spec:
backoffLimit: 6
ttlSecondsAfterFinished: 604800
template:
metadata:
labels:
policy.cozystack.io/allow-to-apiserver: "true"
spec:
serviceAccountName: cozystack-credentials-migration-69
restartPolicy: OnFailure
containers:
- name: migration
image: ${image}
command:
- credentials-migrate
- finish
- --migration=69
- --kind=Redis
- --format=plaintext
- --fixed-account=default
- --source-key=password
- --enabled-flag=authEnabled
- --source-suffix=-auth
- --timeout=30m
env:
- name: CREDENTIALS_MIGRATE_ACTOR
value: system:serviceaccount:${NAMESPACE}:cozystack-credentials-migration-69
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-69 \
--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-69 \
--namespace "$NAMESPACE" \
--type merge \
--patch "{\"metadata\":{\"ownerReferences\":[{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\"name\":\"cozystack-credentials-migration-69\",\"uid\":\"${job_uid}\"}]}}"
stamp_cozystack_version 70
+174
View File
@@ -0,0 +1,174 @@
#!/bin/sh
# Migration 70 --> 71
# Convert the Valkey password to platform-minted credentials, first part.
#
# The converted valkey chart renders one CredentialTemplate, for the default
# user, while authEnabled is on, and points the RedisFailover's
# auth.secretPath at its 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 that Secret, unowned,
# for every existing Valkey release from the password in <release>-auth, so
# the clients keep the password they have at every point of the upgrade.
# (Replication, the Sentinels, the probes and the exporter move to the
# operator's own internal account when the operator is upgraded,
# independently of this migration.) The controller adopts the Secret once
# the template exists. A release whose Secret was written, or that has
# authentication off, is marked for seeding.
#
# The hook also suspends every Valkey release until the redis-operator
# Deployment runs its new revision. Every application chart switches the
# moment the platform chart moves the packages source, while the operator
# rolls out later, and the converted chart changes the pod template: the
# old operator rolls such a change by deleting the master, failing writes
# for about a minute, where the new one moves the master off first and
# applies the password with no restart. The finish Job resumes the
# releases once the new operator runs, and may read Deployments for that.
#
# The second part is the cozystack-credentials-migration-70 Job, which waits
# per release for its chart to switch, then deletes whatever is left of
# <release>-auth, which the switched chart no longer renders. The hook creates
# the Job directly, with a least-privilege ServiceAccount the Job owns, for the
# reasons migration 64 gives: a chart-rendered Job would hold up the platform
# release and fault on its immutable pod template at the next upgrade. To
# rerun it by hand, delete the Job and re-apply the manifest below.
#
# Fail-closed: migrations never re-run, so an error here stops the upgrade
# rather than stamping the version past a release that was not recorded.
set -euo pipefail
# shellcheck source=lib/cozystack-version.sh
. "$(dirname "$0")/lib/cozystack-version.sh"
NAMESPACE="${NAMESPACE:-cozy-system}"
credentials-migrate seed \
--migration 70 \
--kind Valkey \
--format plaintext \
--fixed-account default \
--source-key password \
--enabled-flag authEnabled \
--source-suffix=-auth \
--hold-until-rollout cozy-redis-operator/redis-operator
# 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-70 \
--namespace "$NAMESPACE" \
--ignore-not-found
kubectl delete serviceaccount cozystack-credentials-migration-70 \
--namespace "$NAMESPACE" \
--ignore-not-found
kubectl apply --filename - <<YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: cozystack-credentials-migration-70
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"]
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get"]
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: cozystack-credentials-migration-70
namespace: ${NAMESPACE}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: cozystack-credentials-migration-70
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cozystack-credentials-migration-70
subjects:
- kind: ServiceAccount
name: cozystack-credentials-migration-70
namespace: ${NAMESPACE}
---
apiVersion: batch/v1
kind: Job
metadata:
name: cozystack-credentials-migration-70
namespace: ${NAMESPACE}
spec:
backoffLimit: 6
ttlSecondsAfterFinished: 604800
template:
metadata:
labels:
policy.cozystack.io/allow-to-apiserver: "true"
spec:
serviceAccountName: cozystack-credentials-migration-70
restartPolicy: OnFailure
containers:
- name: migration
image: ${image}
command:
- credentials-migrate
- finish
- --migration=70
- --kind=Valkey
- --format=plaintext
- --fixed-account=default
- --source-key=password
- --enabled-flag=authEnabled
- --source-suffix=-auth
- --timeout=30m
env:
- name: CREDENTIALS_MIGRATE_ACTOR
value: system:serviceaccount:${NAMESPACE}:cozystack-credentials-migration-70
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-70 \
--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-70 \
--namespace "$NAMESPACE" \
--type merge \
--patch "{\"metadata\":{\"ownerReferences\":[{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\"name\":\"cozystack-credentials-migration-70\",\"uid\":\"${job_uid}\"}]}}"
stamp_cozystack_version 71
+173
View File
@@ -0,0 +1,173 @@
#!/bin/sh
# Migration 71 --> 72
# Convert Bucket users to platform-minted credentials.
#
# The converted bucket chart stops rendering a tenant user's BucketAccess and
# renders an engine-issued CredentialTemplate in its place;
# cozystack-controller then owns the BucketAccess and re-creates it on a mint.
# A BucketAccess's keys are bound to its UID (the COSI sidecar names the driver
# account after it), so a deleted and re-created BucketAccess is a new key
# pair. This hook runs before any component chart changes version and keeps
# every existing user's keys:
#
# - each tenant BucketAccess the bucket chart rendered gets
# helm.sh/resource-policy=keep, which Helm reads off the live object
# before it deletes a resource the new chart no longer renders, so the
# upgrade leaves it in place; and credentials.cozystack.io/adopt=true, which
# lets the controller take it over and copy the keys it already has into
# the account Secret. Clients keep working until the first mint.
#
# - the CredentialTemplate CRD baked into this image is applied first.
# The converted chart renders spec.bucketAccess, which a cluster that ran
# migration 64 in an earlier release lacks until cozystack-controller
# upgrades, possibly after the bucket releases switch: the API server
# would prune the field, and the controller would skip the template.
#
# - the backup bucket's system user is marked platform in its Bucket
# release, so it keeps its chart-rendered BucketAccess and its readable
# Secret whichever of the bucket chart and backupstrategy-controller is
# upgraded first. Its BucketAccess is not marked.
#
# - each tenant user's <bucket>-<user>-credentials loses its accessKey and
# secretKey, which the tenant can read. The converted bucket-system chart
# renders that Secret without them, but its upgrade cannot remove them:
# the old chart wrote them through stringData, so they are absent from the
# manifest Helm diffs against, and a three-way merge keeps a live field
# that neither manifest names (helm v3.20 pkg/kube/client.go createPatch,
# strategicpatch.CreateThreeWayMergePatch). Done here, before the chart
# switch, the keys are gone however the release is upgraded. A platform
# user's Secret keeps them.
#
# There is no finish Job and so no standing identity: once the keys are
# stripped here, the COSI Secret the sidecar writes is the only other copy,
# and it has to stay for the grant. The keep annotation is
# left on adopted BucketAccesses: Helm no longer tracks them, and the garbage
# collector removes them with their template, which the annotation does not
# affect.
#
# Fail-closed: migrations never re-run, so an error here stops the upgrade
# rather than stamping the version past a BucketAccess that was not marked.
set -euo pipefail
# shellcheck source=lib/cozystack-version.sh
. "$(dirname "$0")/lib/cozystack-version.sh"
# shellcheck source=lib/credential-crd.sh
. "$(dirname "$0")/lib/credential-crd.sh"
apply_credential_crd
# Where backupstrategy-controller provisions the backup bucket, from its
# release values when they override the chart defaults.
BACKUP_RELEASE_NAMESPACE="${BACKUP_RELEASE_NAMESPACE:-cozy-backup-controller}"
BACKUP_RELEASE_NAME="${BACKUP_RELEASE_NAME:-backupstrategy-controller}"
backup_value() {
kubectl get helmreleases.helm.toolkit.fluxcd.io "$BACKUP_RELEASE_NAME" \
--namespace "$BACKUP_RELEASE_NAMESPACE" \
--ignore-not-found \
--output "jsonpath={.spec.values.backupStorage.$1}"
}
platform_namespace=$(backup_value namespace)
platform_bucket=$(backup_value bucketName)
provision=$(backup_value provisionBucket)
platform_namespace="${platform_namespace:-tenant-root}"
platform_bucket="${platform_bucket:-cozy-backups}"
platform_release="bucket-${platform_bucket}"
platform_access="${platform_release}-system"
# Only a release that has the system user: a merge patch would otherwise add
# one to a bucket that never declared it.
if [ "$provision" != "false" ]; then
system_user=$(kubectl get helmreleases.helm.toolkit.fluxcd.io "$platform_release" \
--namespace "$platform_namespace" \
--ignore-not-found \
--output 'jsonpath={.spec.values.users.system}')
if [ -n "$system_user" ]; then
kubectl patch helmreleases.helm.toolkit.fluxcd.io "$platform_release" \
--namespace "$platform_namespace" \
--type merge \
--patch '{"spec":{"values":{"users":{"system":{"platform":true}}}}}'
fi
fi
# A cluster without the COSI API has no BucketAccess to keep.
crd=$(kubectl get customresourcedefinitions.apiextensions.k8s.io \
bucketaccesses.objectstorage.k8s.io \
--ignore-not-found \
--output name)
if [ -z "$crd" ]; then
stamp_cozystack_version 72
exit 0
fi
# One line per BucketAccessClass: name and access policy. The anonymous
# public-read access is told by its class, never by its name: with publicRead
# off a tenant user may be called public-read, and its keyed BucketAccess has
# the same name the anonymous one would.
classes=$(kubectl get bucketaccessclasses.objectstorage.k8s.io \
--output 'jsonpath={range .items[*]}{.metadata.name}{" "}{.parameters.accessPolicy}{"\n"}{end}')
# Whether a BucketAccess of this class is the keyless public-read access: its
# class grants the public-read policy, or, gone since, carries the -public
# suffix the SeaweedFS chart gives only that class.
public_class() {
_policy=$(printf '%s\n' "$classes" | awk -v class="$1" '
$1 == class { found = 1; policy = $2 }
END { if (found) print (policy == "" ? "-" : policy) }')
case "$_policy" in
public-read) return 0 ;;
"") case "$1" in *-public) return 0 ;; esac ;;
esac
return 1
}
# One line per BucketAccess: namespace, name, the Helm release that rendered
# it, its class, and the kind of its controller, if any.
accesses=$(kubectl get bucketaccesses.objectstorage.k8s.io \
--all-namespaces \
--output 'jsonpath={range .items[*]}{.metadata.namespace}{" "}{.metadata.name}{" "}{.metadata.annotations.meta\.helm\.sh/release-name}{" "}{.spec.bucketAccessClassName}{" "}{.metadata.ownerReferences[?(@.controller==true)].kind}{"\n"}{end}')
printf '%s\n' "$accesses" | while read -r namespace name release class controller; do
[ -n "$name" ] || continue
# Only what a bucket chart rendered for one of its users.
case "$release" in bucket-*) ;; *) continue ;; esac
case "$name" in "${release}"-?*) ;; *) continue ;; esac
# The anonymous public-read access has no keys and stays chart-rendered.
if public_class "$class"; then
continue
fi
# The backup bucket's system user stays a chart-rendered platform account.
if [ "$namespace" = "$platform_namespace" ] && [ "$name" = "$platform_access" ]; then
continue
fi
# Strip the keys from the tenant-readable Secret, checked without reading
# them, and patched only when one is there: a merge patch of null removes a
# key and leaves endpoint and bucketName in place.
secret="${name}-credentials"
held=$(kubectl get secrets "$secret" \
--namespace "$namespace" \
--ignore-not-found \
--output 'go-template={{with .data}}{{if or (index . "accessKey") (index . "secretKey")}}held{{end}}{{end}}')
if [ -n "$held" ]; then
kubectl patch secrets "$secret" \
--namespace "$namespace" \
--type merge \
--patch '{"data":{"accessKey":null,"secretKey":null}}'
echo "removed the keys from Secret $namespace/$secret"
fi
# Already taken over.
[ -z "$controller" ] || continue
kubectl annotate bucketaccesses.objectstorage.k8s.io "$name" \
--namespace "$namespace" \
--overwrite \
helm.sh/resource-policy=keep
kubectl label bucketaccesses.objectstorage.k8s.io "$name" \
--namespace "$namespace" \
--overwrite \
credentials.cozystack.io/adopt=true
echo "marked BucketAccess $namespace/$name for adoption"
done
stamp_cozystack_version 72
@@ -0,0 +1,29 @@
# shellcheck shell=sh
# Shared helper for applying the CredentialTemplate CRD during migrations.
#
# The CRD ships with cozystack-controller, whose release can upgrade minutes
# after the tenant releases switch charts. A converted chart that renders a
# CredentialTemplate, or a field the installed CRD does not have yet, fails
# (or has the field pruned) in between, so a conversion that needs the CRD
# applies the copy baked into the migrations image before any chart
# switches. It is labelled and annotated as owned by the cozystack-controller
# release, as that release's later upgrade expects to find it.
#
# Sourced, not executed. A migration that needs it does:
# . "$(dirname "$0")/lib/credential-crd.sh"
# apply_credential_crd
# apply_credential_crd
# Server-side apply the baked CRD, hand it to the cozystack-controller Helm
# release, and wait until it is established. $CREDENTIAL_CRD_FILE overrides
# the path, for the tests. Every step fails the migration on error, under the
# caller's set -e.
apply_credential_crd() {
_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
}
+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: 68
targetVersion: 72
# 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
@@ -6,6 +6,11 @@ metadata:
namespace: {{ .Values.backupStorage.namespace }}
spec:
users:
# A platform user: its keys stay in the bucket-system Secret this
# controller reads (backupStorage.systemSecretName), which no tenant
# role selects, and it gets no CredentialTemplate whose mint would
# rotate them under every default backup.
system:
readonly: false
platform: true
{{- end }}
@@ -82,14 +82,15 @@ spec:
{{- end }}
env:
{{- /*
Redis password, when the app has authEnabled (the default). The chart
emits the Secret <prefix><app>-auth; mount it optionally so a no-auth
app still schedules.
Redis password, when the app has authEnabled (the default): the
account Secret <prefix><app>.default.account of its default
CredentialTemplate, which a mint rewrites. Mount it optionally so a
no-auth app still schedules.
*/}}
- name: REDIS_PASSWORD
valueFrom:
secretKeyRef:
name: {{ printf `{{ .Release.Prefix | default "redis-" }}{{ .Release.Name }}-auth` | quote }}
name: {{ printf `{{ .Release.Prefix | default "redis-" }}{{ .Release.Name }}.default.account` | quote }}
key: password
optional: true
{{- /*
@@ -42,6 +42,14 @@ tests:
path: metadata.namespace
value: tenant-root
template: templates/bucket.yaml
# The system user is a platform account: its keys stay in the Secret
# this controller reads, and no tenant credential can rotate them.
- equal:
path: spec.users.system
value:
readonly: false
platform: true
template: templates/bucket.yaml
- hasDocuments:
count: 0
template: templates/strategy-cnpg-default.yaml
@@ -92,3 +92,19 @@ tests:
content:
name: S3_INSECURE_SKIP_VERIFY
value: "true"
- it: "reads the password from the account Secret of the app's default account"
asserts:
# The app's chart no longer renders <app>-auth: the password lives in the
# account Secret of its default CredentialTemplate, which a mint
# rewrites, so the next backup authenticates with the new password. The
# reference stays optional so an app without authentication schedules.
- contains:
path: spec.template.spec.containers[0].env
content:
name: REDIS_PASSWORD
valueFrom:
secretKeyRef:
name: '{{ .Release.Prefix | default "redis-" }}{{ .Release.Name }}.default.account'
key: password
optional: true
+1 -1
View File
@@ -8,7 +8,7 @@ spec:
plural: buckets
singular: bucket
openAPISchema: |-
{"title":"Chart Values","type":"object","properties":{"locking":{"description":"Provisions bucket from the `-lock` BucketClass (with object lock enabled).","type":"boolean","default":false},"lockingDefaultRetention":{"description":"With `locking`, keeps the default retention of the `-lock` BucketClass (COMPLIANCE, 365 days). Set to `false` to provision from the `-lock-noretention` BucketClass instead: Object Lock is enabled with no default retention, and retention is then set on the bucket or per object through the S3 API. Read at creation only.","type":"boolean","default":true},"storagePool":{"description":"Selects a specific BucketClass by storage pool name.","type":"string","default":"","x-cozystack-options":{"source":"storagepool"}},"ui":{"description":"Deploys the web UI (s3manager) with its Service and its Ingress or HTTPRoute at `<bucket>.<tenant host>`. Set to `false` to run the bucket without them.","type":"boolean","default":true},"publicRead":{"description":"Serves the bucket's objects to anyone without credentials at `<endpoint>/<bucket>/<key>`. Anonymous callers can read objects but cannot list the bucket or write to it.","type":"boolean","default":false},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"readonly":{"description":"Whether the user has read-only access.","type":"boolean"}}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}}
{"title":"Chart Values","type":"object","properties":{"locking":{"description":"Provisions bucket from the `-lock` BucketClass (with object lock enabled).","type":"boolean","default":false},"lockingDefaultRetention":{"description":"With `locking`, keeps the default retention of the `-lock` BucketClass (COMPLIANCE, 365 days). Set to `false` to provision from the `-lock-noretention` BucketClass instead: Object Lock is enabled with no default retention, and retention is then set on the bucket or per object through the S3 API. Read at creation only.","type":"boolean","default":true},"storagePool":{"description":"Selects a specific BucketClass by storage pool name.","type":"string","default":"","x-cozystack-options":{"source":"storagepool"}},"ui":{"description":"Deploys the web UI (s3manager) with its Service and its Ingress or HTTPRoute at `<bucket>.<tenant host>`. Set to `false` to run the bucket without them.","type":"boolean","default":true},"publicRead":{"description":"Serves the bucket's objects to anyone without credentials at `<endpoint>/<bucket>/<key>`. Anonymous callers can read objects but cannot list the bucket or write to it.","type":"boolean","default":false},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"platform":{"description":"Marks a platform account, such as the `system` user of the backup bucket, which backupstrategy-controller sets. Its keys stay in the `<bucket>-<user>-credentials` Secret, which no tenant can read, and are never minted. Clearing it drops the chart-rendered BucketAccess, which revokes those keys, and the user becomes a normal account whose keys are minted through its Credential. Leave it unset for your own users.","type":"boolean"},"readonly":{"description":"Whether the user has read-only access.","type":"boolean"}}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}}
release:
prefix: bucket-
labels:
@@ -36,23 +36,46 @@
to every bucket needs a controller that owns them and is tracked
separately.
*/}}
{{- /*
What the Secret holds depends on who consumes the user. A tenant user's keys
live in the account Secret of its CredentialTemplate and are shown only by a
mint, so its Secret here carries the endpoint and bucket name, which are not
secret. A platform user (users.<name>.platform) has no template: its Secret
keeps the keys for the platform component that reads it, and is labelled so
the tenant Secret view and the dashboard leave it out.
*/}}
{{- range $name, $user := .Values.users }}
{{- $secretName := printf "%s-%s" $.Values.bucketName $name }}
{{- $existingSecret := lookup "v1" "Secret" $.Release.Namespace $secretName }}
{{- if $existingSecret }}
{{- $bucketInfo := fromJson (b64dec (index $existingSecret.data "BucketInfo")) }}
{{- $platform := default false $user.platform }}
---
apiVersion: v1
kind: Secret
metadata:
name: {{ $secretName }}-credentials
labels:
{{- if $platform }}
internal.cozystack.io/tenantresource: "false"
{{- else }}
apps.cozystack.io/user-secret: "true"
{{- end }}
type: Opaque
stringData:
accessKey: {{ index $bucketInfo.spec.secretS3 "accessKeyID" | quote }}
secretKey: {{ index $bucketInfo.spec.secretS3 "accessSecretKey" | quote }}
endpoint: {{ index $bucketInfo.spec.secretS3 "endpoint" | trimPrefix "https://" | trimPrefix "http://" | quote }}
bucketName: {{ index $bucketInfo.spec "bucketName" | quote }}
{{- /*
data rather than stringData: Helm's three-way merge removes a live key only
when the previous manifest named it, and a stringData key never appears in
data, so a key dropped from stringData stays in the Secret. Rendered as
data, a key this chart stops emitting is removed on the upgrade that drops
it. The keys the stringData chart left on tenant users are stripped by
platform migration 71.
*/}}
data:
{{- if $platform }}
accessKey: {{ index $bucketInfo.spec.secretS3 "accessKeyID" | b64enc | quote }}
secretKey: {{ index $bucketInfo.spec.secretS3 "accessSecretKey" | b64enc | quote }}
{{- end }}
endpoint: {{ index $bucketInfo.spec.secretS3 "endpoint" | trimPrefix "https://" | trimPrefix "http://" | b64enc | quote }}
bucketName: {{ index $bucketInfo.spec "bucketName" | b64enc | quote }}
{{- end }}
{{- end }}
@@ -78,3 +78,77 @@ tests:
- equal:
path: metadata.name
value: bucket-cozy-backups-ui
# With the COSI Secrets present (kubernetesProvider), what the per-user
# Secret holds depends on who consumes the user: a tenant user's keys live
# in its account Secret and are shown only by a mint, a platform user keeps
# them here, hidden from tenants.
- it: "a tenant user's Secret carries the endpoint and bucket name, no keys"
templates:
- templates/user-credentials.yaml
set:
<<: *base
users:
web: {}
kubernetesProvider: &cosiSecrets
scheme:
"v1/Secret":
gvr:
version: "v1"
resource: "secrets"
namespaced: true
objects:
- kind: Secret
apiVersion: v1
metadata:
name: bucket-cozy-backups-web
namespace: tenant-root
data:
BucketInfo: eyJtZXRhZGF0YSI6eyJuYW1lIjoiYmMtdWlkIn0sInNwZWMiOnsiYnVja2V0TmFtZSI6ImJ1Y2tldC1jbGFpbS11aWQiLCJzZWNyZXRTMyI6eyJlbmRwb2ludCI6Imh0dHBzOi8vczMuZXhhbXBsZS5vcmciLCJhY2Nlc3NLZXlJRCI6IkFLSUFURVNUIiwiYWNjZXNzU2VjcmV0S2V5IjoidGVzdC1zZWNyZXQifX19
- kind: Secret
apiVersion: v1
metadata:
name: bucket-cozy-backups-system
namespace: tenant-root
data:
BucketInfo: eyJtZXRhZGF0YSI6eyJuYW1lIjoiYmMtdWlkIn0sInNwZWMiOnsiYnVja2V0TmFtZSI6ImJ1Y2tldC1jbGFpbS11aWQiLCJzZWNyZXRTMyI6eyJlbmRwb2ludCI6Imh0dHBzOi8vczMuZXhhbXBsZS5vcmciLCJhY2Nlc3NLZXlJRCI6IkFLSUFURVNUIiwiYWNjZXNzU2VjcmV0S2V5IjoidGVzdC1zZWNyZXQifX19
asserts:
- hasDocuments:
count: 1
- equal:
path: metadata.labels
value:
apps.cozystack.io/user-secret: "true"
- equal:
path: data
value:
endpoint: czMuZXhhbXBsZS5vcmc=
bucketName: YnVja2V0LWNsYWltLXVpZA==
# Rendered as data, so a key the chart stops emitting is removed by
# Helm's three-way merge on the upgrade that drops it.
- notExists:
path: stringData
- it: "a platform user's Secret keeps the keys and is hidden from tenants"
templates:
- templates/user-credentials.yaml
set:
<<: *base
users:
system:
platform: true
kubernetesProvider: *cosiSecrets
asserts:
- hasDocuments:
count: 1
- equal:
path: metadata.labels
value:
internal.cozystack.io/tenantresource: "false"
- equal:
path: data
value:
accessKey: QUtJQVRFU1Q=
secretKey: dGVzdC1zZWNyZXQ=
endpoint: czMuZXhhbXBsZS5vcmc=
bucketName: YnVja2V0LWNsYWltLXVpZA==
@@ -59,6 +59,37 @@ spec:
Secret that stores its password. A kind's chart renders one per account; a
tenant cannot write it.
properties:
bucketAccess:
description: |-
BucketAccess makes the account engine-issued: it names the BucketAccess
whose COSI grant issues the account's keys, which the platform cannot
choose. cozystack-controller creates and owns it, re-creates it on a
mint, and deletes it on a revoke. The keys are stored as they are
issued, so the format is plaintext.
properties:
bucketAccessClassName:
description: BucketAccessClassName is the class that sets the
access policy.
minLength: 1
type: string
bucketClaimName:
description: BucketClaimName is the BucketClaim the access is
granted on.
minLength: 1
type: string
name:
description: Name of the BucketAccess and of the Secret the COSI
sidecar writes.
minLength: 1
type: string
required:
- bucketAccessClassName
- bucketClaimName
- name
type: object
x-kubernetes-validations:
- message: bucketAccess.name is immutable
rule: self.name == oldSelf.name
format:
description: Format is how a password is stored in the account Secret.
properties:
@@ -106,6 +137,10 @@ spec:
- format
- username
type: object
x-kubernetes-validations:
- message: a template with bucketAccess stores its keys in the plaintext
format
rule: '!has(self.bucketAccess) || self.format.name == ''plaintext'''
status:
description: |-
CredentialTemplateStatus mirrors the record the account Secret keeps, so the
@@ -64,6 +64,19 @@ rules:
# writes their Ready status. It never creates or deletes a sentinel; that is
# the chart's (helm-controller's) job. No tenant role grants any verb on
# internal.cozystack.io, which is what keeps sentinels out of tenant reach.
# COSICredentialReconciler creates the BucketAccess an engine-issued
# CredentialTemplate names, adopts one the conversion marked, and deletes it on
# a mint or a revoke, which makes the COSI sidecar revoke the old keys,
# re-creating it for a mint. No tenant role grants any verb on
# objectstorage.k8s.io.
- apiGroups: ["objectstorage.k8s.io"]
resources: ["bucketaccesses"]
verbs: ["get", "list", "watch", "create", "update", "delete"]
# It reads the class and the claim of a BucketAccess the sidecar has not
# finalized, to tell whether a deleted template can release it at once.
- apiGroups: ["objectstorage.k8s.io"]
resources: ["bucketaccessclasses", "bucketclaims"]
verbs: ["get"]
- apiGroups: ["internal.cozystack.io"]
resources: ["tenantprojections"]
verbs: ["get", "list", "watch"]
@@ -36,3 +36,20 @@ tests:
apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- it: lets the COSI credentials reconciler re-create BucketAccesses
documentSelector:
path: kind
value: ClusterRole
asserts:
- contains:
path: rules
content:
apiGroups: ["objectstorage.k8s.io"]
resources: ["bucketaccesses"]
verbs: ["get", "list", "watch", "create", "update", "delete"]
- contains:
path: rules
content:
apiGroups: ["objectstorage.k8s.io"]
resources: ["bucketaccessclasses", "bucketclaims"]
verbs: ["get"]
+8 -7
View File
@@ -8,7 +8,7 @@ spec:
plural: rabbitmqs
singular: rabbitmq
openAPISchema: |-
{"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of RabbitMQ replicas.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each RabbitMQ replica. Every resource left unset here is taken from `resourcesPreset`.","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. It supplies every resource `resources` does not set, not only a `resources` left empty entirely.","type":"string","default":"s1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"affinity":{"description":"Pod affinity applied to RabbitMQ pods (standard Kubernetes corev1.Affinity). Use podAntiAffinity with topologyKey `kubernetes.io/hostname` to spread RabbitMQ pods across nodes.","type":"object","default":{},"x-kubernetes-preserve-unknown-fields":true},"tls":{"description":"TLS configuration. TLS is off unless `tls.enabled` is set to true.","type":"object","default":{},"properties":{"disableNonTLSListeners":{"description":"Close the plaintext AMQP (5672) and management (15672) listeners. This is a broker-level switch: it drops in-cluster clients as well as external ones, and it cannot be combined with `users` or `vhosts`. Erlang distribution (25672) and epmd (4369) stay plaintext regardless. Defaults to false.","type":"boolean"},"enabled":{"description":"Enable TLS for AMQPS (5671) and Management HTTPS (15671). Applies whether or not `external` is set. Plaintext AMQP (5672) and management (15672) keep serving unless `disableNonTLSListeners` is set as well. Moves the `port` key of the `<release>-default-user` Secret from 5672 to 5671, and the metrics port from 15692 to 15691. Defaults to false.","type":"boolean"}}},"version":{"description":"RabbitMQ major.minor version to deploy","type":"string","default":"v4.2","enum":["v4.2","v4.1","v4.0","v3.13"]},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user.","type":"string"}}}},"vhosts":{"description":"Virtual hosts configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","required":["roles"],"properties":{"roles":{"description":"Virtual host roles list.","type":"object","properties":{"admin":{"description":"List of admin users.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of readonly users.","type":"array","items":{"type":"string"}}}}}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}}
{"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of RabbitMQ replicas.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each RabbitMQ replica. Every resource left unset here is taken from `resourcesPreset`.","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. It supplies every resource `resources` does not set, not only a `resources` left empty entirely.","type":"string","default":"s1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"affinity":{"description":"Pod affinity applied to RabbitMQ pods (standard Kubernetes corev1.Affinity). Use podAntiAffinity with topologyKey `kubernetes.io/hostname` to spread RabbitMQ pods across nodes.","type":"object","default":{},"x-kubernetes-preserve-unknown-fields":true},"tls":{"description":"TLS configuration. TLS is off unless `tls.enabled` is set to true.","type":"object","default":{},"properties":{"disableNonTLSListeners":{"description":"Close the plaintext AMQP (5672) and management (15672) listeners. This is a broker-level switch: it drops in-cluster clients as well as external ones, and it cannot be combined with `users` or `vhosts`. Erlang distribution (25672) and epmd (4369) stay plaintext regardless. Defaults to false.","type":"boolean"},"enabled":{"description":"Enable TLS for AMQPS (5671) and Management HTTPS (15671). Applies whether or not `external` is set. Plaintext AMQP (5672) and management (15672) keep serving unless `disableNonTLSListeners` is set as well. Moves the `port` key of the `<release>-default-user` Secret from 5672 to 5671, and the metrics port from 15692 to 15691. Defaults to false.","type":"boolean"}}},"version":{"description":"RabbitMQ major.minor version to deploy","type":"string","default":"v4.2","enum":["v4.2","v4.1","v4.0","v3.13"]},"users":{"description":"Users configuration map. Each user is a RabbitMQ user that messaging-topology-operator keeps from an account Secret the platform holds. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. The operator applies either to the broker within seconds. A `password` key here is ignored. The administrator in `<release>-default-user` belongs to the platform and is not shown to tenants.","type":"object","default":{},"additionalProperties":{"type":"object"}},"vhosts":{"description":"Virtual hosts configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","required":["roles"],"properties":{"roles":{"description":"Virtual host roles list.","type":"object","properties":{"admin":{"description":"List of admin users.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of readonly users.","type":"array","items":{"type":"string"}}}}}}},"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 oLine truncated
release:
prefix: rabbitmq-
labels:
@@ -40,16 +40,19 @@ spec:
# Bounded, not absolute: matching is exact-name with no globs, so a Secret a
# future operator version introduces stays in scope of the label-only
# include. The primary defence is the lineage webhook stamping only what it
# can attribute; this closes the enumerable set. -default-user is excluded
# from the exclusion on purpose — it is included by name below.
# can attribute; this closes the enumerable set.
#
# -default-user holds the administrator messaging-topology-operator logs
# in with, a platform account no tenant reads. The tenant accounts live in
# account Secrets that no definition selects: the credentials API shows a
# password once, in the response of the mint that issued it.
exclude:
- resourceNames:
- rabbitmq-{{ .name }}-ca
- rabbitmq-{{ .name }}-tls
- rabbitmq-{{ .name }}-erlang-cookie
include:
- resourceNames:
- rabbitmq-{{ .name }}-default-user
include:
# The key-free trust anchor the CA-extraction controller publishes. The
# chart names its own CA Secret in a TenantProjection sentinel, and the
# controller stamps this label on the projection it writes from that
@@ -58,8 +61,6 @@ spec:
# engine shares; it carries no per-release name templating.
- matchLabels:
internal.cozystack.io/tenant-ca: "true"
- matchLabels:
apps.cozystack.io/user-secret: "true"
services:
exclude: []
include:
+5 -3
View File
@@ -8,7 +8,7 @@ spec:
plural: redises
singular: redis
openAPISchema: |-
{"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Redis replicas. Three Sentinels watch them, or a single one when `replicas` is 1, since a lone pod has no replica to fail over to.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each Redis replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"affinity":{"description":"Kubernetes affinity configuration for Redis and Sentinel pods.","type":"object","default":{},"properties":{"redis":{"description":"Kubernetes Affinity for Redis pods. When set, redis-operator uses it verbatim and does not add its default soft podAntiAffinity; include podAntiAffinity unless replica co-location is intended.","type":"object","default":{},"x-kubernetes-preserve-unknown-fields":true},"sentinel":{"description":"Kubernetes Affinity for Sentinel pods. When set, redis-operator uses it verbatim and does not add its default soft podAntiAffinity; include podAntiAffinity unless replica co-location is intended.","type":"object","default":{},"x-kubernetes-preserve-unknown-fields":true}}},"size":{"description":"Persistent Volume Claim size available for application data.","default":"1Gi","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. Can be enabled only when the instance is created, together with `tls.enabled: true`; turning it on for an existing instance, or changing `tls.enabled` while it is on, is refused at admission.","type":"boolean","default":false},"version":{"description":"Redis major version to deploy. The Redis and Sentinel pods run the same image.","type":"string","default":"v8","enum":["v8","v7"]},"tls":{"description":"TLS configuration. TLS is opt-in and is not inferred from `external`.","type":"object","default":{},"properties":{"authClients":{"description":"Maps to the Redis `tls-auth-clients` directive. Defaults to `no` — the server certificate is presented but client certificates are not validated. `yes` requires a client certificate signed by this release's CA, which the platform does not issue. Changing it restarts the Redis and Sentinel pods, because the directive is read from the config file once at startup.","type":"string","enum":["no","optional","yes"]},"enabled":{"description":"Enable TLS for Redis and Sentinel connections. Disabled unless set. Enabling it moves Redis and Sentinel to a TLS-only listener, so existing plaintext clients must be migrated at the same time. Encryption is provided by the redis-operator fork that mounts the certificate Secret into both Redis and Sentinel pods at `/tls`.","type":"boolean"}}},"authEnabled":{"description":"Enable password generation.","type":"boolean","default":true},"minReplicasToWrite":{"description":"Redis `min-replicas-to-write`: the master refuses writes unless at least this many replicas are connected and within `minReplicasMaxLag`. Unset by default, which leaves the Redis default (disabled). With `replicas: 2` and a value of 1 the master rejects writes while its only replica is down, trading availability for a bound on the writes lost if an isolated master is failed over. Replication stays asynchronous, so this bounds the loss, it does not remove it. Must be 0 or more and below `replicas` (a mLine truncated
{"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Redis replicas. Three Sentinels watch them, or a single one when `replicas` is 1, since a lone pod has no replica to fail over to.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each Redis replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"affinity":{"description":"Kubernetes affinity configuration for Redis and Sentinel pods.","type":"object","default":{},"properties":{"redis":{"description":"Kubernetes Affinity for Redis pods. When set, redis-operator uses it verbatim and does not add its default soft podAntiAffinity; include podAntiAffinity unless replica co-location is intended.","type":"object","default":{},"x-kubernetes-preserve-unknown-fields":true},"sentinel":{"description":"Kubernetes Affinity for Sentinel pods. When set, redis-operator uses it verbatim and does not add its default soft podAntiAffinity; include podAntiAffinity unless replica co-location is intended.","type":"object","default":{},"x-kubernetes-preserve-unknown-fields":true}}},"size":{"description":"Persistent Volume Claim size available for application data.","default":"1Gi","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. Can be enabled only when the instance is created, together with `tls.enabled: true`; turning it on for an existing instance, or changing `tls.enabled` while it is on, is refused at admission.","type":"boolean","default":false},"version":{"description":"Redis major version to deploy. The Redis and Sentinel pods run the same image.","type":"string","default":"v8","enum":["v8","v7"]},"tls":{"description":"TLS configuration. TLS is opt-in and is not inferred from `external`.","type":"object","default":{},"properties":{"authClients":{"description":"Maps to the Redis `tls-auth-clients` directive. Defaults to `no` — the server certificate is presented but client certificates are not validated. `yes` requires a client certificate signed by this release's CA, which the platform does not issue. Changing it restarts the Redis and Sentinel pods, because the directive is read from the config file once at startup.","type":"string","enum":["no","optional","yes"]},"enabled":{"description":"Enable TLS for Redis and Sentinel connections. Disabled unless set. Enabling it moves Redis and Sentinel to a TLS-only listener, so existing plaintext clients must be migrated at the same time. Encryption is provided by the redis-operator fork that mounts the certificate Secret into both Redis and Sentinel pods at `/tls`.","type":"boolean"}}},"authEnabled":{"description":"Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password.","type":"boolean","default":true},"minReplicasToWrite":{"description":"Redis `min-replicas-to-write`: the master refuses writes unless at least this many replicas are connected and within `minReplicasMaxLag`. Unset by default, which leaves the Redis default (disabled). With `replicas: 2` and a value of 1 the master rejeLine truncated
release:
prefix: redis-
labels:
@@ -59,9 +59,11 @@ spec:
# of its labels, so it is the one of the three a lineage walk can
# resolve at all.
- redis-{{ .name }}.ca-cert
# The operator's internal account, which replication, the Sentinels,
# the probes and the exporter authenticate with. It carries an
# ownerReference to the RedisFailover, as the CA-only copy does.
- rfr-redis-{{ .name }}-internal
include:
- resourceNames:
- redis-{{ .name }}-auth
# 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.
+7 -4
View File
@@ -8,7 +8,7 @@ spec:
plural: valkeys
singular: valkey
openAPISchema: |-
{"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Valkey replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each Valkey replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"1Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"Valkey major version to deploy","type":"string","default":"v8","enum":["v8","v7"]},"authEnabled":{"description":"Enable password generation.","type":"boolean","default":true},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}}
{"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Valkey replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each Valkey replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"1Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"Valkey major version to deploy","type":"string","default":"v8","enum":["v8","v7"]},"authEnabled":{"description":"Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password.","type":"boolean","default":true},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}}
release:
prefix: valkey-
labels:
@@ -27,10 +27,13 @@ spec:
icon: PHN2ZyB3aWR0aD0iMTQ0IiBoZWlnaHQ9IjE0NCIgdmlld0JveD0iMCAwIDE0NCAxNDQiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPHJlY3Qgd2lkdGg9IjE0NCIgaGVpZ2h0PSIxNDQiIHJ4PSIyNCIgZmlsbD0idXJsKCN2YWxrZXlfYmcpIi8+CiAgPHBhdGggZD0iTTM2IDQwaDE4bDE4IDQ0IDE4LTQ0aDE4TDgwIDEwOGgtMTZMMzYgNDB6IiBmaWxsPSIjZmZmZmZmIi8+CiAgPGNpcmNsZSBjeD0iNzIiIGN5PSI1MiIgcj0iNyIgZmlsbD0iI2ZmZmZmZiIvPgogIDxkZWZzPgogICAgPGxpbmVhckdyYWRpZW50IGlkPSJ2YWxrZXlfYmciIHgxPSIwIiB5MT0iMCIgeDI9IjE0NCIgeTI9IjE0NCIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPgogICAgICA8c3RvcCBzdG9wLWNvbG9yPSIjN0EzQkZGIi8+CiAgICAgIDxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iI0M2MjQ5QiIvPgogICAgPC9saW5lYXJHcmFkaWVudD4KICA8L2RlZnM+Cjwvc3ZnPgo=
keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "replicas"], ["spec", "resources"], ["spec", "resourcesPreset"], ["spec", "size"], ["spec", "storageClass"], ["spec", "external"], ["spec", "version"], ["spec", "authEnabled"], ["spec", "schedulingClass"]]
secrets:
exclude: []
include:
exclude:
# The operator's internal account, which replication, the Sentinels,
# the probes and the exporter authenticate with. It carries an
# ownerReference to the RedisFailover, so a lineage walk resolves it.
- resourceNames:
- valkey-{{ .name }}-auth
- rfr-valkey-{{ .name }}-internal
include: []
services:
exclude: []
include:
@@ -136,6 +136,11 @@ type CredentialRequestStatus struct {
// shown once.
// +optional
Password string `json:"password,omitempty"`
// AccessKeyID is the access key that goes with Password, for an account
// whose engine issues a key pair (a template with bucketAccess); present
// in a mint's answer only and shown once.
// +optional
AccessKeyID string `json:"accessKeyID,omitempty"`
// IssuedAt is when the operation took effect in the record.
IssuedAt metav1.Time `json:"issuedAt,omitempty"`
}
+15 -5
View File
@@ -117,6 +117,9 @@ type Config struct {
GenericConfig *genericapiserver.RecommendedConfig
ResourceConfig *config.ResourceConfig
ServeSDN bool
// CredentialsCOSIWait bounds the wait of a mint or a revoke on an
// engine-issued credential; zero keeps the default.
CredentialsCOSIWait time.Duration
}
// CozyServer holds the state for the Kubernetes master/api server.
@@ -125,9 +128,10 @@ type CozyServer struct {
}
type completedConfig struct {
GenericConfig genericapiserver.CompletedConfig
ResourceConfig *config.ResourceConfig
ServeSDN bool
GenericConfig genericapiserver.CompletedConfig
ResourceConfig *config.ResourceConfig
ServeSDN bool
CredentialsCOSIWait time.Duration
}
// CompletedConfig embeds a private pointer that cannot be created outside of this package.
@@ -141,6 +145,7 @@ func (cfg *Config) Complete() CompletedConfig {
cfg.GenericConfig.Complete(),
cfg.ResourceConfig,
cfg.ServeSDN,
cfg.CredentialsCOSIWait,
}
return CompletedConfig{&c}
@@ -239,7 +244,7 @@ func (c completedConfig) New() (*CozyServer, error) {
if err != nil {
return nil, fmt.Errorf("failed to build dynamic client: %w", err)
}
if err := InstallStaticAPIGroups(s.GenericAPIServer, cli, watchCli, dyn, c.ServeSDN); err != nil {
if err := InstallStaticAPIGroups(s.GenericAPIServer, cli, watchCli, dyn, c.ServeSDN, c.CredentialsCOSIWait); err != nil {
return nil, err
}
@@ -261,7 +266,9 @@ func (c completedConfig) New() (*CozyServer, error) {
// another server owns the group: kube-aggregator still merges this server's
// /openapi/v3 index, so both backends list the group-version and fetching its
// OpenAPI fails on a redirect whenever the two disagree on the hash.
func InstallStaticAPIGroups(server *genericapiserver.GenericAPIServer, cli client.Client, watchCli client.WithWatch, dyn dynamic.Interface, serveSDN bool) error {
// credentialsCOSIWait bounds the wait of a mint or a revoke on an
// engine-issued credential; zero keeps the default.
func InstallStaticAPIGroups(server *genericapiserver.GenericAPIServer, cli client.Client, watchCli client.WithWatch, dyn dynamic.Interface, serveSDN bool, credentialsCOSIWait time.Duration) error {
// --- static, cluster-scoped resource for core group ---
coreV1alpha1Storage := map[string]rest.Storage{}
coreV1alpha1Storage["tenantnamespaces"] = cozyregistry.RESTInPeace(
@@ -283,6 +290,9 @@ func InstallStaticAPIGroups(server *genericapiserver.GenericAPIServer, cli clien
tapstorage.NewREST(dyn),
)
credentials := credentialstorage.NewREST(cli, watchCli)
if credentialsCOSIWait > 0 {
credentials.SetCOSIWait(credentialsCOSIWait)
}
coreV1alpha1Storage["credentials"] = cozyregistry.RESTInPeace(credentials)
coreV1alpha1Storage["credentials/mint"] = credentialstorage.NewMintREST(credentials)
coreV1alpha1Storage["credentials/revoke"] = credentialstorage.NewRevokeREST(credentials)
+1 -1
View File
@@ -63,7 +63,7 @@ func startStaticGroupsServer(t *testing.T, serveSDN bool) *httptest.Server {
}
cli := fake.NewClientBuilder().Build()
dyn := dynamicfake.NewSimpleDynamicClient(runtime.NewScheme())
if err := apiserver.InstallStaticAPIGroups(srv, cli, cli, dyn, serveSDN); err != nil {
if err := apiserver.InstallStaticAPIGroups(srv, cli, cli, dyn, serveSDN, 0); err != nil {
t.Fatal(err)
}
srv.PrepareRun()
+14 -3
View File
@@ -35,6 +35,7 @@ import (
sdnv1alpha1 "github.com/cozystack/cozystack/pkg/apis/sdn/v1alpha1"
"github.com/cozystack/cozystack/pkg/apiserver"
"github.com/cozystack/cozystack/pkg/config"
credentialstorage "github.com/cozystack/cozystack/pkg/registry/core/credential"
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
@@ -78,6 +79,12 @@ type CozyServerOptions struct {
// ServeSDN installs the sdn.cozystack.io group; off where another
// aggregated server owns it.
ServeSDN bool
// CredentialsCOSIWait bounds how long a mint or a revoke of an
// engine-issued credential waits for cozystack-controller to serve it,
// with a new grant or with the old one gone, before it answers a retryable
// timeout.
CredentialsCOSIWait time.Duration
}
// NewCozyServerOptions returns a new instance of CozyServerOptions
@@ -176,6 +183,9 @@ func NewCommandStartCozyServer(ctx context.Context, defaults *CozyServerOptions)
flags.IntVar(&o.HelmReleaseMaxHistory, "helmrelease-max-history", o.HelmReleaseMaxHistory,
"Number of release revisions Helm keeps for HelmReleases generated from Application "+
"resources (Spec.MaxHistory). 0 means unlimited; 5 matches Helm's default.")
flags.DurationVar(&o.CredentialsCOSIWait, "credentials-cosi-wait", credentialstorage.DefaultCOSIWait,
"How long a mint or a revoke of a credential whose keys a COSI driver issues waits for "+
"cozystack-controller to serve it before it answers a retryable timeout.")
flags.BoolVar(&o.ServeSDN, "serve-sdn", o.ServeSDN,
"Serve the sdn.cozystack.io API group. Turn off where another aggregated API server owns the group.")
@@ -496,9 +506,10 @@ func (o *CozyServerOptions) Config() (*apiserver.Config, error) {
}
config := &apiserver.Config{
GenericConfig: serverConfig,
ResourceConfig: o.ResourceConfig,
ServeSDN: o.ServeSDN,
GenericConfig: serverConfig,
ResourceConfig: o.ResourceConfig,
ServeSDN: o.ServeSDN,
CredentialsCOSIWait: o.CredentialsCOSIWait,
}
return config, nil
}
+30
View File
@@ -59,6 +59,30 @@ const (
PasswordKey = "password"
)
// What the API and the controller share about an engine-issued account, one
// whose template names a BucketAccess and whose keys the COSI driver issues:
// the secret key is the password, stored as issued in the plaintext format,
// the access key sits beside it, and a mint or a revoke is a request the
// controller serves by re-creating the BucketAccess, or, for a revoke, by
// deleting it.
const (
// BucketAccessAnnotation on an account Secret names the BucketAccess whose
// grant issues its keys, which marks the account engine-issued.
BucketAccessAnnotation = "credentials.cozystack.io/bucket-access"
// AccessKeyIDKey holds the access key that goes with the password.
AccessKeyIDKey = "accessKeyID"
// RequestAnnotation carries the id of the latest mint or revoke, which the
// API writes with the Secret and the controller puts on the BucketAccess
// it creates to serve it.
RequestAnnotation = "credentials.cozystack.io/request"
// GrantedAnnotation carries the request id the Secret's keys were issued
// for; the API returns them only to the request that id names.
GrantedAnnotation = "credentials.cozystack.io/granted"
// AdoptLabel on a BucketAccess lets the controller take over one the
// chart rendered before the conversion, keeping its keys.
AdoptLabel = "credentials.cozystack.io/adopt"
)
var nonNameChars = regexp.MustCompile(`[^a-z0-9-]`)
// Account is one tenant account of an application.
@@ -206,3 +230,9 @@ func IsAccountValuesFrom(ref helmv2.ValuesReference) bool {
func IsAccountSecret(sec *corev1.Secret) bool {
return sec != nil && sec.Labels[AccountLabel] == "true"
}
// IsEngineIssued reports whether an account Secret belongs to an account
// whose keys the COSI driver issues.
func IsEngineIssued(sec *corev1.Secret) bool {
return sec != nil && sec.Annotations[BucketAccessAnnotation] != ""
}
@@ -635,6 +635,13 @@ func schema_pkg_apis_core_v1alpha1_CredentialRequestStatus(ref common.ReferenceC
Format: "",
},
},
"accessKeyID": {
SchemaProps: spec.SchemaProps{
Description: "AccessKeyID is the access key that goes with Password, for an account whose engine issues a key pair (a template with bucketAccess); present in a mint's answer only and shown once.",
Type: []string{"string"},
Format: "",
},
},
"issuedAt": {
SchemaProps: spec.SchemaProps{
Description: "IssuedAt is when the operation took effect in the record.",
+2
View File
@@ -2369,6 +2369,7 @@ var removedUserPasswordKinds = map[string]string{
mariadbKind: mintedPasswordWarning,
clickhouseKind: mintedPasswordWarning,
mongodbKind: mintedPasswordWarning,
rabbitmqKind: mintedPasswordWarning,
}
// mintedPasswordWarning is the warning of a kind whose user passwords the
@@ -2379,6 +2380,7 @@ const mintedPasswordWarning = "spec.users[%q].password is ignored: passwords are
const (
clickhouseKind = "ClickHouse"
mongodbKind = "MongoDB"
rabbitmqKind = "RabbitMQ"
postgresKind = "Postgres"
mariadbKind = "MariaDB"
)
@@ -164,6 +164,7 @@ func TestWarnRemovedUserPasswords(t *testing.T) {
}{
{"postgres warns", postgresKind, rawWithPassword, true},
{"mariadb warns", mariadbKind, rawWithPassword, true},
{"rabbitmq warns", rabbitmqKind, rawWithPassword, true},
{"mongodb warns", mongodbKind, rawWithPassword, true},
{"clickhouse warns", clickhouseKind, rawWithPassword, true},
{"other kind stays quiet", "Redis", rawWithPassword, false},
@@ -197,7 +198,7 @@ func TestWarnRemovedUserPasswords(t *testing.T) {
// mint on the user's Credential: its <release>-credentials Secret holds no user
// password a tenant can read, so naming it sends the reader to a dead end.
func TestWarnRemovedUserPasswords_PointsAtMint(t *testing.T) {
for _, kind := range []string{postgresKind, clickhouseKind, mariadbKind, mongodbKind} {
for _, kind := range []string{postgresKind, clickhouseKind, mariadbKind, mongodbKind, rabbitmqKind} {
t.Run(kind, func(t *testing.T) {
r := &REST{kindName: kind}
app := &appsv1alpha1.Application{Spec: &apiextv1.JSON{Raw: []byte(`{"users":{"app":{"password":"hackme"}}}`)}}
+137
View File
@@ -0,0 +1,137 @@
// SPDX-License-Identifier: Apache-2.0
package credential
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"time"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1"
"github.com/cozystack/cozystack/pkg/credentials/account"
)
// DefaultCOSIWait is how long a mint or a revoke of an engine-issued
// credential waits to be served unless cozystack-api is told otherwise. A COSI
// grant or revoke usually takes seconds.
const DefaultCOSIWait = 60 * time.Second
// regrant performs a mint or a revoke on an account whose keys the COSI
// driver issues, which the API cannot choose. It writes the account Secret,
// rebuilt from the template without keys and carrying a fresh request id, in
// the one write every operation makes. cozystack-controller serves the
// request by deleting the BucketAccess, which revokes the keys the account
// held, and marks the Secret with the id: for a mint, once it has created a
// new BucketAccess and copied its keys into the Secret; for a revoke, once
// the old one is gone, leaving the account without keys until the next
// mint. The request waits for that mark. A mint reads the keys back and
// returns them, once: no other request carries the id, so no later caller
// is shown them. A revoke returns none. A wait that runs out answers a
// retryable timeout and shows nothing; the controller still serves the
// request, and the next mint or revoke supersedes it.
func (o *OperationREST) regrant(ctx context.Context, name string, res *resolved, by, mirrored string) (*corev1alpha1.CredentialRequest, error) {
r := o.parent
tmpl := res.tmpl
id, err := requestID()
if err != nil {
return nil, apierrors.NewInternalError(err)
}
now := metav1.NewTime(r.now())
sec := buildSecret(tmpl, "", recordOf(tmpl).Apply(o.op, now, by))
delete(sec.Data, account.PasswordKey)
sec.Annotations[account.BucketAccessAnnotation] = tmpl.Spec.BucketAccess.Name
sec.Annotations[account.RequestAnnotation] = id
if err := o.write(ctx, name, sec, mirrored); err != nil {
return nil, err
}
reason := ReasonCredentialIssued
if o.op == corev1alpha1.CredentialOperationRevoke {
reason = ReasonCredentialRevoked
}
Emit(ctx, r.direct, res.hr, reason, tmpl.Spec.Username, by)
mint := o.op == corev1alpha1.CredentialOperationMint
issued, err := o.awaitGrant(ctx, name, types.NamespacedName{Namespace: sec.Namespace, Name: sec.Name}, id, mint)
if err != nil {
return nil, err
}
if issued == nil && mint {
return nil, apierrors.NewTimeoutError(fmt.Sprintf(
"credential %s: the new keys were not issued within %s; they will not be shown, mint again", name, r.cosiWait), 1)
}
if issued == nil {
return nil, apierrors.NewTimeoutError(fmt.Sprintf(
"credential %s: the old keys were not revoked within %s; they keep working until cozystack-controller removes their BucketAccess, which it still does, and a new revoke waits for that again", name, r.cosiWait), 1)
}
out := &corev1alpha1.CredentialRequest{
TypeMeta: metav1.TypeMeta{APIVersion: corev1alpha1.SchemeGroupVersion.String(), Kind: "CredentialRequest"},
Status: corev1alpha1.CredentialRequestStatus{Username: tmpl.Spec.Username, IssuedAt: now},
}
if mint {
out.Status.Password = string(issued.Data[account.PasswordKey])
out.Status.AccessKeyID = string(issued.Data[account.AccessKeyIDKey])
}
return out, nil
}
// awaitGrant polls the account Secret, uncached, until the controller marks
// it as served for the request id, holding keys when withKeys asks for them,
// and returns it; nil when the wait runs out. A Secret marked for another id
// means a later request took over, which is a conflict for this one.
func (o *OperationREST) awaitGrant(ctx context.Context, name string, key types.NamespacedName, id string, withKeys bool) (*corev1.Secret, error) {
r := o.parent
var issued *corev1.Secret
var lost bool
err := wait.PollUntilContextTimeout(ctx, r.cosiPoll, r.cosiWait, false, func(ctx context.Context) (bool, error) {
sec := &corev1.Secret{}
if err := r.direct.Get(ctx, key, sec); err != nil {
return false, client404(err)
}
if sec.Annotations[account.RequestAnnotation] != id {
lost = true
return true, nil
}
if sec.Annotations[account.GrantedAnnotation] == id && (!withKeys || len(sec.Data[account.PasswordKey]) > 0) {
issued = sec
return true, nil
}
return false, nil
})
if lost {
return nil, apierrors.NewConflict(r.gvr.GroupResource(), name,
fmt.Errorf("another request on this credential took over before its keys were issued; retry"))
}
if issued != nil {
return issued, nil
}
if err != nil && !wait.Interrupted(err) {
return nil, err
}
return nil, nil
}
// client404 keeps polling through a Secret that is momentarily missing.
func client404(err error) error {
if apierrors.IsNotFound(err) {
return nil
}
return err
}
func requestID() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
+229
View File
@@ -0,0 +1,229 @@
// SPDX-License-Identifier: Apache-2.0
package credential
import (
"context"
"strings"
"testing"
"time"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1"
"github.com/cozystack/cozystack/pkg/credentials/account"
"github.com/cozystack/cozystack/pkg/credentials/format"
)
// cosiSeeded returns an engine-issued template with the account Secret the
// controller leaves after the first grant, and the status mirroring it.
func (f *fixture) cosiSeeded(t *testing.T) *cozyv1alpha1.CredentialTemplate {
t.Helper()
tmpl := template(cred, "web")
tmpl.Spec.Format.Name = format.Plaintext
tmpl.Spec.Secret = cozyv1alpha1.CredentialTemplateSecret{}
tmpl.Spec.BucketAccess = &cozyv1alpha1.CredentialTemplateBucketAccess{Name: release + "-web", BucketClaimName: release, BucketAccessClassName: "seaweedfs"}
if err := f.c.Create(f.ctx, tmpl); err != nil {
t.Fatal(err)
}
at := metav1.NewTime(f.r.now())
sec := buildSecret(tmpl, "first-secret", account.Record{}.Apply(corev1alpha1.CredentialOperationCreate, at, "controller"))
sec.Data[account.AccessKeyIDKey] = []byte("AKIAFIRST")
sec.Annotations[account.GrantedAnnotation] = ""
sec.Annotations[account.BucketAccessAnnotation] = release + "-web"
if err := f.c.Create(f.ctx, sec); err != nil {
t.Fatal(err)
}
tmpl.Status.SecretResourceVersion = sec.ResourceVersion
if err := f.c.Status().Update(f.ctx, tmpl); err != nil {
t.Fatal(err)
}
f.mu.Lock()
f.writes = nil
f.mu.Unlock()
f.r.cosiPoll = 5 * time.Millisecond
f.r.cosiWait = 2 * time.Second
return tmpl
}
// serveGrants does what cozystack-controller does for each request a mint or
// a revoke writes: it marks the Secret with the request id, storing a new key
// pair for a mint and none for a revoke, and mirrors the Secret's version into
// the template's status. It stops with the test.
func (f *fixture) serveGrants(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
key := types.NamespacedName{Namespace: ns, Name: cred + account.SecretSuffix}
n := 0
go func() {
for ctx.Err() == nil {
time.Sleep(5 * time.Millisecond)
sec := &corev1.Secret{}
if err := f.c.Get(ctx, key, sec); err != nil {
continue
}
id := sec.Annotations[account.RequestAnnotation]
if id == "" || sec.Annotations[account.GrantedAnnotation] == id {
continue
}
n++
if account.ReadRecord(sec).Origin != corev1alpha1.CredentialOriginRevoked {
sec.Data[account.PasswordKey] = []byte("secret-" + id)
sec.Data[account.AccessKeyIDKey] = []byte("AKIA" + string(rune('A'+n)))
}
sec.Annotations[account.GrantedAnnotation] = id
if err := f.c.Update(ctx, sec); err != nil {
continue
}
tmpl := &cozyv1alpha1.CredentialTemplate{}
if err := f.c.Get(ctx, types.NamespacedName{Namespace: ns, Name: cred}, tmpl); err == nil {
tmpl.Status.SecretResourceVersion = sec.ResourceVersion
_ = f.c.Status().Update(ctx, tmpl)
}
}
}()
}
// awaitMirror waits until the template's status mirrors the account Secret.
func (f *fixture) awaitMirror(t *testing.T) {
t.Helper()
for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
sec := f.secret(t, cred+account.SecretSuffix)
tmpl := &cozyv1alpha1.CredentialTemplate{}
if err := f.c.Get(f.ctx, types.NamespacedName{Namespace: ns, Name: cred}, tmpl); err != nil {
t.Fatal(err)
}
if tmpl.Status.SecretResourceVersion == sec.ResourceVersion {
return
}
}
t.Fatal("the status never mirrored the account Secret")
}
func TestCOSIMintReturnsTheKeysOfItsOwnGrantOnce(t *testing.T) {
f := newFixture(t)
f.cosiSeeded(t)
f.serveGrants(t)
first, err := f.do(NewMintREST(f.r), cred, "", false)
if err != nil {
t.Fatal(err)
}
f.mu.Lock()
firstWrite := f.writes[0]
f.mu.Unlock()
if firstWrite != "update "+cred+account.SecretSuffix {
t.Errorf("first write = %q, want the account Secret update", firstWrite)
}
if first.Status.Username != "web" || first.Status.Password == "" || first.Status.AccessKeyID == "" {
t.Fatalf("answer = %+v, want the new key pair", first.Status)
}
if first.Status.Password == "first-secret" || first.Status.AccessKeyID == "AKIAFIRST" {
t.Error("the mint returned the keys it replaced")
}
sec := f.secret(t, cred+account.SecretSuffix)
if string(sec.Data[account.PasswordKey]) != first.Status.Password {
t.Error("the answer is not what the Secret holds")
}
if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginMinted || rec.By != "jane@example.org" {
t.Errorf("record = %+v", rec)
}
// The controller mirrors the Secret into the status after marking it, so
// a mint that starts in between would be answered with a conflict.
f.awaitMirror(t)
second, err := f.do(NewMintREST(f.r), cred, "", false)
if err != nil {
t.Fatal(err)
}
if second.Status.Password == first.Status.Password || second.Status.AccessKeyID == first.Status.AccessKeyID {
t.Error("a second mint showed the first mint's keys again")
}
}
func TestCOSIRevokeReturnsNoKeys(t *testing.T) {
f := newFixture(t)
f.cosiSeeded(t)
f.serveGrants(t)
res, err := f.do(NewRevokeREST(f.r), cred, "", false)
if err != nil {
t.Fatal(err)
}
if res.Status.Password != "" || res.Status.AccessKeyID != "" {
t.Errorf("answer = %+v, want no keys", res.Status)
}
sec := f.secret(t, cred+account.SecretSuffix)
if _, held := sec.Data[account.PasswordKey]; held || len(sec.Data[account.AccessKeyIDKey]) > 0 {
t.Errorf("data = %v, want no keys after a revoke", sec.Data)
}
if id := sec.Annotations[account.RequestAnnotation]; id == "" || sec.Annotations[account.GrantedAnnotation] != id {
t.Errorf("annotations = %v, want the revoke served", sec.Annotations)
}
if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginRevoked {
t.Errorf("record = %+v, want Revoked", rec)
}
}
func TestCOSIRevokeThatOutwaitsTheControllerSaysTheKeysStillWork(t *testing.T) {
f := newFixture(t)
f.cosiSeeded(t)
f.r.cosiWait = 50 * time.Millisecond
_, err := f.do(NewRevokeREST(f.r), cred, "", false)
if !apierrors.IsTimeout(err) || !strings.Contains(err.Error(), "keep working") {
t.Fatalf("err = %v, want a retryable timeout saying the keys still work", err)
}
}
func TestCOSIRefusesACredentialWithAForeignBucketAccess(t *testing.T) {
f := newFixture(t)
tmpl := f.cosiSeeded(t)
meta.SetStatusCondition(&tmpl.Status.Conditions, metav1.Condition{
Type: cozyv1alpha1.CredentialTemplateBucketAccessConflict, Status: metav1.ConditionTrue, Reason: "ForeignBucketAccess",
})
if err := f.c.Status().Update(f.ctx, tmpl); err != nil {
t.Fatal(err)
}
for _, op := range []*OperationREST{NewMintREST(f.r), NewRevokeREST(f.r)} {
if _, err := f.do(op, cred, "", false); !apierrors.IsConflict(err) {
t.Fatalf("%s: err = %v, want a conflict", op.op, err)
}
}
f.mu.Lock()
defer f.mu.Unlock()
if len(f.writes) != 0 {
t.Errorf("writes = %v, want none", f.writes)
}
}
func TestCOSIMintThatOutwaitsTheGrantShowsNothing(t *testing.T) {
f := newFixture(t)
f.cosiSeeded(t)
f.r.cosiWait = 50 * time.Millisecond
_, err := f.do(NewMintREST(f.r), cred, "", false)
if !apierrors.IsTimeout(err) {
t.Fatalf("err = %v, want a retryable timeout", err)
}
sec := f.secret(t, cred+account.SecretSuffix)
if _, held := sec.Data[account.PasswordKey]; held {
t.Error("the Secret still holds keys the mint replaced")
}
if _, held := sec.Data[account.AccessKeyIDKey]; held {
t.Error("the Secret still holds an access key the mint replaced")
}
if sec.Annotations[account.RequestAnnotation] == "" {
t.Error("the mint wrote no request for the controller")
}
f.mu.Lock()
defer f.mu.Unlock()
if len(f.writes) != 1 {
t.Errorf("writes = %v, want the one Secret update", f.writes)
}
}
+15 -3
View File
@@ -3,8 +3,9 @@
// Package credential serves core.cozystack.io/credentials, a view over the
// CredentialTemplates a kind's chart renders, with the mint and revoke
// subresources. The view shows the account's record as the template's status
// mirrors it, and never reads a Secret. See design-proposals/user-secrets-api
// in cozystack/community.
// mirrors it, and reads no Secret but the one a mint of an engine-issued
// account waits on. See design-proposals/user-secrets-api in
// cozystack/community.
package credential
import (
@@ -56,6 +57,11 @@ type REST struct {
direct client.Client
gvr schema.GroupVersionResource
now func() time.Time
// cosiWait bounds how long a mint or a revoke of an engine-issued
// credential waits for the controller to serve it; cosiPoll is how often
// it looks.
cosiWait time.Duration
cosiPoll time.Duration
}
// NewREST creates the credentials storage.
@@ -68,10 +74,16 @@ func NewREST(c, direct client.Client) *REST {
Version: "v1alpha1",
Resource: "credentials",
},
now: time.Now,
now: time.Now,
cosiWait: DefaultCOSIWait,
cosiPoll: 500 * time.Millisecond,
}
}
// SetCOSIWait sets how long a mint or a revoke of an engine-issued credential
// waits for its new grant.
func (r *REST) SetCOSIWait(d time.Duration) { r.cosiWait = d }
func (*REST) NamespaceScoped() bool { return true }
func (*REST) GetSingularName() string { return singularName }
func (*REST) Destroy() {}
@@ -10,6 +10,7 @@ import (
"flag"
"io"
"strings"
"sync"
"testing"
"time"
@@ -46,6 +47,7 @@ type fixture struct {
c client.Client
r *REST
ctx context.Context
mu sync.Mutex
writes []string
}
@@ -69,7 +71,9 @@ func newFixture(t *testing.T, objs ...client.Object) *fixture {
record := func(verb string) func(ctx context.Context, c client.WithWatch, obj client.Object, _ ...any) {
return func(_ context.Context, _ client.WithWatch, obj client.Object, _ ...any) {
if _, isEvent := obj.(*corev1.Event); !isEvent {
f.mu.Lock()
f.writes = append(f.writes, verb+" "+obj.GetName())
f.mu.Unlock()
}
}
}
+42 -20
View File
@@ -87,6 +87,16 @@ func (o *OperationREST) Create(ctx context.Context, name string, obj runtime.Obj
return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf(
"credential %s has a Secret it did not create; a platform administrator has to remove it first", name))
}
// A template that names a BucketAccess is engine-issued: the COSI driver,
// not the API, chooses its keys.
engineIssued := tmpl.Spec.BucketAccess != nil
if engineIssued && meta.IsStatusConditionTrue(tmpl.Status.Conditions, cozyv1alpha1.CredentialTemplateBucketAccessConflict) {
// The controller leaves a BucketAccess it did not create alone, so
// it could serve neither operation, and the request would only wait
// out its timeout.
return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf(
"credential %s has a BucketAccess it did not create; a platform administrator has to remove it first", name))
}
if !format.Known(tmpl.Spec.Format.Name) {
return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf(
"credential %s names the format %q, which is not built in", name, tmpl.Spec.Format.Name))
@@ -115,6 +125,10 @@ func (o *OperationREST) Create(ctx context.Context, name string, obj runtime.Obj
}, nil
}
if engineIssued {
return o.regrant(ctx, name, res, user.GetName(), mirrored)
}
password, err := format.GeneratePassword()
if err != nil {
return nil, apierrors.NewInternalError(err)
@@ -126,26 +140,8 @@ func (o *OperationREST) Create(ctx context.Context, name string, obj runtime.Obj
now := metav1.NewTime(r.now())
by := user.GetName()
sec := buildSecret(tmpl, stored, recordOf(tmpl).Apply(o.op, now, by))
// The status is all the API knows of the Secret. A status that lags the
// Secret, or a Secret written since the status was read, makes the write
// fail rather than overwrite it, and the caller gets a conflict and no
// password.
if mirrored == "" {
if err := r.direct.Create(ctx, sec); err != nil {
if apierrors.IsAlreadyExists(err) {
return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf("credential %s is being seeded; retry", name))
}
return nil, err
}
} else {
sec.ResourceVersion = mirrored
if err := r.direct.Update(ctx, sec); err != nil {
if apierrors.IsConflict(err) || apierrors.IsNotFound(err) {
return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf("credential %s changed while the request was in flight; retry", name))
}
return nil, err
}
if err := o.write(ctx, name, sec, mirrored); err != nil {
return nil, err
}
reason := ReasonCredentialIssued
@@ -168,6 +164,32 @@ func (o *OperationREST) Create(ctx context.Context, name string, obj runtime.Obj
}, nil
}
// write stores the account Secret under the version the template's status
// mirrors, or creates it when the account has none. The status is all the
// API knows of the Secret. A status that lags the Secret, or a Secret written
// since the status was read, makes the write fail rather than overwrite it,
// and the caller gets a conflict and no password.
func (o *OperationREST) write(ctx context.Context, name string, sec *corev1.Secret, mirrored string) error {
r := o.parent
if mirrored == "" {
if err := r.direct.Create(ctx, sec); err != nil {
if apierrors.IsAlreadyExists(err) {
return apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf("credential %s is being seeded; retry", name))
}
return err
}
return nil
}
sec.ResourceVersion = mirrored
if err := r.direct.Update(ctx, sec); err != nil {
if apierrors.IsConflict(err) || apierrors.IsNotFound(err) {
return apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf("credential %s changed while the request was in flight; retry", name))
}
return err
}
return nil
}
// recordOf returns the record the template's status mirrors, which the mint
// extends with its own operation.
func recordOf(tmpl *cozyv1alpha1.CredentialTemplate) account.Record {