-
Notifications
You must be signed in to change notification settings - Fork 123
/
model.go
1237 lines (1016 loc) · 31.8 KB
/
model.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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021-2023 Zenauth Ltd.
// SPDX-License-Identifier: Apache-2.0
package client
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sync"
"time"
"go.uber.org/multierr"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/structpb"
auditv1 "github.com/cerbos/cerbos/api/genpb/cerbos/audit/v1"
effectv1 "github.com/cerbos/cerbos/api/genpb/cerbos/effect/v1"
enginev1 "github.com/cerbos/cerbos/api/genpb/cerbos/engine/v1"
policyv1 "github.com/cerbos/cerbos/api/genpb/cerbos/policy/v1"
requestv1 "github.com/cerbos/cerbos/api/genpb/cerbos/request/v1"
responsev1 "github.com/cerbos/cerbos/api/genpb/cerbos/response/v1"
schemav1 "github.com/cerbos/cerbos/api/genpb/cerbos/schema/v1"
"github.com/cerbos/cerbos/internal/policy"
"github.com/cerbos/cerbos/internal/schema"
"github.com/cerbos/cerbos/internal/util"
)
const apiVersion = "api.cerbos.dev/v1"
// Principal is a container for principal data.
type Principal struct {
p *enginev1.Principal
err error
}
// NewPrincipal creates a new principal object with the given ID and roles.
func NewPrincipal(id string, roles ...string) *Principal {
return &Principal{
p: &enginev1.Principal{
Id: id,
Roles: roles,
},
}
}
// WithPolicyVersion sets the policy version for this principal.
func (p *Principal) WithPolicyVersion(policyVersion string) *Principal {
p.p.PolicyVersion = policyVersion
return p
}
// WithRoles appends the set of roles to principal's existing roles.
func (p *Principal) WithRoles(roles ...string) *Principal {
p.p.Roles = append(p.p.Roles, roles...)
return p
}
// WithScope sets the scope this principal belongs to.
func (p *Principal) WithScope(scope string) *Principal {
p.p.Scope = scope
return p
}
// WithAttributes merges the given attributes to principal's existing attributes.
func (p *Principal) WithAttributes(attr map[string]any) *Principal {
if p.p.Attr == nil {
p.p.Attr = make(map[string]*structpb.Value, len(attr))
}
for k, v := range attr {
pbVal, err := util.ToStructPB(v)
if err != nil {
p.err = multierr.Append(p.err, fmt.Errorf("invalid attribute value for '%s': %w", k, err))
continue
}
p.p.Attr[k] = pbVal
}
return p
}
// WithAttr adds a new attribute to the principal.
// It will overwrite any existing attribute having the same key.
func (p *Principal) WithAttr(key string, value any) *Principal {
if p.p.Attr == nil {
p.p.Attr = make(map[string]*structpb.Value)
}
pbVal, err := util.ToStructPB(value)
if err != nil {
p.err = multierr.Append(p.err, fmt.Errorf("invalid attribute value for '%s': %w", key, err))
return p
}
p.p.Attr[key] = pbVal
return p
}
// Err returns any errors accumulated during the construction of the principal.
func (p *Principal) Err() error {
return p.err
}
// Validate checks whether the principal object is valid.
func (p *Principal) Validate() error {
if p.err != nil {
return p.err
}
return p.p.Validate()
}
// Resource is a single resource instance.
type Resource struct {
r *enginev1.Resource
err error
}
// NewResource creates a new instance of a resource.
func NewResource(kind, id string) *Resource {
return &Resource{
r: &enginev1.Resource{Kind: kind, Id: id},
}
}
// WithPolicyVersion sets the policy version for this resource.
func (r *Resource) WithPolicyVersion(policyVersion string) *Resource {
r.r.PolicyVersion = policyVersion
return r
}
// WithAttributes merges the given attributes to the resource's existing attributes.
func (r *Resource) WithAttributes(attr map[string]any) *Resource {
if r.r.Attr == nil {
r.r.Attr = make(map[string]*structpb.Value, len(attr))
}
for k, v := range attr {
pbVal, err := util.ToStructPB(v)
if err != nil {
r.err = multierr.Append(r.err, fmt.Errorf("invalid attribute value for '%s': %w", k, err))
continue
}
r.r.Attr[k] = pbVal
}
return r
}
// WithAttr adds a new attribute to the resource.
// It will overwrite any existing attribute having the same key.
func (r *Resource) WithAttr(key string, value any) *Resource {
if r.r.Attr == nil {
r.r.Attr = make(map[string]*structpb.Value)
}
pbVal, err := util.ToStructPB(value)
if err != nil {
r.err = multierr.Append(r.err, fmt.Errorf("invalid attribute value for '%s': %w", key, err))
return r
}
r.r.Attr[key] = pbVal
return r
}
// WithScope sets the scope this resource belongs to.
func (r *Resource) WithScope(scope string) *Resource {
r.r.Scope = scope
return r
}
// Err returns any errors accumulated during the construction of the resource.
func (r *Resource) Err() error {
return r.err
}
// Validate checks whether the resource is valid.
func (r *Resource) Validate() error {
if r.err != nil {
return r.err
}
return r.r.Validate()
}
// ResourceSet is a container for a set of resources of the same kind.
type ResourceSet struct {
rs *requestv1.ResourceSet
err error
}
// NewResourceSet creates a new resource set.
func NewResourceSet(kind string) *ResourceSet {
return &ResourceSet{
rs: &requestv1.ResourceSet{Kind: kind},
}
}
// WithPolicyVersion sets the policy version for this resource set.
func (rs *ResourceSet) WithPolicyVersion(policyVersion string) *ResourceSet {
rs.rs.PolicyVersion = policyVersion
return rs
}
// AddResourceInstance adds a new resource instance to the resource set.
func (rs *ResourceSet) AddResourceInstance(id string, attr map[string]any) *ResourceSet {
if rs.rs.Instances == nil {
rs.rs.Instances = make(map[string]*requestv1.AttributesMap)
}
pbAttr := make(map[string]*structpb.Value, len(attr))
for k, v := range attr {
pbVal, err := structpb.NewValue(v)
if err != nil {
rs.err = multierr.Append(rs.err, fmt.Errorf("invalid attribute value for '%s': %w", k, err))
continue
}
pbAttr[k] = pbVal
}
rs.rs.Instances[id] = &requestv1.AttributesMap{Attr: pbAttr}
return rs
}
// Err returns any errors accumulated during the construction of this resource set.
func (rs *ResourceSet) Err() error {
return rs.err
}
// Validate checks whether this resource set is valid.
func (rs *ResourceSet) Validate() error {
if rs.err != nil {
return rs.err
}
return rs.rs.Validate()
}
// CheckResourceSetResponse is the response from the CheckResourceSet API call.
type CheckResourceSetResponse struct {
*responsev1.CheckResourceSetResponse
}
// IsAllowed returns true if the response indicates that the given action on the given resource is allowed.
// If the resource or action is not contained in the response, the return value will always be false.
func (crsr *CheckResourceSetResponse) IsAllowed(resourceID, action string) bool {
res, ok := crsr.ResourceInstances[resourceID]
if !ok {
return false
}
effect, ok := res.Actions[action]
if !ok {
return false
}
return effect == effectv1.Effect_EFFECT_ALLOW
}
// Errors returns all validation errors returned by the server.
func (crsr *CheckResourceSetResponse) Errors() error {
var err error
for resource, actions := range crsr.ResourceInstances {
for _, verr := range actions.ValidationErrors {
err = multierr.Append(err,
fmt.Errorf("resource %q failed validation: source=%s path=%s msg=%s", resource, verr.Source, verr.Path, verr.Message),
)
}
}
return err
}
func (crsr *CheckResourceSetResponse) String() string {
return protojson.Format(crsr.CheckResourceSetResponse)
}
func (crsr *CheckResourceSetResponse) MarshalJSON() ([]byte, error) {
return protojson.Marshal(crsr.CheckResourceSetResponse)
}
// ResourceBatch is a container for a batch of heterogeneous resources.
type ResourceBatch struct {
err error
batch []*requestv1.CheckResourcesRequest_ResourceEntry
}
// NewResourceBatch creates a new resource batch.
func NewResourceBatch() *ResourceBatch {
return &ResourceBatch{}
}
// Add a new resource to the batch.
func (rb *ResourceBatch) Add(resource *Resource, actions ...string) *ResourceBatch {
if resource == nil || len(actions) == 0 {
return rb
}
entry := &requestv1.CheckResourcesRequest_ResourceEntry{
Actions: actions,
Resource: resource.r,
}
if err := entry.Validate(); err != nil {
rb.err = multierr.Append(rb.err, fmt.Errorf("invalid resource '%s': %w", resource.r.Id, err))
return rb
}
rb.batch = append(rb.batch, entry)
return rb
}
// Err returns any errors accumulated during the construction of the resource batch.
func (rb *ResourceBatch) Err() error {
return rb.err
}
// Validate checks whether the resource batch is valid.
func (rb *ResourceBatch) Validate() error {
if rb.err != nil {
return rb.err
}
if len(rb.batch) == 0 {
return errors.New("empty batch")
}
var errList error
for _, entry := range rb.batch {
if err := entry.Validate(); err != nil {
errList = multierr.Append(errList, err)
}
}
return errList
}
func (rb *ResourceBatch) toResourceBatchEntry() []*requestv1.CheckResourceBatchRequest_BatchEntry {
b := make([]*requestv1.CheckResourceBatchRequest_BatchEntry, len(rb.batch))
for i, r := range rb.batch {
b[i] = &requestv1.CheckResourceBatchRequest_BatchEntry{
Resource: r.Resource,
Actions: r.Actions,
}
}
return b
}
// CheckResourceBatchResponse is the response from the CheckResourceBatch API call.
type CheckResourceBatchResponse struct {
*responsev1.CheckResourceBatchResponse
idx map[string][]int
once sync.Once
}
func (crbr *CheckResourceBatchResponse) buildIdx() {
crbr.once.Do(func() {
crbr.idx = make(map[string][]int, len(crbr.Results))
for i, r := range crbr.Results {
v := crbr.idx[r.ResourceId]
crbr.idx[r.ResourceId] = append(v, i)
}
})
}
// IsAllowed returns true if the given resource and action is allowed.
// If the resource or the action is not included in the response, the result will always be false.
func (crbr *CheckResourceBatchResponse) IsAllowed(resourceID, action string) bool {
crbr.buildIdx()
indexes, ok := crbr.idx[resourceID]
if !ok {
return false
}
for _, i := range indexes {
r := crbr.Results[i]
if r == nil {
continue
}
if effect, ok := r.Actions[action]; ok {
return effect == effectv1.Effect_EFFECT_ALLOW
}
}
return false
}
// Errors returns any validation errors returned by the server.
func (crbr *CheckResourceBatchResponse) Errors() error {
var err error
for _, result := range crbr.Results {
for _, verr := range result.ValidationErrors {
err = multierr.Append(err,
fmt.Errorf("resource %q failed validation: source=%s path=%s msg=%s", result.ResourceId, verr.Source, verr.Path, verr.Message),
)
}
}
return err
}
func (crbr *CheckResourceBatchResponse) String() string {
return protojson.Format(crbr.CheckResourceBatchResponse)
}
func (crbr *CheckResourceBatchResponse) MarshalJSON() ([]byte, error) {
return protojson.Marshal(crbr.CheckResourceBatchResponse)
}
type ResourceResult struct {
*responsev1.CheckResourcesResponse_ResultEntry
err error
}
func (rr *ResourceResult) Err() error {
return rr.err
}
// IsAllowed returns true if the given action is allowed.
// Returns false if the action is not in the response of if there was an error getting this result.
func (rr *ResourceResult) IsAllowed(action string) bool {
if rr != nil && rr.err == nil {
return rr.Actions[action] == effectv1.Effect_EFFECT_ALLOW
}
return false
}
// MatchResource is a function that returns true if the given resource is of interest.
// This is useful when you have more than one resource with the same ID and need to distinguish
// between them in the response.
type MatchResource func(*responsev1.CheckResourcesResponse_ResultEntry_Resource) bool
// MatchResourceKind is a matcher that checks that the resource kind matches the given value.
func MatchResourceKind(kind string) MatchResource {
return func(r *responsev1.CheckResourcesResponse_ResultEntry_Resource) bool {
return r.Kind == kind
}
}
// MatchResourceScope is a matcher that checks that the resource scope matches the given value.
func MatchResourceScope(scope string) MatchResource {
return func(r *responsev1.CheckResourcesResponse_ResultEntry_Resource) bool {
return r.Scope == scope
}
}
// MatchResourcePolicyVersion is a matcher that checks that the resource policy version matches the given value.
func MatchResourcePolicyVersion(version string) MatchResource {
return func(r *responsev1.CheckResourcesResponse_ResultEntry_Resource) bool {
return r.PolicyVersion == version
}
}
// MatchResourcePolicyKindScopeVersion is a matcher that checks that the resource policy kind, version and scope matches the given values.
func MatchResourcePolicyKindScopeVersion(kind, version, scope string) MatchResource {
return func(r *responsev1.CheckResourcesResponse_ResultEntry_Resource) bool {
return r.Kind == kind && r.PolicyVersion == version && r.Scope == scope
}
}
// CheckResourcesResponse is the response from the CheckResources API call.
type CheckResourcesResponse struct {
*responsev1.CheckResourcesResponse
idx map[string][]int
once sync.Once
}
func (crr *CheckResourcesResponse) buildIdx() {
crr.once.Do(func() {
crr.idx = make(map[string][]int, len(crr.Results))
for i, r := range crr.Results {
v := crr.idx[r.Resource.Id]
crr.idx[r.Resource.Id] = append(v, i)
}
})
}
// GetResource finds the resource with the given ID and optional properties from the result list.
// Returns a ResourceResult object with the Err field set if the resource is not found.
func (crr *CheckResourcesResponse) GetResource(resourceID string, match ...MatchResource) *ResourceResult {
crr.buildIdx()
indexes, ok := crr.idx[resourceID]
if !ok {
return &ResourceResult{err: fmt.Errorf("resource with ID %q does not exist in the response", resourceID)}
}
for _, i := range indexes {
r := crr.Results[i]
if r == nil {
continue
}
found := true
for _, m := range match {
found = found && m(r.Resource)
}
if found {
return &ResourceResult{CheckResourcesResponse_ResultEntry: r}
}
}
return &ResourceResult{err: fmt.Errorf("resource with ID %q does not exist in the response", resourceID)}
}
// Errors returns any validation errors returned by the server.
func (crr *CheckResourcesResponse) Errors() error {
var err error
for _, result := range crr.Results {
for _, verr := range result.ValidationErrors {
err = multierr.Append(err,
fmt.Errorf("resource %q failed validation: source=%s path=%s msg=%s", result.Resource.Id, verr.Source, verr.Path, verr.Message),
)
}
}
return err
}
func (crr *CheckResourcesResponse) String() string {
return protojson.Format(crr.CheckResourcesResponse)
}
func (crr *CheckResourcesResponse) MarshalJSON() ([]byte, error) {
return protojson.Marshal(crr.CheckResourcesResponse)
}
// PolicySet is a container for a set of policies.
type PolicySet struct {
err error
policies []*policyv1.Policy
}
// NewPolicySet creates a new policy set.
func NewPolicySet() *PolicySet {
return &PolicySet{}
}
// AddPolicyFromFile adds a policy from the given file to the set.
func (ps *PolicySet) AddPolicyFromFile(file string) *PolicySet {
f, err := os.Open(file)
if err != nil {
ps.err = multierr.Append(ps.err, fmt.Errorf("failed to add policy from file '%s': %w", file, err))
return ps
}
defer f.Close()
return ps.AddPolicyFromReader(f)
}
// AddPolicyFromFileWithErr adds a policy from the given file to the set and returns the error.
func (ps *PolicySet) AddPolicyFromFileWithErr(file string) (*PolicySet, error) {
f, err := os.Open(file)
if err != nil {
return nil, fmt.Errorf("failed to open file %s: %w", file, err)
}
defer f.Close()
p, err := policy.ReadPolicy(f)
if err != nil {
return nil, fmt.Errorf("failed to read policy: %w", err)
}
return ps.AddPolicies(p), nil
}
// AddPolicyFromReader adds a policy from the given reader to the set.
func (ps *PolicySet) AddPolicyFromReader(r io.Reader) *PolicySet {
p, err := policy.ReadPolicy(r)
if err != nil {
ps.err = multierr.Append(ps.err, fmt.Errorf("failed to add policy from reader: %w", err))
return ps
}
ps.policies = append(ps.policies, p)
return ps
}
// AddPolicies adds the given policies to the set.
func (ps *PolicySet) AddPolicies(policies ...*policyv1.Policy) *PolicySet {
ps.policies = append(ps.policies, policies...)
return ps
}
// AddResourcePolicies adds the given resource policies to the set.
func (ps *PolicySet) AddResourcePolicies(policies ...*ResourcePolicy) *PolicySet {
for _, p := range policies {
if p == nil {
continue
}
if err := ps.add(p); err != nil {
ps.err = multierr.Append(ps.err, fmt.Errorf("failed to add resource policy [%s:%s]: %w", p.p.Resource, p.p.Version, err))
}
}
return ps
}
// AddPrincipalPolicies adds the given principal policies to the set.
func (ps *PolicySet) AddPrincipalPolicies(policies ...*PrincipalPolicy) *PolicySet {
for _, p := range policies {
if p == nil {
continue
}
if err := ps.add(p); err != nil {
ps.err = multierr.Append(ps.err, fmt.Errorf("failed to add principal policy [%s:%s]: %w", p.pp.Principal, p.pp.Version, err))
}
}
return ps
}
// AddDerivedRoles adds the given derived roles to the set.
func (ps *PolicySet) AddDerivedRoles(policies ...*DerivedRoles) *PolicySet {
for _, p := range policies {
if p == nil {
continue
}
if err := ps.add(p); err != nil {
ps.err = multierr.Append(ps.err, fmt.Errorf("failed to add derived roles [%s]: %w", p.dr.Name, err))
}
}
return ps
}
// GetPolicies returns all of the policies in the set.
func (ps *PolicySet) GetPolicies() []*policyv1.Policy {
return ps.policies
}
// Size returns the number of policies in this set.
func (ps *PolicySet) Size() int {
return len(ps.policies)
}
func (ps *PolicySet) add(b interface {
build() (*policyv1.Policy, error)
},
) error {
p, err := b.build()
if err != nil {
return err
}
ps.policies = append(ps.policies, p)
return nil
}
// Err returns the errors accumulated during the construction of the policy set.
func (ps *PolicySet) Err() error {
return ps.err
}
// Validate checks whether the policy set is valid.
func (ps *PolicySet) Validate() error {
if ps.err != nil {
return ps.err
}
if len(ps.policies) == 0 {
return errors.New("empty policy set")
}
return nil
}
// SchemaSet is a container for a set of schemas.
type SchemaSet struct {
err error
schemas []*schemav1.Schema
}
// NewSchemaSet creates a new schema set.
func NewSchemaSet() *SchemaSet {
return &SchemaSet{}
}
// AddSchemaFromFile adds a schema from the given file to the set.
func (ss *SchemaSet) AddSchemaFromFile(file string, ignorePathInID bool) *SchemaSet {
f, err := os.Open(file)
if err != nil {
ss.err = multierr.Append(ss.err, fmt.Errorf("failed to add schema from file '%s': %w", file, err))
return ss
}
name := file
if ignorePathInID {
name = filepath.Base(name)
}
defer f.Close()
return ss.AddSchemaFromReader(f, name)
}
// AddSchemaFromFileWithErr adds a schema from the given file to the set and returns the error.
func (ss *SchemaSet) AddSchemaFromFileWithErr(file string, ignorePathInID bool) (*SchemaSet, error) {
id := file
if ignorePathInID {
id = filepath.Base(id)
}
return ss.AddSchemaFromFileWithIDAndErr(file, id)
}
// AddSchemaFromFileWithIDAndErr adds a schema with the given id from the given file to the set and returns the error.
func (ss *SchemaSet) AddSchemaFromFileWithIDAndErr(file, id string) (*SchemaSet, error) {
f, err := os.Open(file)
if err != nil {
return nil, fmt.Errorf("failed to open file %s: %w", file, err)
}
defer f.Close()
s, err := schema.ReadSchema(f, id)
if err != nil {
return nil, fmt.Errorf("failed to read schema: %w", err)
}
return ss.AddSchemas(s), nil
}
// AddSchemaFromReader adds a schema from the given reader to the set.
func (ss *SchemaSet) AddSchemaFromReader(r io.Reader, id string) *SchemaSet {
s, err := schema.ReadSchema(r, id)
if err != nil {
ss.err = multierr.Append(ss.err, fmt.Errorf("failed to add schema from reader: %w", err))
return ss
}
ss.schemas = append(ss.schemas, s)
return ss
}
// AddSchemas adds the given schemas to the set.
func (ss *SchemaSet) AddSchemas(schemas ...*schemav1.Schema) *SchemaSet {
ss.schemas = append(ss.schemas, schemas...)
return ss
}
// GetSchemas returns all of the schemas in the set.
func (ss *SchemaSet) GetSchemas() []*schemav1.Schema {
return ss.schemas
}
// Size returns the number of schemas in this set.
func (ss *SchemaSet) Size() int {
return len(ss.schemas)
}
// Err returns the errors accumulated during the construction of the schema set.
func (ss *SchemaSet) Err() error {
return ss.err
}
// Schema is a builder for Schemas_Schema.
type Schema struct {
s *policyv1.Schemas_Schema
}
func NewSchema(ref string) *Schema {
return (&Schema{
s: &policyv1.Schemas_Schema{
Ref: "",
IgnoreWhen: &policyv1.Schemas_IgnoreWhen{},
},
}).WithRef(ref)
}
// WithRef sets the ref of this schema.
func (s *Schema) WithRef(ref string) *Schema {
s.s.Ref = ref
return s
}
// AddIgnoredActions adds action(s) to the ignoreWhen field of the schema.
func (s *Schema) AddIgnoredActions(actions ...string) *Schema {
s.s.IgnoreWhen.Actions = append(s.s.IgnoreWhen.Actions, actions...)
return s
}
func (s *Schema) Validate() error {
return s.s.Validate()
}
func (s *Schema) build() *policyv1.Schemas_Schema {
return s.s
}
// ResourcePolicy is a builder for resource policies.
type ResourcePolicy struct {
p *policyv1.ResourcePolicy
err error
}
// NewResourcePolicy creates a new resource policy builder.
func NewResourcePolicy(resource, version string) *ResourcePolicy {
return &ResourcePolicy{
p: &policyv1.ResourcePolicy{
Resource: resource,
Version: version,
},
}
}
// WithDerivedRolesImports adds import statements for derived roles.
func (rp *ResourcePolicy) WithDerivedRolesImports(imp ...string) *ResourcePolicy {
rp.p.ImportDerivedRoles = append(rp.p.ImportDerivedRoles, imp...)
return rp
}
func (rp *ResourcePolicy) WithScope(scope string) *ResourcePolicy {
rp.p.Scope = scope
return rp
}
func (rp *ResourcePolicy) WithPrincipalSchema(principalSchema *Schema) *ResourcePolicy {
rp.p.Schemas.PrincipalSchema = principalSchema.build()
return rp
}
func (rp *ResourcePolicy) WithResourceSchema(resourceSchema *Schema) *ResourcePolicy {
rp.p.Schemas.ResourceSchema = resourceSchema.build()
return rp
}
// AddResourceRules adds resource rules to the policy.
func (rp *ResourcePolicy) AddResourceRules(rules ...*ResourceRule) *ResourcePolicy {
for _, r := range rules {
if r == nil {
continue
}
if err := r.Validate(); err != nil {
rp.err = multierr.Append(rp.err, fmt.Errorf("invalid rule: %w", err))
continue
}
rp.p.Rules = append(rp.p.Rules, r.rule)
}
return rp
}
// Err returns any errors accumulated during the construction of the policy.
func (rp *ResourcePolicy) Err() error {
return rp.err
}
// Validate checks whether the policy is valid.
func (rp *ResourcePolicy) Validate() error {
if rp.err != nil {
return rp.err
}
_, err := rp.build()
return err
}
func (rp *ResourcePolicy) build() (*policyv1.Policy, error) {
p := &policyv1.Policy{
ApiVersion: apiVersion,
PolicyType: &policyv1.Policy_ResourcePolicy{
ResourcePolicy: rp.p,
},
}
return p, policy.Validate(p)
}
// ResourceRule is a rule in a resource policy.
type ResourceRule struct {
rule *policyv1.ResourceRule
}
// NewAllowResourceRule creates a resource rule that allows the actions when matched.
func NewAllowResourceRule(actions ...string) *ResourceRule {
return &ResourceRule{
rule: &policyv1.ResourceRule{
Actions: actions,
Effect: effectv1.Effect_EFFECT_ALLOW,
},
}
}
// NewDenyResourceRule creates a resource rule that denies the actions when matched.
func NewDenyResourceRule(actions ...string) *ResourceRule {
return &ResourceRule{
rule: &policyv1.ResourceRule{
Actions: actions,
Effect: effectv1.Effect_EFFECT_DENY,
},
}
}
// WithName sets the name of the ResourceRule.
func (rr *ResourceRule) WithName(name string) *ResourceRule {
rr.rule.Name = name
return rr
}
// WithRoles adds roles to which this rule applies.
func (rr *ResourceRule) WithRoles(roles ...string) *ResourceRule {
rr.rule.Roles = append(rr.rule.Roles, roles...)
return rr
}
// WithDerivedRoles adds derived roles to which this rule applies.
func (rr *ResourceRule) WithDerivedRoles(roles ...string) *ResourceRule {
rr.rule.DerivedRoles = append(rr.rule.DerivedRoles, roles...)
return rr
}
// WithCondition sets the condition that applies to this rule.
func (rr *ResourceRule) WithCondition(m match) *ResourceRule {
rr.rule.Condition = &policyv1.Condition{
Condition: &policyv1.Condition_Match{
Match: m.build(),
},
}
return rr
}
// Err returns errors accumulated during the construction of the resource rule.
func (rr *ResourceRule) Err() error {
return nil
}
// Validate checks whether the resource rule is valid.
func (rr *ResourceRule) Validate() error {
return rr.rule.Validate()
}
// PrincipalPolicy is a builder for principal policies.
type PrincipalPolicy struct {
pp *policyv1.PrincipalPolicy
err error
}
// NewPrincipalPolicy creates a new principal policy.
func NewPrincipalPolicy(principal, version string) *PrincipalPolicy {
return &PrincipalPolicy{
pp: &policyv1.PrincipalPolicy{
Principal: principal,
Version: version,
},
}
}
// AddPrincipalRules adds rules to this policy.
func (pp *PrincipalPolicy) AddPrincipalRules(rules ...*PrincipalRule) *PrincipalPolicy {
for _, r := range rules {
if r == nil {
continue
}
if err := r.Validate(); err != nil {
pp.err = multierr.Append(pp.err, fmt.Errorf("invalid rule: %w", err))
continue
}
pp.pp.Rules = append(pp.pp.Rules, r.rule)
}
return pp
}
// WithScope sets the scope of this policy.
func (pp *PrincipalPolicy) WithScope(scope string) *PrincipalPolicy {
pp.pp.Scope = scope
return pp
}
// WithVersion sets the version of this policy.
func (pp *PrincipalPolicy) WithVersion(version string) *PrincipalPolicy {
pp.pp.Version = version
return pp
}
// Err returns the errors accumulated during the construction of this policy.
func (pp *PrincipalPolicy) Err() error {
return pp.err
}
// Validate checks whether the policy is valid.
func (pp *PrincipalPolicy) Validate() error {
if pp.err != nil {
return pp.err
}