Merge branch '16265-security-updates' into dependabot/bundler/apps/workbench/loofah...
[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.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"
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) Logout(ctx context.Context, cluster *arvados.Cluster, railsproxy *railsProxy, opts arvados.LogoutOptions) (arvados.LogoutResponse, error) {
56         target := opts.ReturnTo
57         if target == "" {
58                 if cluster.Services.Workbench2.ExternalURL.Host != "" {
59                         target = cluster.Services.Workbench2.ExternalURL.String()
60                 } else {
61                         target = cluster.Services.Workbench1.ExternalURL.String()
62                 }
63         }
64         return arvados.LogoutResponse{RedirectLocation: target}, nil
65 }
66
67 func (ctrl *googleLoginController) Login(ctx context.Context, cluster *arvados.Cluster, railsproxy *railsProxy, opts arvados.LoginOptions) (arvados.LoginResponse, error) {
68         provider, err := ctrl.getProvider()
69         if err != nil {
70                 return ctrl.loginError(fmt.Errorf("error setting up OpenID Connect provider: %s", err))
71         }
72         redirURL, err := (*url.URL)(&cluster.Services.Controller.ExternalURL).Parse("/login")
73         if err != nil {
74                 return ctrl.loginError(fmt.Errorf("error making redirect URL: %s", err))
75         }
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(),
82         }
83         verifier := provider.Verifier(&oidc.Config{
84                 ClientID: conf.ClientID,
85         })
86         if opts.State == "" {
87                 // Initiate Google sign-in.
88                 if opts.ReturnTo == "" {
89                         return ctrl.loginError(errors.New("missing return_to parameter"))
90                 }
91                 me := url.URL(cluster.Services.Controller.ExternalURL)
92                 callback, err := me.Parse("/" + arvados.EndpointLogin.Path)
93                 if err != nil {
94                         return ctrl.loginError(err)
95                 }
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")),
106                 }, nil
107         } else {
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"))
112                 }
113                 oauth2Token, err := conf.Exchange(ctx, opts.Code)
114                 if err != nil {
115                         return ctrl.loginError(fmt.Errorf("error in OAuth2 exchange: %s", err))
116                 }
117                 rawIDToken, ok := oauth2Token.Extra("id_token").(string)
118                 if !ok {
119                         return ctrl.loginError(errors.New("error in OAuth2 exchange: no ID token in OAuth2 token"))
120                 }
121                 idToken, err := verifier.Verify(ctx, rawIDToken)
122                 if err != nil {
123                         return ctrl.loginError(fmt.Errorf("error verifying ID token: %s", err))
124                 }
125                 authinfo, err := ctrl.getAuthInfo(ctx, cluster, conf, oauth2Token, idToken)
126                 if err != nil {
127                         return ctrl.loginError(err)
128                 }
129                 ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{cluster.SystemRootToken}})
130                 return railsproxy.UserSessionCreate(ctxRoot, rpc.UserSessionCreateOptions{
131                         ReturnTo: state.Remote + "," + state.ReturnTo,
132                         AuthInfo: *authinfo,
133                 })
134         }
135 }
136
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")
144
145         var claims struct {
146                 Name     string `json:"name"`
147                 Email    string `json:"email"`
148                 Verified bool   `json:"email_verified"`
149         }
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]
158                 } else {
159                         ret.FirstName = names[0]
160                 }
161                 ret.Email = claims.Email
162         }
163
164         if !cluster.Login.GoogleAlternateEmailAddresses {
165                 if ret.Email == "" {
166                         return nil, fmt.Errorf("cannot log in with unverified email address %q", claims.Email)
167                 }
168                 return &ret, nil
169         }
170
171         svc, err := people.NewService(ctx, option.WithTokenSource(conf.TokenSource(ctx, token)), option.WithScopes(people.UserEmailsReadScope))
172         if err != nil {
173                 return nil, fmt.Errorf("error setting up People API: %s", err)
174         }
175         if p := ctrl.peopleAPIBasePath; p != "" {
176                 // Override normal API endpoint (for testing)
177                 svc.BasePath = p
178         }
179         person, err := people.NewPeopleService(svc).Get("people/me").PersonFields("emailAddresses,names").Do()
180         if err != nil {
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")
186                 } else {
187                         return nil, fmt.Errorf("error getting profile info from People API: %s", err)
188                 }
189         }
190
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
198                         break
199                 }
200         }
201
202         altEmails := map[string]bool{}
203         if ret.Email != "" {
204                 altEmails[ret.Email] = true
205         }
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")
209                         continue
210                 }
211                 altEmails[ea.Value] = true
212                 if ea.Metadata.Primary || ret.Email == "" {
213                         ret.Email = ea.Value
214                 }
215         }
216         if len(altEmails) == 0 {
217                 return nil, errors.New("cannot log in without a verified email address")
218         }
219         for ae := range altEmails {
220                 if ae != ret.Email {
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]
224                         }
225                 }
226         }
227         return &ret, nil
228 }
229
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>`)
232         if err != nil {
233                 return
234         }
235         err = tmpl.Execute(&resp.HTML, sendError.Error())
236         return
237 }
238
239 func (ctrl *googleLoginController) newOAuth2State(key []byte, remote, returnTo string) oauth2State {
240         s := oauth2State{
241                 Time:     time.Now().Unix(),
242                 Remote:   remote,
243                 ReturnTo: returnTo,
244         }
245         s.HMAC = s.computeHMAC(key)
246         return s
247 }
248
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
254 }
255
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")
261         if len(f) != 4 {
262                 return
263         }
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)
268         return
269 }
270
271 func (s oauth2State) verify(key []byte) bool {
272         if delta := time.Now().Unix() - s.Time; delta < 0 || delta > 300 {
273                 return false
274         }
275         return hmac.Equal(s.computeHMAC(key), s.HMAC)
276 }
277
278 func (s oauth2State) String() string {
279         var buf bytes.Buffer
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)
282         enc.Close()
283         return buf.String()
284 }
285
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)
289         return mac.Sum(nil)
290 }