1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
21 "git.arvados.org/arvados.git/lib/controller/rpc"
22 "git.arvados.org/arvados.git/sdk/go/arvados"
23 "git.arvados.org/arvados.git/sdk/go/auth"
24 "git.arvados.org/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) Logout(ctx context.Context, cluster *arvados.Cluster, railsproxy *railsProxy, opts arvados.LogoutOptions) (arvados.LogoutResponse, error) {
56 target := opts.ReturnTo
58 if cluster.Services.Workbench2.ExternalURL.Host != "" {
59 target = cluster.Services.Workbench2.ExternalURL.String()
61 target = cluster.Services.Workbench1.ExternalURL.String()
64 return arvados.LogoutResponse{RedirectLocation: target}, nil
67 func (ctrl *googleLoginController) Login(ctx context.Context, cluster *arvados.Cluster, railsproxy *railsProxy, opts arvados.LoginOptions) (arvados.LoginResponse, error) {
68 provider, err := ctrl.getProvider()
70 return ctrl.loginError(fmt.Errorf("error setting up OpenID Connect provider: %s", err))
72 redirURL, err := (*url.URL)(&cluster.Services.Controller.ExternalURL).Parse("/login")
74 return ctrl.loginError(fmt.Errorf("error making redirect URL: %s", err))
76 conf := &oauth2.Config{
77 ClientID: cluster.Login.GoogleClientID,
78 ClientSecret: cluster.Login.GoogleClientSecret,
79 Endpoint: provider.Endpoint(),
80 Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
81 RedirectURL: redirURL.String(),
83 verifier := provider.Verifier(&oidc.Config{
84 ClientID: conf.ClientID,
87 // Initiate Google sign-in.
88 if opts.ReturnTo == "" {
89 return ctrl.loginError(errors.New("missing return_to parameter"))
91 me := url.URL(cluster.Services.Controller.ExternalURL)
92 callback, err := me.Parse("/" + arvados.EndpointLogin.Path)
94 return ctrl.loginError(err)
96 conf.RedirectURL = callback.String()
97 state := ctrl.newOAuth2State([]byte(cluster.SystemRootToken), opts.Remote, opts.ReturnTo)
98 return arvados.LoginResponse{
99 RedirectLocation: conf.AuthCodeURL(state.String(),
100 // prompt=select_account tells Google
101 // to show the "choose which Google
102 // account" page, even if the client
103 // is currently logged in to exactly
104 // one Google account.
105 oauth2.SetAuthURLParam("prompt", "select_account")),
108 // Callback after Google sign-in.
109 state := ctrl.parseOAuth2State(opts.State)
110 if !state.verify([]byte(cluster.SystemRootToken)) {
111 return ctrl.loginError(errors.New("invalid OAuth2 state"))
113 oauth2Token, err := conf.Exchange(ctx, opts.Code)
115 return ctrl.loginError(fmt.Errorf("error in OAuth2 exchange: %s", err))
117 rawIDToken, ok := oauth2Token.Extra("id_token").(string)
119 return ctrl.loginError(errors.New("error in OAuth2 exchange: no ID token in OAuth2 token"))
121 idToken, err := verifier.Verify(ctx, rawIDToken)
123 return ctrl.loginError(fmt.Errorf("error verifying ID token: %s", err))
125 authinfo, err := ctrl.getAuthInfo(ctx, cluster, conf, oauth2Token, idToken)
127 return ctrl.loginError(err)
129 ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{cluster.SystemRootToken}})
130 return railsproxy.UserSessionCreate(ctxRoot, rpc.UserSessionCreateOptions{
131 ReturnTo: state.Remote + "," + state.ReturnTo,
137 // Use a person's token to get all of their email addresses, with the
138 // primary address at index 0. The provided defaultAddr is always
139 // included in the returned slice, and is used as the primary if the
140 // Google API does not indicate one.
141 func (ctrl *googleLoginController) getAuthInfo(ctx context.Context, cluster *arvados.Cluster, conf *oauth2.Config, token *oauth2.Token, idToken *oidc.IDToken) (*rpc.UserSessionAuthInfo, error) {
142 var ret rpc.UserSessionAuthInfo
143 defer ctxlog.FromContext(ctx).WithField("ret", &ret).Debug("getAuthInfo returned")
146 Name string `json:"name"`
147 Email string `json:"email"`
148 Verified bool `json:"email_verified"`
150 if err := idToken.Claims(&claims); err != nil {
151 return nil, fmt.Errorf("error extracting claims from ID token: %s", err)
152 } else if claims.Verified {
153 // Fall back to this info if the People API call
154 // (below) doesn't return a primary && verified email.
155 if names := strings.Fields(strings.TrimSpace(claims.Name)); len(names) > 1 {
156 ret.FirstName = strings.Join(names[0:len(names)-1], " ")
157 ret.LastName = names[len(names)-1]
159 ret.FirstName = names[0]
161 ret.Email = claims.Email
164 if !cluster.Login.GoogleAlternateEmailAddresses {
166 return nil, fmt.Errorf("cannot log in with unverified email address %q", claims.Email)
171 svc, err := people.NewService(ctx, option.WithTokenSource(conf.TokenSource(ctx, token)), option.WithScopes(people.UserEmailsReadScope))
173 return nil, fmt.Errorf("error setting up People API: %s", err)
175 if p := ctrl.peopleAPIBasePath; p != "" {
176 // Override normal API endpoint (for testing)
179 person, err := people.NewPeopleService(svc).Get("people/me").PersonFields("emailAddresses,names").Do()
181 if strings.Contains(err.Error(), "Error 403") && strings.Contains(err.Error(), "accessNotConfigured") {
182 // Log the original API error, but display
183 // only the "fix config" advice to the user.
184 ctxlog.FromContext(ctx).WithError(err).WithField("email", ret.Email).Error("People API is not enabled")
185 return nil, errors.New("configuration error: Login.GoogleAlternateEmailAddresses is true, but Google People API is not enabled")
187 return nil, fmt.Errorf("error getting profile info from People API: %s", err)
191 // The given/family names returned by the People API and
192 // flagged as "primary" (if any) take precedence over the
193 // split-by-whitespace result from above.
194 for _, name := range person.Names {
195 if name.Metadata != nil && name.Metadata.Primary {
196 ret.FirstName = name.GivenName
197 ret.LastName = name.FamilyName
202 altEmails := map[string]bool{}
204 altEmails[ret.Email] = true
206 for _, ea := range person.EmailAddresses {
207 if ea.Metadata == nil || !ea.Metadata.Verified {
208 ctxlog.FromContext(ctx).WithField("address", ea.Value).Info("skipping unverified email address")
211 altEmails[ea.Value] = true
212 if ea.Metadata.Primary || ret.Email == "" {
216 if len(altEmails) == 0 {
217 return nil, errors.New("cannot log in without a verified email address")
219 for ae := range altEmails {
221 ret.AlternateEmails = append(ret.AlternateEmails, ae)
222 if i := strings.Index(ae, "@"); i > 0 && strings.ToLower(ae[i+1:]) == strings.ToLower(cluster.Users.PreferDomainForUsername) {
223 ret.Username = strings.SplitN(ae[:i], "+", 2)[0]
230 func (ctrl *googleLoginController) loginError(sendError error) (resp arvados.LoginResponse, err error) {
231 tmpl, err := template.New("error").Parse(`<h2>Login error:</h2><p>{{.}}</p>`)
235 err = tmpl.Execute(&resp.HTML, sendError.Error())
239 func (ctrl *googleLoginController) newOAuth2State(key []byte, remote, returnTo string) oauth2State {
241 Time: time.Now().Unix(),
245 s.HMAC = s.computeHMAC(key)
249 type oauth2State struct {
250 HMAC []byte // hash of other fields; see computeHMAC()
251 Time int64 // creation time (unix timestamp)
252 Remote string // remote cluster if requesting a salted token, otherwise blank
253 ReturnTo string // redirect target
256 func (ctrl *googleLoginController) parseOAuth2State(encoded string) (s oauth2State) {
257 // Errors are not checked. If decoding/parsing fails, the
258 // token will be rejected by verify().
259 decoded, _ := base64.RawURLEncoding.DecodeString(encoded)
260 f := strings.Split(string(decoded), "\n")
264 fmt.Sscanf(f[0], "%x", &s.HMAC)
265 fmt.Sscanf(f[1], "%x", &s.Time)
266 fmt.Sscanf(f[2], "%s", &s.Remote)
267 fmt.Sscanf(f[3], "%s", &s.ReturnTo)
271 func (s oauth2State) verify(key []byte) bool {
272 if delta := time.Now().Unix() - s.Time; delta < 0 || delta > 300 {
275 return hmac.Equal(s.computeHMAC(key), s.HMAC)
278 func (s oauth2State) String() string {
280 enc := base64.NewEncoder(base64.RawURLEncoding, &buf)
281 fmt.Fprintf(enc, "%x\n%x\n%s\n%s", s.HMAC, s.Time, s.Remote, s.ReturnTo)
286 func (s oauth2State) computeHMAC(key []byte) []byte {
287 mac := hmac.New(sha256.New, key)
288 fmt.Fprintf(mac, "%x %s %s", s.Time, s.Remote, s.ReturnTo)