dc634e8d8f6fdba47989ce81b8b3bee59741bcd9
[arvados.git] / lib / controller / localdb / login.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package localdb
6
7 import (
8         "bytes"
9         "context"
10         "crypto/hmac"
11         "crypto/sha256"
12         "encoding/base64"
13         "errors"
14         "fmt"
15         "net/url"
16         "strings"
17         "sync"
18         "text/template"
19         "time"
20
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"
26         "golang.org/x/oauth2"
27         "google.golang.org/api/option"
28         "google.golang.org/api/people/v1"
29 )
30
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
35         mu                sync.Mutex
36 }
37
38 func (ctrl *googleLoginController) getProvider() (*oidc.Provider, error) {
39         ctrl.mu.Lock()
40         defer ctrl.mu.Unlock()
41         if ctrl.provider == nil {
42                 issuer := ctrl.issuer
43                 if issuer == "" {
44                         issuer = "https://accounts.google.com"
45                 }
46                 provider, err := oidc.NewProvider(context.Background(), issuer)
47                 if err != nil {
48                         return nil, err
49                 }
50                 ctrl.provider = provider
51         }
52         return ctrl.provider, nil
53 }
54
55 func (ctrl *googleLoginController) Login(ctx context.Context, cluster *arvados.Cluster, railsproxy *railsProxy, opts arvados.LoginOptions) (arvados.LoginResponse, error) {
56         provider, err := ctrl.getProvider()
57         if err != nil {
58                 return ctrl.loginError(fmt.Errorf("error setting up OpenID Connect provider: %s", err))
59         }
60         redirURL, err := (*url.URL)(&cluster.Services.Controller.ExternalURL).Parse("/login")
61         if err != nil {
62                 return ctrl.loginError(fmt.Errorf("error making redirect URL: %s", err))
63         }
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(),
70         }
71         verifier := provider.Verifier(&oidc.Config{
72                 ClientID: conf.ClientID,
73         })
74         if opts.State == "" {
75                 // Initiate Google sign-in.
76                 if opts.ReturnTo == "" {
77                         return ctrl.loginError(errors.New("missing return_to parameter"))
78                 }
79                 me := url.URL(cluster.Services.Controller.ExternalURL)
80                 callback, err := me.Parse("/" + arvados.EndpointLogin.Path)
81                 if err != nil {
82                         return ctrl.loginError(err)
83                 }
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")),
94                 }, nil
95         } else {
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"))
100                 }
101                 oauth2Token, err := conf.Exchange(ctx, opts.Code)
102                 if err != nil {
103                         return ctrl.loginError(fmt.Errorf("error in OAuth2 exchange: %s", err))
104                 }
105                 rawIDToken, ok := oauth2Token.Extra("id_token").(string)
106                 if !ok {
107                         return ctrl.loginError(errors.New("error in OAuth2 exchange: no ID token in OAuth2 token"))
108                 }
109                 idToken, err := verifier.Verify(ctx, rawIDToken)
110                 if err != nil {
111                         return ctrl.loginError(fmt.Errorf("error verifying ID token: %s", err))
112                 }
113                 authinfo, err := ctrl.getAuthInfo(ctx, cluster, conf, oauth2Token, idToken)
114                 if err != nil {
115                         return ctrl.loginError(err)
116                 }
117                 ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{cluster.SystemRootToken}})
118                 return railsproxy.UserSessionCreate(ctxRoot, rpc.UserSessionCreateOptions{
119                         ReturnTo: state.Remote + "," + state.ReturnTo,
120                         AuthInfo: *authinfo,
121                 })
122         }
123 }
124
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")
132
133         var claims struct {
134                 Name     string `json:"name"`
135                 Email    string `json:"email"`
136                 Verified bool   `json:"email_verified"`
137         }
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]
146                 } else {
147                         ret.FirstName = names[0]
148                 }
149                 ret.Email = claims.Email
150         }
151
152         if !cluster.Login.GoogleAlternateEmailAddresses {
153                 if ret.Email == "" {
154                         return nil, fmt.Errorf("cannot log in with unverified email address %q", claims.Email)
155                 }
156                 return &ret, nil
157         }
158
159         svc, err := people.NewService(ctx, option.WithTokenSource(conf.TokenSource(ctx, token)), option.WithScopes(people.UserEmailsReadScope))
160         if err != nil {
161                 return nil, fmt.Errorf("error setting up People API: %s", err)
162         }
163         if p := ctrl.peopleAPIBasePath; p != "" {
164                 // Override normal API endpoint (for testing)
165                 svc.BasePath = p
166         }
167         person, err := people.NewPeopleService(svc).Get("people/me").PersonFields("emailAddresses,names").Do()
168         if err != nil {
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")
174                 } else {
175                         return nil, fmt.Errorf("error getting profile info from People API: %s", err)
176                 }
177         }
178
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
186                         break
187                 }
188         }
189
190         altEmails := map[string]bool{}
191         if ret.Email != "" {
192                 altEmails[ret.Email] = true
193         }
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")
197                         continue
198                 }
199                 altEmails[ea.Value] = true
200                 if ea.Metadata.Primary || ret.Email == "" {
201                         ret.Email = ea.Value
202                 }
203         }
204         if len(altEmails) == 0 {
205                 return nil, errors.New("cannot log in without a verified email address")
206         }
207         for ae := range altEmails {
208                 if ae != ret.Email {
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]
212                         }
213                 }
214         }
215         return &ret, nil
216 }
217
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>`)
220         if err != nil {
221                 return
222         }
223         err = tmpl.Execute(&resp.HTML, sendError.Error())
224         return
225 }
226
227 func (ctrl *googleLoginController) newOAuth2State(key []byte, remote, returnTo string) oauth2State {
228         s := oauth2State{
229                 Time:     time.Now().Unix(),
230                 Remote:   remote,
231                 ReturnTo: returnTo,
232         }
233         s.HMAC = s.computeHMAC(key)
234         return s
235 }
236
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
242 }
243
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")
249         if len(f) != 4 {
250                 return
251         }
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)
256         return
257 }
258
259 func (s oauth2State) verify(key []byte) bool {
260         if delta := time.Now().Unix() - s.Time; delta < 0 || delta > 300 {
261                 return false
262         }
263         return hmac.Equal(s.computeHMAC(key), s.HMAC)
264 }
265
266 func (s oauth2State) String() string {
267         var buf bytes.Buffer
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)
270         enc.Close()
271         return buf.String()
272 }
273
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)
277         return mac.Sum(nil)
278 }