17014: Port container request federation code to new style (WIP).
[arvados.git] / lib / controller / localdb / login_oidc.go
index f42b8f8beaf1d2721a78c9883c20353eabd0e43b..d82b2adb21367152089a9de7807252aa159676ec 100644 (file)
@@ -32,11 +32,14 @@ import (
 
 type oidcLoginController struct {
        Cluster            *arvados.Cluster
-       RailsProxy         *railsProxy
+       Parent             *Conn
        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
 
        // override Google People API base URL for testing purposes
        // (normally empty, set by google pkg to
@@ -103,34 +106,33 @@ func (ctrl *oidcLoginController) Login(ctx context.Context, opts arvados.LoginOp
                                // one Google account.
                                oauth2.SetAuthURLParam("prompt", "select_account")),
                }, nil
-       } else {
-               // Callback after OIDC sign-in.
-               state := ctrl.parseOAuth2State(opts.State)
-               if !state.verify([]byte(ctrl.Cluster.SystemRootToken)) {
-                       return loginError(errors.New("invalid OAuth2 state"))
-               }
-               oauth2Token, err := ctrl.oauth2conf.Exchange(ctx, opts.Code)
-               if err != nil {
-                       return loginError(fmt.Errorf("error in OAuth2 exchange: %s", err))
-               }
-               rawIDToken, ok := oauth2Token.Extra("id_token").(string)
-               if !ok {
-                       return loginError(errors.New("error in OAuth2 exchange: no ID token in OAuth2 token"))
-               }
-               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, oauth2Token, idToken)
-               if err != nil {
-                       return loginError(err)
-               }
-               ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{ctrl.Cluster.SystemRootToken}})
-               return ctrl.RailsProxy.UserSessionCreate(ctxRoot, rpc.UserSessionCreateOptions{
-                       ReturnTo: state.Remote + "," + state.ReturnTo,
-                       AuthInfo: *authinfo,
-               })
        }
+       // Callback after OIDC sign-in.
+       state := ctrl.parseOAuth2State(opts.State)
+       if !state.verify([]byte(ctrl.Cluster.SystemRootToken)) {
+               return loginError(errors.New("invalid OAuth2 state"))
+       }
+       oauth2Token, err := ctrl.oauth2conf.Exchange(ctx, opts.Code)
+       if err != nil {
+               return loginError(fmt.Errorf("error in OAuth2 exchange: %s", err))
+       }
+       rawIDToken, ok := oauth2Token.Extra("id_token").(string)
+       if !ok {
+               return loginError(errors.New("error in OAuth2 exchange: no ID token in OAuth2 token"))
+       }
+       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, oauth2Token, idToken)
+       if err != nil {
+               return loginError(err)
+       }
+       ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{ctrl.Cluster.SystemRootToken}})
+       return ctrl.Parent.UserSessionCreate(ctxRoot, rpc.UserSessionCreateOptions{
+               ReturnTo: state.Remote + "," + state.ReturnTo,
+               AuthInfo: *authinfo,
+       })
 }
 
 func (ctrl *oidcLoginController) UserAuthenticate(ctx context.Context, opts arvados.UserAuthenticateOptions) (arvados.APIClientAuthorization, error) {
@@ -145,28 +147,29 @@ func (ctrl *oidcLoginController) getAuthInfo(ctx context.Context, token *oauth2.
        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
        }
@@ -186,9 +189,8 @@ func (ctrl *oidcLoginController) getAuthInfo(ctx context.Context, token *oauth2.
                        // only the "fix config" advice to the user.
                        ctxlog.FromContext(ctx).WithError(err).WithField("email", ret.Email).Error("People API is not enabled")
                        return nil, errors.New("configuration error: Login.GoogleAlternateEmailAddresses is true, but Google People API is not enabled")
-               } else {
-                       return nil, fmt.Errorf("error getting profile info from People API: %s", err)
                }
+               return nil, fmt.Errorf("error getting profile info from People API: %s", err)
        }
 
        // The given/family names returned by the People API and
@@ -220,9 +222,13 @@ func (ctrl *oidcLoginController) getAuthInfo(ctx context.Context, token *oauth2.
                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]
                        }
                }