Debian Codegraph @

pkg/apis/meta/fuzzer/fuzzer.go

raw
1 /*
2 Copyright 2017 The Kubernetes 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 fuzzer
18
19 import (
20 "fmt"
21 "math/rand"
22 "sort"
23 "strconv"
24 "strings"
25
26 "sigs.k8s.io/randfill"
27
28 apitesting "k8s.io/apimachinery/pkg/api/apitesting"
29 "k8s.io/apimachinery/pkg/api/apitesting/fuzzer"
30 "k8s.io/apimachinery/pkg/api/resource"
31 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
32 metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"
33 "k8s.io/apimachinery/pkg/runtime"
34 runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer"
35 "k8s.io/apimachinery/pkg/types"
36 "k8s.io/apimachinery/pkg/util/sets"
37 )
38
39 func genericFuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{} {
40 return []interface{}{
41 func(q *resource.Quantity, c randfill.Continue) {
42 *q = *resource.NewQuantity(c.Int63n(1000), resource.DecimalExponent)
43 },
44 func(j *int, c randfill.Continue) {
45 *j = int(c.Int31())
46 },
47 func(j **int, c randfill.Continue) {
48 if c.Bool() {
49 i := int(c.Int31())
50 *j = &i
51 } else {
52 *j = nil
53 }
54 },
55 func(j *runtime.TypeMeta, c randfill.Continue) {
56 // We have to customize the randomization of TypeMetas because their
57 // APIVersion and Kind must remain blank in memory.
58 j.APIVersion = ""
59 j.Kind = ""
60 },
61 func(j *runtime.Object, c randfill.Continue) {
62 // TODO: uncomment when round trip starts from a versioned object
63 if true { // c.Bool() {
64 *j = &runtime.Unknown{
65 // We do not set TypeMeta here because it is not carried through a round trip
66 Raw: []byte(`{"apiVersion":"unknown.group/unknown","kind":"Something","someKey":"someValue"}`),
67 ContentType: runtime.ContentTypeJSON,
68 }
69 } else {
70 types := []runtime.Object{&metav1.Status{}, &metav1.APIGroup{}}
71 t := types[c.Rand.Intn(len(types))]
72 c.Fill(t)
73 *j = t
74 }
75 },
76 func(r *runtime.RawExtension, c randfill.Continue) {
77 // Pick an arbitrary type and fuzz it
78 types := []runtime.Object{&metav1.Status{}, &metav1.APIGroup{}}
79 obj := types[c.Rand.Intn(len(types))]
80 c.Fill(obj)
81
82 // Find a codec for converting the object to raw bytes. This is necessary for the
83 // api version and kind to be correctly set be serialization.
84 var codec = apitesting.TestCodec(codecs, metav1.SchemeGroupVersion)
85
86 // Convert the object to raw bytes
87 bytes, err := runtime.Encode(codec, obj)
88 if err != nil {
89 panic(fmt.Sprintf("Failed to encode object: %v", err))
90 }
91
92 // strip trailing newlines which do not survive roundtrips
93 for len(bytes) >= 1 && bytes[len(bytes)-1] == 10 {
94 bytes = bytes[:len(bytes)-1]
95 }
96
97 // Set the bytes field on the RawExtension
98 r.Raw = bytes
99 },
100 }
101 }
102
103 // taken from randfill (nee gofuzz) internals for RandString
104 type charRange struct {
105 first, last rune
106 }
107
108 func (c *charRange) choose(r *rand.Rand) rune {
109 count := int64(c.last - c.first + 1)
110 ch := c.first + rune(r.Int63n(count))
111
112 return ch
113 }
114
115 // randomLabelPart produces a valid random label value or name-part
116 // of a label key.
117 func randomLabelPart(c randfill.Continue, canBeEmpty bool) string {
118 validStartEnd := []charRange{{'0', '9'}, {'a', 'z'}, {'A', 'Z'}}
119 validMiddle := []charRange{{'0', '9'}, {'a', 'z'}, {'A', 'Z'},
120 {'.', '.'}, {'-', '-'}, {'_', '_'}}
121
122 partLen := c.Rand.Intn(64) // len is [0, 63]
123 if !canBeEmpty {
124 partLen = c.Rand.Intn(63) + 1 // len is [1, 63]
125 }
126
127 runes := make([]rune, partLen)
128 if partLen == 0 {
129 return string(runes)
130 }
131
132 runes[0] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand)
133 for i := range runes[1:] {
134 runes[i+1] = validMiddle[c.Rand.Intn(len(validMiddle))].choose(c.Rand)
135 }
136 runes[len(runes)-1] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand)
137
138 return string(runes)
139 }
140
141 func randomDNSLabel(c randfill.Continue) string {
142 validStartEnd := []charRange{{'0', '9'}, {'a', 'z'}}
143 validMiddle := []charRange{{'0', '9'}, {'a', 'z'}, {'-', '-'}}
144
145 partLen := c.Rand.Intn(63) + 1 // len is [1, 63]
146 runes := make([]rune, partLen)
147
148 runes[0] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand)
149 for i := range runes[1:] {
150 runes[i+1] = validMiddle[c.Rand.Intn(len(validMiddle))].choose(c.Rand)
151 }
152 runes[len(runes)-1] = validStartEnd[c.Rand.Intn(len(validStartEnd))].choose(c.Rand)
153
154 return string(runes)
155 }
156
157 func randomLabelKey(c randfill.Continue) string {
158 namePart := randomLabelPart(c, false)
159 prefixPart := ""
160
161 usePrefix := c.Bool()
162 if usePrefix {
163 // we can fit, with dots, at most 3 labels in the 253 allotted characters
164 prefixPartsLen := c.Rand.Intn(2) + 1
165 prefixParts := make([]string, prefixPartsLen)
166 for i := range prefixParts {
167 prefixParts[i] = randomDNSLabel(c)
168 }
169 prefixPart = strings.Join(prefixParts, ".") + "/"
170 }
171
172 return prefixPart + namePart
173 }
174
175 func v1FuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{} {
176
177 return []interface{}{
178 func(j *metav1.TypeMeta, c randfill.Continue) {
179 // We have to customize the randomization of TypeMetas because their
180 // APIVersion and Kind must remain blank in memory.
181 j.APIVersion = ""
182 j.Kind = ""
183 },
184 func(j *metav1.ObjectMeta, c randfill.Continue) {
185 c.FillNoCustom(j)
186
187 j.ResourceVersion = strconv.FormatUint(c.Uint64(), 10)
188 j.UID = types.UID(c.String(0))
189
190 // Fuzzing sec and nsec in a smaller range (uint32 instead of int64),
191 // so that the result Unix time is a valid date and can be parsed into RFC3339 format.
192 var sec, nsec uint32
193 c.Fill(&sec)
194 c.Fill(&nsec)
195 j.CreationTimestamp = metav1.Unix(int64(sec), int64(nsec)).Rfc3339Copy()
196
197 if j.DeletionTimestamp != nil {
198 c.Fill(&sec)
199 c.Fill(&nsec)
200 t := metav1.Unix(int64(sec), int64(nsec)).Rfc3339Copy()
201 j.DeletionTimestamp = &t
202 }
203
204 if len(j.Labels) == 0 {
205 j.Labels = nil
206 } else {
207 delete(j.Labels, "")
208 }
209 if len(j.Annotations) == 0 {
210 j.Annotations = nil
211 } else {
212 delete(j.Annotations, "")
213 }
214 if len(j.OwnerReferences) == 0 {
215 j.OwnerReferences = nil
216 }
217 if len(j.Finalizers) == 0 {
218 j.Finalizers = nil
219 }
220 },
221 func(j *metav1.ResourceVersionMatch, c randfill.Continue) {
222 matches := []metav1.ResourceVersionMatch{"", metav1.ResourceVersionMatchExact, metav1.ResourceVersionMatchNotOlderThan}
223 *j = matches[c.Rand.Intn(len(matches))]
224 },
225 func(j *metav1.ListMeta, c randfill.Continue) {
226 j.ResourceVersion = strconv.FormatUint(c.Uint64(), 10)
227 j.SelfLink = c.String(0) //nolint:staticcheck // SA1019 backwards compatibility
228 },
229 func(j *metav1.LabelSelector, c randfill.Continue) {
230 c.FillNoCustom(j)
231 // we can't have an entirely empty selector, so force
232 // use of MatchExpression if necessary
233 if len(j.MatchLabels) == 0 && len(j.MatchExpressions) == 0 {
234 j.MatchExpressions = make([]metav1.LabelSelectorRequirement, c.Rand.Intn(2)+1)
235 }
236
237 if j.MatchLabels != nil {
238 fuzzedMatchLabels := make(map[string]string, len(j.MatchLabels))
239 for i := 0; i < len(j.MatchLabels); i++ {
240 fuzzedMatchLabels[randomLabelKey(c)] = randomLabelPart(c, true)
241 }
242 j.MatchLabels = fuzzedMatchLabels
243 }
244
245 validOperators := []metav1.LabelSelectorOperator{
246 metav1.LabelSelectorOpIn,
247 metav1.LabelSelectorOpNotIn,
248 metav1.LabelSelectorOpExists,
249 metav1.LabelSelectorOpDoesNotExist,
250 }
251
252 if j.MatchExpressions != nil {
253 // NB: the label selector parser code sorts match expressions by key, and
254 // sorts and deduplicates the values, so we need to make sure ours are
255 // sorted and deduplicated as well here to preserve round-trip comparison.
256 // In practice, not sorting doesn't hurt anything...
257
258 for i := range j.MatchExpressions {
259 req := metav1.LabelSelectorRequirement{}
260 c.Fill(&req)
261 req.Key = randomLabelKey(c)
262 req.Operator = validOperators[c.Rand.Intn(len(validOperators))]
263 if req.Operator == metav1.LabelSelectorOpIn || req.Operator == metav1.LabelSelectorOpNotIn {
264 if len(req.Values) == 0 {
265 // we must have some values here, so randomly choose a short length
266 req.Values = make([]string, c.Rand.Intn(2)+1)
267 }
268 for i := range req.Values {
269 req.Values[i] = randomLabelPart(c, true)
270 }
271 req.Values = sets.List(sets.New(req.Values...))
272 } else {
273 req.Values = nil
274 }
275 j.MatchExpressions[i] = req
276 }
277
278 sort.Slice(j.MatchExpressions, func(a, b int) bool { return j.MatchExpressions[a].Key < j.MatchExpressions[b].Key })
279 }
280 },
281 func(j *metav1.ManagedFieldsEntry, c randfill.Continue) {
282 c.FillNoCustom(j)
283 j.FieldsV1 = nil
284 },
285 }
286 }
287
288 func v1beta1FuzzerFuncs(codecs runtimeserializer.CodecFactory) []interface{} {
289 return []interface{}{
290 func(r *metav1beta1.TableOptions, c randfill.Continue) {
291 c.FillNoCustom(r)
292 // NoHeaders is not serialized to the wire but is allowed within the versioned
293 // type because we don't use meta internal types in the client and API server.
294 r.NoHeaders = false
295 },
296 func(r *metav1beta1.TableRow, c randfill.Continue) {
297 c.Fill(&r.Object)
298 c.Fill(&r.Conditions)
299 if len(r.Conditions) == 0 {
300 r.Conditions = nil
301 }
302 n := c.Intn(10)
303 if n > 0 {
304 r.Cells = make([]interface{}, n)
305 }
306 for i := range r.Cells {
307 t := c.Intn(6)
308 switch t {
309 case 0:
310 r.Cells[i] = c.String(0)
311 case 1:
312 r.Cells[i] = c.Int63()
313 case 2:
314 r.Cells[i] = c.Bool()
315 case 3:
316 x := map[string]interface{}{}
317 for j := c.Intn(10) + 1; j >= 0; j-- {
318 x[c.String(0)] = c.String(0)
319 }
320 r.Cells[i] = x
321 case 4:
322 x := make([]interface{}, c.Intn(10))
323 for i := range x {
324 x[i] = c.Int63()
325 }
326 r.Cells[i] = x
327 default:
328 r.Cells[i] = nil
329 }
330 }
331 },
332 }
333 }
334
335 var Funcs = fuzzer.MergeFuzzerFuncs(
336 genericFuzzerFuncs,
337 v1FuzzerFuncs,
338 v1beta1FuzzerFuncs,
339 )