Skip to content

Commit 0b0cae6

Browse files
committed
fix(registry): keep backend status codes on aggregated write errors
Rebuild the backing StatusError with prefixed context instead of flattening it through fmt.Errorf, so typed rejections keep their code and reason on the wire. Read the delete target through the direct client to keep the dry-run prospective result off the cache, and cover the remaining dryRunDeleteResult branches. Signed-off-by: Yan Bondarenko <[email protected]>
1 parent cb9c576 commit 0b0cae6

5 files changed

Lines changed: 157 additions & 8 deletions

File tree

‎pkg/registry/apps/application/rest.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation
245245
err = r.c.Create(ctx, helmRelease, registry.ClientCreateOptions(options))
246246
if err != nil {
247247
klog.Errorf("Failed to create HelmRelease %s: %v", helmRelease.Name, err)
248-
return nil, fmt.Errorf("failed to create HelmRelease: %v", err)
248+
return nil, registry.WrapPreservingStatus("failed to create HelmRelease", err)
249249
}
250250

251251
// Convert the created HelmRelease back to Application
@@ -565,7 +565,7 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje
565565
// over from it below.
566566
cur := &helmv2.HelmRelease{}
567567
if err := r.c.Get(ctx, client.ObjectKey{Namespace: helmRelease.Namespace, Name: helmRelease.Name}, cur, &client.GetOptions{Raw: &metav1.GetOptions{}}); err != nil {
568-
return nil, false, fmt.Errorf("failed to fetch current HelmRelease: %w", err)
568+
return nil, false, registry.WrapPreservingStatus("failed to fetch current HelmRelease", err)
569569
}
570570
if helmRelease.ResourceVersion == "" {
571571
helmRelease.SetResourceVersion(cur.GetResourceVersion())
@@ -618,7 +618,7 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje
618618
})
619619
if err != nil {
620620
klog.Errorf("Failed to update HelmRelease %s: %v", helmRelease.Name, err)
621-
return nil, false, fmt.Errorf("failed to update HelmRelease: %v", err)
621+
return nil, false, registry.WrapPreservingStatus("failed to update HelmRelease", err)
622622
}
623623

624624
// Convert the updated HelmRelease back to Application
@@ -691,7 +691,7 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va
691691
err = r.c.Delete(ctx, helmRelease, registry.ClientDeleteOptions(options))
692692
if err != nil {
693693
klog.Errorf("Failed to delete HelmRelease %s: %v", helmReleaseName, err)
694-
return nil, false, fmt.Errorf("failed to delete HelmRelease: %w", err)
694+
return nil, false, registry.WrapPreservingStatus("failed to delete HelmRelease", err)
695695
}
696696

697697
klog.V(6).Infof("Successfully deleted HelmRelease %s", helmReleaseName)

