-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathaccess_request.go
1941 lines (1709 loc) · 67.1 KB
/
access_request.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 2019 Gravitational, 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 services
import (
"context"
"sort"
"strings"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/uuid"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/vulcand/predicate"
"golang.org/x/exp/slices"
"github.com/gravitational/teleport/api/accessrequest"
"github.com/gravitational/teleport/api/client"
apidefaults "github.com/gravitational/teleport/api/defaults"
"github.com/gravitational/teleport/api/types"
apiutils "github.com/gravitational/teleport/api/utils"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/utils/parse"
)
const maxAccessRequestReasonSize = 4096
// A day is sometimes 23 hours, sometimes 25 hours, usually 24 hours.
const day = 24 * time.Hour
// maxAccessDuration is the maximum duration that an access request can be
// granted for.
const maxAccessDuration = 7 * day
// ValidateAccessRequest validates the AccessRequest and sets default values
func ValidateAccessRequest(ar types.AccessRequest) error {
if err := ar.CheckAndSetDefaults(); err != nil {
return trace.Wrap(err)
}
_, err := uuid.Parse(ar.GetName())
if err != nil {
return trace.BadParameter("invalid access request id %q", ar.GetName())
}
if len(ar.GetRequestReason()) > maxAccessRequestReasonSize {
return trace.BadParameter("access request reason is too long, max %v bytes", maxAccessRequestReasonSize)
}
if len(ar.GetResolveReason()) > maxAccessRequestReasonSize {
return trace.BadParameter("access request resolve reason is too long, max %v bytes", maxAccessRequestReasonSize)
}
return nil
}
// ClusterGetter provides access to the local cluster
type ClusterGetter interface {
// GetClusterName returns the local cluster name
GetClusterName(opts ...MarshalOption) (types.ClusterName, error)
// GetRemoteCluster returns a remote cluster by name
GetRemoteCluster(clusterName string) (types.RemoteCluster, error)
}
// ValidateAccessRequestClusterNames checks that the clusters in the access request exist
func ValidateAccessRequestClusterNames(cg ClusterGetter, ar types.AccessRequest) error {
localClusterName, err := cg.GetClusterName()
if err != nil {
return trace.Wrap(err)
}
var invalidClusters []string
for _, resourceID := range ar.GetRequestedResourceIDs() {
if resourceID.ClusterName == "" {
continue
}
if resourceID.ClusterName == localClusterName.GetClusterName() {
continue
}
_, err := cg.GetRemoteCluster(resourceID.ClusterName)
if err != nil && !trace.IsNotFound(err) {
return trace.Wrap(err, "failed to fetch remote cluster %q", resourceID.ClusterName)
}
if trace.IsNotFound(err) {
invalidClusters = append(invalidClusters, resourceID.ClusterName)
}
}
if len(invalidClusters) > 0 {
return trace.NotFound("access request contains invalid or unknown cluster names: %v",
strings.Join(invalidClusters, ", "))
}
return nil
}
// NewAccessRequest assembles an AccessRequest resource.
func NewAccessRequest(user string, roles ...string) (types.AccessRequest, error) {
return NewAccessRequestWithResources(user, roles, []types.ResourceID{})
}
// NewAccessRequestWithResources assembles an AccessRequest resource with
// requested resources.
func NewAccessRequestWithResources(user string, roles []string, resourceIDs []types.ResourceID) (types.AccessRequest, error) {
req, err := types.NewAccessRequestWithResources(uuid.New().String(), user, roles, resourceIDs)
if err != nil {
return nil, trace.Wrap(err)
}
if err := ValidateAccessRequest(req); err != nil {
return nil, trace.Wrap(err)
}
return req, nil
}
// RequestIDs is a collection of IDs for privilege escalation requests.
type RequestIDs struct {
AccessRequests []string `json:"access_requests,omitempty"`
}
func (r *RequestIDs) Marshal() ([]byte, error) {
data, err := utils.FastMarshal(r)
if err != nil {
return nil, trace.Wrap(err)
}
return data, nil
}
func (r *RequestIDs) Unmarshal(data []byte) error {
if err := utils.FastUnmarshal(data, r); err != nil {
return trace.Wrap(err)
}
return trace.Wrap(r.Check())
}
func (r *RequestIDs) Check() error {
for _, id := range r.AccessRequests {
_, err := uuid.Parse(id)
if err != nil {
return trace.BadParameter("invalid request id %q", id)
}
}
return nil
}
func (r *RequestIDs) IsEmpty() bool {
return len(r.AccessRequests) < 1
}
// AccessRequestGetter defines the interface for fetching access request resources.
type AccessRequestGetter interface {
// GetAccessRequests gets all currently active access requests.
GetAccessRequests(ctx context.Context, filter types.AccessRequestFilter) ([]types.AccessRequest, error)
// GetPluginData loads all plugin data matching the supplied filter.
GetPluginData(ctx context.Context, filter types.PluginDataFilter) ([]types.PluginData, error)
}
// DynamicAccessCore is the core functionality common to all DynamicAccess implementations.
type DynamicAccessCore interface {
AccessRequestGetter
// CreateAccessRequestV2 stores a new access request.
CreateAccessRequestV2(ctx context.Context, req types.AccessRequest) (types.AccessRequest, error)
// DeleteAccessRequest deletes an access request.
DeleteAccessRequest(ctx context.Context, reqID string) error
// UpdatePluginData updates a per-resource PluginData entry.
UpdatePluginData(ctx context.Context, params types.PluginDataUpdateParams) error
}
// DynamicAccess is a service which manages dynamic RBAC. Specifically, this is the
// dynamic access interface implemented by remote clients.
type DynamicAccess interface {
DynamicAccessCore
// SetAccessRequestState updates the state of an existing access request.
SetAccessRequestState(ctx context.Context, params types.AccessRequestUpdate) error
// SubmitAccessReview applies a review to a request and returns the post-application state.
SubmitAccessReview(ctx context.Context, params types.AccessReviewSubmission) (types.AccessRequest, error)
// GetAccessRequestAllowedPromotions returns suggested access lists for the given access request.
GetAccessRequestAllowedPromotions(ctx context.Context, req types.AccessRequest) (*types.AccessRequestAllowedPromotions, error)
}
// DynamicAccessOracle is a service capable of answering questions related
// to the dynamic access API. Necessary because some information (e.g. the
// list of roles a user is allowed to request) can not be calculated by
// actors with limited privileges.
type DynamicAccessOracle interface {
GetAccessCapabilities(ctx context.Context, req types.AccessCapabilitiesRequest) (*types.AccessCapabilities, error)
}
// CalculateAccessCapabilities aggregates the requested capabilities using the supplied getter
// to load relevant resources.
func CalculateAccessCapabilities(ctx context.Context, clock clockwork.Clock, clt RequestValidatorGetter, req types.AccessCapabilitiesRequest) (*types.AccessCapabilities, error) {
var caps types.AccessCapabilities
// all capabilities require use of a request validator. calculating suggested reviewers
// requires that the validator be configured for variable expansion.
v, err := NewRequestValidator(ctx, clock, clt, req.User, ExpandVars(req.SuggestedReviewers))
if err != nil {
return nil, trace.Wrap(err)
}
if len(req.ResourceIDs) != 0 {
caps.ApplicableRolesForResources, err = v.applicableSearchAsRoles(ctx, req.ResourceIDs, "")
if err != nil {
return nil, trace.Wrap(err)
}
}
if req.RequestableRoles {
caps.RequestableRoles, err = v.GetRequestableRoles()
if err != nil {
return nil, trace.Wrap(err)
}
}
if req.SuggestedReviewers {
caps.SuggestedReviewers = v.SuggestedReviewers
}
caps.RequireReason = v.requireReason
caps.RequestPrompt = v.prompt
caps.AutoRequest = v.autoRequest
return &caps, nil
}
// applicableSearchAsRoles prunes the search_as_roles and only returns those
// application for the given list of resourceIDs.
func (m *RequestValidator) applicableSearchAsRoles(ctx context.Context, resourceIDs []types.ResourceID, loginHint string) ([]string, error) {
// First collect all possible search_as_roles.
var rolesToRequest []string
for _, roleName := range m.Roles.AllowSearch {
if !m.CanSearchAsRole(roleName) {
continue
}
rolesToRequest = append(rolesToRequest, roleName)
}
if len(rolesToRequest) == 0 {
return nil, trace.AccessDenied(`Resource Access Requests require usable "search_as_roles", none found for user %q`, m.userState.GetName())
}
// Prune the list of roles to request to only those which may be necessary
// to access the requested resources.
var err error
rolesToRequest, err = m.pruneResourceRequestRoles(ctx, resourceIDs, loginHint, rolesToRequest)
if err != nil {
return nil, trace.Wrap(err)
}
return rolesToRequest, nil
}
// DynamicAccessExt is an extended dynamic access interface
// used to implement some auth server internals.
type DynamicAccessExt interface {
DynamicAccessCore
// CreateAccessRequest stores a new access request.
CreateAccessRequest(ctx context.Context, req types.AccessRequest) error
// ApplyAccessReview applies a review to a request in the backend and returns the post-application state.
ApplyAccessReview(ctx context.Context, params types.AccessReviewSubmission, checker ReviewPermissionChecker) (types.AccessRequest, error)
// UpsertAccessRequest creates or updates an access request.
UpsertAccessRequest(ctx context.Context, req types.AccessRequest) error
// DeleteAllAccessRequests deletes all existent access requests.
DeleteAllAccessRequests(ctx context.Context) error
// SetAccessRequestState updates the state of an existing access request.
SetAccessRequestState(ctx context.Context, params types.AccessRequestUpdate) (types.AccessRequest, error)
// CreateAccessRequestAllowedPromotions creates a list of allowed access list promotions for the given access request.
CreateAccessRequestAllowedPromotions(ctx context.Context, req types.AccessRequest, accessLists *types.AccessRequestAllowedPromotions) error
// GetAccessRequestAllowedPromotions returns a lists of allowed access list promotions for the given access request.
GetAccessRequestAllowedPromotions(ctx context.Context, req types.AccessRequest) (*types.AccessRequestAllowedPromotions, error)
}
// reviewParamsContext is a simplified view of an access review
// which represents the incoming review during review threshold
// filter evaluation.
type reviewParamsContext struct {
Reason string `json:"reason"`
Annotations map[string][]string `json:"annotations"`
}
// reviewAuthorContext is a simplified view of a user
// resource which represents the author of a review during
// review threshold filter evaluation.
type reviewAuthorContext struct {
Roles []string `json:"roles"`
Traits map[string][]string `json:"traits"`
}
// reviewRequestContext is a simplified view of an access request
// resource which represents the request parameters which are in-scope
// during review threshold filter evaluation.
type reviewRequestContext struct {
Roles []string `json:"roles"`
Reason string `json:"reason"`
SystemAnnotations map[string][]string `json:"system_annotations"`
}
// thresholdFilterContext is the top-level context used to evaluate
// review threshold filters.
type thresholdFilterContext struct {
Reviewer reviewAuthorContext `json:"reviewer"`
Review reviewParamsContext `json:"review"`
Request reviewRequestContext `json:"request"`
}
// reviewPermissionContext is the top-level context used to evaluate
// a user's review permissions. It is functionally identical to the
// thresholdFilterContext except that it does not expose review parameters.
// this is because review permissions are used to determine which requests
// a user is allowed to see, and therefore needs to be calculable prior
// to construction of review parameters.
type reviewPermissionContext struct {
Reviewer reviewAuthorContext `json:"reviewer"`
Request reviewRequestContext `json:"request"`
}
// ValidateAccessPredicates checks request & review permission predicates for
// syntax errors. Used to help prevent users from accidentally writing incorrect
// predicates. This function should only be called by the auth server prior to
// storing new/updated roles. Normal role validation deliberately omits these
// checks in order to allow us to extend the available namespaces without breaking
// backwards compatibility with older nodes/proxies (which never need to evaluate
// these predicates).
func ValidateAccessPredicates(role types.Role) error {
tp, err := NewJSONBoolParser(thresholdFilterContext{})
if err != nil {
return trace.Wrap(err, "failed to build empty threshold predicate parser (this is a bug)")
}
if len(role.GetAccessRequestConditions(types.Deny).Thresholds) != 0 {
// deny blocks never contain thresholds. a threshold which happens to describe a *denial condition* is
// still part of the "allow" block. thresholds are not part of deny blocks because thresholds describe the
// state-transition scenarios supported by a request (including potentially being denied). deny.request blocks match
// requests which are *never* allowable, and therefore will never reach the point of needing to encode thresholds.
return trace.BadParameter("deny.request cannot contain thresholds, set denial counts in allow.request.thresholds instead")
}
for _, t := range role.GetAccessRequestConditions(types.Allow).Thresholds {
if t.Filter == "" {
continue
}
if _, err := tp.EvalBoolPredicate(t.Filter); err != nil {
return trace.BadParameter("invalid threshold predicate: %q, %v", t.Filter, err)
}
}
rp, err := NewJSONBoolParser(reviewPermissionContext{})
if err != nil {
return trace.Wrap(err, "failed to build empty review predicate parser (this is a bug)")
}
if w := role.GetAccessReviewConditions(types.Deny).Where; w != "" {
if _, err := rp.EvalBoolPredicate(w); err != nil {
return trace.BadParameter("invalid review predicate: %q, %v", w, err)
}
}
if w := role.GetAccessReviewConditions(types.Allow).Where; w != "" {
if _, err := rp.EvalBoolPredicate(w); err != nil {
return trace.BadParameter("invalid review predicate: %q, %v", w, err)
}
}
if maxDuration := role.GetAccessRequestConditions(types.Allow).MaxDuration; maxDuration.Duration() != 0 &&
maxDuration.Duration() > maxAccessDuration {
return trace.BadParameter("max access duration must be less or equal 7 days")
}
return nil
}
// ApplyAccessReview attempts to apply the specified access review to the specified request.
func ApplyAccessReview(req types.AccessRequest, rev types.AccessReview, author UserState) error {
if rev.Author != author.GetName() {
return trace.BadParameter("mismatched review author (expected %q, got %q)", rev.Author, author)
}
// role lists must be deduplicated and sorted
rev.Roles = apiutils.Deduplicate(rev.Roles)
sort.Strings(rev.Roles)
// basic compatibility/sanity checks
if err := checkReviewCompat(req, rev); err != nil {
return trace.Wrap(err)
}
// aggregate the threshold indexes for this review
tids, err := collectReviewThresholdIndexes(req, rev, author)
if err != nil {
return trace.Wrap(err)
}
// set a review created time if not already set
if rev.Created.IsZero() {
rev.Created = time.Now()
}
// set threshold indexes
rev.ThresholdIndexes = tids
// Resolved requests should not be updated.
switch {
case req.GetState().IsApproved():
return trace.AccessDenied("the access request has been already approved")
case req.GetState().IsDenied():
return trace.AccessDenied("the access request has been already denied")
case req.GetState().IsPromoted():
return trace.AccessDenied("the access request has been already promoted")
}
req.SetReviews(append(req.GetReviews(), rev))
// request is still pending, so check to see if this
// review introduces a state-transition.
res, err := calculateReviewBasedResolution(req)
if err != nil || res == nil {
return trace.Wrap(err)
}
// state-transition was triggered. update the appropriate fields.
if err := req.SetState(res.state); err != nil {
return trace.Wrap(err)
}
req.SetResolveReason(res.reason)
if req.GetPromotedAccessListName() == "" {
// Set the title only if it's not set yet. This is to prevent
// overwriting the title by another promotion review.
req.SetPromotedAccessListName(rev.GetAccessListName())
req.SetPromotedAccessListTitle(rev.GetAccessListTitle())
}
req.SetExpiry(req.GetAccessExpiry())
return nil
}
// checkReviewCompat performs basic checks to ensure that the specified review can be
// applied to the specified request (part of review application logic).
func checkReviewCompat(req types.AccessRequest, rev types.AccessReview) error {
// Proposal cannot be already resolved.
if !rev.ProposedState.IsResolved() {
// Skip the promoted state in the error message. It's not a state that most people
// should be concerned with.
return trace.BadParameter("invalid state proposal: %s (expected approval/denial)", rev.ProposedState)
}
// the default threshold should exist. if it does not, the request either is not fully
// initialized (i.e., variable expansion has not been run yet), or the request was inserted into
// the backend by a teleport instance which does not support the review feature.
if len(req.GetThresholds()) == 0 {
return trace.BadParameter("request is uninitialized or does not support reviews")
}
// user must not have previously reviewed this request
for _, existingReview := range req.GetReviews() {
if existingReview.Author == rev.Author {
return trace.AccessDenied("user %q has already reviewed this request", rev.Author)
}
}
rtm := req.GetRoleThresholdMapping()
// TODO(fspmarshall): Remove this restriction once role overrides
// in reviews are fully supported.
if len(rev.Roles) != 0 && len(rev.Roles) != len(rtm) {
return trace.NotImplemented("role subselection is not yet supported in reviews, try omitting role list")
}
// TODO(fspmarhsall): Remove this restriction once annotations
// in reviews are fully supported.
if len(rev.Annotations) != 0 {
return trace.NotImplemented("annotations are not yet supported in reviews, try omitting annotations field")
}
// verify that all roles are present within the request
for _, role := range rev.Roles {
if _, ok := rtm[role]; !ok {
return trace.BadParameter("role %q is not a member of this request", role)
}
}
return nil
}
// collectReviewThresholdIndexes aggregates the indexes of all thresholds whose filters match
// the supplied review (part of review application logic).
func collectReviewThresholdIndexes(req types.AccessRequest, rev types.AccessReview, author UserState) ([]uint32, error) {
parser, err := newThresholdFilterParser(req, rev, author)
if err != nil {
return nil, trace.Wrap(err)
}
var tids []uint32
for i, t := range req.GetThresholds() {
match, err := accessReviewThresholdMatchesFilter(t, parser)
if err != nil {
return nil, trace.Wrap(err)
}
if !match {
continue
}
tid := uint32(i)
if int(tid) != i {
// sanity-check. we disallow extremely large threshold lists elsewhere, but it's always
// best to double-check these things.
return nil, trace.Errorf("threshold index %d out of supported range (this is a bug)", i)
}
tids = append(tids, tid)
}
return tids, nil
}
// accessReviewThresholdMatchesFilter returns true if Filter rule matches
// Empty Filter block always matches
func accessReviewThresholdMatchesFilter(t types.AccessReviewThreshold, parser predicate.Parser) (bool, error) {
if t.Filter == "" {
return true, nil
}
ifn, err := parser.Parse(t.Filter)
if err != nil {
return false, trace.Wrap(err)
}
fn, ok := ifn.(predicate.BoolPredicate)
if !ok {
return false, trace.BadParameter("unsupported type: %T", ifn)
}
return fn(), nil
}
// newThresholdFilterParser creates a custom parser context which exposes a simplified view of the review author
// and the request for evaluation of review threshold filters.
func newThresholdFilterParser(req types.AccessRequest, rev types.AccessReview, author UserState) (BoolPredicateParser, error) {
return NewJSONBoolParser(thresholdFilterContext{
Reviewer: reviewAuthorContext{
Roles: author.GetRoles(),
Traits: author.GetTraits(),
},
Review: reviewParamsContext{
Reason: rev.Reason,
Annotations: rev.Annotations,
},
Request: reviewRequestContext{
Roles: req.GetOriginalRoles(),
Reason: req.GetRequestReason(),
SystemAnnotations: req.GetSystemAnnotations(),
},
})
}
// requestResolution describes a request state-transition from
// PENDING to some other state.
type requestResolution struct {
state types.RequestState
reason string
}
// calculateReviewBasedResolution calculates the request resolution based upon
// a request's reviews. Returns (nil,nil) in the event no resolution has been reached.
func calculateReviewBasedResolution(req types.AccessRequest) (*requestResolution, error) {
// thresholds and reviews must be populated before state-transitions are possible
thresholds, reviews := req.GetThresholds(), req.GetReviews()
if len(thresholds) == 0 || len(reviews) == 0 {
return nil, nil
}
// approved keeps track of roles that have hit at least one
// of their approval thresholds.
approved := make(map[string]struct{})
// denied keeps track of whether or not we've seen *any* role get denied
// (which role does not currently matter since we short-circuit on the
// first denial to be triggered).
denied := false
// counts keeps track of the approval and denial counts for all thresholds.
counts := make([]struct{ approval, denial uint32 }, len(thresholds))
// lastReview stores the most recently processed review. Since processing halts
// once we hit our first approval/denial condition, this review represents the
// triggering review for the approval/denial state-transition.
var lastReview types.AccessReview
// Iterate through all reviews and aggregate them against `counts`.
ProcessReviews:
for _, rev := range reviews {
lastReview = rev
for _, tid := range rev.ThresholdIndexes {
idx := int(tid)
if len(thresholds) <= idx {
return nil, trace.Errorf("threshold index '%d' out of range (this is a bug)", idx)
}
switch {
case rev.ProposedState.IsApproved():
counts[idx].approval++
case rev.ProposedState.IsDenied():
counts[idx].denial++
case rev.ProposedState.IsPromoted():
// Promote skips the threshold check.
break ProcessReviews
default:
return nil, trace.BadParameter("cannot calculate state-transition, unexpected proposal: %s", rev.ProposedState)
}
}
// If we hit any denial thresholds, short-circuit immediately
for i, t := range thresholds {
if counts[i].denial >= t.Deny && t.Deny != 0 {
denied = true
break ProcessReviews
}
}
// check for roles that can be transitioned to an approved state
CheckRoleApprovals:
for role, thresholdSets := range req.GetRoleThresholdMapping() {
if _, ok := approved[role]; ok {
// role was marked approved during a previous iteration
continue CheckRoleApprovals
}
// iterate through all threshold sets. All sets must have at least
// one threshold which has hit its approval count in order for the
// role to be considered approved.
CheckThresholdSets:
for _, tset := range thresholdSets.Sets {
for _, tid := range tset.Indexes {
idx := int(tid)
if len(thresholds) <= idx {
return nil, trace.Errorf("threshold index out of range %s/%d (this is a bug)", role, tid)
}
t := thresholds[idx]
if counts[idx].approval >= t.Approve && t.Approve != 0 {
// this set contains a threshold which has met its approval condition.
// skip to the next set.
continue CheckThresholdSets
}
}
// no thresholds met for this set. there may be additional roles/thresholds
// which did meet their requirements this iteration, but there is no point
// processing them unless this set has also hit its requirements. we therefore
// move immediately to processing the next review.
continue ProcessReviews
}
// since we skip to the next review as soon as we see a set which has not hit any of its
// approval scenarios, we know that if we get to this point the role must be approved.
approved[role] = struct{}{}
}
// If we got here, then we iterated across all roles in the rtm without hitting any that
// had not met their approval scenario. The request has hit an approved state and further
// reviews will not be processed.
break ProcessReviews
}
switch {
case lastReview.ProposedState.IsApproved():
if len(approved) != len(req.GetRoleThresholdMapping()) {
// processing halted on approval, but not all roles have
// hit their approval thresholds; no state-transition.
return nil, nil
}
case lastReview.ProposedState.IsDenied():
if !denied {
// processing halted on denial, but no roles have hit
// their denial thresholds; no state-transition.
return nil, nil
}
case lastReview.ProposedState.IsPromoted():
// Let the state change. Promoted won't grant any access, meaning it is roughly equivalent to denial.
// But we want to be able to distinguish between promoted and denied in audit logs/UI.
default:
return nil, trace.BadParameter("cannot calculate state-transition, unexpected proposal: %s", lastReview.ProposedState)
}
// processing halted on valid state-transition; return resolution
// based on last review
return &requestResolution{
state: lastReview.ProposedState,
reason: lastReview.Reason,
}, nil
}
// GetAccessRequest is a helper function assists with loading a specific request by ID.
func GetAccessRequest(ctx context.Context, acc DynamicAccess, reqID string) (types.AccessRequest, error) {
reqs, err := acc.GetAccessRequests(ctx, types.AccessRequestFilter{
ID: reqID,
})
if err != nil {
return nil, trace.Wrap(err)
}
if len(reqs) < 1 {
return nil, trace.NotFound("no access request matching %q", reqID)
}
return reqs[0], nil
}
// GetTraitMappings gets the AccessRequestConditions' claims as a TraitMappingsSet
func GetTraitMappings(cms []types.ClaimMapping) types.TraitMappingSet {
tm := make([]types.TraitMapping, 0, len(cms))
for _, mapping := range cms {
tm = append(tm, types.TraitMapping{
Trait: mapping.Claim,
Value: mapping.Value,
Roles: mapping.Roles,
})
}
return types.TraitMappingSet(tm)
}
// RequestValidatorGetter is the interface required by the request validation
// functions used to get necessary resources.
type RequestValidatorGetter interface {
UserLoginStatesGetter
UserGetter
RoleGetter
client.ListResourcesClient
GetRoles(ctx context.Context) ([]types.Role, error)
GetClusterName(opts ...MarshalOption) (types.ClusterName, error)
}
// appendRoleMatchers constructs all role matchers for a given
// AccessRequestConditions instance and appends them to the
// supplied matcher slice.
func appendRoleMatchers(matchers []parse.Matcher, roles []string, cms []types.ClaimMapping, traits map[string][]string) ([]parse.Matcher, error) {
// build matchers for the role list
for _, r := range roles {
m, err := parse.NewMatcher(r)
if err != nil {
return nil, trace.Wrap(err)
}
matchers = append(matchers, m)
}
// build matchers for all role mappings
ms, err := TraitsToRoleMatchers(GetTraitMappings(cms), traits)
if err != nil {
return nil, trace.Wrap(err)
}
return append(matchers, ms...), nil
}
// insertAnnotations constructs all annotations for a given
// AccessRequestConditions instance and adds them to the
// supplied annotations mapping.
func insertAnnotations(annotations map[string][]string, conditions types.AccessRequestConditions, traits map[string][]string) {
for key, vals := range conditions.Annotations {
// get any previous values at key
allVals := annotations[key]
// iterate through all new values and expand any
// variable interpolation syntax they contain.
ApplyTraits:
for _, v := range vals {
applied, err := ApplyValueTraits(v, traits)
if err != nil {
// skip values that failed variable expansion
continue ApplyTraits
}
allVals = append(allVals, applied...)
}
annotations[key] = allVals
}
}
// ReviewPermissionChecker is a helper for validating whether a user
// is allowed to review specific access requests.
type ReviewPermissionChecker struct {
UserState UserState
Roles struct {
// allow/deny mappings sort role matches into lists based on their
// constraining predicate (where) expression.
AllowReview, DenyReview map[string][]parse.Matcher
}
}
// HasAllowDirectives checks if any allow directives exist. A user with
// no allow directives will never be able to review any requests.
func (c *ReviewPermissionChecker) HasAllowDirectives() bool {
for _, allowMatchers := range c.Roles.AllowReview {
if len(allowMatchers) > 0 {
return true
}
}
return false
}
// CanReviewRequest checks if the user is allowed to review the specified request.
// note that the ability to review a request does not necessarily imply that any specific
// approval/denial thresholds will actually match the user's review. Matching one or more
// thresholds is not a pre-requisite for review submission.
func (c *ReviewPermissionChecker) CanReviewRequest(req types.AccessRequest) (bool, error) {
// TODO(fspmarshall): Refactor this to improve readability when
// adding role subselection support.
// user cannot review their own request
if c.UserState.GetName() == req.GetUser() {
return false, nil
}
// method allocates new array if an override has already been
// called, so get the role list once in advance.
requestedRoles := req.GetOriginalRoles()
parser, err := NewJSONBoolParser(reviewPermissionContext{
Reviewer: reviewAuthorContext{
Roles: c.UserState.GetRoles(),
Traits: c.UserState.GetTraits(),
},
Request: reviewRequestContext{
Roles: requestedRoles,
Reason: req.GetRequestReason(),
SystemAnnotations: req.GetSystemAnnotations(),
},
})
if err != nil {
return false, trace.Wrap(err)
}
// check all denial rules first.
for expr, denyMatchers := range c.Roles.DenyReview {
// if predicate is non-empty, it must match
if expr != "" {
match, err := parser.EvalBoolPredicate(expr)
if err != nil {
return false, trace.Wrap(err)
}
if !match {
continue
}
}
for _, role := range requestedRoles {
for _, deny := range denyMatchers {
if deny.Match(role) {
// short-circuit on first denial
return false, nil
}
}
}
}
// needsAllow tracks the list of roles which still need to match an allow directive
// in order for the request to be reviewable. we need to perform a deep copy here
// since we perform a filter-in-place when we find a matching allow directive.
needsAllow := make([]string, len(requestedRoles))
copy(needsAllow, requestedRoles)
Outer:
for expr, allowMatchers := range c.Roles.AllowReview {
// if predicate is non-empty, it must match.
if expr != "" {
match, err := parser.EvalBoolPredicate(expr)
if err != nil {
return false, trace.Wrap(err)
}
if !match {
continue Outer
}
}
// unmatched collects unmatched roles for our filter-in-place operation.
unmatched := needsAllow[:0]
MatchRoles:
for _, role := range needsAllow {
for _, allow := range allowMatchers {
if allow.Match(role) {
// role matched this allow directive, and will be filtered out
continue MatchRoles
}
}
// still unmatched, this role will continue to be part of
// the needsAllow list next iteration.
unmatched = append(unmatched, role)
}
// finalize our filter-in-place
needsAllow = unmatched
if len(needsAllow) == 0 {
// all roles have matched an allow directive, no further
// processing is required.
break Outer
}
}
return len(needsAllow) == 0, nil
}
type userStateRoleOverride struct {
UserState
Roles []string
}
func (u userStateRoleOverride) GetRoles() []string {
return u.Roles
}
func NewReviewPermissionChecker(
ctx context.Context,
getter RequestValidatorGetter,
username string,
identity *tlsca.Identity,
) (ReviewPermissionChecker, error) {
uls, err := GetUserOrLoginState(ctx, getter, username)
if err != nil {
return ReviewPermissionChecker{}, trace.Wrap(err)
}
// By default, the users freshly fetched roles are used rather than the
// roles on the x509 identity. This prevents recursive access request
// review.
//
// For bots, however, the roles on the identity must be used. This is
// because the certs output by a bot always use role impersonation and the
// role directly assigned to a bot has minimal permissions.
if uls.IsBot() {
if identity == nil {
// Handle an edge case where SubmitAccessReview is being invoked
// in-memory but as a bot user.
return ReviewPermissionChecker{}, trace.BadParameter(
"bot user provided but identity parameter is nil",
)
}
if identity.Username != username {
// It should not be possible for these to be different as a
// guard in AuthorizeAccessReviewRequest prevents submitting a
// request as another user unless you have the admin role. This
// safeguard protects against that regressing and creating an
// inconsistent state.
return ReviewPermissionChecker{}, trace.BadParameter(
"bot identity username and review author mismatch",
)
}
if len(identity.ActiveRequests) > 0 {
// It should not be possible for a bot's output certificates to
// have active requests - but this additional check safeguards us
// against a regression elsewhere and prevents recursive access
// requests occurring.
return ReviewPermissionChecker{}, trace.BadParameter(
"bot should not have active requests",
)
}
// Override list of roles to roles currently present on the x509 ident.
uls = userStateRoleOverride{
UserState: uls,
Roles: identity.Groups,
}
}
c := ReviewPermissionChecker{
UserState: uls,
}
c.Roles.AllowReview = make(map[string][]parse.Matcher)
c.Roles.DenyReview = make(map[string][]parse.Matcher)
// load all statically assigned roles for the user and
// use them to build our checker state.
for _, roleName := range c.UserState.GetRoles() {
role, err := getter.GetRole(ctx, roleName)
if err != nil {
return ReviewPermissionChecker{}, trace.Wrap(err)
}
if err := c.push(role); err != nil {
return ReviewPermissionChecker{}, trace.Wrap(err)
}
}
return c, nil
}
func (c *ReviewPermissionChecker) push(role types.Role) error {
allow, deny := role.GetAccessReviewConditions(types.Allow), role.GetAccessReviewConditions(types.Deny)
var err error
c.Roles.DenyReview[deny.Where], err = appendRoleMatchers(c.Roles.DenyReview[deny.Where], deny.Roles, deny.ClaimsToRoles, c.UserState.GetTraits())
if err != nil {
return trace.Wrap(err)
}
c.Roles.AllowReview[allow.Where], err = appendRoleMatchers(c.Roles.AllowReview[allow.Where], allow.Roles, allow.ClaimsToRoles, c.UserState.GetTraits())
if err != nil {