forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
631 lines (553 loc) · 25.8 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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
package origin
import (
"crypto/tls"
"crypto/x509"
"fmt"
"net/http"
"net/url"
"path"
"strings"
"code.google.com/p/go-uuid/uuid"
kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
kuser "github.com/GoogleCloudPlatform/kubernetes/pkg/auth/user"
"github.com/GoogleCloudPlatform/kubernetes/pkg/tools"
"github.com/RangelReale/osin"
"github.com/RangelReale/osincli"
"github.com/emicklei/go-restful"
"github.com/golang/glog"
"github.com/openshift/origin/pkg/auth/authenticator"
"github.com/openshift/origin/pkg/auth/authenticator/challenger/passwordchallenger"
"github.com/openshift/origin/pkg/auth/authenticator/password/allowanypassword"
"github.com/openshift/origin/pkg/auth/authenticator/password/basicauthpassword"
"github.com/openshift/origin/pkg/auth/authenticator/request/basicauthrequest"
"github.com/openshift/origin/pkg/auth/authenticator/request/bearertoken"
"github.com/openshift/origin/pkg/auth/authenticator/request/headerrequest"
"github.com/openshift/origin/pkg/auth/authenticator/request/unionrequest"
"github.com/openshift/origin/pkg/auth/authenticator/token/filetoken"
"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/csrf"
"github.com/openshift/origin/pkg/auth/server/grant"
"github.com/openshift/origin/pkg/auth/server/login"
"github.com/openshift/origin/pkg/auth/server/session"
"github.com/openshift/origin/pkg/auth/server/tokenrequest"
"github.com/openshift/origin/pkg/auth/userregistry/identitymapper"
cmdutil "github.com/openshift/origin/pkg/cmd/util"
oauthapi "github.com/openshift/origin/pkg/oauth/api"
clientregistry "github.com/openshift/origin/pkg/oauth/registry/client"
oauthclient "github.com/openshift/origin/pkg/oauth/registry/client"
"github.com/openshift/origin/pkg/oauth/registry/clientauthorization"
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"
"github.com/openshift/origin/pkg/user"
useretcd "github.com/openshift/origin/pkg/user/registry/etcd"
)
const (
OpenShiftOAuthAPIPrefix = "/oauth"
OpenShiftLoginPrefix = "/login"
OpenShiftApprovePrefix = "/oauth/approve"
OpenShiftOAuthCallbackPrefix = "/oauth2callback"
OpenShiftWebConsoleClientID = "openshift-web-console"
)
var (
OSWebConsoleClientBase = oauthapi.OAuthClient{
ObjectMeta: kapi.ObjectMeta{
Name: OpenShiftWebConsoleClientID,
},
Secret: uuid.NewUUID().String(), // random secret so no one knows what it is ahead of time.
}
// OSBrowserClientBase is used as a skeleton for building a Client. We can't set the allowed redirecturis because we don't yet know the host:port of the auth server
OSBrowserClientBase = oauthapi.OAuthClient{
ObjectMeta: kapi.ObjectMeta{
Name: "openshift-browser-client",
},
Secret: uuid.NewUUID().String(), // random secret so no one knows what it is ahead of time. This still allows us to loop back for /requestToken
}
OSCliClientBase = oauthapi.OAuthClient{
ObjectMeta: kapi.ObjectMeta{
Name: "openshift-challenging-client",
},
Secret: uuid.NewUUID().String(), // random secret so no one knows what it is ahead of time. This still allows us to loop back for /requestToken
RespondWithChallenges: true,
}
)
type AuthRequestHandlerType string
const (
// AuthRequestHandlerBearer validates a passed "Authorization: Bearer" token, using the specified TokenStore
AuthRequestHandlerBearer AuthRequestHandlerType = "bearer"
// AuthRequestHandlerRequestHeader treats any request with a value in one of the RequestHeaders headers as authenticated
AuthRequestHandlerRequestHeader AuthRequestHandlerType = "requestheader"
// AuthRequestHandlerBasicAuth validates a passed "Authorization: Basic" header using the specified PasswordAuth
AuthRequestHandlerBasicAuth AuthRequestHandlerType = "basicauth"
// AuthRequestHandlerSession authenticates requests containing user information in the request session
AuthRequestHandlerSession AuthRequestHandlerType = "session"
)
type AuthHandlerType string
const (
// AuthHandlerLogin redirects unauthenticated requests to a login page, or sends a www-authenticate challenge. Logins are validated using the specified PasswordAuth
AuthHandlerLogin AuthHandlerType = "login"
// AuthHandlerGithub redirects unauthenticated requests to GitHub to request an OAuth token.
AuthHandlerGithub AuthHandlerType = "github"
// AuthHandlerGoogle redirects unauthenticated requests to Google to request an OAuth token.
AuthHandlerGoogle AuthHandlerType = "google"
// AuthHandlerDeny treats unauthenticated requests as failures
AuthHandlerDeny AuthHandlerType = "deny"
)
type GrantHandlerType string
const (
// GrantHandlerAuto auto-approves client authorization grant requests
GrantHandlerAuto GrantHandlerType = "auto"
// GrantHandlerPrompt prompts the user to approve new client authorization grant requests
GrantHandlerPrompt GrantHandlerType = "prompt"
// GrantHandlerDeny auto-denies client authorization grant requests
GrantHandlerDeny GrantHandlerType = "deny"
)
type PasswordAuthType string
const (
// PasswordAuthAnyPassword treats any non-empty username and password combination as a successful authentication
PasswordAuthAnyPassword PasswordAuthType = "anypassword"
// PasswordAuthBasicAuthURL validates password credentials by making a request to a remote url using basic auth. See basicauthpassword.Authenticator
PasswordAuthBasicAuthURL PasswordAuthType = "basicauthurl"
)
type TokenStoreType string
const (
// Validate bearer tokens by looking in the OAuth access token registry
TokenStoreOAuth TokenStoreType = "oauth"
// Validate bearer tokens by looking in a CSV file located at the specified TokenFilePath
TokenStoreFile TokenStoreType = "file"
)
func ParseAuthRequestHandlerTypes(types string) []AuthRequestHandlerType {
handlerTypes := []AuthRequestHandlerType{}
for _, handlerType := range strings.Split(types, ",") {
trimmedType := AuthRequestHandlerType(strings.TrimSpace(handlerType))
switch trimmedType {
case AuthRequestHandlerBearer, AuthRequestHandlerRequestHeader, AuthRequestHandlerBasicAuth, AuthRequestHandlerSession:
handlerTypes = append(handlerTypes, trimmedType)
default:
glog.Fatalf("Unrecognized request handler type: %s", trimmedType)
}
}
return handlerTypes
}
type AuthConfig struct {
// URL to call internally during token request
MasterAddr string
// URL to direct browsers to the master on
MasterPublicAddr string
// Valid redirectURI prefixes to direct browsers to the web console
AssetPublicAddresses []string
MasterRoots *x509.CertPool
EtcdHelper tools.EtcdHelper
// Max age of authorize tokens
AuthorizeTokenMaxAgeSeconds int32
// Max age of access tokens
AccessTokenMaxAgeSeconds int32
// AuthRequestHandlers contains an ordered list of authenticators that decide if a request is authenticated
AuthRequestHandlers []AuthRequestHandlerType
// AuthHandler specifies what handles unauthenticated requests
AuthHandler AuthHandlerType
// GrantHandler specifies what handles requests for new client authorizations
GrantHandler GrantHandlerType
// PasswordAuth specifies how to validate username/passwords. Used by AuthRequestHandlerBasicAuth and AuthHandlerLogin
PasswordAuth PasswordAuthType
// BasicAuthURL specifies the remote URL to validate username/passwords against using basic auth. Used by PasswordAuthBasicAuthURL.
BasicAuthURL string
// TokenStore specifies how to validate bearer tokens. Used by AuthRequestHandlerBearer.
TokenStore TokenStoreType
// TokenFilePath is a path to a CSV file to load valid tokens from. Used by TokenStoreFile.
TokenFilePath string
// RequestHeaders lists the headers to check (in order) for a username. Used by AuthRequestHandlerRequestHeader
RequestHeaders []string
// SessionSecrets list the secret(s) to use to encrypt created sessions. Used by AuthRequestHandlerSession
SessionSecrets []string
// SessionMaxAgeSeconds specifies how long created sessions last. Used by AuthRequestHandlerSession
SessionMaxAgeSeconds int32
// SessionName is the cookie name used to store the session
SessionName string
// sessionAuth holds the Authenticator built from the exported Session* options. It should only be accessed via getSessionAuth(), since it is lazily built.
sessionAuth *session.Authenticator
// GoogleClientID is the client_id of a client registered with the Google OAuth provider.
// It must be authorized to redirect to {MasterPublicAddr}/oauth2callback/google
// Used by AuthHandlerGoogle
GoogleClientID string
// GoogleClientID is the client_secret of a client registered with the Google OAuth provider.
GoogleClientSecret string
// GithubClientID is the client_id of a client registered with the GitHub OAuth provider.
// It must be authorized to redirect to {MasterPublicAddr}/oauth2callback/github
// Used by AuthHandlerGithub
GithubClientID string
// GithubClientID is the client_secret of a client registered with the GitHub OAuth provider.
GithubClientSecret string
}
// InstallSupport registers endpoints for an OAuth2 server 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(container *restful.Container) []string {
// TODO: register into container
mux := container.ServeMux
oauthEtcd := oauthetcd.New(c.EtcdHelper)
authRequestHandler, authHandler, authFinalizer := c.getAuthorizeAuthenticationHandlers(mux)
storage := registrystorage.New(oauthEtcd, oauthEtcd, oauthEtcd, registry.NewUserConversion())
config := osinserver.NewDefaultServerConfig()
if c.AuthorizeTokenMaxAgeSeconds > 0 {
config.AuthorizationExpiration = c.AuthorizeTokenMaxAgeSeconds
}
if c.AccessTokenMaxAgeSeconds > 0 {
config.AccessExpiration = c.AccessTokenMaxAgeSeconds
}
grantChecker := registry.NewClientAuthorizationGrantChecker(oauthEtcd)
grantHandler := c.getGrantHandler(mux, authRequestHandler, oauthEtcd, oauthEtcd)
server := osinserver.New(
config,
storage,
osinserver.AuthorizeHandlers{
handlers.NewAuthorizeAuthenticator(
authRequestHandler,
authHandler,
handlers.EmptyError{},
),
handlers.NewGrantCheck(
grantChecker,
grantHandler,
handlers.EmptyError{},
),
authFinalizer,
},
osinserver.AccessHandlers{
handlers.NewDenyAccessAuthenticator(),
},
osinserver.NewDefaultErrorHandler(),
)
server.Install(mux, OpenShiftOAuthAPIPrefix)
CreateOrUpdateDefaultOAuthClients(c.MasterPublicAddr, c.AssetPublicAddresses, oauthEtcd)
osOAuthClientConfig := c.NewOpenShiftOAuthClientConfig(&OSBrowserClientBase)
osOAuthClientConfig.RedirectUrl = c.MasterPublicAddr + path.Join(OpenShiftOAuthAPIPrefix, tokenrequest.DisplayTokenEndpoint)
osOAuthClient, _ := osincli.NewClient(osOAuthClientConfig)
if c.MasterRoots != nil {
// Copy the default transport
var transport http.Transport = *http.DefaultTransport.(*http.Transport)
// Set TLS CA roots
transport.TLSClientConfig = &tls.Config{RootCAs: c.MasterRoots}
osOAuthClient.Transport = &transport
}
tokenRequestEndpoints := tokenrequest.NewEndpoints(osOAuthClient)
tokenRequestEndpoints.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),
}
}
// NewOpenShiftOAuthClientConfig provides config for OpenShift OAuth client
func (c *AuthConfig) NewOpenShiftOAuthClientConfig(client *oauthapi.OAuthClient) *osincli.ClientConfig {
config := &osincli.ClientConfig{
ClientId: client.Name,
ClientSecret: client.Secret,
ErrorsInStatusCode: true,
SendClientSecretInParams: true,
AuthorizeUrl: OpenShiftOAuthAuthorizeURL(c.MasterPublicAddr),
TokenUrl: OpenShiftOAuthTokenURL(c.MasterPublicAddr),
Scope: "",
}
return config
}
func OpenShiftOAuthAuthorizeURL(masterAddr string) string {
return masterAddr + path.Join(OpenShiftOAuthAPIPrefix, osinserver.AuthorizePath)
}
func OpenShiftOAuthTokenURL(masterAddr string) string {
return masterAddr + path.Join(OpenShiftOAuthAPIPrefix, osinserver.TokenPath)
}
func CreateOrUpdateDefaultOAuthClients(masterPublicAddr string, assetPublicAddresses []string, clientRegistry oauthclient.Registry) {
clientsToEnsure := []*oauthapi.OAuthClient{
{
ObjectMeta: kapi.ObjectMeta{
Name: OSWebConsoleClientBase.Name,
},
Secret: OSWebConsoleClientBase.Secret,
RespondWithChallenges: OSWebConsoleClientBase.RespondWithChallenges,
RedirectURIs: assetPublicAddresses,
},
{
ObjectMeta: kapi.ObjectMeta{
Name: OSBrowserClientBase.Name,
},
Secret: OSBrowserClientBase.Secret,
RespondWithChallenges: OSBrowserClientBase.RespondWithChallenges,
RedirectURIs: []string{masterPublicAddr + path.Join(OpenShiftOAuthAPIPrefix, tokenrequest.DisplayTokenEndpoint)},
},
{
ObjectMeta: kapi.ObjectMeta{
Name: OSCliClientBase.Name,
},
Secret: OSCliClientBase.Secret,
RespondWithChallenges: OSCliClientBase.RespondWithChallenges,
RedirectURIs: []string{masterPublicAddr + path.Join(OpenShiftOAuthAPIPrefix, tokenrequest.DisplayTokenEndpoint)},
},
}
for _, currClient := range clientsToEnsure {
if existing, err := clientRegistry.GetClient(currClient.Name); err == nil || strings.Contains(err.Error(), " not found") {
if existing != nil {
clientRegistry.DeleteClient(currClient.Name)
}
if err = clientRegistry.CreateClient(currClient); err != nil {
glog.Errorf("Error creating client: %v due to %v\n", currClient, err)
}
} else {
glog.Errorf("Error getting client: %v due to %v\n", currClient, err)
}
}
}
// getCSRF returns the object responsible for generating and checking CSRF tokens
func getCSRF() csrf.CSRF {
return csrf.NewCookieCSRF("csrf", "/", "", false, false)
}
func (c *AuthConfig) getSessionAuth() *session.Authenticator {
if c.sessionAuth == nil {
sessionStore := session.NewStore(int(c.SessionMaxAgeSeconds), c.SessionSecrets...)
c.sessionAuth = session.NewAuthenticator(sessionStore, c.SessionName)
}
return c.sessionAuth
}
func (c *AuthConfig) getAuthorizeAuthenticationHandlers(mux cmdutil.Mux) (authenticator.Request, handlers.AuthenticationHandler, osinserver.AuthorizeHandler) {
authRequestHandler := c.getAuthenticationRequestHandler()
authHandler := c.getAuthenticationHandler(mux, handlers.EmptyError{})
authFinalizer := c.getAuthenticationFinalizer()
return authRequestHandler, authHandler, authFinalizer
}
// getGrantHandler returns the object that handles approving or rejecting grant requests
func (c *AuthConfig) getGrantHandler(mux cmdutil.Mux, auth authenticator.Request, clientregistry clientregistry.Registry, authregistry clientauthorization.Registry) handlers.GrantHandler {
var grantHandler handlers.GrantHandler
grantHandlerType := c.GrantHandler
switch grantHandlerType {
case GrantHandlerDeny:
grantHandler = handlers.NewEmptyGrant()
case GrantHandlerAuto:
grantHandler = handlers.NewAutoGrant(authregistry)
case GrantHandlerPrompt:
grantServer := grant.NewGrant(getCSRF(), auth, grant.DefaultFormRenderer, clientregistry, authregistry)
grantServer.Install(mux, OpenShiftApprovePrefix)
grantHandler = handlers.NewRedirectGrant(OpenShiftApprovePrefix)
default:
glog.Fatalf("No grant handler found that matches %v. The oauth server cannot start!", grantHandlerType)
}
return grantHandler
}
// getAuthenticationFinalizer returns an authentication finalizer which is called just prior to writing a response to an authorization request
func (c *AuthConfig) getAuthenticationFinalizer() osinserver.AuthorizeHandler {
for _, requestHandler := range c.AuthRequestHandlers {
switch requestHandler {
case AuthRequestHandlerSession:
// The session needs to know the authorize flow is done so it can invalidate the session
return osinserver.AuthorizeHandlerFunc(func(ar *osin.AuthorizeRequest, w http.ResponseWriter) (bool, error) {
_ = c.getSessionAuth().InvalidateAuthentication(w, ar.HttpRequest)
return false, nil
})
}
}
// Otherwise return a no-op finalizer
return osinserver.AuthorizeHandlerFunc(func(ar *osin.AuthorizeRequest, w http.ResponseWriter) (bool, error) {
return false, nil
})
}
func (c *AuthConfig) getAuthenticationHandler(mux cmdutil.Mux, errorHandler handlers.AuthenticationErrorHandler) handlers.AuthenticationHandler {
successHandler := c.getAuthenticationSuccessHandler()
// TODO presumably 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 := c.AuthHandler
switch authHandlerType {
case AuthHandlerGithub, AuthHandlerGoogle:
callbackPath := path.Join(OpenShiftOAuthCallbackPrefix, string(authHandlerType))
userRegistry := useretcd.New(c.EtcdHelper, user.NewDefaultUserInitStrategy())
identityMapper := identitymapper.NewAlwaysCreateUserIdentityToUserMapper(string(authHandlerType) /*for now*/, userRegistry)
var oauthProvider external.Provider
if authHandlerType == AuthHandlerGoogle {
oauthProvider = google.NewProvider(c.GoogleClientID, c.GoogleClientSecret)
} else if authHandlerType == AuthHandlerGithub {
oauthProvider = github.NewProvider(c.GithubClientID, c.GithubClientSecret)
}
state := external.DefaultState()
oauthHandler, err := external.NewExternalOAuthRedirector(oauthProvider, state, c.MasterPublicAddr+callbackPath, successHandler, errorHandler, identityMapper)
if err != nil {
glog.Fatalf("unexpected error: %v", err)
}
mux.Handle(callbackPath, oauthHandler)
authHandler = handlers.NewUnionAuthenticationHandler(nil, map[string]handlers.AuthenticationRedirector{string(authHandlerType): oauthHandler}, errorHandler)
case AuthHandlerLogin:
passwordAuth := c.getPasswordAuthenticator()
authHandler = handlers.NewUnionAuthenticationHandler(
map[string]handlers.AuthenticationChallenger{"login": passwordchallenger.NewBasicAuthChallenger("openshift")},
map[string]handlers.AuthenticationRedirector{"login": &redirector{RedirectURL: OpenShiftLoginPrefix, ThenParam: "then"}},
errorHandler,
)
login := login.NewLogin(getCSRF(), &callbackPasswordAuthenticator{passwordAuth, successHandler}, login.DefaultLoginFormRenderer)
login.Install(mux, OpenShiftLoginPrefix)
case AuthHandlerDeny:
authHandler = handlers.EmptyAuth{}
default:
glog.Fatalf("No AuthenticationHandler found that matches %v. The oauth server cannot start!", authHandlerType)
}
return authHandler
}
func (c *AuthConfig) getPasswordAuthenticator() authenticator.Password {
// TODO presumably 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
passwordAuthType := c.PasswordAuth
userRegistry := useretcd.New(c.EtcdHelper, user.NewDefaultUserInitStrategy())
identityMapper := identitymapper.NewAlwaysCreateUserIdentityToUserMapper(string(passwordAuthType) /*for now*/, userRegistry)
var passwordAuth authenticator.Password
switch passwordAuthType {
case PasswordAuthBasicAuthURL:
basicAuthURL := c.BasicAuthURL
if len(basicAuthURL) == 0 {
glog.Fatalf("BasicAuthURL is required to support basic password auth")
}
passwordAuth = basicauthpassword.New(basicAuthURL, identityMapper)
case PasswordAuthAnyPassword:
// Accepts any username and password
passwordAuth = allowanypassword.New(identityMapper)
default:
glog.Fatalf("No password auth found that matches %v. The oauth server cannot start!", passwordAuthType)
}
return passwordAuth
}
func (c *AuthConfig) getAuthenticationSuccessHandler() handlers.AuthenticationSuccessHandler {
successHandlers := handlers.AuthenticationSuccessHandlers{}
for _, requestHandler := range c.AuthRequestHandlers {
switch requestHandler {
case AuthRequestHandlerSession:
// The session needs to know so it can write auth info into the session
successHandlers = append(successHandlers, c.getSessionAuth())
}
}
switch c.AuthHandler {
case AuthHandlerGithub, AuthHandlerGoogle:
successHandlers = append(successHandlers, external.DefaultState().(handlers.AuthenticationSuccessHandler))
case AuthHandlerLogin:
successHandlers = append(successHandlers, redirectSuccessHandler{})
}
return successHandlers
}
func (c *AuthConfig) getAuthenticationRequestHandlerFromType(authRequestHandlerType AuthRequestHandlerType) authenticator.Request {
// TODO presumably 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
switch authRequestHandlerType {
case AuthRequestHandlerBearer:
switch c.TokenStore {
case TokenStoreOAuth:
tokenAuthenticator, err := GetEtcdTokenAuthenticator(c.EtcdHelper)
if err != nil {
glog.Fatalf("Error creating TokenAuthenticator: %v. The oauth server cannot start!", err)
}
authRequestHandler = bearertoken.New(tokenAuthenticator)
case TokenStoreFile:
tokenAuthenticator, err := GetCSVTokenAuthenticator(c.TokenFilePath)
if err != nil {
glog.Fatalf("Error creating TokenAuthenticator: %v. The oauth server cannot start!", err)
}
authRequestHandler = bearertoken.New(tokenAuthenticator)
default:
glog.Fatalf("Unknown TokenStore %s. Must be oauth or file. The oauth server cannot start!", c.TokenStore)
}
case AuthRequestHandlerRequestHeader:
userRegistry := useretcd.New(c.EtcdHelper, user.NewDefaultUserInitStrategy())
identityMapper := identitymapper.NewAlwaysCreateUserIdentityToUserMapper(string(authRequestHandlerType) /*for now*/, userRegistry)
authRequestConfig := &headerrequest.Config{
UserNameHeaders: c.RequestHeaders,
}
authRequestHandler = headerrequest.NewAuthenticator(authRequestConfig, identityMapper)
case AuthRequestHandlerBasicAuth:
passwordAuthenticator := c.getPasswordAuthenticator()
authRequestHandler = basicauthrequest.NewBasicAuthAuthentication(passwordAuthenticator)
case AuthRequestHandlerSession:
authRequestHandler = c.getSessionAuth()
default:
glog.Fatalf("No AuthenticationRequestHandler found that matches %v. The oauth server cannot start!", authRequestHandlerType)
}
return authRequestHandler
}
func (c *AuthConfig) getAuthenticationRequestHandler() authenticator.Request {
// TODO presumably 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 authRequestHandlers []authenticator.Request
for _, requestHandler := range c.AuthRequestHandlers {
authRequestHandlers = append(authRequestHandlers, c.getAuthenticationRequestHandlerFromType(requestHandler))
}
authRequestHandler := unionrequest.NewUnionAuthentication(authRequestHandlers...)
return authRequestHandler
}
func GetEtcdTokenAuthenticator(etcdHelper tools.EtcdHelper) (authenticator.Token, error) {
oauthRegistry := oauthetcd.New(etcdHelper)
return authnregistry.NewTokenAuthenticator(oauthRegistry), nil
}
func GetCSVTokenAuthenticator(path string) (authenticator.Token, error) {
return filetoken.NewTokenAuthenticator(path)
}
// Captures the original request url as a "then" param in a redirect to a login flow
type redirector struct {
RedirectURL string
ThenParam string
}
// AuthenticationRedirectNeeded redirects HTTP request to authorization URL
func (auth *redirector) AuthenticationRedirect(w http.ResponseWriter, req *http.Request) error {
redirectURL, err := url.Parse(auth.RedirectURL)
if err != nil {
return err
}
if len(auth.ThenParam) != 0 {
redirectURL.RawQuery = url.Values{
auth.ThenParam: {req.URL.String()},
}.Encode()
}
http.Redirect(w, req, redirectURL.String(), http.StatusFound)
return 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{}
// AuthenticationSuccess informs client when authentication was successful
func (redirectSuccessHandler) AuthenticationSucceeded(user kuser.Info, then string, w http.ResponseWriter, req *http.Request) (bool, error) {
if len(then) == 0 {
return false, fmt.Errorf("Auth succeeded, but no redirect existed - user=%#v", user)
}
http.Redirect(w, req, then, http.StatusFound)
return true, nil
}
// authenticationHandlerFilter creates a filter object that will enforce authentication directly
func authenticationHandlerFilter(handler http.Handler, authenticator authenticator.Request, contextMapper kapi.RequestContextMapper) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
user, ok, err := authenticator.AuthenticateRequest(req)
if err != nil || !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
glog.V(4).Infof("user %v -> %v", user, req.URL)
ctx, ok := contextMapper.Get(req)
if !ok {
http.Error(w, "Unable to find request context", http.StatusInternalServerError)
return
}
if err := contextMapper.Update(req, kapi.WithUser(ctx, user)); err != nil {
glog.V(4).Infof("Error setting authenticated context: %v", err)
http.Error(w, "Unable to set authenticated request context", http.StatusInternalServerError)
return
}
handler.ServeHTTP(w, req)
})
}