File: corrupt_obj_deleter_test.go

package info (click to toggle)
golang-k8s-apiserver 0.33.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 11,660 kB
  • sloc: sh: 236; makefile: 5
file content (332 lines) | stat: -rw-r--r-- 10,767 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/*
Copyright 2024 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package registry

import (
	"context"
	"fmt"
	"strings"
	"testing"

	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apiserver/pkg/apis/example"
	genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
	"k8s.io/apiserver/pkg/registry/rest"
	"k8s.io/apiserver/pkg/storage"

	"k8s.io/utils/ptr"
)

type result struct {
	deleted bool
	err     error
}

type deleteWant struct {
	deleted  bool
	checkErr func(err error) bool
}

var (
	wantNoError     = func(err error) bool { return err == nil }
	wantErrContains = func(shouldContain string) func(error) bool {
		return func(err error) bool {
			return err != nil && strings.Contains(err.Error(), shouldContain)
		}
	}
)

func (w deleteWant) verify(t *testing.T, got result) {
	t.Helper()

	if !w.checkErr(got.err) {
		t.Errorf("Unexpected failure with the deletion operation, got: %v", got.err)
	}
	if w.deleted != got.deleted {
		t.Errorf("Expected deleted to be: %t, but got: %t", w.deleted, got.deleted)
	}

}

func TestUnsafeDeletePrecondition(t *testing.T) {
	option := func(enabled bool) *metav1.DeleteOptions {
		return &metav1.DeleteOptions{
			IgnoreStoreReadErrorWithClusterBreakingPotential: ptr.To[bool](enabled),
		}
	}

	const (
		unsafeDeleteNotAllowed = "ignoreStoreReadErrorWithClusterBreakingPotential: Invalid value: true: is exclusively used to delete corrupt object(s), try again by removing this option"
		internalErr            = "Internal error occurred: initialization error, expected normal deletion flow to be used"
	)

	tests := []struct {
		name    string
		err     error
		opts    *metav1.DeleteOptions
		invoked int
		want    deleteWant
	}{
		{
			name: "option nil, should throw internal error",
			opts: nil,
			want: deleteWant{checkErr: wantErrContains(internalErr)},
		},
		{
			name: "option empty, should throw internal error",
			opts: &metav1.DeleteOptions{},
			want: deleteWant{checkErr: wantErrContains(internalErr)},
		},
		{
			name: "option false, should throw internal error",
			opts: option(false),
			want: deleteWant{checkErr: wantErrContains(internalErr)},
		},
		{
			name: "option true, object readable, should throw invalid error",
			opts: option(true),
			want: deleteWant{
				checkErr: wantErrContains(unsafeDeleteNotAllowed),
			},
		},
		{
			name: "option true, object not readable with unexpected error, should throw invalid error",
			opts: option(true),
			err:  fmt.Errorf("unexpected error"),
			want: deleteWant{
				checkErr: wantErrContains(unsafeDeleteNotAllowed),
			},
		},
		{
			name: "option true, object not readable with storage internal error, should throw invalid error",
			opts: option(true),
			err:  storage.NewInternalError(fmt.Errorf("unexpected error")),
			want: deleteWant{
				checkErr: wantErrContains(unsafeDeleteNotAllowed),
			},
		},
		{
			name: "option true, object not readable with corrupt object error, unsafe-delete should trigger",
			opts: option(true),
			err:  storage.NewCorruptObjError("foo", fmt.Errorf("object not decodable")),
			want: deleteWant{
				deleted:  true,
				checkErr: wantNoError,
			},
			invoked: 1,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			ctx := genericapirequest.WithNamespace(genericapirequest.NewContext(), "test")
			destroyFunc, registry := NewTestGenericStoreRegistry(t)
			defer destroyFunc()

			object := &example.Pod{
				ObjectMeta: metav1.ObjectMeta{Name: "foo"},
				Spec:       example.PodSpec{NodeName: "machine"},
			}
			_, err := registry.Create(ctx, object, rest.ValidateAllObjectFunc, &metav1.CreateOptions{})
			if err != nil {
				t.Fatalf("Unexpected error from Create: %v", err)
			}

			// wrap the storage so it returns the expected error
			cs := &corruptStorage{
				Interface: registry.Storage.Storage,
				err:       test.err,
			}
			registry.Storage.Storage = cs
			deleter := NewCorruptObjectDeleter(registry)

			_, deleted, err := deleter.Delete(ctx, "foo", rest.ValidateAllObjectFunc, test.opts)

			got := result{deleted: deleted, err: err}
			test.want.verify(t, got)
			if want, got := test.invoked, cs.unsafeDeleteInvoked; want != got {
				t.Errorf("Expected unsafe-delete to be invoked %d time(s), but got: %d", want, got)
			}
		})
	}
}

func TestUnsafeDeleteWithCorruptObject(t *testing.T) {
	ctx := genericapirequest.WithNamespace(genericapirequest.NewContext(), "test")
	destroyFunc, registry := NewTestGenericStoreRegistry(t)
	defer destroyFunc()

	object := &example.Pod{
		ObjectMeta: metav1.ObjectMeta{Name: "foo"},
		Spec:       example.PodSpec{NodeName: "machine"},
	}
	// a) prerequisite: try deleting the object, we expect a not found error
	_, _, err := registry.Delete(ctx, object.Name, rest.ValidateAllObjectFunc, nil)
	if !errors.IsNotFound(err) {
		t.Errorf("Unexpected error: %v", err)
	}

	// b) create the target object
	_, err = registry.Create(ctx, object, rest.ValidateAllObjectFunc, &metav1.CreateOptions{})
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	// c) wrap the storage to return corrupt object error
	cs := &corruptStorage{
		Interface: registry.Storage.Storage,
		err:       storage.NewCorruptObjError("key", fmt.Errorf("untransformable")),
	}
	registry.Storage.Storage = cs

	got := result{}
	// d) try deleting the traget object
	_, got.deleted, got.err = registry.Delete(ctx, object.Name, rest.ValidateAllObjectFunc, nil)
	want := deleteWant{checkErr: errors.IsInternalError}
	want.verify(t, got)

	// e) set up an unsafe-deleter
	deleter := NewCorruptObjectDeleter(registry)

	// f) try to delete the object, but don't set the delete option just yet
	_, got.deleted, got.err = deleter.Delete(ctx, object.Name, rest.ValidateAllObjectFunc, nil)
	want.verify(t, got)

	// g) this time, set the delete option to ignore store read error
	_, got.deleted, got.err = deleter.Delete(ctx, object.Name, rest.ValidateAllObjectFunc, &metav1.DeleteOptions{
		IgnoreStoreReadErrorWithClusterBreakingPotential: ptr.To[bool](true),
	})
	want = deleteWant{
		deleted:  true,
		checkErr: wantNoError,
	}
	want.verify(t, got)
	if want, got := 1, cs.unsafeDeleteInvoked; want != got {
		t.Errorf("Expected unsafe-delete to be invoked %d time(s), but got: %d", want, got)
	}
}

func TestUnsafeDeleteWithUnexpectedError(t *testing.T) {
	ctx := genericapirequest.WithNamespace(genericapirequest.NewContext(), "test")
	// TODO: inject a corrupt transformer
	destroyFunc, registry := NewTestGenericStoreRegistry(t)
	defer destroyFunc()

	object := &example.Pod{
		ObjectMeta: metav1.ObjectMeta{Name: "foo"},
		Spec:       example.PodSpec{NodeName: "machine"},
	}
	// a) create the target object
	_, err := registry.Create(ctx, object, rest.ValidateAllObjectFunc, &metav1.CreateOptions{})
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	// b) wrap the storage to return corrupt object error
	cs := &corruptStorage{
		Interface: registry.Storage.Storage,
		err:       storage.NewInternalError(fmt.Errorf("unexpected error")),
	}
	registry.Storage.Storage = cs

	// c) try deleting the object using normal deletion flow
	got := result{}
	_, got.deleted, got.err = registry.Delete(ctx, object.Name, rest.ValidateAllObjectFunc, nil)
	want := deleteWant{checkErr: errors.IsInternalError}
	want.verify(t, got)

	// d) set up a corrupt object deleter for the registry
	deleter := NewCorruptObjectDeleter(registry)

	// e) try deleting with unsafe-delete
	_, got.deleted, got.err = deleter.Delete(ctx, object.Name, rest.ValidateAllObjectFunc, &metav1.DeleteOptions{
		IgnoreStoreReadErrorWithClusterBreakingPotential: ptr.To[bool](true),
	})
	want = deleteWant{
		checkErr: wantErrContains("is exclusively used to delete corrupt object(s), try again by removing this option"),
	}
	want.verify(t, got)
	if want, got := 0, cs.unsafeDeleteInvoked; want != got {
		t.Errorf("Expected unsafe-delete to be invoked %d time(s), but got: %d", want, got)
	}
}

func TestUnsafeDeleteWithAdmissionShouldBeSkipped(t *testing.T) {
	ctx := genericapirequest.WithNamespace(genericapirequest.NewContext(), "test")
	destroyFunc, registry := NewTestGenericStoreRegistry(t)
	defer destroyFunc()

	// a) create the target object
	object := &example.Pod{
		ObjectMeta: metav1.ObjectMeta{Name: "foo"},
		Spec:       example.PodSpec{NodeName: "machine"},
	}
	_, err := registry.Create(ctx, object, rest.ValidateAllObjectFunc, &metav1.CreateOptions{})
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	// b) wrap the storage layer to return corrupt object error
	registry.Storage.Storage = &corruptStorage{
		Interface: registry.Storage.Storage,
		err:       storage.NewCorruptObjError("key", fmt.Errorf("untransformable")),
	}

	// c) set up a corrupt object deleter for the registry
	deleter := NewCorruptObjectDeleter(registry)

	// d) try unsafe delete, but pass a validation that always fails
	var admissionInvoked int
	_, deleted, err := deleter.Delete(ctx, object.Name, func(_ context.Context, _ runtime.Object) error {
		admissionInvoked++
		return fmt.Errorf("admission was not skipped")
	}, &metav1.DeleteOptions{
		IgnoreStoreReadErrorWithClusterBreakingPotential: ptr.To[bool](true),
	})

	if err != nil {
		t.Errorf("Unexpected error from Delete: %v", err)
	}
	if want, got := true, deleted; want != got {
		t.Errorf("Expected deleted: %t, but got: %t", want, got)
	}
	if want, got := 0, admissionInvoked; want != got {
		t.Errorf("Expected admission to be invoked %d time(s), but got: %d", want, got)
	}
}

type corruptStorage struct {
	storage.Interface
	err                 error
	unsafeDeleteInvoked int
}

func (s *corruptStorage) Get(ctx context.Context, key string, opts storage.GetOptions, objPtr runtime.Object) error {
	if s.err != nil {
		return s.err
	}
	return s.Interface.Get(ctx, key, opts, objPtr)
}

func (s *corruptStorage) Delete(ctx context.Context, key string, out runtime.Object, preconditions *storage.Preconditions, deleteValidation storage.ValidateObjectFunc, cachedExistingObject runtime.Object, opts storage.DeleteOptions) error {
	if opts.IgnoreStoreReadError {
		s.unsafeDeleteInvoked++
	}
	return s.Interface.Delete(ctx, key, out, preconditions, deleteValidation, cachedExistingObject, opts)
}