From d65f86277cc1c378f5896bda209a402bab781e46 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Mon, 23 Nov 2026 16:27:00 +0100 Subject: [PATCH] feat(api): serve Credentials with mint and revoke A Credential is a view over a CredentialTemplate's status, so a list or a get never reads a Secret. A mint builds the whole account Secret from the template and writes it under the Secret resourceVersion the template's status mirrors, so a concurrent mint or a seed in between fails with a conflict instead of silently replacing a password someone just received, and returns the plaintext once. A revoke stores a random password and discards it. A dry-run writes nothing. Each mint and revoke records an Event on the application naming the account and the caller, never the value, which needs create on events. The API review gate now captures a subresource registration such as credentials/mint as a resource of its own rather than dropping it. Co-authored-by: Timofei Larkin Assisted-by: LLM Signed-off-by: Andrei Kvapil --- internal/apigate/parse.go | 6 +- internal/apigate/parse_test.go | 4 + .../system/cozystack-api/templates/rbac.yaml | 5 + .../system/cozystack-api/tests/rbac_test.yaml | 21 +- pkg/apiserver/apiserver.go | 5 + pkg/registry/core/credential/event.go | 57 +++ pkg/registry/core/credential/rest.go | 281 +++++++++++++ pkg/registry/core/credential/rest_test.go | 387 ++++++++++++++++++ pkg/registry/core/credential/subresources.go | 224 ++++++++++ 9 files changed, 982 insertions(+), 8 deletions(-) create mode 100644 pkg/registry/core/credential/event.go create mode 100644 pkg/registry/core/credential/rest.go create mode 100644 pkg/registry/core/credential/rest_test.go create mode 100644 pkg/registry/core/credential/subresources.go diff --git a/internal/apigate/parse.go b/internal/apigate/parse.go index 0fe248f6c..5fa007dc1 100644 --- a/internal/apigate/parse.go +++ b/internal/apigate/parse.go @@ -172,10 +172,12 @@ var storageVarGroups = map[string]string{ // coreV1alpha1Storage["tenantsecrets"] = ... // // The plural class allows hyphens so a future hyphenated resource name is not -// silently dropped. The apps storage map is indexed by a variable +// silently dropped, and a slash so a subresource registration such as +// `credentials/mint` is gated as a resource of its own rather than dropped. +// The apps storage map is indexed by a variable // (appsV1alpha1Storage[resConfig.Application.Plural]), not a string literal, so // it never matches here — the apps API is covered by the cozyrds instead. -var apiserverStorageRe = regexp.MustCompile(`(\w+Storage)\["([a-z0-9-]+)"\]`) +var apiserverStorageRe = regexp.MustCompile(`(\w+Storage)\["([a-z0-9/-]+)"\]`) // unmappedStoragePrefix labels resources whose storage variable prefix is not // in storageVarGroups. Rather than silently dropping them — which would let a diff --git a/internal/apigate/parse_test.go b/internal/apigate/parse_test.go index 8c6ba577d..9bd254f2b 100644 --- a/internal/apigate/parse_test.go +++ b/internal/apigate/parse_test.go @@ -190,6 +190,7 @@ metadata: func TestParseAPIServerStorages(t *testing.T) { src := ` coreV1alpha1Storage["tenantsecrets"] = cozyregistry.RESTInPeace(x) + coreV1alpha1Storage["credentials/mint"] = credentialstorage.NewMintREST(w) sdnV1alpha1Storage["securitygroups"] = cozyregistry.RESTInPeace(y) appsV1alpha1Storage[resConfig.Application.Plural] = cozyregistry.RESTInPeace(z) ` @@ -204,6 +205,9 @@ func TestParseAPIServerStorages(t *testing.T) { if got["securitygroups"] != "sdn.cozystack.io" { t.Fatalf("expected sdn securitygroups, got %v", got) } + if got["credentials/mint"] != "core.cozystack.io" { + t.Fatalf("expected the subresource registration to be gated, got %v", got) + } if _, leaked := got["Plural"]; leaked { t.Fatalf("apps dynamic registration must not be captured: %v", got) } diff --git a/packages/system/cozystack-api/templates/rbac.yaml b/packages/system/cozystack-api/templates/rbac.yaml index a1eba49eb..a49b3099f 100644 --- a/packages/system/cozystack-api/templates/rbac.yaml +++ b/packages/system/cozystack-api/templates/rbac.yaml @@ -18,6 +18,11 @@ rules: - apiGroups: [""] resources: ["secrets"] verbs: ["create", "update", "patch", "delete"] +# A mint or revoke records an Event on the application naming the account and +# the caller, never the value. +- apiGroups: [""] + resources: ["events"] + verbs: ["create"] - apiGroups: ["admissionregistration.k8s.io"] resources: ["mutatingwebhookconfigurations", "validatingwebhookconfigurations", "validatingadmissionpolicies", "validatingadmissionpolicybindings"] verbs: ["get", "watch", "list"] diff --git a/packages/system/cozystack-api/tests/rbac_test.yaml b/packages/system/cozystack-api/tests/rbac_test.yaml index 18d4eb460..03b5e9d26 100644 --- a/packages/system/cozystack-api/tests/rbac_test.yaml +++ b/packages/system/cozystack-api/tests/rbac_test.yaml @@ -15,9 +15,9 @@ release: # the API group string exactly. # # The last two tests bound the role from two directions, and neither covers the -# other. The count bound pins the list at exactly twenty-one: templates/rbac.yaml -# carries no template directives, so anything appended makes rules[21] exist and -# anything dropped takes rules[20] away, whatever the rule is called. It says +# other. The count bound pins the list at exactly twenty-two: templates/rbac.yaml +# carries no template directives, so anything appended makes rules[22] exist and +# anything dropped takes rules[21] away, whatever the rule is called. It says # nothing about a grant swapped in for an existing one, because the count does # not move under a swap. The spelling assert catches that case for the one rule # it names, and misses every other wording of it, because helm-unittest compares @@ -85,11 +85,20 @@ tests: resources: ["bucketclasses"] verbs: ["get", "watch", "list"] - - it: ships exactly the twenty-one rules this role is pinned to + - it: grants create on events for the credential issued and revoked records + asserts: + - contains: + path: rules + content: + apiGroups: [""] + resources: ["events"] + verbs: ["create"] + + - it: ships exactly the twenty-two rules this role is pinned to asserts: # Both directions. A dropped grant is the failure this suite is about: # the apiserver returns forbidden and List silently drops the dropdown. - exists: - path: rules[20] - - notExists: path: rules[21] + - notExists: + path: rules[22] diff --git a/pkg/apiserver/apiserver.go b/pkg/apiserver/apiserver.go index 52df2e4cc..f52928cd5 100644 --- a/pkg/apiserver/apiserver.go +++ b/pkg/apiserver/apiserver.go @@ -47,6 +47,7 @@ import ( "github.com/cozystack/cozystack/pkg/config" cozyregistry "github.com/cozystack/cozystack/pkg/registry" applicationstorage "github.com/cozystack/cozystack/pkg/registry/apps/application" + credentialstorage "github.com/cozystack/cozystack/pkg/registry/core/credential" optionstorage "github.com/cozystack/cozystack/pkg/registry/core/option" tapstorage "github.com/cozystack/cozystack/pkg/registry/core/tap" tenantmodulestorage "github.com/cozystack/cozystack/pkg/registry/core/tenantmodule" @@ -259,6 +260,10 @@ func InstallStaticAPIGroups(server *genericapiserver.GenericAPIServer, cli clien coreV1alpha1Storage["taps"] = cozyregistry.RESTInPeace( tapstorage.NewREST(dyn), ) + credentials := credentialstorage.NewREST(cli, watchCli) + coreV1alpha1Storage["credentials"] = cozyregistry.RESTInPeace(credentials) + coreV1alpha1Storage["credentials/mint"] = credentialstorage.NewMintREST(credentials) + coreV1alpha1Storage["credentials/revoke"] = credentialstorage.NewRevokeREST(credentials) coreApiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(core.GroupName, Scheme, metav1.ParameterCodec, Codecs) coreApiGroupInfo.VersionedResourcesStorageMap["v1alpha1"] = coreV1alpha1Storage diff --git a/pkg/registry/core/credential/event.go b/pkg/registry/core/credential/event.go new file mode 100644 index 000000000..ad54c47b7 --- /dev/null +++ b/pkg/registry/core/credential/event.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 + +package credential + +import ( + "context" + "fmt" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/klog/v2" + "sigs.k8s.io/controller-runtime/pkg/client" + + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" +) + +// Event reasons the API records on an application for its credentials. +const ( + ReasonCredentialIssued = "CredentialIssued" + ReasonCredentialRevoked = "CredentialRevoked" +) + +// Emit records an Event on the application naming the account and the caller, +// never a value. Best effort: a failure is logged and does not fail the +// operation, which the audit log records in any case. +func Emit(ctx context.Context, c client.Client, hr *helmv2.HelmRelease, reason, username, by string) { + now := metav1.NewTime(time.Now()) + verb := "issued" + if reason == ReasonCredentialRevoked { + verb = "revoked" + } + ev := &corev1.Event{ + ObjectMeta: metav1.ObjectMeta{ + GenerateName: hr.Labels[appsv1alpha1.ApplicationNameLabel] + ".", + Namespace: hr.Namespace, + }, + InvolvedObject: corev1.ObjectReference{ + APIVersion: appsv1alpha1.SchemeGroupVersion.String(), + Kind: hr.Labels[appsv1alpha1.ApplicationKindLabel], + Name: hr.Labels[appsv1alpha1.ApplicationNameLabel], + Namespace: hr.Namespace, + UID: hr.UID, + }, + Reason: reason, + Message: fmt.Sprintf("password of user %s %s by %s", username, verb, by), + Type: corev1.EventTypeNormal, + Source: corev1.EventSource{Component: "cozystack-api"}, + FirstTimestamp: now, + LastTimestamp: now, + Count: 1, + } + if err := c.Create(ctx, ev); err != nil { + klog.Warningf("failed to record %s event for %s/%s: %v", reason, hr.Namespace, hr.Name, err) + } +} diff --git a/pkg/registry/core/credential/rest.go b/pkg/registry/core/credential/rest.go new file mode 100644 index 000000000..0126818fb --- /dev/null +++ b/pkg/registry/core/credential/rest.go @@ -0,0 +1,281 @@ +// SPDX-License-Identifier: Apache-2.0 + +// 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. +package credential + +import ( + "context" + "fmt" + "net/http" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metainternal "k8s.io/apimachinery/pkg/apis/meta/internalversion" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/duration" + "k8s.io/apiserver/pkg/endpoints/request" + "k8s.io/apiserver/pkg/registry/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" + "github.com/cozystack/cozystack/pkg/registry" + fieldfilter "github.com/cozystack/cozystack/pkg/registry/fields" + "github.com/cozystack/cozystack/pkg/registry/sorting" +) + +var ( + _ rest.Getter = &REST{} + _ rest.Lister = &REST{} + _ rest.TableConvertor = &REST{} + _ rest.Scoper = &REST{} + _ rest.SingularNameProvider = &REST{} +) + +const ( + singularName = "credential" + kindCredential = "Credential" + kindList = "CredentialList" +) + +// REST serves the credentials view. +type REST struct { + c client.Client + // direct reads and writes for mint and revoke, which the cached client + // would answer with a template status a moment old. + direct client.Client + gvr schema.GroupVersionResource + now func() time.Time +} + +// NewREST creates the credentials storage. +func NewREST(c, direct client.Client) *REST { + return &REST{ + c: c, + direct: direct, + gvr: schema.GroupVersionResource{ + Group: corev1alpha1.GroupName, + Version: "v1alpha1", + Resource: "credentials", + }, + now: time.Now, + } +} + +func (*REST) NamespaceScoped() bool { return true } +func (*REST) GetSingularName() string { return singularName } +func (*REST) Destroy() {} +func (*REST) New() runtime.Object { return &corev1alpha1.Credential{} } +func (*REST) NewList() runtime.Object { return &corev1alpha1.CredentialList{} } +func (*REST) Kind() string { return kindCredential } +func (r *REST) GroupVersionKind(schema.GroupVersion) schema.GroupVersionKind { + return r.gvr.GroupVersion().WithKind(kindCredential) +} + +func nsFrom(ctx context.Context) (string, error) { + ns, ok := request.NamespaceFrom(ctx) + if !ok || ns == "" { + return "", apierrors.NewBadRequest("namespace required") + } + return ns, nil +} + +// resolved is one account the registry has located: its template and the +// HelmRelease that rendered it. +type resolved struct { + tmpl *cozyv1alpha1.CredentialTemplate + hr *helmv2.HelmRelease +} + +// resolve locates the account a Credential name points at. The template must +// exist and the HelmRelease that rendered it must be live, or the credential +// does not exist. +func (r *REST) resolve(ctx context.Context, c client.Reader, namespace, name string) (*resolved, error) { + tmpl := &cozyv1alpha1.CredentialTemplate{} + if err := c.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, tmpl); err != nil { + if apierrors.IsNotFound(err) { + return nil, apierrors.NewNotFound(r.gvr.GroupResource(), name) + } + return nil, err + } + hr, err := r.release(ctx, c, tmpl, nil) + if err != nil { + return nil, err + } + if hr == nil { + return nil, apierrors.NewNotFound(r.gvr.GroupResource(), name) + } + return &resolved{tmpl: tmpl, hr: hr}, nil +} + +// release returns the live HelmRelease that rendered a template, nil when the +// template names none or its release is gone. cache saves a list from reading +// one release per template. +func (r *REST) release(ctx context.Context, c client.Reader, tmpl *cozyv1alpha1.CredentialTemplate, cache map[string]*helmv2.HelmRelease) (*helmv2.HelmRelease, error) { + name := tmpl.Annotations[account.ReleaseNameAnnotation] + if name == "" || !tmpl.DeletionTimestamp.IsZero() { + return nil, nil + } + if hr, seen := cache[name]; seen { + return hr, nil + } + hr := &helmv2.HelmRelease{} + if err := c.Get(ctx, types.NamespacedName{Namespace: tmpl.Namespace, Name: name}, hr); err != nil { + if !apierrors.IsNotFound(err) { + return nil, err + } + hr = nil + } + if cache != nil { + cache[name] = hr + } + return hr, nil +} + +// toCredential builds the view of one account from its template. +func toCredential(tmpl *cozyv1alpha1.CredentialTemplate, hr *helmv2.HelmRelease) corev1alpha1.Credential { + st := tmpl.Status + origin := corev1alpha1.CredentialOrigin(st.Password.Origin) + if origin == "" { + origin = corev1alpha1.CredentialOriginNotIssued + } + pw := corev1alpha1.CredentialPasswordState{Origin: origin, By: st.Password.By} + if st.Password.At != nil { + pw.At = *st.Password.At + } + var history []corev1alpha1.CredentialHistoryEntry + for _, h := range st.History { + history = append(history, corev1alpha1.CredentialHistoryEntry{Operation: corev1alpha1.CredentialOperation(h.Operation), At: h.At, By: h.By}) + } + return corev1alpha1.Credential{ + TypeMeta: metav1.TypeMeta{ + APIVersion: corev1alpha1.SchemeGroupVersion.String(), + Kind: kindCredential, + }, + ObjectMeta: metav1.ObjectMeta{ + Name: tmpl.Name, + Namespace: tmpl.Namespace, + UID: tmpl.UID, + ResourceVersion: st.SecretResourceVersion, + CreationTimestamp: tmpl.CreationTimestamp, + }, + Spec: corev1alpha1.CredentialSpec{ + Application: corev1alpha1.CredentialApplicationRef{ + APIGroup: hr.Labels[appsv1alpha1.ApplicationGroupLabel], + Kind: hr.Labels[appsv1alpha1.ApplicationKindLabel], + Name: hr.Labels[appsv1alpha1.ApplicationNameLabel], + }, + User: tmpl.Spec.Username, + }, + Status: corev1alpha1.CredentialStatus{Password: pw, History: history}, + } +} + +func (r *REST) Get(ctx context.Context, name string, _ *metav1.GetOptions) (runtime.Object, error) { + ns, err := nsFrom(ctx) + if err != nil { + return nil, err + } + res, err := r.resolve(ctx, r.c, ns, name) + if err != nil { + return nil, err + } + cred := toCredential(res.tmpl, res.hr) + return &cred, nil +} + +func (r *REST) List(ctx context.Context, opts *metainternal.ListOptions) (runtime.Object, error) { + ns, err := nsFrom(ctx) + if err != nil { + return nil, err + } + out := &corev1alpha1.CredentialList{ + TypeMeta: metav1.TypeMeta{ + APIVersion: corev1alpha1.SchemeGroupVersion.String(), + Kind: kindList, + }, + } + fieldFilter, err := fieldfilter.ParseFieldSelector(opts.FieldSelector) + if err != nil { + return nil, err + } + if fieldFilter.Namespace != "" && fieldFilter.Namespace != ns { + return out, nil + } + listOpts := &client.ListOptions{Namespace: ns} + if opts.LabelSelector != nil { + if _, selectable := opts.LabelSelector.Requirements(); !selectable { + return out, nil + } + listOpts.LabelSelector = opts.LabelSelector + } + + list := &cozyv1alpha1.CredentialTemplateList{} + if err := r.c.List(ctx, list, listOpts); err != nil { + return nil, err + } + releases := map[string]*helmv2.HelmRelease{} + for i := range list.Items { + tmpl := &list.Items[i] + hr, err := r.release(ctx, r.c, tmpl, releases) + if err != nil { + return nil, err + } + if hr == nil || !fieldFilter.MatchesName(tmpl.Name) { + continue + } + out.Items = append(out.Items, toCredential(tmpl, hr)) + } + listRV := list.ResourceVersion + if listRV == "" { + listRV, _ = registry.MaxResourceVersion(list) + } + out.ResourceVersion = listRV + sorting.ByNamespacedName[corev1alpha1.Credential, *corev1alpha1.Credential](out.Items) + return out, nil +} + +func (r *REST) ConvertToTable(ctx context.Context, object runtime.Object, _ runtime.Object) (*metav1.Table, error) { + table := &metav1.Table{ + ColumnDefinitions: []metav1.TableColumnDefinition{ + {Name: "Name", Type: "string", Format: "name"}, + {Name: "Application", Type: "string"}, + {Name: "User", Type: "string"}, + {Name: "Origin", Type: "string"}, + {Name: "Age", Type: "string"}, + }, + } + now := r.now() + row := func(c *corev1alpha1.Credential) metav1.TableRow { + age := "" + if !c.CreationTimestamp.IsZero() { + age = duration.HumanDuration(now.Sub(c.CreationTimestamp.Time)) + } + return metav1.TableRow{ + Cells: []any{c.Name, c.Spec.Application.Kind + "/" + c.Spec.Application.Name, c.Spec.User, string(c.Status.Password.Origin), age}, + Object: runtime.RawExtension{Object: c}, + } + } + switch v := object.(type) { + case *corev1alpha1.Credential: + table.Rows = append(table.Rows, row(v)) + case *corev1alpha1.CredentialList: + table.ResourceVersion = v.ResourceVersion + for i := range v.Items { + table.Rows = append(table.Rows, row(&v.Items[i])) + } + default: + return nil, apierrors.NewGenericServerResponse(http.StatusInternalServerError, "", r.gvr.GroupResource(), "", fmt.Sprintf("unexpected object type %T", object), 0, false) + } + return table, nil +} diff --git a/pkg/registry/core/credential/rest_test.go b/pkg/registry/core/credential/rest_test.go new file mode 100644 index 000000000..cce84140b --- /dev/null +++ b/pkg/registry/core/credential/rest_test.go @@ -0,0 +1,387 @@ +// SPDX-License-Identifier: Apache-2.0 + +package credential + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "flag" + "io" + "strings" + "testing" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metainternal "k8s.io/apimachinery/pkg/apis/meta/internalversion" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apiserver/pkg/authentication/user" + "k8s.io/apiserver/pkg/endpoints/request" + "k8s.io/klog/v2" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" +) + +const ( + ns = "tenant-foo" + release = "clickhouse-logs" + cred = release + ".web" +) + +// fixture is a fake cluster with one application release and the templates +// its chart rendered. writes counts every write a request makes, so a test +// can hold the API to one object per request. +type fixture struct { + c client.Client + r *REST + ctx context.Context + writes []string +} + +func newFixture(t *testing.T, objs ...client.Object) *fixture { + t.Helper() + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, helmv2.AddToScheme, cozyv1alpha1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + hr := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{ + Name: release, Namespace: ns, UID: "hr-uid", + Labels: map[string]string{ + appsv1alpha1.ApplicationGroupLabel: appsv1alpha1.GroupName, + appsv1alpha1.ApplicationKindLabel: "ClickHouse", + appsv1alpha1.ApplicationNameLabel: "logs", + }, + }} + f := &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.writes = append(f.writes, verb+" "+obj.GetName()) + } + } + } + c := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(append(objs, hr)...). + WithStatusSubresource(&cozyv1alpha1.CredentialTemplate{}). + WithInterceptorFuncs(interceptor.Funcs{ + Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + record("create")(ctx, c, obj) + return c.Create(ctx, obj, opts...) + }, + Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error { + record("update")(ctx, c, obj) + return c.Update(ctx, obj, opts...) + }, + Delete: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + record("delete")(ctx, c, obj) + return c.Delete(ctx, obj, opts...) + }, + }).Build() + f.c = c + f.r = NewREST(c, c) + f.r.now = func() time.Time { return time.Date(2026, 10, 2, 9, 14, 7, 0, time.UTC) } + f.ctx = request.WithUser(request.WithNamespace(context.Background(), ns), &user.DefaultInfo{Name: "jane@example.org"}) + return f +} + +func template(name, username string) *cozyv1alpha1.CredentialTemplate { + return &cozyv1alpha1.CredentialTemplate{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, Namespace: ns, UID: types.UID("uid-" + name), + Annotations: map[string]string{account.ReleaseNameAnnotation: release}, + }, + Spec: cozyv1alpha1.CredentialTemplateSpec{ + Username: username, + Format: cozyv1alpha1.CredentialTemplateFormat{Name: "sha256"}, + Secret: cozyv1alpha1.CredentialTemplateSecret{Labels: map[string]string{"reconcile.fluxcd.io/watch": "Enabled"}}, + }, + } +} + +// seeded returns a template with its Secret, as the controller leaves them: +// the Secret seeded and the template's status mirroring its version. +func (f *fixture) seeded(t *testing.T, name, username string) (*cozyv1alpha1.CredentialTemplate, *corev1.Secret) { + t.Helper() + tmpl := template(name, username) + if err := f.c.Create(f.ctx, tmpl); err != nil { + t.Fatal(err) + } + at := metav1.NewTime(f.r.now()) + sec := buildSecret(tmpl, "seed", account.Record{}.Apply(corev1alpha1.CredentialOperationCreate, at, "controller")) + if err := f.c.Create(f.ctx, sec); err != nil { + t.Fatal(err) + } + tmpl.Status.SecretResourceVersion = sec.ResourceVersion + tmpl.Status.Password = cozyv1alpha1.CredentialTemplatePasswordState{Origin: "NotIssued", By: "controller", At: &at} + tmpl.Status.History = []cozyv1alpha1.CredentialTemplateHistoryEntry{{Operation: "Create", At: at, By: "controller"}} + if err := f.c.Status().Update(f.ctx, tmpl); err != nil { + t.Fatal(err) + } + f.writes = nil + return tmpl, sec +} + +func (f *fixture) secret(t *testing.T, name string) *corev1.Secret { + t.Helper() + sec := &corev1.Secret{} + if err := f.c.Get(f.ctx, types.NamespacedName{Namespace: ns, Name: name}, sec); err != nil { + t.Fatalf("get %s: %v", name, err) + } + return sec +} + +func (f *fixture) do(op *OperationREST, name, precondition string, dryRun bool) (*corev1alpha1.CredentialRequest, error) { + req := &corev1alpha1.CredentialRequest{} + if precondition != "" { + req.Spec.Preconditions = &corev1alpha1.CredentialRequestPreconditions{ResourceVersion: precondition} + } + opts := &metav1.CreateOptions{} + if dryRun { + opts.DryRun = []string{metav1.DryRunAll} + } + out, err := op.Create(f.ctx, name, req, nil, opts) + if err != nil { + return nil, err + } + return out.(*corev1alpha1.CredentialRequest), nil +} + +func (f *fixture) events(t *testing.T) []corev1.Event { + t.Helper() + list := &corev1.EventList{} + if err := f.c.List(f.ctx, list, client.InNamespace(ns)); err != nil { + t.Fatal(err) + } + return list.Items +} + +func TestGetShowsTheMirroredRecord(t *testing.T) { + f := newFixture(t) + tmpl, sec := f.seeded(t, cred, "web") + obj, err := f.r.Get(f.ctx, cred, nil) + if err != nil { + t.Fatal(err) + } + c := obj.(*corev1alpha1.Credential) + if c.UID != tmpl.UID || c.ResourceVersion != sec.ResourceVersion { + t.Errorf("uid %q version %q, want the template's uid and the Secret's version", c.UID, c.ResourceVersion) + } + if c.Spec.User != "web" || c.Spec.Application.Kind != "ClickHouse" || c.Spec.Application.Name != "logs" { + t.Errorf("spec = %+v", c.Spec) + } + if c.Status.Password.Origin != corev1alpha1.CredentialOriginNotIssued || len(c.Status.History) != 1 { + t.Errorf("status = %+v", c.Status) + } +} + +func TestGetAndListSkipATemplateWithoutALiveRelease(t *testing.T) { + orphan := template(release+"-gone.web", "web") + orphan.Annotations[account.ReleaseNameAnnotation] = release + "-gone" + unrendered := template(release+".api", "api") + delete(unrendered.Annotations, account.ReleaseNameAnnotation) + f := newFixture(t, orphan, unrendered) + f.seeded(t, cred, "web") + for _, name := range []string{orphan.Name, unrendered.Name} { + if _, err := f.r.Get(f.ctx, name, nil); !apierrors.IsNotFound(err) { + t.Errorf("get %s: err = %v, want NotFound", name, err) + } + } + obj, err := f.r.List(f.ctx, &metainternal.ListOptions{}) + if err != nil { + t.Fatal(err) + } + items := obj.(*corev1alpha1.CredentialList).Items + if len(items) != 1 || items[0].Name != cred { + t.Errorf("list = %v, want only %s", items, cred) + } +} + +func TestListShowsAnAccountWithoutASecretAsNotIssued(t *testing.T) { + f := newFixture(t, template(cred, "web")) + obj, err := f.r.List(f.ctx, &metainternal.ListOptions{}) + if err != nil { + t.Fatal(err) + } + items := obj.(*corev1alpha1.CredentialList).Items + if len(items) != 1 || items[0].Status.Password.Origin != corev1alpha1.CredentialOriginNotIssued || items[0].ResourceVersion != "" { + t.Errorf("list = %+v", items) + } +} + +func TestMintWritesOneSecretUnderTheMirroredVersion(t *testing.T) { + f := newFixture(t) + tmpl, _ := f.seeded(t, cred, "web") + res, err := f.do(NewMintREST(f.r), cred, tmpl.Status.SecretResourceVersion, false) + if err != nil { + t.Fatal(err) + } + if len(f.writes) != 1 || f.writes[0] != "update "+cred+account.SecretSuffix { + t.Errorf("writes = %v, want one update of the account Secret", f.writes) + } + if len(res.Status.Password) != 32 || res.Status.Username != "web" { + t.Fatalf("answer = %+v", res.Status) + } + sec := f.secret(t, cred+account.SecretSuffix) + sum := sha256.Sum256([]byte(res.Status.Password)) + if string(sec.Data[account.PasswordKey]) != hex.EncodeToString(sum[:]) { + t.Error("the Secret does not hold the verifier of the minted password") + } + if sec.Labels["reconcile.fluxcd.io/watch"] != "Enabled" || sec.Labels[account.AccountLabel] != "true" { + t.Errorf("labels = %v", sec.Labels) + } + if ref := metav1.GetControllerOf(sec); ref == nil || ref.UID != tmpl.UID { + t.Errorf("controller = %v, want the template", ref) + } + rec := account.ReadRecord(sec) + if rec.Origin != corev1alpha1.CredentialOriginMinted || rec.By != "jane@example.org" || len(rec.History) != 2 { + t.Errorf("record = %+v, want Minted by the caller on top of the mirrored history", rec) + } + evs := f.events(t) + if len(evs) != 1 || evs[0].Reason != ReasonCredentialIssued { + t.Fatalf("events = %v", evs) + } + if strings.Contains(evs[0].Message, res.Status.Password) { + t.Error("the event carries the password") + } +} + +func TestMintCreatesTheSecretOfAnAccountThatHasNone(t *testing.T) { + f := newFixture(t, template(cred, "web")) + res, err := f.do(NewMintREST(f.r), cred, "", false) + if err != nil { + t.Fatal(err) + } + if len(f.writes) != 1 || f.writes[0] != "create "+cred+account.SecretSuffix { + t.Errorf("writes = %v, want one create of the account Secret", f.writes) + } + if res.Status.Password == "" { + t.Error("no password") + } +} + +func TestMintConflictsWhenTheStatusLagsTheSecret(t *testing.T) { + f := newFixture(t) + tmpl, sec := f.seeded(t, cred, "web") + // Somebody minted after the status was mirrored. + sec.Data[account.PasswordKey] = []byte("other") + if err := f.c.Update(f.ctx, sec); err != nil { + t.Fatal(err) + } + before := f.secret(t, sec.Name) + f.writes = nil + res, err := f.do(NewMintREST(f.r), cred, "", false) + if !apierrors.IsConflict(err) || res != nil { + t.Fatalf("err = %v, answer = %v, want a conflict and no password", err, res) + } + if after := f.secret(t, sec.Name); string(after.Data[account.PasswordKey]) != string(before.Data[account.PasswordKey]) { + t.Error("the Secret was overwritten") + } + _ = tmpl +} + +func TestMintConflictsOnAStalePrecondition(t *testing.T) { + f := newFixture(t) + f.seeded(t, cred, "web") + if _, err := f.do(NewMintREST(f.r), cred, "999999", false); !apierrors.IsConflict(err) { + t.Fatalf("err = %v, want a conflict", err) + } + if len(f.writes) != 0 { + t.Errorf("writes = %v, want none", f.writes) + } +} + +func TestMintRefusesAConflictingSecretAndAnUnknownFormat(t *testing.T) { + conflict := template(cred, "web") + conflict.Status.Conditions = []metav1.Condition{{Type: cozyv1alpha1.CredentialTemplateSecretConflict, Status: metav1.ConditionTrue, Reason: "ForeignSecret", LastTransitionTime: metav1.Now()}} + unknown := template(release+".api", "api") + unknown.Spec.Format.Name = "apr1" + f := newFixture(t, conflict, unknown) + for _, name := range []string{conflict.Name, unknown.Name} { + if _, err := f.do(NewMintREST(f.r), name, "", false); !apierrors.IsConflict(err) { + t.Errorf("mint %s: err = %v, want a conflict", name, err) + } + } + if len(f.writes) != 0 { + t.Errorf("writes = %v, want none", f.writes) + } +} + +func TestMintOnAMissingTemplateIsNotFound(t *testing.T) { + f := newFixture(t) + if _, err := f.do(NewMintREST(f.r), release+".nobody", "", false); !apierrors.IsNotFound(err) { + t.Fatalf("err = %v, want NotFound", err) + } +} + +func TestRevokeReturnsNoPassword(t *testing.T) { + f := newFixture(t) + f.seeded(t, cred, "web") + res, err := f.do(NewRevokeREST(f.r), cred, "", false) + if err != nil { + t.Fatal(err) + } + if res.Status.Password != "" { + t.Error("a revoke returned a password") + } + if rec := account.ReadRecord(f.secret(t, cred+account.SecretSuffix)); rec.Origin != corev1alpha1.CredentialOriginRevoked { + t.Errorf("origin = %s, want Revoked", rec.Origin) + } + if evs := f.events(t); len(evs) != 1 || evs[0].Reason != ReasonCredentialRevoked { + t.Errorf("events = %v", evs) + } +} + +func TestDryRunMintAndRevokeWriteNothing(t *testing.T) { + f := newFixture(t) + f.seeded(t, cred, "web") + for _, op := range []*OperationREST{NewMintREST(f.r), NewRevokeREST(f.r)} { + res, err := f.do(op, cred, "", true) + if err != nil { + t.Fatal(err) + } + if res.Status.Password != "" { + t.Error("a dry run returned a password") + } + } + if len(f.writes) != 0 || len(f.events(t)) != 0 { + t.Errorf("writes = %v, events = %v, want none", f.writes, f.events(t)) + } +} + +func TestMintLogsNoPassword(t *testing.T) { + var buf bytes.Buffer + fs := flag.NewFlagSet("klog", flag.ContinueOnError) + klog.InitFlags(fs) + _ = fs.Set("v", "10") + _ = fs.Set("logtostderr", "false") + klog.SetOutput(&buf) + defer func() { + klog.SetOutput(io.Discard) + _ = fs.Set("logtostderr", "true") + _ = fs.Set("v", "0") + }() + + f := newFixture(t) + f.seeded(t, cred, "web") + res, err := f.do(NewMintREST(f.r), cred, "", false) + if err != nil { + t.Fatal(err) + } + klog.Flush() + if strings.Contains(buf.String(), res.Status.Password) { + t.Fatal("the minted password reached the log") + } +} diff --git a/pkg/registry/core/credential/subresources.go b/pkg/registry/core/credential/subresources.go new file mode 100644 index 000000000..8f1158735 --- /dev/null +++ b/pkg/registry/core/credential/subresources.go @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: Apache-2.0 + +package credential + +import ( + "context" + "fmt" + + 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/runtime/schema" + "k8s.io/apiserver/pkg/endpoints/request" + "k8s.io/apiserver/pkg/registry/rest" + "k8s.io/apiserver/pkg/util/dryrun" + + 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" +) + +var ( + _ rest.NamedCreater = &OperationREST{} + _ rest.Scoper = &OperationREST{} + _ rest.GroupVersionKindProvider = &OperationREST{} +) + +// OperationREST is the mint or the revoke subresource of a Credential. Both +// take a CredentialRequest, build the whole account Secret from the template +// with the stored value of a fresh random password, and write it in one +// request: an update under the Secret version the template's status mirrors, +// or a create when the account has no Secret yet. The Secret is never read. A +// mint returns the password, once; a revoke discards it, so nobody holds a +// working one until the next mint. +type OperationREST struct { + parent *REST + op corev1alpha1.CredentialOperation +} + +// NewMintREST and NewRevokeREST return the two subresource storages of a +// credentials registry. +func NewMintREST(parent *REST) *OperationREST { + return &OperationREST{parent: parent, op: corev1alpha1.CredentialOperationMint} +} + +func NewRevokeREST(parent *REST) *OperationREST { + return &OperationREST{parent: parent, op: corev1alpha1.CredentialOperationRevoke} +} + +func (*OperationREST) New() runtime.Object { return &corev1alpha1.CredentialRequest{} } +func (*OperationREST) Destroy() {} +func (*OperationREST) NamespaceScoped() bool { return true } +func (o *OperationREST) GroupVersionKind(schema.GroupVersion) schema.GroupVersionKind { + return o.parent.gvr.GroupVersion().WithKind("CredentialRequest") +} + +// Create performs the operation on the named Credential. +func (o *OperationREST) Create(ctx context.Context, name string, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) { + req, ok := obj.(*corev1alpha1.CredentialRequest) + if !ok { + return nil, apierrors.NewBadRequest(fmt.Sprintf("expected CredentialRequest, got %T", obj)) + } + ns, err := nsFrom(ctx) + if err != nil { + return nil, err + } + user, ok := request.UserFrom(ctx) + if !ok { + return nil, apierrors.NewUnauthorized("user missing in context") + } + if createValidation != nil { + if err := createValidation(ctx, req); err != nil { + return nil, err + } + } + + r := o.parent + res, err := r.resolve(ctx, r.direct, ns, name) + if err != nil { + return nil, err + } + tmpl := res.tmpl + if meta.IsStatusConditionTrue(tmpl.Status.Conditions, cozyv1alpha1.CredentialTemplateSecretConflict) { + 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)) + } + 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)) + } + + var precondition string + if req.Spec.Preconditions != nil { + precondition = req.Spec.Preconditions.ResourceVersion + } + mirrored := tmpl.Status.SecretResourceVersion + // The Credential's version is the account Secret's, as the template's + // status mirrors it, so a caller that read the credential and sends that + // version back learns, as a conflict, that somebody minted in between + // instead of silently killing the password that person just received. + if precondition != "" && precondition != mirrored { + return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf( + "credential %s changed: password %s by %s", name, describe(corev1alpha1.CredentialOrigin(tmpl.Status.Password.Origin)), tmpl.Status.Password.By)) + } + + if options != nil && dryrun.IsDryRun(options.DryRun) { + // A dry run answers as the operation would, without a password: one + // that is never stored would not log in. + return &corev1alpha1.CredentialRequest{ + TypeMeta: metav1.TypeMeta{APIVersion: corev1alpha1.SchemeGroupVersion.String(), Kind: "CredentialRequest"}, + Status: corev1alpha1.CredentialRequestStatus{Username: tmpl.Spec.Username, IssuedAt: metav1.NewTime(r.now())}, + }, nil + } + + password, err := format.GeneratePassword() + if err != nil { + return nil, apierrors.NewInternalError(err) + } + stored, err := format.Encode(tmpl.Spec.Format.Name, password) + if err != nil { + return nil, apierrors.NewInternalError(err) + } + 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 + } + } + + reason := ReasonCredentialIssued + if o.op == corev1alpha1.CredentialOperationRevoke { + reason = ReasonCredentialRevoked + password = "" + } + Emit(ctx, r.direct, res.hr, reason, tmpl.Spec.Username, by) + + return &corev1alpha1.CredentialRequest{ + TypeMeta: metav1.TypeMeta{ + APIVersion: corev1alpha1.SchemeGroupVersion.String(), + Kind: "CredentialRequest", + }, + Status: corev1alpha1.CredentialRequestStatus{ + Username: tmpl.Spec.Username, + Password: password, + IssuedAt: now, + }, + }, 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 { + st := tmpl.Status + 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 +} + +// buildSecret builds the whole account Secret of a template, as the +// controller would seed it, with the given stored value and record. +func buildSecret(tmpl *cozyv1alpha1.CredentialTemplate, stored string, rec account.Record) *corev1.Secret { + controller := true + 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}, + OwnerReferences: []metav1.OwnerReference{{ + APIVersion: cozyv1alpha1.GroupVersion.String(), + Kind: "CredentialTemplate", + Name: tmpl.Name, + UID: tmpl.UID, + Controller: &controller, + BlockOwnerDeletion: &controller, + }}, + }, + Type: corev1.SecretTypeBasicAuth, + Data: map[string][]byte{ + account.UsernameKey: []byte(tmpl.Spec.Username), + account.PasswordKey: []byte(stored), + }, + } + account.WriteRecord(sec, rec) + return sec +} + +func describe(origin corev1alpha1.CredentialOrigin) string { + switch origin { + case corev1alpha1.CredentialOriginMinted: + return "issued" + case corev1alpha1.CredentialOriginRevoked: + return "revoked" + case corev1alpha1.CredentialOriginMigrated: + return "migrated" + } + return "seeded" +}