mirror of
https://github.com/cozystack/cozystack.git
synced 2026-12-06 07:03:45 +09:00
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:
94 files changed
+10276
-280
No files matched your search
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user