Merge branch 'patch-1' of https://github.com/mr-c/arvados into mr-c-patch-1
[arvados.git] / lib / controller / localdb / login_oidc.go
index b0458a7ad471dd53ba593e56fc61ae81d60fde8a..9274d75d7c9fdc1973cbcad621b306599e571893 100644 (file)
@@ -36,24 +36,50 @@ type oidcLoginController struct {
        Issuer             string // OIDC issuer URL, e.g., "https://accounts.google.com"
        ClientID           string
        ClientSecret       string
-       UseGooglePeopleAPI bool // Use Google People API to look up alternate email addresses
+       UseGooglePeopleAPI bool   // Use Google People API to look up alternate email addresses
+       EmailClaim         string // OpenID claim to use as email address; typically "email"
+       EmailVerifiedClaim string // If non-empty, ensure claim value is true before accepting EmailClaim; typically "email_verified"
+       UsernameClaim      string // If non-empty, use as preferred username
 
-       peopleAPIBasePath string // override Google People API base URL (normally empty, set by google pkg to https://people.googleapis.com/)
-       provider          *oidc.Provider
-       mu                sync.Mutex
+       // override Google People API base URL for testing purposes
+       // (normally empty, set by google pkg to
+       // https://people.googleapis.com/)
+       peopleAPIBasePath string
+
+       provider   *oidc.Provider        // initialized by setup()
+       oauth2conf *oauth2.Config        // initialized by setup()
+       verifier   *oidc.IDTokenVerifier // initialized by setup()
+       mu         sync.Mutex            // protects setup()
 }
 
