Debian Codegraph @

pkg/cel/library/format.go

raw
1 /*
2 Copyright 2024 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 library
18
19 import (
20 "fmt"
21 "net/url"
22
23 "github.com/google/cel-go/cel"
24 "github.com/google/cel-go/common/decls"
25 "github.com/google/cel-go/common/types"
26 "github.com/google/cel-go/common/types/ref"
27
28 apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation"
29 "k8s.io/apimachinery/pkg/util/validation"
30 apiservercel "k8s.io/apiserver/pkg/cel"
31 "k8s.io/kube-openapi/pkg/validation/strfmt"
32 )
33
34 var (
35 // base64_length estimate for base64 regex size from github.com/asaskevich/govalidator
36 base64Length = 84
37 // url_length estimate for url regex size from github.com/asaskevich/govalidator
38 urlLength = 1103
39 )
40
41 // Format provides a CEL library exposing common named Kubernetes string
42 // validations. Can be used in CRD ValidationRules messageExpression.
43 //
44 // Example:
45 //
46 // rule: format.dns1123label.validate(object.metadata.name).hasValue()
47 // messageExpression: format.dns1123label.validate(object.metadata.name).value().join("\n")
48 //
49 // format.named(name: string) -> ?Format
50 //
51 // Returns the Format with the given name, if it exists. Otherwise, optional.none
52 // Allowed names are:
53 // - `dns1123Label`
54 // - `dns1123Subdomain`
55 // - `dns1035Label`
56 // - `qualifiedName`
57 // - `dns1123LabelPrefix`
58 // - `dns1123SubdomainPrefix`
59 // - `dns1035LabelPrefix`
60 // - `labelValue`
61 // - `uri`
62 // - `uuid`
63 // - `byte`
64 // - `date`
65 // - `datetime`
66 //
67 // format.<formatName>() -> Format
68 //
69 // Convenience functions for all the named formats are also available
70 //
71 // Examples:
72 // format.dns1123Label().validate("my-label-name")
73 // format.dns1123Subdomain().validate("apiextensions.k8s.io")
74 // format.dns1035Label().validate("my-label-name")
75 // format.qualifiedName().validate("apiextensions.k8s.io/v1beta1")
76 // format.dns1123LabelPrefix().validate("my-label-prefix-")
77 // format.dns1123SubdomainPrefix().validate("mysubdomain.prefix.-")
78 // format.dns1035LabelPrefix().validate("my-label-prefix-")
79 // format.uri().validate("http://example.com")
80 // Uses same pattern as isURL, but returns an error
81 // format.uuid().validate("123e4567-e89b-12d3-a456-426614174000")
82 // format.byte().validate("aGVsbG8=")
83 // format.date().validate("2021-01-01")
84 // format.datetime().validate("2021-01-01T00:00:00Z")
85 //
86
87 // <Format>.validate(str: string) -> ?list<string>
88 //
89 // Validates the given string against the given format. Returns optional.none
90 // if the string is valid, otherwise a list of validation error strings.
91 func Format() cel.EnvOption {
92 return cel.Lib(formatLib)
93 }
94
95 var formatLib = &format{}
96
97 type format struct{}
98
99 func (*format) LibraryName() string {
100 return "kubernetes.format"
101 }
102
103 func (*format) Types() []*cel.Type {
104 return []*cel.Type{apiservercel.FormatType}
105 }
106
107 func (*format) declarations() map[string][]cel.FunctionOpt {
108 return formatLibraryDecls
109 }
110
111 func ZeroArgumentFunctionBinding(binding func() ref.Val) decls.OverloadOpt {
112 return func(o *decls.OverloadDecl) (*decls.OverloadDecl, error) {
113 wrapped, err := decls.FunctionBinding(func(values ...ref.Val) ref.Val { return binding() })(o)
114 if err != nil {
115 return nil, err
116 }
117 if len(wrapped.ArgTypes()) != 0 {
118 return nil, fmt.Errorf("function binding must have 0 arguments")
119 }
120 return o, nil
121 }
122 }
123
124 func (*format) CompileOptions() []cel.EnvOption {
125 options := make([]cel.EnvOption, 0, len(formatLibraryDecls))
126 for name, overloads := range formatLibraryDecls {
127 options = append(options, cel.Function(name, overloads...))
128 }
129 for name, constantValue := range ConstantFormats {
130 prefixedName := "format." + name
131 options = append(options, cel.Function(prefixedName, cel.Overload(prefixedName, []*cel.Type{}, apiservercel.FormatType, ZeroArgumentFunctionBinding(func() ref.Val {
132 return constantValue
133 }))))
134 }
135 return options
136 }
137
138 func (*format) ProgramOptions() []cel.ProgramOption {
139 return []cel.ProgramOption{}
140 }
141
142 var ConstantFormats = map[string]apiservercel.Format{
143 "dns1123Label": {
144 Name: "DNS1123Label",
145 ValidateFunc: func(s string) []string { return apimachineryvalidation.NameIsDNSLabel(s, false) },
146 MaxRegexSize: 30,
147 },
148 "dns1123Subdomain": {
149 Name: "DNS1123Subdomain",
150 ValidateFunc: func(s string) []string { return apimachineryvalidation.NameIsDNSSubdomain(s, false) },
151 MaxRegexSize: 60,
152 },
153 "dns1035Label": {
154 Name: "DNS1035Label",
155 ValidateFunc: func(s string) []string { return apimachineryvalidation.NameIsDNS1035Label(s, false) },
156 MaxRegexSize: 30,
157 },
158 "qualifiedName": {
159 Name: "QualifiedName",
160 ValidateFunc: validation.IsQualifiedName,
161 MaxRegexSize: 60, // uses subdomain regex
162 },
163
164 "dns1123LabelPrefix": {
165 Name: "DNS1123LabelPrefix",
166 ValidateFunc: func(s string) []string { return apimachineryvalidation.NameIsDNSLabel(s, true) },
167 MaxRegexSize: 30,
168 },
169 "dns1123SubdomainPrefix": {
170 Name: "DNS1123SubdomainPrefix",
171 ValidateFunc: func(s string) []string { return apimachineryvalidation.NameIsDNSSubdomain(s, true) },
172 MaxRegexSize: 60,
173 },
174 "dns1035LabelPrefix": {
175 Name: "DNS1035LabelPrefix",
176 ValidateFunc: func(s string) []string { return apimachineryvalidation.NameIsDNS1035Label(s, true) },
177 MaxRegexSize: 30,
178 },
179 "labelValue": {
180 Name: "LabelValue",
181 ValidateFunc: validation.IsValidLabelValue,
182 MaxRegexSize: 40,
183 },
184
185 // CRD formats
186 // Implementations sourced from strfmt, which kube-openapi uses as its
187 // format library. There are other CRD formats supported, but they are
188 // covered by other portions of the CEL library (like IP/CIDR), or their
189 // use is discouraged (like bsonobjectid, email, etc)
190 "uri": {
191 Name: "URI",
192 ValidateFunc: func(s string) []string {
193 // Directly call ParseRequestURI since we can get a better error message
194 _, err := url.ParseRequestURI(s)
195 if err != nil {
196 return []string{err.Error()}
197 }
198 return nil
199 },
200 // Use govalidator url regex to estimate, since ParseRequestURI
201 // doesnt use regex
202 MaxRegexSize: urlLength,
203 },
204 "uuid": {
205 Name: "uuid",
206 ValidateFunc: func(s string) []string {
207 if !strfmt.Default.Validates("uuid", s) {
208 return []string{"does not match the UUID format"}
209 }
210 return nil
211 },
212 MaxRegexSize: len(strfmt.UUIDPattern),
213 },
214 "byte": {
215 Name: "byte",
216 ValidateFunc: func(s string) []string {
217 if !strfmt.Default.Validates("byte", s) {
218 return []string{"invalid base64"}
219 }
220 return nil
221 },
222 MaxRegexSize: base64Length,
223 },
224 "date": {
225 Name: "date",
226 ValidateFunc: func(s string) []string {
227 if !strfmt.Default.Validates("date", s) {
228 return []string{"invalid date"}
229 }
230 return nil
231 },
232 // Estimated regex size for RFC3339FullDate which is
233 // a date format. Assume a date-time pattern is longer
234 // so use that to conservatively estimate this
235 MaxRegexSize: len(strfmt.DateTimePattern),
236 },
237 "datetime": {
238 Name: "datetime",
239 ValidateFunc: func(s string) []string {
240 if !strfmt.Default.Validates("datetime", s) {
241 return []string{"invalid datetime"}
242 }
243 return nil
244 },
245 MaxRegexSize: len(strfmt.DateTimePattern),
246 },
247 }
248
249 var formatLibraryDecls = map[string][]cel.FunctionOpt{
250 "validate": {
251 cel.MemberOverload("format-validate", []*cel.Type{apiservercel.FormatType, cel.StringType}, cel.OptionalType(cel.ListType(cel.StringType)), cel.BinaryBinding(formatValidate)),
252 },
253 "format.named": {
254 cel.Overload("format-named", []*cel.Type{cel.StringType}, cel.OptionalType(apiservercel.FormatType), cel.UnaryBinding(func(name ref.Val) ref.Val {
255 nameString, ok := name.Value().(string)
256 if !ok {
257 return types.MaybeNoSuchOverloadErr(name)
258 }
259
260 f, ok := ConstantFormats[nameString]
261 if !ok {
262 return types.OptionalNone
263 }
264 return types.OptionalOf(f)
265 })),
266 },
267 }
268
269 func formatValidate(arg1, arg2 ref.Val) ref.Val {
270 f, ok := arg1.Value().(apiservercel.Format)
271 if !ok {
272 return types.MaybeNoSuchOverloadErr(arg1)
273 }
274
275 str, ok := arg2.Value().(string)
276 if !ok {
277 return types.MaybeNoSuchOverloadErr(arg2)
278 }
279
280 res := f.ValidateFunc(str)
281 if len(res) == 0 {
282 return types.OptionalNone
283 }
284 return types.OptionalOf(types.NewStringList(types.DefaultTypeAdapter, res))
285 }