/
lib.go
524 lines (500 loc) · 14.9 KB
/
lib.go
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
// Copyright 2023-2024 Buf Technologies, Inc.
//
// 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 celext
import (
"bytes"
"math"
"net"
"net/mail"
"net/netip"
"net/url"
"strconv"
"strings"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/overloads"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
"github.com/google/cel-go/common/types/traits"
"github.com/google/cel-go/ext"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/dynamicpb"
)
// DefaultEnv produces a cel.Env with the necessary cel.EnvOption and
// cel.ProgramOption values preconfigured for usage throughout the
// module. If useUTC is true, timestamp operations use the UTC timezone instead
// of the local timezone.
func DefaultEnv(useUTC bool) (*cel.Env, error) {
return cel.NewEnv(
// we bind in the global type registry optimistically to ensure expressions
// operating against Any WKTs can resolve their underlying type if it's
// known to the application. They will otherwise fail with a runtime error
// if the type is unknown.
cel.TypeDescs(protoregistry.GlobalFiles),
cel.Lib(lib{
useUTC: useUTC,
}),
)
}
// RequiredCELEnvOptions returns the options required to have expressions which
// rely on the provided descriptor.
func RequiredCELEnvOptions(fieldDesc protoreflect.FieldDescriptor) []cel.EnvOption {
if fieldDesc.IsMap() {
return append(
RequiredCELEnvOptions(fieldDesc.MapKey()),
RequiredCELEnvOptions(fieldDesc.MapValue())...,
)
}
if fieldDesc.Kind() == protoreflect.MessageKind {
return []cel.EnvOption{
cel.Types(dynamicpb.NewMessage(fieldDesc.Message())),
}
}
return nil
}
// lib is the collection of functions and settings required by protovalidate
// beyond the standard definitions of the CEL Specification:
//
// https://github.com/google/cel-spec/blob/master/doc/langdef.md#list-of-standard-definitions
//
// All implementations of protovalidate MUST implement these functions and
// should avoid exposing additional functions as they will not be portable.
type lib struct {
useUTC bool
}
//nolint:funlen
func (l lib) CompileOptions() []cel.EnvOption {
return []cel.EnvOption{
cel.DefaultUTCTimeZone(l.useUTC),
cel.CrossTypeNumericComparisons(true),
cel.EagerlyValidateDeclarations(true),
// TODO: reduce this to just the functionality we want to support
ext.Strings(ext.StringsValidateFormatCalls(true)),
cel.Variable("now", cel.TimestampType),
cel.Function("unique",
l.uniqueMemberOverload(cel.BoolType, l.uniqueScalar),
l.uniqueMemberOverload(cel.IntType, l.uniqueScalar),
l.uniqueMemberOverload(cel.UintType, l.uniqueScalar),
l.uniqueMemberOverload(cel.DoubleType, l.uniqueScalar),
l.uniqueMemberOverload(cel.StringType, l.uniqueScalar),
l.uniqueMemberOverload(cel.BytesType, l.uniqueBytes),
),
cel.Function("isNan",
cel.MemberOverload(
"double_is_nan_bool",
[]*cel.Type{cel.DoubleType},
cel.BoolType,
cel.UnaryBinding(func(value ref.Val) ref.Val {
num, ok := value.Value().(float64)
if !ok {
return types.UnsupportedRefValConversionErr(value)
}
return types.Bool(math.IsNaN(num))
}),
),
),
cel.Function("isInf",
cel.MemberOverload(
"double_is_inf_bool",
[]*cel.Type{cel.DoubleType},
cel.BoolType,
cel.UnaryBinding(func(value ref.Val) ref.Val {
num, ok := value.Value().(float64)
if !ok {
return types.UnsupportedRefValConversionErr(value)
}
return types.Bool(math.IsInf(num, 0))
}),
),
cel.MemberOverload(
"double_int_is_inf_bool",
[]*cel.Type{cel.DoubleType, cel.IntType},
cel.BoolType,
cel.BinaryBinding(func(lhs ref.Val, rhs ref.Val) ref.Val {
num, ok := lhs.Value().(float64)
if !ok {
return types.UnsupportedRefValConversionErr(lhs)
}
sign, ok := rhs.Value().(int64)
if !ok {
return types.UnsupportedRefValConversionErr(rhs)
}
return types.Bool(math.IsInf(num, int(sign)))
}),
),
),
cel.Function("isHostname",
cel.MemberOverload(
"string_is_hostname_bool",
[]*cel.Type{cel.StringType},
cel.BoolType,
cel.FunctionBinding(func(args ...ref.Val) ref.Val {
host, ok := args[0].Value().(string)
if !ok {
return types.Bool(false)
}
return types.Bool(l.validateHostname(host))
}),
),
),
cel.Function("isEmail",
cel.MemberOverload(
"string_is_email_bool",
[]*cel.Type{cel.StringType},
cel.BoolType,
cel.FunctionBinding(func(args ...ref.Val) ref.Val {
addr, ok := args[0].Value().(string)
if !ok {
return types.Bool(false)
}
return types.Bool(l.validateEmail(addr))
}),
),
),
cel.Function("isIp",
cel.MemberOverload(
"string_is_ip_bool",
[]*cel.Type{cel.StringType},
cel.BoolType,
cel.FunctionBinding(func(args ...ref.Val) ref.Val {
addr, ok := args[0].Value().(string)
if !ok {
return types.Bool(false)
}
return types.Bool(l.validateIP(addr, 0))
}),
),
cel.MemberOverload(
"string_int_is_ip_bool",
[]*cel.Type{cel.StringType, cel.IntType},
cel.BoolType,
cel.FunctionBinding(func(args ...ref.Val) ref.Val {
addr, aok := args[0].Value().(string)
vers, vok := args[1].Value().(int64)
if !aok || !vok {
return types.Bool(false)
}
return types.Bool(l.validateIP(addr, vers))
})),
),
cel.Function("isIpPrefix",
cel.MemberOverload(
"string_is_ip_prefix_bool",
[]*cel.Type{cel.StringType},
cel.BoolType,
cel.FunctionBinding(func(args ...ref.Val) ref.Val {
prefix, ok := args[0].Value().(string)
if !ok {
return types.Bool(false)
}
return types.Bool(l.validateIPPrefix(prefix, 0, false))
})),
cel.MemberOverload(
"string_int_is_ip_prefix_bool",
[]*cel.Type{cel.StringType, cel.IntType},
cel.BoolType,
cel.FunctionBinding(func(args ...ref.Val) ref.Val {
prefix, pok := args[0].Value().(string)
vers, vok := args[1].Value().(int64)
if !pok || !vok {
return types.Bool(false)
}
return types.Bool(l.validateIPPrefix(prefix, vers, false))
})),
cel.MemberOverload(
"string_bool_is_ip_prefix_bool",
[]*cel.Type{cel.StringType, cel.BoolType},
cel.BoolType,
cel.FunctionBinding(func(args ...ref.Val) ref.Val {
prefix, pok := args[0].Value().(string)
strict, sok := args[1].Value().(bool)
if !pok || !sok {
return types.Bool(false)
}
return types.Bool(l.validateIPPrefix(prefix, 0, strict))
})),
cel.MemberOverload(
"string_int_bool_is_ip_prefix_bool",
[]*cel.Type{cel.StringType, cel.IntType, cel.BoolType},
cel.BoolType,
cel.FunctionBinding(func(args ...ref.Val) ref.Val {
prefix, pok := args[0].Value().(string)
vers, vok := args[1].Value().(int64)
strict, sok := args[2].Value().(bool)
if !pok || !vok || !sok {
return types.Bool(false)
}
return types.Bool(l.validateIPPrefix(prefix, vers, strict))
})),
),
cel.Function("isUri",
cel.MemberOverload(
"string_is_uri_bool",
[]*cel.Type{cel.StringType},
cel.BoolType,
cel.FunctionBinding(func(args ...ref.Val) ref.Val {
s, ok := args[0].Value().(string)
if !ok {
return types.Bool(false)
}
uri, err := url.Parse(s)
return types.Bool(err == nil && uri.IsAbs())
}),
),
),
cel.Function("isUriRef",
cel.MemberOverload(
"string_is_uri_ref_bool",
[]*cel.Type{cel.StringType},
cel.BoolType,
cel.FunctionBinding(func(args ...ref.Val) ref.Val {
s, ok := args[0].Value().(string)
if !ok {
return types.Bool(false)
}
_, err := url.Parse(s)
return types.Bool(err == nil)
}),
),
),
cel.Function(overloads.Contains,
cel.MemberOverload(
overloads.ContainsString, []*cel.Type{cel.StringType, cel.StringType}, cel.BoolType,
cel.BinaryBinding(func(lhs ref.Val, rhs ref.Val) ref.Val {
substr, ok := rhs.Value().(string)
if !ok {
return types.UnsupportedRefValConversionErr(rhs)
}
return types.Bool(strings.Contains(lhs.Value().(string), substr))
}),
),
cel.MemberOverload("contains_bytes", []*cel.Type{cel.BytesType, cel.BytesType}, cel.BoolType,
cel.BinaryBinding(func(lhs ref.Val, rhs ref.Val) ref.Val {
substr, ok := rhs.Value().([]byte)
if !ok {
return types.UnsupportedRefValConversionErr(rhs)
}
return types.Bool(bytes.Contains(lhs.Value().([]byte), substr))
}),
),
),
cel.Function(overloads.EndsWith,
cel.MemberOverload(
overloads.EndsWithString, []*cel.Type{cel.StringType, cel.StringType}, cel.BoolType,
cel.BinaryBinding(func(lhs ref.Val, rhs ref.Val) ref.Val {
suffix, ok := rhs.Value().(string)
if !ok {
return types.UnsupportedRefValConversionErr(rhs)
}
return types.Bool(strings.HasSuffix(lhs.Value().(string), suffix))
}),
),
cel.MemberOverload("ends_with_bytes", []*cel.Type{cel.BytesType, cel.BytesType}, cel.BoolType,
cel.BinaryBinding(func(lhs ref.Val, rhs ref.Val) ref.Val {
suffix, ok := rhs.Value().([]byte)
if !ok {
return types.UnsupportedRefValConversionErr(rhs)
}
return types.Bool(bytes.HasSuffix(lhs.Value().([]byte), suffix))
}),
),
),
cel.Function(overloads.StartsWith,
cel.MemberOverload(
overloads.StartsWithString, []*cel.Type{cel.StringType, cel.StringType}, cel.BoolType,
cel.BinaryBinding(func(lhs ref.Val, rhs ref.Val) ref.Val {
prefix, ok := rhs.Value().(string)
if !ok {
return types.UnsupportedRefValConversionErr(rhs)
}
return types.Bool(strings.HasPrefix(lhs.Value().(string), prefix))
}),
),
cel.MemberOverload("starts_with_bytes", []*cel.Type{cel.BytesType, cel.BytesType}, cel.BoolType,
cel.BinaryBinding(func(lhs ref.Val, rhs ref.Val) ref.Val {
prefix, ok := rhs.Value().([]byte)
if !ok {
return types.UnsupportedRefValConversionErr(rhs)
}
return types.Bool(bytes.HasPrefix(lhs.Value().([]byte), prefix))
}),
),
),
cel.Function("isHostAndPort",
cel.MemberOverload("string_bool_is_host_and_port_bool",
[]*cel.Type{cel.StringType, cel.BoolType}, cel.BoolType,
cel.BinaryBinding(func(lhs ref.Val, rhs ref.Val) ref.Val {
val, vok := lhs.Value().(string)
portReq, pok := rhs.Value().(bool)
if !vok || !pok {
return types.Bool(false)
}
return types.Bool(l.isHostAndPort(val, portReq))
}),
),
),
}
}
func (l lib) ProgramOptions() []cel.ProgramOption {
return []cel.ProgramOption{
cel.EvalOptions(
cel.OptOptimize,
),
}
}
func (l lib) uniqueMemberOverload(itemType *cel.Type, overload func(lister traits.Lister) ref.Val) cel.FunctionOpt {
return cel.MemberOverload(
itemType.String()+"_unique_bool",
[]*cel.Type{cel.ListType(itemType)},
cel.BoolType,
cel.UnaryBinding(func(value ref.Val) ref.Val {
list, ok := value.(traits.Lister)
if !ok {
return types.UnsupportedRefValConversionErr(value)
}
return overload(list)
}),
)
}
func (l lib) uniqueScalar(list traits.Lister) ref.Val {
exist := make(map[ref.Val]struct{})
for i := int64(0); i < list.Size().Value().(int64); i++ {
if _, ok := exist[list.Get(types.Int(i))]; ok {
return types.Bool(false)
}
exist[list.Get(types.Int(i))] = struct{}{}
}
return types.Bool(true)
}
// uniqueBytes is an overload implementation of the unique function that
// compares bytes type CEL values. This function is used instead of uniqueScalar
// as the bytes ([]uint8) type is not hashable in Go; we cheat this by converting
// the value to a string.
func (l lib) uniqueBytes(list traits.Lister) ref.Val {
exist := make(map[any]struct{})
for i := int64(0); i < list.Size().Value().(int64); i++ {
val := list.Get(types.Int(i)).Value()
if b, ok := val.([]uint8); ok {
val = string(b)
}
if _, ok := exist[val]; ok {
return types.Bool(false)
}
exist[val] = struct{}{}
}
return types.Bool(true)
}
func (l lib) validateEmail(addr string) bool {
a, err := mail.ParseAddress(addr)
if err != nil || strings.ContainsRune(addr, '<') || a.Address != addr {
return false
}
addr = a.Address
if len(addr) > 254 {
return false
}
parts := strings.SplitN(addr, "@", 2)
return len(parts[0]) <= 64 && l.validateHostname(parts[1])
}
func (l lib) validateHostname(host string) bool {
if len(host) > 253 {
return false
}
s := strings.ToLower(strings.TrimSuffix(host, "."))
allDigits := false
// split hostname on '.' and validate each part
for _, part := range strings.Split(s, ".") {
allDigits = true
// if part is empty, longer than 63 chars, or starts/ends with '-', it is invalid
if l := len(part); l == 0 || l > 63 || part[0] == '-' || part[l-1] == '-' {
return false
}
// for each character in part
for _, ch := range part {
// if the character is not a-z, 0-9, or '-', it is invalid
if (ch < 'a' || ch > 'z') && (ch < '0' || ch > '9') && ch != '-' {
return false
}
allDigits = allDigits && ch >= '0' && ch <= '9'
}
}
// the last part cannot be all numbers
return !allDigits
}
func (l lib) validateIP(addr string, ver int64) bool {
address := net.ParseIP(addr)
if address == nil {
return false
}
switch ver {
case 0:
return true
case 4:
return address.To4() != nil
case 6:
return address.To4() == nil
default:
return false
}
}
func (l lib) validateIPPrefix(p string, ver int64, strict bool) bool {
prefix, err := netip.ParsePrefix(p)
if err != nil {
return false
}
if strict && (prefix.Addr() != prefix.Masked().Addr()) {
return false
}
switch ver {
case 0:
return true
case 4:
return prefix.Addr().Is4()
case 6:
return prefix.Addr().Is6()
default:
return false
}
}
func (l lib) isHostAndPort(val string, portRequired bool) bool {
if len(val) == 0 {
return false
}
splitIdx := strings.LastIndexByte(val, ':')
if val[0] == '[' { // ipv6
end := strings.IndexByte(val, ']')
switch end + 1 {
case len(val): // no port
return !portRequired && l.validateIP(val[1:end], 6)
case splitIdx: // port
return l.validateIP(val[1:end], 6) &&
l.validatePort(val[splitIdx+1:])
default: // malformed
return false
}
}
if splitIdx < 0 {
return !portRequired &&
(l.validateHostname(val) ||
l.validateIP(val, 4))
}
host, port := val[:splitIdx], val[splitIdx+1:]
return (l.validateHostname(host) ||
l.validateIP(host, 4)) &&
l.validatePort(port)
}
func (l lib) validatePort(val string) bool {
n, err := strconv.ParseUint(val, 10, 32)
return err == nil && n <= 65535
}