-func (ctrl *oidcLoginController) getProvider() (*oidc.Provider, error) {
+// Initialize ctrl.provider and ctrl.oauth2conf.
+func (ctrl *oidcLoginController) setup() error {
        ctrl.mu.Lock()
        defer ctrl.mu.Unlock()
-       if ctrl.provider == nil {
-               provider, err := oidc.NewProvider(context.Background(), ctrl.Issuer)
-               if err != nil {
-                       return nil, err
-               }
-               ctrl.provider = provider
+       if ctrl.provider != nil {
+               // already set up
+               return nil
+       }
+       redirURL, err := (*url.URL)(&ctrl.Cluster.Services.Controller.ExternalURL).Parse("/" + arvados.EndpointLogin.Path)
+       if err != nil {
+               return fmt.Errorf("error making redirect URL: %s", err)
+       }
+       provider, err := oidc.NewProvider(context.Background(), ctrl.Issuer)
+       if err != nil {
+               return err
        }
-       return ctrl.provider, nil
+       ctrl.oauth2conf = &oauth2.Config{
+               ClientID:     ctrl.ClientID,
+               ClientSecret: ctrl.ClientSecret,
+               Endpoint:     provider.Endpoint(),
+               Scopes:       []string{oidc.ScopeOpenID, "profile", "email"},
+               RedirectURL:  redirURL.String(),
+       }
+       ctrl.verifier = provider.Verifier(&oidc.Config{
+               ClientID: ctrl.ClientID,
+       })
+       ctrl.provider = provider
+       return nil
 }
 
 func (ctrl *oidcLoginController) Logout(ctx context.Context, opts arvados.LogoutOptions) (arvados.LogoutResponse, error) {
@@ -61,38 +87,18 @@ func (ctrl *oidcLoginController) Logout(ctx context.Context, opts arvados.Logout
 }
 
 func (ctrl *oidcLoginController) Login(ctx context.Context, opts arvados.LoginOptions) (arvados.LoginResponse, error) {
-       provider, err := ctrl.getProvider()
+       err := ctrl.setup()
        if err != nil {
                return loginError(fmt.Errorf("error setting up OpenID Connect provider: %s", err))
        }
-       redirURL, err := (*url.URL)(&ctrl.Cluster.Services.Controller.ExternalURL).Parse("/login")
-       if err != nil {
-               return loginError(fmt.Errorf("error making redirect URL: %s", err))
-       }
-       conf := &oauth2.Config{
-               ClientID:     ctrl.Cluster.Login.Google.ClientID,
-               ClientSecret: ctrl.Cluster.Login.Google.ClientSecret,
-               Endpoint:     provider.Endpoint(),
-               Scopes:       []string{oidc.ScopeOpenID, "profile", "email"},
-               RedirectURL:  redirURL.String(),
-       }
-       verifier := provider.Verifier(&oidc.Config{
-               ClientID: conf.ClientID,
-       })
        if opts.State == "" {
                // Initiate OIDC sign-in.
                if opts.ReturnTo == "" {
                        return loginError(errors.New("missing return_to parameter"))
                }
-               me := url.URL(ctrl.Cluster.Services.Controller.ExternalURL)
-               callback, err := me.Parse("/" + arvados.EndpointLogin.Path)
-               if err != nil {
-                       return loginError(err)
-               }
-               conf.RedirectURL = callback.String()
                state := ctrl.newOAuth2State([]byte(ctrl.Cluster.SystemRootToken), opts.Remote, opts.ReturnTo)
                return arvados.LoginResponse{
-                       RedirectLocation: conf.AuthCodeURL(state.String(),
+                       RedirectLocation: ctrl.oauth2conf.AuthCodeURL(state.String(),
                                // prompt=select_account tells Google
                                // to show the "choose which Google
                                // account" page, even if the client
@@ -106,7 +112,7 @@ func (ctrl *oidcLoginController) Login(ctx context.Context, opts arvados.LoginOp
                if !state.verify([]byte(ctrl.Cluster.SystemRootToken)) {
                        return loginError(errors.New("invalid OAuth2 state"))
                }
-               oauth2Token, err := conf.Exchange(ctx, opts.Code)
+               oauth2Token, err := ctrl.oauth2conf.Exchange(ctx, opts.Code)
                if err != nil {
                        return loginError(fmt.Errorf("error in OAuth2 exchange: %s", err))
                }
@@ -114,11 +120,11 @@ func (ctrl *oidcLoginController) Login(ctx context.Context, opts arvados.LoginOp
                if !ok {
                        return loginError(errors.New("error in OAuth2 exchange: no ID token in OAuth2 token"))
                }
-               idToken, err := verifier.Verify(ctx, rawIDToken)
+               idToken, err := ctrl.verifier.Verify(ctx, rawIDToken)
                if err != nil {
                        return loginError(fmt.Errorf("error verifying ID token: %s", err))
                }
-               authinfo, err := ctrl.getAuthInfo(ctx, ctrl.Cluster, conf, oauth2Token, idToken)
+               authinfo, err := ctrl.getAuthInfo(ctx, oauth2Token, idToken)
                if err != nil {
                        return loginError(err)
                }
@@ -138,37 +144,38 @@ func (ctrl *oidcLoginController) UserAuthenticate(ctx context.Context, opts arva
 // primary address at index 0. The provided defaultAddr is always
 // included in the returned slice, and is used as the primary if the
 // Google API does not indicate one.
-func (ctrl *oidcLoginController) getAuthInfo(ctx context.Context, cluster *arvados.Cluster, conf *oauth2.Config, token *oauth2.Token, idToken *oidc.IDToken) (*rpc.UserSessionAuthInfo, error) {
+func (ctrl *oidcLoginController) getAuthInfo(ctx context.Context, token *oauth2.Token, idToken *oidc.IDToken) (*rpc.UserSessionAuthInfo, error) {
        var ret rpc.UserSessionAuthInfo
        defer ctxlog.FromContext(ctx).WithField("ret", &ret).Debug("getAuthInfo returned")
 
-       var claims struct {
-               Name     string `json:"name"`
-               Email    string `json:"email"`
-               Verified bool   `json:"email_verified"`
-       }
+       var claims map[string]interface{}
        if err := idToken.Claims(&claims); err != nil {
                return nil, fmt.Errorf("error extracting claims from ID token: %s", err)
-       } else if claims.Verified {
+       } else if verified, _ := claims[ctrl.EmailVerifiedClaim].(bool); verified || ctrl.EmailVerifiedClaim == "" {
                // Fall back to this info if the People API call
                // (below) doesn't return a primary && verified email.
-               if names := strings.Fields(strings.TrimSpace(claims.Name)); len(names) > 1 {
+               name, _ := claims["name"].(string)
+               if names := strings.Fields(strings.TrimSpace(name)); len(names) > 1 {
                        ret.FirstName = strings.Join(names[0:len(names)-1], " ")
                        ret.LastName = names[len(names)-1]
                } else {
                        ret.FirstName = names[0]
                }
-               ret.Email = claims.Email
+               ret.Email, _ = claims[ctrl.EmailClaim].(string)
+       }
+
+       if ctrl.UsernameClaim != "" {
+               ret.Username, _ = claims[ctrl.UsernameClaim].(string)
        }
 
        if !ctrl.UseGooglePeopleAPI {
                if ret.Email == "" {
-                       return nil, fmt.Errorf("cannot log in with unverified email address %q", claims.Email)
+                       return nil, fmt.Errorf("cannot log in with unverified email address %q", claims[ctrl.EmailClaim])
                }
                return &ret, nil
        }
 
-       svc, err := people.NewService(ctx, option.WithTokenSource(conf.TokenSource(ctx, token)), option.WithScopes(people.UserEmailsReadScope))
+       svc, err := people.NewService(ctx, option.WithTokenSource(ctrl.oauth2conf.TokenSource(ctx, token)), option.WithScopes(people.UserEmailsReadScope))
        if err != nil {
                return nil, fmt.Errorf("error setting up People API: %s", err)
        }
@@ -217,9 +224,13 @@ func (ctrl *oidcLoginController) getAuthInfo(ctx context.Context, cluster *arvad
                return nil, errors.New("cannot log in without a verified email address")
        }
        for ae := range altEmails {
-               if ae != ret.Email {
-                       ret.AlternateEmails = append(ret.AlternateEmails, ae)
-                       if i := strings.Index(ae, "@"); i > 0 && strings.ToLower(ae[i+1:]) == strings.ToLower(ctrl.Cluster.Users.PreferDomainForUsername) {
+               if ae == ret.Email {
+                       continue
+               }
+               ret.AlternateEmails = append(ret.AlternateEmails, ae)
+               if ret.Username == "" {
+                       i := strings.Index(ae, "@")
+                       if i > 0 && strings.ToLower(ae[i+1:]) == strings.ToLower(ctrl.Cluster.Users.PreferDomainForUsername) {
                                ret.Username = strings.SplitN(ae[:i], "+", 2)[0]
                        }
                }