‎pkg/registry/apps/application/rest_write_options_test.go‎

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ package application
1919
import (
2020
"context"
2121
"fmt"
22+
"net/http"
2223
"reflect"
24+
"strings"
2325
"testing"
2426

2527
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
@@ -29,6 +31,7 @@ import (
2931
"k8s.io/apimachinery/pkg/runtime"
3032
"k8s.io/apimachinery/pkg/runtime/schema"
3133
"k8s.io/apimachinery/pkg/types"
34+
"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters"
3235
"k8s.io/apiserver/pkg/endpoints/request"
3336
"k8s.io/apiserver/pkg/registry/rest"
3437
"sigs.k8s.io/controller-runtime/pkg/client"
@@ -206,6 +209,58 @@ func TestDeletePropagatesWriteOptions(t *testing.T) {
206209
}
207210
}
208211

212+
// assertWireStatus checks the answer the aggregated endpoint would put on the
213+
// wire: ErrorToAPIStatus type-switches on the APIStatus interface and never
214+
// unwraps, so a merely fmt.Errorf-wrapped backend rejection collapses to a
215+
// generic 500 with an empty reason even while errors.Is/As still succeed.
216+
func assertWireStatus(t *testing.T, err error, wantCode int32, wantReason metav1.StatusReason, wantContext string) {
217+
t.Helper()
218+
status := responsewriters.ErrorToAPIStatus(err)
219+
if status.Code != wantCode || status.Reason != wantReason {
220+
t.Fatalf("wire status = %d %q, want %d %q (err: %v)", status.Code, status.Reason, wantCode, wantReason, err)
221+
}
222+
if !strings.Contains(status.Message, wantContext) {
223+
t.Fatalf("wire message %q lost the %q context", status.Message, wantContext)
224+
}
225+
}
226+
227+
func TestCreatePreservesBackendStatus(t *testing.T) {
228+
alreadyExists := apierrors.NewAlreadyExists(
229+
schema.GroupResource{Group: helmv2.GroupVersion.Group, Resource: "helmreleases"},
230+
"postgresql-example",
231+
)
232+
r := newOptionsTestREST(t, interceptor.Funcs{
233+
Create: func(_ context.Context, _ client.WithWatch, _ client.Object, _ ...client.CreateOption) error {
234+
return alreadyExists
235+
},
236+
})
237+
ctx := request.WithNamespace(context.Background(), optionsTestNamespace)
238+
_, err := r.Create(ctx, optionsTestApplication(), nil, &metav1.CreateOptions{})
239+
if !apierrors.IsAlreadyExists(err) {
240+
t.Fatalf("Create returned %v, want a preserved AlreadyExists", err)
241+
}
242+
assertWireStatus(t, err, http.StatusConflict, metav1.StatusReasonAlreadyExists, "failed to create HelmRelease")
243+
}
244+
245+
func TestUpdatePreservesBackendStatus(t *testing.T) {
246+
forbidden := apierrors.NewForbidden(
247+
schema.GroupResource{Group: helmv2.GroupVersion.Group, Resource: "helmreleases"},
248+
"postgresql-example",
249+
fmt.Errorf("rejected by admission policy"),
250+
)
251+
r := newOptionsTestREST(t, interceptor.Funcs{
252+
Update: func(_ context.Context, _ client.WithWatch, _ client.Object, _ ...client.UpdateOption) error {
253+
return forbidden
254+
},
255+
}, optionsTestHelmRelease())
256+
ctx := request.WithNamespace(context.Background(), optionsTestNamespace)
257+
_, _, err := r.Update(ctx, "example", rest.DefaultUpdatedObjectInfo(optionsTestApplication()), nil, nil, false, &metav1.UpdateOptions{})
258+
if !apierrors.IsForbidden(err) {
259+
t.Fatalf("Update returned %v, want a preserved Forbidden", err)
260+
}
261+
assertWireStatus(t, err, http.StatusForbidden, metav1.StatusReasonForbidden, "failed to update HelmRelease")
262+
}
263+
209264
func TestDeletePreservesConflictError(t *testing.T) {
210265
conflict := apierrors.NewConflict(
211266
schema.GroupResource{Group: helmv2.GroupVersion.Group, Resource: "helmreleases"},
@@ -218,7 +273,9 @@ func TestDeletePreservesConflictError(t *testing.T) {
218273
},
219274
}, optionsTestHelmRelease())
220275
ctx := request.WithNamespace(context.Background(), optionsTestNamespace)
221-
if _, _, err := r.Delete(ctx, "example", nil, &metav1.DeleteOptions{}); !apierrors.IsConflict(err) {
276+
_, _, err := r.Delete(ctx, "example", nil, &metav1.DeleteOptions{})
277+
if !apierrors.IsConflict(err) {
222278
t.Fatalf("Delete returned %v, want a preserved Conflict", err)
223279
}
280+
assertWireStatus(t, err, http.StatusConflict, metav1.StatusReasonConflict, "failed to delete HelmRelease")
224281
}

‎pkg/registry/errors.go‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
Copyright 2026 The Cozystack Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package registry
18+
19+
import (
20+
"errors"
21+
"fmt"
22+
23+
apierrors "k8s.io/apimachinery/pkg/api/errors"
24+
)
25+
26+
// WrapPreservingStatus prefixes a backing API error with context while keeping
27+
// its machine-readable Status intact. The endpoint handlers resolve the wire
28+
// answer through ErrorToAPIStatus, which type-switches on the APIStatus
29+
// interface and never unwraps, so a fmt.Errorf-wrapped backend rejection
30+
// reaches the client as a generic 500 with an empty reason even though
31+
// errors.Is/As still see the cause. Rebuilding the StatusError keeps the
32+
// original code and reason (409 Conflict, 403 Forbidden, ...) on the wire.
33+
// Non-status errors fall back to plain wrapping.
34+
func WrapPreservingStatus(msg string, err error) error {
35+
var status apierrors.APIStatus
36+
if errors.As(err, &status) {
37+
st := status.Status()
38+
st.Message = fmt.Sprintf("%s: %s", msg, st.Message)
39+
return &apierrors.StatusError{ErrStatus: st}
40+
}
41+
return fmt.Errorf("%s: %w", msg, err)
42+
}

‎pkg/registry/sdn/securitygroup/rest.go‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -345,8 +345,12 @@ func dryRunDeleteResult(current *CiliumNetworkPolicy, opts *metav1.DeleteOptions
345345
}
346346
}
347347

