-
Notifications
You must be signed in to change notification settings - Fork 5
/
value.go
723 lines (633 loc) · 19.2 KB
/
value.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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
package cedar
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/netip"
"strconv"
"strings"
"unicode"
"github.com/cedar-policy/cedar-go/x/exp/parser"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
)
type Value interface {
// String produces a string representation of the Value.
String() string
// Cedar produces a valid Cedar language representation of the Value.
Cedar() string
// ExplicitMarshalJSON marshals the Value into JSON using the explicit (if
// applicable) JSON form, which is necessary for marshalling values within
// Sets or Records where the type is not defined.
ExplicitMarshalJSON() ([]byte, error)
equal(Value) bool
typeName() string
deepClone() Value
}
func zeroValue() Value {
return nil
}
// A Boolean is a value that is either true or false.
type Boolean bool
func (a Boolean) equal(bi Value) bool {
b, ok := bi.(Boolean)
return ok && a == b
}
func (v Boolean) typeName() string { return "bool" }
// String produces a string representation of the Boolean, e.g. `true`.
func (v Boolean) String() string { return v.Cedar() }
// Cedar produces a valid Cedar language representation of the Boolean, e.g. `true`.
func (v Boolean) Cedar() string {
return fmt.Sprint(bool(v))
}
// ExplicitMarshalJSON marshals the Boolean into JSON.
func (v Boolean) ExplicitMarshalJSON() ([]byte, error) { return json.Marshal(v) }
func (v Boolean) deepClone() Value { return v }
// A Long is a whole number without decimals that can range from -9223372036854775808 to 9223372036854775807.
type Long int64
func (a Long) equal(bi Value) bool {
b, ok := bi.(Long)
return ok && a == b
}
// ExplicitMarshalJSON marshals the Long into JSON.
func (v Long) ExplicitMarshalJSON() ([]byte, error) { return json.Marshal(v) }
func (v Long) typeName() string { return "long" }
// String produces a string representation of the Long, e.g. `42`.
func (v Long) String() string { return v.Cedar() }
// Cedar produces a valid Cedar language representation of the Long, e.g. `42`.
func (v Long) Cedar() string {
return fmt.Sprint(int64(v))
}
func (v Long) deepClone() Value { return v }
// A String is a sequence of characters consisting of letters, numbers, or symbols.
type String string
func (a String) equal(bi Value) bool {
b, ok := bi.(String)
return ok && a == b
}
// ExplicitMarshalJSON marshals the String into JSON.
func (v String) ExplicitMarshalJSON() ([]byte, error) { return json.Marshal(v) }
func (v String) typeName() string { return "string" }
// String produces an unquoted string representation of the String, e.g. `hello`.
func (v String) String() string {
return string(v)
}
// Cedar produces a valid Cedar language representation of the String, e.g. `"hello"`.
func (v String) Cedar() string {
return parser.FakeRustQuote(string(v))
}
func (v String) deepClone() Value { return v }
// A Set is a collection of elements that can be of the same or different types.
type Set []Value
func (s Set) contains(v Value) bool {
for _, e := range s {
if e.equal(v) {
return true
}
}
return false
}
// Equals returns true if the sets are equal.
func (s Set) Equals(b Set) bool { return s.equal(b) }
func (as Set) equal(bi Value) bool {
bs, ok := bi.(Set)
if !ok {
return false
}
for _, a := range as {
if !bs.contains(a) {
return false
}
}
for _, b := range bs {
if !as.contains(b) {
return false
}
}
return true
}
func (v *explicitValue) UnmarshalJSON(b []byte) error {
return unmarshalJSON(b, &v.Value)
}
func (v *Set) UnmarshalJSON(b []byte) error {
var res []explicitValue
err := json.Unmarshal(b, &res)
if err != nil {
return err
}
for _, vv := range res {
*v = append(*v, vv.Value)
}
return nil
}
// MarshalJSON marshals the Set into JSON, the marshaller uses the explicit JSON
// form for all the values in the Set.
func (v Set) MarshalJSON() ([]byte, error) {
w := &bytes.Buffer{}
w.WriteByte('[')
for i, vv := range v {
if i > 0 {
w.WriteByte(',')
}
b, err := vv.ExplicitMarshalJSON()
if err != nil {
return nil, err
}
w.Write(b)
}
w.WriteByte(']')
return w.Bytes(), nil
}
// ExplicitMarshalJSON marshals the Set into JSON, the marshaller uses the
// explicit JSON form for all the values in the Set.
func (v Set) ExplicitMarshalJSON() ([]byte, error) { return v.MarshalJSON() }
func (v Set) typeName() string { return "set" }
// String produces a string representation of the Set, e.g. `[1,2,3]`.
func (v Set) String() string { return v.Cedar() }
// Cedar produces a valid Cedar language representation of the Set, e.g. `[1,2,3]`.
func (v Set) Cedar() string {
var sb strings.Builder
sb.WriteRune('[')
for i, elem := range v {
if i > 0 {
sb.WriteString(",")
}
sb.WriteString(elem.Cedar())
}
sb.WriteRune(']')
return sb.String()
}
func (v Set) deepClone() Value { return v.DeepClone() }
// DeepClone returns a deep clone of the Set.
func (v Set) DeepClone() Set {
if v == nil {
return v
}
res := make(Set, len(v))
for i, vv := range v {
res[i] = vv.deepClone()
}
return res
}
// A Record is a collection of attributes. Each attribute consists of a name and
// an associated value. Names are simple strings. Values can be of any type.
type Record map[string]Value
// Equals returns true if the records are equal.
func (r Record) Equals(b Record) bool { return r.equal(b) }
func (a Record) equal(bi Value) bool {
b, ok := bi.(Record)
if !ok || len(a) != len(b) {
return false
}
for k, av := range a {
bv, ok := b[k]
if !ok || !av.equal(bv) {
return false
}
}
return true
}
func (v *Record) UnmarshalJSON(b []byte) error {
var res map[string]explicitValue
err := json.Unmarshal(b, &res)
if err != nil {
return err
}
*v = Record{}
for kk, vv := range res {
(*v)[kk] = vv.Value
}
return nil
}
// MarshalJSON marshals the Record into JSON, the marshaller uses the explicit
// JSON form for all the values in the Record.
func (v Record) MarshalJSON() ([]byte, error) {
w := &bytes.Buffer{}
w.WriteByte('{')
keys := maps.Keys(v)
slices.Sort(keys)
for i, kk := range keys {
if i > 0 {
w.WriteByte(',')
}
kb, _ := json.Marshal(kk) // json.Marshal cannot error on strings
w.Write(kb)
w.WriteByte(':')
vv := v[kk]
vb, err := vv.ExplicitMarshalJSON()
if err != nil {
return nil, err
}
w.Write(vb)
}
w.WriteByte('}')
return w.Bytes(), nil
}
// ExplicitMarshalJSON marshals the Record into JSON, the marshaller uses the
// explicit JSON form for all the values in the Record.
func (v Record) ExplicitMarshalJSON() ([]byte, error) { return v.MarshalJSON() }
func (r Record) typeName() string { return "record" }
// String produces a string representation of the Record, e.g. `{"a":1,"b":2,"c":3}`.
func (r Record) String() string { return r.Cedar() }
// Cedar produces a valid Cedar language representation of the Record, e.g. `{"a":1,"b":2,"c":3}`.
func (r Record) Cedar() string {
var sb strings.Builder
sb.WriteRune('{')
first := true
keys := maps.Keys(r)
slices.Sort(keys)
for _, k := range keys {
v := r[k]
if !first {
sb.WriteString(",")
}
first = false
sb.WriteString(parser.FakeRustQuote(k))
sb.WriteString(":")
sb.WriteString(v.Cedar())
}
sb.WriteRune('}')
return sb.String()
}
func (v Record) deepClone() Value { return v.DeepClone() }
// DeepClone returns a deep clone of the Record.
func (v Record) DeepClone() Record {
if v == nil {
return v
}
res := make(Record, len(v))
for k, vv := range v {
res[k] = vv.deepClone()
}
return res
}
// An EntityUID is the identifier for a principal, action, or resource.
type EntityUID struct {
Type string
ID string
}
func NewEntityUID(typ, id string) EntityUID {
return EntityUID{
Type: typ,
ID: id,
}
}
// IsZero returns true if the EntityUID has an empty Type and ID.
func (a EntityUID) IsZero() bool {
return a.Type == "" && a.ID == ""
}
func (a EntityUID) equal(bi Value) bool {
b, ok := bi.(EntityUID)
return ok && a == b
}
func (v EntityUID) typeName() string { return fmt.Sprintf("(entity of type `%s`)", v.Type) }
// String produces a string representation of the EntityUID, e.g. `Type::"id"`.
func (v EntityUID) String() string { return v.Cedar() }
// Cedar produces a valid Cedar language representation of the EntityUID, e.g. `Type::"id"`.
func (v EntityUID) Cedar() string {
return v.Type + "::" + parser.FakeRustQuote(v.ID)
}
func (v *EntityUID) UnmarshalJSON(b []byte) error {
// TODO: review after adding support for schemas
var res entityValueJSON
if err := json.Unmarshal(b, &res); err != nil {
return err
}
if res.Entity != nil {
v.Type = res.Entity.Type
v.ID = res.Entity.ID
return nil
} else if res.Type != nil && res.ID != nil { // require both Type and ID to parse "implicit" JSON
v.Type = *res.Type
v.ID = *res.ID
return nil
}
return errJSONEntityNotFound
}
// ExplicitMarshalJSON marshals the EntityUID into JSON using the implicit form.
func (v EntityUID) MarshalJSON() ([]byte, error) {
return json.Marshal(entityValueJSON{
Type: &v.Type,
ID: &v.ID,
})
}
// ExplicitMarshalJSON marshals the EntityUID into JSON using the explicit form.
func (v EntityUID) ExplicitMarshalJSON() ([]byte, error) {
return json.Marshal(entityValueJSON{
Entity: &extEntity{
Type: v.Type,
ID: v.ID,
},
})
}
func (v EntityUID) deepClone() Value { return v }
func entityValueFromSlice(v []string) EntityUID {
return EntityUID{
Type: strings.Join(v[:len(v)-1], "::"),
ID: v[len(v)-1],
}
}
// path is the type portion of an EntityUID
type path string
func (a path) equal(bi Value) bool {
b, ok := bi.(path)
return ok && a == b
}
func (v path) typeName() string { return fmt.Sprintf("(path of type `%s`)", v) }
func (v path) String() string { return string(v) }
func (v path) Cedar() string { return string(v) }
func (v path) ExplicitMarshalJSON() ([]byte, error) { return json.Marshal(string(v)) }
func (v path) deepClone() Value { return v }
func pathFromSlice(v []string) path {
return path(strings.Join(v, "::"))
}
// A Decimal is a value with both a whole number part and a decimal part of no
// more than four digits. In Go this is stored as an int64, the precision is
// defined by the constant DecimalPrecision.
type Decimal int64
// DecimalPrecision is the precision of a Decimal.
const DecimalPrecision = 10000
// ParseDecimal takes a string representation of a decimal number and converts it into a Decimal type.
func ParseDecimal(s string) (Decimal, error) {
// Check for empty string.
if len(s) == 0 {
return Decimal(0), fmt.Errorf("%w: string too short", errDecimal)
}
i := 0
// Parse an optional '-'.
negative := false
if s[i] == '-' {
negative = true
i++
if i == len(s) {
return Decimal(0), fmt.Errorf("%w: string too short", errDecimal)
}
}
// Parse the required first digit.
c := rune(s[i])
if !unicode.IsDigit(c) {
return Decimal(0), fmt.Errorf("%w: unexpected character %s", errDecimal, strconv.QuoteRune(c))
}
integer := int64(c - '0')
i++
// Parse any other digits, ending with i pointing to '.'.
for ; ; i++ {
if i == len(s) {
return Decimal(0), fmt.Errorf("%w: string missing decimal point", errDecimal)
}
c = rune(s[i])
if c == '.' {
break
}
if !unicode.IsDigit(c) {
return Decimal(0), fmt.Errorf("%w: unexpected character %s", errDecimal, strconv.QuoteRune(c))
}
integer = 10*integer + int64(c-'0')
if integer > 922337203685477 {
return Decimal(0), fmt.Errorf("%w: overflow", errDecimal)
}
}
// Advance past the '.'.
i++
// Parse the fraction part
fraction := int64(0)
fractionDigits := 0
for ; i < len(s); i++ {
c = rune(s[i])
if !unicode.IsDigit(c) {
return Decimal(0), fmt.Errorf("%w: unexpected character %s", errDecimal, strconv.QuoteRune(c))
}
fraction = 10*fraction + int64(c-'0')
fractionDigits++
}
// Adjust the fraction part based on how many digits we parsed.
switch fractionDigits {
case 0:
return Decimal(0), fmt.Errorf("%w: missing digits after decimal point", errDecimal)
case 1:
fraction *= 1000
case 2:
fraction *= 100
case 3:
fraction *= 10
case 4:
default:
return Decimal(0), fmt.Errorf("%w: too many digits after decimal point", errDecimal)
}
// Check for overflow before we put the number together.
if integer >= 922337203685477 && (fraction > 5808 || (!negative && fraction == 5808)) {
return Decimal(0), fmt.Errorf("%w: overflow", errDecimal)
}
// Put the number together.
if negative {
// Doing things in this order keeps us from overflowing when parsing
// -922337203685477.5808. This isn't technically necessary because the
// go spec defines arithmetic to be well-defined when overflowing.
// However, doing things this way doesn't hurt, so let's be pedantic.
return Decimal(DecimalPrecision*-integer - fraction), nil
} else {
return Decimal(DecimalPrecision*integer + fraction), nil
}
}
func (a Decimal) equal(bi Value) bool {
b, ok := bi.(Decimal)
return ok && a == b
}
func (v Decimal) typeName() string { return "decimal" }
// Cedar produces a valid Cedar language representation of the Decimal, e.g. `decimal("12.34")`.
func (v Decimal) Cedar() string { return `decimal("` + v.String() + `")` }
// String produces a string representation of the Decimal, e.g. `12.34`.
func (v Decimal) String() string {
var res string
if v < 0 {
// Make sure we don't overflow here. Also, go truncates towards zero.
integer := v / DecimalPrecision
decimal := integer*DecimalPrecision - v
res = fmt.Sprintf("-%d.%04d", -integer, decimal)
} else {
res = fmt.Sprintf("%d.%04d", v/DecimalPrecision, v%DecimalPrecision)
}
// Trim off up to three trailing zeros.
right := len(res)
for trimmed := 0; right-1 >= 0 && trimmed < 3; right, trimmed = right-1, trimmed+1 {
if res[right-1] != '0' {
break
}
}
return res[:right]
}
func (v *Decimal) UnmarshalJSON(b []byte) error {
var arg string
if len(b) > 0 && b[0] == '"' {
if err := json.Unmarshal(b, &arg); err != nil {
return errors.Join(errJSONDecode, err)
}
} else {
// NOTE: cedar supports two other forms, for now we're only supporting the smallest implicit and explicit form.
// The following are not supported:
// "decimal(\"1234.5678\")"
// {"fn":"decimal","arg":"1234.5678"}
var res extValueJSON
if err := json.Unmarshal(b, &res); err != nil {
return errors.Join(errJSONDecode, err)
}
if res.Extn == nil {
return errJSONExtNotFound
}
if res.Extn.Fn != "decimal" {
return errJSONExtFnMatch
}
arg = res.Extn.Arg
}
vv, err := ParseDecimal(arg)
if err != nil {
return err
}
*v = vv
return nil
}
// ExplicitMarshalJSON marshals the Decimal into JSON using the implicit form.
func (v Decimal) MarshalJSON() ([]byte, error) { return []byte(`"` + v.String() + `"`), nil }
// ExplicitMarshalJSON marshals the Decimal into JSON using the explicit form.
func (v Decimal) ExplicitMarshalJSON() ([]byte, error) {
return json.Marshal(extValueJSON{
Extn: &extn{
Fn: "decimal",
Arg: v.String(),
},
})
}
func (v Decimal) deepClone() Value { return v }
// An IPAddr is value that represents an IP address. It can be either IPv4 or IPv6.
// The value can represent an individual address or a range of addresses.
type IPAddr netip.Prefix
// ParseIPAddr takes a string representation of an IP address and converts it into an IPAddr type.
func ParseIPAddr(s string) (IPAddr, error) {
// We disallow IPv4-mapped IPv6 addresses in dotted notation because Cedar does.
if strings.Count(s, ":") >= 2 && strings.Count(s, ".") >= 2 {
return IPAddr{}, fmt.Errorf("%w: cannot parse IPv4 addresses embedded in IPv6 addresses", errIP)
} else if net, err := netip.ParsePrefix(s); err == nil {
return IPAddr(net), nil
} else if addr, err := netip.ParseAddr(s); err == nil {
return IPAddr(netip.PrefixFrom(addr, addr.BitLen())), nil
} else {
return IPAddr{}, fmt.Errorf("%w: error parsing IP address %s", errIP, s)
}
}
func (a IPAddr) equal(bi Value) bool {
b, ok := bi.(IPAddr)
return ok && a == b
}
func (v IPAddr) typeName() string { return "IP" }
// Cedar produces a valid Cedar language representation of the IPAddr, e.g. `ip("127.0.0.1")`.
func (v IPAddr) Cedar() string { return `ip("` + v.String() + `")` }
// String produces a string representation of the IPAddr, e.g. `127.0.0.1`.
func (v IPAddr) String() string {
if v.Prefix().Bits() == v.Addr().BitLen() {
return v.Addr().String()
}
return v.Prefix().String()
}
func (v IPAddr) Prefix() netip.Prefix {
return netip.Prefix(v)
}
func (v IPAddr) isIPv4() bool {
return v.Addr().Is4()
}
func (v IPAddr) isIPv6() bool {
return v.Addr().Is6()
}
func (v IPAddr) isLoopback() bool {
// This comment is in the Cedar Rust implementation:
//
// Loopback addresses are "127.0.0.0/8" for IpV4 and "::1" for IpV6
//
// Unlike the implementation of `is_multicast`, we don't need to test prefix
//
// The reason for IpV6 is obvious: There's only one loopback address
//
// The reason for IpV4 is that provided the truncated ip address is a
// loopback address, its prefix cannot be less than 8 because
// otherwise its more significant byte cannot be 127
return v.Prefix().Masked().Addr().IsLoopback()
}
func (v IPAddr) Addr() netip.Addr {
return netip.Prefix(v).Addr()
}
func (v IPAddr) isMulticast() bool {
// This comment is in the Cedar Rust implementation:
//
// Multicast addresses are "224.0.0.0/4" for IpV4 and "ff00::/8" for
// IpV6
//
// If an IpNet's addresses are multicast addresses, calling
// `is_in_range()` over it and its associated net above should
// evaluate to true
//
// The implementation uses the property that if `ip1/prefix1` is in
// range `ip2/prefix2`, then `ip1` is in `ip2/prefix2` and `prefix1 >=
// prefix2`
var min_prefix_len int
if v.isIPv4() {
min_prefix_len = 4
} else {
min_prefix_len = 8
}
return v.Addr().IsMulticast() && v.Prefix().Bits() >= min_prefix_len
}
func (c IPAddr) contains(o IPAddr) bool {
return c.Prefix().Contains(o.Addr()) && c.Prefix().Bits() <= o.Prefix().Bits()
}
func (v *IPAddr) UnmarshalJSON(b []byte) error {
var arg string
if len(b) > 0 && b[0] == '"' {
if err := json.Unmarshal(b, &arg); err != nil {
return errors.Join(errJSONDecode, err)
}
} else {
// NOTE: cedar supports two other forms, for now we're only supporting the smallest implicit explicit form.
// The following are not supported:
// "ip(\"192.168.0.42\")"
// {"fn":"ip","arg":"192.168.0.42"}
var res extValueJSON
if err := json.Unmarshal(b, &res); err != nil {
return errors.Join(errJSONDecode, err)
}
if res.Extn == nil {
return errJSONExtNotFound
}
if res.Extn.Fn != "ip" {
return errJSONExtFnMatch
}
arg = res.Extn.Arg
}
vv, err := ParseIPAddr(arg)
if err != nil {
return err
}
*v = vv
return nil
}
// ExplicitMarshalJSON marshals the IPAddr into JSON using the implicit form.
func (v IPAddr) MarshalJSON() ([]byte, error) { return []byte(`"` + v.String() + `"`), nil }
// ExplicitMarshalJSON marshals the IPAddr into JSON using the explicit form.
func (v IPAddr) ExplicitMarshalJSON() ([]byte, error) {
if v.Prefix().Bits() == v.Prefix().Addr().BitLen() {
return json.Marshal(extValueJSON{
Extn: &extn{
Fn: "ip",
Arg: v.Addr().String(),
},
})
}
return json.Marshal(extValueJSON{
Extn: &extn{
Fn: "ip",
Arg: v.String(),
},
})
}
// in this case, netip.Prefix does contain a pointer, but
// the interface given is immutable, so it is safe to return
func (v IPAddr) deepClone() Value { return v }