diff --git a/pkg/apiserver/apiserver.go b/pkg/apiserver/apiserver.go index a48a42c70..53d7829a0 100644 --- a/pkg/apiserver/apiserver.go +++ b/pkg/apiserver/apiserver.go @@ -117,6 +117,9 @@ type Config struct { GenericConfig *genericapiserver.RecommendedConfig ResourceConfig *config.ResourceConfig ServeSDN bool + // CredentialsCOSIWait bounds the wait of a mint or a revoke on an + // engine-issued credential; zero keeps the default. + CredentialsCOSIWait time.Duration } // CozyServer holds the state for the Kubernetes master/api server. @@ -125,9 +128,10 @@ type CozyServer struct { } type completedConfig struct { - GenericConfig genericapiserver.CompletedConfig - ResourceConfig *config.ResourceConfig - ServeSDN bool + GenericConfig genericapiserver.CompletedConfig + ResourceConfig *config.ResourceConfig + ServeSDN bool + CredentialsCOSIWait time.Duration } // CompletedConfig embeds a private pointer that cannot be created outside of this package. @@ -141,6 +145,7 @@ func (cfg *Config) Complete() CompletedConfig { cfg.GenericConfig.Complete(), cfg.ResourceConfig, cfg.ServeSDN, + cfg.CredentialsCOSIWait, } return CompletedConfig{&c} @@ -239,7 +244,7 @@ func (c completedConfig) New() (*CozyServer, error) { if err != nil { return nil, fmt.Errorf("failed to build dynamic client: %w", err) } - if err := InstallStaticAPIGroups(s.GenericAPIServer, cli, watchCli, dyn, c.ServeSDN); err != nil { + if err := InstallStaticAPIGroups(s.GenericAPIServer, cli, watchCli, dyn, c.ServeSDN, c.CredentialsCOSIWait); err != nil { return nil, err } @@ -261,7 +266,9 @@ func (c completedConfig) New() (*CozyServer, error) { // another server owns the group: kube-aggregator still merges this server's // /openapi/v3 index, so both backends list the group-version and fetching its // OpenAPI fails on a redirect whenever the two disagree on the hash. -func InstallStaticAPIGroups(server *genericapiserver.GenericAPIServer, cli client.Client, watchCli client.WithWatch, dyn dynamic.Interface, serveSDN bool) error { +// credentialsCOSIWait bounds the wait of a mint or a revoke on an +// engine-issued credential; zero keeps the default. +func InstallStaticAPIGroups(server *genericapiserver.GenericAPIServer, cli client.Client, watchCli client.WithWatch, dyn dynamic.Interface, serveSDN bool, credentialsCOSIWait time.Duration) error { // --- static, cluster-scoped resource for core group --- coreV1alpha1Storage := map[string]rest.Storage{} coreV1alpha1Storage["tenantnamespaces"] = cozyregistry.RESTInPeace( @@ -283,6 +290,9 @@ func InstallStaticAPIGroups(server *genericapiserver.GenericAPIServer, cli clien tapstorage.NewREST(dyn), ) credentials := credentialstorage.NewREST(cli, watchCli) + if credentialsCOSIWait > 0 { + credentials.SetCOSIWait(credentialsCOSIWait) + } coreV1alpha1Storage["credentials"] = cozyregistry.RESTInPeace(credentials) coreV1alpha1Storage["credentials/mint"] = credentialstorage.NewMintREST(credentials) coreV1alpha1Storage["credentials/revoke"] = credentialstorage.NewRevokeREST(credentials) diff --git a/pkg/cmd/server/serve_sdn_test.go b/pkg/cmd/server/serve_sdn_test.go index 0a12b1f15..3512b303d 100644 --- a/pkg/cmd/server/serve_sdn_test.go +++ b/pkg/cmd/server/serve_sdn_test.go @@ -63,7 +63,7 @@ func startStaticGroupsServer(t *testing.T, serveSDN bool) *httptest.Server { } cli := fake.NewClientBuilder().Build() dyn := dynamicfake.NewSimpleDynamicClient(runtime.NewScheme()) - if err := apiserver.InstallStaticAPIGroups(srv, cli, cli, dyn, serveSDN); err != nil { + if err := apiserver.InstallStaticAPIGroups(srv, cli, cli, dyn, serveSDN, 0); err != nil { t.Fatal(err) } srv.PrepareRun() diff --git a/pkg/cmd/server/start.go b/pkg/cmd/server/start.go index 327446e6f..99bac2539 100644 --- a/pkg/cmd/server/start.go +++ b/pkg/cmd/server/start.go @@ -35,6 +35,7 @@ import ( sdnv1alpha1 "github.com/cozystack/cozystack/pkg/apis/sdn/v1alpha1" "github.com/cozystack/cozystack/pkg/apiserver" "github.com/cozystack/cozystack/pkg/config" + credentialstorage "github.com/cozystack/cozystack/pkg/registry/core/credential" "github.com/spf13/cobra" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" @@ -78,6 +79,12 @@ type CozyServerOptions struct { // ServeSDN installs the sdn.cozystack.io group; off where another // aggregated server owns it. ServeSDN bool + + // CredentialsCOSIWait bounds how long a mint or a revoke of an + // engine-issued credential waits for cozystack-controller to serve it, + // with a new grant or with the old one gone, before it answers a retryable + // timeout. + CredentialsCOSIWait time.Duration } // NewCozyServerOptions returns a new instance of CozyServerOptions @@ -176,6 +183,9 @@ func NewCommandStartCozyServer(ctx context.Context, defaults *CozyServerOptions) flags.IntVar(&o.HelmReleaseMaxHistory, "helmrelease-max-history", o.HelmReleaseMaxHistory, "Number of release revisions Helm keeps for HelmReleases generated from Application "+ "resources (Spec.MaxHistory). 0 means unlimited; 5 matches Helm's default.") + flags.DurationVar(&o.CredentialsCOSIWait, "credentials-cosi-wait", credentialstorage.DefaultCOSIWait, + "How long a mint or a revoke of a credential whose keys a COSI driver issues waits for "+ + "cozystack-controller to serve it before it answers a retryable timeout.") flags.BoolVar(&o.ServeSDN, "serve-sdn", o.ServeSDN, "Serve the sdn.cozystack.io API group. Turn off where another aggregated API server owns the group.") @@ -496,9 +506,10 @@ func (o *CozyServerOptions) Config() (*apiserver.Config, error) { } config := &apiserver.Config{ - GenericConfig: serverConfig, - ResourceConfig: o.ResourceConfig, - ServeSDN: o.ServeSDN, + GenericConfig: serverConfig, + ResourceConfig: o.ResourceConfig, + ServeSDN: o.ServeSDN, + CredentialsCOSIWait: o.CredentialsCOSIWait, } return config, nil } diff --git a/pkg/registry/core/credential/cosi.go b/pkg/registry/core/credential/cosi.go new file mode 100644 index 000000000..c8e97f25c --- /dev/null +++ b/pkg/registry/core/credential/cosi.go @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: Apache-2.0 + +package credential + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/wait" + + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" +) + +// DefaultCOSIWait is how long a mint or a revoke of an engine-issued +// credential waits to be served unless cozystack-api is told otherwise. A COSI +// grant or revoke usually takes seconds. +const DefaultCOSIWait = 60 * time.Second + +// regrant performs a mint or a revoke on an account whose keys the COSI +// driver issues, which the API cannot choose. It writes the account Secret, +// rebuilt from the template without keys and carrying a fresh request id, in +// the one write every operation makes. cozystack-controller serves the +// request by deleting the BucketAccess, which revokes the keys the account +// held, and marks the Secret with the id: for a mint, once it has created a +// new BucketAccess and copied its keys into the Secret; for a revoke, once +// the old one is gone, leaving the account without keys until the next +// mint. The request waits for that mark. A mint reads the keys back and +// returns them, once: no other request carries the id, so no later caller +// is shown them. A revoke returns none. A wait that runs out answers a +// retryable timeout and shows nothing; the controller still serves the +// request, and the next mint or revoke supersedes it. +func (o *OperationREST) regrant(ctx context.Context, name string, res *resolved, by, mirrored string) (*corev1alpha1.CredentialRequest, error) { + r := o.parent + tmpl := res.tmpl + id, err := requestID() + if err != nil { + return nil, apierrors.NewInternalError(err) + } + now := metav1.NewTime(r.now()) + sec := buildSecret(tmpl, "", recordOf(tmpl).Apply(o.op, now, by)) + delete(sec.Data, account.PasswordKey) + sec.Annotations[account.BucketAccessAnnotation] = tmpl.Spec.BucketAccess.Name + sec.Annotations[account.RequestAnnotation] = id + if err := o.write(ctx, name, sec, mirrored); err != nil { + return nil, err + } + + reason := ReasonCredentialIssued + if o.op == corev1alpha1.CredentialOperationRevoke { + reason = ReasonCredentialRevoked + } + Emit(ctx, r.direct, res.hr, reason, tmpl.Spec.Username, by) + + mint := o.op == corev1alpha1.CredentialOperationMint + issued, err := o.awaitGrant(ctx, name, types.NamespacedName{Namespace: sec.Namespace, Name: sec.Name}, id, mint) + if err != nil { + return nil, err + } + if issued == nil && mint { + return nil, apierrors.NewTimeoutError(fmt.Sprintf( + "credential %s: the new keys were not issued within %s; they will not be shown, mint again", name, r.cosiWait), 1) + } + if issued == nil { + return nil, apierrors.NewTimeoutError(fmt.Sprintf( + "credential %s: the old keys were not revoked within %s; they keep working until cozystack-controller removes their BucketAccess, which it still does, and a new revoke waits for that again", name, r.cosiWait), 1) + } + + out := &corev1alpha1.CredentialRequest{ + TypeMeta: metav1.TypeMeta{APIVersion: corev1alpha1.SchemeGroupVersion.String(), Kind: "CredentialRequest"}, + Status: corev1alpha1.CredentialRequestStatus{Username: tmpl.Spec.Username, IssuedAt: now}, + } + if mint { + out.Status.Password = string(issued.Data[account.PasswordKey]) + out.Status.AccessKeyID = string(issued.Data[account.AccessKeyIDKey]) + } + return out, nil +} + +// awaitGrant polls the account Secret, uncached, until the controller marks +// it as served for the request id, holding keys when withKeys asks for them, +// and returns it; nil when the wait runs out. A Secret marked for another id +// means a later request took over, which is a conflict for this one. +func (o *OperationREST) awaitGrant(ctx context.Context, name string, key types.NamespacedName, id string, withKeys bool) (*corev1.Secret, error) { + r := o.parent + var issued *corev1.Secret + var lost bool + err := wait.PollUntilContextTimeout(ctx, r.cosiPoll, r.cosiWait, false, func(ctx context.Context) (bool, error) { + sec := &corev1.Secret{} + if err := r.direct.Get(ctx, key, sec); err != nil { + return false, client404(err) + } + if sec.Annotations[account.RequestAnnotation] != id { + lost = true + return true, nil + } + if sec.Annotations[account.GrantedAnnotation] == id && (!withKeys || len(sec.Data[account.PasswordKey]) > 0) { + issued = sec + return true, nil + } + return false, nil + }) + if lost { + return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, + fmt.Errorf("another request on this credential took over before its keys were issued; retry")) + } + if issued != nil { + return issued, nil + } + if err != nil && !wait.Interrupted(err) { + return nil, err + } + return nil, nil +} + +// client404 keeps polling through a Secret that is momentarily missing. +func client404(err error) error { + if apierrors.IsNotFound(err) { + return nil + } + return err +} + +func requestID() (string, error) { + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + return "", err + } + return hex.EncodeToString(b), nil +} diff --git a/pkg/registry/core/credential/cosi_test.go b/pkg/registry/core/credential/cosi_test.go new file mode 100644 index 000000000..d9a6e20d0 --- /dev/null +++ b/pkg/registry/core/credential/cosi_test.go @@ -0,0 +1,229 @@ +// SPDX-License-Identifier: Apache-2.0 + +package credential + +import ( + "context" + "strings" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" + "github.com/cozystack/cozystack/pkg/credentials/format" +) + +// cosiSeeded returns an engine-issued template with the account Secret the +// controller leaves after the first grant, and the status mirroring it. +func (f *fixture) cosiSeeded(t *testing.T) *cozyv1alpha1.CredentialTemplate { + t.Helper() + tmpl := template(cred, "web") + tmpl.Spec.Format.Name = format.Plaintext + tmpl.Spec.Secret = cozyv1alpha1.CredentialTemplateSecret{} + tmpl.Spec.BucketAccess = &cozyv1alpha1.CredentialTemplateBucketAccess{Name: release + "-web", BucketClaimName: release, BucketAccessClassName: "seaweedfs"} + if err := f.c.Create(f.ctx, tmpl); err != nil { + t.Fatal(err) + } + at := metav1.NewTime(f.r.now()) + sec := buildSecret(tmpl, "first-secret", account.Record{}.Apply(corev1alpha1.CredentialOperationCreate, at, "controller")) + sec.Data[account.AccessKeyIDKey] = []byte("AKIAFIRST") + sec.Annotations[account.GrantedAnnotation] = "" + sec.Annotations[account.BucketAccessAnnotation] = release + "-web" + if err := f.c.Create(f.ctx, sec); err != nil { + t.Fatal(err) + } + tmpl.Status.SecretResourceVersion = sec.ResourceVersion + if err := f.c.Status().Update(f.ctx, tmpl); err != nil { + t.Fatal(err) + } + f.mu.Lock() + f.writes = nil + f.mu.Unlock() + f.r.cosiPoll = 5 * time.Millisecond + f.r.cosiWait = 2 * time.Second + return tmpl +} + +// serveGrants does what cozystack-controller does for each request a mint or +// a revoke writes: it marks the Secret with the request id, storing a new key +// pair for a mint and none for a revoke, and mirrors the Secret's version into +// the template's status. It stops with the test. +func (f *fixture) serveGrants(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + key := types.NamespacedName{Namespace: ns, Name: cred + account.SecretSuffix} + n := 0 + go func() { + for ctx.Err() == nil { + time.Sleep(5 * time.Millisecond) + sec := &corev1.Secret{} + if err := f.c.Get(ctx, key, sec); err != nil { + continue + } + id := sec.Annotations[account.RequestAnnotation] + if id == "" || sec.Annotations[account.GrantedAnnotation] == id { + continue + } + n++ + if account.ReadRecord(sec).Origin != corev1alpha1.CredentialOriginRevoked { + sec.Data[account.PasswordKey] = []byte("secret-" + id) + sec.Data[account.AccessKeyIDKey] = []byte("AKIA" + string(rune('A'+n))) + } + sec.Annotations[account.GrantedAnnotation] = id + if err := f.c.Update(ctx, sec); err != nil { + continue + } + tmpl := &cozyv1alpha1.CredentialTemplate{} + if err := f.c.Get(ctx, types.NamespacedName{Namespace: ns, Name: cred}, tmpl); err == nil { + tmpl.Status.SecretResourceVersion = sec.ResourceVersion + _ = f.c.Status().Update(ctx, tmpl) + } + } + }() +} + +// awaitMirror waits until the template's status mirrors the account Secret. +func (f *fixture) awaitMirror(t *testing.T) { + t.Helper() + for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) { + sec := f.secret(t, cred+account.SecretSuffix) + tmpl := &cozyv1alpha1.CredentialTemplate{} + if err := f.c.Get(f.ctx, types.NamespacedName{Namespace: ns, Name: cred}, tmpl); err != nil { + t.Fatal(err) + } + if tmpl.Status.SecretResourceVersion == sec.ResourceVersion { + return + } + } + t.Fatal("the status never mirrored the account Secret") +} + +func TestCOSIMintReturnsTheKeysOfItsOwnGrantOnce(t *testing.T) { + f := newFixture(t) + f.cosiSeeded(t) + f.serveGrants(t) + + first, err := f.do(NewMintREST(f.r), cred, "", false) + if err != nil { + t.Fatal(err) + } + f.mu.Lock() + firstWrite := f.writes[0] + f.mu.Unlock() + if firstWrite != "update "+cred+account.SecretSuffix { + t.Errorf("first write = %q, want the account Secret update", firstWrite) + } + if first.Status.Username != "web" || first.Status.Password == "" || first.Status.AccessKeyID == "" { + t.Fatalf("answer = %+v, want the new key pair", first.Status) + } + if first.Status.Password == "first-secret" || first.Status.AccessKeyID == "AKIAFIRST" { + t.Error("the mint returned the keys it replaced") + } + sec := f.secret(t, cred+account.SecretSuffix) + if string(sec.Data[account.PasswordKey]) != first.Status.Password { + t.Error("the answer is not what the Secret holds") + } + if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginMinted || rec.By != "jane@example.org" { + t.Errorf("record = %+v", rec) + } + + // The controller mirrors the Secret into the status after marking it, so + // a mint that starts in between would be answered with a conflict. + f.awaitMirror(t) + second, err := f.do(NewMintREST(f.r), cred, "", false) + if err != nil { + t.Fatal(err) + } + if second.Status.Password == first.Status.Password || second.Status.AccessKeyID == first.Status.AccessKeyID { + t.Error("a second mint showed the first mint's keys again") + } +} + +func TestCOSIRevokeReturnsNoKeys(t *testing.T) { + f := newFixture(t) + f.cosiSeeded(t) + f.serveGrants(t) + + res, err := f.do(NewRevokeREST(f.r), cred, "", false) + if err != nil { + t.Fatal(err) + } + if res.Status.Password != "" || res.Status.AccessKeyID != "" { + t.Errorf("answer = %+v, want no keys", res.Status) + } + sec := f.secret(t, cred+account.SecretSuffix) + if _, held := sec.Data[account.PasswordKey]; held || len(sec.Data[account.AccessKeyIDKey]) > 0 { + t.Errorf("data = %v, want no keys after a revoke", sec.Data) + } + if id := sec.Annotations[account.RequestAnnotation]; id == "" || sec.Annotations[account.GrantedAnnotation] != id { + t.Errorf("annotations = %v, want the revoke served", sec.Annotations) + } + if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginRevoked { + t.Errorf("record = %+v, want Revoked", rec) + } +} + +func TestCOSIRevokeThatOutwaitsTheControllerSaysTheKeysStillWork(t *testing.T) { + f := newFixture(t) + f.cosiSeeded(t) + f.r.cosiWait = 50 * time.Millisecond + + _, err := f.do(NewRevokeREST(f.r), cred, "", false) + if !apierrors.IsTimeout(err) || !strings.Contains(err.Error(), "keep working") { + t.Fatalf("err = %v, want a retryable timeout saying the keys still work", err) + } +} + +func TestCOSIRefusesACredentialWithAForeignBucketAccess(t *testing.T) { + f := newFixture(t) + tmpl := f.cosiSeeded(t) + meta.SetStatusCondition(&tmpl.Status.Conditions, metav1.Condition{ + Type: cozyv1alpha1.CredentialTemplateBucketAccessConflict, Status: metav1.ConditionTrue, Reason: "ForeignBucketAccess", + }) + if err := f.c.Status().Update(f.ctx, tmpl); err != nil { + t.Fatal(err) + } + for _, op := range []*OperationREST{NewMintREST(f.r), NewRevokeREST(f.r)} { + if _, err := f.do(op, cred, "", false); !apierrors.IsConflict(err) { + t.Fatalf("%s: err = %v, want a conflict", op.op, err) + } + } + f.mu.Lock() + defer f.mu.Unlock() + if len(f.writes) != 0 { + t.Errorf("writes = %v, want none", f.writes) + } +} + +func TestCOSIMintThatOutwaitsTheGrantShowsNothing(t *testing.T) { + f := newFixture(t) + f.cosiSeeded(t) + f.r.cosiWait = 50 * time.Millisecond + + _, err := f.do(NewMintREST(f.r), cred, "", false) + if !apierrors.IsTimeout(err) { + t.Fatalf("err = %v, want a retryable timeout", err) + } + sec := f.secret(t, cred+account.SecretSuffix) + if _, held := sec.Data[account.PasswordKey]; held { + t.Error("the Secret still holds keys the mint replaced") + } + if _, held := sec.Data[account.AccessKeyIDKey]; held { + t.Error("the Secret still holds an access key the mint replaced") + } + if sec.Annotations[account.RequestAnnotation] == "" { + t.Error("the mint wrote no request for the controller") + } + f.mu.Lock() + defer f.mu.Unlock() + if len(f.writes) != 1 { + t.Errorf("writes = %v, want the one Secret update", f.writes) + } +} diff --git a/pkg/registry/core/credential/rest.go b/pkg/registry/core/credential/rest.go index 0126818fb..7feff633c 100644 --- a/pkg/registry/core/credential/rest.go +++ b/pkg/registry/core/credential/rest.go @@ -3,8 +3,9 @@ // Package credential serves core.cozystack.io/credentials, a view over the // CredentialTemplates a kind's chart renders, with the mint and revoke // subresources. The view shows the account's record as the template's status -// mirrors it, and never reads a Secret. See design-proposals/user-secrets-api -// in cozystack/community. +// mirrors it, and reads no Secret but the one a mint of an engine-issued +// account waits on. See design-proposals/user-secrets-api in +// cozystack/community. package credential import ( @@ -56,6 +57,11 @@ type REST struct { direct client.Client gvr schema.GroupVersionResource now func() time.Time + // cosiWait bounds how long a mint or a revoke of an engine-issued + // credential waits for the controller to serve it; cosiPoll is how often + // it looks. + cosiWait time.Duration + cosiPoll time.Duration } // NewREST creates the credentials storage. @@ -68,10 +74,16 @@ func NewREST(c, direct client.Client) *REST { Version: "v1alpha1", Resource: "credentials", }, - now: time.Now, + now: time.Now, + cosiWait: DefaultCOSIWait, + cosiPoll: 500 * time.Millisecond, } } +// SetCOSIWait sets how long a mint or a revoke of an engine-issued credential +// waits for its new grant. +func (r *REST) SetCOSIWait(d time.Duration) { r.cosiWait = d } + func (*REST) NamespaceScoped() bool { return true } func (*REST) GetSingularName() string { return singularName } func (*REST) Destroy() {} diff --git a/pkg/registry/core/credential/rest_test.go b/pkg/registry/core/credential/rest_test.go index cce84140b..335403057 100644 --- a/pkg/registry/core/credential/rest_test.go +++ b/pkg/registry/core/credential/rest_test.go @@ -10,6 +10,7 @@ import ( "flag" "io" "strings" + "sync" "testing" "time" @@ -46,6 +47,7 @@ type fixture struct { c client.Client r *REST ctx context.Context + mu sync.Mutex writes []string } @@ -69,7 +71,9 @@ func newFixture(t *testing.T, objs ...client.Object) *fixture { record := func(verb string) func(ctx context.Context, c client.WithWatch, obj client.Object, _ ...any) { return func(_ context.Context, _ client.WithWatch, obj client.Object, _ ...any) { if _, isEvent := obj.(*corev1.Event); !isEvent { + f.mu.Lock() f.writes = append(f.writes, verb+" "+obj.GetName()) + f.mu.Unlock() } } } diff --git a/pkg/registry/core/credential/subresources.go b/pkg/registry/core/credential/subresources.go index 8f1158735..c3d496505 100644 --- a/pkg/registry/core/credential/subresources.go +++ b/pkg/registry/core/credential/subresources.go @@ -87,6 +87,16 @@ func (o *OperationREST) Create(ctx context.Context, name string, obj runtime.Obj return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf( "credential %s has a Secret it did not create; a platform administrator has to remove it first", name)) } + // A template that names a BucketAccess is engine-issued: the COSI driver, + // not the API, chooses its keys. + engineIssued := tmpl.Spec.BucketAccess != nil + if engineIssued && meta.IsStatusConditionTrue(tmpl.Status.Conditions, cozyv1alpha1.CredentialTemplateBucketAccessConflict) { + // The controller leaves a BucketAccess it did not create alone, so + // it could serve neither operation, and the request would only wait + // out its timeout. + return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf( + "credential %s has a BucketAccess it did not create; a platform administrator has to remove it first", name)) + } if !format.Known(tmpl.Spec.Format.Name) { return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf( "credential %s names the format %q, which is not built in", name, tmpl.Spec.Format.Name)) @@ -115,6 +125,10 @@ func (o *OperationREST) Create(ctx context.Context, name string, obj runtime.Obj }, nil } + if engineIssued { + return o.regrant(ctx, name, res, user.GetName(), mirrored) + } + password, err := format.GeneratePassword() if err != nil { return nil, apierrors.NewInternalError(err) @@ -126,26 +140,8 @@ func (o *OperationREST) Create(ctx context.Context, name string, obj runtime.Obj now := metav1.NewTime(r.now()) by := user.GetName() sec := buildSecret(tmpl, stored, recordOf(tmpl).Apply(o.op, now, by)) - - // The status is all the API knows of the Secret. A status that lags the - // Secret, or a Secret written since the status was read, makes the write - // fail rather than overwrite it, and the caller gets a conflict and no - // password. - if mirrored == "" { - if err := r.direct.Create(ctx, sec); err != nil { - if apierrors.IsAlreadyExists(err) { - return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf("credential %s is being seeded; retry", name)) - } - return nil, err - } - } else { - sec.ResourceVersion = mirrored - if err := r.direct.Update(ctx, sec); err != nil { - if apierrors.IsConflict(err) || apierrors.IsNotFound(err) { - return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf("credential %s changed while the request was in flight; retry", name)) - } - return nil, err - } + if err := o.write(ctx, name, sec, mirrored); err != nil { + return nil, err } reason := ReasonCredentialIssued @@ -168,6 +164,32 @@ func (o *OperationREST) Create(ctx context.Context, name string, obj runtime.Obj }, nil } +// write stores the account Secret under the version the template's status +// mirrors, or creates it when the account has none. The status is all the +// API knows of the Secret. A status that lags the Secret, or a Secret written +// since the status was read, makes the write fail rather than overwrite it, +// and the caller gets a conflict and no password. +func (o *OperationREST) write(ctx context.Context, name string, sec *corev1.Secret, mirrored string) error { + r := o.parent + if mirrored == "" { + if err := r.direct.Create(ctx, sec); err != nil { + if apierrors.IsAlreadyExists(err) { + return apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf("credential %s is being seeded; retry", name)) + } + return err + } + return nil + } + sec.ResourceVersion = mirrored + if err := r.direct.Update(ctx, sec); err != nil { + if apierrors.IsConflict(err) || apierrors.IsNotFound(err) { + return apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf("credential %s changed while the request was in flight; retry", name)) + } + return err + } + return nil +} + // recordOf returns the record the template's status mirrors, which the mint // extends with its own operation. func recordOf(tmpl *cozyv1alpha1.CredentialTemplate) account.Record {