forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.go
696 lines (595 loc) · 27.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
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
package apiserver
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
"github.com/RangelReale/osin"
"github.com/RangelReale/osincli"
"github.com/golang/glog"
kerrs "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
knet "k8s.io/apimachinery/pkg/util/net"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apiserver/pkg/authentication/authenticator"
"k8s.io/apiserver/pkg/authentication/request/union"
x509request "k8s.io/apiserver/pkg/authentication/request/x509"
kuser "k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/kubernetes/pkg/client/retry"
"github.com/openshift/origin/pkg/auth/authenticator/challenger/passwordchallenger"
"github.com/openshift/origin/pkg/auth/authenticator/challenger/placeholderchallenger"
"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/password/denypassword"
"github.com/openshift/origin/pkg/auth/authenticator/password/htpasswd"
"github.com/openshift/origin/pkg/auth/authenticator/password/keystonepassword"
"github.com/openshift/origin/pkg/auth/authenticator/password/ldappassword"
"github.com/openshift/origin/pkg/auth/authenticator/redirector"
"github.com/openshift/origin/pkg/auth/authenticator/request/basicauthrequest"
"github.com/openshift/origin/pkg/auth/authenticator/request/headerrequest"
"github.com/openshift/origin/pkg/auth/ldaputil"
"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/gitlab"
"github.com/openshift/origin/pkg/auth/oauth/external/google"
"github.com/openshift/origin/pkg/auth/oauth/external/openid"
"github.com/openshift/origin/pkg/auth/oauth/handlers"
"github.com/openshift/origin/pkg/auth/oauth/registry"
"github.com/openshift/origin/pkg/auth/server/csrf"
"github.com/openshift/origin/pkg/auth/server/errorpage"
"github.com/openshift/origin/pkg/auth/server/grant"
"github.com/openshift/origin/pkg/auth/server/login"
"github.com/openshift/origin/pkg/auth/server/selectprovider"
"github.com/openshift/origin/pkg/auth/server/tokenrequest"
"github.com/openshift/origin/pkg/auth/userregistry/identitymapper"
configapi "github.com/openshift/origin/pkg/cmd/server/api"
cmdutil "github.com/openshift/origin/pkg/cmd/util"
oauthapi "github.com/openshift/origin/pkg/oauth/apis/oauth"
oauthclient "github.com/openshift/origin/pkg/oauth/generated/internalclientset/typed/oauth/internalversion"
clientregistry "github.com/openshift/origin/pkg/oauth/registry/oauthclient"
"github.com/openshift/origin/pkg/oauth/server/osinserver"
"github.com/openshift/origin/pkg/oauth/server/osinserver/registrystorage"
oauthutil "github.com/openshift/origin/pkg/oauth/util"
saoauth "github.com/openshift/origin/pkg/serviceaccounts/oauthclient"
)
const (
openShiftLoginPrefix = "/login"
openShiftApproveSubpath = "approve"
OpenShiftOAuthCallbackPrefix = "/oauth2callback"
OpenShiftWebConsoleClientID = "openshift-web-console"
OpenShiftBrowserClientID = "openshift-browser-client"
OpenShiftCLIClientID = "openshift-challenging-client"
)
// WithOAuth decorates the given handler by serving the OAuth2 endpoints while
// passing through all other requests to the given handler.
func (c *OAuthServerConfig) WithOAuth(handler http.Handler, requestContextMapper request.RequestContextMapper) (http.Handler, error) {
baseMux := http.NewServeMux()
mux := c.possiblyWrapMux(baseMux)
// pass through all other requests
mux.Handle("/", handler)
combinedOAuthClientGetter := saoauth.NewServiceAccountOAuthClientGetter(
c.KubeClient.Core(),
c.KubeClient.Core(),
c.EventsClient,
c.RouteClient.Route(),
c.OAuthClientClient,
oauthapi.GrantHandlerType(c.Options.GrantConfig.ServiceAccountMethod),
)
errorPageHandler, err := c.getErrorHandler()
if err != nil {
glog.Fatal(err)
}
authRequestHandler, authHandler, authFinalizer, err := c.getAuthorizeAuthenticationHandlers(mux, errorPageHandler, requestContextMapper)
if err != nil {
glog.Fatal(err)
}
storage := registrystorage.New(c.OAuthAccessTokenClient, c.OAuthAuthorizeTokenClient, combinedOAuthClientGetter, registry.NewUserConversion())
config := osinserver.NewDefaultServerConfig()
if c.Options.TokenConfig.AuthorizeTokenMaxAgeSeconds > 0 {
config.AuthorizationExpiration = c.Options.TokenConfig.AuthorizeTokenMaxAgeSeconds
}
if c.Options.TokenConfig.AccessTokenMaxAgeSeconds > 0 {
config.AccessExpiration = c.Options.TokenConfig.AccessTokenMaxAgeSeconds
}
grantChecker := registry.NewClientAuthorizationGrantChecker(c.OAuthClientAuthorizationClient)
grantHandler := c.getGrantHandler(mux, authRequestHandler, combinedOAuthClientGetter, c.OAuthClientAuthorizationClient)
server := osinserver.New(
config,
storage,
osinserver.AuthorizeHandlers{
handlers.NewAuthorizeAuthenticator(
authRequestHandler,
authHandler,
errorPageHandler,
),
handlers.NewGrantCheck(
grantChecker,
grantHandler,
errorPageHandler,
),
authFinalizer,
},
osinserver.AccessHandlers{
handlers.NewDenyAccessAuthenticator(),
},
osinserver.NewDefaultErrorHandler(),
)
server.Install(mux, oauthutil.OpenShiftOAuthAPIPrefix)
tokenRequestEndpoints := tokenrequest.NewEndpoints(c.Options.MasterPublicURL, c.getOsinOAuthClient)
tokenRequestEndpoints.Install(mux, oauthutil.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 baseMux, nil
}
func (c *OAuthServerConfig) getOsinOAuthClient() (*osincli.Client, error) {
browserClient, err := c.OAuthClientClient.Get(OpenShiftBrowserClientID, metav1.GetOptions{})
if err != nil {
return nil, err
}
osOAuthClientConfig := newOpenShiftOAuthClientConfig(browserClient.Name, browserClient.Secret, c.Options.MasterPublicURL, c.Options.MasterURL)
osOAuthClientConfig.RedirectUrl = oauthutil.OpenShiftOAuthTokenDisplayURL(c.Options.MasterPublicURL)
osOAuthClient, err := osincli.NewClient(osOAuthClientConfig)
if err != nil {
return nil, err
}
if len(*c.Options.MasterCA) > 0 {
rootCAs, err := cmdutil.CertPoolFromFile(*c.Options.MasterCA)
if err != nil {
return nil, err
}
osOAuthClient.Transport = knet.SetTransportDefaults(&http.Transport{
TLSClientConfig: &tls.Config{RootCAs: rootCAs},
})
}
return osOAuthClient, nil
}
func (c *OAuthServerConfig) possiblyWrapMux(mux cmdutil.Mux) cmdutil.Mux {
// Register directly into the given mux
if c.HandlerWrapper == nil {
return mux
}
// Wrap all handlers before registering into the container's mux
// This lets us do things like defer session clearing to the end of a request
return &handlerWrapperMux{
mux: mux,
wrapper: c.HandlerWrapper,
}
}
func (c *OAuthServerConfig) getErrorHandler() (*errorpage.ErrorPage, error) {
errorTemplate := ""
if c.Options.Templates != nil {
errorTemplate = c.Options.Templates.Error
}
errorPageRenderer, err := errorpage.NewErrorPageTemplateRenderer(errorTemplate)
if err != nil {
return nil, err
}
return errorpage.NewErrorPageHandler(errorPageRenderer), nil
}
// newOpenShiftOAuthClientConfig provides config for OpenShift OAuth client
func newOpenShiftOAuthClientConfig(clientId, clientSecret, masterPublicURL, masterURL string) *osincli.ClientConfig {
config := &osincli.ClientConfig{
ClientId: clientId,
ClientSecret: clientSecret,
ErrorsInStatusCode: true,
SendClientSecretInParams: true,
AuthorizeUrl: oauthutil.OpenShiftOAuthAuthorizeURL(masterPublicURL),
TokenUrl: oauthutil.OpenShiftOAuthTokenURL(masterURL),
Scope: "",
}
return config
}
func ensureOAuthClient(client oauthapi.OAuthClient, oauthClients oauthclient.OAuthClientInterface, preserveExistingRedirects, preserveExistingSecret bool) error {
_, err := oauthClients.Create(&client)
if err == nil || !kerrs.IsAlreadyExists(err) {
return err
}
return retry.RetryOnConflict(retry.DefaultRetry, func() error {
existing, err := oauthClients.Get(client.Name, metav1.GetOptions{})
if err != nil {
return err
}
// Ensure the correct challenge setting
existing.RespondWithChallenges = client.RespondWithChallenges
// Preserve an existing client secret
if !preserveExistingSecret || len(existing.Secret) == 0 {
existing.Secret = client.Secret
}
// Preserve redirects for clients other than the CLI client
// The CLI client doesn't care about the redirect URL, just the token or error fragment
if preserveExistingRedirects {
// Add in any redirects from the existing one
// This preserves any additional customized redirects in the default clients
redirects := sets.NewString(client.RedirectURIs...)
for _, redirect := range existing.RedirectURIs {
if !redirects.Has(redirect) {
client.RedirectURIs = append(client.RedirectURIs, redirect)
redirects.Insert(redirect)
}
}
}
existing.RedirectURIs = client.RedirectURIs
// If the GrantMethod is present, keep it for compatibility
// If it is empty, assign the requested strategy.
if len(existing.GrantMethod) == 0 {
existing.GrantMethod = client.GrantMethod
}
_, err = oauthClients.Update(existing)
return err
})
}
// getCSRF returns the object responsible for generating and checking CSRF tokens
func (c *OAuthServerConfig) getCSRF() csrf.CSRF {
secure := isHTTPS(c.Options.MasterPublicURL)
return csrf.NewCookieCSRF("csrf", "/", "", secure, true)
}
func (c *OAuthServerConfig) getAuthorizeAuthenticationHandlers(mux cmdutil.Mux, errorHandler handlers.AuthenticationErrorHandler, requestContextMapper request.RequestContextMapper) (authenticator.Request, handlers.AuthenticationHandler, osinserver.AuthorizeHandler, error) {
authRequestHandler, err := c.getAuthenticationRequestHandler()
if err != nil {
return nil, nil, nil, err
}
authHandler, err := c.getAuthenticationHandler(mux, errorHandler, requestContextMapper)
if err != nil {
return nil, nil, nil, err
}
authFinalizer := c.getAuthenticationFinalizer()
return authRequestHandler, authHandler, authFinalizer, nil
}
// getGrantHandler returns the object that handles approving or rejecting grant requests
func (c *OAuthServerConfig) getGrantHandler(mux cmdutil.Mux, auth authenticator.Request, clientregistry clientregistry.Getter, authregistry oauthclient.OAuthClientAuthorizationInterface) handlers.GrantHandler {
// check that the global default strategy is something we honor
if !configapi.ValidGrantHandlerTypes.Has(string(c.Options.GrantConfig.Method)) {
glog.Fatalf("No grant handler found that matches %v. The OAuth server cannot start!", c.Options.GrantConfig.Method)
}
// Since any OAuth client could require prompting, we will unconditionally
// start the GrantServer here.
grantServer := grant.NewGrant(c.getCSRF(), auth, grant.DefaultFormRenderer, clientregistry, authregistry)
grantServer.Install(mux, path.Join(oauthutil.OpenShiftOAuthAPIPrefix, osinserver.AuthorizePath, openShiftApproveSubpath))
// Set defaults for standard clients. These can be overridden.
return handlers.NewPerClientGrant(
handlers.NewRedirectGrant(openShiftApproveSubpath),
oauthapi.GrantHandlerType(c.Options.GrantConfig.Method),
)
}
// getAuthenticationFinalizer returns an authentication finalizer which is called just prior to writing a response to an authorization request
func (c *OAuthServerConfig) getAuthenticationFinalizer() osinserver.AuthorizeHandler {
if c.SessionAuth != nil {
// The session needs to know the authorize flow is done so it can invalidate the session
return osinserver.AuthorizeHandlerFunc(func(ar *osin.AuthorizeRequest, resp *osin.Response, w http.ResponseWriter) (bool, error) {
_ = c.SessionAuth.InvalidateAuthentication(w, ar.HttpRequest)
return false, nil
})
}
// Otherwise return a no-op finalizer
return osinserver.AuthorizeHandlerFunc(func(ar *osin.AuthorizeRequest, resp *osin.Response, w http.ResponseWriter) (bool, error) {
return false, nil
})
}
func (c *OAuthServerConfig) getAuthenticationHandler(mux cmdutil.Mux, errorHandler handlers.AuthenticationErrorHandler, requestContextMapper request.RequestContextMapper) (handlers.AuthenticationHandler, error) {
// TODO: make this ordered once we can have more than one
challengers := map[string]handlers.AuthenticationChallenger{}
redirectors := new(handlers.AuthenticationRedirectors)
// Determine if we have more than one password-based Identity Provider
multiplePasswordProviders := false
passwordProviderCount := 0
for _, identityProvider := range c.Options.IdentityProviders {
if configapi.IsPasswordAuthenticator(identityProvider) && identityProvider.UseAsLogin {
passwordProviderCount++
if passwordProviderCount > 1 {
multiplePasswordProviders = true
break
}
}
}
for _, identityProvider := range c.Options.IdentityProviders {
identityMapper, err := identitymapper.NewIdentityUserMapper(c.IdentityClient, c.UserClient, c.UserIdentityMappingClient, identitymapper.MappingMethodType(identityProvider.MappingMethod))
if err != nil {
return nil, err
}
// TODO: refactor handler building per type
if configapi.IsPasswordAuthenticator(identityProvider) {
passwordAuth, err := c.getPasswordAuthenticator(identityProvider)
if err != nil {
return nil, err
}
if identityProvider.UseAsLogin {
// Password auth requires:
// 1. a session success handler (to remember you logged in)
// 2. a redirectSuccessHandler (to go back to the "then" param)
if c.SessionAuth == nil {
return nil, errors.New("SessionAuth is required for password-based login")
}
passwordSuccessHandler := handlers.AuthenticationSuccessHandlers{c.SessionAuth, redirectSuccessHandler{}}
var (
// loginPath is unescaped, the way the mux will see it once URL-decoding is done
loginPath = openShiftLoginPrefix
// redirectLoginPath is escaped, the way we would need to send a Location redirect to a client
redirectLoginPath = openShiftLoginPrefix
)
if multiplePasswordProviders {
// If there is more than one Identity Provider acting as a login
// provider, we need to give each of them their own login path,
// to avoid ambiguity.
loginPath = path.Join(openShiftLoginPrefix, identityProvider.Name)
// url-encode the provider name for redirecting
redirectLoginPath = path.Join(openShiftLoginPrefix, (&url.URL{Path: identityProvider.Name}).String())
}
// Since we're redirecting to a local login page, we don't need to force absolute URL resolution
redirectors.Add(identityProvider.Name, redirector.NewRedirector(nil, redirectLoginPath+"?then=${url}"))
var loginTemplateFile string
if c.Options.Templates != nil {
loginTemplateFile = c.Options.Templates.Login
}
loginFormRenderer, err := login.NewLoginFormRenderer(loginTemplateFile)
if err != nil {
return nil, err
}
login := login.NewLogin(identityProvider.Name, c.getCSRF(), &callbackPasswordAuthenticator{passwordAuth, passwordSuccessHandler}, loginFormRenderer)
login.Install(mux, loginPath)
}
if identityProvider.UseAsChallenger {
// For now, all password challenges share a single basic challenger, since they'll all respond to any basic credentials
challengers["basic-challenge"] = passwordchallenger.NewBasicAuthChallenger("openshift")
}
} else if configapi.IsOAuthIdentityProvider(identityProvider) {
oauthProvider, err := c.getOAuthProvider(identityProvider)
if err != nil {
return nil, err
}
// Default state builder, combining CSRF and return URL handling
state := external.CSRFRedirectingState(c.getCSRF())
// OAuth auth requires
// 1. a session success handler (to remember you logged in)
// 2. a state success handler (to go back to the URL encoded in the state)
if c.SessionAuth == nil {
return nil, errors.New("SessionAuth is required for OAuth-based login")
}
oauthSuccessHandler := handlers.AuthenticationSuccessHandlers{c.SessionAuth, state}
// If the specified errorHandler doesn't handle the login error, let the state error handler attempt to propagate specific errors back to the token requester
oauthErrorHandler := handlers.AuthenticationErrorHandlers{errorHandler, state}
callbackPath := path.Join(OpenShiftOAuthCallbackPrefix, identityProvider.Name)
oauthRedirector, oauthHandler, err := external.NewExternalOAuthRedirector(oauthProvider, state, c.Options.MasterPublicURL+callbackPath, oauthSuccessHandler, oauthErrorHandler, identityMapper)
if err != nil {
return nil, fmt.Errorf("unexpected error: %v", err)
}
mux.Handle(callbackPath, oauthHandler)
if identityProvider.UseAsLogin {
redirectors.Add(identityProvider.Name, oauthRedirector)
}
if identityProvider.UseAsChallenger {
// For now, all password challenges share a single basic challenger, since they'll all respond to any basic credentials
challengers["basic-challenge"] = passwordchallenger.NewBasicAuthChallenger("openshift")
}
} else if requestHeaderProvider, isRequestHeader := identityProvider.Provider.(*configapi.RequestHeaderIdentityProvider); isRequestHeader {
// We might be redirecting to an external site, we need to fully resolve the request URL to the public master
baseRequestURL, err := url.Parse(oauthutil.OpenShiftOAuthAuthorizeURL(c.Options.MasterPublicURL))
if err != nil {
return nil, err
}
if identityProvider.UseAsChallenger {
challengers["requestheader-"+identityProvider.Name+"-redirect"] = redirector.NewChallenger(baseRequestURL, requestHeaderProvider.ChallengeURL)
}
if identityProvider.UseAsLogin {
redirectors.Add(identityProvider.Name, redirector.NewRedirector(baseRequestURL, requestHeaderProvider.LoginURL))
}
}
}
if redirectors.Count() > 0 && len(challengers) == 0 {
// Add a default challenger that will warn and give a link to the web browser token-granting location
challengers["placeholder"] = placeholderchallenger.New(oauthutil.OpenShiftOAuthTokenRequestURL(c.Options.MasterPublicURL))
}
var selectProviderTemplateFile string
if c.Options.Templates != nil {
selectProviderTemplateFile = c.Options.Templates.ProviderSelection
}
selectProviderRenderer, err := selectprovider.NewSelectProviderRenderer(selectProviderTemplateFile)
if err != nil {
return nil, err
}
selectProvider := selectprovider.NewSelectProvider(selectProviderRenderer, c.Options.AlwaysShowProviderSelection)
authHandler := handlers.NewUnionAuthenticationHandler(challengers, redirectors, errorHandler, selectProvider, requestContextMapper)
return authHandler, nil
}
func (c *OAuthServerConfig) getOAuthProvider(identityProvider configapi.IdentityProvider) (external.Provider, error) {
switch provider := identityProvider.Provider.(type) {
case (*configapi.GitHubIdentityProvider):
clientSecret, err := configapi.ResolveStringValue(provider.ClientSecret)
if err != nil {
return nil, err
}
return github.NewProvider(identityProvider.Name, provider.ClientID, clientSecret, provider.Organizations, provider.Teams), nil
case (*configapi.GitLabIdentityProvider):
transport, err := cmdutil.TransportFor(provider.CA, "", "")
if err != nil {
return nil, err
}
clientSecret, err := configapi.ResolveStringValue(provider.ClientSecret)
if err != nil {
return nil, err
}
return gitlab.NewProvider(identityProvider.Name, transport, provider.URL, provider.ClientID, clientSecret)
case (*configapi.GoogleIdentityProvider):
clientSecret, err := configapi.ResolveStringValue(provider.ClientSecret)
if err != nil {
return nil, err
}
return google.NewProvider(identityProvider.Name, provider.ClientID, clientSecret, provider.HostedDomain)
case (*configapi.OpenIDIdentityProvider):
transport, err := cmdutil.TransportFor(provider.CA, "", "")
if err != nil {
return nil, err
}
clientSecret, err := configapi.ResolveStringValue(provider.ClientSecret)
if err != nil {
return nil, err
}
// OpenID Connect requests MUST contain the openid scope value
// http://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
scopes := sets.NewString("openid")
scopes.Insert(provider.ExtraScopes...)
config := openid.Config{
ClientID: provider.ClientID,
ClientSecret: clientSecret,
Scopes: scopes.List(),
ExtraAuthorizeParameters: provider.ExtraAuthorizeParameters,
AuthorizeURL: provider.URLs.Authorize,
TokenURL: provider.URLs.Token,
UserInfoURL: provider.URLs.UserInfo,
IDClaims: provider.Claims.ID,
PreferredUsernameClaims: provider.Claims.PreferredUsername,
EmailClaims: provider.Claims.Email,
NameClaims: provider.Claims.Name,
}
return openid.NewProvider(identityProvider.Name, transport, config)
default:
return nil, fmt.Errorf("No OAuth provider found that matches %v. The OAuth server cannot start!", identityProvider)
}
}
func (c *OAuthServerConfig) getPasswordAuthenticator(identityProvider configapi.IdentityProvider) (authenticator.Password, error) {
identityMapper, err := identitymapper.NewIdentityUserMapper(c.IdentityClient, c.UserClient, c.UserIdentityMappingClient, identitymapper.MappingMethodType(identityProvider.MappingMethod))
if err != nil {
return nil, err
}
switch provider := identityProvider.Provider.(type) {
case (*configapi.AllowAllPasswordIdentityProvider):
return allowanypassword.New(identityProvider.Name, identityMapper), nil
case (*configapi.DenyAllPasswordIdentityProvider):
return denypassword.New(), nil
case (*configapi.LDAPPasswordIdentityProvider):
url, err := ldaputil.ParseURL(provider.URL)
if err != nil {
return nil, fmt.Errorf("Error parsing LDAPPasswordIdentityProvider URL: %v", err)
}
bindPassword, err := configapi.ResolveStringValue(provider.BindPassword)
if err != nil {
return nil, err
}
clientConfig, err := ldaputil.NewLDAPClientConfig(provider.URL,
provider.BindDN,
bindPassword,
provider.CA,
provider.Insecure)
if err != nil {
return nil, err
}
opts := ldappassword.Options{
URL: url,
ClientConfig: clientConfig,
UserAttributeDefiner: ldaputil.NewLDAPUserAttributeDefiner(provider.Attributes),
}
return ldappassword.New(identityProvider.Name, opts, identityMapper)
case (*configapi.HTPasswdPasswordIdentityProvider):
htpasswdFile := provider.File
if len(htpasswdFile) == 0 {
return nil, fmt.Errorf("HTPasswdFile is required to support htpasswd auth")
}
if htpasswordAuth, err := htpasswd.New(identityProvider.Name, htpasswdFile, identityMapper); err != nil {
return nil, fmt.Errorf("Error loading htpasswd file %s: %v", htpasswdFile, err)
} else {
return htpasswordAuth, nil
}
case (*configapi.BasicAuthPasswordIdentityProvider):
connectionInfo := provider.RemoteConnectionInfo
if len(connectionInfo.URL) == 0 {
return nil, fmt.Errorf("URL is required for BasicAuthPasswordIdentityProvider")
}
transport, err := cmdutil.TransportFor(connectionInfo.CA, connectionInfo.ClientCert.CertFile, connectionInfo.ClientCert.KeyFile)
if err != nil {
return nil, fmt.Errorf("Error building BasicAuthPasswordIdentityProvider client: %v", err)
}
return basicauthpassword.New(identityProvider.Name, connectionInfo.URL, transport, identityMapper), nil
case (*configapi.KeystonePasswordIdentityProvider):
connectionInfo := provider.RemoteConnectionInfo
if len(connectionInfo.URL) == 0 {
return nil, fmt.Errorf("URL is required for KeystonePasswordIdentityProvider")
}
transport, err := cmdutil.TransportFor(connectionInfo.CA, connectionInfo.ClientCert.CertFile, connectionInfo.ClientCert.KeyFile)
if err != nil {
return nil, fmt.Errorf("Error building KeystonePasswordIdentityProvider client: %v", err)
}
return keystonepassword.New(identityProvider.Name, connectionInfo.URL, transport, provider.DomainName, identityMapper), nil
default:
return nil, fmt.Errorf("No password auth found that matches %v. The OAuth server cannot start!", identityProvider)
}
}
func (c *OAuthServerConfig) getAuthenticationRequestHandler() (authenticator.Request, error) {
var authRequestHandlers []authenticator.Request
if c.SessionAuth != nil {
authRequestHandlers = append(authRequestHandlers, c.SessionAuth)
}
for _, identityProvider := range c.Options.IdentityProviders {
identityMapper, err := identitymapper.NewIdentityUserMapper(c.IdentityClient, c.UserClient, c.UserIdentityMappingClient, identitymapper.MappingMethodType(identityProvider.MappingMethod))
if err != nil {
return nil, err
}
if configapi.IsPasswordAuthenticator(identityProvider) {
passwordAuthenticator, err := c.getPasswordAuthenticator(identityProvider)
if err != nil {
return nil, err
}
authRequestHandlers = append(authRequestHandlers, basicauthrequest.NewBasicAuthAuthentication(identityProvider.Name, passwordAuthenticator, true))
} else if identityProvider.UseAsChallenger && configapi.IsOAuthIdentityProvider(identityProvider) {
oauthProvider, err := c.getOAuthProvider(identityProvider)
if err != nil {
return nil, err
}
oauthPasswordAuthenticator, err := external.NewOAuthPasswordAuthenticator(oauthProvider, identityMapper)
if err != nil {
return nil, fmt.Errorf("unexpected error: %v", err)
}
authRequestHandlers = append(authRequestHandlers, basicauthrequest.NewBasicAuthAuthentication(identityProvider.Name, oauthPasswordAuthenticator, true))
} else {
switch provider := identityProvider.Provider.(type) {
case (*configapi.RequestHeaderIdentityProvider):
var authRequestHandler authenticator.Request
authRequestConfig := &headerrequest.Config{
IDHeaders: provider.Headers,
NameHeaders: provider.NameHeaders,
EmailHeaders: provider.EmailHeaders,
PreferredUsernameHeaders: provider.PreferredUsernameHeaders,
}
authRequestHandler = headerrequest.NewAuthenticator(identityProvider.Name, authRequestConfig, identityMapper)
// Wrap with an x509 verifier
if len(provider.ClientCA) > 0 {
caData, err := ioutil.ReadFile(provider.ClientCA)
if err != nil {
return nil, fmt.Errorf("Error reading %s: %v", provider.ClientCA, err)
}
opts := x509request.DefaultVerifyOptions()
opts.Roots = x509.NewCertPool()
if ok := opts.Roots.AppendCertsFromPEM(caData); !ok {
return nil, fmt.Errorf("Error loading certs from %s: %v", provider.ClientCA, err)
}
authRequestHandler = x509request.NewVerifier(opts, authRequestHandler, sets.NewString(provider.ClientCommonNames...))
}
authRequestHandlers = append(authRequestHandlers, authRequestHandler)
}
}
}
authRequestHandler := union.New(authRequestHandlers...)
return authRequestHandler, nil
}
// callbackPasswordAuthenticator combines password auth, successful login callback,
// and "then" param redirection
type callbackPasswordAuthenticator struct {
authenticator.Password
handlers.AuthenticationSuccessHandler
}
// redirectSuccessHandler redirects to the then param on successful authentication
type redirectSuccessHandler struct{}
// AuthenticationSucceeded 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
}