From 07a08196046bfbcfb07b1ac76a61cb378fc04784 Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Wed, 14 Oct 2026 11:58:49 +0200 Subject: [PATCH 1/3] fix(lineage-webhook): keep an explicit tenantresource false The webhook computes the tenantresource verdict from the ApplicationDefinition selectors on first admission and copies it over whatever label the chart rendered, so a chart cannot take a Secret the definition still selects off the tenantsecrets projection. The credentials conversion in design-proposals/user-secrets-api needs exactly that during its migration window: the converted chart renders the platform-only credentials Secret with tenantresource false while the old definition still selects the name. A rendered false is now kept; a rendered true is still replaced by the computed verdict, so the object can only narrow what the definition grants, never widen it. Assisted-by: LLM Signed-off-by: Timofei Larkin (cherry picked from commit 7b214464ee88e6ae67782cc8b114ebe4cd33660d) Signed-off-by: cozystack-ci[bot] <274107086+cozystack-ci[bot]@users.noreply.github.com> --- internal/lineagecontrollerwebhook/webhook.go | 19 ++- .../webhook_tenantresource_test.go | 115 ++++++++++++++++++ 2 files changed, 128 insertions(+), 6 deletions(-) create mode 100644 internal/lineagecontrollerwebhook/webhook_tenantresource_test.go diff --git a/internal/lineagecontrollerwebhook/webhook.go b/internal/lineagecontrollerwebhook/webhook.go index ea8b0d01b..d2ef5f938 100644 --- a/internal/lineagecontrollerwebhook/webhook.go +++ b/internal/lineagecontrollerwebhook/webhook.go @@ -193,12 +193,19 @@ func (h *LineageControllerWebhook) computeLabels(ctx context.Context, obj *unstr crd := cfg.appCRDMap[appRef{gv.Group, owner.GetKind()}] resourceSelectors := h.getResourceSelectors(obj.GroupVersionKind().GroupKind(), crd) - labels[corev1alpha1.TenantResourceLabelKey] = func(b bool) string { - if b { - return corev1alpha1.TenantResourceLabelValue - } - return "false" - }(matchResourceToExcludeInclude(ctx, obj.GetName(), templateLabels, obj.GetLabels(), resourceSelectors)) + selected := matchResourceToExcludeInclude(ctx, obj.GetName(), templateLabels, obj.GetLabels(), resourceSelectors) + // The verdict can be narrowed by the object and never widened: a chart that + // renders tenantresource "false" keeps it even where the definition selects + // the name, while a chart-set "true" is replaced by the computed verdict. + // This is what lets a chart take a Secret the definition still selects off + // the tenantsecrets projection while the definition catches up. + if obj.GetLabels()[corev1alpha1.TenantResourceLabelKey] == "false" { + selected = false + } + labels[corev1alpha1.TenantResourceLabelKey] = "false" + if selected { + labels[corev1alpha1.TenantResourceLabelKey] = corev1alpha1.TenantResourceLabelValue + } return labels, nil } diff --git a/internal/lineagecontrollerwebhook/webhook_tenantresource_test.go b/internal/lineagecontrollerwebhook/webhook_tenantresource_test.go new file mode 100644 index 000000000..4fe9f6af8 --- /dev/null +++ b/internal/lineagecontrollerwebhook/webhook_tenantresource_test.go @@ -0,0 +1,115 @@ +package lineagecontrollerwebhook + +import ( + "context" + "encoding/json" + "strings" + "testing" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +// The tenantresource verdict is the definition's, but an object may narrow it +// and never widen it: a rendered "false" survives a selector that matches the +// name, a rendered "true" does not survive one that does not. +func TestHandle_TenantResourceLabelNarrowsOnly(t *testing.T) { + tenantResourcePath := "/metadata/labels/" + strings.ReplaceAll(corev1alpha1.TenantResourceLabelKey, "/", "~1") + + tests := []struct { + name string + secret string + rendered string + // want is the value the label must hold once the patch is applied; + // "" means the response must not touch the label at all. + want string + }{ + { + name: "a rendered false is kept where the definition selects the name", + secret: "harbor-demo-credentials", + rendered: "false", + want: "", + }, + { + name: "a rendered true is overwritten where the definition does not select the name", + secret: "harbor-demo-other", + rendered: "true", + want: "false", + }, + { + name: "no rendered label gets the definition's verdict", + secret: "harbor-demo-credentials", + rendered: "", + want: "true", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + w := newHandleTestWebhook(t) + w.config.Store(&runtimeConfig{appCRDMap: map[appRef]*cozyv1alpha1.ApplicationDefinition{ + {"apps.cozystack.io", "Harbor"}: {Spec: cozyv1alpha1.ApplicationDefinitionSpec{ + Application: cozyv1alpha1.ApplicationDefinitionApplication{Kind: "Harbor"}, + Secrets: cozyv1alpha1.ApplicationDefinitionResources{ + Include: []*cozyv1alpha1.ApplicationDefinitionResourceSelector{ + {ResourceNames: []string{"{{ .kind }}-{{ .name }}-credentials"}}, + }, + }, + }}, + }}) + + labels := map[string]string{"helm.toolkit.fluxcd.io/name": "harbor-demo"} + if tt.rendered != "" { + labels[corev1alpha1.TenantResourceLabelKey] = tt.rendered + } + obj := &unstructured.Unstructured{} + obj.SetAPIVersion("v1") + obj.SetKind("Secret") + obj.SetNamespace("tenant-demo") + obj.SetName(tt.secret) + obj.SetLabels(labels) + raw, err := json.Marshal(obj) + if err != nil { + t.Fatalf("marshal object: %v", err) + } + + resp := w.Handle(context.Background(), admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{ + Kind: metav1.GroupVersionKind{Version: "v1", Kind: "Secret"}, + Namespace: "tenant-demo", + Name: tt.secret, + Operation: admissionv1.Create, + Object: runtime.RawExtension{Raw: raw}, + }}) + if !resp.Allowed { + t.Fatalf("expected allowed response, got %+v", resp.Result) + } + + var got string + var touched bool + for _, p := range resp.Patches { + if p.Path != tenantResourcePath { + continue + } + touched = true + v, ok := p.Value.(string) + if !ok { + t.Fatalf("patch %s carries %T, want string", p.Path, p.Value) + } + got = v + } + switch { + case tt.want == "" && touched: + t.Errorf("expected the label untouched, got patch value %q", got) + case tt.want != "" && !touched: + t.Errorf("expected a patch setting the label to %q, got none", tt.want) + case tt.want != "" && got != tt.want: + t.Errorf("label patched to %q, want %q", got, tt.want) + } + }) + } +} From 84e68279f17491618c4aa04caa05096e9ec8edd6 Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Mon, 26 Oct 2026 10:51:43 +0100 Subject: [PATCH 2/3] docs(lineage-webhook): cut the rationale from the verdict comment Comments carry the mechanism, not the reason the change was made; the reason is in the design doc and the PR. Assisted-by: LLM Signed-off-by: Timofei Larkin (cherry picked from commit d687e73fd40d455868fc32fd904112b10e4cb6de) Signed-off-by: cozystack-ci[bot] <274107086+cozystack-ci[bot]@users.noreply.github.com> --- internal/lineagecontrollerwebhook/webhook.go | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/internal/lineagecontrollerwebhook/webhook.go b/internal/lineagecontrollerwebhook/webhook.go index d2ef5f938..a98735da3 100644 --- a/internal/lineagecontrollerwebhook/webhook.go +++ b/internal/lineagecontrollerwebhook/webhook.go @@ -194,11 +194,9 @@ func (h *LineageControllerWebhook) computeLabels(ctx context.Context, obj *unstr resourceSelectors := h.getResourceSelectors(obj.GroupVersionKind().GroupKind(), crd) selected := matchResourceToExcludeInclude(ctx, obj.GetName(), templateLabels, obj.GetLabels(), resourceSelectors) - // The verdict can be narrowed by the object and never widened: a chart that - // renders tenantresource "false" keeps it even where the definition selects - // the name, while a chart-set "true" is replaced by the computed verdict. - // This is what lets a chart take a Secret the definition still selects off - // the tenantsecrets projection while the definition catches up. + // The object may narrow the verdict and never widen it: a rendered "false" + // is kept even where the definition selects the name, a rendered "true" is + // replaced by the computed verdict. if obj.GetLabels()[corev1alpha1.TenantResourceLabelKey] == "false" { selected = false } From 5f025e9d807a3d6aae4cb44cac4b5355d4dd6837 Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Tue, 27 Oct 2026 16:14:35 +0100 Subject: [PATCH 3/3] fix(lineage-webhook): keep a rendered false only on create The cacert controller re-runs admission after a selector change by dropping managed-by-cozystack and keeping the other labels, so the UPDATE carries the "false" this webhook wrote on an earlier admission. Reading that as the chart's narrowing froze the old verdict: a projection, once revoked, could not be granted again. The chart's narrowing only matters on CREATE, since an existing Secret already carries managed-by-cozystack and skips the webhook. Assisted-by: LLM Signed-off-by: Timofei Larkin (cherry picked from commit 730fd5ebf52aaa0e493a43904f20e1f11e134cc7) Signed-off-by: cozystack-ci[bot] <274107086+cozystack-ci[bot]@users.noreply.github.com> --- internal/lineagecontrollerwebhook/webhook.go | 16 ++++--- .../webhook_tenantresource_test.go | 43 ++++++++++++++++--- 2 files changed, 48 insertions(+), 11 deletions(-) diff --git a/internal/lineagecontrollerwebhook/webhook.go b/internal/lineagecontrollerwebhook/webhook.go index a98735da3..b6e996275 100644 --- a/internal/lineagecontrollerwebhook/webhook.go +++ b/internal/lineagecontrollerwebhook/webhook.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/cozystack/cozystack/pkg/lineage" + admissionv1 "k8s.io/api/admission/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -123,7 +124,7 @@ func (h *LineageControllerWebhook) Handle(ctx context.Context, req admission.Req logger.Error(err, "error computing lineage labels") return admission.Errored(500, fmt.Errorf("error computing lineage labels: %w", err)) } - labels, err := h.computeLabels(ctx, obj, owner) + labels, err := h.computeLabels(ctx, obj, owner, req.Operation) if err != nil { logger.Error(err, "error computing lineage labels") return admission.Errored(500, fmt.Errorf("error computing lineage labels: %w", err)) @@ -159,7 +160,7 @@ func (h *LineageControllerWebhook) getOwner(ctx context.Context, o *unstructured return obj, err } -func (h *LineageControllerWebhook) computeLabels(ctx context.Context, obj *unstructured.Unstructured, owner *unstructured.Unstructured) (map[string]string, error) { +func (h *LineageControllerWebhook) computeLabels(ctx context.Context, obj *unstructured.Unstructured, owner *unstructured.Unstructured, op admissionv1.Operation) (map[string]string, error) { if owner == nil { return nil, nil } @@ -194,10 +195,13 @@ func (h *LineageControllerWebhook) computeLabels(ctx context.Context, obj *unstr resourceSelectors := h.getResourceSelectors(obj.GroupVersionKind().GroupKind(), crd) selected := matchResourceToExcludeInclude(ctx, obj.GetName(), templateLabels, obj.GetLabels(), resourceSelectors) - // The object may narrow the verdict and never widen it: a rendered "false" - // is kept even where the definition selects the name, a rendered "true" is - // replaced by the computed verdict. - if obj.GetLabels()[corev1alpha1.TenantResourceLabelKey] == "false" { + // On CREATE the object may narrow the verdict and never widen it: a + // rendered "false" is kept even where the definition selects the name, a + // rendered "true" is replaced. Only on CREATE: a re-admission (UPDATE with + // managed-by-cozystack dropped, as the cacert controller does on a selector + // change) carries the "false" this webhook wrote earlier, and keeping it + // would block a grant. + if op == admissionv1.Create && obj.GetLabels()[corev1alpha1.TenantResourceLabelKey] == "false" { selected = false } labels[corev1alpha1.TenantResourceLabelKey] = "false" diff --git a/internal/lineagecontrollerwebhook/webhook_tenantresource_test.go b/internal/lineagecontrollerwebhook/webhook_tenantresource_test.go index 4fe9f6af8..32d218715 100644 --- a/internal/lineagecontrollerwebhook/webhook_tenantresource_test.go +++ b/internal/lineagecontrollerwebhook/webhook_tenantresource_test.go @@ -16,13 +16,15 @@ import ( ) // The tenantresource verdict is the definition's, but an object may narrow it -// and never widen it: a rendered "false" survives a selector that matches the -// name, a rendered "true" does not survive one that does not. +// on CREATE and never widen it: a rendered "false" survives a selector that +// matches the name, a rendered "true" does not survive one that does not. A +// re-admission UPDATE gets the definition's verdict whatever the label says. func TestHandle_TenantResourceLabelNarrowsOnly(t *testing.T) { tenantResourcePath := "/metadata/labels/" + strings.ReplaceAll(corev1alpha1.TenantResourceLabelKey, "/", "~1") tests := []struct { name string + op admissionv1.Operation secret string rendered string // want is the value the label must hold once the patch is applied; @@ -31,22 +33,41 @@ func TestHandle_TenantResourceLabelNarrowsOnly(t *testing.T) { }{ { name: "a rendered false is kept where the definition selects the name", + op: admissionv1.Create, secret: "harbor-demo-credentials", rendered: "false", want: "", }, { name: "a rendered true is overwritten where the definition does not select the name", + op: admissionv1.Create, secret: "harbor-demo-other", rendered: "true", want: "false", }, { name: "no rendered label gets the definition's verdict", + op: admissionv1.Create, secret: "harbor-demo-credentials", rendered: "", want: "true", }, + { + // The cacert controller's re-admission after a selector change: + // managed-by-cozystack dropped, the old verdict still on the object. + name: "a re-admission grants where the definition now selects the name", + op: admissionv1.Update, + secret: "harbor-demo-credentials", + rendered: "false", + want: "true", + }, + { + name: "a re-admission revokes where the definition no longer selects the name", + op: admissionv1.Update, + secret: "harbor-demo-other", + rendered: "true", + want: "false", + }, } for _, tt := range tests { @@ -78,13 +99,25 @@ func TestHandle_TenantResourceLabelNarrowsOnly(t *testing.T) { t.Fatalf("marshal object: %v", err) } - resp := w.Handle(context.Background(), admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{ + req := admissionv1.AdmissionRequest{ Kind: metav1.GroupVersionKind{Version: "v1", Kind: "Secret"}, Namespace: "tenant-demo", Name: tt.secret, - Operation: admissionv1.Create, + Operation: tt.op, Object: runtime.RawExtension{Raw: raw}, - }}) + } + if tt.op == admissionv1.Update { + old := obj.DeepCopy() + oldLabels := old.GetLabels() + oldLabels[ManagedObjectKey] = "true" + old.SetLabels(oldLabels) + oldRaw, err := json.Marshal(old) + if err != nil { + t.Fatalf("marshal old object: %v", err) + } + req.OldObject = runtime.RawExtension{Raw: oldRaw} + } + resp := w.Handle(context.Background(), admission.Request{AdmissionRequest: req}) if !resp.Allowed { t.Fatalf("expected allowed response, got %+v", resp.Result) }