348-
if opts != nil && opts.OrphanDependents != nil {
349-
if *opts.OrphanDependents {
348+
var orphanDependents *bool
349+
if opts != nil {
350+
orphanDependents = opts.OrphanDependents //nolint:staticcheck // SA1019: the apiserver still honours the deprecated field (shouldOrphanDependents), so the dry-run mirror reads it too.
351+
}
352+
if orphanDependents != nil {
353+
if *orphanDependents {
350354
finalizers = append(finalizers, metav1.FinalizerOrphanDependents)
351355
}
352356
} else if opts != nil && opts.PropagationPolicy != nil {
@@ -861,7 +865,11 @@ func (r *REST) Delete(
861865
return nil, false, err
862866
}
863867
current := &CiliumNetworkPolicy{}
864-
if err := r.c.Get(ctx, types.NamespacedName{Namespace: ns, Name: name}, current, &client.GetOptions{Raw: &metav1.GetOptions{}}); err != nil {
868+
// Read through the direct (uncached) client: the dry-run branch derives its
869+
// prospective result from this object, and a stale cache copy could
870+
// misreport the finalizer set - the same skew the post-delete read below
871+
// guards against.
872+
if err := r.w.Get(ctx, types.NamespacedName{Namespace: ns, Name: name}, current, &client.GetOptions{Raw: &metav1.GetOptions{}}); err != nil {
865873
return nil, false, err
866874
}
867875
if !isSecurityGroup(current) {

‎pkg/registry/sdn/securitygroup/rest_test.go‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -441,16 +441,30 @@ func TestDeleteDryRunReportsPolicyWithoutFinalizerAsInstant(t *testing.T) {
441441
if !deleted {
442442
t.Fatalf("dry-run Delete of a finalizer-less policy reported deleted=false; want true (instant)")
443443
}
444+
445+
// Explicitly disabled orphaning must not synthesize a finalizer either; the
446+
// dry-run object survives, so the same storage serves the second call.
447+
orphanDisabled := false
448+
//nolint:staticcheck // SA1019: the apiserver still honours the deprecated OrphanDependents, so the dry-run mirror is exercised with it.
449+
_, deleted, err = r.Delete(ctxNS(), "sg-db", nil, &metav1.DeleteOptions{DryRun: []string{metav1.DryRunAll}, OrphanDependents: &orphanDisabled})
450+
if err != nil {
451+
t.Fatalf("dry-run Delete with orphanDependents=false returned error: %v", err)
452+
}
453+
if !deleted {
454+
t.Fatalf("dry-run Delete with orphanDependents=false reported deleted=false; want true (instant)")
455+
}
444456
}
445457

446458
func TestDeleteDryRunReportsProspectiveAsyncState(t *testing.T) {
447459
foreground := metav1.DeletePropagationForeground
448460
orphan := metav1.DeletePropagationOrphan
461+
orphanDependents := true
449462
tests := []struct {
450463
name string
451464
initialFinalizers []string
452465
options *metav1.DeleteOptions
453466
wantFinalizer string
467+
absentFinalizer string
454468
}{
455469
{
456470
name: "existing membership finalizer",
@@ -468,6 +482,31 @@ func TestDeleteDryRunReportsProspectiveAsyncState(t *testing.T) {
468482
options: &metav1.DeleteOptions{DryRun: []string{metav1.DryRunAll}, PropagationPolicy: &orphan},
469483
wantFinalizer: metav1.FinalizerOrphanDependents,
470484
},
485+
{
486+
name: "explicit orphanDependents",
487+
//nolint:staticcheck // SA1019: the apiserver still honours the deprecated OrphanDependents, so the dry-run mirror is exercised with it.
488+
options: &metav1.DeleteOptions{DryRun: []string{metav1.DryRunAll}, OrphanDependents: &orphanDependents},
489+
wantFinalizer: metav1.FinalizerOrphanDependents,
490+
},
491+
{
492+
name: "pre-existing orphan finalizer preserved without explicit policy",
493+
initialFinalizers: []string{metav1.FinalizerOrphanDependents},
494+
options: &metav1.DeleteOptions{DryRun: []string{metav1.DryRunAll}},
495+
wantFinalizer: metav1.FinalizerOrphanDependents,
496+
},
497+
{
498+
name: "pre-existing foregroundDeletion finalizer preserved without explicit policy",
499+
initialFinalizers: []string{metav1.FinalizerDeleteDependents},
500+
options: &metav1.DeleteOptions{DryRun: []string{metav1.DryRunAll}},
501+
wantFinalizer: metav1.FinalizerDeleteDependents,
502+
},
503+
{
504+
name: "conflicting explicit policy replaces the pre-existing GC finalizer",
505+
initialFinalizers: []string{metav1.FinalizerOrphanDependents},
506+
options: &metav1.DeleteOptions{DryRun: []string{metav1.DryRunAll}, PropagationPolicy: &foreground},
507+
wantFinalizer: metav1.FinalizerDeleteDependents,
508+
absentFinalizer: metav1.FinalizerOrphanDependents,
509+
},
471510
}
472511

473512
for _, tt := range tests {
@@ -490,6 +529,9 @@ func TestDeleteDryRunReportsProspectiveAsyncState(t *testing.T) {
490529
if sg.DeletionTimestamp == nil || !hasFinalizer(sg.Finalizers, tt.wantFinalizer) {
491530
t.Fatalf("prospective result missing deletion state: timestamp=%v finalizers=%v", sg.DeletionTimestamp, sg.Finalizers)
492531
}
532+
if tt.absentFinalizer != "" && hasFinalizer(sg.Finalizers, tt.absentFinalizer) {
533+
t.Fatalf("prospective result kept the finalizer the explicit policy replaces: finalizers=%v", sg.Finalizers)
534+
}
493535

494536
stored := &CiliumNetworkPolicy{}
495537
if err := r.c.Get(context.Background(), types.NamespacedName{Namespace: testNamespace, Name: "sg-db"}, stored); err != nil {

0 commit comments

Comments
 (0)