From e8fef61fa1585e461e02544a592aa322cb153d4f Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Wed, 4 Nov 2026 19:13:55 +0300 Subject: [PATCH 1/8] fix(backups): re-render the default backup objects when the S3 endpoint changes The S3 endpoint the platform backups use is copied twice and neither copy is refreshed. The COSI sidecar writes BucketInfo once per BucketAccess, so the credentials Secret rendered from it keeps its endpoint, and the Velero BSL and the default Strategy CRs keep whatever endpoint the last render of backupstrategy-controller saw. The default objects gate only acted on objects that were missing, so after a publishing.host change every backup kept going to the old host with nothing reporting it. The gate now also forces a render when a copy is stale: the bucket's -system release when the credentials Secret's endpoint differs from the COSI Secret it is rendered from, and backupstrategy-controller when the endpoint an object was rendered with differs from the credentials Secret's. That endpoint sits at a different path in every kind, in some only as a bare host, so the chart stamps the rendered value on each object as backups.cozystack.io/endpoint and the gate compares that. Objects rendered before the annotation existed count as stale until one forced render has gone through, which stamps it. The COSI Secret itself still holds the endpoint the BucketAccess was granted with; it follows a host change only once the BucketAccess is re-granted. Assisted-by: LLM Signed-off-by: Alexey Artamonov (cherry picked from commit cd91138f3327a4886c72b9e8a35b4e54c06abad7) Signed-off-by: Myasnikov Daniil --- cmd/backupstrategy-controller/main.go | 1 + hack/backupstrategy-crd-gate.bats | 36 ++ .../backupcontroller/default_objects_gate.go | 163 ++++++- .../default_objects_gate_test.go | 401 +++++++++++++++++- .../templates/_helpers.tpl | 7 +- .../templates/deployment.yaml | 7 + .../templates/strategy-altinity-default.yaml | 2 + .../templates/strategy-cnpg-default.yaml | 2 + .../templates/strategy-etcd-default.yaml | 2 + .../strategy-foundationdb-default.yaml | 2 + .../templates/strategy-kafka-default.yaml | 2 + .../templates/strategy-mariadb-default.yaml | 2 + .../templates/strategy-mongodb-default.yaml | 2 + .../templates/strategy-rabbitmq-default.yaml | 2 + .../templates/strategy-redis-default.yaml | 2 + .../strategy-velero-vmdisk-default.yaml | 2 + .../strategy-velero-vminstance-default.yaml | 2 + .../templates/velero-bsl.yaml | 2 + .../tests/default_objects_gate_test.yaml | 60 +++ .../backupstrategy-controller/values.yaml | 11 +- .../bucket/templates/user-credentials.yaml | 4 +- 21 files changed, 678 insertions(+), 36 deletions(-) diff --git a/cmd/backupstrategy-controller/main.go b/cmd/backupstrategy-controller/main.go index 625d79820..119ae3007 100644 --- a/cmd/backupstrategy-controller/main.go +++ b/cmd/backupstrategy-controller/main.go @@ -243,6 +243,7 @@ func main() { Namespace: os.Getenv("BACKUP_CREDENTIALS_HELMRELEASE_NAMESPACE"), Name: os.Getenv("BACKUP_CREDENTIALS_HELMRELEASE_NAME"), }, + CredentialsCOSISecretName: os.Getenv("BACKUP_CREDENTIALS_COSI_SECRET_NAME"), } if err := gate.SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to add DefaultObjectsGate runnable") diff --git a/hack/backupstrategy-crd-gate.bats b/hack/backupstrategy-crd-gate.bats index b4ad482a0..0f68a1ca4 100644 --- a/hack/backupstrategy-crd-gate.bats +++ b/hack/backupstrategy-crd-gate.bats @@ -133,3 +133,39 @@ $tpl: $obj does not gate on crdEstablished for $crd" rm -rf "$tmp" } + +# The controller's DefaultObjectsGate tells an object rendered with a stale S3 +# endpoint (publishing.host changed after the render) by the +# backups.cozystack.io/endpoint annotation, because the endpoint itself sits at +# a different path in every kind. An object the chart renders without it is +# forced once and then never compared again, so a new template that forgets it +# would silently keep a stale endpoint. +@test "every rendered Strategy CR and the Velero BSL carry the rendered endpoint annotation" { + tmp=$(mktemp -d) + + helm template t "$CHART" -n cozy-backup-controller \ + --set backupStorage.bucketNameOverride=ext-bucket \ + --set backupStorage.endpoint=https://s3.example.org \ + --output-dir "$tmp/open" >/dev/null + + objs=$(find "$tmp/open" -name '*.yaml' | sort | while read -r f; do + yq eval-all "select((.apiVersion // \"\" | test(\"^${STRATEGY_API}\")) or .kind == \"BackupStorageLocation\") | .kind + \"/\" + .metadata.name + \" \" + (.metadata.annotations[\"backups.cozystack.io/endpoint\"] // \"\")" "$f" \ + | sed "s#^#$(basename "$f") #" + done) + if ! echo "$objs" | grep -q " BackupStorageLocation/"; then + echo "render produced no BSL; nothing was checked for it" >&2 + false + fi + if ! echo "$objs" | grep -q " CNPG/"; then + echo "render produced no Strategy CR; nothing was checked" >&2 + false + fi + bad=$(echo "$objs" | awk '$3 != "https://s3.example.org"') + if [ -n "$bad" ]; then + echo "objects without the rendered endpoint in backups.cozystack.io/endpoint:" >&2 + echo "$bad" >&2 + false + fi + + rm -rf "$tmp" +} diff --git a/internal/backupcontroller/default_objects_gate.go b/internal/backupcontroller/default_objects_gate.go index 023682036..efcd970d5 100644 --- a/internal/backupcontroller/default_objects_gate.go +++ b/internal/backupcontroller/default_objects_gate.go @@ -2,10 +2,12 @@ package backupcontroller import ( "context" + "encoding/json" "errors" "fmt" "net/http" "sort" + "strings" "time" "github.com/go-logr/logr" @@ -91,6 +93,11 @@ const ( // same lookup-gated template as the Strategy CRs, so it belongs to the // same existence check. defaultBackupStorageLocationName = "cozy-default" + + // endpointAnnotation carries the S3 endpoint the chart rendered into the + // object. The endpoint itself sits at a different path in every kind, + // and in some only as a bare host, so the gate compares this instead. + endpointAnnotation = "backups.cozystack.io/endpoint" ) var backupStorageLocationGVR = schema.GroupVersionResource{ @@ -157,6 +164,14 @@ type DefaultObjectsGate struct { // then admin-managed and no release renders it, so there is nothing // to force. CredentialsHelmRelease types.NamespacedName + // CredentialsCOSISecretName is the Secret the COSI sidecar writes for the + // platform bucket's BucketAccess, in Config.SourceNamespace, from which + // CredentialsHelmRelease renders the credentials Secret. The sidecar + // writes it once per BucketAccess, so after a publishing.host change a + // re-granted BucketAccess carries the new endpoint while the credentials + // Secret keeps the old one; the gate compares the two. Empty disables + // the comparison. + CredentialsCOSISecretName string // VeleroNamespace is where the cozy-default BackupStorageLocation // lives. Empty skips the BSL check (velero.bslEnabled=false). VeleroNamespace string @@ -177,6 +192,11 @@ type DefaultObjectsGate struct { // MinForceInterval for no reason. lastForce time.Time lastCredentialsForce time.Time + // renderForced records that a forced render of HelmRelease went through. + // That render stamps endpointAnnotation on every object the chart + // renders, so from then on an object without it (one rendered by a chart + // that predates the annotation) is not counted as stale again. + renderForced bool } // errHelmReleaseSuspended reports that the target release has @@ -285,10 +305,10 @@ func (g *DefaultObjectsGate) checkAndLog(ctx context.Context, logger logr.Logger // The release named here is whichever one renders what is missing: // the credentials Secret comes from the bucket's -system // release, everything else from this chart's own. - logger.Info("forced a Helm upgrade to create missing default backup objects", + logger.Info("forced a Helm upgrade to create missing or stale default backup objects", "helmRelease", g.forcedReleaseFor(missing).String(), "missing", missing) case len(missing) > 0: - logger.Info("default backup objects still missing, no force issued on this tick", + logger.Info("default backup objects still missing or stale, no force issued on this tick", "helmRelease", g.forcedReleaseFor(missing).String(), "missing", missing, "minForceInterval", g.MinForceInterval.String()) default: @@ -302,7 +322,7 @@ func (g *DefaultObjectsGate) checkAndLog(ctx context.Context, logger logr.Logger // resolving the bucket name is a precondition for checking those at all. func (g *DefaultObjectsGate) forcedReleaseFor(missing []string) types.NamespacedName { credsKey := fmt.Sprintf("Secret/%s", g.Config.SourceSecretName) - if len(missing) == 1 && missing[0] == credsKey && g.CredentialsHelmRelease.Name != "" { + if len(missing) == 1 && (missing[0] == credsKey || strings.HasPrefix(missing[0], credsKey+" ")) && g.CredentialsHelmRelease.Name != "" { return g.CredentialsHelmRelease } return g.HelmRelease @@ -345,23 +365,95 @@ func (g *DefaultObjectsGate) Check(ctx context.Context) ([]string, bool, error) return g.reconcileCredentials(ctx) } + // The objects below are rendered from this Secret, so while it is stale + // they would only be re-rendered with the same stale endpoint. + stale, err := g.staleCredentials(ctx, src) + if err != nil { + defaultObjectsCheckErrors.WithLabelValues(g.BackupClassName).Inc() + return nil, false, err + } + if stale != "" { + return g.force(ctx, g.CredentialsHelmRelease, &g.lastCredentialsForce, []string{stale}) + } + backupClass := &backupsv1alpha1.BackupClass{} if err := g.Client.Get(ctx, client.ObjectKey{Name: g.BackupClassName}, backupClass); err != nil { defaultObjectsCheckErrors.WithLabelValues(g.BackupClassName).Inc() return nil, false, fmt.Errorf("get BackupClass %s: %w", g.BackupClassName, err) } - missing, err := g.missingObjects(ctx, backupClass) + // With provisionBucket=false (no bucket release) the chart renders + // backupStorage.endpoint rather than the Secret's, so the two may + // legitimately differ and there is nothing to compare. + want := "" + if g.CredentialsHelmRelease.Name != "" { + want = renderedEndpointFor(src.Data["endpoint"]) + } + state, err := g.inspectObjects(ctx, backupClass, want) if err != nil { defaultObjectsCheckErrors.WithLabelValues(g.BackupClassName).Inc() return nil, false, err } - defaultObjectsMissing.WithLabelValues(g.BackupClassName).Set(float64(len(missing))) - if len(missing) == 0 { + defaultObjectsMissing.WithLabelValues(g.BackupClassName).Set(float64(len(state.missing))) + needed := append(state.missing, state.stale...) + if len(needed) == 0 { return nil, false, nil } + sort.Strings(needed) - return g.force(ctx, g.HelmRelease, &g.lastForce, missing) + needed, forced, err := g.force(ctx, g.HelmRelease, &g.lastForce, needed) + if forced { + g.renderForced = true + } + return needed, forced, err +} + +// staleCredentials reports the credentials Secret, formatted for logs, when +// its endpoint differs from the one in the COSI Secret it is rendered from, +// comparing against what packages/system/bucket/templates/user-credentials.yaml +// writes for it. The COSI Secret being absent (the BucketAccess is being +// re-granted) leaves nothing to compare against and is not staleness. +func (g *DefaultObjectsGate) staleCredentials(ctx context.Context, src *corev1.Secret) (string, error) { + if g.CredentialsCOSISecretName == "" || g.CredentialsHelmRelease.Name == "" || g.CredentialsHelmRelease.Namespace == "" { + return "", nil + } + cosi := &corev1.Secret{} + key := types.NamespacedName{Namespace: g.Config.SourceNamespace, Name: g.CredentialsCOSISecretName} + if err := g.Client.Get(ctx, key, cosi); err != nil { + if apierrors.IsNotFound(err) { + return "", nil + } + return "", fmt.Errorf("get COSI Secret %s: %w", key, err) + } + var info struct { + Spec struct { + SecretS3 struct { + Endpoint string `json:"endpoint"` + } `json:"secretS3"` + } `json:"spec"` + } + if err := json.Unmarshal(cosi.Data["BucketInfo"], &info); err != nil { + return "", fmt.Errorf("parse BucketInfo of COSI Secret %s: %w", key, err) + } + want := strings.TrimPrefix(strings.TrimPrefix(info.Spec.SecretS3.Endpoint, "https://"), "http://") + have := string(src.Data["endpoint"]) + if have == want { + return "", nil + } + return fmt.Sprintf("Secret/%s (endpoint %q, COSI Secret has %q)", g.Config.SourceSecretName, have, want), nil +} + +// renderedEndpointFor mirrors the "backupstrategy-controller.endpoint" helper +// for a provisioned bucket: the credentials Secret's endpoint, trimmed, with +// any scheme replaced by https://. It is the value the chart stamps as +// endpointAnnotation. An empty endpoint makes the helper fall back to +// backupStorage.endpoint, which the gate cannot see, so it returns "". +func renderedEndpointFor(raw []byte) string { + host := strings.TrimSpace(string(raw)) + if host == "" { + return "" + } + return "https://" + strings.TrimPrefix(strings.TrimPrefix(host, "https://"), "http://") } // reconcileCredentials handles the one object the gate cannot check the same @@ -431,16 +523,42 @@ func (g *DefaultObjectsGate) force(ctx context.Context, target types.NamespacedN return missing, true, nil } -// missingObjects returns a sorted, de-duplicated list of the +// defaultObjectsState is what inspectObjects found: the objects that do not +// exist, and the existing ones rendered with an endpoint other than the one +// the chart would render now. +type defaultObjectsState struct { + missing []string + stale []string +} + +// staleEndpoint reports an existing object rendered with another endpoint +// than want, formatted for logs. An empty want disables the comparison. +func (g *DefaultObjectsGate) staleEndpoint(state *defaultObjectsState, key string, obj *unstructured.Unstructured, want string) { + if want == "" { + return + } + have, ok := obj.GetAnnotations()[endpointAnnotation] + switch { + case !ok: + if !g.renderForced { + state.stale = append(state.stale, key+" (no endpoint annotation)") + } + case have != want: + state.stale = append(state.stale, fmt.Sprintf("%s (endpoint %q, want %q)", key, have, want)) + } +} + +// inspectObjects returns a sorted, de-duplicated list of the // "/" objects the BackupClass references that do not exist, -// plus the Velero BSL when a Velero namespace is configured. +// plus the Velero BSL when a Velero namespace is configured, and the existing +// ones whose endpointAnnotation differs from want. // // An unmappable group/kind (the CRD is not installed) is NOT reported as // missing: no Helm re-render can create an object whose CRD is absent, and // counting it would keep the gate forcing upgrades forever. -func (g *DefaultObjectsGate) missingObjects(ctx context.Context, backupClass *backupsv1alpha1.BackupClass) ([]string, error) { +func (g *DefaultObjectsGate) inspectObjects(ctx context.Context, backupClass *backupsv1alpha1.BackupClass, want string) (defaultObjectsState, error) { seen := map[string]struct{}{} - var missing []string + var state defaultObjectsState for _, strategy := range backupClass.Spec.Strategies { name := strategy.StrategyRef.Name @@ -472,17 +590,18 @@ func (g *DefaultObjectsGate) missingObjects(ctx context.Context, backupClass *ba if meta.IsNoMatchError(err) { continue } - return nil, fmt.Errorf("map %s/%s: %w", group, kind, err) + return defaultObjectsState{}, fmt.Errorf("map %s/%s: %w", group, kind, err) } // Strategy CRs are cluster-scoped; Namespace("") is correct for // both scopes on the dynamic client. - _, err = g.Resource(mapping.Resource).Get(ctx, name, metav1.GetOptions{}) + obj, err := g.Resource(mapping.Resource).Get(ctx, name, metav1.GetOptions{}) switch { case err == nil: + g.staleEndpoint(&state, key, obj, want) case apierrors.IsNotFound(err): - missing = append(missing, key) + state.missing = append(state.missing, key) default: - return nil, fmt.Errorf("get %s %s: %w", kind, name, err) + return defaultObjectsState{}, fmt.Errorf("get %s %s: %w", kind, name, err) } } @@ -496,24 +615,26 @@ func (g *DefaultObjectsGate) missingObjects(ctx context.Context, backupClass *ba mapping, err := g.RESTMapping(schema.GroupKind{Group: backupStorageLocationGVR.Group, Kind: "BackupStorageLocation"}) switch { case err == nil: - _, getErr := g.Resource(mapping.Resource).Namespace(g.VeleroNamespace).Get(ctx, defaultBackupStorageLocationName, metav1.GetOptions{}) + key := fmt.Sprintf("BackupStorageLocation/%s", defaultBackupStorageLocationName) + obj, getErr := g.Resource(mapping.Resource).Namespace(g.VeleroNamespace).Get(ctx, defaultBackupStorageLocationName, metav1.GetOptions{}) switch { case getErr == nil: + g.staleEndpoint(&state, key, obj, want) case apierrors.IsNotFound(getErr): - missing = append(missing, fmt.Sprintf("BackupStorageLocation/%s", defaultBackupStorageLocationName)) + state.missing = append(state.missing, key) default: - return nil, fmt.Errorf("get BackupStorageLocation %s: %w", defaultBackupStorageLocationName, getErr) + return defaultObjectsState{}, fmt.Errorf("get BackupStorageLocation %s: %w", defaultBackupStorageLocationName, getErr) } case meta.IsNoMatchError(err): // Velero API not served (e.g. Velero uninstalled after bootstrap): // no Helm re-render can create the BSL, so it is not "missing". default: - return nil, fmt.Errorf("map BackupStorageLocation: %w", err) + return defaultObjectsState{}, fmt.Errorf("map BackupStorageLocation: %w", err) } } - sort.Strings(missing) - return missing, nil + sort.Strings(state.missing) + return state, nil } // forceHelmRelease stamps BOTH reconcile.fluxcd.io/forceAt and diff --git a/internal/backupcontroller/default_objects_gate_test.go b/internal/backupcontroller/default_objects_gate_test.go index f5cbb5489..dc1c0c9f0 100644 --- a/internal/backupcontroller/default_objects_gate_test.go +++ b/internal/backupcontroller/default_objects_gate_test.go @@ -2,6 +2,8 @@ package backupcontroller import ( "context" + "errors" + "strings" "testing" "time" @@ -18,6 +20,7 @@ import ( k8stesting "k8s.io/client-go/testing" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1" ) @@ -110,14 +113,60 @@ func cozyDefaultBackupClass() *backupsv1alpha1.BackupClass { } } +// renderedEndpoint is what the chart stamps on every default object for the +// endpoint sourceSecret carries: the steady state after a render that saw it. +const renderedEndpoint = "https://s3.example.com" + func strategyObject(kind, name string) *unstructured.Unstructured { u := &unstructured.Unstructured{} u.SetAPIVersion(strategyAPIGroup + "/v1alpha1") u.SetKind(kind) u.SetName(name) + u.SetAnnotations(map[string]string{endpointAnnotation: renderedEndpoint}) return u } +func withEndpoint(u *unstructured.Unstructured, endpoint string) *unstructured.Unstructured { + u.SetAnnotations(map[string]string{endpointAnnotation: endpoint}) + return u +} + +// unannotated is an object rendered by a chart that predates the endpoint +// annotation. +func unannotated(u *unstructured.Unstructured) *unstructured.Unstructured { + u.SetAnnotations(nil) + return u +} + +// allDefaultObjects is every object cozy-default routes to, plus the BSL, as +// the chart renders them for sourceSecret's endpoint. +func allDefaultObjects() []runtime.Object { + return []runtime.Object{ + strategyObject("CNPG", "cozy-default-cnpg"), + strategyObject("MariaDB", "cozy-default-mariadb"), + strategyObject("Etcd", "cozy-default-etcd"), + strategyObject("Altinity", "cozy-default-altinity"), + strategyObject("Velero", "cozy-default-velero-vminstance"), + strategyObject("Velero", "cozy-default-velero-vmdisk"), + bslObject(), + } +} + +// cosiSecret is the Secret the COSI sidecar writes for the platform bucket's +// BucketAccess, which user-credentials.yaml renders the credentials Secret +// from. The BucketInfo document is one read off a live cluster, with the keys +// and the host replaced. +func cosiSecret(endpoint string) *corev1.Secret { + bucketInfo := `{"metadata": {"name": "bc-b8e30337-1821-418f-a4dd-163e8016aaee", "creationTimestamp": null}, ` + + `"spec": {"bucketName": "bucket-1a2b", "authenticationType": "KEY", ` + + `"secretS3": {"endpoint": "` + endpoint + `", "region": "", "accessKeyID": "AK", "accessSecretKey": "SK"}, ` + + `"secretAzure": null, "protocols": ["s3"]}}` + return &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Namespace: "tenant-root", Name: "bucket-cozy-backups-system"}, + Data: map[string][]byte{"BucketInfo": []byte(bucketInfo)}, + } +} + func helmReleaseObject() *unstructured.Unstructured { u := &unstructured.Unstructured{} u.SetAPIVersion("helm.toolkit.fluxcd.io/v2") @@ -163,9 +212,10 @@ func newGate(t *testing.T, ctrlObjs []client.Object, dynObjs ...runtime.Object) Namespace: "tenant-root", Name: "bucket-cozy-backups-system", }, - VeleroNamespace: "cozy-velero", - MinForceInterval: 5 * time.Minute, - now: func() time.Time { return time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) }, + CredentialsCOSISecretName: "bucket-cozy-backups-system", + VeleroNamespace: "cozy-velero", + MinForceInterval: 5 * time.Minute, + now: func() time.Time { return time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) }, } g.Interface = dyn g.RESTMapper = gateRESTMapper() @@ -193,6 +243,7 @@ func bslObject() *unstructured.Unstructured { u.SetKind("BackupStorageLocation") u.SetNamespace("cozy-velero") u.SetName(defaultBackupStorageLocationName) + u.SetAnnotations(map[string]string{endpointAnnotation: renderedEndpoint}) return u } @@ -259,7 +310,7 @@ func TestCheckForcesWhenObjectsMissing(t *testing.T) { // the cluster. func TestCheckNoopWhenAllPresent(t *testing.T) { g, dyn := newGate(t, - []client.Object{sourceSecret("bucket-1a2b"), cozyDefaultBackupClass()}, + []client.Object{sourceSecret("bucket-1a2b"), cosiSecret("https://s3.example.com"), cozyDefaultBackupClass()}, helmReleaseObject(), strategyObject("CNPG", "cozy-default-cnpg"), strategyObject("MariaDB", "cozy-default-mariadb"), @@ -550,10 +601,11 @@ func TestMissingObjectsIgnoresUnmappedKinds(t *testing.T) { bslObject(), ) - missing, err := g.missingObjects(context.Background(), bc) + state, err := g.inspectObjects(context.Background(), bc, "") if err != nil { - t.Fatalf("missingObjects: %v", err) + t.Fatalf("inspectObjects: %v", err) } + missing := state.missing if len(missing) != 0 { t.Fatalf("missing = %v, want none (unmapped kind must be ignored)", missing) } @@ -579,10 +631,11 @@ func TestMissingObjectsSkipsVeleroWhenNamespaceEmpty(t *testing.T) { ) g.VeleroNamespace = "" - missing, err := g.missingObjects(context.Background(), bc) + state, err := g.inspectObjects(context.Background(), bc, "") if err != nil { - t.Fatalf("missingObjects: %v", err) + t.Fatalf("inspectObjects: %v", err) } + missing := state.missing if len(missing) != 0 { t.Fatalf("missing = %v, want none when Velero is disabled", missing) } @@ -630,10 +683,11 @@ func TestMissingObjectsSkipsBSLWhenVeleroAPIAbsent(t *testing.T) { } g.RESTMapper = m - missing, err := g.missingObjects(context.Background(), bc) + state, err := g.inspectObjects(context.Background(), bc, "") if err != nil { - t.Fatalf("missingObjects: %v", err) + t.Fatalf("inspectObjects: %v", err) } + missing := state.missing if len(missing) != 0 { t.Fatalf("missing = %v, want none when the Velero API is absent", missing) } @@ -744,3 +798,330 @@ func TestCheckToleratesAbsentHelmRelease(t *testing.T) { t.Error("objects should still be reported as missing") } } + +// TestCheckForcesCredentialsReleaseWhenEndpointStale covers the credentials +// Secret outliving the endpoint it was rendered from. The COSI sidecar writes +// BucketInfo once per BucketAccess, so a re-granted BucketAccess (after a +// publishing.host change) carries the new endpoint while the credentials +// Secret -system rendered earlier keeps the old one: the Secret +// exists, so the missing-Secret path never fires, and every consumer keeps +// the dead host. +func TestCheckForcesCredentialsReleaseWhenEndpointStale(t *testing.T) { + objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...) + g, dyn := newGate(t, + []client.Object{sourceSecret("bucket-1a2b"), cosiSecret("https://s3.new.example.com"), cozyDefaultBackupClass()}, + objs..., + ) + + missing, forced, err := g.Check(context.Background()) + if err != nil { + t.Fatalf("Check: %v", err) + } + if !forced { + t.Fatal("expected the bucket release forced while its credentials Secret carries a stale endpoint") + } + if len(missing) != 1 || !strings.HasPrefix(missing[0], "Secret/bucket-cozy-backups-system-credentials") { + t.Fatalf("missing = %v, want the credentials Secret", missing) + } + if ann := credentialsForceAnnotations(t, dyn); ann["reconcile.fluxcd.io/forceAt"] == "" { + t.Errorf("bucket release not forced: %v", ann) + } + // The objects were rendered from the stale Secret and agree with it; + // re-rendering them before the Secret is fixed would bake the old + // endpoint in again. + if ann := forceAnnotations(t, dyn); len(ann) != 0 { + t.Errorf("own HelmRelease forced while the credentials Secret is stale: %v", ann) + } +} + +// TestCheckCredentialsEndpointComparison pins the comparison against what +// user-credentials.yaml writes for a given BucketInfo endpoint (the scheme +// stripped, nothing else), so a Secret the chart rendered from the current +// BucketInfo never counts as stale and the bucket release is not forced on +// every throttle window. +func TestCheckCredentialsEndpointComparison(t *testing.T) { + for _, tc := range []struct { + name string + cosi string + wantForce bool + }{ + {"https scheme stripped", "https://s3.example.com", false}, + {"http scheme stripped", "http://s3.example.com", false}, + {"bare host", "s3.example.com", false}, + {"other host", "https://s3.new.example.com", true}, + {"other port", "https://s3.example.com:8443", true}, + } { + t.Run(tc.name, func(t *testing.T) { + objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...) + g, dyn := newGate(t, + []client.Object{sourceSecret("bucket-1a2b"), cosiSecret(tc.cosi), cozyDefaultBackupClass()}, + objs..., + ) + if _, _, err := g.Check(context.Background()); err != nil { + t.Fatalf("Check: %v", err) + } + forced := credentialsForceAnnotations(t, dyn)["reconcile.fluxcd.io/forceAt"] != "" + if forced != tc.wantForce { + t.Fatalf("bucket release forced = %v, want %v", forced, tc.wantForce) + } + }) + } +} + +// TestCheckSkipsCredentialsComparisonWithoutCOSISecret covers the window in +// which the BucketAccess is being re-granted: the COSI Secret is gone and +// there is nothing to compare against, which is not evidence of staleness. +func TestCheckSkipsCredentialsComparisonWithoutCOSISecret(t *testing.T) { + objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...) + g, dyn := newGate(t, + []client.Object{sourceSecret("bucket-1a2b"), cozyDefaultBackupClass()}, + objs..., + ) + + missing, forced, err := g.Check(context.Background()) + if err != nil || forced || len(missing) != 0 { + t.Fatalf("missing = %v, forced = %v, err = %v; want a no-op", missing, forced, err) + } + if ann := credentialsForceAnnotations(t, dyn); len(ann) != 0 { + t.Errorf("bucket release forced with no COSI Secret to compare against: %v", ann) + } +} + +// TestCheckSkipsCredentialsComparisonWhenUnconfigured pins both switches that +// turn the comparison off: no COSI Secret name, and no bucket release (external +// S3, where the Secret is admin-managed and no BucketInfo backs it). +func TestCheckSkipsCredentialsComparisonWhenUnconfigured(t *testing.T) { + for _, tc := range []struct { + name string + apply func(g *DefaultObjectsGate) + }{ + {"no COSI Secret name", func(g *DefaultObjectsGate) { g.CredentialsCOSISecretName = "" }}, + {"no bucket release", func(g *DefaultObjectsGate) { g.CredentialsHelmRelease = types.NamespacedName{} }}, + {"no bucket release name", func(g *DefaultObjectsGate) { g.CredentialsHelmRelease.Name = "" }}, + {"no bucket release namespace", func(g *DefaultObjectsGate) { g.CredentialsHelmRelease.Namespace = "" }}, + } { + t.Run(tc.name, func(t *testing.T) { + objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...) + g, dyn := newGate(t, + []client.Object{sourceSecret("bucket-1a2b"), cosiSecret("https://s3.new.example.com"), cozyDefaultBackupClass()}, + objs..., + ) + tc.apply(g) + // The real API server rejects a Get with an empty name; the fake + // answers NotFound, which would hide a lookup of an unset name. + g.Client = interceptor.NewClient(g.Client.(client.WithWatch), interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if key.Name == "" { + return errors.New("resource name may not be empty") + } + return c.Get(ctx, key, obj, opts...) + }, + }) + missing, forced, err := g.Check(context.Background()) + if err != nil || forced || len(missing) != 0 { + t.Fatalf("missing = %v, forced = %v, err = %v; want a no-op", missing, forced, err) + } + if ann := credentialsForceAnnotations(t, dyn); len(ann) != 0 { + t.Errorf("bucket release forced with the comparison disabled: %v", ann) + } + }) + } +} + +// TestCheckReportsMalformedCOSISecret pins that a COSI Secret the gate cannot +// read is an error the check counts, not a silent "not stale". +func TestCheckReportsMalformedCOSISecret(t *testing.T) { + defaultObjectsCheckErrors.Reset() + bad := cosiSecret("") + bad.Data["BucketInfo"] = []byte("{not json") + objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...) + g, _ := newGate(t, []client.Object{sourceSecret("bucket-1a2b"), bad, cozyDefaultBackupClass()}, objs...) + + if _, forced, err := g.Check(context.Background()); err == nil || forced { + t.Fatalf("forced = %v, err = %v; want an error", forced, err) + } + if got := testutil.ToFloat64(defaultObjectsCheckErrors.WithLabelValues("cozy-default")); got != 1 { + t.Fatalf("check errors = %v, want 1", got) + } +} + +// TestCheckForcesOwnReleaseWhenObjectEndpointStale is the second half of a +// publishing.host change: the credentials Secret now carries the new +// endpoint, but the BSL and the default Strategies baked the old one at the +// last render of this chart and nothing re-renders them, so every backup +// keeps going to the dead host. +func TestCheckForcesOwnReleaseWhenObjectEndpointStale(t *testing.T) { + for _, tc := range []struct { + name string + stale *unstructured.Unstructured + key string + }{ + {"strategy", strategyObject("CNPG", "cozy-default-cnpg"), "CNPG/cozy-default-cnpg"}, + {"BSL", bslObject(), "BackupStorageLocation/cozy-default"}, + } { + t.Run(tc.name, func(t *testing.T) { + var objs []runtime.Object + for _, o := range allDefaultObjects() { + u := o.(*unstructured.Unstructured) + if u.GetKind() == tc.stale.GetKind() && u.GetName() == tc.stale.GetName() { + withEndpoint(u, "https://s3.old.example.com") + } + objs = append(objs, u) + } + objs = append(objs, helmReleaseObject(), credentialsHelmReleaseObject()) + g, dyn := newGate(t, + []client.Object{sourceSecret("bucket-1a2b"), cosiSecret("https://s3.example.com"), cozyDefaultBackupClass()}, + objs..., + ) + + missing, forced, err := g.Check(context.Background()) + if err != nil { + t.Fatalf("Check: %v", err) + } + if !forced { + t.Fatal("expected this chart's release forced while an object carries a stale endpoint") + } + if len(missing) != 1 || !strings.HasPrefix(missing[0], tc.key+" ") { + t.Fatalf("missing = %v, want only %s", missing, tc.key) + } + if ann := forceAnnotations(t, dyn); ann["reconcile.fluxcd.io/forceAt"] == "" { + t.Errorf("own HelmRelease not forced: %v", ann) + } + if ann := credentialsForceAnnotations(t, dyn); len(ann) != 0 { + t.Errorf("bucket release forced for a stale object: %v", ann) + } + }) + } +} + +// TestCheckIgnoresObjectEndpointOnExternalS3 pins that the comparison is off +// when no bucket release is configured: with provisionBucket=false the chart +// renders backupStorage.endpoint, not the Secret's, so the two legitimately +// differ and forcing would loop every MinForceInterval. +func TestCheckIgnoresObjectEndpointOnExternalS3(t *testing.T) { + objs := []runtime.Object{helmReleaseObject()} + for _, o := range allDefaultObjects() { + objs = append(objs, withEndpoint(o.(*unstructured.Unstructured), "https://minio.example.internal:9000")) + } + g, dyn := newGate(t, []client.Object{sourceSecret("bucket-1a2b"), cozyDefaultBackupClass()}, objs...) + g.CredentialsHelmRelease = types.NamespacedName{} + + missing, forced, err := g.Check(context.Background()) + if err != nil || forced || len(missing) != 0 { + t.Fatalf("missing = %v, forced = %v, err = %v; want a no-op", missing, forced, err) + } + if ann := forceAnnotations(t, dyn); len(ann) != 0 { + t.Errorf("own HelmRelease forced on external S3: %v", ann) + } +} + +// TestCheckIgnoresObjectEndpointWithoutSecretEndpoint covers a credentials +// Secret with no endpoint key: the chart then renders its values fallback, +// which the gate cannot reproduce, so there is nothing to compare against. +func TestCheckIgnoresObjectEndpointWithoutSecretEndpoint(t *testing.T) { + src := sourceSecret("bucket-1a2b") + delete(src.Data, "endpoint") + objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...) + g, dyn := newGate(t, []client.Object{src, cozyDefaultBackupClass()}, objs...) + + if _, forced, err := g.Check(context.Background()); err != nil || forced { + t.Fatalf("forced = %v, err = %v; want a no-op", forced, err) + } + if ann := forceAnnotations(t, dyn); len(ann) != 0 { + t.Errorf("own HelmRelease forced with no endpoint to compare against: %v", ann) + } +} + +// TestCheckForcesOnceForUnannotatedObjects covers objects rendered by a chart +// that predates the endpoint annotation. Their endpoint is unknown, so they +// are treated as stale until one forced render has gone through, which stamps +// the annotation. A force that did not go through (throttled) does not count, +// and once one has, an object still without the annotation (one the chart +// does not render) must not force again every MinForceInterval. +func TestCheckForcesOnceForUnannotatedObjects(t *testing.T) { + base := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + objs := []runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()} + for _, o := range allDefaultObjects() { + objs = append(objs, unannotated(o.(*unstructured.Unstructured))) + } + g, dyn := newGate(t, []client.Object{sourceSecret("bucket-1a2b"), cozyDefaultBackupClass()}, objs...) + g.lastForce = base.Add(-time.Minute) + g.now = func() time.Time { return base } + + if missing, forced, err := g.Check(context.Background()); err != nil || forced || len(missing) != 7 { + t.Fatalf("throttled Check: missing = %v, forced = %v, err = %v; want 7 reported, none forced", missing, forced, err) + } + + g.now = func() time.Time { return base.Add(5 * time.Minute) } + if _, forced, err := g.Check(context.Background()); err != nil || !forced { + t.Fatalf("first unthrottled Check: forced = %v, err = %v; want forced", forced, err) + } + first := forceAnnotations(t, dyn)["reconcile.fluxcd.io/forceAt"] + + g.now = func() time.Time { return base.Add(time.Hour) } + missing, forced, err := g.Check(context.Background()) + if err != nil || forced || len(missing) != 0 { + t.Fatalf("after the forced render: missing = %v, forced = %v, err = %v; want a no-op", missing, forced, err) + } + if again := forceAnnotations(t, dyn)["reconcile.fluxcd.io/forceAt"]; again != first { + t.Errorf("forced again for unannotated objects: %q, then %q", first, again) + } +} + +// TestCheckStillForcesStaleAfterUnannotatedForce pins that the once-only +// treatment covers the missing annotation alone: an annotation that names the +// wrong endpoint still forces after that. +func TestCheckStillForcesStaleAfterUnannotatedForce(t *testing.T) { + objs := []runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()} + for _, o := range allDefaultObjects() { + objs = append(objs, withEndpoint(o.(*unstructured.Unstructured), "https://s3.old.example.com")) + } + g, _ := newGate(t, []client.Object{sourceSecret("bucket-1a2b"), cozyDefaultBackupClass()}, objs...) + g.renderForced = true + + if _, forced, err := g.Check(context.Background()); err != nil || !forced { + t.Fatalf("forced = %v, err = %v; want forced", forced, err) + } +} + +// TestRenderedEndpointMatchesTheChart pins renderedEndpointFor to the +// "backupstrategy-controller.endpoint" helper, which the chart stamps as the +// annotation: trim, strip a scheme, force https://. Any divergence makes the +// gate see every object as stale and force this release forever. +func TestRenderedEndpointMatchesTheChart(t *testing.T) { + for _, tc := range []struct{ in, want string }{ + {"s3.example.com", "https://s3.example.com"}, + {"s3.example.com\n", "https://s3.example.com"}, + {" s3.example.com ", "https://s3.example.com"}, + {"https://s3.example.com", "https://s3.example.com"}, + {"http://s3.example.com:8333", "https://s3.example.com:8333"}, + {"s3.example.com/prefix/", "https://s3.example.com/prefix/"}, + // No endpoint in the Secret: the chart renders its values fallback, + // which the gate cannot reproduce, so it compares nothing. + {"", ""}, + } { + if got := renderedEndpointFor([]byte(tc.in)); got != tc.want { + t.Errorf("renderedEndpointFor(%q) = %q, want %q", tc.in, got, tc.want) + } + } +} + +// TestForcedReleaseForNamesTheStaleCredentialsRelease pins the release the +// log line names: a stale credentials Secret is repaired by the bucket +// release, like a missing one, and everything else by this chart's own. +func TestForcedReleaseForNamesTheStaleCredentialsRelease(t *testing.T) { + g, _ := newGate(t, nil) + for _, tc := range []struct { + missing []string + want types.NamespacedName + }{ + {[]string{"Secret/bucket-cozy-backups-system-credentials"}, g.CredentialsHelmRelease}, + {[]string{`Secret/bucket-cozy-backups-system-credentials (endpoint "s3.old", COSI Secret has "s3.new")`}, g.CredentialsHelmRelease}, + {[]string{"Secret/bucket-cozy-backups-system-credentials-other"}, g.HelmRelease}, + {[]string{`CNPG/cozy-default-cnpg (endpoint "https://s3.old", want "https://s3.new")`}, g.HelmRelease}, + } { + if got := g.forcedReleaseFor(tc.missing); got != tc.want { + t.Errorf("forcedReleaseFor(%v) = %v, want %v", tc.missing, got, tc.want) + } + } +} diff --git a/packages/system/backupstrategy-controller/templates/_helpers.tpl b/packages/system/backupstrategy-controller/templates/_helpers.tpl index 6665cc639..f64c77b88 100644 --- a/packages/system/backupstrategy-controller/templates/_helpers.tpl +++ b/packages/system/backupstrategy-controller/templates/_helpers.tpl @@ -101,8 +101,11 @@ https://. - provisionBucket: true + Secret missing (offline `helm template`/unit render, or pre-reconcile install where lookup returns nil) → fall back - to .Values.backupStorage.endpoint. On a live deploy Flux re-renders on - spec.interval once the Secret exists, promoting the derived endpoint. + to .Values.backupStorage.endpoint. Flux does not re-render on + spec.interval; the controller's DefaultObjectsGate forces the render + once the Secret exists, and again whenever the Secret's endpoint stops + matching the backups.cozystack.io/endpoint annotation every default + Strategy CR and the Velero BSL carry with this helper's output. Normalization of the decoded value: trim first (a trailing newline in the Secret data would otherwise ride into the URL and break it), then strip any diff --git a/packages/system/backupstrategy-controller/templates/deployment.yaml b/packages/system/backupstrategy-controller/templates/deployment.yaml index f35e97661..adc09fa2a 100644 --- a/packages/system/backupstrategy-controller/templates/deployment.yaml +++ b/packages/system/backupstrategy-controller/templates/deployment.yaml @@ -87,6 +87,13 @@ spec: value: {{ printf "bucket-%s-system" .Values.backupStorage.bucketName | quote }} - name: BACKUP_CREDENTIALS_HELMRELEASE_NAMESPACE value: {{ .Values.backupStorage.namespace | quote }} + # The COSI Secret that release renders the credentials Secret from + # (packages/system/bucket/templates/user-credentials.yaml appends + # "-credentials" to its name). The COSI sidecar writes it once per + # BucketAccess, so the gate compares the two endpoints and forces the + # release when the credentials Secret lags behind. + - name: BACKUP_CREDENTIALS_COSI_SECRET_NAME + value: {{ trimSuffix "-credentials" .Values.backupStorage.systemSecretName | quote }} {{- end }} {{- if .Values.velero.bslEnabled }} - name: BACKUP_DEFAULT_OBJECTS_VELERO_NAMESPACE diff --git a/packages/system/backupstrategy-controller/templates/strategy-altinity-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-altinity-default.yaml index 3357140b6..d9094c082 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-altinity-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-altinity-default.yaml @@ -18,6 +18,8 @@ apiVersion: strategy.backups.cozystack.io/v1alpha1 kind: Altinity metadata: name: cozy-default-altinity + annotations: + backups.cozystack.io/endpoint: {{ include "backupstrategy-controller.endpoint" . | quote }} spec: template: spec: diff --git a/packages/system/backupstrategy-controller/templates/strategy-cnpg-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-cnpg-default.yaml index 58dda61b1..bf34b2e0d 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-cnpg-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-cnpg-default.yaml @@ -5,6 +5,8 @@ apiVersion: strategy.backups.cozystack.io/v1alpha1 kind: CNPG metadata: name: cozy-default-cnpg + annotations: + backups.cozystack.io/endpoint: {{ include "backupstrategy-controller.endpoint" . | quote }} spec: template: {{- /* diff --git a/packages/system/backupstrategy-controller/templates/strategy-etcd-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-etcd-default.yaml index f335f04cf..5183af45b 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-etcd-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-etcd-default.yaml @@ -5,6 +5,8 @@ apiVersion: strategy.backups.cozystack.io/v1alpha1 kind: Etcd metadata: name: cozy-default-etcd + annotations: + backups.cozystack.io/endpoint: {{ include "backupstrategy-controller.endpoint" . | quote }} spec: template: destination: diff --git a/packages/system/backupstrategy-controller/templates/strategy-foundationdb-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-foundationdb-default.yaml index 061be2ffb..82f9ab6ca 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-foundationdb-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-foundationdb-default.yaml @@ -8,6 +8,8 @@ apiVersion: strategy.backups.cozystack.io/v1alpha1 kind: FoundationDB metadata: name: cozy-default-foundationdb + annotations: + backups.cozystack.io/endpoint: {{ include "backupstrategy-controller.endpoint" . | quote }} spec: template: blobStoreConfiguration: diff --git a/packages/system/backupstrategy-controller/templates/strategy-kafka-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-kafka-default.yaml index d5c88bdf5..efa103bdd 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-kafka-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-kafka-default.yaml @@ -23,6 +23,8 @@ apiVersion: strategy.backups.cozystack.io/v1alpha1 kind: Kafka metadata: name: cozy-default-kafka + annotations: + backups.cozystack.io/endpoint: {{ include "backupstrategy-controller.endpoint" . | quote }} spec: artifactURITemplate: {{ printf "s3://%s/{{ .Release.Namespace }}/{{ .Release.Name }}/{{ .BackupName }}/kafka-metadata.txt" $bucketName | quote }} template: diff --git a/packages/system/backupstrategy-controller/templates/strategy-mariadb-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-mariadb-default.yaml index ec8b35160..7615a8b0d 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-mariadb-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-mariadb-default.yaml @@ -7,6 +7,8 @@ apiVersion: strategy.backups.cozystack.io/v1alpha1 kind: MariaDB metadata: name: cozy-default-mariadb + annotations: + backups.cozystack.io/endpoint: {{ include "backupstrategy-controller.endpoint" . | quote }} spec: template: storage: diff --git a/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml index 3bf8ff407..95e621d76 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-mongodb-default.yaml @@ -54,6 +54,8 @@ apiVersion: strategy.backups.cozystack.io/v1alpha1 kind: MongoDB metadata: name: cozy-default-mongodb + annotations: + backups.cozystack.io/endpoint: {{ include "backupstrategy-controller.endpoint" . | quote }} spec: template: storageName: s3-storage diff --git a/packages/system/backupstrategy-controller/templates/strategy-rabbitmq-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-rabbitmq-default.yaml index 4faea49a2..562217a77 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-rabbitmq-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-rabbitmq-default.yaml @@ -26,6 +26,8 @@ apiVersion: strategy.backups.cozystack.io/v1alpha1 kind: Rabbitmq metadata: name: cozy-default-rabbitmq + annotations: + backups.cozystack.io/endpoint: {{ include "backupstrategy-controller.endpoint" . | quote }} spec: # The driver defers the run until the RabbitmqCluster reports AllReplicasReady # (a Go-side precondition), so a not-yet-ready broker surfaces a precise diff --git a/packages/system/backupstrategy-controller/templates/strategy-redis-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-redis-default.yaml index f2f9a54b0..d8e39d821 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-redis-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-redis-default.yaml @@ -21,6 +21,8 @@ apiVersion: strategy.backups.cozystack.io/v1alpha1 kind: Redis metadata: name: cozy-default-redis + annotations: + backups.cozystack.io/endpoint: {{ include "backupstrategy-controller.endpoint" . | quote }} spec: template: spec: diff --git a/packages/system/backupstrategy-controller/templates/strategy-velero-vmdisk-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-velero-vmdisk-default.yaml index 4511fbc58..1c1a7b9b5 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-velero-vmdisk-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-velero-vmdisk-default.yaml @@ -5,6 +5,8 @@ apiVersion: strategy.backups.cozystack.io/v1alpha1 kind: Velero metadata: name: cozy-default-velero-vmdisk + annotations: + backups.cozystack.io/endpoint: {{ include "backupstrategy-controller.endpoint" . | quote }} spec: template: restoreSpec: diff --git a/packages/system/backupstrategy-controller/templates/strategy-velero-vminstance-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-velero-vminstance-default.yaml index b1f919125..9666a7cce 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-velero-vminstance-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-velero-vminstance-default.yaml @@ -5,6 +5,8 @@ apiVersion: strategy.backups.cozystack.io/v1alpha1 kind: Velero metadata: name: cozy-default-velero-vminstance + annotations: + backups.cozystack.io/endpoint: {{ include "backupstrategy-controller.endpoint" . | quote }} spec: template: restoreSpec: diff --git a/packages/system/backupstrategy-controller/templates/velero-bsl.yaml b/packages/system/backupstrategy-controller/templates/velero-bsl.yaml index e0ba05ad8..e50f3a1fc 100644 --- a/packages/system/backupstrategy-controller/templates/velero-bsl.yaml +++ b/packages/system/backupstrategy-controller/templates/velero-bsl.yaml @@ -12,6 +12,8 @@ kind: BackupStorageLocation metadata: name: cozy-default namespace: {{ .Values.velero.namespace }} + annotations: + backups.cozystack.io/endpoint: {{ include "backupstrategy-controller.endpoint" . | quote }} spec: provider: aws # default=false: do not silently displace an admin-provisioned default diff --git a/packages/system/backupstrategy-controller/tests/default_objects_gate_test.yaml b/packages/system/backupstrategy-controller/tests/default_objects_gate_test.yaml index 976fee166..ed616ce79 100644 --- a/packages/system/backupstrategy-controller/tests/default_objects_gate_test.yaml +++ b/packages/system/backupstrategy-controller/tests/default_objects_gate_test.yaml @@ -11,6 +11,8 @@ suite: DefaultObjectsGate wiring — the release the gate forces, and its RBAC templates: - templates/deployment.yaml - templates/rbac.yaml + - templates/strategy-cnpg-default.yaml + - templates/velero-bsl.yaml release: name: backupstrategy-controller @@ -61,6 +63,16 @@ tests: content: name: BACKUP_CREDENTIALS_HELMRELEASE_NAMESPACE value: tenant-root + # The COSI Secret the bucket release renders the credentials Secret + # from is the BucketAccess credentialsSecretName, -system, + # which is also BACKUP_STORAGE_SECRET_NAME minus "-credentials" + # (packages/system/bucket/templates/user-credentials.yaml). The gate + # compares the two endpoints. + - contains: + path: spec.template.spec.containers[0].env + content: + name: BACKUP_CREDENTIALS_COSI_SECRET_NAME + value: bucket-cozy-backups-system # BACKUP_STORAGE_SECRET_NAME is exactly the release name above with # "-credentials" appended — that is what makes forcing this release the # thing that creates that Secret. @@ -86,6 +98,11 @@ tests: content: name: BACKUP_STORAGE_SECRET_NAME value: bucket-platform-backups-system-credentials + - contains: + path: spec.template.spec.containers[0].env + content: + name: BACKUP_CREDENTIALS_COSI_SECRET_NAME + value: bucket-platform-backups-system # External S3: the Secret is admin-managed and no release renders it, so # there is nothing to force. Handing the gate stale coordinates would make @@ -105,6 +122,11 @@ tests: content: name: BACKUP_CREDENTIALS_HELMRELEASE_NAMESPACE value: tenant-root + - notContains: + path: spec.template.spec.containers[0].env + content: + name: BACKUP_CREDENTIALS_COSI_SECRET_NAME + value: bucket-cozy-backups-system - it: "velero.bslEnabled=false: the BSL is not rendered, so the gate must not look for it" template: templates/deployment.yaml @@ -154,3 +176,41 @@ tests: apiGroups: ["velero.io"] resources: ["backupstoragelocations"] verbs: ["get"] + + # The gate compares backups.cozystack.io/endpoint with the endpoint it + # derives from the credentials Secret (renderedEndpointFor in + # internal/backupcontroller/default_objects_gate.go, whose test uses the + # same input). Any divergence would make every object look stale and force + # this release every MinForceInterval. + - it: "objects carry the endpoint derived from the credentials Secret as their endpoint annotation" + set: + backupStorage.bucketNameOverride: test-bucket + kubernetesProvider: + scheme: + "v1/Secret": + gvr: + version: v1 + resource: secrets + namespaced: true + objects: + - apiVersion: v1 + kind: Secret + metadata: + name: bucket-cozy-backups-system-credentials + namespace: tenant-root + data: + # "http://s3.example.com:8333\n" + endpoint: aHR0cDovL3MzLmV4YW1wbGUuY29tOjgzMzMK + asserts: + - equal: + path: metadata.annotations["backups.cozystack.io/endpoint"] + value: https://s3.example.com:8333 + template: templates/strategy-cnpg-default.yaml + - equal: + path: spec.template.barmanObjectStore.endpointURL + value: https://s3.example.com:8333 + template: templates/strategy-cnpg-default.yaml + - equal: + path: metadata.annotations["backups.cozystack.io/endpoint"] + value: https://s3.example.com:8333 + template: templates/velero-bsl.yaml diff --git a/packages/system/backupstrategy-controller/values.yaml b/packages/system/backupstrategy-controller/values.yaml index eebdaaf0f..cdca60ff8 100644 --- a/packages/system/backupstrategy-controller/values.yaml +++ b/packages/system/backupstrategy-controller/values.yaml @@ -200,8 +200,15 @@ backupStorage: # credentials Secret is missing it forces the bucket's -system # release; once the bucket name resolves it checks that every object # cozy-default routes to exists and forces THIS release when any is - # missing. Both are throttled, independently, and a no-op in the steady - # state. A suspended release is skipped rather than re-stamped forever. The + # missing. It repairs a stale S3 endpoint the same way: when the + # credentials Secret's endpoint differs from the COSI Secret it is rendered + # from it forces the bucket's -system release, and when the + # backups.cozystack.io/endpoint annotation on the Velero BSL or a default + # Strategy differs from the credentials Secret's endpoint it forces THIS + # release. The COSI Secret itself keeps the endpoint it was granted with, so + # after a publishing.host change that endpoint follows only once the + # BucketAccess is re-granted. Both are throttled, independently, and a no-op + # in the steady state. A suspended release is skipped rather than re-stamped forever. The # gate does NOT create the objects itself: their bodies are values-driven # and Helm stays their single owner. # diff --git a/packages/system/bucket/templates/user-credentials.yaml b/packages/system/bucket/templates/user-credentials.yaml index 6c2a14bd1..a45320254 100644 --- a/packages/system/bucket/templates/user-credentials.yaml +++ b/packages/system/bucket/templates/user-credentials.yaml @@ -27,7 +27,9 @@ So the repair lives outside the chart, where it is per-object and costs a throttled annotation patch: backupstrategy-controller's DefaultObjectsGate (internal/backupcontroller/default_objects_gate.go) forces this release - when the platform bucket's credentials Secret is absent. That covers the + when the platform bucket's credentials Secret is absent, or when its + endpoint differs from the COSI Secret's (a BucketAccess re-granted after a + publishing.host change). That covers the cluster-breaking case — the cozy-backups Secret feeds the credentials projector, hence every default BackupClass strategy, Velero, and migration 50. Tenant buckets keep the pre-existing behaviour; generalising the gate From 8ae1adfb274c1080487cd1df4b2f4b66fbccb7b1 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Wed, 4 Nov 2026 19:20:29 +0300 Subject: [PATCH 2/8] fix(backups): compare the credentials endpoint only for a Secret derived from COSI backupStorage.systemSecretName may name a Secret the bucket chart does not render from a COSI Secret: the raw COSI Secret itself, which the projector accepts, or any Secret without the -credentials suffix. The COSI Secret name was then the source name unchanged, so the gate compared a Secret with itself and either reported it stale on every tick or failed the check, and stopped repairing missing default objects as well. Skip the comparison when there is no distinct COSI Secret or no endpoint key to compare. The gate compares the annotation with what the chart's endpoint helper renders, and the helper renders a present but blank endpoint as a bare https:// instead of falling back, so the gate has to compute the same value or its expectation and the chart disagree for that Secret. The gate's docs, metric help and log lines named only missing objects, so they did not cover a stale endpoint they now report. Assisted-by: LLM Signed-off-by: Alexey Artamonov (cherry picked from commit d0f47f7dd5a7f57147fd1c67347ba2a9994ae49f) Signed-off-by: Myasnikov Daniil --- .../backupcontroller/default_objects_gate.go | 41 ++++++++++------ .../default_objects_gate_test.go | 49 +++++++++++++++++++ .../templates/deployment.yaml | 2 + .../tests/default_objects_gate_test.yaml | 13 +++++ .../backupstrategy-controller/values.yaml | 6 +-- 5 files changed, 92 insertions(+), 19 deletions(-) diff --git a/internal/backupcontroller/default_objects_gate.go b/internal/backupcontroller/default_objects_gate.go index efcd970d5..d0ed29954 100644 --- a/internal/backupcontroller/default_objects_gate.go +++ b/internal/backupcontroller/default_objects_gate.go @@ -51,15 +51,16 @@ var defaultObjectsMissing = prometheus.NewGaugeVec( ) // defaultObjectsForceReconciles counts the forced Helm upgrades the gate -// issued to materialise those objects. A counter that keeps climbing means -// the forced render is not producing the objects (e.g. a CRD is missing), +// issued to materialise those objects or to refresh their S3 endpoint. A +// counter that keeps climbing means the forced render is not producing the +// objects (e.g. a CRD is missing) or not changing their endpoint, // which is a different failure than the install-time race this gate closes. // A suspended release is NOT counted here: it is skipped before the patch, // so a paused release cannot masquerade as a render that keeps failing. var defaultObjectsForceReconciles = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "cozystack_backup_default_objects_force_reconciles_total", - Help: "Number of forced HelmRelease reconciles issued to create missing platform backup objects.", + Help: "Number of forced HelmRelease reconciles issued to create missing platform backup objects or refresh their S3 endpoint.", }, []string{"namespace", "name"}, ) @@ -125,8 +126,9 @@ var backupStorageLocationGVR = schema.GroupVersionResource{ // is resolvable — read from the same platform credentials Secret the // projector already consumes, so no new dependency and no `lookup` — it // checks that every object the platform BackupClass routes to actually -// exists, and forces one Helm upgrade when any is missing. A forced -// upgrade re-runs the lookups, so the gated templates materialise. +// exists, and forces one Helm upgrade when any is missing or carries a stale +// S3 endpoint. A forced upgrade re-runs the lookups, so the gated templates +// materialise with the current endpoint. // // It deliberately does not create the objects itself: their bodies are // values-driven (endpoint, region, forcePathStyle, the Altinity strategy's @@ -317,8 +319,9 @@ func (g *DefaultObjectsGate) checkAndLog(ctx context.Context, logger logr.Logger } // forcedReleaseFor reports which release renders the given missing set, for -// logging only. reconcileCredentials returns the credentials Secret as the -// sole missing object, and it is never mixed with the routed objects — +// logging only. reconcileCredentials and staleCredentials return the +// credentials Secret as the sole entry, and it is never mixed with the routed +// objects — // resolving the bucket name is a precondition for checking those at all. func (g *DefaultObjectsGate) forcedReleaseFor(missing []string) types.NamespacedName { credsKey := fmt.Sprintf("Secret/%s", g.Config.SourceSecretName) @@ -329,9 +332,10 @@ func (g *DefaultObjectsGate) forcedReleaseFor(missing []string) types.Namespaced } // Check resolves the platform bucket name, verifies that every object the -// BackupClass routes to exists, and forces one Helm upgrade when any is -// missing. It returns the missing objects (formatted for logs) and whether -// a forced upgrade was issued on this call. +// BackupClass routes to exists and carries the current S3 endpoint, and +// forces one Helm upgrade when any is missing or stale. It returns those +// objects (formatted for logs) and whether a forced upgrade was issued on this +// call. // // While the source Secret is absent or carries no bucket name, the gate // cannot evaluate the routed objects — their templates gate on the same @@ -412,11 +416,16 @@ func (g *DefaultObjectsGate) Check(ctx context.Context) ([]string, bool, error) // its endpoint differs from the one in the COSI Secret it is rendered from, // comparing against what packages/system/bucket/templates/user-credentials.yaml // writes for it. The COSI Secret being absent (the BucketAccess is being -// re-granted) leaves nothing to compare against and is not staleness. +// re-granted) leaves nothing to compare against and is not staleness, and +// neither is a source Secret the bucket chart does not render: the COSI Secret +// itself (the projector accepts one) or one without the endpoint key. func (g *DefaultObjectsGate) staleCredentials(ctx context.Context, src *corev1.Secret) (string, error) { if g.CredentialsCOSISecretName == "" || g.CredentialsHelmRelease.Name == "" || g.CredentialsHelmRelease.Namespace == "" { return "", nil } + if _, ok := src.Data["endpoint"]; !ok || g.CredentialsCOSISecretName == g.Config.SourceSecretName { + return "", nil + } cosi := &corev1.Secret{} key := types.NamespacedName{Namespace: g.Config.SourceNamespace, Name: g.CredentialsCOSISecretName} if err := g.Client.Get(ctx, key, cosi); err != nil { @@ -446,13 +455,13 @@ func (g *DefaultObjectsGate) staleCredentials(ctx context.Context, src *corev1.S // renderedEndpointFor mirrors the "backupstrategy-controller.endpoint" helper // for a provisioned bucket: the credentials Secret's endpoint, trimmed, with // any scheme replaced by https://. It is the value the chart stamps as -// endpointAnnotation. An empty endpoint makes the helper fall back to -// backupStorage.endpoint, which the gate cannot see, so it returns "". +// endpointAnnotation. An absent or empty endpoint makes the helper fall back +// to backupStorage.endpoint, which the gate cannot see, so it returns "". func renderedEndpointFor(raw []byte) string { - host := strings.TrimSpace(string(raw)) - if host == "" { + if len(raw) == 0 { return "" } + host := strings.TrimSpace(string(raw)) return "https://" + strings.TrimPrefix(strings.TrimPrefix(host, "https://"), "http://") } @@ -511,7 +520,7 @@ func (g *DefaultObjectsGate) force(ctx context.Context, target types.NamespacedN // annotations would be ignored, so skip the patch entirely and // leave the force counter alone — a climbing counter must keep // meaning "the forced render is not producing the objects". - log.FromContext(ctx).Info("skipped forcing a suspended HelmRelease; missing default backup objects will not be repaired until it is resumed", + log.FromContext(ctx).Info("skipped forcing a suspended HelmRelease; missing or stale default backup objects will not be repaired until it is resumed", "helmRelease", target.String(), "missing", missing) *last = now return missing, false, nil diff --git a/internal/backupcontroller/default_objects_gate_test.go b/internal/backupcontroller/default_objects_gate_test.go index dc1c0c9f0..cff6187cd 100644 --- a/internal/backupcontroller/default_objects_gate_test.go +++ b/internal/backupcontroller/default_objects_gate_test.go @@ -1099,6 +1099,9 @@ func TestRenderedEndpointMatchesTheChart(t *testing.T) { // No endpoint in the Secret: the chart renders its values fallback, // which the gate cannot reproduce, so it compares nothing. {"", ""}, + // Present but blank: the helper's lookup sees a non-empty value and + // renders the bare scheme. + {"\n", "https://"}, } { if got := renderedEndpointFor([]byte(tc.in)); got != tc.want { t.Errorf("renderedEndpointFor(%q) = %q, want %q", tc.in, got, tc.want) @@ -1125,3 +1128,49 @@ func TestForcedReleaseForNamesTheStaleCredentialsRelease(t *testing.T) { } } } + +// TestCheckSkipsCredentialsComparisonWithoutDerivedSecret covers a +// systemSecretName the bucket chart does not render: the same name as the COSI +// Secret (the projector also reads a raw COSI Secret) or a Secret without the +// endpoint key. Comparing it would report it stale on every tick, or fail the +// check, and the missing objects would never be repaired. +func TestCheckSkipsCredentialsComparisonWithoutDerivedSecret(t *testing.T) { + for _, tc := range []struct { + name string + apply func(g *DefaultObjectsGate, src *corev1.Secret) + }{ + {"COSI Secret is the source", func(g *DefaultObjectsGate, src *corev1.Secret) { + g.CredentialsCOSISecretName = g.Config.SourceSecretName + src.Data["BucketInfo"] = cosiSecret("https://s3.new.example.com").Data["BucketInfo"] + }}, + {"source without endpoint", func(_ *DefaultObjectsGate, src *corev1.Secret) { + delete(src.Data, "endpoint") + }}, + } { + t.Run(tc.name, func(t *testing.T) { + src := sourceSecret("bucket-1a2b") + var objs []runtime.Object + for _, o := range allDefaultObjects() { + if u := o.(*unstructured.Unstructured); u.GetName() != "cozy-default-cnpg" { + objs = append(objs, u) + } + } + objs = append(objs, helmReleaseObject(), credentialsHelmReleaseObject()) + g, dyn := newGate(t, nil, objs...) + tc.apply(g, src) + g.Client = fake.NewClientBuilder().WithScheme(gateScheme()). + WithObjects(src, cosiSecret("https://s3.new.example.com"), cozyDefaultBackupClass()).Build() + + missing, forced, err := g.Check(context.Background()) + if err != nil { + t.Fatalf("Check: %v", err) + } + if !forced || len(missing) != 1 || missing[0] != "CNPG/cozy-default-cnpg" { + t.Fatalf("missing = %v, forced = %v; want the missing strategy repaired", missing, forced) + } + if ann := credentialsForceAnnotations(t, dyn); len(ann) != 0 { + t.Errorf("bucket release forced: %v", ann) + } + }) + } +} diff --git a/packages/system/backupstrategy-controller/templates/deployment.yaml b/packages/system/backupstrategy-controller/templates/deployment.yaml index adc09fa2a..1278bec8a 100644 --- a/packages/system/backupstrategy-controller/templates/deployment.yaml +++ b/packages/system/backupstrategy-controller/templates/deployment.yaml @@ -92,9 +92,11 @@ spec: # "-credentials" to its name). The COSI sidecar writes it once per # BucketAccess, so the gate compares the two endpoints and forces the # release when the credentials Secret lags behind. + {{- if hasSuffix "-credentials" .Values.backupStorage.systemSecretName }} - name: BACKUP_CREDENTIALS_COSI_SECRET_NAME value: {{ trimSuffix "-credentials" .Values.backupStorage.systemSecretName | quote }} {{- end }} + {{- end }} {{- if .Values.velero.bslEnabled }} - name: BACKUP_DEFAULT_OBJECTS_VELERO_NAMESPACE value: {{ .Values.velero.namespace | quote }} diff --git a/packages/system/backupstrategy-controller/tests/default_objects_gate_test.yaml b/packages/system/backupstrategy-controller/tests/default_objects_gate_test.yaml index ed616ce79..446bbdcfa 100644 --- a/packages/system/backupstrategy-controller/tests/default_objects_gate_test.yaml +++ b/packages/system/backupstrategy-controller/tests/default_objects_gate_test.yaml @@ -128,6 +128,19 @@ tests: name: BACKUP_CREDENTIALS_COSI_SECRET_NAME value: bucket-cozy-backups-system + # A systemSecretName that is not -credentials is not rendered by + # the bucket chart from a COSI Secret, so there is nothing to compare it to. + - it: "systemSecretName without the -credentials suffix: no COSI Secret to compare against" + template: templates/deployment.yaml + set: + backupStorage.systemSecretName: bucket-cozy-backups-system + asserts: + - notContains: + path: spec.template.spec.containers[0].env + any: true + content: + name: BACKUP_CREDENTIALS_COSI_SECRET_NAME + - it: "velero.bslEnabled=false: the BSL is not rendered, so the gate must not look for it" template: templates/deployment.yaml set: diff --git a/packages/system/backupstrategy-controller/values.yaml b/packages/system/backupstrategy-controller/values.yaml index cdca60ff8..740672a44 100644 --- a/packages/system/backupstrategy-controller/values.yaml +++ b/packages/system/backupstrategy-controller/values.yaml @@ -208,9 +208,9 @@ backupStorage: # release. The COSI Secret itself keeps the endpoint it was granted with, so # after a publishing.host change that endpoint follows only once the # BucketAccess is re-granted. Both are throttled, independently, and a no-op - # in the steady state. A suspended release is skipped rather than re-stamped forever. The - # gate does NOT create the objects itself: their bodies are values-driven - # and Helm stays their single owner. + # in the steady state. A suspended release is skipped rather than + # re-stamped forever. The gate does NOT create the objects itself: their + # bodies are values-driven and Helm stays their single owner. # # Turn this off only if you manage the default Strategy CRs out of band and # accept that a missed install-time render is never repaired. Watch From c0d081a6f67f10f829719b5552271737bd77cd3a Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Wed, 4 Nov 2026 19:31:46 +0300 Subject: [PATCH 3/8] fix(backups): keep repairing missing default objects while credentials lag The credentials comparison returned early when the credentials Secret was stale or the COSI Secret could not be read, so a missing default Strategy or BSL was no longer created on that tick, nor on any later one while the bucket release stayed suspended, kept failing, or the COSI Secret stayed unreadable. Repairing missing objects is what the gate did before the comparison existed, and it does not depend on the answer. Run the object check on every tick and force each release for what it renders, reporting a comparison error alongside instead of in place of the repair. Assisted-by: LLM Signed-off-by: Alexey Artamonov (cherry picked from commit ef7626a951a84e084b32efe539c4b9059e1229e9) Signed-off-by: Myasnikov Daniil --- .../backupcontroller/default_objects_gate.go | 97 +++++++------ .../default_objects_gate_test.go | 131 ++++++++++++++++-- 2 files changed, 177 insertions(+), 51 deletions(-) diff --git a/internal/backupcontroller/default_objects_gate.go b/internal/backupcontroller/default_objects_gate.go index d0ed29954..8fb58c65e 100644 --- a/internal/backupcontroller/default_objects_gate.go +++ b/internal/backupcontroller/default_objects_gate.go @@ -194,10 +194,11 @@ type DefaultObjectsGate struct { // MinForceInterval for no reason. lastForce time.Time lastCredentialsForce time.Time - // renderForced records that a forced render of HelmRelease went through. - // That render stamps endpointAnnotation on every object the chart - // renders, so from then on an object without it (one rendered by a chart - // that predates the annotation) is not counted as stale again. + // renderForced records that a forced render of HelmRelease was requested + // (the annotations were patched; whether the upgrade succeeds is not + // observed). That render stamps endpointAnnotation on every object the + // chart renders, so from then on an object without it (one rendered by a + // chart that predates the annotation) is not counted as stale again. renderForced bool } @@ -302,33 +303,41 @@ func (g *DefaultObjectsGate) checkAndLog(ctx context.Context, logger logr.Logger // Info, not Error: every branch here is either transient (the // bucket is still being provisioned) or already exposed as a // metric, and this runs every minute for the life of the cluster. - logger.Info("default backup objects check failed", "error", err.Error()) + logger.Info("default backup objects check failed", "error", err.Error(), + "missing", missing, "forced", forced) case len(missing) > 0 && forced: - // The release named here is whichever one renders what is missing: + // The releases named here are the ones that render what is missing: // the credentials Secret comes from the bucket's -system // release, everything else from this chart's own. logger.Info("forced a Helm upgrade to create missing or stale default backup objects", - "helmRelease", g.forcedReleaseFor(missing).String(), "missing", missing) + "helmReleases", g.forcedReleasesFor(missing), "missing", missing) case len(missing) > 0: logger.Info("default backup objects still missing or stale, no force issued on this tick", - "helmRelease", g.forcedReleaseFor(missing).String(), "missing", missing, + "helmReleases", g.forcedReleasesFor(missing), "missing", missing, "minForceInterval", g.MinForceInterval.String()) default: logger.V(1).Info("all default backup objects present") } } -// forcedReleaseFor reports which release renders the given missing set, for -// logging only. reconcileCredentials and staleCredentials return the -// credentials Secret as the sole entry, and it is never mixed with the routed -// objects — -// resolving the bucket name is a precondition for checking those at all. -func (g *DefaultObjectsGate) forcedReleaseFor(missing []string) types.NamespacedName { +// forcedReleasesFor reports which releases render the given entries, for +// logging only: the credentials Secret comes from CredentialsHelmRelease, +// everything else from HelmRelease. +func (g *DefaultObjectsGate) forcedReleasesFor(missing []string) []string { credsKey := fmt.Sprintf("Secret/%s", g.Config.SourceSecretName) - if len(missing) == 1 && (missing[0] == credsKey || strings.HasPrefix(missing[0], credsKey+" ")) && g.CredentialsHelmRelease.Name != "" { - return g.CredentialsHelmRelease + var out []string + seen := map[string]bool{} + for _, m := range missing { + release := g.HelmRelease.String() + if (m == credsKey || strings.HasPrefix(m, credsKey+" ")) && g.CredentialsHelmRelease.Name != "" { + release = g.CredentialsHelmRelease.String() + } + if !seen[release] { + seen[release] = true + out = append(out, release) + } } - return g.HelmRelease + return out } // Check resolves the platform bucket name, verifies that every object the @@ -369,21 +378,17 @@ func (g *DefaultObjectsGate) Check(ctx context.Context) ([]string, bool, error) return g.reconcileCredentials(ctx) } - // The objects below are rendered from this Secret, so while it is stale - // they would only be re-rendered with the same stale endpoint. - stale, err := g.staleCredentials(ctx, src) - if err != nil { + staleCreds, credsErr := g.staleCredentials(ctx, src) + if credsErr != nil { defaultObjectsCheckErrors.WithLabelValues(g.BackupClassName).Inc() - return nil, false, err - } - if stale != "" { - return g.force(ctx, g.CredentialsHelmRelease, &g.lastCredentialsForce, []string{stale}) } backupClass := &backupsv1alpha1.BackupClass{} if err := g.Client.Get(ctx, client.ObjectKey{Name: g.BackupClassName}, backupClass); err != nil { - defaultObjectsCheckErrors.WithLabelValues(g.BackupClassName).Inc() - return nil, false, fmt.Errorf("get BackupClass %s: %w", g.BackupClassName, err) + if credsErr == nil { + defaultObjectsCheckErrors.WithLabelValues(g.BackupClassName).Inc() + } + return nil, false, errors.Join(credsErr, fmt.Errorf("get BackupClass %s: %w", g.BackupClassName, err)) } // With provisionBucket=false (no bucket release) the chart renders @@ -395,21 +400,33 @@ func (g *DefaultObjectsGate) Check(ctx context.Context) ([]string, bool, error) } state, err := g.inspectObjects(ctx, backupClass, want) if err != nil { - defaultObjectsCheckErrors.WithLabelValues(g.BackupClassName).Inc() - return nil, false, err + if credsErr == nil { + defaultObjectsCheckErrors.WithLabelValues(g.BackupClassName).Inc() + } + return nil, false, errors.Join(credsErr, err) } defaultObjectsMissing.WithLabelValues(g.BackupClassName).Set(float64(len(state.missing))) - needed := append(state.missing, state.stale...) - if len(needed) == 0 { - return nil, false, nil - } - sort.Strings(needed) - needed, forced, err := g.force(ctx, g.HelmRelease, &g.lastForce, needed) - if forced { - g.renderForced = true + var needed []string + var forced bool + errs := []error{credsErr} + if staleCreds != "" { + _, credsForced, err := g.force(ctx, g.CredentialsHelmRelease, &g.lastCredentialsForce, []string{staleCreds}) + needed = append(needed, staleCreds) + forced = credsForced + errs = append(errs, err) } - return needed, forced, err + if objects := append(state.missing, state.stale...); len(objects) > 0 { + sort.Strings(objects) + _, objectsForced, err := g.force(ctx, g.HelmRelease, &g.lastForce, objects) + needed = append(needed, objects...) + if objectsForced { + forced = true + g.renderForced = true + } + errs = append(errs, err) + } + return needed, forced, errors.Join(errs...) } // staleCredentials reports the credentials Secret, formatted for logs, when @@ -559,8 +576,8 @@ func (g *DefaultObjectsGate) staleEndpoint(state *defaultObjectsState, key strin // inspectObjects returns a sorted, de-duplicated list of the // "/" objects the BackupClass references that do not exist, -// plus the Velero BSL when a Velero namespace is configured, and the existing -// ones whose endpointAnnotation differs from want. +// plus the Velero BSL when a Velero namespace is configured, and, unsorted, +// the existing ones whose endpointAnnotation differs from want. // // An unmappable group/kind (the CRD is not installed) is NOT reported as // missing: no Helm re-render can create an object whose CRD is absent, and diff --git a/internal/backupcontroller/default_objects_gate_test.go b/internal/backupcontroller/default_objects_gate_test.go index cff6187cd..fac76e132 100644 --- a/internal/backupcontroller/default_objects_gate_test.go +++ b/internal/backupcontroller/default_objects_gate_test.go @@ -3,6 +3,7 @@ package backupcontroller import ( "context" "errors" + "slices" "strings" "testing" "time" @@ -1109,24 +1110,32 @@ func TestRenderedEndpointMatchesTheChart(t *testing.T) { } } -// TestForcedReleaseForNamesTheStaleCredentialsRelease pins the release the -// log line names: a stale credentials Secret is repaired by the bucket -// release, like a missing one, and everything else by this chart's own. -func TestForcedReleaseForNamesTheStaleCredentialsRelease(t *testing.T) { +// TestForcedReleasesForNamesEachRenderingRelease pins the releases the log +// line names: the credentials Secret, missing or stale, is repaired by the +// bucket release, everything else by this chart's own, and both are named when +// one check forced both. +func TestForcedReleasesForNamesEachRenderingRelease(t *testing.T) { g, _ := newGate(t, nil) + creds, own := g.CredentialsHelmRelease.String(), g.HelmRelease.String() for _, tc := range []struct { missing []string - want types.NamespacedName + want []string }{ - {[]string{"Secret/bucket-cozy-backups-system-credentials"}, g.CredentialsHelmRelease}, - {[]string{`Secret/bucket-cozy-backups-system-credentials (endpoint "s3.old", COSI Secret has "s3.new")`}, g.CredentialsHelmRelease}, - {[]string{"Secret/bucket-cozy-backups-system-credentials-other"}, g.HelmRelease}, - {[]string{`CNPG/cozy-default-cnpg (endpoint "https://s3.old", want "https://s3.new")`}, g.HelmRelease}, + {[]string{"Secret/bucket-cozy-backups-system-credentials"}, []string{creds}}, + {[]string{`Secret/bucket-cozy-backups-system-credentials (endpoint "s3.old", COSI Secret has "s3.new")`}, []string{creds}}, + {[]string{"Secret/bucket-cozy-backups-system-credentials-other"}, []string{own}}, + {[]string{`CNPG/cozy-default-cnpg (endpoint "https://s3.old", want "https://s3.new")`, "Etcd/cozy-default-etcd"}, []string{own}}, + {[]string{`Secret/bucket-cozy-backups-system-credentials (endpoint "s3.old", COSI Secret has "s3.new")`, "CNPG/cozy-default-cnpg"}, []string{creds, own}}, } { - if got := g.forcedReleaseFor(tc.missing); got != tc.want { - t.Errorf("forcedReleaseFor(%v) = %v, want %v", tc.missing, got, tc.want) + if got := g.forcedReleasesFor(tc.missing); !slices.Equal(got, tc.want) { + t.Errorf("forcedReleasesFor(%v) = %v, want %v", tc.missing, got, tc.want) } } + // External S3: no bucket release, so nothing but this chart's own. + g.CredentialsHelmRelease = types.NamespacedName{} + if got := g.forcedReleasesFor([]string{"Secret/bucket-cozy-backups-system-credentials"}); !slices.Equal(got, []string{own}) { + t.Errorf("forcedReleasesFor without a bucket release = %v, want [%s]", got, own) + } } // TestCheckSkipsCredentialsComparisonWithoutDerivedSecret covers a @@ -1174,3 +1183,103 @@ func TestCheckSkipsCredentialsComparisonWithoutDerivedSecret(t *testing.T) { }) } } + +// TestCheckRepairsMissingObjectsWhileCredentialsUnresolved pins that a stale +// or unreadable credentials comparison does not cost the repair of missing +// objects the gate made before it existed. The comparison only withholds the +// endpoint check, whose answer would be rendered from the same stale Secret. +func TestCheckRepairsMissingObjectsWhileCredentialsUnresolved(t *testing.T) { + malformed := cosiSecret("") + malformed.Data["BucketInfo"] = []byte("{not json") + for _, tc := range []struct { + name string + cosi *corev1.Secret + credsHR *unstructured.Unstructured + wantErr bool + wantCredsHRAt bool + }{ + {"stale credentials", cosiSecret("https://s3.new.example.com"), credentialsHelmReleaseObject(), false, true}, + {"stale credentials, bucket release suspended", cosiSecret("https://s3.new.example.com"), suspended(credentialsHelmReleaseObject()), false, false}, + {"malformed COSI Secret", malformed, credentialsHelmReleaseObject(), true, false}, + } { + t.Run(tc.name, func(t *testing.T) { + defaultObjectsCheckErrors.Reset() + defaultObjectsMissing.Reset() + var objs []runtime.Object + for _, o := range allDefaultObjects() { + if u := o.(*unstructured.Unstructured); u.GetName() != "cozy-default-cnpg" { + objs = append(objs, u) + } + } + objs = append(objs, helmReleaseObject(), tc.credsHR) + g, dyn := newGate(t, []client.Object{sourceSecret("bucket-1a2b"), tc.cosi, cozyDefaultBackupClass()}, objs...) + + missing, forced, err := g.Check(context.Background()) + if (err != nil) != tc.wantErr { + t.Fatalf("err = %v, want error %v", err, tc.wantErr) + } + if !forced { + t.Error("forced = false, want this chart's release forced for the missing strategy") + } + if ann := forceAnnotations(t, dyn); ann["reconcile.fluxcd.io/forceAt"] == "" { + t.Errorf("own HelmRelease not forced for a missing strategy: %v", ann) + } + if got := credentialsForceAnnotations(t, dyn)["reconcile.fluxcd.io/forceAt"] != ""; got != tc.wantCredsHRAt { + t.Errorf("bucket release forced = %v, want %v", got, tc.wantCredsHRAt) + } + found := false + for _, m := range missing { + found = found || m == "CNPG/cozy-default-cnpg" + } + if !found { + t.Errorf("missing = %v, want CNPG/cozy-default-cnpg reported", missing) + } + if got := testutil.ToFloat64(defaultObjectsMissing.WithLabelValues("cozy-default")); got != 1 { + t.Errorf("missing gauge = %v, want 1", got) + } + wantErrs := 0.0 + if tc.wantErr { + wantErrs = 1 + } + if got := testutil.ToFloat64(defaultObjectsCheckErrors.WithLabelValues("cozy-default")); got != wantErrs { + t.Errorf("check errors = %v, want %v", got, wantErrs) + } + }) + } +} + +// TestCheckCountsOneErrorPerCheck pins that a check failing in two places is +// still one check that did not reach a conclusion. +func TestCheckCountsOneErrorPerCheck(t *testing.T) { + defaultObjectsCheckErrors.Reset() + bad := cosiSecret("") + bad.Data["BucketInfo"] = []byte("{not json") + g, _ := newGate(t, []client.Object{sourceSecret("bucket-1a2b"), bad}, helmReleaseObject(), credentialsHelmReleaseObject()) + + if _, _, err := g.Check(context.Background()); err == nil { + t.Fatal("Check succeeded with a malformed COSI Secret and no BackupClass") + } + if got := testutil.ToFloat64(defaultObjectsCheckErrors.WithLabelValues("cozy-default")); got != 1 { + t.Fatalf("check errors = %v, want 1", got) + } +} + +// TestCheckSurfacesCredentialsPatchFailure pins that a failed force of the +// bucket release is reported, not recorded as done. +func TestCheckSurfacesCredentialsPatchFailure(t *testing.T) { + objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...) + g, dyn := newGate(t, + []client.Object{sourceSecret("bucket-1a2b"), cosiSecret("https://s3.new.example.com"), cozyDefaultBackupClass()}, + objs..., + ) + dyn.PrependReactor("patch", "helmreleases", func(k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, apierrors.NewForbidden(schema.GroupResource{Group: "helm.toolkit.fluxcd.io", Resource: "helmreleases"}, "bucket-cozy-backups-system", nil) + }) + + if _, forced, err := g.Check(context.Background()); err == nil || forced { + t.Fatalf("forced = %v, err = %v; want an error and forced=false", forced, err) + } + if !g.lastCredentialsForce.IsZero() { + t.Error("lastCredentialsForce advanced despite the patch failing") + } +} From f42825dac91cc4fa6a7614d60997896cadf909a0 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 5 Nov 2026 21:02:16 +0300 Subject: [PATCH 4/8] fix(backups): refresh stale credentials even when the routed objects are unreadable The credentials endpoint comparison needs only the credentials Secret and the COSI Secret it is rendered from, yet its forced render was issued only after the BackupClass and every routed object had been read. A missing BackupClass or one unreadable Strategy therefore kept the old endpoint in the credentials Secret, which the projector hands to every driver, not just the one whose object failed. Assisted-by: LLM Signed-off-by: Alexey Artamonov (cherry picked from commit 399ccd3f4aaf2c1f7d64fccc76173021104f0717) Signed-off-by: Myasnikov Daniil --- .../backupcontroller/default_objects_gate.go | 25 ++++++---- .../default_objects_gate_test.go | 50 +++++++++++++++++++ 2 files changed, 64 insertions(+), 11 deletions(-) diff --git a/internal/backupcontroller/default_objects_gate.go b/internal/backupcontroller/default_objects_gate.go index 8fb58c65e..b99f67b41 100644 --- a/internal/backupcontroller/default_objects_gate.go +++ b/internal/backupcontroller/default_objects_gate.go @@ -378,17 +378,29 @@ func (g *DefaultObjectsGate) Check(ctx context.Context) ([]string, bool, error) return g.reconcileCredentials(ctx) } + // The credentials comparison needs only the two Secrets, so its force goes + // out before the object reads: an unreadable BackupClass or Strategy must + // not keep the stale endpoint in the Secret every driver reads. + var needed []string + var forced bool staleCreds, credsErr := g.staleCredentials(ctx, src) + errs := []error{credsErr} if credsErr != nil { defaultObjectsCheckErrors.WithLabelValues(g.BackupClassName).Inc() } + if staleCreds != "" { + _, credsForced, err := g.force(ctx, g.CredentialsHelmRelease, &g.lastCredentialsForce, []string{staleCreds}) + needed = append(needed, staleCreds) + forced = credsForced + errs = append(errs, err) + } backupClass := &backupsv1alpha1.BackupClass{} if err := g.Client.Get(ctx, client.ObjectKey{Name: g.BackupClassName}, backupClass); err != nil { if credsErr == nil { defaultObjectsCheckErrors.WithLabelValues(g.BackupClassName).Inc() } - return nil, false, errors.Join(credsErr, fmt.Errorf("get BackupClass %s: %w", g.BackupClassName, err)) + return needed, forced, errors.Join(append(errs, fmt.Errorf("get BackupClass %s: %w", g.BackupClassName, err))...) } // With provisionBucket=false (no bucket release) the chart renders @@ -403,19 +415,10 @@ func (g *DefaultObjectsGate) Check(ctx context.Context) ([]string, bool, error) if credsErr == nil { defaultObjectsCheckErrors.WithLabelValues(g.BackupClassName).Inc() } - return nil, false, errors.Join(credsErr, err) + return needed, forced, errors.Join(append(errs, err)...) } defaultObjectsMissing.WithLabelValues(g.BackupClassName).Set(float64(len(state.missing))) - var needed []string - var forced bool - errs := []error{credsErr} - if staleCreds != "" { - _, credsForced, err := g.force(ctx, g.CredentialsHelmRelease, &g.lastCredentialsForce, []string{staleCreds}) - needed = append(needed, staleCreds) - forced = credsForced - errs = append(errs, err) - } if objects := append(state.missing, state.stale...); len(objects) > 0 { sort.Strings(objects) _, objectsForced, err := g.force(ctx, g.HelmRelease, &g.lastForce, objects) diff --git a/internal/backupcontroller/default_objects_gate_test.go b/internal/backupcontroller/default_objects_gate_test.go index fac76e132..befaedabe 100644 --- a/internal/backupcontroller/default_objects_gate_test.go +++ b/internal/backupcontroller/default_objects_gate_test.go @@ -1283,3 +1283,53 @@ func TestCheckSurfacesCredentialsPatchFailure(t *testing.T) { t.Error("lastCredentialsForce advanced despite the patch failing") } } + +// TestCheckForcesStaleCredentialsWhenObjectsUnreadable pins that the +// credentials comparison needs only the two Secrets: a BackupClass or a routed +// object the gate cannot read must not keep the stale endpoint in the +// credentials Secret, which every other driver reads through the projector. +func TestCheckForcesStaleCredentialsWhenObjectsUnreadable(t *testing.T) { + for _, tc := range []struct { + name string + backupClass bool + forbidCNPG bool + }{ + {"BackupClass absent", false, false}, + {"routed Strategy unreadable", true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + defaultObjectsCheckErrors.Reset() + ctrlObjs := []client.Object{sourceSecret("bucket-1a2b"), cosiSecret("https://s3.new.example.com")} + if tc.backupClass { + ctrlObjs = append(ctrlObjs, cozyDefaultBackupClass()) + } + objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...) + g, dyn := newGate(t, ctrlObjs, objs...) + if tc.forbidCNPG { + dyn.PrependReactor("get", "cnpgs", func(k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, apierrors.NewForbidden(schema.GroupResource{Group: strategyAPIGroup, Resource: "cnpgs"}, "cozy-default-cnpg", nil) + }) + } + + missing, forced, err := g.Check(context.Background()) + if err == nil { + t.Fatal("Check succeeded although the routed objects could not be evaluated") + } + if !forced { + t.Error("forced = false, want the bucket release forced for its stale credentials Secret") + } + if ann := credentialsForceAnnotations(t, dyn); ann["reconcile.fluxcd.io/forceAt"] == "" { + t.Errorf("bucket release not forced: %v", ann) + } + if ann := forceAnnotations(t, dyn); len(ann) != 0 { + t.Errorf("own HelmRelease forced without a conclusive object check: %v", ann) + } + if len(missing) != 1 || !strings.HasPrefix(missing[0], "Secret/bucket-cozy-backups-system-credentials") { + t.Errorf("missing = %v, want the credentials Secret", missing) + } + if got := testutil.ToFloat64(defaultObjectsCheckErrors.WithLabelValues("cozy-default")); got != 1 { + t.Errorf("check errors = %v, want 1", got) + } + }) + } +} From ddb0d52d51208e0999c832e73bf530fcb0861a50 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 5 Nov 2026 21:02:51 +0300 Subject: [PATCH 5/8] fix(backups): leave the credentials Secret alone when BucketInfo has no endpoint A BucketInfo without an endpoint differs from every credentials Secret that has one, so the gate forced the bucket release on every throttle window. That render cannot converge: an empty endpoint would be written into the Secret every driver reads, and with the key absent the template's trimPrefix fails and parks the release in Failed. Assisted-by: LLM Signed-off-by: Alexey Artamonov (cherry picked from commit bd2b6c4b49ece9741db01d3013bbe6f8f837d3de) Signed-off-by: Myasnikov Daniil --- internal/backupcontroller/default_objects_gate.go | 6 ++++-- internal/backupcontroller/default_objects_gate_test.go | 4 ++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/internal/backupcontroller/default_objects_gate.go b/internal/backupcontroller/default_objects_gate.go index b99f67b41..9b6fc0ede 100644 --- a/internal/backupcontroller/default_objects_gate.go +++ b/internal/backupcontroller/default_objects_gate.go @@ -438,7 +438,9 @@ func (g *DefaultObjectsGate) Check(ctx context.Context) ([]string, bool, error) // writes for it. The COSI Secret being absent (the BucketAccess is being // re-granted) leaves nothing to compare against and is not staleness, and // neither is a source Secret the bucket chart does not render: the COSI Secret -// itself (the projector accepts one) or one without the endpoint key. +// itself (the projector accepts one) or one without the endpoint key. A +// BucketInfo without an endpoint is not a target either: rendering from it +// writes an empty endpoint, or fails the release when the key is absent. func (g *DefaultObjectsGate) staleCredentials(ctx context.Context, src *corev1.Secret) (string, error) { if g.CredentialsCOSISecretName == "" || g.CredentialsHelmRelease.Name == "" || g.CredentialsHelmRelease.Namespace == "" { return "", nil @@ -466,7 +468,7 @@ func (g *DefaultObjectsGate) staleCredentials(ctx context.Context, src *corev1.S } want := strings.TrimPrefix(strings.TrimPrefix(info.Spec.SecretS3.Endpoint, "https://"), "http://") have := string(src.Data["endpoint"]) - if have == want { + if want == "" || have == want { return "", nil } return fmt.Sprintf("Secret/%s (endpoint %q, COSI Secret has %q)", g.Config.SourceSecretName, have, want), nil diff --git a/internal/backupcontroller/default_objects_gate_test.go b/internal/backupcontroller/default_objects_gate_test.go index befaedabe..bed60053f 100644 --- a/internal/backupcontroller/default_objects_gate_test.go +++ b/internal/backupcontroller/default_objects_gate_test.go @@ -851,6 +851,10 @@ func TestCheckCredentialsEndpointComparison(t *testing.T) { {"bare host", "s3.example.com", false}, {"other host", "https://s3.new.example.com", true}, {"other port", "https://s3.example.com:8443", true}, + // A forced render from a BucketInfo with no endpoint would write an + // empty endpoint into the Secret every driver reads (or, with the key + // absent, fail the bucket release's render), never a working one. + {"no endpoint in BucketInfo", "", false}, } { t.Run(tc.name, func(t *testing.T) { objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...) From b972a60f939dcff312b337aa2c1c1afaddb43f79 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 5 Nov 2026 21:03:16 +0300 Subject: [PATCH 6/8] fix(backups): compare the credentials endpoint only for the forced bucket's Secret The gate forces bucket--system, which renders the credentials Secret of that bucket's system user and nothing else. The COSI Secret name was derived from systemSecretName instead, so a value naming another bucket's Secret made a lagging endpoint there force the platform bucket release every throttle window without ever refreshing the Secret that was compared. Assisted-by: LLM Signed-off-by: Alexey Artamonov (cherry picked from commit dc909c778c8585c5acb4cadcd456fa4a0d13d5cd) Signed-off-by: Myasnikov Daniil --- .../templates/deployment.yaml | 9 ++++++--- .../tests/default_objects_gate_test.yaml | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/packages/system/backupstrategy-controller/templates/deployment.yaml b/packages/system/backupstrategy-controller/templates/deployment.yaml index 1278bec8a..887b7e64e 100644 --- a/packages/system/backupstrategy-controller/templates/deployment.yaml +++ b/packages/system/backupstrategy-controller/templates/deployment.yaml @@ -91,10 +91,13 @@ spec: # (packages/system/bucket/templates/user-credentials.yaml appends # "-credentials" to its name). The COSI sidecar writes it once per # BucketAccess, so the gate compares the two endpoints and forces the - # release when the credentials Secret lags behind. - {{- if hasSuffix "-credentials" .Values.backupStorage.systemSecretName }} + # release when the credentials Secret lags behind. Only the system + # user's Secret of this very bucket is rendered by that release; any + # other systemSecretName would be forced without ever changing. + {{- $cosiSecretName := printf "bucket-%s-system" .Values.backupStorage.bucketName }} + {{- if eq .Values.backupStorage.systemSecretName (printf "%s-credentials" $cosiSecretName) }} - name: BACKUP_CREDENTIALS_COSI_SECRET_NAME - value: {{ trimSuffix "-credentials" .Values.backupStorage.systemSecretName | quote }} + value: {{ $cosiSecretName | quote }} {{- end }} {{- end }} {{- if .Values.velero.bslEnabled }} diff --git a/packages/system/backupstrategy-controller/tests/default_objects_gate_test.yaml b/packages/system/backupstrategy-controller/tests/default_objects_gate_test.yaml index 446bbdcfa..a222d66ee 100644 --- a/packages/system/backupstrategy-controller/tests/default_objects_gate_test.yaml +++ b/packages/system/backupstrategy-controller/tests/default_objects_gate_test.yaml @@ -141,6 +141,21 @@ tests: content: name: BACKUP_CREDENTIALS_COSI_SECRET_NAME + # The forced release renders only -credentials for its own system + # user. A systemSecretName naming another bucket's Secret is not refreshed by + # forcing bucket--system, so comparing it would force that + # release every MinForceInterval and change nothing. + - it: "systemSecretName of another bucket: no COSI Secret to compare against" + template: templates/deployment.yaml + set: + backupStorage.systemSecretName: bucket-other-system-credentials + asserts: + - notContains: + path: spec.template.spec.containers[0].env + any: true + content: + name: BACKUP_CREDENTIALS_COSI_SECRET_NAME + - it: "velero.bslEnabled=false: the BSL is not rendered, so the gate must not look for it" template: templates/deployment.yaml set: From 0ce4aa69004a770a35b710724206ae4e03644305 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 5 Nov 2026 21:04:25 +0300 Subject: [PATCH 7/8] fix(backups): keep forcing objects that still lack the endpoint annotation An object without backups.cozystack.io/endpoint stopped counting as stale as soon as one forced render had been requested, whether or not that render succeeded. A failed upgrade left the objects unannotated and the gate silent until the controller restarted, which also hid the climbing force counter meant to report exactly that failure. Such an object now stays stale until a render stamps it; MinForceInterval already bounds the cost. Assisted-by: LLM Signed-off-by: Alexey Artamonov (cherry picked from commit ee5e51ee6ce272302bc47932ba58eadb4c7c6dc0) Signed-off-by: Myasnikov Daniil --- hack/backupstrategy-crd-gate.bats | 6 +-- .../backupcontroller/default_objects_gate.go | 19 +++------- .../default_objects_gate_test.go | 38 ++++++------------- 3 files changed, 19 insertions(+), 44 deletions(-) diff --git a/hack/backupstrategy-crd-gate.bats b/hack/backupstrategy-crd-gate.bats index 0f68a1ca4..fac48f35e 100644 --- a/hack/backupstrategy-crd-gate.bats +++ b/hack/backupstrategy-crd-gate.bats @@ -137,9 +137,9 @@ $tpl: $obj does not gate on crdEstablished for $crd" # The controller's DefaultObjectsGate tells an object rendered with a stale S3 # endpoint (publishing.host changed after the render) by the # backups.cozystack.io/endpoint annotation, because the endpoint itself sits at -# a different path in every kind. An object the chart renders without it is -# forced once and then never compared again, so a new template that forgets it -# would silently keep a stale endpoint. +# a different path in every kind. An object the chart renders without it +# counts as stale on every check, so a new template that forgets it would +# force this release every MinForceInterval forever. @test "every rendered Strategy CR and the Velero BSL carry the rendered endpoint annotation" { tmp=$(mktemp -d) diff --git a/internal/backupcontroller/default_objects_gate.go b/internal/backupcontroller/default_objects_gate.go index 9b6fc0ede..9aea96f31 100644 --- a/internal/backupcontroller/default_objects_gate.go +++ b/internal/backupcontroller/default_objects_gate.go @@ -194,12 +194,6 @@ type DefaultObjectsGate struct { // MinForceInterval for no reason. lastForce time.Time lastCredentialsForce time.Time - // renderForced records that a forced render of HelmRelease was requested - // (the annotations were patched; whether the upgrade succeeds is not - // observed). That render stamps endpointAnnotation on every object the - // chart renders, so from then on an object without it (one rendered by a - // chart that predates the annotation) is not counted as stale again. - renderForced bool } // errHelmReleaseSuspended reports that the target release has @@ -423,10 +417,7 @@ func (g *DefaultObjectsGate) Check(ctx context.Context) ([]string, bool, error) sort.Strings(objects) _, objectsForced, err := g.force(ctx, g.HelmRelease, &g.lastForce, objects) needed = append(needed, objects...) - if objectsForced { - forced = true - g.renderForced = true - } + forced = forced || objectsForced errs = append(errs, err) } return needed, forced, errors.Join(errs...) @@ -563,7 +554,9 @@ type defaultObjectsState struct { } // staleEndpoint reports an existing object rendered with another endpoint -// than want, formatted for logs. An empty want disables the comparison. +// than want, formatted for logs. An empty want disables the comparison. An +// object without the annotation (rendered by a chart that predates it) stays +// stale until a render stamps it: requesting one does not prove it landed. func (g *DefaultObjectsGate) staleEndpoint(state *defaultObjectsState, key string, obj *unstructured.Unstructured, want string) { if want == "" { return @@ -571,9 +564,7 @@ func (g *DefaultObjectsGate) staleEndpoint(state *defaultObjectsState, key strin have, ok := obj.GetAnnotations()[endpointAnnotation] switch { case !ok: - if !g.renderForced { - state.stale = append(state.stale, key+" (no endpoint annotation)") - } + state.stale = append(state.stale, key+" (no endpoint annotation)") case have != want: state.stale = append(state.stale, fmt.Sprintf("%s (endpoint %q, want %q)", key, have, want)) } diff --git a/internal/backupcontroller/default_objects_gate_test.go b/internal/backupcontroller/default_objects_gate_test.go index bed60053f..e287c9872 100644 --- a/internal/backupcontroller/default_objects_gate_test.go +++ b/internal/backupcontroller/default_objects_gate_test.go @@ -1037,13 +1037,13 @@ func TestCheckIgnoresObjectEndpointWithoutSecretEndpoint(t *testing.T) { } } -// TestCheckForcesOnceForUnannotatedObjects covers objects rendered by a chart -// that predates the endpoint annotation. Their endpoint is unknown, so they -// are treated as stale until one forced render has gone through, which stamps -// the annotation. A force that did not go through (throttled) does not count, -// and once one has, an object still without the annotation (one the chart -// does not render) must not force again every MinForceInterval. -func TestCheckForcesOnceForUnannotatedObjects(t *testing.T) { +// TestCheckKeepsForcingForUnannotatedObjects covers objects rendered by a +// chart that predates the endpoint annotation. Their endpoint is unknown, so +// they count as stale until a render stamps the annotation. Having requested +// a render proves nothing: one that failed leaves them unannotated, and the +// next unthrottled check must force again rather than fall silent, so the +// force counter keeps reporting the render that does not land. +func TestCheckKeepsForcingForUnannotatedObjects(t *testing.T) { base := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) objs := []runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()} for _, o := range allDefaultObjects() { @@ -1065,27 +1065,11 @@ func TestCheckForcesOnceForUnannotatedObjects(t *testing.T) { g.now = func() time.Time { return base.Add(time.Hour) } missing, forced, err := g.Check(context.Background()) - if err != nil || forced || len(missing) != 0 { - t.Fatalf("after the forced render: missing = %v, forced = %v, err = %v; want a no-op", missing, forced, err) + if err != nil || !forced || len(missing) != 7 { + t.Fatalf("after a render that left them unannotated: missing = %v, forced = %v, err = %v; want 7 reported and forced again", missing, forced, err) } - if again := forceAnnotations(t, dyn)["reconcile.fluxcd.io/forceAt"]; again != first { - t.Errorf("forced again for unannotated objects: %q, then %q", first, again) - } -} - -// TestCheckStillForcesStaleAfterUnannotatedForce pins that the once-only -// treatment covers the missing annotation alone: an annotation that names the -// wrong endpoint still forces after that. -func TestCheckStillForcesStaleAfterUnannotatedForce(t *testing.T) { - objs := []runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()} - for _, o := range allDefaultObjects() { - objs = append(objs, withEndpoint(o.(*unstructured.Unstructured), "https://s3.old.example.com")) - } - g, _ := newGate(t, []client.Object{sourceSecret("bucket-1a2b"), cozyDefaultBackupClass()}, objs...) - g.renderForced = true - - if _, forced, err := g.Check(context.Background()); err != nil || !forced { - t.Fatalf("forced = %v, err = %v; want forced", forced, err) + if again := forceAnnotations(t, dyn)["reconcile.fluxcd.io/forceAt"]; again == first { + t.Errorf("not forced again for unannotated objects: forceAt still %q", first) } } From 490eab5b9aba6f677fdd561af954ac3726d67801 Mon Sep 17 00:00:00 2001 From: Alexey Artamonov Date: Thu, 5 Nov 2026 21:14:32 +0300 Subject: [PATCH 8/8] docs(backups): state when the gate compares endpoints in the values reference The values reference read as if the credentials endpoint were always compared and an object without the endpoint annotation never forced a render. Operators sizing the force counter or choosing a custom systemSecretName need both conditions spelled out. Assisted-by: LLM Signed-off-by: Alexey Artamonov (cherry picked from commit c6c107fd08fd62e3b48ef8f905c4e299ff25cf00) Signed-off-by: Myasnikov Daniil --- packages/system/backupstrategy-controller/values.yaml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/system/backupstrategy-controller/values.yaml b/packages/system/backupstrategy-controller/values.yaml index 740672a44..ad3dfd001 100644 --- a/packages/system/backupstrategy-controller/values.yaml +++ b/packages/system/backupstrategy-controller/values.yaml @@ -202,10 +202,12 @@ backupStorage: # cozy-default routes to exists and forces THIS release when any is # missing. It repairs a stale S3 endpoint the same way: when the # credentials Secret's endpoint differs from the COSI Secret it is rendered - # from it forces the bucket's -system release, and when the + # from it forces the bucket's -system release (only while + # systemSecretName is bucket--system-credentials, the one + # Secret that release renders), and when the # backups.cozystack.io/endpoint annotation on the Velero BSL or a default - # Strategy differs from the credentials Secret's endpoint it forces THIS - # release. The COSI Secret itself keeps the endpoint it was granted with, so + # Strategy differs from the credentials Secret's endpoint, or is absent, it + # forces THIS release. The COSI Secret itself keeps the endpoint it was granted with, so # after a publishing.host change that endpoint follows only once the # BucketAccess is re-granted. Both are throttled, independently, and a no-op # in the steady state. A suspended release is skipped rather than