fix(lineage-webhook): keep an explicit tenantresource false (#4920)

## What this PR does

Lets a chart narrow the lineage webhook's
`internal.cozystack.io/tenantresource` verdict without being able to
widen it. The webhook computes the verdict from the
ApplicationDefinition's `secrets` selectors on first admission and
copied it over whatever label the chart rendered, so a Secret the
definition still selected was projected through
`core.cozystack.io/tenantsecrets` whatever the chart said. A `"false"`
rendered on a Secret the webhook admits for the first time (CREATE) is
now kept; a rendered `"true"` is still replaced by the computed verdict.
A re-admission (UPDATE with `managed-by-cozystack` dropped, which the
cacert controller does on a selector change) still gets the definition's
verdict, because the `"false"` it carries is the one this webhook wrote
earlier.

This is rollout step 2 of the accepted [user secrets API
proposal](https://github.com/cozystack/community/blob/main/design-proposals/user-secrets-api/README.md):
during a kind's conversion the converted chart renders the platform-only
`<release>-credentials` Secret with `tenantresource: "false"` while the
old definition may still select the name, and the label is what keeps
that Secret off the projection in the window. It ships on its own
because nothing else depends on it and the conversions do.

Behaviour otherwise unchanged: an object with no rendered label gets the
definition's verdict as before, and the re-admission short-circuit on
`managed-by-cozystack` is untouched.

Covered by a handler test: on CREATE, a rendered `false` kept where the
selector matches, a rendered `true` overwritten where it does not, and
no rendered label taking the verdict; on a re-admission UPDATE, a grant
where the selector now matches and a revoke where it no longer does.

### Screenshots

No UI change.

### Downstream repositories

Walked the trigger map against the diff: two files under
`internal/lineagecontrollerwebhook`, no CRD, no package, no chart, no
values, no `hack/` change. The ApplicationDefinition's selector
semantics gain one exception, but the website's ApplicationDefinition
page does not describe the projection verdict at that depth, so there is
nothing there to update.

- [x] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack)
- follow-up:
- [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up:
- [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up:
- [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) -
follow-up:
- [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) -
follow-up:
- [ ]
[cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server)
- follow-up:
- [ ]
[cozystack/external-apps-example](https://github.com/cozystack/external-apps-example)
- follow-up:
- [ ] [cozystack/examples](https://github.com/cozystack/examples) -
follow-up:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
fix(lineage-webhook): a Secret created with `internal.cozystack.io/tenantresource: "false"` keeps that label even where its ApplicationDefinition selects the name, so a chart can take a Secret off the tenantsecrets projection; a rendered `"true"` is still overwritten by the definition's verdict.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* On resource creation, an existing `false` tenant-resource label is
preserved even when the configured selector matches. Otherwise, the
label reflects the selector’s verdict. On updates, the label is set
according to the selector.
* **Tests**
* Added coverage for tenant-resource label behavior on creation and
updates, including existing and missing labels.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Backported-from: 65cb73e380
This commit is contained in:
Myasnikov Daniil committed 2026-11-25 09:58:12 +00:00
commit acdca8d971
2 files changed
+165 -8

No files matched your search

+17 -8
View File
@@ -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
}
@@ -193,12 +194,20 @@ 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)
// 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"
if selected {
labels[corev1alpha1.TenantResourceLabelKey] = corev1alpha1.TenantResourceLabelValue
}
return labels, nil
}
@@ -0,0 +1,148 @@
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
// 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;
// "" means the response must not touch the label at all.
want string
}{
{
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 {
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)
}
req := admissionv1.AdmissionRequest{
Kind: metav1.GroupVersionKind{Version: "v1", Kind: "Secret"},
Namespace: "tenant-demo",
Name: tt.secret,
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)
}
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)
}
})
}
}