From 0ab26f7a8eabe47fb3a06a8b9b63c24389510075 Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Mon, 23 Nov 2026 16:26:58 +0100 Subject: [PATCH 01/10] feat(api): add the Credential kinds Cozystack generates managed application passwords at Helm render time and keeps them in a Secret tenants can read again at any time, which a deployment whose policy requires a credential shown once cannot accept. The accepted design moves generation into the platform: each account of a converted application gets a core.cozystack.io Credential, the record of who set its password and when, never the value, and its mint and revoke subresources take a TokenRequest-shaped CredentialRequest. Design: https://github.com/cozystack/community/blob/main/design-proposals/user-secrets-api/README.md Assisted-by: LLM Signed-off-by: Timofei Larkin Signed-off-by: Andrei Kvapil --- .../cozystack_api_violation_exceptions.list | 1 + pkg/apis/core/v1alpha1/credential_types.go | 141 ++++ pkg/apis/core/v1alpha1/model_name.go | 44 ++ pkg/apis/core/v1alpha1/register.go | 5 +- .../core/v1alpha1/zz_generated.deepcopy.go | 234 +++++++ pkg/generated/openapi/zz_generated.openapi.go | 618 ++++++++++++++---- 6 files changed, 931 insertions(+), 112 deletions(-) create mode 100644 pkg/apis/core/v1alpha1/credential_types.go diff --git a/api/api-rules/cozystack_api_violation_exceptions.list b/api/api-rules/cozystack_api_violation_exceptions.list index 310af75e0..0c9d9f826 100644 --- a/api/api-rules/cozystack_api_violation_exceptions.list +++ b/api/api-rules/cozystack_api_violation_exceptions.list @@ -1,4 +1,5 @@ API rule violation: list_type_missing,github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1,ApplicationStatus,Conditions +API rule violation: list_type_missing,github.com/cozystack/cozystack/pkg/apis/core/v1alpha1,CredentialStatus,History API rule violation: list_type_missing,github.com/cozystack/cozystack/pkg/apis/core/v1alpha1,OptionSpec,Items API rule violation: list_type_missing,github.com/cozystack/cozystack/pkg/apis/core/v1alpha1,TapPackage,Tags API rule violation: list_type_missing,github.com/cozystack/cozystack/pkg/apis/core/v1alpha1,TapSpec,Packages diff --git a/pkg/apis/core/v1alpha1/credential_types.go b/pkg/apis/core/v1alpha1/credential_types.go new file mode 100644 index 000000000..26a0b31ce --- /dev/null +++ b/pkg/apis/core/v1alpha1/credential_types.go @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: Apache-2.0 + +package v1alpha1 + +import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// Credential is the record of one account of a converted application: who can +// know the live password and who changed it, never the password or its stored +// form. It is a view over the status of the account's CredentialTemplate: +// cozystack-controller keeps the account Secret and mirrors its record into +// that status. See +// design-proposals/user-secrets-api in cozystack/community. +type Credential struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec CredentialSpec `json:"spec,omitempty"` + Status CredentialStatus `json:"status,omitempty"` +} + +// CredentialSpec identifies the account. It is derived from the application +// and read-only. +type CredentialSpec struct { + // Application is the managed application the account belongs to. + Application CredentialApplicationRef `json:"application"` + // User is the account name as the application declares it. + User string `json:"user"` +} + +// CredentialApplicationRef names a managed application. +type CredentialApplicationRef struct { + APIGroup string `json:"apiGroup"` + Kind string `json:"kind"` + Name string `json:"name"` +} + +// CredentialStatus is the account's record. +type CredentialStatus struct { + // Password says where the live password came from. + Password CredentialPasswordState `json:"password,omitempty"` + // History holds the last ten operations, newest first. + // +optional + History []CredentialHistoryEntry `json:"history,omitempty"` +} + +// CredentialOrigin says who can know the live password. +type CredentialOrigin string + +const ( + // CredentialOriginNotIssued: cozystack-controller seeded the account with + // a random password shown to nobody. Nobody can log in until someone + // mints. + CredentialOriginNotIssued CredentialOrigin = "NotIssued" + // CredentialOriginMigrated: the account went through the conversion with + // the password tenants could read before it; a mint should replace it. + CredentialOriginMigrated CredentialOrigin = "Migrated" + // CredentialOriginMinted: the password was shown once, to the caller of + // the mint recorded in At and By. + CredentialOriginMinted CredentialOrigin = "Minted" + // CredentialOriginRevoked: the live password is random and discarded, so + // nobody holds a working one until the next mint. + CredentialOriginRevoked CredentialOrigin = "Revoked" +) + +// CredentialPasswordState records the operation that set the live password. +type CredentialPasswordState struct { + Origin CredentialOrigin `json:"origin,omitempty"` + // +optional + At metav1.Time `json:"at,omitempty"` + // +optional + By string `json:"by,omitempty"` +} + +// CredentialOperation names a recorded operation on an account. +type CredentialOperation string + +const ( + CredentialOperationCreate CredentialOperation = "Create" + CredentialOperationMigrate CredentialOperation = "Migrate" + CredentialOperationMint CredentialOperation = "Mint" + CredentialOperationRevoke CredentialOperation = "Revoke" +) + +// CredentialHistoryEntry is one recorded operation. +type CredentialHistoryEntry struct { + Operation CredentialOperation `json:"operation"` + At metav1.Time `json:"at"` + By string `json:"by"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// CredentialList is a list of Credential objects. +type CredentialList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Credential `json:"items"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// CredentialRequest is the body and the answer of the mint and revoke +// subresources of a Credential, in the shape of a Kubernetes TokenRequest: a +// create on the subresource carries the request in spec and is answered with +// the result in status, and nothing is stored. +type CredentialRequest struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec CredentialRequestSpec `json:"spec,omitempty"` + Status CredentialRequestStatus `json:"status,omitempty"` +} + +// CredentialRequestSpec carries the caller's preconditions. +type CredentialRequestSpec struct { + // +optional + Preconditions *CredentialRequestPreconditions `json:"preconditions,omitempty"` +} + +// CredentialRequestPreconditions makes the operation conditional on the +// Credential being unchanged since the caller read it, so a mint cannot +// silently replace a password someone else just received. +type CredentialRequestPreconditions struct { + // ResourceVersion is the Credential's resourceVersion the caller last read. + // +optional + ResourceVersion string `json:"resourceVersion,omitempty"` +} + +// CredentialRequestStatus is the result of a mint or a revoke. +type CredentialRequestStatus struct { + // Username is the account name as the engine knows it. + Username string `json:"username,omitempty"` + // Password is the new plaintext, present in a mint's answer only and + // shown once. + // +optional + Password string `json:"password,omitempty"` + // IssuedAt is when the operation took effect in the record. + IssuedAt metav1.Time `json:"issuedAt,omitempty"` +} diff --git a/pkg/apis/core/v1alpha1/model_name.go b/pkg/apis/core/v1alpha1/model_name.go index 3ba6d8f36..133ad7f79 100644 --- a/pkg/apis/core/v1alpha1/model_name.go +++ b/pkg/apis/core/v1alpha1/model_name.go @@ -122,3 +122,47 @@ func (in TapPackage) OpenAPIModelName() string { func (in TapVerify) OpenAPIModelName() string { return "com.github.cozystack.cozystack.pkg.apis.core.v1alpha1.TapVerify" } + +func (in Credential) OpenAPIModelName() string { + return "com.github.cozystack.cozystack.pkg.apis.core.v1alpha1.Credential" +} + +func (in CredentialApplicationRef) OpenAPIModelName() string { + return "com.github.cozystack.cozystack.pkg.apis.core.v1alpha1.CredentialApplicationRef" +} + +func (in CredentialHistoryEntry) OpenAPIModelName() string { + return "com.github.cozystack.cozystack.pkg.apis.core.v1alpha1.CredentialHistoryEntry" +} + +func (in CredentialList) OpenAPIModelName() string { + return "com.github.cozystack.cozystack.pkg.apis.core.v1alpha1.CredentialList" +} + +func (in CredentialPasswordState) OpenAPIModelName() string { + return "com.github.cozystack.cozystack.pkg.apis.core.v1alpha1.CredentialPasswordState" +} + +func (in CredentialRequest) OpenAPIModelName() string { + return "com.github.cozystack.cozystack.pkg.apis.core.v1alpha1.CredentialRequest" +} + +func (in CredentialRequestPreconditions) OpenAPIModelName() string { + return "com.github.cozystack.cozystack.pkg.apis.core.v1alpha1.CredentialRequestPreconditions" +} + +func (in CredentialRequestSpec) OpenAPIModelName() string { + return "com.github.cozystack.cozystack.pkg.apis.core.v1alpha1.CredentialRequestSpec" +} + +func (in CredentialRequestStatus) OpenAPIModelName() string { + return "com.github.cozystack.cozystack.pkg.apis.core.v1alpha1.CredentialRequestStatus" +} + +func (in CredentialSpec) OpenAPIModelName() string { + return "com.github.cozystack.cozystack.pkg.apis.core.v1alpha1.CredentialSpec" +} + +func (in CredentialStatus) OpenAPIModelName() string { + return "com.github.cozystack.cozystack.pkg.apis.core.v1alpha1.CredentialStatus" +} diff --git a/pkg/apis/core/v1alpha1/register.go b/pkg/apis/core/v1alpha1/register.go index b1a840158..3686e80b2 100644 --- a/pkg/apis/core/v1alpha1/register.go +++ b/pkg/apis/core/v1alpha1/register.go @@ -65,7 +65,10 @@ func RegisterStaticTypes(scheme *runtime.Scheme) { &OptionList{}, &Tap{}, &TapList{}, + &Credential{}, + &CredentialList{}, + &CredentialRequest{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - klog.V(1).Info("Registered static kinds: TenantNamespace, TenantSecret, TenantModule, Option, Tap") + klog.V(1).Info("Registered static kinds: TenantNamespace, TenantSecret, TenantModule, Option, Tap, Credential, CredentialRequest") } diff --git a/pkg/apis/core/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/core/v1alpha1/zz_generated.deepcopy.go index 8088e27fd..f01e97a9d 100644 --- a/pkg/apis/core/v1alpha1/zz_generated.deepcopy.go +++ b/pkg/apis/core/v1alpha1/zz_generated.deepcopy.go @@ -26,6 +26,240 @@ import ( runtime "k8s.io/apimachinery/pkg/runtime" ) +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Credential) DeepCopyInto(out *Credential) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Credential. +func (in *Credential) DeepCopy() *Credential { + if in == nil { + return nil + } + out := new(Credential) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Credential) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialApplicationRef) DeepCopyInto(out *CredentialApplicationRef) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialApplicationRef. +func (in *CredentialApplicationRef) DeepCopy() *CredentialApplicationRef { + if in == nil { + return nil + } + out := new(CredentialApplicationRef) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialHistoryEntry) DeepCopyInto(out *CredentialHistoryEntry) { + *out = *in + in.At.DeepCopyInto(&out.At) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialHistoryEntry. +func (in *CredentialHistoryEntry) DeepCopy() *CredentialHistoryEntry { + if in == nil { + return nil + } + out := new(CredentialHistoryEntry) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialList) DeepCopyInto(out *CredentialList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Credential, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialList. +func (in *CredentialList) DeepCopy() *CredentialList { + if in == nil { + return nil + } + out := new(CredentialList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *CredentialList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialPasswordState) DeepCopyInto(out *CredentialPasswordState) { + *out = *in + in.At.DeepCopyInto(&out.At) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialPasswordState. +func (in *CredentialPasswordState) DeepCopy() *CredentialPasswordState { + if in == nil { + return nil + } + out := new(CredentialPasswordState) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialRequest) DeepCopyInto(out *CredentialRequest) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialRequest. +func (in *CredentialRequest) DeepCopy() *CredentialRequest { + if in == nil { + return nil + } + out := new(CredentialRequest) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *CredentialRequest) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialRequestPreconditions) DeepCopyInto(out *CredentialRequestPreconditions) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialRequestPreconditions. +func (in *CredentialRequestPreconditions) DeepCopy() *CredentialRequestPreconditions { + if in == nil { + return nil + } + out := new(CredentialRequestPreconditions) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialRequestSpec) DeepCopyInto(out *CredentialRequestSpec) { + *out = *in + if in.Preconditions != nil { + in, out := &in.Preconditions, &out.Preconditions + *out = new(CredentialRequestPreconditions) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialRequestSpec. +func (in *CredentialRequestSpec) DeepCopy() *CredentialRequestSpec { + if in == nil { + return nil + } + out := new(CredentialRequestSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialRequestStatus) DeepCopyInto(out *CredentialRequestStatus) { + *out = *in + in.IssuedAt.DeepCopyInto(&out.IssuedAt) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialRequestStatus. +func (in *CredentialRequestStatus) DeepCopy() *CredentialRequestStatus { + if in == nil { + return nil + } + out := new(CredentialRequestStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialSpec) DeepCopyInto(out *CredentialSpec) { + *out = *in + out.Application = in.Application + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialSpec. +func (in *CredentialSpec) DeepCopy() *CredentialSpec { + if in == nil { + return nil + } + out := new(CredentialSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialStatus) DeepCopyInto(out *CredentialStatus) { + *out = *in + in.Password.DeepCopyInto(&out.Password) + if in.History != nil { + in, out := &in.History, &out.History + *out = make([]CredentialHistoryEntry, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialStatus. +func (in *CredentialStatus) DeepCopy() *CredentialStatus { + if in == nil { + return nil + } + out := new(CredentialStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Option) DeepCopyInto(out *Option) { *out = *in diff --git a/pkg/generated/openapi/zz_generated.openapi.go b/pkg/generated/openapi/zz_generated.openapi.go index 6f5b41465..511e8bf8b 100644 --- a/pkg/generated/openapi/zz_generated.openapi.go +++ b/pkg/generated/openapi/zz_generated.openapi.go @@ -36,117 +36,128 @@ import ( func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition { return map[string]common.OpenAPIDefinition{ - v1alpha1.Application{}.OpenAPIModelName(): schema_pkg_apis_apps_v1alpha1_Application(ref), - v1alpha1.ApplicationList{}.OpenAPIModelName(): schema_pkg_apis_apps_v1alpha1_ApplicationList(ref), - v1alpha1.ApplicationStatus{}.OpenAPIModelName(): schema_pkg_apis_apps_v1alpha1_ApplicationStatus(ref), - corev1alpha1.Option{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_Option(ref), - corev1alpha1.OptionItem{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_OptionItem(ref), - corev1alpha1.OptionList{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_OptionList(ref), - corev1alpha1.OptionSpec{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_OptionSpec(ref), - corev1alpha1.Tap{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_Tap(ref), - corev1alpha1.TapList{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TapList(ref), - corev1alpha1.TapPackage{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TapPackage(ref), - corev1alpha1.TapSource{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TapSource(ref), - corev1alpha1.TapSpec{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TapSpec(ref), - corev1alpha1.TapVerify{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TapVerify(ref), - corev1alpha1.TenantModule{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantModule(ref), - corev1alpha1.TenantModuleList{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantModuleList(ref), - corev1alpha1.TenantModuleStatus{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantModuleStatus(ref), - corev1alpha1.TenantNamespace{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantNamespace(ref), - corev1alpha1.TenantNamespaceList{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantNamespaceList(ref), - corev1alpha1.TenantSecret{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantSecret(ref), - corev1alpha1.TenantSecretList{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantSecretList(ref), - sdnv1alpha1.ApplicationReference{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_ApplicationReference(ref), - sdnv1alpha1.EgressRule{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_EgressRule(ref), - sdnv1alpha1.FQDNSelector{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_FQDNSelector(ref), - sdnv1alpha1.IngressRule{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_IngressRule(ref), - sdnv1alpha1.PortProtocol{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_PortProtocol(ref), - sdnv1alpha1.PortRule{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_PortRule(ref), - sdnv1alpha1.SecurityGroup{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_SecurityGroup(ref), - sdnv1alpha1.SecurityGroupList{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_SecurityGroupList(ref), - sdnv1alpha1.SecurityGroupSpec{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_SecurityGroupSpec(ref), - v1.ConversionRequest{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_ConversionRequest(ref), - v1.ConversionResponse{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_ConversionResponse(ref), - v1.ConversionReview{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_ConversionReview(ref), - v1.CustomResourceColumnDefinition{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceColumnDefinition(ref), - v1.CustomResourceConversion{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceConversion(ref), - v1.CustomResourceDefinition{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceDefinition(ref), - v1.CustomResourceDefinitionCondition{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceDefinitionCondition(ref), - v1.CustomResourceDefinitionList{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceDefinitionList(ref), - v1.CustomResourceDefinitionNames{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceDefinitionNames(ref), - v1.CustomResourceDefinitionSpec{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceDefinitionSpec(ref), - v1.CustomResourceDefinitionStatus{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceDefinitionStatus(ref), - v1.CustomResourceDefinitionVersion{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceDefinitionVersion(ref), - v1.CustomResourceSubresourceScale{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceSubresourceScale(ref), - v1.CustomResourceSubresourceStatus{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceSubresourceStatus(ref), - v1.CustomResourceSubresources{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceSubresources(ref), - v1.CustomResourceValidation{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceValidation(ref), - v1.ExternalDocumentation{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_ExternalDocumentation(ref), - v1.JSON{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_JSON(ref), - v1.JSONSchemaProps{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_JSONSchemaProps(ref), - v1.JSONSchemaPropsOrArray{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_JSONSchemaPropsOrArray(ref), - v1.JSONSchemaPropsOrBool{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_JSONSchemaPropsOrBool(ref), - v1.JSONSchemaPropsOrStringArray{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_JSONSchemaPropsOrStringArray(ref), - v1.SelectableField{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_SelectableField(ref), - v1.ServiceReference{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_ServiceReference(ref), - v1.ValidationRule{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_ValidationRule(ref), - v1.WebhookClientConfig{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_WebhookClientConfig(ref), - v1.WebhookConversion{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_WebhookConversion(ref), - resource.Quantity{}.OpenAPIModelName(): schema_apimachinery_pkg_api_resource_Quantity(ref), - metav1.APIGroup{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_APIGroup(ref), - metav1.APIGroupList{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_APIGroupList(ref), - metav1.APIResource{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_APIResource(ref), - metav1.APIResourceList{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_APIResourceList(ref), - metav1.APIVersions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_APIVersions(ref), - metav1.ApplyOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_ApplyOptions(ref), - metav1.Condition{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Condition(ref), - metav1.CreateOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_CreateOptions(ref), - metav1.DeleteOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_DeleteOptions(ref), - metav1.Duration{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Duration(ref), - metav1.FieldSelectorRequirement{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_FieldSelectorRequirement(ref), - metav1.FieldsV1{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_FieldsV1(ref), - metav1.GetOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_GetOptions(ref), - metav1.GroupKind{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_GroupKind(ref), - metav1.GroupResource{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_GroupResource(ref), - metav1.GroupVersion{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_GroupVersion(ref), - metav1.GroupVersionForDiscovery{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_GroupVersionForDiscovery(ref), - metav1.GroupVersionKind{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_GroupVersionKind(ref), - metav1.GroupVersionResource{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_GroupVersionResource(ref), - metav1.InternalEvent{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_InternalEvent(ref), - metav1.LabelSelector{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_LabelSelector(ref), - metav1.LabelSelectorRequirement{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_LabelSelectorRequirement(ref), - metav1.List{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_List(ref), - metav1.ListMeta{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_ListMeta(ref), - metav1.ListOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_ListOptions(ref), - metav1.ManagedFieldsEntry{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_ManagedFieldsEntry(ref), - metav1.MicroTime{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_MicroTime(ref), - metav1.ObjectMeta{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_ObjectMeta(ref), - metav1.OwnerReference{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_OwnerReference(ref), - metav1.PartialObjectMetadata{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_PartialObjectMetadata(ref), - metav1.PartialObjectMetadataList{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_PartialObjectMetadataList(ref), - metav1.Patch{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Patch(ref), - metav1.PatchOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_PatchOptions(ref), - metav1.Preconditions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Preconditions(ref), - metav1.RootPaths{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_RootPaths(ref), - metav1.ServerAddressByClientCIDR{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_ServerAddressByClientCIDR(ref), - metav1.ShardInfo{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_ShardInfo(ref), - metav1.Status{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Status(ref), - metav1.StatusCause{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_StatusCause(ref), - metav1.StatusDetails{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_StatusDetails(ref), - metav1.Table{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Table(ref), - metav1.TableColumnDefinition{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_TableColumnDefinition(ref), - metav1.TableOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_TableOptions(ref), - metav1.TableRow{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_TableRow(ref), - metav1.TableRowCondition{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_TableRowCondition(ref), - metav1.Time{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Time(ref), - metav1.Timestamp{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Timestamp(ref), - metav1.TypeMeta{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_TypeMeta(ref), - metav1.UpdateOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_UpdateOptions(ref), - metav1.WatchEvent{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_WatchEvent(ref), - runtime.RawExtension{}.OpenAPIModelName(): schema_k8sio_apimachinery_pkg_runtime_RawExtension(ref), - runtime.TypeMeta{}.OpenAPIModelName(): schema_k8sio_apimachinery_pkg_runtime_TypeMeta(ref), - runtime.Unknown{}.OpenAPIModelName(): schema_k8sio_apimachinery_pkg_runtime_Unknown(ref), - version.Info{}.OpenAPIModelName(): schema_k8sio_apimachinery_pkg_version_Info(ref), + v1alpha1.Application{}.OpenAPIModelName(): schema_pkg_apis_apps_v1alpha1_Application(ref), + v1alpha1.ApplicationList{}.OpenAPIModelName(): schema_pkg_apis_apps_v1alpha1_ApplicationList(ref), + v1alpha1.ApplicationStatus{}.OpenAPIModelName(): schema_pkg_apis_apps_v1alpha1_ApplicationStatus(ref), + corev1alpha1.Credential{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_Credential(ref), + corev1alpha1.CredentialApplicationRef{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_CredentialApplicationRef(ref), + corev1alpha1.CredentialHistoryEntry{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_CredentialHistoryEntry(ref), + corev1alpha1.CredentialList{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_CredentialList(ref), + corev1alpha1.CredentialPasswordState{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_CredentialPasswordState(ref), + corev1alpha1.CredentialRequest{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_CredentialRequest(ref), + corev1alpha1.CredentialRequestPreconditions{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_CredentialRequestPreconditions(ref), + corev1alpha1.CredentialRequestSpec{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_CredentialRequestSpec(ref), + corev1alpha1.CredentialRequestStatus{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_CredentialRequestStatus(ref), + corev1alpha1.CredentialSpec{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_CredentialSpec(ref), + corev1alpha1.CredentialStatus{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_CredentialStatus(ref), + corev1alpha1.Option{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_Option(ref), + corev1alpha1.OptionItem{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_OptionItem(ref), + corev1alpha1.OptionList{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_OptionList(ref), + corev1alpha1.OptionSpec{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_OptionSpec(ref), + corev1alpha1.Tap{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_Tap(ref), + corev1alpha1.TapList{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TapList(ref), + corev1alpha1.TapPackage{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TapPackage(ref), + corev1alpha1.TapSource{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TapSource(ref), + corev1alpha1.TapSpec{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TapSpec(ref), + corev1alpha1.TapVerify{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TapVerify(ref), + corev1alpha1.TenantModule{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantModule(ref), + corev1alpha1.TenantModuleList{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantModuleList(ref), + corev1alpha1.TenantModuleStatus{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantModuleStatus(ref), + corev1alpha1.TenantNamespace{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantNamespace(ref), + corev1alpha1.TenantNamespaceList{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantNamespaceList(ref), + corev1alpha1.TenantSecret{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantSecret(ref), + corev1alpha1.TenantSecretList{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantSecretList(ref), + sdnv1alpha1.ApplicationReference{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_ApplicationReference(ref), + sdnv1alpha1.EgressRule{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_EgressRule(ref), + sdnv1alpha1.FQDNSelector{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_FQDNSelector(ref), + sdnv1alpha1.IngressRule{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_IngressRule(ref), + sdnv1alpha1.PortProtocol{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_PortProtocol(ref), + sdnv1alpha1.PortRule{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_PortRule(ref), + sdnv1alpha1.SecurityGroup{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_SecurityGroup(ref), + sdnv1alpha1.SecurityGroupList{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_SecurityGroupList(ref), + sdnv1alpha1.SecurityGroupSpec{}.OpenAPIModelName(): schema_pkg_apis_sdn_v1alpha1_SecurityGroupSpec(ref), + v1.ConversionRequest{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_ConversionRequest(ref), + v1.ConversionResponse{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_ConversionResponse(ref), + v1.ConversionReview{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_ConversionReview(ref), + v1.CustomResourceColumnDefinition{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceColumnDefinition(ref), + v1.CustomResourceConversion{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceConversion(ref), + v1.CustomResourceDefinition{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceDefinition(ref), + v1.CustomResourceDefinitionCondition{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceDefinitionCondition(ref), + v1.CustomResourceDefinitionList{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceDefinitionList(ref), + v1.CustomResourceDefinitionNames{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceDefinitionNames(ref), + v1.CustomResourceDefinitionSpec{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceDefinitionSpec(ref), + v1.CustomResourceDefinitionStatus{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceDefinitionStatus(ref), + v1.CustomResourceDefinitionVersion{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceDefinitionVersion(ref), + v1.CustomResourceSubresourceScale{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceSubresourceScale(ref), + v1.CustomResourceSubresourceStatus{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceSubresourceStatus(ref), + v1.CustomResourceSubresources{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceSubresources(ref), + v1.CustomResourceValidation{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_CustomResourceValidation(ref), + v1.ExternalDocumentation{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_ExternalDocumentation(ref), + v1.JSON{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_JSON(ref), + v1.JSONSchemaProps{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_JSONSchemaProps(ref), + v1.JSONSchemaPropsOrArray{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_JSONSchemaPropsOrArray(ref), + v1.JSONSchemaPropsOrBool{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_JSONSchemaPropsOrBool(ref), + v1.JSONSchemaPropsOrStringArray{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_JSONSchemaPropsOrStringArray(ref), + v1.SelectableField{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_SelectableField(ref), + v1.ServiceReference{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_ServiceReference(ref), + v1.ValidationRule{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_ValidationRule(ref), + v1.WebhookClientConfig{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_WebhookClientConfig(ref), + v1.WebhookConversion{}.OpenAPIModelName(): schema_pkg_apis_apiextensions_v1_WebhookConversion(ref), + resource.Quantity{}.OpenAPIModelName(): schema_apimachinery_pkg_api_resource_Quantity(ref), + metav1.APIGroup{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_APIGroup(ref), + metav1.APIGroupList{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_APIGroupList(ref), + metav1.APIResource{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_APIResource(ref), + metav1.APIResourceList{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_APIResourceList(ref), + metav1.APIVersions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_APIVersions(ref), + metav1.ApplyOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_ApplyOptions(ref), + metav1.Condition{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Condition(ref), + metav1.CreateOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_CreateOptions(ref), + metav1.DeleteOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_DeleteOptions(ref), + metav1.Duration{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Duration(ref), + metav1.FieldSelectorRequirement{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_FieldSelectorRequirement(ref), + metav1.FieldsV1{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_FieldsV1(ref), + metav1.GetOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_GetOptions(ref), + metav1.GroupKind{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_GroupKind(ref), + metav1.GroupResource{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_GroupResource(ref), + metav1.GroupVersion{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_GroupVersion(ref), + metav1.GroupVersionForDiscovery{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_GroupVersionForDiscovery(ref), + metav1.GroupVersionKind{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_GroupVersionKind(ref), + metav1.GroupVersionResource{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_GroupVersionResource(ref), + metav1.InternalEvent{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_InternalEvent(ref), + metav1.LabelSelector{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_LabelSelector(ref), + metav1.LabelSelectorRequirement{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_LabelSelectorRequirement(ref), + metav1.List{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_List(ref), + metav1.ListMeta{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_ListMeta(ref), + metav1.ListOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_ListOptions(ref), + metav1.ManagedFieldsEntry{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_ManagedFieldsEntry(ref), + metav1.MicroTime{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_MicroTime(ref), + metav1.ObjectMeta{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_ObjectMeta(ref), + metav1.OwnerReference{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_OwnerReference(ref), + metav1.PartialObjectMetadata{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_PartialObjectMetadata(ref), + metav1.PartialObjectMetadataList{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_PartialObjectMetadataList(ref), + metav1.Patch{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Patch(ref), + metav1.PatchOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_PatchOptions(ref), + metav1.Preconditions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Preconditions(ref), + metav1.RootPaths{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_RootPaths(ref), + metav1.ServerAddressByClientCIDR{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_ServerAddressByClientCIDR(ref), + metav1.ShardInfo{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_ShardInfo(ref), + metav1.Status{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Status(ref), + metav1.StatusCause{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_StatusCause(ref), + metav1.StatusDetails{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_StatusDetails(ref), + metav1.Table{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Table(ref), + metav1.TableColumnDefinition{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_TableColumnDefinition(ref), + metav1.TableOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_TableOptions(ref), + metav1.TableRow{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_TableRow(ref), + metav1.TableRowCondition{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_TableRowCondition(ref), + metav1.Time{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Time(ref), + metav1.Timestamp{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_Timestamp(ref), + metav1.TypeMeta{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_TypeMeta(ref), + metav1.UpdateOptions{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_UpdateOptions(ref), + metav1.WatchEvent{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_WatchEvent(ref), + runtime.RawExtension{}.OpenAPIModelName(): schema_k8sio_apimachinery_pkg_runtime_RawExtension(ref), + runtime.TypeMeta{}.OpenAPIModelName(): schema_k8sio_apimachinery_pkg_runtime_TypeMeta(ref), + runtime.Unknown{}.OpenAPIModelName(): schema_k8sio_apimachinery_pkg_runtime_Unknown(ref), + version.Info{}.OpenAPIModelName(): schema_k8sio_apimachinery_pkg_version_Info(ref), } } @@ -319,6 +330,391 @@ func schema_pkg_apis_apps_v1alpha1_ApplicationStatus(ref common.ReferenceCallbac } } +func schema_pkg_apis_core_v1alpha1_Credential(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "Credential is the record of one account of a converted application: who can know the live password and who changed it, never the password or its stored form. It is a view over the status of the account's CredentialTemplate: cozystack-controller keeps the account Secret and mirrors its record into that status. See design-proposals/user-secrets-api in cozystack/community.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref(metav1.ObjectMeta{}.OpenAPIModelName()), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref(corev1alpha1.CredentialSpec{}.OpenAPIModelName()), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref(corev1alpha1.CredentialStatus{}.OpenAPIModelName()), + }, + }, + }, + }, + }, + Dependencies: []string{ + corev1alpha1.CredentialSpec{}.OpenAPIModelName(), corev1alpha1.CredentialStatus{}.OpenAPIModelName(), metav1.ObjectMeta{}.OpenAPIModelName()}, + } +} + +func schema_pkg_apis_core_v1alpha1_CredentialApplicationRef(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "CredentialApplicationRef names a managed application.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "apiGroup": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "kind": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "name": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"apiGroup", "kind", "name"}, + }, + }, + } +} + +func schema_pkg_apis_core_v1alpha1_CredentialHistoryEntry(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "CredentialHistoryEntry is one recorded operation.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "operation": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "at": { + SchemaProps: spec.SchemaProps{ + Ref: ref(metav1.Time{}.OpenAPIModelName()), + }, + }, + "by": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"operation", "at", "by"}, + }, + }, + Dependencies: []string{ + metav1.Time{}.OpenAPIModelName()}, + } +} + +func schema_pkg_apis_core_v1alpha1_CredentialList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "CredentialList is a list of Credential objects.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref(metav1.ListMeta{}.OpenAPIModelName()), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Ref: ref(corev1alpha1.Credential{}.OpenAPIModelName()), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + corev1alpha1.Credential{}.OpenAPIModelName(), metav1.ListMeta{}.OpenAPIModelName()}, + } +} + +func schema_pkg_apis_core_v1alpha1_CredentialPasswordState(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "CredentialPasswordState records the operation that set the live password.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "origin": { + SchemaProps: spec.SchemaProps{ + Type: []string{"string"}, + Format: "", + }, + }, + "at": { + SchemaProps: spec.SchemaProps{ + Ref: ref(metav1.Time{}.OpenAPIModelName()), + }, + }, + "by": { + SchemaProps: spec.SchemaProps{ + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + Dependencies: []string{ + metav1.Time{}.OpenAPIModelName()}, + } +} + +func schema_pkg_apis_core_v1alpha1_CredentialRequest(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "CredentialRequest is the body and the answer of the mint and revoke subresources of a Credential, in the shape of a Kubernetes TokenRequest: a create on the subresource carries the request in spec and is answered with the result in status, and nothing is stored.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref(metav1.ObjectMeta{}.OpenAPIModelName()), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref(corev1alpha1.CredentialRequestSpec{}.OpenAPIModelName()), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref(corev1alpha1.CredentialRequestStatus{}.OpenAPIModelName()), + }, + }, + }, + }, + }, + Dependencies: []string{ + corev1alpha1.CredentialRequestSpec{}.OpenAPIModelName(), corev1alpha1.CredentialRequestStatus{}.OpenAPIModelName(), metav1.ObjectMeta{}.OpenAPIModelName()}, + } +} + +func schema_pkg_apis_core_v1alpha1_CredentialRequestPreconditions(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "CredentialRequestPreconditions makes the operation conditional on the Credential being unchanged since the caller read it, so a mint cannot silently replace a password someone else just received.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "resourceVersion": { + SchemaProps: spec.SchemaProps{ + Description: "ResourceVersion is the Credential's resourceVersion the caller last read.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + } +} + +func schema_pkg_apis_core_v1alpha1_CredentialRequestSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "CredentialRequestSpec carries the caller's preconditions.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "preconditions": { + SchemaProps: spec.SchemaProps{ + Ref: ref(corev1alpha1.CredentialRequestPreconditions{}.OpenAPIModelName()), + }, + }, + }, + }, + }, + Dependencies: []string{ + corev1alpha1.CredentialRequestPreconditions{}.OpenAPIModelName()}, + } +} + +func schema_pkg_apis_core_v1alpha1_CredentialRequestStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "CredentialRequestStatus is the result of a mint or a revoke.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "username": { + SchemaProps: spec.SchemaProps{ + Description: "Username is the account name as the engine knows it.", + Type: []string{"string"}, + Format: "", + }, + }, + "password": { + SchemaProps: spec.SchemaProps{ + Description: "Password is the new plaintext, present in a mint's answer only and shown once.", + Type: []string{"string"}, + Format: "", + }, + }, + "issuedAt": { + SchemaProps: spec.SchemaProps{ + Description: "IssuedAt is when the operation took effect in the record.", + Ref: ref(metav1.Time{}.OpenAPIModelName()), + }, + }, + }, + }, + }, + Dependencies: []string{ + metav1.Time{}.OpenAPIModelName()}, + } +} + +func schema_pkg_apis_core_v1alpha1_CredentialSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "CredentialSpec identifies the account. It is derived from the application and read-only.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "application": { + SchemaProps: spec.SchemaProps{ + Description: "Application is the managed application the account belongs to.", + Default: map[string]interface{}{}, + Ref: ref(corev1alpha1.CredentialApplicationRef{}.OpenAPIModelName()), + }, + }, + "user": { + SchemaProps: spec.SchemaProps{ + Description: "User is the account name as the application declares it.", + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"application", "user"}, + }, + }, + Dependencies: []string{ + corev1alpha1.CredentialApplicationRef{}.OpenAPIModelName()}, + } +} + +func schema_pkg_apis_core_v1alpha1_CredentialStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "CredentialStatus is the account's record.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "password": { + SchemaProps: spec.SchemaProps{ + Description: "Password says where the live password came from.", + Default: map[string]interface{}{}, + Ref: ref(corev1alpha1.CredentialPasswordState{}.OpenAPIModelName()), + }, + }, + "history": { + SchemaProps: spec.SchemaProps{ + Description: "History holds the last ten operations, newest first.", + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Ref: ref(corev1alpha1.CredentialHistoryEntry{}.OpenAPIModelName()), + }, + }, + }, + }, + }, + }, + }, + }, + Dependencies: []string{ + corev1alpha1.CredentialHistoryEntry{}.OpenAPIModelName(), corev1alpha1.CredentialPasswordState{}.OpenAPIModelName()}, + } +} + func schema_pkg_apis_core_v1alpha1_Option(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ From 0cd89dc1c85970af1881a03abf23ec51b8ce5a7d Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Mon, 23 Nov 2026 16:26:59 +0100 Subject: [PATCH 02/10] feat(credentials): add the built-in password formats The platform stores what an engine checks a password against, not the password: a SCRAM-SHA-256 verifier for PostgreSQL, the mysql_native_password hash for MariaDB, the SHA-256 hex for ClickHouse, and the plaintext only for an engine whose operator computes its own verifier. The migration tooling imports the same package, so a converted release and a mint store the same form. CodeQL flags the SHA-1 and SHA-256 of a password as weak hashing of sensitive data. Both are the forms the engines store and check against and accept in no other form, and the design relies on the 32-character random password rather than on the digest for strength, so the code says that where the hashing happens. Assisted-by: LLM Signed-off-by: Timofei Larkin Signed-off-by: Andrei Kvapil --- pkg/credentials/format/format.go | 138 ++++++++++++++++++++++++++ pkg/credentials/format/format_test.go | 122 +++++++++++++++++++++++ 2 files changed, 260 insertions(+) create mode 100644 pkg/credentials/format/format.go create mode 100644 pkg/credentials/format/format_test.go diff --git a/pkg/credentials/format/format.go b/pkg/credentials/format/format.go new file mode 100644 index 000000000..7f7592cac --- /dev/null +++ b/pkg/credentials/format/format.go @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package format turns a password into the value an engine stores to check +// it, and generates the passwords. The migration tooling imports it too, so a +// migrated release and a mint store the same form. +package format + +import ( + "crypto/hmac" + "crypto/pbkdf2" + "crypto/rand" + "crypto/sha1" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "fmt" + "strings" +) + +// Built-in format names. +const ( + // ScramSHA256 is PostgreSQL's SCRAM-SHA-256 verifier, + // SCRAM-SHA-256$:$:, which + // ALTER ROLE ... PASSWORD stores as it is. + ScramSHA256 = "scram-sha-256" + // MySQLNative is the mysql_native_password hash, "*" followed by the + // upper-case hex of SHA1(SHA1(password)), which mariadb-operator pastes + // into ALTER USER ... IDENTIFIED BY PASSWORD as it is. + MySQLNative = "mysql-native" + // SHA256 is the lower-case hex of SHA-256(password), ClickHouse's + // password_sha256_hex. + SHA256 = "sha256" + // Plaintext stores the password itself, for an engine whose operator or + // server computes its own verifier from it. + Plaintext = "plaintext" +) + +// PasswordLength is the length of every generated password. +const PasswordLength = 32 + +// passwordAlphabet needs no escaping in SQL, connection URIs or shells, and +// 32 characters of it carry about 190 bits of entropy. +const passwordAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + +// scramIterations is PostgreSQL's default for SCRAM-SHA-256. +const scramIterations = 4096 + +// scramSaltLength matches what PostgreSQL itself generates. +const scramSaltLength = 16 + +// Known reports whether name is a built-in format. +func Known(name string) bool { + switch name { + case ScramSHA256, MySQLNative, SHA256, Plaintext: + return true + } + return false +} + +// GeneratePassword draws PasswordLength characters uniformly from the +// alphabet with crypto/rand. Rejection sampling keeps the draw unbiased: a +// byte is accepted only below the largest multiple of the alphabet size. +func GeneratePassword() (string, error) { + const limit = byte(256 - 256%len(passwordAlphabet)) + out := make([]byte, 0, PasswordLength) + buf := make([]byte, PasswordLength*2) + for len(out) < PasswordLength { + if _, err := rand.Read(buf); err != nil { + return "", fmt.Errorf("read random bytes: %w", err) + } + for _, b := range buf { + if b >= limit { + continue + } + out = append(out, passwordAlphabet[int(b)%len(passwordAlphabet)]) + if len(out) == PasswordLength { + break + } + } + } + return string(out), nil +} + +// Encode returns the stored form of password in the named built-in format. +func Encode(name, password string) (string, error) { + switch name { + case ScramSHA256: + salt := make([]byte, scramSaltLength) + if _, err := rand.Read(salt); err != nil { + return "", fmt.Errorf("read salt: %w", err) + } + return encodeScramSHA256(password, salt, scramIterations) + case MySQLNative: + return encodeMySQLNative(password), nil + case SHA256: + // Unsalted: ClickHouse's password_sha256_hex accepts no other form. + sum := sha256.Sum256([]byte(password)) + return hex.EncodeToString(sum[:]), nil + case Plaintext: + return password, nil + } + return "", fmt.Errorf("unknown password format %q", name) +} + +// encodeScramSHA256 builds the verifier PostgreSQL stores for a SCRAM +// password (RFC 5802 with SHA-256, RFC 7677): the salted password through +// PBKDF2, the client key hashed into the stored key, and the server key. +// The password is used as is: the generated alphabet is plain ASCII, which +// SASLprep leaves unchanged. +func encodeScramSHA256(password string, salt []byte, iterations int) (string, error) { + salted, err := pbkdf2.Key(sha256.New, password, salt, iterations, sha256.Size) + if err != nil { + return "", fmt.Errorf("derive salted password: %w", err) + } + clientKey := hmacSHA256(salted, "Client Key") + storedKey := sha256.Sum256(clientKey) + serverKey := hmacSHA256(salted, "Server Key") + return fmt.Sprintf("SCRAM-SHA-256$%d:%s$%s:%s", + iterations, + base64.StdEncoding.EncodeToString(salt), + base64.StdEncoding.EncodeToString(storedKey[:]), + base64.StdEncoding.EncodeToString(serverKey), + ), nil +} + +func hmacSHA256(key []byte, message string) []byte { + mac := hmac.New(sha256.New, key) + mac.Write([]byte(message)) + return mac.Sum(nil) +} + +// encodeMySQLNative is MariaDB's PASSWORD(): SHA-1 of SHA-1, unsalted, the +// only form mysql_native_password accepts. +func encodeMySQLNative(password string) string { + first := sha1.Sum([]byte(password)) + second := sha1.Sum(first[:]) + return "*" + strings.ToUpper(hex.EncodeToString(second[:])) +} diff --git a/pkg/credentials/format/format_test.go b/pkg/credentials/format/format_test.go new file mode 100644 index 000000000..63d76d253 --- /dev/null +++ b/pkg/credentials/format/format_test.go @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: Apache-2.0 + +package format + +import ( + "crypto/hmac" + "crypto/pbkdf2" + "crypto/sha256" + "encoding/base64" + "regexp" + "strings" + "testing" +) + +func TestGeneratePassword(t *testing.T) { + seen := map[string]bool{} + for range 64 { + p, err := GeneratePassword() + if err != nil { + t.Fatalf("generate: %v", err) + } + if len(p) != PasswordLength { + t.Fatalf("password %q has length %d, want %d", p, len(p), PasswordLength) + } + for _, c := range p { + if !strings.ContainsRune(passwordAlphabet, c) { + t.Fatalf("password %q carries %q outside the alphabet", p, c) + } + } + if seen[p] { + t.Fatalf("password %q generated twice", p) + } + seen[p] = true + } +} + +// The verifier must be the canonical PostgreSQL form, since CNPG forwards it +// unchanged and PostgreSQL stores anything else as a plaintext password. The +// keys are recomputed here from the salt the verifier carries with the +// primitives RFC 5802 names, independently of the encoder's own helpers. +func TestEncodeScramSHA256(t *testing.T) { + const password = "pencil" + salt, err := base64.StdEncoding.DecodeString("W22ZaJ0SNY7soEsUEjb6gQ==") + if err != nil { + t.Fatal(err) + } + got, err := encodeScramSHA256(password, salt, 4096) + if err != nil { + t.Fatalf("encode: %v", err) + } + + re := regexp.MustCompile(`^SCRAM-SHA-256\$(\d+):([A-Za-z0-9+/=]+)\$([A-Za-z0-9+/=]+):([A-Za-z0-9+/=]+)$`) + m := re.FindStringSubmatch(got) + if m == nil { + t.Fatalf("verifier %q is not in the canonical form", got) + } + if m[1] != "4096" { + t.Errorf("iterations %s, want 4096", m[1]) + } + if m[2] != "W22ZaJ0SNY7soEsUEjb6gQ==" { + t.Errorf("salt %s, want the input salt", m[2]) + } + + salted, err := pbkdf2.Key(sha256.New, password, salt, 4096, 32) + if err != nil { + t.Fatal(err) + } + mac := hmac.New(sha256.New, salted) + mac.Write([]byte("Client Key")) + stored := sha256.Sum256(mac.Sum(nil)) + mac = hmac.New(sha256.New, salted) + mac.Write([]byte("Server Key")) + server := mac.Sum(nil) + if want := base64.StdEncoding.EncodeToString(stored[:]); m[3] != want { + t.Errorf("StoredKey %s, want %s", m[3], want) + } + if want := base64.StdEncoding.EncodeToString(server); m[4] != want { + t.Errorf("ServerKey %s, want %s", m[4], want) + } + + // A fresh salt every call, so two encodings of one password differ. + a, _ := Encode(ScramSHA256, password) + b, _ := Encode(ScramSHA256, password) + if a == b { + t.Errorf("two SCRAM encodings share a salt: %s", a) + } +} + +func TestEncodeFixedVectors(t *testing.T) { + tests := []struct { + format, password, want string + }{ + // MySQL's own PASSWORD('password'). + {MySQLNative, "password", "*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19"}, + // SHA-256 of "abc", FIPS 180-2 example B.1. + {SHA256, "abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}, + {Plaintext, "as-is", "as-is"}, + } + for _, tt := range tests { + got, err := Encode(tt.format, tt.password) + if err != nil { + t.Fatalf("%s: %v", tt.format, err) + } + if got != tt.want { + t.Errorf("%s(%q) = %q, want %q", tt.format, tt.password, got, tt.want) + } + } +} + +func TestEncodeUnknownFormat(t *testing.T) { + if _, err := Encode("apr1", "x"); err == nil { + t.Fatal("expected an error for an unknown format") + } + for _, name := range []string{ScramSHA256, MySQLNative, SHA256, Plaintext} { + if !Known(name) { + t.Errorf("%s not known", name) + } + } + if Known("apr1") { + t.Error("apr1 reported known") + } +} From 9e7c684fe293a459c79928e72beede8c6b7d99c9 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Mon, 23 Nov 2026 16:26:59 +0100 Subject: [PATCH 03/10] feat(api): add the CredentialTemplate kind An application write in the Cozystack API that kept an account list, its Secrets and the HelmRelease in step needed a cross-replica lock and still raced. The accepted design (cozystack/community#137) moves the account list to the chart instead: a kind's chart renders one cozystack.io CredentialTemplate per account, naming the user, the stored format and the Secret's labels, and its status mirrors the account Secret's record so the Credential view reads templates only. Tenants cannot write a template, and username is immutable because the account Secret's name derives from it. valuesPath starts with "_" so the Application API hides it on read and refuses it on write. Design: https://github.com/cozystack/community/blob/main/design-proposals/user-secrets-api/README.md Assisted-by: LLM Signed-off-by: Andrei Kvapil --- api/v1alpha1/credentialtemplate_types.go | 138 +++++++++++ api/v1alpha1/zz_generated.deepcopy.go | 188 ++++++++++++++- cmd/backport-batch/test-inputs.txt | 1 + .../cozystack.io_credentialtemplates.yaml | 221 ++++++++++++++++++ 4 files changed, 543 insertions(+), 5 deletions(-) create mode 100644 api/v1alpha1/credentialtemplate_types.go create mode 100644 packages/system/cozystack-controller/definitions/cozystack.io_credentialtemplates.yaml diff --git a/api/v1alpha1/credentialtemplate_types.go b/api/v1alpha1/credentialtemplate_types.go new file mode 100644 index 000000000..e23709965 --- /dev/null +++ b/api/v1alpha1/credentialtemplate_types.go @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: Apache-2.0 + +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// CredentialTemplateSpec describes one account of an application and the +// Secret that stores its password. A kind's chart renders one per account; a +// tenant cannot write it. +type CredentialTemplateSpec struct { + // Username is the account name as the engine knows it. + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="username is immutable" + Username string `json:"username"` + + // Format is how a password is stored in the account Secret. + Format CredentialTemplateFormat `json:"format"` + + // Secret describes the account Secret beyond its fixed username and + // password keys. + // +optional + Secret CredentialTemplateSecret `json:"secret,omitempty"` + + // ValuesPath, for an engine whose operator reads no Secret, asks for the + // stored value to be pulled into the release's values under + // .u. It starts with "_", which + // the Application API hides on read and refuses on write. + // +optional + // +kubebuilder:validation:Pattern=`^_[A-Za-z0-9_]*$` + ValuesPath string `json:"valuesPath,omitempty"` +} + +// CredentialTemplateFormat names a stored form of a password. +type CredentialTemplateFormat struct { + // Name is a built-in format: scram-sha-256, mysql-native, sha256 or + // plaintext. + // +kubebuilder:validation:MinLength=1 + Name string `json:"name"` +} + +// CredentialTemplateSecret describes the account Secret. +type CredentialTemplateSecret struct { + // Labels are put on the account Secret, for an operator that notices a + // changed Secret only when it carries a label. + // +optional + // +kubebuilder:validation:XValidation:rule="!('credentials.cozystack.io/account' in self)",message="the credentials.cozystack.io/account label is reserved" + Labels map[string]string `json:"labels,omitempty"` +} + +// CredentialTemplateStatus mirrors the record the account Secret keeps, so the +// Credential view reads templates only. +type CredentialTemplateStatus struct { + // SecretResourceVersion is the resourceVersion of the account Secret this + // status mirrors; empty while the account has no Secret. + // +optional + SecretResourceVersion string `json:"secretResourceVersion,omitempty"` + + // Password says where the live password came from. + // +optional + Password CredentialTemplatePasswordState `json:"password,omitempty"` + + // History holds the last ten operations, newest first. + // +optional + // +listType=atomic + History []CredentialTemplateHistoryEntry `json:"history,omitempty"` + + // ObservedGeneration is the generation the controller last acted on. + // +optional + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + + // +optional + // +listType=map + // +listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// CredentialTemplatePasswordState records the operation that set the live +// password. +type CredentialTemplatePasswordState struct { + // Origin is NotIssued, Migrated, Minted or Revoked. + // +optional + Origin string `json:"origin,omitempty"` + // +optional + At *metav1.Time `json:"at,omitempty"` + // +optional + By string `json:"by,omitempty"` +} + +// CredentialTemplateHistoryEntry is one recorded operation on the account. +type CredentialTemplateHistoryEntry struct { + // Operation is Create, Migrate, Mint or Revoke. + Operation string `json:"operation"` + At metav1.Time `json:"at"` + By string `json:"by"` +} + +// Condition types a CredentialTemplate reports. +const ( + // CredentialTemplateSecretConflict: a Secret at the account Secret's name + // that the controller did not create or adopt; it is left alone. + CredentialTemplateSecretConflict = "SecretConflict" + // CredentialTemplateUnknownFormat: the format names no built-in format. + CredentialTemplateUnknownFormat = "UnknownFormat" +) + +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="User",type="string",JSONPath=".spec.username" +// +kubebuilder:printcolumn:name="Format",type="string",JSONPath=".spec.format.name" +// +kubebuilder:printcolumn:name="Origin",type="string",JSONPath=".status.password.origin" +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp" + +// CredentialTemplate is one account of an application, rendered by the kind's +// chart. A controller keeps its account Secret, named .account, and the +// Cozystack API mints and revokes through it. See +// design-proposals/user-secrets-api in cozystack/community. +type CredentialTemplate struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec CredentialTemplateSpec `json:"spec,omitempty"` + Status CredentialTemplateStatus `json:"status,omitempty"` +} + +// +kubebuilder:object:root=true + +// CredentialTemplateList contains a list of CredentialTemplate. +type CredentialTemplateList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []CredentialTemplate `json:"items"` +} + +func init() { + SchemeBuilder.Register(&CredentialTemplate{}, &CredentialTemplateList{}) +} diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index 2f6004c57..dfb0c233d 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -23,9 +23,9 @@ package v1alpha1 import ( "github.com/fluxcd/helm-controller/api/v2" "github.com/fluxcd/pkg/apis/kustomize" - "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) @@ -355,6 +355,184 @@ func (in *ComponentInstall) DeepCopy() *ComponentInstall { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialTemplate) DeepCopyInto(out *CredentialTemplate) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialTemplate. +func (in *CredentialTemplate) DeepCopy() *CredentialTemplate { + if in == nil { + return nil + } + out := new(CredentialTemplate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *CredentialTemplate) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialTemplateFormat) DeepCopyInto(out *CredentialTemplateFormat) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialTemplateFormat. +func (in *CredentialTemplateFormat) DeepCopy() *CredentialTemplateFormat { + if in == nil { + return nil + } + out := new(CredentialTemplateFormat) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialTemplateHistoryEntry) DeepCopyInto(out *CredentialTemplateHistoryEntry) { + *out = *in + in.At.DeepCopyInto(&out.At) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialTemplateHistoryEntry. +func (in *CredentialTemplateHistoryEntry) DeepCopy() *CredentialTemplateHistoryEntry { + if in == nil { + return nil + } + out := new(CredentialTemplateHistoryEntry) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialTemplateList) DeepCopyInto(out *CredentialTemplateList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]CredentialTemplate, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialTemplateList. +func (in *CredentialTemplateList) DeepCopy() *CredentialTemplateList { + if in == nil { + return nil + } + out := new(CredentialTemplateList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *CredentialTemplateList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialTemplatePasswordState) DeepCopyInto(out *CredentialTemplatePasswordState) { + *out = *in + if in.At != nil { + in, out := &in.At, &out.At + *out = (*in).DeepCopy() + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialTemplatePasswordState. +func (in *CredentialTemplatePasswordState) DeepCopy() *CredentialTemplatePasswordState { + if in == nil { + return nil + } + out := new(CredentialTemplatePasswordState) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialTemplateSecret) DeepCopyInto(out *CredentialTemplateSecret) { + *out = *in + if in.Labels != nil { + in, out := &in.Labels, &out.Labels + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialTemplateSecret. +func (in *CredentialTemplateSecret) DeepCopy() *CredentialTemplateSecret { + if in == nil { + return nil + } + out := new(CredentialTemplateSecret) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialTemplateSpec) DeepCopyInto(out *CredentialTemplateSpec) { + *out = *in + out.Format = in.Format + in.Secret.DeepCopyInto(&out.Secret) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialTemplateSpec. +func (in *CredentialTemplateSpec) DeepCopy() *CredentialTemplateSpec { + if in == nil { + return nil + } + out := new(CredentialTemplateSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialTemplateStatus) DeepCopyInto(out *CredentialTemplateStatus) { + *out = *in + in.Password.DeepCopyInto(&out.Password) + if in.History != nil { + in, out := &in.History, &out.History + *out = make([]CredentialTemplateHistoryEntry, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialTemplateStatus. +func (in *CredentialTemplateStatus) DeepCopy() *CredentialTemplateStatus { + if in == nil { + return nil + } + out := new(CredentialTemplateStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DependencyStatus) DeepCopyInto(out *DependencyStatus) { *out = *in @@ -422,7 +600,7 @@ func (in *PackageComponent) DeepCopyInto(out *PackageComponent) { } if in.Values != nil { in, out := &in.Values, &out.Values - *out = new(v1.JSON) + *out = new(apiextensionsv1.JSON) (*in).DeepCopyInto(*out) } } @@ -575,7 +753,7 @@ func (in *PackageSourceStatus) DeepCopyInto(out *PackageSourceStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make([]metav1.Condition, len(*in)) + *out = make([]v1.Condition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -624,7 +802,7 @@ func (in *PackageStatus) DeepCopyInto(out *PackageStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make([]metav1.Condition, len(*in)) + *out = make([]v1.Condition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } diff --git a/cmd/backport-batch/test-inputs.txt b/cmd/backport-batch/test-inputs.txt index 4262b0e1f..d76bb0fab 100644 --- a/cmd/backport-batch/test-inputs.txt +++ b/cmd/backport-batch/test-inputs.txt @@ -16,6 +16,7 @@ go.mod go.sum # In-repo packages the tool and its tests import. +api/v1alpha1/ internal/apigate/ pkg/apis/apps/v1alpha1/ pkg/apis/apps/validation/ diff --git a/packages/system/cozystack-controller/definitions/cozystack.io_credentialtemplates.yaml b/packages/system/cozystack-controller/definitions/cozystack.io_credentialtemplates.yaml new file mode 100644 index 000000000..b56c24c73 --- /dev/null +++ b/packages/system/cozystack-controller/definitions/cozystack.io_credentialtemplates.yaml @@ -0,0 +1,221 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.16.4 + name: credentialtemplates.cozystack.io +spec: + group: cozystack.io + names: + kind: CredentialTemplate + listKind: CredentialTemplateList + plural: credentialtemplates + singular: credentialtemplate + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.username + name: User + type: string + - jsonPath: .spec.format.name + name: Format + type: string + - jsonPath: .status.password.origin + name: Origin + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + CredentialTemplate is one account of an application, rendered by the kind's + chart. A controller keeps its account Secret, named .account, and the + Cozystack API mints and revokes through it. See + design-proposals/user-secrets-api in cozystack/community. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + CredentialTemplateSpec describes one account of an application and the + Secret that stores its password. A kind's chart renders one per account; a + tenant cannot write it. + properties: + format: + description: Format is how a password is stored in the account Secret. + properties: + name: + description: |- + Name is a built-in format: scram-sha-256, mysql-native, sha256 or + plaintext. + minLength: 1 + type: string + required: + - name + type: object + secret: + description: |- + Secret describes the account Secret beyond its fixed username and + password keys. + properties: + labels: + additionalProperties: + type: string + description: |- + Labels are put on the account Secret, for an operator that notices a + changed Secret only when it carries a label. + type: object + x-kubernetes-validations: + - message: the credentials.cozystack.io/account label is reserved + rule: '!(''credentials.cozystack.io/account'' in self)' + type: object + username: + description: Username is the account name as the engine knows it. + minLength: 1 + type: string + x-kubernetes-validations: + - message: username is immutable + rule: self == oldSelf + valuesPath: + description: |- + ValuesPath, for an engine whose operator reads no Secret, asks for the + stored value to be pulled into the release's values under + .u. It starts with "_", which + the Application API hides on read and refuses on write. + pattern: ^_[A-Za-z0-9_]*$ + type: string + required: + - format + - username + type: object + status: + description: |- + CredentialTemplateStatus mirrors the record the account Secret keeps, so the + Credential view reads templates only. + properties: + conditions: + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + history: + description: History holds the last ten operations, newest first. + items: + description: CredentialTemplateHistoryEntry is one recorded operation + on the account. + properties: + at: + format: date-time + type: string + by: + type: string + operation: + description: Operation is Create, Migrate, Mint or Revoke. + type: string + required: + - at + - by + - operation + type: object + type: array + x-kubernetes-list-type: atomic + observedGeneration: + description: ObservedGeneration is the generation the controller last + acted on. + format: int64 + type: integer + password: + description: Password says where the live password came from. + properties: + at: + format: date-time + type: string + by: + type: string + origin: + description: Origin is NotIssued, Migrated, Minted or Revoked. + type: string + type: object + secretResourceVersion: + description: |- + SecretResourceVersion is the resourceVersion of the account Secret this + status mirrors; empty while the account has no Secret. + type: string + type: object + type: object + served: true + storage: true + subresources: + status: {} From 3c547721fa1d9e3b98bde670fc49c678e26ba299 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Mon, 23 Nov 2026 16:26:59 +0100 Subject: [PATCH 04/10] feat(credentials): add the account package The Cozystack API, the CredentialTemplate controller and the migration tooling must agree on an account Secret's name, its labels, the record of who set the password and when, and the valuesFrom entry that carries a stored value into a chart that reads no Secret. One package holds all of it so the three cannot drift apart. The values key of an account is the SHA-256 of its user name, which fits a valuesFrom targetPath whatever characters the name holds. Co-authored-by: Timofei Larkin Assisted-by: LLM Signed-off-by: Andrei Kvapil --- pkg/credentials/account/account.go | 208 ++++++++++++++++++++++++ pkg/credentials/account/account_test.go | 109 +++++++++++++ 2 files changed, 317 insertions(+) create mode 100644 pkg/credentials/account/account.go create mode 100644 pkg/credentials/account/account_test.go diff --git a/pkg/credentials/account/account.go b/pkg/credentials/account/account.go new file mode 100644 index 000000000..88012e5d9 --- /dev/null +++ b/pkg/credentials/account/account.go @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package account is what the Cozystack API, the CredentialTemplate controller +// and the migration tooling share about account Secrets: their names, the +// labels and annotations that carry the record, and how the stored value +// reaches a chart through valuesFrom. It writes nothing itself. +package account + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "regexp" + "strings" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/validation" + + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" +) + +const ( + // AccountLabel marks the account Secret of a CredentialTemplate, which + // cozystack-controller seeds and keeps, so the controller can watch these + // Secrets by label without matching any other Secret of the application. + AccountLabel = "credentials.cozystack.io/account" + // OriginAnnotation holds the CredentialOrigin of the live password. + OriginAnnotation = "credentials.cozystack.io/origin" + // AtAnnotation holds when the live password was set, RFC 3339. + AtAnnotation = "credentials.cozystack.io/at" + // ByAnnotation holds who set the live password. + ByAnnotation = "credentials.cozystack.io/by" + // HistoryAnnotation holds the last HistoryLimit operations as a JSON list, + // newest first. + HistoryAnnotation = "credentials.cozystack.io/history" + // HistoryLimit bounds the history kept on the Secret; the audit log keeps + // every operation. + HistoryLimit = 10 + // FormatAnnotation names the format the Secret's password is stored in, so + // the controller sees when a template's format changed. + FormatAnnotation = "credentials.cozystack.io/format" + // SeedAnnotation on a HelmRelease lets the controller seed the account + // Secrets of its templates. The API sets it on every release it creates, + // the conversion on a release whose Secrets it wrote; a release without it + // keeps passwords the platform never saw, so its accounts are left for a + // mint. + SeedAnnotation = "credentials.cozystack.io/seed" + // ReleaseNameAnnotation is what Helm puts on every object it renders, + // naming the release; it ties a template to its HelmRelease. + ReleaseNameAnnotation = "meta.helm.sh/release-name" + // SecretSuffix follows the template name in the account Secret's name. + SecretSuffix = ".account" + // UsernameKey and PasswordKey are the two data keys of every account + // Secret, whatever the format. + UsernameKey = "username" + PasswordKey = "password" +) + +var nonNameChars = regexp.MustCompile(`[^a-z0-9-]`) + +// Account is one tenant account of an application. +type Account struct { + // Username as the application declares it and the engine knows it. + Username string + // Mapped is Username lowercased with every character outside [a-z0-9-] + // replaced by "-"; it names the Secret and the Credential. + Mapped string +} + +// MapName returns the object-name form of a user name, or an error when the +// form is not a valid DNS label, which no Secret or Credential name can carry. +func MapName(username string) (string, error) { + mapped := nonNameChars.ReplaceAllString(strings.ToLower(username), "-") + if errs := validation.IsDNS1123Label(mapped); len(errs) > 0 { + return "", fmt.Errorf("user name %q maps to %q, which is not a valid name: %s", username, mapped, strings.Join(errs, "; ")) + } + return mapped, nil +} + +// SecretName is the account Secret of a user of a release. +func SecretName(release, mapped string) string { + return release + "." + mapped + SecretSuffix +} + +// Record is the per-account record an account Secret carries in its +// annotations and the Credential view shows. +type Record struct { + Origin corev1alpha1.CredentialOrigin + At metav1.Time + By string + History []corev1alpha1.CredentialHistoryEntry +} + +// ReadRecord decodes the record of an account Secret. A Secret with no +// annotations yields an empty record rather than an error, so a Secret +// written by hand still lists. +func ReadRecord(sec *corev1.Secret) Record { + var r Record + ann := sec.GetAnnotations() + r.Origin = corev1alpha1.CredentialOrigin(ann[OriginAnnotation]) + r.By = ann[ByAnnotation] + if at := ann[AtAnnotation]; at != "" { + if t, err := parseTime(at); err == nil { + r.At = t + } + } + if h := ann[HistoryAnnotation]; h != "" { + _ = json.Unmarshal([]byte(h), &r.History) + } + return r +} + +// WriteRecord encodes the record into the Secret's annotations. +func WriteRecord(sec *corev1.Secret, r Record) { + if sec.Annotations == nil { + sec.Annotations = map[string]string{} + } + sec.Annotations[OriginAnnotation] = string(r.Origin) + sec.Annotations[ByAnnotation] = r.By + sec.Annotations[AtAnnotation] = r.At.UTC().Format(timeLayout) + history, _ := json.Marshal(r.History) + sec.Annotations[HistoryAnnotation] = string(history) +} + +// Apply records an operation: the origin becomes the operation's, At and By +// are the operation's, and the entry goes to the front of the history, which +// keeps HistoryLimit entries. +func (r Record) Apply(op corev1alpha1.CredentialOperation, at metav1.Time, by string) Record { + r.Origin = originOf(op) + r.At = at + r.By = by + entry := corev1alpha1.CredentialHistoryEntry{Operation: op, At: at, By: by} + history := make([]corev1alpha1.CredentialHistoryEntry, 0, len(r.History)+1) + history = append(history, entry) + history = append(history, r.History...) + if len(history) > HistoryLimit { + history = history[:HistoryLimit] + } + r.History = history + return r +} + +func originOf(op corev1alpha1.CredentialOperation) corev1alpha1.CredentialOrigin { + switch op { + case corev1alpha1.CredentialOperationMigrate: + return corev1alpha1.CredentialOriginMigrated + case corev1alpha1.CredentialOperationMint: + return corev1alpha1.CredentialOriginMinted + case corev1alpha1.CredentialOperationRevoke: + return corev1alpha1.CredentialOriginRevoked + } + return corev1alpha1.CredentialOriginNotIssued +} + +const timeLayout = "2006-01-02T15:04:05Z" + +func parseTime(s string) (metav1.Time, error) { + var t metav1.Time + err := t.UnmarshalQueryParameter(s) + return t, err +} + +// Labels are the labels an account Secret carries: those its template names, +// and the account marker, which a template cannot override. +func Labels(templateLabels map[string]string) map[string]string { + labels := make(map[string]string, len(templateLabels)+1) + for k, v := range templateLabels { + labels[k] = v + } + labels[AccountLabel] = "true" + return labels +} + +// DigestKey is the values key one account's stored value lands under: the +// SHA-256 of the user name, which fits a valuesFrom targetPath whatever the +// name holds. +func DigestKey(username string) string { + sum := sha256.Sum256([]byte(username)) + return "u" + hex.EncodeToString(sum[:]) +} + +// ValuesFrom is the HelmRelease valuesFrom entry that carries an account's +// stored value into .. It is optional, so the release +// renders while the account has no Secret yet. +func ValuesFrom(secretName, valuesPath, username string) helmv2.ValuesReference { + return helmv2.ValuesReference{ + Kind: "Secret", + Name: secretName, + ValuesKey: PasswordKey, + TargetPath: valuesPath + "." + DigestKey(username), + Optional: true, + } +} + +// IsAccountValuesFrom reports whether a valuesFrom entry is one ValuesFrom +// builds, which the controller owns and the Application API keeps. +func IsAccountValuesFrom(ref helmv2.ValuesReference) bool { + return ref.Kind == "Secret" && ref.ValuesKey == PasswordKey && strings.HasSuffix(ref.Name, SecretSuffix) +} + +// IsAccountSecret reports whether a Secret is the account Secret of a +// CredentialTemplate. +func IsAccountSecret(sec *corev1.Secret) bool { + return sec != nil && sec.Labels[AccountLabel] == "true" +} diff --git a/pkg/credentials/account/account_test.go b/pkg/credentials/account/account_test.go new file mode 100644 index 000000000..cc7a7c0b9 --- /dev/null +++ b/pkg/credentials/account/account_test.go @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: Apache-2.0 + +package account + +import ( + "strings" + "testing" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" +) + +func TestMapName(t *testing.T) { + tests := []struct { + in, want string + wantErr bool + }{ + {in: "web", want: "web"}, + {in: "Bob.Smith", want: "bob-smith"}, + {in: "app_user", want: "app-user"}, + {in: "-leading", wantErr: true}, + {in: "", wantErr: true}, + {in: strings.Repeat("a", 64), wantErr: true}, + } + for _, tt := range tests { + got, err := MapName(tt.in) + if tt.wantErr { + if err == nil { + t.Errorf("MapName(%q) = %q, want an error", tt.in, got) + } + continue + } + if err != nil { + t.Errorf("MapName(%q): %v", tt.in, err) + continue + } + if got != tt.want { + t.Errorf("MapName(%q) = %q, want %q", tt.in, got, tt.want) + } + } +} + +func TestNames(t *testing.T) { + if got := SecretName("postgres-orders", "web"); got != "postgres-orders.web.account" { + t.Errorf("SecretName = %q", got) + } +} + +func TestRecordRoundTrip(t *testing.T) { + sec := &corev1.Secret{} + if r := ReadRecord(sec); r.Origin != "" || len(r.History) != 0 { + t.Errorf("empty Secret read as %+v", r) + } + + at := metav1.NewTime(time.Date(2026, 10, 2, 9, 14, 7, 0, time.UTC)) + r := Record{}.Apply(corev1alpha1.CredentialOperationCreate, at, "jane@example.org") + r = r.Apply(corev1alpha1.CredentialOperationMint, at, "jane@example.org") + WriteRecord(sec, r) + back := ReadRecord(sec) + if back.Origin != corev1alpha1.CredentialOriginMinted || back.By != "jane@example.org" || !back.At.Equal(&at) { + t.Errorf("record read back as %+v", back) + } + if len(back.History) != 2 || back.History[0].Operation != corev1alpha1.CredentialOperationMint || back.History[1].Operation != corev1alpha1.CredentialOperationCreate { + t.Errorf("history read back as %+v", back.History) + } + + for range HistoryLimit + 5 { + r = r.Apply(corev1alpha1.CredentialOperationRevoke, at, "bob") + } + if len(r.History) != HistoryLimit { + t.Errorf("history has %d entries, want %d", len(r.History), HistoryLimit) + } + if r.Origin != corev1alpha1.CredentialOriginRevoked { + t.Errorf("origin %s after revoke", r.Origin) + } +} + +func TestLabels(t *testing.T) { + l := Labels(map[string]string{"cnpg.io/reload": "true", AccountLabel: "false"}) + if l[AccountLabel] != "true" || l["cnpg.io/reload"] != "true" || len(l) != 2 { + t.Errorf("labels = %v, want the template's plus the account marker, which a template cannot override", l) + } + if !IsAccountSecret(&corev1.Secret{ObjectMeta: metav1.ObjectMeta{Labels: l}}) { + t.Error("labelled Secret not recognised") + } + if IsAccountSecret(&corev1.Secret{}) { + t.Error("bare Secret recognised") + } +} + +func TestValuesFrom(t *testing.T) { + ref := ValuesFrom("clickhouse-logs.web.account", "_accounts", "web") + if ref.Kind != "Secret" || ref.Name != "clickhouse-logs.web.account" || ref.ValuesKey != PasswordKey || !ref.Optional { + t.Errorf("entry = %+v", ref) + } + if !strings.HasPrefix(ref.TargetPath, "_accounts.u") || len(ref.TargetPath) != len("_accounts.u")+64 { + t.Errorf("targetPath = %q, want _accounts.u", ref.TargetPath) + } + if !IsAccountValuesFrom(ref) { + t.Error("an entry ValuesFrom builds is not recognised") + } + if IsAccountValuesFrom(helmv2.ValuesReference{Kind: "Secret", Name: "cozystack-values"}) { + t.Error("the platform values entry is taken for an account entry") + } +} From d65f86277cc1c378f5896bda209a402bab781e46 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Mon, 23 Nov 2026 16:27:00 +0100 Subject: [PATCH 05/10] 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" +} From d4f1381bda6969de5476c5cc9a42f923805076ff Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Mon, 23 Nov 2026 16:27:00 +0100 Subject: [PATCH 06/10] feat(controller): seed account Secrets from CredentialTemplates The account list now comes from the chart, so something has to turn a rendered CredentialTemplate into an account Secret. The controller seeds a missing Secret, but only on a release marked for seeding: the mark says no client holds a password a seeded one would replace, which is true for a release the API created and, after the conversion, for a converted one. It seeds again when the template's format changes, adopts an unowned Secret the conversion wrote, leaves any other Secret at the name alone, and mirrors the Secret's record into the template's status. A second reconciler adds a valuesFrom entry per template that names a valuesPath, for an engine whose operator reads no Secret. A template reaches it one event at a time, and a conversion writes the Secrets and their entries before the converted chart renders the templates, so an entry whose Secret still exists is kept until its template is seen; it goes once the Secret is gone. The ApplicationDefinition reconciler keeps these entries rather than resetting valuesFrom to the platform values. HelmReleases are watched for the seed mark appearing or going, filtered so helm-controller's status writes do not wake the controller. Without that, a template the chart rendered before the release carried the mark stayed unseeded until the next resync, which on MariaDB turned into a ten-minute Helm timeout on the unready User. Account Secrets are read through the uncached reader and watched as metadata, because an account Secret may hold a plaintext that has no business in a cache. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- cmd/cozystack-controller/main.go | 20 + .../applicationdefinition_helmreconciler.go | 10 +- ...plicationdefinition_helmreconciler_test.go | 44 ++ .../credentialtemplate_controller.go | 485 ++++++++++++++++++ .../credentialtemplate_controller_test.go | 324 ++++++++++++ 5 files changed, 882 insertions(+), 1 deletion(-) create mode 100644 internal/controller/credentialtemplate_controller.go create mode 100644 internal/controller/credentialtemplate_controller_test.go diff --git a/cmd/cozystack-controller/main.go b/cmd/cozystack-controller/main.go index 59ba3b515..df9c408a7 100644 --- a/cmd/cozystack-controller/main.go +++ b/cmd/cozystack-controller/main.go @@ -337,6 +337,26 @@ func main() { os.Exit(1) } + // Account Secrets are watched as metadata on the same unscoped metadata + // cache, for the reason the CA-extraction reconciler gives above, and read + // uncached: an account Secret may hold a plaintext. + if err = (&controller.CredentialTemplateReconciler{ + Client: mgr.GetClient(), + Reader: mgr.GetAPIReader(), + Scheme: mgr.GetScheme(), + Recorder: mgr.GetEventRecorderFor("credentialtemplate-controller"), + }).SetupWithManager(mgr, caSecretCluster.GetCache()); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "CredentialTemplate") + os.Exit(1) + } + if err = (&controller.CredentialValuesReconciler{ + Client: mgr.GetClient(), + Reader: mgr.GetAPIReader(), + }).SetupWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "CredentialValues") + os.Exit(1) + } + // +kubebuilder:scaffold:builder if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { diff --git a/internal/controller/applicationdefinition_helmreconciler.go b/internal/controller/applicationdefinition_helmreconciler.go index 91011500e..b370e18fc 100644 --- a/internal/controller/applicationdefinition_helmreconciler.go +++ b/internal/controller/applicationdefinition_helmreconciler.go @@ -8,6 +8,7 @@ import ( cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" "github.com/cozystack/cozystack/internal/shared/appdefowner" "github.com/cozystack/cozystack/pkg/config" + "github.com/cozystack/cozystack/pkg/credentials/account" helmv2 "github.com/fluxcd/helm-controller/api/v2" corev1 "k8s.io/api/core/v1" @@ -210,8 +211,15 @@ func (r *ApplicationDefinitionHelmReconciler) updateHelmReleaseChart(ctx context updated = true } - // Check and update valuesFrom configuration + // Check and update valuesFrom configuration. The entries that carry an + // account's stored value into the chart belong to the CredentialTemplate + // controller, so they are kept as they are. expected := expectedValuesFrom() + for _, ref := range hrCopy.Spec.ValuesFrom { + if account.IsAccountValuesFrom(ref) { + expected = append(expected, ref) + } + } if !valuesFromEqual(hrCopy.Spec.ValuesFrom, expected) { logger.V(4).Info("Updating HelmRelease valuesFrom", "name", hr.Name, "namespace", hr.Namespace) hrCopy.Spec.ValuesFrom = expected diff --git a/internal/controller/applicationdefinition_helmreconciler_test.go b/internal/controller/applicationdefinition_helmreconciler_test.go index 33fc871b4..fa293f073 100644 --- a/internal/controller/applicationdefinition_helmreconciler_test.go +++ b/internal/controller/applicationdefinition_helmreconciler_test.go @@ -10,6 +10,7 @@ import ( cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" "github.com/cozystack/cozystack/pkg/config" + "github.com/cozystack/cozystack/pkg/credentials/account" helmv2 "github.com/fluxcd/helm-controller/api/v2" "github.com/fluxcd/pkg/apis/kustomize" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -959,3 +960,46 @@ func TestAppDefHelm_UpdateFailureRequeues(t *testing.T) { t.Fatalf("expected %s synced past the failed %s, got %+v", written, failed, got.Spec.HealthCheckExprs) } } + +// TestAppDefHelm_KeepsAccountValuesFrom pins that the canonical valuesFrom +// leaves the entries the CredentialTemplate controller owns in place: they +// carry each account's stored value into the chart, and stripping them on +// every definition change would take the accounts out of the release. +func TestAppDefHelm_KeepsAccountValuesFrom(t *testing.T) { + scheme := newAppDefHelmScheme(t) + chartRef := &helmv2.CrossNamespaceSourceReference{Kind: "OCIRepository", Name: "clickhouse-app", Namespace: "cozy-public"} + appDef := &cozyv1alpha1.ApplicationDefinition{ + ObjectMeta: metav1.ObjectMeta{Name: "clickhouse"}, + Spec: cozyv1alpha1.ApplicationDefinitionSpec{ + Application: cozyv1alpha1.ApplicationDefinitionApplication{Kind: "ClickHouse"}, + Release: cozyv1alpha1.ApplicationDefinitionRelease{ChartRef: chartRef}, + }, + } + entry := account.ValuesFrom("clickhouse-logs.web.account", "_accounts", "web") + hr := &helmv2.HelmRelease{ + ObjectMeta: metav1.ObjectMeta{ + Name: "clickhouse-logs", + Namespace: "tenant-foo", + Labels: map[string]string{ + "apps.cozystack.io/application.kind": "ClickHouse", + "apps.cozystack.io/application.group": "apps.cozystack.io", + }, + }, + Spec: helmv2.HelmReleaseSpec{ + ChartRef: chartRef, + ValuesFrom: []helmv2.ValuesReference{{Kind: "ConfigMap", Name: "wrong"}, entry}, + }, + } + fakeClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(appDef, hr).Build() + r := &ApplicationDefinitionHelmReconciler{Client: fakeClient, Scheme: scheme} + if _, err := r.Reconcile(context.TODO(), reconcile.Request{NamespacedName: types.NamespacedName{Name: "clickhouse"}}); err != nil { + t.Fatalf("unexpected error: %v", err) + } + got := &helmv2.HelmRelease{} + if err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: "clickhouse-logs", Namespace: "tenant-foo"}, got); err != nil { + t.Fatal(err) + } + if len(got.Spec.ValuesFrom) != 2 || got.Spec.ValuesFrom[0].Name != "cozystack-values" || got.Spec.ValuesFrom[1] != entry { + t.Fatalf("valuesFrom = %+v, want the platform values and the account entry", got.Spec.ValuesFrom) + } +} diff --git a/internal/controller/credentialtemplate_controller.go b/internal/controller/credentialtemplate_controller.go new file mode 100644 index 000000000..36e7e6fdc --- /dev/null +++ b/internal/controller/credentialtemplate_controller.go @@ -0,0 +1,485 @@ +// SPDX-License-Identifier: Apache-2.0 + +package controller + +import ( + "context" + "fmt" + "sort" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + 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/event" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/predicate" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + "sigs.k8s.io/controller-runtime/pkg/source" + + 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" +) + +// +kubebuilder:rbac:groups=cozystack.io,resources=credentialtemplates,verbs=get;list;watch +// +kubebuilder:rbac:groups=cozystack.io,resources=credentialtemplates/status,verbs=get;update;patch +// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch +// +kubebuilder:rbac:groups=helm.toolkit.fluxcd.io,resources=helmreleases,verbs=get;list;watch;update;patch + +// CredentialControllerActor is who the record names for the operations the +// controller performs: seeding a Secret, or seeding it again after a format +// change. +const CredentialControllerActor = "system:serviceaccount:cozy-system:cozystack-controller" + +// Event reasons the controller records on a CredentialTemplate. +const ( + reasonCredentialReset = "CredentialReset" + reasonCredentialAdopted = "CredentialAdopted" +) + +// CredentialTemplateReconciler keeps each CredentialTemplate and its account +// Secret in step: it seeds a missing Secret on a release marked for seeding, +// seeds it again when the template's format changes, adopts an unowned Secret +// the conversion wrote, leaves any other Secret at the name alone, and mirrors +// the Secret's record into the template's status. See +// design-proposals/user-secrets-api in cozystack/community. +// +// Secrets are read through Reader, uncached: the manager's Secret cache is +// scoped to other reconcilers, and an account Secret may hold a plaintext +// that has no business in a cache. Their changes reach the controller through +// a metadata-only watch. +type CredentialTemplateReconciler struct { + client.Client + Reader client.Reader + Scheme *runtime.Scheme + Recorder record.EventRecorder + Now func() time.Time +} + +func (r *CredentialTemplateReconciler) now() metav1.Time { + if r.Now != nil { + return metav1.NewTime(r.Now()) + } + return metav1.Now() +} + +func (r *CredentialTemplateReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + logger := log.FromContext(ctx) + + tmpl := &cozyv1alpha1.CredentialTemplate{} + if err := r.Get(ctx, req.NamespacedName, tmpl); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + if !tmpl.DeletionTimestamp.IsZero() { + return ctrl.Result{}, nil + } + status := tmpl.Status.DeepCopy() + status.ObservedGeneration = tmpl.Generation + + if !format.Known(tmpl.Spec.Format.Name) { + meta.SetStatusCondition(&status.Conditions, metav1.Condition{ + Type: cozyv1alpha1.CredentialTemplateUnknownFormat, + Status: metav1.ConditionTrue, + Reason: "NotBuiltIn", + Message: fmt.Sprintf("format %q is not a built-in format", tmpl.Spec.Format.Name), + }) + return ctrl.Result{}, r.writeStatus(ctx, tmpl, status) + } + meta.RemoveStatusCondition(&status.Conditions, cozyv1alpha1.CredentialTemplateUnknownFormat) + + sec, err := r.secret(ctx, tmpl) + if err != nil { + return ctrl.Result{}, err + } + + switch { + case sec == nil: + seed, err := r.seedAllowed(ctx, tmpl) + if err != nil { + return ctrl.Result{}, err + } + if seed { + if sec, err = r.seed(ctx, tmpl); err != nil { + return ctrl.Result{}, err + } + } + case metav1.IsControlledBy(sec, tmpl): + if sec.Annotations[account.FormatAnnotation] != tmpl.Spec.Format.Name { + if sec, err = r.reseed(ctx, tmpl, sec); err != nil { + return ctrl.Result{}, err + } + } else if sec, err = r.alignLabels(ctx, tmpl, sec); err != nil { + return ctrl.Result{}, err + } + case adoptable(sec, tmpl): + if sec, err = r.adopt(ctx, tmpl, sec); err != nil { + return ctrl.Result{}, err + } + default: + logger.Info("leaving a Secret the controller did not create alone", "secret", sec.Name) + 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 seeded", sec.Name), + }) + mirror(status, nil) + return ctrl.Result{}, r.writeStatus(ctx, tmpl, status) + } + meta.RemoveStatusCondition(&status.Conditions, cozyv1alpha1.CredentialTemplateSecretConflict) + mirror(status, sec) + return ctrl.Result{}, r.writeStatus(ctx, tmpl, status) +} + +// secret reads the template's account Secret, nil when it does not exist. +func (r *CredentialTemplateReconciler) secret(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) + switch { + case apierrors.IsNotFound(err): + return nil, nil + case err != nil: + return nil, err + } + return sec, nil +} + +// seedAllowed reports whether the template's release is marked for seeding. +// A release without the mark keeps passwords the platform never saw, which a +// seeded random password would replace under its clients. +func (r *CredentialTemplateReconciler) seedAllowed(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate) (bool, error) { + release := tmpl.Annotations[account.ReleaseNameAnnotation] + if release == "" { + return false, nil + } + hr := &helmv2.HelmRelease{} + if err := r.Get(ctx, types.NamespacedName{Namespace: tmpl.Namespace, Name: release}, hr); err != nil { + return false, client.IgnoreNotFound(err) + } + return hr.Annotations[account.SeedAnnotation] == "true", nil +} + +// newSecret builds the account Secret of a template holding the stored form of +// a random password that is discarded here. +func (r *CredentialTemplateReconciler) newSecret(tmpl *cozyv1alpha1.CredentialTemplate, rec account.Record) (*corev1.Secret, error) { + password, err := format.GeneratePassword() + if err != nil { + return nil, err + } + stored, err := format.Encode(tmpl.Spec.Format.Name, password) + if err != nil { + return nil, 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}, + }, + Type: corev1.SecretTypeBasicAuth, + Data: map[string][]byte{ + account.UsernameKey: []byte(tmpl.Spec.Username), + account.PasswordKey: []byte(stored), + }, + } + account.WriteRecord(sec, rec.Apply(corev1alpha1.CredentialOperationCreate, r.now(), CredentialControllerActor)) + if err := controllerutil.SetControllerReference(tmpl, sec, r.Scheme); err != nil { + return nil, err + } + return sec, nil +} + +func (r *CredentialTemplateReconciler) seed(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate) (*corev1.Secret, error) { + sec, err := r.newSecret(tmpl, account.Record{}) + if err != nil { + return nil, err + } + if err := r.Create(ctx, sec); err != nil { + if apierrors.IsAlreadyExists(err) { + // A mint created it in between; the next reconcile mirrors it. + return r.secret(ctx, tmpl) + } + return nil, err + } + return sec, nil +} + +// reseed replaces a Secret whose value is stored in another format than the +// template now names: a stored value cannot be converted without the +// password, so the account starts over as NotIssued. +func (r *CredentialTemplateReconciler) reseed(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, cur *corev1.Secret) (*corev1.Secret, error) { + sec, err := r.newSecret(tmpl, account.ReadRecord(cur)) + if err != nil { + return nil, err + } + sec.ResourceVersion = cur.ResourceVersion + if err := r.Update(ctx, sec); err != nil { + return nil, err + } + if r.Recorder != nil { + r.Recorder.Eventf(tmpl, corev1.EventTypeWarning, reasonCredentialReset, + "format changed from %q to %q; the account was given a new password nobody holds, mint one", cur.Annotations[account.FormatAnnotation], tmpl.Spec.Format.Name) + } + return sec, nil +} + +// alignLabels brings the Secret's labels in line with the template's, without +// touching its value or record. +func (r *CredentialTemplateReconciler) alignLabels(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, sec *corev1.Secret) (*corev1.Secret, error) { + want := account.Labels(tmpl.Spec.Secret.Labels) + if equality.Semantic.DeepEqual(sec.Labels, want) { + return sec, nil + } + updated := sec.DeepCopy() + updated.Labels = want + if err := r.Update(ctx, updated); err != nil { + return nil, err + } + return updated, nil +} + +// adoptable reports whether an unowned Secret at the template's name is one +// the conversion wrote for this account: the account marker, no controller, +// and the same username. +func adoptable(sec *corev1.Secret, tmpl *cozyv1alpha1.CredentialTemplate) bool { + return account.IsAccountSecret(sec) && + metav1.GetControllerOf(sec) == nil && + string(sec.Data[account.UsernameKey]) == tmpl.Spec.Username +} + +// adopt takes over a Secret the conversion wrote, keeping its value and +// record. A Secret without a format annotation was written in the format its +// kind converted to, which the template names. +func (r *CredentialTemplateReconciler) adopt(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, cur *corev1.Secret) (*corev1.Secret, error) { + sec := cur.DeepCopy() + if err := controllerutil.SetControllerReference(tmpl, sec, r.Scheme); err != nil { + return nil, err + } + if sec.Annotations == nil { + sec.Annotations = map[string]string{} + } + if sec.Annotations[account.FormatAnnotation] == "" { + sec.Annotations[account.FormatAnnotation] = tmpl.Spec.Format.Name + } + sec.Labels = account.Labels(tmpl.Spec.Secret.Labels) + if err := r.Update(ctx, sec); err != nil { + return nil, err + } + if r.Recorder != nil { + r.Recorder.Event(tmpl, corev1.EventTypeNormal, reasonCredentialAdopted, "adopted the account Secret the conversion wrote") + } + return sec, nil +} + +// mirror copies the record of the account Secret into the template's status; +// nil clears it. +func mirror(status *cozyv1alpha1.CredentialTemplateStatus, sec *corev1.Secret) { + if sec == nil { + status.SecretResourceVersion = "" + status.Password = cozyv1alpha1.CredentialTemplatePasswordState{Origin: string(corev1alpha1.CredentialOriginNotIssued)} + status.History = nil + return + } + rec := account.ReadRecord(sec) + status.SecretResourceVersion = sec.ResourceVersion + status.Password = cozyv1alpha1.CredentialTemplatePasswordState{Origin: string(rec.Origin), By: rec.By} + if rec.Origin == "" { + status.Password.Origin = string(corev1alpha1.CredentialOriginNotIssued) + } + if !rec.At.IsZero() { + at := rec.At + status.Password.At = &at + } + status.History = nil + for _, h := range rec.History { + status.History = append(status.History, cozyv1alpha1.CredentialTemplateHistoryEntry{Operation: string(h.Operation), At: h.At, By: h.By}) + } +} + +func (r *CredentialTemplateReconciler) writeStatus(ctx context.Context, 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) +} + +// SetupWithManager registers the reconciler. accountSecrets is a metadata +// cache of Secrets, so a change to an account Secret (a mint, a revoke) +// reaches the template that owns it without any Secret data being cached. +func (r *CredentialTemplateReconciler) SetupWithManager(mgr ctrl.Manager, accountSecrets cache.Cache) error { + secretMeta := &metav1.PartialObjectMetadata{} + secretMeta.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("Secret")) + isAccount := predicate.NewTypedPredicateFuncs(func(o *metav1.PartialObjectMetadata) bool { + return o.GetLabels()[account.AccountLabel] == "true" + }) + owner := handler.TypedEnqueueRequestForOwner[*metav1.PartialObjectMetadata]( + mgr.GetScheme(), mgr.GetRESTMapper(), &cozyv1alpha1.CredentialTemplate{}, handler.OnlyControllerOwner()) + return ctrl.NewControllerManagedBy(mgr). + Named("credentialtemplate"). + For(&cozyv1alpha1.CredentialTemplate{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})). + WatchesRawSource(source.Kind(accountSecrets, secretMeta, owner, isAccount)). + Watches(&helmv2.HelmRelease{}, handler.EnqueueRequestsFromMapFunc(r.templatesOfRelease), builder.WithPredicates(seedMarkChanged)). + Complete(r) +} + +// seedMarkChanged passes only a HelmRelease whose seed mark appeared or +// went, so helm-controller's status writes do not wake the reconciler. A +// template rendered before its release was marked, as when the conversion +// marks a release whose chart has already switched, is seeded as soon as +// the mark lands rather than at the next resync. +var seedMarkChanged = predicate.Funcs{ + CreateFunc: func(e event.CreateEvent) bool { return e.Object.GetAnnotations()[account.SeedAnnotation] == "true" }, + DeleteFunc: func(event.DeleteEvent) bool { return false }, + GenericFunc: func(event.GenericEvent) bool { return false }, + UpdateFunc: func(e event.UpdateEvent) bool { + return e.ObjectOld.GetAnnotations()[account.SeedAnnotation] != e.ObjectNew.GetAnnotations()[account.SeedAnnotation] + }, +} + +// templatesOfRelease maps a HelmRelease to the templates it rendered. +func (r *CredentialTemplateReconciler) templatesOfRelease(ctx context.Context, o client.Object) []reconcile.Request { + list := &cozyv1alpha1.CredentialTemplateList{} + if err := r.List(ctx, list, client.InNamespace(o.GetNamespace())); err != nil { + log.FromContext(ctx).Error(err, "listing CredentialTemplates for a seed mark change", "release", o.GetName()) + return nil + } + var reqs []reconcile.Request + for _, t := range list.Items { + if t.Annotations[account.ReleaseNameAnnotation] == o.GetName() { + reqs = append(reqs, reconcile.Request{NamespacedName: types.NamespacedName{Namespace: t.Namespace, Name: t.Name}}) + } + } + return reqs +} + +// CredentialValuesReconciler keeps the valuesFrom entries of a HelmRelease in +// step with the templates of its release that name a valuesPath, for an +// engine whose operator reads no Secret. It is keyed by the HelmRelease but +// watches only templates, so helm-controller's status writes do not wake it. +type CredentialValuesReconciler struct { + client.Client + // Reader checks Secrets uncached, for the reason + // CredentialTemplateReconciler gives. + Reader client.Reader +} + +// valuesRecheck is how soon a release whose entries were kept for a template +// not seen yet is looked at again. +const valuesRecheck = 30 * time.Second + +// +kubebuilder:rbac:groups=helm.toolkit.fluxcd.io,resources=helmreleases,verbs=get;list;watch;update;patch + +func (r *CredentialValuesReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + hr := &helmv2.HelmRelease{} + if err := r.Get(ctx, req.NamespacedName, hr); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + templates := &cozyv1alpha1.CredentialTemplateList{} + if err := r.List(ctx, templates, client.InNamespace(hr.Namespace)); err != nil { + return ctrl.Result{}, err + } + want := DesiredValuesFrom(hr, templates.Items) + kept, err := r.keepPending(ctx, hr, want) + if err != nil { + return ctrl.Result{}, err + } + want = append(want, kept...) + result := ctrl.Result{} + if len(kept) > 0 { + result.RequeueAfter = valuesRecheck + } + if equality.Semantic.DeepEqual(hr.Spec.ValuesFrom, want) { + return result, nil + } + updated := hr.DeepCopy() + updated.Spec.ValuesFrom = want + return result, r.Update(ctx, updated) +} + +// keepPending returns the account entries of the live release that no +// template accounts for yet but whose Secret exists: the conversion writes +// both before the converted chart renders the templates, and the templates +// of one release reach this controller one event at a time. Dropping such an +// entry would take the account out of the chart until its template appears. +// An entry goes once its Secret is gone, which the garbage collector does +// after the template is removed. +func (r *CredentialValuesReconciler) keepPending(ctx context.Context, hr *helmv2.HelmRelease, want []helmv2.ValuesReference) ([]helmv2.ValuesReference, error) { + present := map[string]bool{} + for _, ref := range want { + if account.IsAccountValuesFrom(ref) { + present[ref.Name] = true + } + } + var kept []helmv2.ValuesReference + for _, ref := range hr.Spec.ValuesFrom { + if !account.IsAccountValuesFrom(ref) || present[ref.Name] { + continue + } + sec := &metav1.PartialObjectMetadata{} + sec.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("Secret")) + err := r.Reader.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: ref.Name}, sec) + switch { + case apierrors.IsNotFound(err): + continue + case err != nil: + return nil, err + } + kept = append(kept, ref) + } + return kept, nil +} + +// DesiredValuesFrom returns the valuesFrom of a HelmRelease with its account +// entries replaced by one per live template of the release that names a +// valuesPath, ordered by template name; every other entry stays where it is. +func DesiredValuesFrom(hr *helmv2.HelmRelease, templates []cozyv1alpha1.CredentialTemplate) []helmv2.ValuesReference { + var out []helmv2.ValuesReference + for _, ref := range hr.Spec.ValuesFrom { + if !account.IsAccountValuesFrom(ref) { + out = append(out, ref) + } + } + var mine []cozyv1alpha1.CredentialTemplate + for _, t := range templates { + if t.Annotations[account.ReleaseNameAnnotation] == hr.Name && t.Spec.ValuesPath != "" && t.DeletionTimestamp.IsZero() { + mine = append(mine, t) + } + } + sort.Slice(mine, func(i, j int) bool { return mine[i].Name < mine[j].Name }) + for _, t := range mine { + out = append(out, account.ValuesFrom(t.Name+account.SecretSuffix, t.Spec.ValuesPath, t.Spec.Username)) + } + return out +} + +// SetupWithManager registers the reconciler. +func (r *CredentialValuesReconciler) SetupWithManager(mgr ctrl.Manager) error { + toRelease := handler.EnqueueRequestsFromMapFunc(func(_ context.Context, o client.Object) []reconcile.Request { + release := o.GetAnnotations()[account.ReleaseNameAnnotation] + if release == "" { + return nil + } + return []reconcile.Request{{NamespacedName: types.NamespacedName{Namespace: o.GetNamespace(), Name: release}}} + }) + return ctrl.NewControllerManagedBy(mgr). + Named("credentialvalues"). + Watches(&cozyv1alpha1.CredentialTemplate{}, toRelease). + Complete(r) +} diff --git a/internal/controller/credentialtemplate_controller_test.go b/internal/controller/credentialtemplate_controller_test.go new file mode 100644 index 000000000..df5af9518 --- /dev/null +++ b/internal/controller/credentialtemplate_controller_test.go @@ -0,0 +1,324 @@ +// SPDX-License-Identifier: Apache-2.0 + +package controller + +import ( + "context" + "testing" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + 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/event" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" +) + +const ( + ctNamespace = "tenant-foo" + ctRelease = "postgres-orders" + ctName = ctRelease + ".web" +) + +type ctFixture struct { + c client.Client + r *CredentialTemplateReconciler + recorder *record.FakeRecorder +} + +func newCTFixture(t *testing.T, seed bool, objs ...client.Object) *ctFixture { + 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: ctRelease, Namespace: ctNamespace}} + if seed { + hr.Annotations = map[string]string{account.SeedAnnotation: "true"} + } + c := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(append(objs, hr)...). + WithStatusSubresource(&cozyv1alpha1.CredentialTemplate{}). + Build() + rec := record.NewFakeRecorder(10) + return &ctFixture{ + c: c, + recorder: rec, + r: &CredentialTemplateReconciler{ + 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 ctTemplate(formatName string) *cozyv1alpha1.CredentialTemplate { + return &cozyv1alpha1.CredentialTemplate{ + ObjectMeta: metav1.ObjectMeta{ + Name: ctName, Namespace: ctNamespace, UID: "tmpl-uid", + Annotations: map[string]string{account.ReleaseNameAnnotation: ctRelease}, + }, + Spec: cozyv1alpha1.CredentialTemplateSpec{ + Username: "web", + Format: cozyv1alpha1.CredentialTemplateFormat{Name: formatName}, + Secret: cozyv1alpha1.CredentialTemplateSecret{Labels: map[string]string{"cnpg.io/reload": "true"}}, + }, + } +} + +func (f *ctFixture) reconcile(t *testing.T) { + t.Helper() + if _, err := f.r.Reconcile(context.Background(), reconcile.Request{NamespacedName: types.NamespacedName{Namespace: ctNamespace, Name: ctName}}); err != nil { + t.Fatal(err) + } +} + +func (f *ctFixture) secret(t *testing.T) *corev1.Secret { + t.Helper() + sec := &corev1.Secret{} + err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: ctName + account.SecretSuffix}, sec) + if apierrors.IsNotFound(err) { + return nil + } + if err != nil { + t.Fatal(err) + } + return sec +} + +func (f *ctFixture) template(t *testing.T) *cozyv1alpha1.CredentialTemplate { + t.Helper() + tmpl := &cozyv1alpha1.CredentialTemplate{} + if err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: ctName}, tmpl); err != nil { + t.Fatal(err) + } + return tmpl +} + +func TestCredentialTemplateSeedsAMarkedRelease(t *testing.T) { + f := newCTFixture(t, true, ctTemplate("scram-sha-256")) + f.reconcile(t) + sec := f.secret(t) + if sec == nil { + t.Fatal("no Secret seeded") + } + if ref := metav1.GetControllerOf(sec); ref == nil || ref.Name != ctName { + t.Errorf("controller = %v, want the template", ref) + } + if string(sec.Data[account.UsernameKey]) != "web" || len(sec.Data[account.PasswordKey]) == 0 { + t.Errorf("data = %v", sec.Data) + } + if sec.Labels["cnpg.io/reload"] != "true" || sec.Labels[account.AccountLabel] != "true" || sec.Annotations[account.FormatAnnotation] != "scram-sha-256" { + t.Errorf("labels %v annotations %v", sec.Labels, sec.Annotations) + } + if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginNotIssued || rec.By != CredentialControllerActor { + t.Errorf("record = %+v", rec) + } + st := f.template(t).Status + if st.SecretResourceVersion != sec.ResourceVersion || st.Password.Origin != "NotIssued" || len(st.History) != 1 { + t.Errorf("status = %+v, want the Secret's record mirrored", st) + } +} + +func TestCredentialTemplateLeavesAnUnmarkedReleaseToAMint(t *testing.T) { + f := newCTFixture(t, false, ctTemplate("scram-sha-256")) + f.reconcile(t) + if f.secret(t) != nil { + t.Fatal("a Secret was seeded on a release whose clients may hold the old password") + } + if st := f.template(t).Status; st.SecretResourceVersion != "" || st.Password.Origin != "NotIssued" { + t.Errorf("status = %+v", st) + } +} + +func TestCredentialTemplateReseedsWhenTheFormatChanges(t *testing.T) { + f := newCTFixture(t, true, ctTemplate("scram-sha-256")) + f.reconcile(t) + before := f.secret(t) + + tmpl := f.template(t) + tmpl.Spec.Format.Name = "sha256" + if err := f.c.Update(context.Background(), tmpl); err != nil { + t.Fatal(err) + } + f.reconcile(t) + after := f.secret(t) + if after.Annotations[account.FormatAnnotation] != "sha256" || string(after.Data[account.PasswordKey]) == string(before.Data[account.PasswordKey]) { + t.Errorf("Secret not seeded again in the new format: %v", after.Annotations) + } + if rec := account.ReadRecord(after); rec.Origin != corev1alpha1.CredentialOriginNotIssued || len(rec.History) != 2 { + t.Errorf("record = %+v, want a second Create on top of the first", rec) + } + select { + case ev := <-f.recorder.Events: + if ev == "" { + t.Error("empty event") + } + default: + t.Error("no event recorded for the reset") + } +} + +func TestCredentialTemplateAdoptsAMigratedSecret(t *testing.T) { + migrated := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: ctName + account.SecretSuffix, Namespace: ctNamespace, + Labels: map[string]string{account.AccountLabel: "true"}, + }, + Data: map[string][]byte{account.UsernameKey: []byte("web"), account.PasswordKey: []byte("SCRAM-SHA-256$migrated")}, + } + account.WriteRecord(migrated, account.Record{}.Apply(corev1alpha1.CredentialOperationMigrate, metav1.Now(), "migration")) + f := newCTFixture(t, true, ctTemplate("scram-sha-256"), migrated) + f.reconcile(t) + sec := f.secret(t) + if ref := metav1.GetControllerOf(sec); ref == nil || ref.Name != ctName { + t.Fatalf("controller = %v, want the template", ref) + } + if string(sec.Data[account.PasswordKey]) != "SCRAM-SHA-256$migrated" { + t.Error("the migrated verifier was replaced") + } + if sec.Labels["cnpg.io/reload"] != "true" || sec.Annotations[account.FormatAnnotation] != "scram-sha-256" { + t.Errorf("labels %v annotations %v", sec.Labels, sec.Annotations) + } + if st := f.template(t).Status; st.Password.Origin != "Migrated" { + t.Errorf("origin = %q, want Migrated", st.Password.Origin) + } +} + +func TestCredentialTemplateLeavesAForeignSecretAlone(t *testing.T) { + foreign := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: ctName + account.SecretSuffix, Namespace: ctNamespace}, + Data: map[string][]byte{"key": []byte("value")}, + } + f := newCTFixture(t, true, ctTemplate("scram-sha-256"), foreign) + f.reconcile(t) + sec := f.secret(t) + if metav1.GetControllerOf(sec) != nil || string(sec.Data["key"]) != "value" { + t.Error("the controller touched a Secret it did not create") + } + if !meta.IsStatusConditionTrue(f.template(t).Status.Conditions, cozyv1alpha1.CredentialTemplateSecretConflict) { + t.Error("no SecretConflict condition") + } +} + +func TestCredentialTemplateReportsAnUnknownFormat(t *testing.T) { + f := newCTFixture(t, true, ctTemplate("apr1")) + f.reconcile(t) + if f.secret(t) != nil { + t.Error("a Secret was seeded in a format the controller does not have") + } + if !meta.IsStatusConditionTrue(f.template(t).Status.Conditions, cozyv1alpha1.CredentialTemplateUnknownFormat) { + t.Error("no UnknownFormat condition") + } +} + +func TestCredentialTemplateMirrorsAMint(t *testing.T) { + f := newCTFixture(t, true, ctTemplate("scram-sha-256")) + f.reconcile(t) + sec := f.secret(t) + account.WriteRecord(sec, account.ReadRecord(sec).Apply(corev1alpha1.CredentialOperationMint, metav1.Now(), "jane")) + if err := f.c.Update(context.Background(), sec); err != nil { + t.Fatal(err) + } + f.reconcile(t) + st := f.template(t).Status + if st.Password.Origin != "Minted" || st.Password.By != "jane" || st.SecretResourceVersion != f.secret(t).ResourceVersion { + t.Errorf("status = %+v, want the mint mirrored", st) + } +} + +func TestDesiredValuesFrom(t *testing.T) { + hr := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "clickhouse-logs"}} + hr.Spec.ValuesFrom = []helmv2.ValuesReference{ + {Kind: "Secret", Name: "cozystack-values"}, + account.ValuesFrom("clickhouse-logs.gone.account", "_accounts", "gone"), + } + mk := func(name, user, path, release string) cozyv1alpha1.CredentialTemplate { + return cozyv1alpha1.CredentialTemplate{ + ObjectMeta: metav1.ObjectMeta{Name: name, Annotations: map[string]string{account.ReleaseNameAnnotation: release}}, + Spec: cozyv1alpha1.CredentialTemplateSpec{Username: user, ValuesPath: path}, + } + } + got := DesiredValuesFrom(hr, []cozyv1alpha1.CredentialTemplate{ + mk("clickhouse-logs.web", "web", "_accounts", "clickhouse-logs"), + mk("clickhouse-logs.api", "api", "_accounts", "clickhouse-logs"), + mk("clickhouse-logs.nopath", "nopath", "", "clickhouse-logs"), + mk("other.web", "web", "_accounts", "other"), + }) + if len(got) != 3 || got[0].Name != "cozystack-values" || got[1].Name != "clickhouse-logs.api.account" || got[2].Name != "clickhouse-logs.web.account" { + t.Errorf("valuesFrom = %+v, want the platform values, then api and web, and no entry for a removed account", got) + } +} + +func TestCredentialValuesKeepsAnEntryWhoseSecretExists(t *testing.T) { + 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) + } + } + pending := account.ValuesFrom("clickhouse-logs.api.account", "_accounts", "api") + gone := account.ValuesFrom("clickhouse-logs.gone.account", "_accounts", "gone") + hr := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "clickhouse-logs", Namespace: ctNamespace}} + hr.Spec.ValuesFrom = []helmv2.ValuesReference{{Kind: "Secret", Name: "cozystack-values"}, pending, gone} + tmpl := &cozyv1alpha1.CredentialTemplate{ + ObjectMeta: metav1.ObjectMeta{Name: "clickhouse-logs.web", Namespace: ctNamespace, Annotations: map[string]string{account.ReleaseNameAnnotation: "clickhouse-logs"}}, + Spec: cozyv1alpha1.CredentialTemplateSpec{Username: "web", ValuesPath: "_accounts"}, + } + // The conversion wrote api's Secret before the chart rendered its template. + sec := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "clickhouse-logs.api.account", Namespace: ctNamespace}} + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(hr, tmpl, sec).Build() + r := &CredentialValuesReconciler{Client: c, Reader: c} + res, err := r.Reconcile(context.Background(), reconcile.Request{NamespacedName: types.NamespacedName{Namespace: ctNamespace, Name: "clickhouse-logs"}}) + if err != nil { + t.Fatal(err) + } + if res.RequeueAfter == 0 { + t.Error("a kept entry must be looked at again") + } + got := &helmv2.HelmRelease{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: "clickhouse-logs"}, got); err != nil { + t.Fatal(err) + } + names := map[string]bool{} + for _, ref := range got.Spec.ValuesFrom { + names[ref.Name] = true + } + if !names["clickhouse-logs.web.account"] || !names["clickhouse-logs.api.account"] || names["clickhouse-logs.gone.account"] { + t.Errorf("valuesFrom = %+v, want web (template), api (Secret, template pending), and no gone", got.Spec.ValuesFrom) + } +} + +func TestSeedMarkChangedPassesOnlyAMarkChange(t *testing.T) { + marked := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "r", Annotations: map[string]string{account.SeedAnnotation: "true"}}} + plain := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "r"}} + if !seedMarkChanged.Update(event.UpdateEvent{ObjectOld: plain, ObjectNew: marked}) { + t.Error("a release that gained the mark must wake the templates") + } + if seedMarkChanged.Update(event.UpdateEvent{ObjectOld: marked, ObjectNew: marked.DeepCopy()}) { + t.Error("a status write must not wake the templates") + } +} + +func TestTemplatesOfReleaseMapsOnlyItsTemplates(t *testing.T) { + other := ctTemplate("scram-sha-256") + other.Name = "postgres-other.web" + other.Annotations = map[string]string{account.ReleaseNameAnnotation: "postgres-other"} + f := newCTFixture(t, true, ctTemplate("scram-sha-256"), other) + reqs := f.r.templatesOfRelease(context.Background(), &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: ctRelease, Namespace: ctNamespace}}) + if len(reqs) != 1 || reqs[0].Name != ctName { + t.Errorf("requests = %v, want only %s", reqs, ctName) + } +} From d1c5bc6fe2e74725d632e4cfa4729619c0fc21bf Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Mon, 23 Nov 2026 16:27:00 +0100 Subject: [PATCH 07/10] feat(api): mark created releases for seeding and keep account values A release the Cozystack API creates has only new accounts, so it is marked for the CredentialTemplate controller to seed. The mark sits outside the apps.cozystack.io- prefix, so an update keeps it. An update rebuilds the HelmRelease from the Application, which lists only the platform values; it now carries over the account valuesFrom entries of the live release, since dropping them would take every account's stored value out of the chart until the controller put them back. Deleting an application whose release is suspended and carries accounts is refused with a conflict. Flux skips the uninstall of a suspended release, so the database would keep running with its last passwords after the account Secrets went with the templates. Co-authored-by: Timofei Larkin Assisted-by: LLM Signed-off-by: Andrei Kvapil --- pkg/registry/apps/application/rest.go | 7 ++ .../apps/application/rest_credentials.go | 62 ++++++++++ .../apps/application/rest_credentials_test.go | 108 ++++++++++++++++++ 3 files changed, 177 insertions(+) create mode 100644 pkg/registry/apps/application/rest_credentials.go create mode 100644 pkg/registry/apps/application/rest_credentials_test.go diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index 60816a43d..038ecff17 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -250,6 +250,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation helmRelease.Labels[ApplicationGroupLabel] = r.gvk.Group helmRelease.Labels[ApplicationNameLabel] = app.Name // Note: Annotations from config are not handled as r.releaseConfig.Annotations is undefined + markForSeeding(helmRelease) klog.V(6).Infof("Creating HelmRelease %s in namespace %s", helmRelease.Name, app.Namespace) @@ -611,6 +612,7 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje return nil, false, err } r.applyLiveMetadata(helmRelease, cur, app, previousFinalizers) + keepAccountValuesFrom(helmRelease, cur) // Suspension is not part of the Application, so the rebuilt object always // says suspend=false, and sending it as is resumes a release that an @@ -655,6 +657,7 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje } helmRelease = converted.DeepCopy() r.applyLiveMetadata(helmRelease, cur, app, previousFinalizers) + keepAccountValuesFrom(helmRelease, cur) helmRelease.SetResourceVersion(cur.GetResourceVersion()) helmRelease.Spec.Suspend = cur.Spec.Suspend } @@ -733,6 +736,10 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va options.Preconditions.ResourceVersion = &liveRV } + if err := r.refuseDeleteSuspended(ctx, name, helmRelease); err != nil { + return nil, false, err + } + // Run the genericapiserver-supplied admission chain (validating webhooks // and ValidatingAdmissionPolicies) on the resolved Application before // removing the underlying HelmRelease. Custom REST handlers must invoke diff --git a/pkg/registry/apps/application/rest_credentials.go b/pkg/registry/apps/application/rest_credentials.go new file mode 100644 index 000000000..f875356dd --- /dev/null +++ b/pkg/registry/apps/application/rest_credentials.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 + +package application + +import ( + "context" + "fmt" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" +) + +// markForSeeding lets the CredentialTemplate controller seed the account +// Secrets of a release the API creates: its accounts are new, so no client +// holds a password a seeded one would replace. A release created before the +// mark existed gets it from the conversion, once the conversion has written +// its Secrets. The mark is outside the apps.cozystack.io- prefix, so an update +// keeps it. +func markForSeeding(hr *helmv2.HelmRelease) { + if hr.Annotations == nil { + hr.Annotations = map[string]string{} + } + hr.Annotations[account.SeedAnnotation] = "true" +} + +// keepAccountValuesFrom carries over the valuesFrom entries the +// CredentialTemplate controller added to the live release: the rebuilt +// release lists only the platform values, and dropping the entries would +// take every account's stored value out of the chart until the controller +// put them back. +func keepAccountValuesFrom(hr, cur *helmv2.HelmRelease) { + for _, ref := range cur.Spec.ValuesFrom { + if account.IsAccountValuesFrom(ref) { + hr.Spec.ValuesFrom = append(hr.Spec.ValuesFrom, ref) + } + } +} + +// refuseDeleteSuspended refuses to delete an application whose release is +// suspended and carries accounts: Flux skips the uninstall of a suspended +// release, so the database would keep running with its last passwords after +// the account Secrets went with the release's templates. +func (r *REST) refuseDeleteSuspended(ctx context.Context, name string, hr *helmv2.HelmRelease) error { + if !hr.Spec.Suspend { + return nil + } + templates := &cozyv1alpha1.CredentialTemplateList{} + if err := r.c.List(ctx, templates, client.InNamespace(hr.Namespace)); err != nil { + return err + } + for _, t := range templates.Items { + if t.Annotations[account.ReleaseNameAnnotation] == hr.Name { + return apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf( + "release %s is suspended, and deleting it would leave the database running after its account Secrets are gone; resume the release first", hr.Name)) + } + } + return nil +} diff --git a/pkg/registry/apps/application/rest_credentials_test.go b/pkg/registry/apps/application/rest_credentials_test.go new file mode 100644 index 000000000..4cc8d42bf --- /dev/null +++ b/pkg/registry/apps/application/rest_credentials_test.go @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: Apache-2.0 + +package application + +import ( + "context" + "testing" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + apierrors "k8s.io/apimachinery/pkg/api/errors" + 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" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" + "github.com/cozystack/cozystack/pkg/config" + "github.com/cozystack/cozystack/pkg/credentials/account" +) + +func newCredentialsTestREST(t *testing.T, objs ...client.Object) (*REST, client.Client) { + t.Helper() + scheme := runtime.NewScheme() + if err := helmv2.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := cozyv1alpha1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + resourceCfg := &config.ResourceConfig{Resources: []config.Resource{{Application: config.ApplicationConfig{Kind: "Postgres"}}}} + if err := appsv1alpha1.RegisterDynamicTypes(scheme, resourceCfg); err != nil { + t.Fatal(err) + } + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objs...).Build() + return &REST{ + c: c, + gvr: schema.GroupVersionResource{Group: appsv1alpha1.GroupName, Version: "v1alpha1", Resource: "postgreses"}, + gvk: schema.GroupVersionKind{Group: appsv1alpha1.GroupName, Version: "v1alpha1", Kind: "Postgres"}, + kindName: "Postgres", + releaseConfig: config.ReleaseConfig{Prefix: "postgres-"}, + }, c +} + +func accountTemplate(release string) *cozyv1alpha1.CredentialTemplate { + return &cozyv1alpha1.CredentialTemplate{ObjectMeta: metav1.ObjectMeta{ + Name: release + ".web", Namespace: "tenant-foo", + Annotations: map[string]string{account.ReleaseNameAnnotation: release}, + }} +} + +// TestUpdate_KeepsAccountValuesFromAndTheSeedMark pins that an Application +// write leaves the CredentialTemplate controller's state on the release: the +// valuesFrom entries that carry each account's stored value into the chart, +// and the mark that lets the controller seed. The rebuilt release lists only +// the platform values, so dropping the entries would take the accounts out of +// the chart until the controller put them back. +func TestUpdate_KeepsAccountValuesFromAndTheSeedMark(t *testing.T) { + hr := suspendTestHelmRelease(false) + hr.Annotations = map[string]string{account.SeedAnnotation: "true"} + entry := account.ValuesFrom("postgres-pg.web.account", "_accounts", "web") + hr.Spec.ValuesFrom = []helmv2.ValuesReference{{Kind: "Secret", Name: "cozystack-values"}, entry} + r, c := newCredentialsTestREST(t, hr) + + ctx := request.WithNamespace(context.Background(), "tenant-foo") + if _, _, err := r.Update(ctx, "pg", newDefaultUpdatedObjectInfo(suspendTestApplication()), nil, nil, false, &metav1.UpdateOptions{}); err != nil { + t.Fatal(err) + } + got := &helmv2.HelmRelease{} + if err := c.Get(ctx, client.ObjectKey{Namespace: "tenant-foo", Name: "postgres-pg"}, got); err != nil { + t.Fatal(err) + } + if len(got.Spec.ValuesFrom) != 2 || got.Spec.ValuesFrom[1] != entry { + t.Errorf("valuesFrom = %+v, want the platform values and the account entry", got.Spec.ValuesFrom) + } + if got.Annotations[account.SeedAnnotation] != "true" { + t.Error("the seed mark was dropped") + } +} + +func TestMarkForSeeding(t *testing.T) { + hr := &helmv2.HelmRelease{} + markForSeeding(hr) + if hr.Annotations[account.SeedAnnotation] != "true" { + t.Errorf("annotations = %v", hr.Annotations) + } +} + +// TestDelete_RefusesASuspendedReleaseWithAccounts: Flux skips the uninstall of +// a suspended release, so deleting it would leave the database running after +// its account Secrets went with the templates. +func TestDelete_RefusesASuspendedReleaseWithAccounts(t *testing.T) { + r, _ := newCredentialsTestREST(t, suspendTestHelmRelease(true), accountTemplate("postgres-pg")) + ctx := request.WithNamespace(context.Background(), "tenant-foo") + if _, _, err := r.Delete(ctx, "pg", nil, &metav1.DeleteOptions{}); !apierrors.IsConflict(err) { + t.Fatalf("err = %v, want a conflict", err) + } +} + +func TestDelete_AllowsASuspendedReleaseWithoutAccounts(t *testing.T) { + r, _ := newCredentialsTestREST(t, suspendTestHelmRelease(true), accountTemplate("postgres-other")) + ctx := request.WithNamespace(context.Background(), "tenant-foo") + if _, _, err := r.Delete(ctx, "pg", nil, &metav1.DeleteOptions{}); apierrors.IsConflict(err) { + t.Fatalf("err = %v, a release without accounts must delete", err) + } +} From 6f02ad753959a81a3ba633d1d6c801e91da7414f Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Mon, 23 Nov 2026 16:27:00 +0100 Subject: [PATCH 08/10] feat(platform): let tenants read Credentials and admins mint them A Credential carries who set an account's password and when, never the value, so it is readable at view. A mint replaces the password and shows the new one once, so mint and revoke are an admin's write. The tenant ServiceAccount gets them too, because it is what the dashboard signs in with when OIDC is off. Assisted-by: LLM Signed-off-by: Timofei Larkin Signed-off-by: Andrei Kvapil --- hack/e2e-tenant-super-admin-write-verbs.yaml | 2 + .../templates/clusterroles.yaml | 28 ++++++++ .../tests/clusterroles-credentials_test.yaml | 67 +++++++++++++++++++ 3 files changed, 97 insertions(+) create mode 100644 packages/system/cozystack-basics/tests/clusterroles-credentials_test.yaml diff --git a/hack/e2e-tenant-super-admin-write-verbs.yaml b/hack/e2e-tenant-super-admin-write-verbs.yaml index f267e1068..c700fa62b 100644 --- a/hack/e2e-tenant-super-admin-write-verbs.yaml +++ b/hack/e2e-tenant-super-admin-write-verbs.yaml @@ -13,6 +13,8 @@ writeVerbs: - "backupjobs.backups.cozystack.io - delete" - "backupjobs.backups.cozystack.io - patch" - "backupjobs.backups.cozystack.io - update" +- "credentials.core.cozystack.io/mint - create" +- "credentials.core.cozystack.io/revoke - create" - "endpoints - delete" - "events - delete" - "persistentvolumes - delete" diff --git a/packages/system/cozystack-basics/templates/clusterroles.yaml b/packages/system/cozystack-basics/templates/clusterroles.yaml index 297667a49..15d381eb7 100644 --- a/packages/system/cozystack-basics/templates/clusterroles.yaml +++ b/packages/system/cozystack-basics/templates/clusterroles.yaml @@ -50,6 +50,19 @@ rules: - options - taps verbs: ["get", "list", "watch"] +- apiGroups: + - core.cozystack.io + resources: + - credentials + verbs: ["get", "list"] +# The tenant ServiceAccount is what the dashboard signs in with when OIDC is +# off, so it issues and revokes passwords as a tenant admin does. +- apiGroups: + - core.cozystack.io + resources: + - credentials/mint + - credentials/revoke + verbs: ["create"] --- # == view cluster role == # Aggregates all roles labeled for view access @@ -138,6 +151,13 @@ rules: - options - taps verbs: ["get", "list", "watch"] +{{/* A Credential is the record of one account: who set its password and when, + never the value. Mint and revoke are separate subresources granted at admin. */}} +- apiGroups: + - core.cozystack.io + resources: + - credentials + verbs: ["get", "list"] {{/* Read-only visibility into the objects that govern read-replica autoscaling of a tenant's own databases: the KEDA ScaledObject the chart renders into the tenant namespace and the keda-hpa- HorizontalPodAutoscaler KEDA creates beside @@ -301,6 +321,14 @@ rules: - update - patch - delete +# A mint replaces an account's password and shows the new one once, so it is +# an admin's write, not a reader's. +- apiGroups: ["core.cozystack.io"] + resources: + - credentials/mint + - credentials/revoke + verbs: + - create --- # == super admin cluster role == # Aggregates admin + all roles labeled for super-admin access diff --git a/packages/system/cozystack-basics/tests/clusterroles-credentials_test.yaml b/packages/system/cozystack-basics/tests/clusterroles-credentials_test.yaml new file mode 100644 index 000000000..d40bba152 --- /dev/null +++ b/packages/system/cozystack-basics/tests/clusterroles-credentials_test.yaml @@ -0,0 +1,67 @@ +suite: cozystack-basics tenant ClusterRoles grant the credentials API + +templates: + - templates/clusterroles.yaml + +release: + name: cozystack-basics + namespace: cozy-system + +# Reading a Credential is a view-tier grant; minting and revoking are admin +# writes, and the tenant ServiceAccount holds both. The subresources are gated +# by verb create on their own resource names, so a grant on credentials alone +# issues nothing. +tests: + - it: cozy:tenant:view:base grants read on core.cozystack.io credentials + documentSelector: + path: metadata.name + value: cozy:tenant:view:base + asserts: + - contains: + path: rules + content: + apiGroups: ["core.cozystack.io"] + resources: ["credentials"] + verbs: ["get", "list"] + + - it: cozy:tenant:view:base does not grant mint or revoke + documentSelector: + path: metadata.name + value: cozy:tenant:view:base + asserts: + - notContains: + path: rules + content: + apiGroups: ["core.cozystack.io"] + resources: ["credentials/mint", "credentials/revoke"] + verbs: ["create"] + + - it: cozy:tenant:admin:base grants create on credentials/mint and credentials/revoke + documentSelector: + path: metadata.name + value: cozy:tenant:admin:base + asserts: + - contains: + path: rules + content: + apiGroups: ["core.cozystack.io"] + resources: ["credentials/mint", "credentials/revoke"] + verbs: ["create"] + + - it: cozy:tenant:base grants read on credentials and create on mint and revoke + documentSelector: + path: metadata.name + value: cozy:tenant:base + asserts: + - contains: + path: rules + content: + apiGroups: ["core.cozystack.io"] + resources: ["credentials"] + verbs: ["get", "list"] + - contains: + path: rules + content: + apiGroups: ["core.cozystack.io"] + resources: ["credentials/mint", "credentials/revoke"] + verbs: ["create"] From d0c0134eb8863bd4a3093d49793cdce2df0e8df1 Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Mon, 23 Nov 2026 16:27:01 +0100 Subject: [PATCH 09/10] docs(operations): describe the audit trail of credential issuance Attribution of a mint or a revoke comes from the kube-apiserver audit log, which records the caller and the subresource but never the body of a request it proxies to an aggregated API, so the password shown once cannot land in it. A distribution that ships no audit policy records nothing and loses attribution silently, so the page gives a policy for it, says where fluent-bit expects the log, how to find an issuance in VictoriaLogs, and how to ship the log to a SIEM. Assisted-by: LLM Signed-off-by: Timofei Larkin Signed-off-by: Andrei Kvapil --- docs/operations/audit-log.md | 73 ++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 docs/operations/audit-log.md diff --git a/docs/operations/audit-log.md b/docs/operations/audit-log.md new file mode 100644 index 000000000..5a6bae0d7 --- /dev/null +++ b/docs/operations/audit-log.md @@ -0,0 +1,73 @@ +# Kubernetes Audit Log + +Cozystack attributes every issuance and revocation of a managed application password to the kube-apiserver audit log. A mint is a `create` on the `mint` subresource of a `core.cozystack.io` Credential, which kube-apiserver audits before it proxies the request to the Cozystack API, recording the caller, the time, the account in `objectRef` and the subresource that tells a mint from a revoke. kube-apiserver records neither the body nor the response of a request it proxies to an aggregated API, at any audit level, so the password shown once in the mint response cannot reach the log. The Cozystack API itself runs without audit flags, and it must stay that way or get a policy that keeps `credentials` below `RequestResponse`, because it is the one server that could write the password down. + +The `monitoring-agents` package tails `/var/log/audit/kube/*.log` on every node and ships it to the VictoriaLogs instance in the `tenant-root` tenant, tagged `audit.*`, where it is kept for a month by default. Only `tenant-root` can read that store. Every other tenant sees the last ten operations on each of its accounts in the Credential's `status.history`, and each mint and revoke also records a Kubernetes Event on the application, with reason `CredentialIssued` or `CredentialRevoked`, naming the account and the caller. + +## Distributions that ship no audit policy + +Talos Linux configures kube-apiserver with an audit policy and writes the log under `/var/log/audit/kube/` out of the box, which is where the default fluent-bit input reads it. A cluster built on a distribution that gives kube-apiserver no audit policy records nothing, so attribution is lost silently. Give it the policy below, or merge these rules into the policy it has, and point the log at the directory fluent-bit tails. + +```yaml +apiVersion: audit.k8s.io/v1 +kind: Policy +omitStages: + - RequestReceived +rules: + # Who issued or revoked which account, and when. Metadata is all there is to + # record for a proxied request, and all there must ever be for this resource. + - level: Metadata + resources: + - group: core.cozystack.io + resources: + - credentials + - credentials/mint + - credentials/revoke + # Account Secrets and the tenantsecrets view carry stored password forms; + # Metadata keeps their data out of the log. + - level: Metadata + resources: + - group: "" + resources: + - secrets + - group: core.cozystack.io + resources: + - tenantsecrets + - level: Metadata +``` + +``` +--audit-policy-file=/etc/kubernetes/audit-policy.yaml +--audit-log-path=/var/log/audit/kube/kube-apiserver.log +--audit-log-maxage=30 +--audit-log-maxbackup=10 +--audit-log-maxsize=100 +``` + +The log path has to be a file under the node's `/var/log/audit/kube/` directory, because the fluent-bit DaemonSet mounts the node's `/var/log` and tails that glob. A distribution that writes the log elsewhere needs `fluent-bit.config.inputs` in the `monitoring-agents` values changed to match. + +## Finding an issuance + +In VictoriaLogs, the stream fields of the audit output include `verb` and `user_username`, and the record keeps the whole audit event, so a mint is found by its subresource: + +``` +objectRef.subresource:mint AND objectRef.resource:credentials +``` + +The matching record names the Credential in `objectRef.name`, the caller in `user_username`, the impersonated user where Kubernetes impersonation was used, the source address, the response code and the authorization decision. The user is a person only when the dashboard signs in through OIDC; without it, the dashboard acts as the tenant ServiceAccount. + +## Shipping the log to a SIEM + +The fluent-bit outputs of `monitoring-agents` are one string, so replacing `config.outputs` to add a destination drops the VictoriaLogs outputs with it. Add an output under `fluent-bit.config.extraOutputs` instead, which is appended after them. The audit records carry the tag `audit.*`: + +```yaml +fluent-bit: + config: + extraOutputs: | + [OUTPUT] + Name forward + Match audit.* + Host siem.example.org + Port 24224 + tls on +``` From 0c66790a54cbed1b5db2bf3533ca88701a490b31 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Mon, 23 Nov 2026 16:27:01 +0100 Subject: [PATCH 10/10] feat(dashboard): manage application credentials from the console Converted applications no longer let tenants read their passwords from a Secret: the API mints a password on request and shows it once. Without a console path, tenants who only use the dashboard would have no way to log in to a fresh database or to replace a migrated password. The Credentials tab lists an application's accounts with where the live password came from and its history, and offers mint and revoke behind a confirmation. Every request carries the resourceVersion the user saw, so a concurrent mint surfaces as a conflict instead of silently killing the password someone else just received. Actions are gated on a SelfSubjectAccessReview so viewers see the record without the buttons. The Credential API serves no watch, so the tab polls, the one exception to the console's no-polling rule besides the metrics panels. Mint and revoke bypass the mutation hooks because React Query keeps a mutation's result in its cache, and a minted password must live only in the dialog's state. The console's agent notes record both, since either would otherwise look like a mistake. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- .../system/dashboard/images/console/CLAUDE.md | 1 + .../detail/ApplicationDetailPage.test.tsx | 39 +++- .../routes/detail/ApplicationDetailPage.tsx | 19 ++ .../routes/detail/CredentialActionDialog.tsx | 158 +++++++++++++++ .../src/routes/detail/CredentialsTab.test.tsx | 187 ++++++++++++++++++ .../src/routes/detail/CredentialsTab.tsx | 151 ++++++++++++++ .../routes/detail/credential-origin.test.ts | 24 +++ .../src/routes/detail/credential-origin.ts | 55 ++++++ .../src/routes/detail/use-app-credentials.ts | 91 +++++++++ 9 files changed, 724 insertions(+), 1 deletion(-) create mode 100644 packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialActionDialog.tsx create mode 100644 packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialsTab.test.tsx create mode 100644 packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialsTab.tsx create mode 100644 packages/system/dashboard/images/console/apps/console/src/routes/detail/credential-origin.test.ts create mode 100644 packages/system/dashboard/images/console/apps/console/src/routes/detail/credential-origin.ts create mode 100644 packages/system/dashboard/images/console/apps/console/src/routes/detail/use-app-credentials.ts diff --git a/packages/system/dashboard/images/console/CLAUDE.md b/packages/system/dashboard/images/console/CLAUDE.md index 036e527d6..c7b04a3b3 100644 --- a/packages/system/dashboard/images/console/CLAUDE.md +++ b/packages/system/dashboard/images/console/CLAUDE.md @@ -82,6 +82,7 @@ the apiserver checks that user's RBAC. poll. Don't add `refetchInterval`. If you need a one-shot, pass `{ watch: false }`. The one exception is the metrics panels in `components/observability`: the observability proxy serves the Prometheus query API, which has no watch, so they refresh on a fixed interval instead. Log lines stream through the tail endpoint and are not polled. + The Credentials tab is the other one: the `core.cozystack.io` Credential API serves no watch, so `use-app-credentials.ts` polls its list. Mint and revoke call `K8sClient.subresource` directly rather than through a mutation hook, because React Query keeps a mutation's result in its cache and a minted password must live only in the dialog's state. 4. **Tenant scoping.** Most resources live in `tenant-` namespaces. Pull the active tenant from `useTenantContext()` — never read the namespace from a URL param or guess it. diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx index a0c3a6b84..7422205d4 100644 --- a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx @@ -11,6 +11,7 @@ const h = vi.hoisted(() => ({ tabLabels: [] as string[], configMaps: [] as unknown[], configMapsError: undefined as unknown, + credentials: [] as unknown[], })) vi.mock("@cozystack/k8s-client", async (importOriginal) => ({ @@ -20,7 +21,9 @@ vi.mock("@cozystack/k8s-client", async (importOriginal) => ({ // Presence probes (use-resource-presence.ts) — report empty lists. useK8sList: (ref: { plural: string }) => ref.plural === "configmaps" ? { data: { items: h.configMaps }, error: h.configMapsError, isLoading: false } - : { data: { items: [] }, isLoading: false }, + : ref.plural === "credentials" + ? { data: { items: h.credentials }, isLoading: false } + : { data: { items: [] }, isLoading: false }, })) vi.mock("../../lib/app-definitions.ts", () => ({ useApplicationDefinitions: () => ({ @@ -61,6 +64,7 @@ vi.mock("./SerialTab.tsx", () => ({ SerialTab: () => null })) vi.mock("./VMPowerControls.tsx", () => ({ VMPowerControls: () => null })) vi.mock("./MetricsTab.tsx", () => ({ MetricsTab: () => null })) vi.mock("./LogsTab.tsx", () => ({ LogsTab: () => null })) +vi.mock("./CredentialsTab.tsx", () => ({ CredentialsTab: () => null })) const { ApplicationDetailPage } = await import("./ApplicationDetailPage.tsx") @@ -181,3 +185,36 @@ describe("ApplicationDetailPage configuration", () => { expect(h.tabLabels).not.toContain("ConfigMaps") }) }) + +describe("ApplicationDetailPage credentials", () => { + function showPostgres(credentials: unknown[]) { + h.appKind = "Postgres" + h.appPlural = "postgreses" + h.get = { + data: { kind: "Postgres", metadata: { name: "demo", namespace: "tenant-test" } }, + isLoading: false, + error: undefined, + } + h.configMaps = [] + h.configMapsError = undefined + h.credentials = credentials + h.tabLabels = [] + renderPage() + } + + it("offers Credentials ahead of Secrets once the application has an account", () => { + showPostgres([{ + metadata: { name: "demo.app" }, + spec: { application: { apiGroup: "apps.cozystack.io", kind: "Postgres", name: "demo" }, user: "app" }, + }]) + expect(h.tabLabels.slice(-5)).toEqual(["Credentials", "Secrets", "Metrics", "Logs", "Events"]) + }) + + it("leaves Credentials off while only other applications have accounts", () => { + showPostgres([{ + metadata: { name: "other.app" }, + spec: { application: { apiGroup: "apps.cozystack.io", kind: "Postgres", name: "other" }, user: "app" }, + }]) + expect(h.tabLabels).not.toContain("Credentials") + }) +}) diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx index ab68f7c49..2cbf7d786 100644 --- a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx @@ -44,6 +44,8 @@ import { useResourceBasePath } from "../../lib/portal.ts" import { useResourcePresence } from "./use-resource-presence.ts" import { useApplicationConfigMaps } from "./use-app-configmaps.ts" import { ConfigMapsTab } from "./ConfigMapsTab.tsx" +import { useApplicationCredentials } from "./use-app-credentials.ts" +import { CredentialsTab } from "./CredentialsTab.tsx" import { LogsTab } from "./LogsTab.tsx" export function ApplicationDetailPage() { @@ -82,6 +84,7 @@ export function ApplicationDetailPage() { const presence = useResourcePresence(ad, instance) const configMaps = useApplicationConfigMaps(ad, instance, tenantNamespace ?? undefined) + const credentials = useApplicationCredentials(ad, instance, tenantNamespace ?? undefined) if (!plural || !name) return // Check the fetch error before the loading guard: on a failed GET, isLoading @@ -166,6 +169,10 @@ export function ApplicationDetailPage() { if (configMaps.names.length > 0 || configMaps.error) { tabs.push({ to: `${base}/configmaps`, label: "ConfigMaps", end: false }) } + // Accounts appear seconds after the application is created, on a poll. + if (credentials.credentials.length > 0 || credentials.error) { + tabs.push({ to: `${base}/credentials`, label: "Credentials", end: false }) + } tabs.push( { to: `${base}/secrets`, label: "Secrets", end: false }, { to: `${base}/metrics`, label: "Metrics", end: false }, @@ -246,6 +253,18 @@ export function ApplicationDetailPage() { path="configmaps" element={} /> + { void credentials.refetch() }} + /> + } + /> } diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialActionDialog.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialActionDialog.tsx new file mode 100644 index 000000000..5687d378c --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialActionDialog.tsx @@ -0,0 +1,158 @@ +import { useState } from "react" +import { K8sApiError, useK8sClient } from "@cozystack/k8s-client" +import { Button, Spinner } from "@cozystack/ui" +import { + DialogBackdrop, + DialogDescription, + DialogPopup, + DialogPortal, + DialogRoot, + DialogTitle, +} from "../../components/ui/dialog.tsx" +import { + runCredentialOperation, + type Credential, + type CredentialOperation, +} from "./use-app-credentials.ts" + +type Phase = + | { name: "confirm" } + | { name: "running" } + | { name: "failed"; message: string } + | { name: "minted"; username: string; password: string } + +function failureMessage(error: unknown, operation: CredentialOperation): string { + if (error instanceof K8sApiError && error.status === 409) { + return `${error.message}. The list has been refreshed: check the account and try again.` + } + if (error instanceof K8sApiError && error.status === 403) { + return `You are not allowed to ${operation} this password: ${error.message}` + } + return error instanceof Error ? error.message : "The request failed." +} + +function MintedPassword({ username, password }: { username: string; password: string }) { + const [copy, setCopy] = useState<"idle" | "ok" | "failed">("idle") + const handleCopy = async () => { + try { + await navigator.clipboard.writeText(password) + setCopy("ok") + } catch { + setCopy("failed") + } + } + return ( +
+

