-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathauth.go
446 lines (389 loc) · 13.4 KB
/
auth.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
package server
import (
"errors"
"fmt"
"net/http"
"net/url"
"strings"
context "github.com/docker/distribution/context"
registryauth "github.com/docker/distribution/registry/auth"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
authorizationapi "k8s.io/kubernetes/pkg/apis/authorization/v1"
imageapi "github.com/openshift/origin/pkg/image/apis/image"
"github.com/openshift/origin/pkg/util/httprequest"
"github.com/openshift/image-registry/pkg/dockerregistry/server/audit"
"github.com/openshift/image-registry/pkg/dockerregistry/server/client"
"github.com/openshift/image-registry/pkg/dockerregistry/server/configuration"
)
type deferredErrors map[string]error
func (d deferredErrors) Add(namespace string, name string, err error) {
d[namespace+"/"+name] = err
}
func (d deferredErrors) Get(namespace string, name string) (error, bool) {
err, exists := d[namespace+"/"+name]
return err, exists
}
func (d deferredErrors) Empty() bool {
return len(d) == 0
}
const (
defaultUserName = "anonymous"
)
// WithUserInfoLogger creates a new context with provided user infomation.
func WithUserInfoLogger(ctx context.Context, username, userid string) context.Context {
ctx = context.WithValue(ctx, audit.AuditUserEntry, username)
if len(userid) > 0 {
ctx = context.WithValue(ctx, audit.AuditUserIDEntry, userid)
}
return context.WithLogger(ctx, context.GetLogger(ctx,
audit.AuditUserEntry,
audit.AuditUserIDEntry,
))
}
type AccessController struct {
realm string
tokenRealm *url.URL
registryClient client.RegistryClient
auditLog bool
metricsConfig configuration.Metrics
}
var _ registryauth.AccessController = &AccessController{}
type authChallenge struct {
realm string
err error
}
var _ registryauth.Challenge = &authChallenge{}
type tokenAuthChallenge struct {
realm string
service string
err error
}
var _ registryauth.Challenge = &tokenAuthChallenge{}
// Errors used and exported by this package.
var (
// Challenging errors
ErrTokenRequired = errors.New("authorization header required")
ErrTokenInvalid = errors.New("failed to decode credentials")
ErrOpenShiftAccessDenied = errors.New("access denied")
// Non-challenging errors
ErrNamespaceRequired = errors.New("repository namespace required")
ErrUnsupportedAction = errors.New("unsupported action")
ErrUnsupportedResource = errors.New("unsupported resource")
)
func (app *App) Auth(options map[string]interface{}) (registryauth.AccessController, error) {
tokenRealm, err := configuration.TokenRealm(app.config.Auth.TokenRealm)
if err != nil {
return nil, err
}
return &AccessController{
realm: app.config.Auth.Realm,
tokenRealm: tokenRealm,
registryClient: app.registryClient,
metricsConfig: app.config.Metrics,
auditLog: app.config.Audit.Enabled,
}, nil
}
// Error returns the internal error string for this authChallenge.
func (ac *authChallenge) Error() string {
return ac.err.Error()
}
// SetHeaders sets the basic challenge header on the response.
func (ac *authChallenge) SetHeaders(w http.ResponseWriter) {
// WWW-Authenticate response challenge header.
// See https://tools.ietf.org/html/rfc6750#section-3
str := fmt.Sprintf("Basic realm=%s", ac.realm)
if ac.err != nil {
str = fmt.Sprintf("%s,error=%q", str, ac.Error())
}
w.Header().Set("WWW-Authenticate", str)
}
// Error returns the internal error string for this authChallenge.
func (ac *tokenAuthChallenge) Error() string {
return ac.err.Error()
}
// SetHeaders sets the bearer challenge header on the response.
func (ac *tokenAuthChallenge) SetHeaders(w http.ResponseWriter) {
// WWW-Authenticate response challenge header.
// See https://docs.docker.com/registry/spec/auth/token/#/how-to-authenticate and https://tools.ietf.org/html/rfc6750#section-3
str := fmt.Sprintf("Bearer realm=%q", ac.realm)
if ac.service != "" {
str += fmt.Sprintf(",service=%q", ac.service)
}
w.Header().Set("WWW-Authenticate", str)
}
// wrapErr wraps errors related to authorization in an authChallenge error that will present a WWW-Authenticate challenge response
func (ac *AccessController) wrapErr(ctx context.Context, err error) error {
switch err {
case ErrTokenRequired:
// Challenge for errors that involve missing tokens
if ac.tokenRealm == nil {
// Send the basic challenge if we don't have a place to redirect
return &authChallenge{realm: ac.realm, err: err}
}
if len(ac.tokenRealm.Scheme) > 0 && len(ac.tokenRealm.Host) > 0 {
// Redirect to token auth if we've been given an absolute URL
return &tokenAuthChallenge{realm: ac.tokenRealm.String(), err: err}
}
// Auto-detect scheme/host from request
req, reqErr := context.GetRequest(ctx)
if reqErr != nil {
return reqErr
}
scheme, host := httprequest.SchemeHost(req)
tokenRealmCopy := *ac.tokenRealm
if len(tokenRealmCopy.Scheme) == 0 {
tokenRealmCopy.Scheme = scheme
}
if len(tokenRealmCopy.Host) == 0 {
tokenRealmCopy.Host = host
}
return &tokenAuthChallenge{realm: tokenRealmCopy.String(), err: err}
case ErrTokenInvalid, ErrOpenShiftAccessDenied:
// Challenge for errors that involve tokens or access denied
return &authChallenge{realm: ac.realm, err: err}
case ErrNamespaceRequired, ErrUnsupportedAction, ErrUnsupportedResource:
// Malformed or unsupported request, no challenge
return err
default:
// By default, just return the error, this gets surfaced as a bad request / internal error, but no challenge
return err
}
}
// Authorized handles checking whether the given request is authorized
// for actions on resources allowed by openshift.
// Sources of access records:
// origin/pkg/cmd/dockerregistry/dockerregistry.go#Execute
// docker/distribution/registry/handlers/app.go#appendAccessRecords
func (ac *AccessController) Authorized(ctx context.Context, accessRecords ...registryauth.Access) (context.Context, error) {
req, err := context.GetRequest(ctx)
if err != nil {
return nil, ac.wrapErr(ctx, err)
}
bearerToken, err := getOpenShiftAPIToken(req)
if err != nil {
return nil, ac.wrapErr(ctx, err)
}
osClient, err := ac.registryClient.ClientFromToken(bearerToken)
if err != nil {
return nil, ac.wrapErr(ctx, err)
}
// In case of docker login, hits endpoint /v2
if len(bearerToken) > 0 && !isMetricsBearerToken(ac.metricsConfig, bearerToken) {
user, userid, err := verifyOpenShiftUser(ctx, osClient)
if err != nil {
return nil, ac.wrapErr(ctx, err)
}
ctx = WithUserInfoLogger(ctx, user, userid)
} else {
ctx = WithUserInfoLogger(ctx, defaultUserName, "")
}
if ac.auditLog {
// TODO: setup own log formatter.
ctx = audit.WithLogger(ctx, audit.GetLogger(ctx))
}
// pushChecks remembers which ns/name pairs had push access checks done
pushChecks := map[string]bool{}
// possibleCrossMountErrors holds errors which may be related to cross mount errors
possibleCrossMountErrors := deferredErrors{}
verifiedPrune := false
// Validate all requested accessRecords
// Only return failure errors from this loop. Success should continue to validate all records
for _, access := range accessRecords {
context.GetLogger(ctx).Debugf("Origin auth: checking for access to %s:%s:%s", access.Resource.Type, access.Resource.Name, access.Action)
switch access.Resource.Type {
case "repository":
imageStreamNS, imageStreamName, err := getNamespaceName(access.Resource.Name)
if err != nil {
return nil, ac.wrapErr(ctx, err)
}
verb := ""
switch access.Action {
case "push":
verb = "update"
pushChecks[imageStreamNS+"/"+imageStreamName] = true
case "pull":
verb = "get"
case "*":
verb = "prune"
default:
return nil, ac.wrapErr(ctx, ErrUnsupportedAction)
}
switch verb {
case "prune":
if verifiedPrune {
continue
}
if err := verifyPruneAccess(ctx, osClient); err != nil {
return nil, ac.wrapErr(ctx, err)
}
verifiedPrune = true
default:
if err := verifyImageStreamAccess(ctx, imageStreamNS, imageStreamName, verb, osClient); err != nil {
if access.Action != "pull" {
return nil, ac.wrapErr(ctx, err)
}
possibleCrossMountErrors.Add(imageStreamNS, imageStreamName, ac.wrapErr(ctx, err))
}
}
case "signature":
namespace, name, err := getNamespaceName(access.Resource.Name)
if err != nil {
return nil, ac.wrapErr(ctx, err)
}
switch access.Action {
case "get":
if err := verifyImageStreamAccess(ctx, namespace, name, access.Action, osClient); err != nil {
return nil, ac.wrapErr(ctx, err)
}
case "put":
if err := verifyImageSignatureAccess(ctx, namespace, name, osClient); err != nil {
return nil, ac.wrapErr(ctx, err)
}
default:
return nil, ac.wrapErr(ctx, ErrUnsupportedAction)
}
case "metrics":
switch access.Action {
case "get":
if !isMetricsBearerToken(ac.metricsConfig, bearerToken) {
return nil, ac.wrapErr(ctx, ErrOpenShiftAccessDenied)
}
default:
return nil, ac.wrapErr(ctx, ErrUnsupportedAction)
}
case "admin":
switch access.Action {
case "prune":
if verifiedPrune {
continue
}
if err := verifyPruneAccess(ctx, osClient); err != nil {
return nil, ac.wrapErr(ctx, err)
}
verifiedPrune = true
default:
return nil, ac.wrapErr(ctx, ErrUnsupportedAction)
}
default:
return nil, ac.wrapErr(ctx, ErrUnsupportedResource)
}
}
// deal with any possible cross-mount errors
for namespaceAndName, err := range possibleCrossMountErrors {
// If we have no push requests, this can't be a cross-mount request, so error
if len(pushChecks) == 0 {
return nil, err
}
// If we also requested a push to this ns/name, this isn't a cross-mount request, so error
if pushChecks[namespaceAndName] {
return nil, err
}
}
// Conditionally add auth errors we want to handle later to the context
if !possibleCrossMountErrors.Empty() {
context.GetLogger(ctx).Debugf("Origin auth: deferring errors: %#v", possibleCrossMountErrors)
ctx = withDeferredErrors(ctx, possibleCrossMountErrors)
}
// Always add a marker to the context so we know auth was run
ctx = withAuthPerformed(ctx)
return withUserClient(ctx, osClient), nil
}
func getOpenShiftAPIToken(req *http.Request) (string, error) {
token := ""
authParts := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
if len(authParts) != 2 {
return "", ErrTokenRequired
}
switch strings.ToLower(authParts[0]) {
case "bearer":
// This is either a direct API token, or a token issued by our docker token handler
token = authParts[1]
// Recognize the token issued to anonymous users by our docker token handler
if token == anonymousToken {
token = ""
}
case "basic":
_, password, ok := req.BasicAuth()
if !ok || len(password) == 0 {
return "", ErrTokenInvalid
}
token = password
default:
return "", ErrTokenRequired
}
return token, nil
}
func verifyOpenShiftUser(ctx context.Context, c client.UsersInterfacer) (string, string, error) {
userInfo, err := c.Users().Get("~", metav1.GetOptions{})
if err != nil {
context.GetLogger(ctx).Errorf("Get user failed with error: %s", err)
if kerrors.IsUnauthorized(err) || kerrors.IsForbidden(err) {
return "", "", ErrOpenShiftAccessDenied
}
return "", "", err
}
return userInfo.GetName(), string(userInfo.GetUID()), nil
}
func verifyWithSAR(ctx context.Context, resource, namespace, name, verb string, c client.SelfSubjectAccessReviewsNamespacer) error {
sar := authorizationapi.SelfSubjectAccessReview{
Spec: authorizationapi.SelfSubjectAccessReviewSpec{
ResourceAttributes: &authorizationapi.ResourceAttributes{
Namespace: namespace,
Verb: verb,
Group: imageapi.GroupName,
Resource: resource,
Name: name,
},
},
}
response, err := c.SelfSubjectAccessReviews().Create(&sar)
if err != nil {
context.GetLogger(ctx).Errorf("OpenShift client error: %s", err)
if kerrors.IsUnauthorized(err) || kerrors.IsForbidden(err) {
return ErrOpenShiftAccessDenied
}
return err
}
if !response.Status.Allowed {
context.GetLogger(ctx).Errorf("OpenShift access denied: %s", response.Status.Reason)
return ErrOpenShiftAccessDenied
}
return nil
}
func verifyImageStreamAccess(ctx context.Context, namespace, imageRepo, verb string, c client.SelfSubjectAccessReviewsNamespacer) error {
return verifyWithSAR(ctx, "imagestreams/layers", namespace, imageRepo, verb, c)
}
func verifyImageSignatureAccess(ctx context.Context, namespace, imageRepo string, c client.SelfSubjectAccessReviewsNamespacer) error {
return verifyWithSAR(ctx, "imagesignatures", namespace, imageRepo, "create", c)
}
func verifyPruneAccess(ctx context.Context, c client.SelfSubjectAccessReviewsNamespacer) error {
sar := authorizationapi.SelfSubjectAccessReview{
Spec: authorizationapi.SelfSubjectAccessReviewSpec{
ResourceAttributes: &authorizationapi.ResourceAttributes{
Verb: "delete",
Group: imageapi.GroupName,
Resource: "images",
},
},
}
response, err := c.SelfSubjectAccessReviews().Create(&sar)
if err != nil {
context.GetLogger(ctx).Errorf("OpenShift client error: %s", err)
if kerrors.IsUnauthorized(err) || kerrors.IsForbidden(err) {
return ErrOpenShiftAccessDenied
}
return err
}
if !response.Status.Allowed {
context.GetLogger(ctx).Errorf("OpenShift access denied: %s", response.Status.Reason)
return ErrOpenShiftAccessDenied
}
return nil
}
func isMetricsBearerToken(metrics configuration.Metrics, token string) bool {
if metrics.Enabled {
return metrics.Secret == token
}
return false
}