forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
291 lines (252 loc) · 8.11 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
package server
import (
"encoding/base64"
"errors"
"fmt"
"net/http"
"strings"
kerrors "github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
log "github.com/Sirupsen/logrus"
ctxu "github.com/docker/distribution/context"
registryauth "github.com/docker/distribution/registry/auth"
authorizationapi "github.com/openshift/origin/pkg/authorization/api"
"github.com/openshift/origin/pkg/client"
"golang.org/x/net/context"
)
func init() {
registryauth.Register("openshift", registryauth.InitFunc(newAccessController))
}
type contextKey int
var userClientKey contextKey = 0
func WithUserClient(parent context.Context, userClient *client.Client) context.Context {
return context.WithValue(parent, userClientKey, userClient)
}
func UserClientFrom(ctx context.Context) (*client.Client, bool) {
userClient, ok := ctx.Value(userClientKey).(*client.Client)
return userClient, ok
}
type AccessController struct {
realm string
}
var _ registryauth.AccessController = &AccessController{}
type authChallenge struct {
realm string
err error
}
var _ registryauth.Challenge = &authChallenge{}
// Errors used and exported by this package.
var (
// Challenging errors
ErrTokenRequired = errors.New("authorization header with basic token required")
ErrTokenInvalid = errors.New("failed to decode basic token")
ErrOpenShiftTokenRequired = errors.New("expected openshift bearer token as password for basic token to registry")
ErrOpenShiftAccessDenied = errors.New("openshift access denied")
// Non-challenging errors
ErrNamespaceRequired = errors.New("repository namespace required")
ErrUnsupportedAction = errors.New("unsupported action")
ErrUnsupportedResource = errors.New("unsupported resource")
)
func newAccessController(options map[string]interface{}) (registryauth.AccessController, error) {
log.Info("Using OpenShift Auth handler")
realm, ok := options["realm"].(string)
if !ok {
// Default to openshift if not present
realm = "openshift"
}
return &AccessController{realm: realm}, nil
}
// Error returns the internal error string for this authChallenge.
func (ac *authChallenge) Error() string {
return ac.err.Error()
}
// ServeHTTP handles writing the challenge response
// by setting the challenge header and status code.
func (ac *authChallenge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// 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().Add("WWW-Authenticate", str)
w.WriteHeader(http.StatusUnauthorized)
}
// wrapErr wraps errors related to authorization in an authChallenge error that will present a WWW-Authenticate challenge response
func (ac *AccessController) wrapErr(err error) error {
switch err {
case ErrTokenRequired, ErrTokenInvalid, ErrOpenShiftTokenRequired, 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 := ctxu.GetRequest(ctx)
if err != nil {
return nil, ac.wrapErr(err)
}
// TODO: change this to an anonymous Access record, don't require a token for it, and fold into the access record check look below
if req.URL.Path == "/healthz" {
return ctx, nil
}
bearerToken, err := getToken(req)
if err != nil {
return nil, ac.wrapErr(err)
}
client, err := NewUserOpenShiftClient(bearerToken)
if err != nil {
return nil, ac.wrapErr(err)
}
// In case of docker login, hits endpoint /v2
if len(accessRecords) == 0 {
if err := verifyOpenShiftUser(client); err != nil {
return nil, ac.wrapErr(err)
}
}
verifiedPrune := false
// Validate all requested accessRecords
// Only return failure errors from this loop. Success should continue to validate all records
for _, access := range accessRecords {
log.Debugf("OpenShift 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(err)
}
verb := ""
switch access.Action {
case "push":
verb = "update"
case "pull":
verb = "get"
case "*":
verb = "prune"
default:
return nil, ac.wrapErr(ErrUnsupportedAction)
}
switch verb {
case "prune":
if verifiedPrune {
continue
}
if err := verifyPruneAccess(client); err != nil {
return nil, ac.wrapErr(err)
}
verifiedPrune = true
default:
if err := verifyImageStreamAccess(imageStreamNS, imageStreamName, verb, client); err != nil {
return nil, ac.wrapErr(err)
}
}
case "admin":
switch access.Action {
case "prune":
if verifiedPrune {
continue
}
if err := verifyPruneAccess(client); err != nil {
return nil, ac.wrapErr(err)
}
verifiedPrune = true
default:
return nil, ac.wrapErr(ErrUnsupportedAction)
}
default:
return nil, ac.wrapErr(ErrUnsupportedResource)
}
}
return WithUserClient(ctx, client), nil
}
func getNamespaceName(resourceName string) (string, string, error) {
repoParts := strings.SplitN(resourceName, "/", 2)
if len(repoParts) != 2 {
return "", "", ErrNamespaceRequired
}
ns := repoParts[0]
if len(ns) == 0 {
return "", "", ErrNamespaceRequired
}
name := repoParts[1]
if len(name) == 0 {
return "", "", ErrNamespaceRequired
}
return ns, name, nil
}
func getToken(req *http.Request) (string, error) {
authParts := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
if len(authParts) != 2 || strings.ToLower(authParts[0]) != "basic" {
return "", ErrTokenRequired
}
basicToken := authParts[1]
payload, err := base64.StdEncoding.DecodeString(basicToken)
if err != nil {
log.Errorf("Basic token decode failed: %s", err)
return "", ErrTokenInvalid
}
osAuthParts := strings.SplitN(string(payload), ":", 2)
if len(osAuthParts) != 2 {
return "", ErrOpenShiftTokenRequired
}
bearerToken := osAuthParts[1]
return bearerToken, nil
}
func verifyOpenShiftUser(client *client.Client) error {
if _, err := client.Users().Get("~"); err != nil {
log.Errorf("Get user failed with error: %s", err)
if kerrors.IsUnauthorized(err) || kerrors.IsForbidden(err) {
return ErrOpenShiftAccessDenied
}
return err
}
return nil
}
func verifyImageStreamAccess(namespace, imageRepo, verb string, client *client.Client) error {
sar := authorizationapi.SubjectAccessReview{
Verb: verb,
Resource: "imagestreams/layers",
ResourceName: imageRepo,
}
response, err := client.SubjectAccessReviews(namespace).Create(&sar)
if err != nil {
log.Errorf("OpenShift client error: %s", err)
if kerrors.IsUnauthorized(err) || kerrors.IsForbidden(err) {
return ErrOpenShiftAccessDenied
}
return err
}
if !response.Allowed {
log.Errorf("OpenShift access denied: %s", response.Reason)
return ErrOpenShiftAccessDenied
}
return nil
}
func verifyPruneAccess(client *client.Client) error {
sar := authorizationapi.SubjectAccessReview{
Verb: "delete",
Resource: "images",
}
response, err := client.ClusterSubjectAccessReviews().Create(&sar)
if err != nil {
log.Errorf("OpenShift client error: %s", err)
if kerrors.IsUnauthorized(err) || kerrors.IsForbidden(err) {
return ErrOpenShiftAccessDenied
}
return err
}
if !response.Allowed {
log.Errorf("OpenShift access denied: %s", response.Reason)
return ErrOpenShiftAccessDenied
}
return nil
}