1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
21 "git.curoverse.com/arvados.git/lib/controller/rpc"
22 "git.curoverse.com/arvados.git/sdk/go/arvados"
23 "git.curoverse.com/arvados.git/sdk/go/auth"
24 "git.curoverse.com/arvados.git/sdk/go/ctxlog"
25 "github.com/coreos/go-oidc"
27 "google.golang.org/api/option"
28 "google.golang.org/api/people/v1"
31 type googleLoginController struct {
32 issuer string // override OIDC issuer URL (normally https://accounts.google.com) for testing
33 peopleAPIBasePath string // override Google People API base URL (normally set by google pkg to https://people.googleapis.com/)
34 provider *oidc.Provider
38 func (ctrl *googleLoginController) getProvider() (*oidc.Provider, error) {
40 defer ctrl.mu.Unlock()
41 if ctrl.provider == nil {
44 issuer = "https://accounts.google.com"
46 provider, err := oidc.NewProvider(context.Background(), issuer)
50 ctrl.provider = provider
52 return ctrl.provider, nil
55 func (ctrl *googleLoginController) Login(ctx context.Context, cluster *arvados.Cluster, railsproxy *railsProxy, opts arvados.LoginOptions) (arvados.LoginResponse, error) {
56 provider, err := ctrl.getProvider()
58 return ctrl.loginError(fmt.Errorf("error setting up OpenID Connect provider: %s", err))
60 redirURL, err := (*url.URL)(&cluster.Services.Controller.ExternalURL).Parse("/login")
62 return ctrl.loginError(fmt.Errorf("error making redirect URL: %s", err))
64 conf := &oauth2.Config{
65 ClientID: cluster.Login.GoogleClientID,
66 ClientSecret: cluster.Login.GoogleClientSecret,
67 Endpoint: provider.Endpoint(),
68 Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
69 RedirectURL: redirURL.String(),
71 verifier := provider.Verifier(&oidc.Config{
72 ClientID: conf.ClientID,
75 // Initiate Google sign-in.
76 if opts.ReturnTo == "" {
77 return ctrl.loginError(errors.New("missing return_to parameter"))
79 me := url.URL(cluster.Services.Controller.ExternalURL)
80 callback, err := me.Parse("/" + arvados.EndpointLogin.Path)
82 return ctrl.loginError(err)
84 conf.RedirectURL = callback.String()
85 state := ctrl.newOAuth2State([]byte(cluster.SystemRootToken), opts.Remote, opts.ReturnTo)
86 return arvados.LoginResponse{
87 RedirectLocation: conf.AuthCodeURL(state.String(),
88 // prompt=select_account tells Google
89 // to show the "choose which Google
90 // account" page, even if the client
91 // is currently logged in to exactly
92 // one Google account.
93 oauth2.SetAuthURLParam("prompt", "select_account")),
96 // Callback after Google sign-in.
97 state := ctrl.parseOAuth2State(opts.State)
98 if !state.verify([]byte(cluster.SystemRootToken)) {
99 return ctrl.loginError(errors.New("invalid OAuth2 state"))
101 oauth2Token, err := conf.Exchange(ctx, opts.Code)
103 return ctrl.loginError(fmt.Errorf("error in OAuth2 exchange: %s", err))
105 rawIDToken, ok := oauth2Token.Extra("id_token").(string)
107 return ctrl.loginError(errors.New("error in OAuth2 exchange: no ID token in OAuth2 token"))
109 idToken, err := verifier.Verify(ctx, rawIDToken)
111 return ctrl.loginError(fmt.Errorf("error verifying ID token: %s", err))
113 authinfo, err := ctrl.getAuthInfo(ctx, cluster, conf, oauth2Token, idToken)
115 return ctrl.loginError(err)
117 ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{cluster.SystemRootToken}})
118 return railsproxy.UserSessionCreate(ctxRoot, rpc.UserSessionCreateOptions{
119 ReturnTo: state.Remote + "," + state.ReturnTo,
125 // Use a person's token to get all of their email addresses, with the
126 // primary address at index 0. The provided defaultAddr is always
127 // included in the returned slice, and is used as the primary if the
128 // Google API does not indicate one.
129 func (ctrl *googleLoginController) getAuthInfo(ctx context.Context, cluster *arvados.Cluster, conf *oauth2.Config, token *oauth2.Token, idToken *oidc.IDToken) (*rpc.UserSessionAuthInfo, error) {
130 var ret rpc.UserSessionAuthInfo
131 defer ctxlog.FromContext(ctx).WithField("ret", &ret).Debug("getAuthInfo returned")
134 Name string `json:"name"`
135 Email string `json:"email"`
136 Verified bool `json:"email_verified"`
138 if err := idToken.Claims(&claims); err != nil {
139 return nil, fmt.Errorf("error extracting claims from ID token: %s", err)
140 } else if claims.Verified {
141 // Fall back to this info if the People API call
142 // (below) doesn't return a primary && verified email.
143 if names := strings.Fields(strings.TrimSpace(claims.Name)); len(names) > 1 {
144 ret.FirstName = strings.Join(names[0:len(names)-1], " ")
145 ret.LastName = names[len(names)-1]
147 ret.FirstName = names[0]
149 ret.Email = claims.Email
152 if !cluster.Login.GoogleAlternateEmailAddresses {
154 return nil, fmt.Errorf("cannot log in with unverified email address %q", claims.Email)
159 svc, err := people.NewService(ctx, option.WithTokenSource(conf.TokenSource(ctx, token)), option.WithScopes(people.UserEmailsReadScope))
161 return nil, fmt.Errorf("error setting up People API: %s", err)
163 if p := ctrl.peopleAPIBasePath; p != "" {
164 // Override normal API endpoint (for testing)
167 person, err := people.NewPeopleService(svc).Get("people/me").PersonFields("emailAddresses,names").Do()
169 if strings.Contains(err.Error(), "Error 403") && strings.Contains(err.Error(), "accessNotConfigured") {
170 // Log the original API error, but display
171 // only the "fix config" advice to the user.
172 ctxlog.FromContext(ctx).WithError(err).WithField("email", ret.Email).Error("People API is not enabled")
173 return nil, errors.New("configuration error: Login.GoogleAlternateEmailAddresses is true, but Google People API is not enabled")
175 return nil, fmt.Errorf("error getting profile info from People API: %s", err)
179 // The given/family names returned by the People API and
180 // flagged as "primary" (if any) take precedence over the
181 // split-by-whitespace result from above.
182 for _, name := range person.Names {
183 if name.Metadata != nil && name.Metadata.Primary {
184 ret.FirstName = name.GivenName
185 ret.LastName = name.FamilyName
190 altEmails := map[string]bool{}
192 altEmails[ret.Email] = true
194 for _, ea := range person.EmailAddresses {
195 if ea.Metadata == nil || !ea.Metadata.Verified {
196 ctxlog.FromContext(ctx).WithField("address", ea.Value).Info("skipping unverified email address")
199 altEmails[ea.Value] = true
200 if ea.Metadata.Primary || ret.Email == "" {
204 if len(altEmails) == 0 {
205 return nil, errors.New("cannot log in without a verified email address")
207 for ae := range altEmails {
209 ret.AlternateEmails = append(ret.AlternateEmails, ae)
210 if i := strings.Index(ae, "@"); i > 0 && strings.ToLower(ae[i+1:]) == strings.ToLower(cluster.Users.PreferDomainForUsername) {
211 ret.Username = strings.SplitN(ae[:i], "+", 2)[0]
218 func (ctrl *googleLoginController) loginError(sendError error) (resp arvados.LoginResponse, err error) {
219 tmpl, err := template.New("error").Parse(`<h2>Login error:</h2><p>{{.}}</p>`)
223 err = tmpl.Execute(&resp.HTML, sendError.Error())
227 func (ctrl *googleLoginController) newOAuth2State(key []byte, remote, returnTo string) oauth2State {
229 Time: time.Now().Unix(),
233 s.HMAC = s.computeHMAC(key)
237 type oauth2State struct {
238 HMAC []byte // hash of other fields; see computeHMAC()
239 Time int64 // creation time (unix timestamp)
240 Remote string // remote cluster if requesting a salted token, otherwise blank
241 ReturnTo string // redirect target
244 func (ctrl *googleLoginController) parseOAuth2State(encoded string) (s oauth2State) {
245 // Errors are not checked. If decoding/parsing fails, the
246 // token will be rejected by verify().
247 decoded, _ := base64.RawURLEncoding.DecodeString(encoded)
248 f := strings.Split(string(decoded), "\n")
252 fmt.Sscanf(f[0], "%x", &s.HMAC)
253 fmt.Sscanf(f[1], "%x", &s.Time)
254 fmt.Sscanf(f[2], "%s", &s.Remote)
255 fmt.Sscanf(f[3], "%s", &s.ReturnTo)
259 func (s oauth2State) verify(key []byte) bool {
260 if delta := time.Now().Unix() - s.Time; delta < 0 || delta > 300 {
263 return hmac.Equal(s.computeHMAC(key), s.HMAC)
266 func (s oauth2State) String() string {
268 enc := base64.NewEncoder(base64.RawURLEncoding, &buf)
269 fmt.Fprintf(enc, "%x\n%x\n%s\n%s", s.HMAC, s.Time, s.Remote, s.ReturnTo)
274 func (s oauth2State) computeHMAC(key []byte) []byte {
275 mac := hmac.New(sha256.New, key)
276 fmt.Fprintf(mac, "%x %s %s", s.Time, s.Remote, s.ReturnTo)