forked from kubevirt/containerized-data-importer
/
authorizer.go
240 lines (193 loc) · 6.12 KB
/
authorizer.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
/*
* This file is part of the CDI project
*
* 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.
*
* Copyright 2019 Red Hat, Inc.
*
*/
package apiserver
import (
"fmt"
"net/http"
"strings"
"k8s.io/klog"
"github.com/emicklei/go-restful"
authorization "k8s.io/api/authorization/v1beta1"
authorizationclient "k8s.io/client-go/kubernetes/typed/authorization/v1beta1"
restclient "k8s.io/client-go/rest"
)
const (
userHeader = "X-Remote-User"
groupHeader = "X-Remote-Group"
userExtraHeaderPrefix = "X-Remote-Extra-"
clientQPS = 200
clientBurst = 400
)
// CdiAPIAuthorizer defines methods to authorize api requests
type CdiAPIAuthorizer interface {
Authorize(req *restful.Request) (bool, string, error)
}
type authorizor struct {
authConfigWatcher AuthConfigWatcher
subjectAccessReview authorizationclient.SubjectAccessReviewInterface
}
func (a *authorizor) matchHeaders(headers http.Header, toMatch []string) ([]string, error) {
for _, header := range toMatch {
value, ok := headers[header]
if ok {
return value, nil
}
}
return nil, fmt.Errorf("one of these headers required for authorization: %+v", toMatch)
}
func (a *authorizor) getUserExtras(headers http.Header, toMatch []string) map[string]authorization.ExtraValue {
extras := map[string]authorization.ExtraValue{}
for _, prefix := range toMatch {
for k, v := range headers {
if strings.HasPrefix(k, prefix) {
extraKey := strings.TrimPrefix(k, prefix)
extras[extraKey] = v
}
}
}
return extras
}
func (a *authorizor) generateAccessReview(req *restful.Request) (*authorization.SubjectAccessReview, error) {
httpRequest := req.Request
if httpRequest == nil {
return nil, fmt.Errorf("empty http request")
}
headers := httpRequest.Header
url := httpRequest.URL
if url == nil {
return nil, fmt.Errorf("no URL in http request")
}
// URL example
// /apis/upload.cdi.kubevirt.io/v1alpha1/namespaces/default/uploadtokenrequest(s)
pathSplit := strings.Split(url.Path, "/")
if len(pathSplit) != 7 {
return nil, fmt.Errorf("unknown api endpoint %s", url.Path)
}
authConfig := a.authConfigWatcher.GetAuthConfig()
group := pathSplit[2]
version := pathSplit[3]
namespace := pathSplit[5]
resource := pathSplit[6]
userExtras := a.getUserExtras(headers, authConfig.ExtraPrefixHeaders)
if group != uploadTokenGroup {
return nil, fmt.Errorf("unknown api group %s", group)
}
if resource != "uploadtokenrequests" {
return nil, fmt.Errorf("unknown resource type %s", resource)
}
users, err := a.matchHeaders(headers, authConfig.UserHeaders)
if err != nil {
return nil, err
}
if len(users) == 0 {
return nil, fmt.Errorf("No user header found")
}
userGroups, err := a.matchHeaders(headers, authConfig.GroupHeaders)
if err != nil {
return nil, err
}
verb := strings.ToLower(httpRequest.Method)
r := &authorization.SubjectAccessReview{}
r.Spec = authorization.SubjectAccessReviewSpec{
User: users[0],
Groups: userGroups,
Extra: userExtras,
}
r.Spec.ResourceAttributes = &authorization.ResourceAttributes{
Namespace: namespace,
Verb: verb,
Group: group,
Version: version,
Resource: resource,
}
return r, nil
}
func isInfoEndpoint(req *restful.Request) bool {
httpRequest := req.Request
if httpRequest == nil || httpRequest.URL == nil {
return false
}
// URL example
// /apis/upload.cdi.kubevirt.io/v1alpha2/namespaces/default/uploadtokenrequests/test
// The /apis/<group>/<version> part of the urls should be accessible without needing authorization
pathSplit := strings.Split(httpRequest.URL.Path, "/")
if len(pathSplit) <= 4 || (len(pathSplit) > 4 && pathSplit[4] == "version") {
return true
}
return false
}
func isAuthenticated(req *restful.Request) bool {
klog.V(3).Infof("Authenticating request: %+v", req.Request)
klog.V(3).Infof("Authenticating request TLS: %+v", req.Request.TLS)
// Peer cert is required for authentication.
// If the peer's cert is provided, we are guaranteed
// it has been validated against our client CA pool
if req.Request == nil ||
req.Request.TLS == nil ||
len(req.Request.TLS.PeerCertificates) == 0 ||
len(req.Request.TLS.VerifiedChains) == 0 {
return false
}
return true
}
func isAllowed(result *authorization.SubjectAccessReview) (bool, string) {
if result.Status.Allowed {
return true, ""
}
return false, result.Status.Reason
}
func (a *authorizor) Authorize(req *restful.Request) (bool, string, error) {
// Endpoints related to getting information about
// what apis our server provides are authorized to
// all users.
if isInfoEndpoint(req) {
return true, "", nil
}
if !isAuthenticated(req) {
return false, "request is not authenticated", nil
}
r, err := a.generateAccessReview(req)
if err != nil {
// only internal service errors are returned
// as an error.
// A failure to generate the access review request
// means the client did not properly format the request.
// Return that error as the "Reason" for the authorization failure.
return false, fmt.Sprintf("%v", err), nil
}
result, err := a.subjectAccessReview.Create(r)
if err != nil {
return false, "internal server error", err
}
allowed, reason := isAllowed(result)
return allowed, reason, nil
}
// NewAuthorizorFromConfig creates a new CdiAPIAuthorizor
func NewAuthorizorFromConfig(config *restclient.Config, authConfigWatcher AuthConfigWatcher) (CdiAPIAuthorizer, error) {
client, err := authorizationclient.NewForConfig(config)
if err != nil {
return nil, err
}
subjectAccessReview := client.SubjectAccessReviews()
a := &authorizor{
authConfigWatcher: authConfigWatcher,
subjectAccessReview: subjectAccessReview,
}
return a, nil
}