From 1c4f433fecdb1620d6ae7674e7ce80ac036820c0 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Sat, 21 Nov 2026 09:18:33 +0100 Subject: [PATCH] feat(controller): re-create the BucketAccess of an engine-issued account The COSI driver issues a Bucket user's keys and never accepts chosen ones, so the password reconciler cannot seed such an account. A separate reconciler creates and owns the BucketAccess a template names, adopts the one the conversion marked so existing keys survive, and copies the keys of the live grant into the account Secret. A mint or a revoke reaches it as a request id on that Secret: a BucketAccess created for an older request is deleted, which makes the sidecar revoke its identity. A mint gets a new BucketAccess; a revoke gets none, so it locks the account out until the next mint. A changed readonly flag or storage pool gives the template another BucketAccess class. The controller records that as a revoke of its own: the account Secret loses its keys and gets a request id and a Revoke entry by the controller, so the revoke path deletes the old grant, creates none, and the next mint is granted under the new class. Re-granting at once would leave keys nobody was shown under a record that says the last mint issued the live ones. A mint the Secret already carries is served under the new class instead. The sidecar has the driver grant an identity before it puts its finalizer on the BucketAccess, so a BucketAccess is deleted only once it carries that finalizer, or once the sidecar can no longer grant it, its class or claim gone or the bucket not ready: a delete in between would skip the driver revoke and leave a working identity behind. A finalizer on the template holds a deleted one until then, so a user removed inside the grant window does not orphan its identity at the provider. The template's status mirrors the account Secret while a request is pending, so a request that never completes does not turn every later one into a conflict, and a lost account Secret is rewritten from the live grant instead of rotating keys under its clients. Lost after a revoke, it is written again as revoked from that status, so it does not take the create path and re-grant keys nobody minted. The password reconciler skips templates that name a BucketAccess and is otherwise unchanged. The account Secret names its BucketAccess in an annotation, which is how the controller tells an engine-issued account Secret from the others. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- cmd/cozystack-controller/main.go | 9 + .../credentialtemplate_controller.go | 12 +- .../controller/credentialtemplate_cosi.go | 716 +++++++++++++++ .../credentialtemplate_cosi_test.go | 868 ++++++++++++++++++ .../cozystack-controller/templates/rbac.yaml | 13 + .../cozystack-controller/tests/rbac_test.yaml | 17 + pkg/credentials/account/account.go | 30 + 7 files changed, 1664 insertions(+), 1 deletion(-) create mode 100644 internal/controller/credentialtemplate_cosi.go create mode 100644 internal/controller/credentialtemplate_cosi_test.go diff --git a/cmd/cozystack-controller/main.go b/cmd/cozystack-controller/main.go index c296496a9..3239ae15f 100644 --- a/cmd/cozystack-controller/main.go +++ b/cmd/cozystack-controller/main.go @@ -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(), diff --git a/internal/controller/credentialtemplate_controller.go b/internal/controller/credentialtemplate_controller.go index 36e7e6fdc..ebdb2032c 100644 --- a/internal/controller/credentialtemplate_controller.go +++ b/internal/controller/credentialtemplate_controller.go @@ -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 diff --git a/internal/controller/credentialtemplate_cosi.go b/internal/controller/credentialtemplate_cosi.go new file mode 100644 index 000000000..cd22246a0 --- /dev/null +++ b/internal/controller/credentialtemplate_cosi.go @@ -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) +} diff --git a/internal/controller/credentialtemplate_cosi_test.go b/internal/controller/credentialtemplate_cosi_test.go new file mode 100644 index 000000000..8b693cec4 --- /dev/null +++ b/internal/controller/credentialtemplate_cosi_test.go @@ -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) + } +} diff --git a/packages/system/cozystack-controller/templates/rbac.yaml b/packages/system/cozystack-controller/templates/rbac.yaml index a9f7b646d..8502b32d8 100644 --- a/packages/system/cozystack-controller/templates/rbac.yaml +++ b/packages/system/cozystack-controller/templates/rbac.yaml @@ -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"] diff --git a/packages/system/cozystack-controller/tests/rbac_test.yaml b/packages/system/cozystack-controller/tests/rbac_test.yaml index 891e28870..7ac9f6277 100644 --- a/packages/system/cozystack-controller/tests/rbac_test.yaml +++ b/packages/system/cozystack-controller/tests/rbac_test.yaml @@ -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"] diff --git a/pkg/credentials/account/account.go b/pkg/credentials/account/account.go index 88012e5d9..3afaf053f 100644 --- a/pkg/credentials/account/account.go +++ b/pkg/credentials/account/account.go @@ -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] != "" +}