forked from openshift/origin
/
auth.go
297 lines (252 loc) · 10.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
package origin
import (
"errors"
"fmt"
"net/http"
"net/url"
"github.com/GoogleCloudPlatform/kubernetes/pkg/tools"
"github.com/golang/glog"
"github.com/openshift/origin/pkg/auth/api"
"github.com/openshift/origin/pkg/auth/authenticator"
"github.com/openshift/origin/pkg/auth/authenticator/basicauthpassword"
"github.com/openshift/origin/pkg/auth/authenticator/bearertoken"
authfile "github.com/openshift/origin/pkg/auth/authenticator/file"
"github.com/openshift/origin/pkg/auth/authenticator/requestheader"
"github.com/openshift/origin/pkg/auth/oauth/external"
"github.com/openshift/origin/pkg/auth/oauth/external/github"
"github.com/openshift/origin/pkg/auth/oauth/external/google"
"github.com/openshift/origin/pkg/auth/oauth/handlers"
"github.com/openshift/origin/pkg/auth/oauth/registry"
authnregistry "github.com/openshift/origin/pkg/auth/oauth/registry"
"github.com/openshift/origin/pkg/auth/server/login"
"github.com/openshift/origin/pkg/auth/server/session"
cmdutil "github.com/openshift/origin/pkg/cmd/util"
oauthetcd "github.com/openshift/origin/pkg/oauth/registry/etcd"
"github.com/openshift/origin/pkg/oauth/server/osinserver"
"github.com/openshift/origin/pkg/oauth/server/osinserver/registrystorage"
)
const (
OpenShiftOAuthAPIPrefix = "/oauth"
OpenShiftLoginPrefix = "/login"
OpenShiftOAuthCallbackPrefix = "/oauth2callback"
)
type AuthConfig struct {
MasterAddr string
SessionSecrets []string
EtcdHelper tools.EtcdHelper
}
// InstallAPI starts an OAuth2 server and registers the supported REST APIs
// into the provided mux, then returns an array of strings indicating what
// endpoints were started (these are format strings that will expect to be sent
// a single string value).
func (c *AuthConfig) InstallAPI(mux cmdutil.Mux) []string {
oauthEtcd := oauthetcd.New(c.EtcdHelper)
authRequestHandler := c.getAuthenticationRequestHandler()
// Check if the authentication handler wants to be told when we authenticated
success, ok := authRequestHandler.(handlers.AuthenticationSuccessHandler)
if !ok {
success = emptySuccess{}
}
authHandler := c.getAuthenticationHandler(mux, success, emptyError{})
storage := registrystorage.New(oauthEtcd, oauthEtcd, oauthEtcd, registry.NewUserConversion())
config := osinserver.NewDefaultServerConfig()
grantChecker := registry.NewClientAuthorizationGrantChecker(oauthEtcd)
grantHandler := emptyGrant{}
server := osinserver.New(
config,
storage,
osinserver.AuthorizeHandlers{
handlers.NewAuthorizeAuthenticator(
authHandler,
authRequestHandler,
),
handlers.NewGrantCheck(
grantChecker,
grantHandler,
),
},
osinserver.AccessHandlers{
handlers.NewDenyAccessAuthenticator(),
},
)
server.Install(mux, OpenShiftOAuthAPIPrefix)
// glog.Infof("oauth server configured as: %#v", server)
// glog.Infof("auth handler: %#v", authHandler)
// glog.Infof("auth request handler: %#v", authRequestHandler)
// glog.Infof("grant checker: %#v", grantChecker)
// glog.Infof("grant handler: %#v", grantHandler)
return []string{
fmt.Sprintf("Started OAuth2 API at %%s%s", OpenShiftOAuthAPIPrefix),
fmt.Sprintf("Started login server at %%s%s", OpenShiftLoginPrefix),
}
}
func (c *AuthConfig) getAuthenticationHandler(mux cmdutil.Mux, success handlers.AuthenticationSuccessHandler, error handlers.AuthenticationErrorHandler) handlers.AuthenticationHandler {
// TODO presumeably we'll want either a list of what we've got or a way to describe a registry of these
// hard-coded strings as a stand-in until it gets sorted out
var authHandler handlers.AuthenticationHandler
authHandlerType := env("ORIGIN_AUTH_HANDLER", "empty")
switch authHandlerType {
case "google", "github":
callbackPath := OpenShiftOAuthCallbackPrefix + "/" + authHandlerType
var oauthProvider external.Provider
if authHandlerType == "google" {
oauthProvider = google.NewProvider(env("ORIGIN_GOOGLE_CLIENT_ID", ""), env("ORIGIN_GOOGLE_CLIENT_SECRET", ""))
} else if authHandlerType == "github" {
oauthProvider = github.NewProvider(env("ORIGIN_GITHUB_CLIENT_ID", ""), env("ORIGIN_GITHUB_CLIENT_SECRET", ""))
}
state := external.DefaultState()
success := handlers.AuthenticationSuccessHandlers{success, state.(handlers.AuthenticationSuccessHandler)}
oauthHandler, err := external.NewHandler(oauthProvider, state, c.MasterAddr+callbackPath, success, error)
if err != nil {
glog.Fatalf("unexpected error: %v", err)
}
mux.Handle(callbackPath, oauthHandler)
authHandler = oauthHandler
case "login":
var passwordAuth authenticator.Password
passwordAuthType := env("ORIGIN_PASSWORD_AUTH_TYPE", "empty")
switch passwordAuthType {
case "basic":
basicAuthURL := env("ORIGIN_BASIC_AUTH_URL", "")
if len(basicAuthURL) == 0 {
glog.Fatalf("ORIGIN_BASIC_AUTH_URL is required to support basic password auth")
}
passwordAuth = basicauthpassword.New(basicAuthURL)
case "empty":
// Accepts any username and password
passwordAuth = emptyPasswordAuth{}
default:
glog.Fatalf("No password auth found that matches %v. The oauth server cannot start!", passwordAuthType)
}
authHandler = &redirectAuthHandler{RedirectURL: OpenShiftLoginPrefix, ThenParam: "then"}
success := handlers.AuthenticationSuccessHandlers{success, redirectSuccessHandler{}}
login := login.NewLogin(emptyCsrf{}, &callbackPasswordAuthenticator{passwordAuth, success}, login.DefaultLoginFormRenderer)
login.Install(mux, OpenShiftLoginPrefix)
case "empty":
authHandler = emptyAuth{}
default:
glog.Fatalf("No AuthenticationHandler found that matches %v. The oauth server cannot start!", authHandlerType)
}
return authHandler
}
func (c *AuthConfig) getAuthenticationRequestHandler() authenticator.Request {
// TODO presumeably we'll want either a list of what we've got or a way to describe a registry of these
// hard-coded strings as a stand-in until it gets sorted out
var authRequestHandler authenticator.Request
authRequestHandlerType := env("ORIGIN_AUTH_REQUEST_HANDLER", "session")
switch authRequestHandlerType {
case "bearer":
tokenAuthenticator, err := GetTokenAuthenticator(c.EtcdHelper)
if err != nil {
glog.Fatalf("Error creating TokenAuthenticator: %v. The oauth server cannot start!", err)
}
authRequestHandler = bearertoken.New(tokenAuthenticator)
case "requestheader":
authRequestHandler = requestheader.NewAuthenticator(requestheader.NewDefaultConfig())
case "session":
sessionStore := session.NewStore(c.SessionSecrets...)
authRequestHandler = session.NewSessionAuthenticator(sessionStore, "ssn")
default:
glog.Fatalf("No AuthenticationRequestHandler found that matches %v. The oauth server cannot start!", authRequestHandlerType)
}
return authRequestHandler
}
func GetTokenAuthenticator(etcdHelper tools.EtcdHelper) (authenticator.Token, error) {
tokenAuthenticatorType := env("ORIGIN_AUTH_TOKEN_AUTHENTICATOR", "etcd")
switch tokenAuthenticatorType {
case "etcd":
oauthRegistry := oauthetcd.New(etcdHelper)
return authnregistry.NewTokenAuthenticator(oauthRegistry), nil
case "file":
return authfile.NewTokenAuthenticator(env("ORIGIN_AUTH_FILE_TOKEN_AUTHENTICATOR_PATH", "authorizedTokens.csv"))
default:
return nil, errors.New(fmt.Sprintf("No TokenAuthenticator found that matches %v. The oauth server cannot start!", tokenAuthenticatorType))
}
}
type emptyAuth struct{}
func (emptyAuth) AuthenticationNeeded(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "<body>AuthenticationNeeded - not implemented</body>")
}
func (emptyAuth) AuthenticationError(err error, w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "<body>AuthenticationError - %s</body>", err)
}
func (emptyAuth) String() string {
return "emptyAuth"
}
// Captures the original request url as a "then" param in a redirect to a login flow
type redirectAuthHandler struct {
RedirectURL string
ThenParam string
}
func (auth *redirectAuthHandler) AuthenticationNeeded(w http.ResponseWriter, req *http.Request) {
redirectURL, err := url.Parse(auth.RedirectURL)
if err != nil {
auth.AuthenticationError(err, w, req)
return
}
if len(auth.ThenParam) != 0 {
redirectURL.RawQuery = url.Values{
auth.ThenParam: {req.URL.String()},
}.Encode()
}
http.Redirect(w, req, redirectURL.String(), http.StatusFound)
}
func (auth *redirectAuthHandler) AuthenticationError(err error, w http.ResponseWriter, req *http.Request) {
w.Header().Add("Content-Type", "text/html")
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "<body>AuthenticationError - %s</body>", err)
}
func (auth *redirectAuthHandler) String() string {
return fmt.Sprintf("redirectAuth{url:%s, then:%s}", auth.RedirectURL, auth.ThenParam)
}
type emptyGrant struct{}
func (emptyGrant) GrantNeeded(client api.Client, user api.UserInfo, grant *api.Grant, w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "<body>GrantNeeded - not implemented<pre>%#v\n%#v\n%#v</pre></body>", client, user, grant)
}
func (emptyGrant) GrantError(err error, w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "<body>GrantError - %s</body>", err)
}
type emptyCsrf struct{}
func (emptyCsrf) Generate() (string, error) {
return "", nil
}
func (emptyCsrf) Check(string) (bool, error) {
return true, nil
}
//
// Approves any login attempt with non-blank username and password
//
type emptyPasswordAuth struct{}
func (emptyPasswordAuth) AuthenticatePassword(user, password string) (api.UserInfo, bool, error) {
if user == "" || password == "" {
return nil, false, nil
}
return &api.DefaultUserInfo{
Name: user,
}, true, nil
}
//
// Combines password auth, successful login callback, and "then" param redirection
//
type callbackPasswordAuthenticator struct {
authenticator.Password
handlers.AuthenticationSuccessHandler
}
// Redirects to the then param on successful authentication
type redirectSuccessHandler struct{}
func (redirectSuccessHandler) AuthenticationSucceeded(user api.UserInfo, then string, w http.ResponseWriter, req *http.Request) error {
if len(then) == 0 {
return fmt.Errorf("Auth succeeded, but no redirect existed - user=%#v", user)
}
http.Redirect(w, req, then, http.StatusFound)
return nil
}
type emptySuccess struct{}
func (emptySuccess) AuthenticationSucceeded(user api.UserInfo, state string, w http.ResponseWriter, req *http.Request) error {
glog.V(4).Infof("AuthenticationSucceeded: %v (state=%s)", user, state)
return nil
}
type emptyError struct{}
func (emptyError) AuthenticationError(err error, w http.ResponseWriter, req *http.Request) {
glog.V(4).Infof("AuthenticationError: %v", err)
}