+ Save this password now. It cannot be shown again: the platform does not keep it. +

+
+
Username
{username}
+
+
Password
+
{password}
+
+
+
+ + {copy !== "idle" && ( + + {copy === "ok" ? "Copied." : "Could not copy. Select and copy the password manually."} + + )} +
+
+ ) +} + +export function CredentialActionDialog({ + namespace, + credential, + operation, + onChanged, + onClose, +}: { + namespace: string + credential: Credential + operation: CredentialOperation + onChanged: () => void + onClose: () => void +}) { + const client = useK8sClient() + const [phase, setPhase] = useState({ name: "confirm" }) + const user = credential.spec?.user ?? credential.metadata.name + const verb = operation === "mint" ? "Generate password" : "Revoke" + + const close = () => { + // Drop the password before the dialog goes away, not only on unmount. + setPhase({ name: "confirm" }) + onClose() + } + + const run = async () => { + setPhase({ name: "running" }) + try { + const result = await runCredentialOperation(client, namespace, credential, operation) + onChanged() + if (operation === "mint" && result?.status?.password) { + setPhase({ name: "minted", username: result.status.username ?? user, password: result.status.password }) + } else { + onClose() + } + } catch (error) { + if (error instanceof K8sApiError && error.status === 409) onChanged() + setPhase({ name: "failed", message: failureMessage(error, operation) }) + } + } + + return ( + { if (!open && phase.name !== "running") close() }} + > + + + + {phase.name === "minted" ? ( + <> + New password for {user} + +
+ +
+ + ) : ( + <> + {verb} for {user}? + + {operation === "mint" + ? "A new password is generated and shown to you once. The current password stops working for every client that uses it." + : "The current password stops working for every client that uses it, and nobody holds a working one until a new password is generated."} + + {phase.name === "failed" && ( +

{phase.message}

+ )} +
+ + {phase.name !== "failed" && ( + + )} +
+ + )} +
+
+
+ ) +} diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialsTab.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialsTab.test.tsx new file mode 100644 index 000000000..a745cc14b --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialsTab.test.tsx @@ -0,0 +1,187 @@ +import { afterEach, describe, expect, it, vi } from "vitest" +import { fireEvent, screen, waitFor, within } from "@testing-library/react" +import { K8sApiError, K8sClient } from "@cozystack/k8s-client" +import type { ApplicationDefinition, ApplicationInstance } from "@cozystack/types" +import { renderWithK8sProvider } from "../../test-utils/render.tsx" +import { CredentialsTab } from "./CredentialsTab.tsx" +import { useApplicationCredentials, type Credential } from "./use-app-credentials.ts" + +const namespace = "tenant-test" +const secret = "s3cr3t-Pa55w0rd-only-once" +const ad: ApplicationDefinition = { + apiVersion: "cozystack.io/v1alpha1", kind: "ApplicationDefinition", + metadata: { name: "postgres" }, + spec: { application: { kind: "Postgres", plural: "postgreses", singular: "postgres", openAPISchema: "{}" } }, +} +const instance: ApplicationInstance = { + apiVersion: "apps.cozystack.io/v1alpha1", kind: "Postgres", + metadata: { name: "demo", namespace }, +} + +function credential(user: string, password: NonNullable["password"], extra: Partial = {}): Credential { + return { + apiVersion: "core.cozystack.io/v1alpha1", kind: "Credential", + metadata: { name: `demo.${user}`, namespace, resourceVersion: `rv-${user}` }, + spec: { application: { apiGroup: "apps.cozystack.io", kind: "Postgres", name: "demo" }, user }, + status: { password, history: [{ operation: "Create", at: "2026-11-20T10:00:00Z", by: "system:serviceaccount:cozy-system:cozystack-api" }] }, + ...extra, + } +} + +const items: Credential[] = [ + credential("alice", { origin: "Minted", at: "2026-11-20T12:00:00Z", by: "jane@example.org" }), + credential("bob", { origin: "Migrated" }), + credential("carol", { origin: "NotIssued" }), + credential("dave", { origin: "Revoked", at: "2026-11-20T13:00:00Z", by: "jane@example.org" }), + credential("eve", { origin: "Migrated" }, { + metadata: { name: "other.eve", namespace }, + spec: { application: { apiGroup: "apps.cozystack.io", kind: "Postgres", name: "other" }, user: "eve" }, + }), +] + +function Credentials() { + const result = useApplicationCredentials(ad, instance, namespace) + return { void result.refetch() }} /> +} + +function makeClient({ allowed = true, list = items }: { allowed?: boolean; list?: Credential[] } = {}) { + const client = new K8sClient() + vi.spyOn(client, "list").mockImplementation(async (group, _version, plural, ns) => { + expect([group, plural, ns]).toEqual(["core.cozystack.io", "credentials", namespace]) + return { apiVersion: "core.cozystack.io/v1alpha1", kind: "CredentialList", metadata: { resourceVersion: "1" }, items: list } + }) + vi.spyOn(client, "watch").mockReturnValue(() => {}) + vi.spyOn(client, "create").mockImplementation(async (_group, _version, _plural, body) => ({ + ...(body as object), status: { allowed }, + })) + return client +} + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +describe("application credentials", () => { + it("lists only this application's accounts with what each origin means", async () => { + renderWithK8sProvider(, { client: makeClient() }) + expect(await screen.findByText("alice")).toBeInTheDocument() + expect(screen.getByText(/Shown once to jane@example\.org at/)).toBeInTheDocument() + expect(screen.getByText(/password from before the conversion still works/)).toBeInTheDocument() + expect(screen.getByText(/Nobody holds a password yet/)).toBeInTheDocument() + expect(screen.getByText(/The password was revoked/)).toBeInTheDocument() + expect(screen.queryByText("eve")).not.toBeInTheDocument() + }) + + it("expands an account's history", async () => { + renderWithK8sProvider(, { client: makeClient({ list: [items[0]] }) }) + fireEvent.click(await screen.findByRole("button", { name: /History \(1\)/ })) + expect(screen.getByText("Created")).toBeInTheDocument() + expect(screen.getByText(/by the platform at/)).toBeInTheDocument() + }) + + it("hides the actions when the user may not mint or revoke", async () => { + const client = makeClient({ allowed: false }) + renderWithK8sProvider(, { client }) + expect(await screen.findByText("alice")).toBeInTheDocument() + await waitFor(() => expect(client.create).toHaveBeenCalledTimes(2)) + expect(client.create).toHaveBeenCalledWith("authorization.k8s.io", "v1", "selfsubjectaccessreviews", expect.objectContaining({ + spec: { resourceAttributes: { namespace, group: "core.cozystack.io", resource: "credentials", subresource: "mint", verb: "create" } }, + })) + expect(screen.queryByRole("button", { name: /Generate password/ })).not.toBeInTheDocument() + expect(screen.queryByRole("button", { name: /Revoke/ })).not.toBeInTheDocument() + }) + + it("shows a minted password once, with the precondition sent, and drops it on close", async () => { + const writeText = vi.fn().mockResolvedValue(undefined) + vi.stubGlobal("navigator", { clipboard: { writeText } }) + const client = makeClient() + const subresource = vi.spyOn(client, "subresource").mockResolvedValue({ + status: { username: "bob", password: secret, issuedAt: "2026-11-21T09:00:00Z" }, + }) + const { queryClient } = renderWithK8sProvider(, { client }) + fireEvent.click(await screen.findByRole("button", { name: "Generate password for bob" })) + const dialog = await screen.findByRole("dialog") + expect(dialog).toHaveTextContent("stops working for every client") + expect(subresource).not.toHaveBeenCalled() + + fireEvent.click(within(dialog).getByRole("button", { name: "Generate password" })) + expect(await screen.findByTestId("minted-password")).toHaveTextContent(secret) + expect(screen.getByText(/cannot be shown again/)).toBeInTheDocument() + expect(subresource).toHaveBeenCalledWith("core.cozystack.io", "v1alpha1", "credentials", "demo.bob", "mint", namespace, { + apiVersion: "core.cozystack.io/v1alpha1", + kind: "CredentialRequest", + spec: { preconditions: { resourceVersion: "rv-bob" } }, + }, "POST") + await waitFor(() => expect(client.list).toHaveBeenCalledTimes(2)) + + fireEvent.click(screen.getByRole("button", { name: "Copy password" })) + await waitFor(() => expect(writeText).toHaveBeenCalledWith(secret)) + + fireEvent.click(screen.getByRole("button", { name: "I have saved it, close" })) + await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()) + expect(document.body).not.toHaveTextContent(secret) + const cached = JSON.stringify([ + queryClient.getQueryCache().getAll().map((q) => q.state.data), + queryClient.getMutationCache().getAll().map((m) => m.state.data), + ]) + expect(cached).not.toContain(secret) + }) + + it("shows the server's conflict, refreshes the list and offers no blind retry", async () => { + const client = makeClient() + vi.spyOn(client, "subresource").mockRejectedValue( + new K8sApiError(409, { message: "credential demo.bob changed: password minted by john@example.org" }), + ) + renderWithK8sProvider(, { client }) + fireEvent.click(await screen.findByRole("button", { name: "Generate password for bob" })) + const dialog = await screen.findByRole("dialog") + fireEvent.click(within(dialog).getByRole("button", { name: "Generate password" })) + expect(await within(dialog).findByRole("alert")).toHaveTextContent("changed: password minted by john@example.org") + await waitFor(() => expect(client.list).toHaveBeenCalledTimes(2)) + expect(within(dialog).queryByRole("button", { name: "Generate password" })).not.toBeInTheDocument() + expect(screen.queryByTestId("minted-password")).not.toBeInTheDocument() + }) + + it("reports a denied action instead of failing silently", async () => { + const client = makeClient() + vi.spyOn(client, "subresource").mockRejectedValue(new K8sApiError(403, { message: "forbidden" })) + renderWithK8sProvider(, { client }) + fireEvent.click(await screen.findByRole("button", { name: "Revoke password for bob" })) + const dialog = await screen.findByRole("dialog") + fireEvent.click(within(dialog).getByRole("button", { name: "Revoke" })) + expect(await within(dialog).findByRole("alert")).toHaveTextContent("not allowed to revoke") + }) + + it("revokes without showing any secret", async () => { + const client = makeClient() + const subresource = vi.spyOn(client, "subresource").mockResolvedValue({ + status: { username: "alice", issuedAt: "2026-11-21T09:00:00Z" }, + }) + renderWithK8sProvider(, { client }) + fireEvent.click(await screen.findByRole("button", { name: "Revoke password for alice" })) + const dialog = await screen.findByRole("dialog") + expect(dialog).toHaveTextContent("stops working for every client") + fireEvent.click(within(dialog).getByRole("button", { name: "Revoke" })) + await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()) + expect(subresource).toHaveBeenCalledWith("core.cozystack.io", "v1alpha1", "credentials", "demo.alice", "revoke", namespace, + expect.objectContaining({ spec: { preconditions: { resourceVersion: "rv-alice" } } }), "POST") + expect(screen.queryByTestId("minted-password")).not.toBeInTheDocument() + }) + + it("offers no revoke where nobody holds a password", async () => { + renderWithK8sProvider(, { client: makeClient() }) + expect(await screen.findByRole("button", { name: "Generate password for carol" })).toBeInTheDocument() + expect(screen.queryByRole("button", { name: "Revoke password for carol" })).not.toBeInTheDocument() + expect(screen.queryByRole("button", { name: "Revoke password for dave" })).not.toBeInTheDocument() + }) + + it("treats a cluster without the Credential API as having no accounts", async () => { + const client = makeClient() + vi.mocked(client.list).mockRejectedValue(new K8sApiError(404, "not found")) + renderWithK8sProvider(, { client }) + expect(await screen.findByText("No accounts yet.")).toBeInTheDocument() + expect(screen.queryByRole("alert")).not.toBeInTheDocument() + }) +}) diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialsTab.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialsTab.tsx new file mode 100644 index 000000000..3820e9e82 --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/CredentialsTab.tsx @@ -0,0 +1,151 @@ +import { useState } from "react" +import { ChevronDown, ChevronRight } from "lucide-react" +import { useSelfSubjectAccessReview } from "@cozystack/k8s-client" +import { Button, Section, Spinner } from "@cozystack/ui" +import { CredentialActionDialog } from "./CredentialActionDialog.tsx" +import { actorLabel, formatTime, operationLabel, originExplanation, originLabel } from "./credential-origin.ts" +import { + CREDENTIALS_GROUP, + type Credential, + type CredentialOperation, +} from "./use-app-credentials.ts" + +// Fail closed: while the review loads or errors the actions stay hidden. +function useOperationAllowed(namespace: string, operation: CredentialOperation): boolean { + const review = useSelfSubjectAccessReview({ + resourceAttributes: { + namespace, + group: CREDENTIALS_GROUP, + resource: "credentials", + subresource: operation, + verb: "create", + }, + }) + return !review.isLoading && !review.error && review.allowed +} + +function History({ credential }: { credential: Credential }) { + const [open, setOpen] = useState(false) + const entries = credential.status?.history ?? [] + if (entries.length === 0) return null + return ( +
+ + {open && ( +
    + {entries.map((entry, i) => ( +
  • + {operationLabel(entry.operation)} by {actorLabel(entry.by)} at {formatTime(entry.at)} +
  • + ))} +
+ )} +
+ ) +} + +function CredentialRow({ + credential, + canMint, + canRevoke, + onAction, +}: { + credential: Credential + canMint: boolean + canRevoke: boolean + onAction: (operation: CredentialOperation) => void +}) { + const user = credential.spec?.user ?? credential.metadata.name + const password = credential.status?.password + return ( +
+
+
+

{user} {originLabel(credential)}

+

{originExplanation(credential)}

+

+ Last change: {formatTime(password?.at)}{password?.by ? ` by ${actorLabel(password.by)}` : ""} +

+
+ {(canMint || canRevoke) && ( +
+ {canMint && ( + + )} + {canRevoke && password?.origin !== "Revoked" && password?.origin !== "NotIssued" && ( + + )} +
+ )} +
+ +
+ ) +} + +export function CredentialsTab({ + namespace, + credentials, + isLoading, + error, + onChanged, +}: { + namespace: string + credentials: Credential[] + isLoading: boolean + error: Error | null + onChanged: () => void +}) { + const canMint = useOperationAllowed(namespace, "mint") + const canRevoke = useOperationAllowed(namespace, "revoke") + const [action, setAction] = useState<{ credential: Credential; operation: CredentialOperation } | null>(null) + + return ( +
+
+ {error ?

{error.message}

+ : isLoading ?
Loading…
+ : credentials.length === 0 ?

No accounts yet.

+ : ( +
+ {credentials.map((credential) => ( + setAction({ credential, operation })} + /> + ))} +
+ )} +
+ {action && ( + setAction(null)} + /> + )} +
+ ) +} diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/credential-origin.test.ts b/packages/system/dashboard/images/console/apps/console/src/routes/detail/credential-origin.test.ts new file mode 100644 index 000000000..cb3916c55 --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/credential-origin.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest" + +import { actorLabel, formatTime, operationLabel, originLabel } from "./credential-origin.ts" +import type { Credential } from "./use-app-credentials.ts" + +describe("credential labels", () => { + it("names a mint the way the button does", () => { + expect(operationLabel("Mint")).toBe("Generated") + expect(operationLabel("Migrate")).toBe("Migrated") + expect(operationLabel("Revoke")).toBe("Revoked") + expect(originLabel({ status: { password: { origin: "Minted" } } } as Credential)).toBe("Generated") + }) + + it("shows the platform's service accounts as the platform", () => { + expect(actorLabel("system:serviceaccount:cozy-system:cozystack-migration-hook")).toBe("the platform") + expect(actorLabel("system:serviceaccount:tenant-foo:ci")).toBe("system:serviceaccount:tenant-foo:ci") + expect(actorLabel("jane@example.org")).toBe("jane@example.org") + expect(actorLabel(undefined)).toBe("unknown") + }) + + it("names the time zone", () => { + expect(formatTime("2026-11-20T12:00:00Z")).toMatch(/[A-Z]{2,}|GMT|UTC/) + }) +}) diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/credential-origin.ts b/packages/system/dashboard/images/console/apps/console/src/routes/detail/credential-origin.ts new file mode 100644 index 000000000..b04e7b883 --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/credential-origin.ts @@ -0,0 +1,55 @@ +import type { Credential } from "./use-app-credentials.ts" + +export function formatTime(at: string | undefined): string { + if (!at) return "—" + const date = new Date(at) + return Number.isNaN(date.getTime()) ? at : date.toLocaleString(undefined, { timeZoneName: "short" }) +} + +// The platform's own service accounts seed, migrate and adopt accounts; a +// tenant reads them as one actor rather than as Kubernetes identities. +const platformActorPrefix = "system:serviceaccount:cozy-system:" + +export function actorLabel(by: string | undefined): string { + if (!by) return "unknown" + return by.startsWith(platformActorPrefix) ? "the platform" : by +} + +// The API names the operations after its subresources; the console calls a +// mint "Generate password", so the history uses the same word. +export function operationLabel(operation: string): string { + switch (operation) { + case "Create": return "Created" + case "Migrate": return "Migrated" + case "Mint": return "Generated" + case "Revoke": return "Revoked" + default: return operation + } +} + +export function originLabel(credential: Credential): string { + const origin = credential.status?.password?.origin + switch (origin) { + case "NotIssued": return "Not issued" + case "Migrated": return "Migrated" + case "Minted": return "Generated" + case "Revoked": return "Revoked" + default: return "Unknown" + } +} + +export function originExplanation(credential: Credential): string { + const password = credential.status?.password + switch (password?.origin) { + case "NotIssued": + return "Nobody holds a password yet. Generate one to log in." + case "Migrated": + return "The password from before the conversion still works. Replace it by generating a new one." + case "Minted": + return `Shown once to ${actorLabel(password.by)} at ${formatTime(password.at)}.` + case "Revoked": + return "The password was revoked. Nobody holds a working one until a new one is generated." + default: + return "The account has no recorded password state yet." + } +} diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/use-app-credentials.ts b/packages/system/dashboard/images/console/apps/console/src/routes/detail/use-app-credentials.ts new file mode 100644 index 000000000..9c476b3a9 --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/use-app-credentials.ts @@ -0,0 +1,91 @@ +import { K8sApiError, useK8sList, type K8sClient, type K8sResource } from "@cozystack/k8s-client" +import { APPS_GROUP, type ApplicationDefinition, type ApplicationInstance } from "@cozystack/types" + +export const CREDENTIALS_GROUP = "core.cozystack.io" +export const CREDENTIALS_VERSION = "v1alpha1" + +export type CredentialOrigin = "NotIssued" | "Migrated" | "Minted" | "Revoked" +export type CredentialOperation = "mint" | "revoke" + +export interface CredentialHistoryEntry { + operation: string + at: string + by: string +} + +export type Credential = K8sResource< + { + application: { apiGroup: string; kind: string; name: string } + user: string + }, + { + password?: { origin?: CredentialOrigin; at?: string; by?: string } + history?: CredentialHistoryEntry[] + } +> + +export interface CredentialRequestResult { + status?: { username?: string; password?: string; issuedAt?: string } +} + +// The Credential API serves no watch, so the list is refreshed on a timer. +const POLL_INTERVAL_MS = 10_000 + +export function useApplicationCredentials( + ad: ApplicationDefinition | undefined, + instance: ApplicationInstance | undefined, + namespace: string | undefined, +) { + const kind = ad?.spec?.application.kind + const name = instance?.metadata.name + const query = useK8sList( + { apiGroup: CREDENTIALS_GROUP, apiVersion: CREDENTIALS_VERSION, plural: "credentials", namespace }, + { + enabled: !!namespace && !!kind && !!name, + watch: false, + refetchInterval: POLL_INTERVAL_MS, + retry: false, + }, + ) + // 404: the cluster predates the Credential API; 403: the user cannot list it. + const unavailable = query.error instanceof K8sApiError && [403, 404].includes(query.error.status) + const credentials = (query.data?.items ?? []) + .filter((c) => { + const app = c.spec?.application + return app?.apiGroup === APPS_GROUP && app.kind === kind && app.name === name + }) + .sort((a, b) => (a.spec?.user ?? "").localeCompare(b.spec?.user ?? "")) + return { + credentials: unavailable ? [] : credentials, + isLoading: query.isLoading, + error: unavailable ? null : query.error, + refetch: query.refetch, + } +} + +/** + * Mint or revoke through the Credential's subresource. Called on the client + * directly rather than through a mutation hook: React Query keeps a mutation's + * result in its cache, and a minted password must not outlive the dialog. + */ +export function runCredentialOperation( + client: K8sClient, + namespace: string, + credential: Credential, + operation: CredentialOperation, +): Promise { + return client.subresource( + CREDENTIALS_GROUP, + CREDENTIALS_VERSION, + "credentials", + credential.metadata.name, + operation, + namespace, + { + apiVersion: `${CREDENTIALS_GROUP}/${CREDENTIALS_VERSION}`, + kind: "CredentialRequest", + spec: { preconditions: { resourceVersion: credential.metadata.resourceVersion ?? "" } }, + }, + "POST", + ) +}