forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
205 lines (176 loc) · 5.45 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
package server
import (
"encoding/base64"
"errors"
"fmt"
"net/http"
"os"
"strings"
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 (
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")
ErrNamespaceRequired = errors.New("repository namespace required")
ErrOpenShiftAccessDenied = errors.New("openshift access denied")
)
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)
}
// Authorized handles checking whether the given request is authorized
// for actions on resources allowed by openshift.
func (ac *AccessController) Authorized(ctx context.Context, accessRecords ...registryauth.Access) (context.Context, error) {
var (
client *client.Client
err error
)
challenge := &authChallenge{realm: ac.realm}
if os.Getenv("DISABLE_USER_AUTH") == "true" {
client, err = NewRegistryOpenShiftClient()
if err != nil {
return nil, err
}
} else {
req, err := ctxu.GetRequest(ctx)
if err != nil {
return nil, err
}
authParts := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
if len(authParts) != 2 || strings.ToLower(authParts[0]) != "basic" {
challenge.err = ErrTokenRequired
return nil, challenge
}
basicToken := authParts[1]
payload, err := base64.StdEncoding.DecodeString(basicToken)
if err != nil {
log.Errorf("Basic token decode failed: %s", err)
challenge.err = ErrTokenInvalid
return nil, challenge
}
osAuthParts := strings.SplitN(string(payload), ":", 2)
if len(osAuthParts) != 2 {
challenge.err = ErrOpenShiftTokenRequired
return nil, challenge
}
user := osAuthParts[0]
bearerToken := osAuthParts[1]
client, err = NewUserOpenShiftClient(bearerToken)
if err != nil {
return nil, err
}
// In case of docker login, hits endpoint /v2
if len(accessRecords) == 0 {
err = VerifyOpenShiftUser(user, client)
if err != nil {
challenge.err = err
return nil, challenge
}
}
}
for _, access := range accessRecords {
log.Debugf("%s:%s:%s", access.Resource.Type, access.Resource.Name, access.Action)
if access.Resource.Type != "repository" {
continue
}
repoParts := strings.SplitN(access.Resource.Name, "/", 2)
if len(repoParts) != 2 {
challenge.err = ErrNamespaceRequired
return nil, challenge
}
verb := ""
switch access.Action {
case "push":
verb = "update"
case "pull":
verb = "get"
default:
challenge.err = fmt.Errorf("Unknown action: %s", access.Action)
return nil, challenge
}
err = VerifyOpenShiftAccess(repoParts[0], repoParts[1], verb, client)
if err != nil {
challenge.err = err
return nil, challenge
}
}
return WithUserClient(ctx, client), nil
}
func VerifyOpenShiftUser(user string, client *client.Client) error {
userObj, err := client.Users().Get("~")
if err != nil {
log.Errorf("Get user failed with error: %s", err)
return ErrOpenShiftAccessDenied
}
if user != userObj.Name {
log.Errorf("Token valid but user name mismatch")
return ErrOpenShiftAccessDenied
}
return nil
}
func VerifyOpenShiftAccess(namespace, imageRepo, verb string, client *client.Client) error {
sar := authorizationapi.SubjectAccessReview{
Verb: verb,
Resource: "imageStreams",
ResourceName: imageRepo,
}
response, err := client.SubjectAccessReviews(namespace).Create(&sar)
if err != nil {
log.Errorf("OpenShift client error: %s", err)
return ErrOpenShiftAccessDenied
}
if !response.Allowed {
log.Errorf("OpenShift access denied: %s", response.Reason)
return ErrOpenShiftAccessDenied
}
return nil
}