Debian Codegraph @

pkg/admission/plugin/authorizer/caching_authorizer.go

raw
1 /*
2 Copyright 2023 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package authorizer
18
19 import (
20 "context"
21 "encoding/json"
22 "sort"
23 "strings"
24
25 "k8s.io/apimachinery/pkg/fields"
26 "k8s.io/apimachinery/pkg/labels"
27 "k8s.io/apiserver/pkg/authentication/user"
28 "k8s.io/apiserver/pkg/authorization/authorizer"
29 )
30
31 type authzResult struct {
32 authorized authorizer.Decision
33 reason string
34 err error
35 }
36
37 type cachingAuthorizer struct {
38 authorizer authorizer.Authorizer
39 decisions map[string]authzResult
40 }
41
42 // NewCachingAuthorizer returns an authorizer that caches decisions for the duration
43 // of the authorizers use. Intended to be used for short-lived operations such as
44 // the handling of a request in the admission chain, and then discarded.
45 func NewCachingAuthorizer(in authorizer.Authorizer) authorizer.Authorizer {
46 return &cachingAuthorizer{
47 authorizer: in,
48 decisions: make(map[string]authzResult),
49 }
50 }
51
52 // The attribute accessors known to cache key construction. If this fails to compile, the cache
53 // implementation may need to be updated.
54 var _ authorizer.Attributes = (interface {
55 GetUser() user.Info
56 GetVerb() string
57 IsReadOnly() bool
58 GetNamespace() string
59 GetResource() string
60 GetSubresource() string
61 GetName() string
62 GetAPIGroup() string
63 GetAPIVersion() string
64 IsResourceRequest() bool
65 GetPath() string
66 GetFieldSelector() (fields.Requirements, error)
67 GetLabelSelector() (labels.Requirements, error)
68 })(nil)
69
70 // The user info accessors known to cache key construction. If this fails to compile, the cache
71 // implementation may need to be updated.
72 var _ user.Info = (interface {
73 GetName() string
74 GetUID() string
75 GetGroups() []string
76 GetExtra() map[string][]string
77 })(nil)
78
79 // Authorize returns an authorization decision by delegating to another Authorizer. If an equivalent
80 // check has already been performed, a cached result is returned. Not safe for concurrent use.
81 func (ca *cachingAuthorizer) Authorize(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) {
82 type SerializableAttributes struct {
83 authorizer.AttributesRecord
84 LabelSelector string
85 }
86
87 serializableAttributes := SerializableAttributes{
88 AttributesRecord: authorizer.AttributesRecord{
89 Verb: a.GetVerb(),
90 Namespace: a.GetNamespace(),
91 APIGroup: a.GetAPIGroup(),
92 APIVersion: a.GetAPIVersion(),
93 Resource: a.GetResource(),
94 Subresource: a.GetSubresource(),
95 Name: a.GetName(),
96 ResourceRequest: a.IsResourceRequest(),
97 Path: a.GetPath(),
98 },
99 }
100 // in the error case, we won't honor this field selector, so the cache doesn't need it.
101 if fieldSelector, err := a.GetFieldSelector(); len(fieldSelector) > 0 {
102 serializableAttributes.FieldSelectorRequirements, serializableAttributes.FieldSelectorParsingErr = fieldSelector, err
103 }
104 if labelSelector, _ := a.GetLabelSelector(); len(labelSelector) > 0 {
105 // the labels requirements have private elements so those don't help us serialize to a unique key
106 serializableAttributes.LabelSelector = labelSelector.String()
107 }
108
109 if u := a.GetUser(); u != nil {
110 di := &user.DefaultInfo{
111 Name: u.GetName(),
112 UID: u.GetUID(),
113 }
114
115 // Differently-ordered groups or extras could cause otherwise-equivalent checks to
116 // have distinct cache keys.
117 if groups := u.GetGroups(); len(groups) > 0 {
118 di.Groups = make([]string, len(groups))
119 copy(di.Groups, groups)
120 sort.Strings(di.Groups)
121 }
122
123 if extra := u.GetExtra(); len(extra) > 0 {
124 di.Extra = make(map[string][]string, len(extra))
125 for k, vs := range extra {
126 vdupe := make([]string, len(vs))
127 copy(vdupe, vs)
128 sort.Strings(vdupe)
129 di.Extra[k] = vdupe
130 }
131 }
132
133 serializableAttributes.User = di
134 }
135
136 var b strings.Builder
137 if err := json.NewEncoder(&b).Encode(serializableAttributes); err != nil {
138 return authorizer.DecisionNoOpinion, "", err
139 }
140 key := b.String()
141
142 if cached, ok := ca.decisions[key]; ok {
143 return cached.authorized, cached.reason, cached.err
144 }
145
146 authorized, reason, err := ca.authorizer.Authorize(ctx, a)
147
148 ca.decisions[key] = authzResult{
149 authorized: authorized,
150 reason: reason,
151 err: err,
152 }
153
154 return authorized, reason, err
155 }