Merge branch '17014-controller-container-requests-take3'
[arvados.git] / lib / controller / localdb / login_oidc.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         "database/sql"
13         "encoding/base64"
14         "errors"
15         "fmt"
16         "io"
17         "net/http"
18         "net/url"
19         "strings"
20         "sync"
21         "text/template"
22         "time"
23
24         "git.arvados.org/arvados.git/lib/controller/api"
25         "git.arvados.org/arvados.git/lib/controller/rpc"
26         "git.arvados.org/arvados.git/lib/ctrlctx"
27         "git.arvados.org/arvados.git/sdk/go/arvados"
28         "git.arvados.org/arvados.git/sdk/go/auth"
29         "git.arvados.org/arvados.git/sdk/go/ctxlog"
30         "git.arvados.org/arvados.git/sdk/go/httpserver"
31         "github.com/coreos/go-oidc"
32         lru "github.com/hashicorp/golang-lru"
33         "github.com/jmoiron/sqlx"
34         "github.com/sirupsen/logrus"
35         "golang.org/x/oauth2"
36         "google.golang.org/api/option"
37         "google.golang.org/api/people/v1"
38 )
39
40 const (
41         tokenCacheSize        = 1000
42         tokenCacheNegativeTTL = time.Minute * 5
43         tokenCacheTTL         = time.Minute * 10
44 )
45
46 type oidcLoginController struct {
47         Cluster            *arvados.Cluster
48         Parent             *Conn
49         Issuer             string // OIDC issuer URL, e.g., "https://accounts.google.com"
50         ClientID           string
51         ClientSecret       string
52         UseGooglePeopleAPI bool   // Use Google People API to look up alternate email addresses
53         EmailClaim         string // OpenID claim to use as email address; typically "email"
54         EmailVerifiedClaim string // If non-empty, ensure claim value is true before accepting EmailClaim; typically "email_verified"
55         UsernameClaim      string // If non-empty, use as preferred username
56
57         // override Google People API base URL for testing purposes
58         // (normally empty, set by google pkg to
59         // https://people.googleapis.com/)
60         peopleAPIBasePath string
61
62         provider   *oidc.Provider        // initialized by setup()
63         oauth2conf *oauth2.Config        // initialized by setup()
64         verifier   *oidc.IDTokenVerifier // initialized by setup()
65         mu         sync.Mutex            // protects setup()
66 }
67
68 // Initialize ctrl.provider and ctrl.oauth2conf.
69 func (ctrl *oidcLoginController) setup() error {
70         ctrl.mu.Lock()
71         defer ctrl.mu.Unlock()
72         if ctrl.provider != nil {
73                 // already set up
74                 return nil
75         }
76         redirURL, err := (*url.URL)(&ctrl.Cluster.Services.Controller.ExternalURL).Parse("/" + arvados.EndpointLogin.Path)
77         if err != nil {
78                 return fmt.Errorf("error making redirect URL: %s", err)
79         }
80         provider, err := oidc.NewProvider(context.Background(), ctrl.Issuer)
81         if err != nil {
82                 return err
83         }
84         ctrl.oauth2conf = &oauth2.Config{
85                 ClientID:     ctrl.ClientID,
86                 ClientSecret: ctrl.ClientSecret,
87                 Endpoint:     provider.Endpoint(),
88                 Scopes:       []string{oidc.ScopeOpenID, "profile", "email"},
89                 RedirectURL:  redirURL.String(),
90         }
91         ctrl.verifier = provider.Verifier(&oidc.Config{
92                 ClientID: ctrl.ClientID,
93         })
94         ctrl.provider = provider
95         return nil
96 }
97
98 func (ctrl *oidcLoginController) Logout(ctx context.Context, opts arvados.LogoutOptions) (arvados.LogoutResponse, error) {
99         return noopLogout(ctrl.Cluster, opts)
100 }
101
102 func (ctrl *oidcLoginController) Login(ctx context.Context, opts arvados.LoginOptions) (arvados.LoginResponse, error) {
103         err := ctrl.setup()
104         if err != nil {
105                 return loginError(fmt.Errorf("error setting up OpenID Connect provider: %s", err))
106         }
107         if opts.State == "" {
108                 // Initiate OIDC sign-in.
109                 if opts.ReturnTo == "" {
110                         return loginError(errors.New("missing return_to parameter"))
111                 }
112                 state := ctrl.newOAuth2State([]byte(ctrl.Cluster.SystemRootToken), opts.Remote, opts.ReturnTo)
113                 return arvados.LoginResponse{
114                         RedirectLocation: ctrl.oauth2conf.AuthCodeURL(state.String(),
115                                 // prompt=select_account tells Google
116                                 // to show the "choose which Google
117                                 // account" page, even if the client
118                                 // is currently logged in to exactly
119                                 // one Google account.
120                                 oauth2.SetAuthURLParam("prompt", "select_account")),
121                 }, nil
122         }
123         // Callback after OIDC sign-in.
124         state := ctrl.parseOAuth2State(opts.State)
125         if !state.verify([]byte(ctrl.Cluster.SystemRootToken)) {
126                 return loginError(errors.New("invalid OAuth2 state"))
127         }
128         oauth2Token, err := ctrl.oauth2conf.Exchange(ctx, opts.Code)
129         if err != nil {
130                 return loginError(fmt.Errorf("error in OAuth2 exchange: %s", err))
131         }
132         rawIDToken, ok := oauth2Token.Extra("id_token").(string)
133         if !ok {
134                 return loginError(errors.New("error in OAuth2 exchange: no ID token in OAuth2 token"))
135         }
136         idToken, err := ctrl.verifier.Verify(ctx, rawIDToken)
137         if err != nil {
138                 return loginError(fmt.Errorf("error verifying ID token: %s", err))
139         }
140         authinfo, err := ctrl.getAuthInfo(ctx, oauth2Token, idToken)
141         if err != nil {
142                 return loginError(err)
143         }
144         ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{ctrl.Cluster.SystemRootToken}})
145         return ctrl.Parent.UserSessionCreate(ctxRoot, rpc.UserSessionCreateOptions{
146                 ReturnTo: state.Remote + "," + state.ReturnTo,
147                 AuthInfo: *authinfo,
148         })
149 }
150
151 func (ctrl *oidcLoginController) UserAuthenticate(ctx context.Context, opts arvados.UserAuthenticateOptions) (arvados.APIClientAuthorization, error) {
152         return arvados.APIClientAuthorization{}, httpserver.ErrorWithStatus(errors.New("username/password authentication is not available"), http.StatusBadRequest)
153 }
154
155 // claimser can decode arbitrary claims into a map. Implemented by
156 // *oauth2.IDToken and *oauth2.UserInfo.
157 type claimser interface {
158         Claims(interface{}) error
159 }
160
161 // Use a person's token to get all of their email addresses, with the
162 // primary address at index 0. The provided defaultAddr is always
163 // included in the returned slice, and is used as the primary if the
164 // Google API does not indicate one.
165 func (ctrl *oidcLoginController) getAuthInfo(ctx context.Context, token *oauth2.Token, claimser claimser) (*rpc.UserSessionAuthInfo, error) {
166         var ret rpc.UserSessionAuthInfo
167         defer ctxlog.FromContext(ctx).WithField("ret", &ret).Debug("getAuthInfo returned")
168
169         var claims map[string]interface{}
170         if err := claimser.Claims(&claims); err != nil {
171                 return nil, fmt.Errorf("error extracting claims from token: %s", err)
172         } else if verified, _ := claims[ctrl.EmailVerifiedClaim].(bool); verified || ctrl.EmailVerifiedClaim == "" {
173                 // Fall back to this info if the People API call
174                 // (below) doesn't return a primary && verified email.
175                 name, _ := claims["name"].(string)
176                 if names := strings.Fields(strings.TrimSpace(name)); len(names) > 1 {
177                         ret.FirstName = strings.Join(names[0:len(names)-1], " ")
178                         ret.LastName = names[len(names)-1]
179                 } else {
180                         ret.FirstName = names[0]
181                 }
182                 ret.Email, _ = claims[ctrl.EmailClaim].(string)
183         }
184
185         if ctrl.UsernameClaim != "" {
186                 ret.Username, _ = claims[ctrl.UsernameClaim].(string)
187         }
188
189         if !ctrl.UseGooglePeopleAPI {
190                 if ret.Email == "" {
191                         return nil, fmt.Errorf("cannot log in with unverified email address %q", claims[ctrl.EmailClaim])
192                 }
193                 return &ret, nil
194         }
195
196         svc, err := people.NewService(ctx, option.WithTokenSource(ctrl.oauth2conf.TokenSource(ctx, token)), option.WithScopes(people.UserEmailsReadScope))
197         if err != nil {
198                 return nil, fmt.Errorf("error setting up People API: %s", err)
199         }
200         if p := ctrl.peopleAPIBasePath; p != "" {
201                 // Override normal API endpoint (for testing)
202                 svc.BasePath = p
203         }
204         person, err := people.NewPeopleService(svc).Get("people/me").PersonFields("emailAddresses,names").Do()
205         if err != nil {
206                 if strings.Contains(err.Error(), "Error 403") && strings.Contains(err.Error(), "accessNotConfigured") {
207                         // Log the original API error, but display
208                         // only the "fix config" advice to the user.
209                         ctxlog.FromContext(ctx).WithError(err).WithField("email", ret.Email).Error("People API is not enabled")
210                         return nil, errors.New("configuration error: Login.GoogleAlternateEmailAddresses is true, but Google People API is not enabled")
211                 }
212                 return nil, fmt.Errorf("error getting profile info from People API: %s", err)
213         }
214
215         // The given/family names returned by the People API and
216         // flagged as "primary" (if any) take precedence over the
217         // split-by-whitespace result from above.
218         for _, name := range person.Names {
219                 if name.Metadata != nil && name.Metadata.Primary {
220                         ret.FirstName = name.GivenName
221                         ret.LastName = name.FamilyName
222                         break
223                 }
224         }
225
226         altEmails := map[string]bool{}
227         if ret.Email != "" {
228                 altEmails[ret.Email] = true
229         }
230         for _, ea := range person.EmailAddresses {
231                 if ea.Metadata == nil || !ea.Metadata.Verified {
232                         ctxlog.FromContext(ctx).WithField("address", ea.Value).Info("skipping unverified email address")
233                         continue
234                 }
235                 altEmails[ea.Value] = true
236                 if ea.Metadata.Primary || ret.Email == "" {
237                         ret.Email = ea.Value
238                 }
239         }
240         if len(altEmails) == 0 {
241                 return nil, errors.New("cannot log in without a verified email address")
242         }
243         for ae := range altEmails {
244                 if ae == ret.Email {
245                         continue
246                 }
247                 ret.AlternateEmails = append(ret.AlternateEmails, ae)
248                 if ret.Username == "" {
249                         i := strings.Index(ae, "@")
250                         if i > 0 && strings.ToLower(ae[i+1:]) == strings.ToLower(ctrl.Cluster.Users.PreferDomainForUsername) {
251                                 ret.Username = strings.SplitN(ae[:i], "+", 2)[0]
252                         }
253                 }
254         }
255         return &ret, nil
256 }
257
258 func loginError(sendError error) (resp arvados.LoginResponse, err error) {
259         tmpl, err := template.New("error").Parse(`<h2>Login error:</h2><p>{{.}}</p>`)
260         if err != nil {
261                 return
262         }
263         err = tmpl.Execute(&resp.HTML, sendError.Error())
264         return
265 }
266
267 func (ctrl *oidcLoginController) newOAuth2State(key []byte, remote, returnTo string) oauth2State {
268         s := oauth2State{
269                 Time:     time.Now().Unix(),
270                 Remote:   remote,
271                 ReturnTo: returnTo,
272         }
273         s.HMAC = s.computeHMAC(key)
274         return s
275 }
276
277 type oauth2State struct {
278         HMAC     []byte // hash of other fields; see computeHMAC()
279         Time     int64  // creation time (unix timestamp)
280         Remote   string // remote cluster if requesting a salted token, otherwise blank
281         ReturnTo string // redirect target
282 }
283
284 func (ctrl *oidcLoginController) parseOAuth2State(encoded string) (s oauth2State) {
285         // Errors are not checked. If decoding/parsing fails, the
286         // token will be rejected by verify().
287         decoded, _ := base64.RawURLEncoding.DecodeString(encoded)
288         f := strings.Split(string(decoded), "\n")
289         if len(f) != 4 {
290                 return
291         }
292         fmt.Sscanf(f[0], "%x", &s.HMAC)
293         fmt.Sscanf(f[1], "%x", &s.Time)
294         fmt.Sscanf(f[2], "%s", &s.Remote)
295         fmt.Sscanf(f[3], "%s", &s.ReturnTo)
296         return
297 }
298
299 func (s oauth2State) verify(key []byte) bool {
300         if delta := time.Now().Unix() - s.Time; delta < 0 || delta > 300 {
301                 return false
302         }
303         return hmac.Equal(s.computeHMAC(key), s.HMAC)
304 }
305
306 func (s oauth2State) String() string {
307         var buf bytes.Buffer
308         enc := base64.NewEncoder(base64.RawURLEncoding, &buf)
309         fmt.Fprintf(enc, "%x\n%x\n%s\n%s", s.HMAC, s.Time, s.Remote, s.ReturnTo)
310         enc.Close()
311         return buf.String()
312 }
313
314 func (s oauth2State) computeHMAC(key []byte) []byte {
315         mac := hmac.New(sha256.New, key)
316         fmt.Fprintf(mac, "%x %s %s", s.Time, s.Remote, s.ReturnTo)
317         return mac.Sum(nil)
318 }
319
320 func OIDCAccessTokenAuthorizer(cluster *arvados.Cluster, getdb func(context.Context) (*sqlx.DB, error)) *oidcTokenAuthorizer {
321         // We want ctrl to be nil if the chosen controller is not a
322         // *oidcLoginController, so we can ignore the 2nd return value
323         // of this type cast.
324         ctrl, _ := NewConn(cluster).loginController.(*oidcLoginController)
325         cache, err := lru.New2Q(tokenCacheSize)
326         if err != nil {
327                 panic(err)
328         }
329         return &oidcTokenAuthorizer{
330                 ctrl:  ctrl,
331                 getdb: getdb,
332                 cache: cache,
333         }
334 }
335
336 type oidcTokenAuthorizer struct {
337         ctrl  *oidcLoginController
338         getdb func(context.Context) (*sqlx.DB, error)
339         cache *lru.TwoQueueCache
340 }
341
342 func (ta *oidcTokenAuthorizer) Middleware(w http.ResponseWriter, r *http.Request, next http.Handler) {
343         if ta.ctrl == nil {
344                 // Not using a compatible (OIDC) login controller.
345         } else if authhdr := strings.Split(r.Header.Get("Authorization"), " "); len(authhdr) > 1 && (authhdr[0] == "OAuth2" || authhdr[0] == "Bearer") {
346                 err := ta.registerToken(r.Context(), authhdr[1])
347                 if err != nil {
348                         http.Error(w, err.Error(), http.StatusInternalServerError)
349                         return
350                 }
351         }
352         next.ServeHTTP(w, r)
353 }
354
355 func (ta *oidcTokenAuthorizer) WrapCalls(origFunc api.RoutableFunc) api.RoutableFunc {
356         if ta.ctrl == nil {
357                 // Not using a compatible (OIDC) login controller.
358                 return origFunc
359         }
360         return func(ctx context.Context, opts interface{}) (_ interface{}, err error) {
361                 creds, ok := auth.FromContext(ctx)
362                 if !ok {
363                         return origFunc(ctx, opts)
364                 }
365                 // Check each token in the incoming request. If any
366                 // are OAuth2 access tokens, swap them out for Arvados
367                 // tokens.
368                 for _, tok := range creds.Tokens {
369                         err = ta.registerToken(ctx, tok)
370                         if err != nil {
371                                 return nil, err
372                         }
373                 }
374                 return origFunc(ctx, opts)
375         }
376 }
377
378 // registerToken checks whether tok is a valid OIDC Access Token and,
379 // if so, ensures that an api_client_authorizations row exists so that
380 // RailsAPI will accept it as an Arvados token.
381 func (ta *oidcTokenAuthorizer) registerToken(ctx context.Context, tok string) error {
382         if tok == ta.ctrl.Cluster.SystemRootToken || strings.HasPrefix(tok, "v2/") {
383                 return nil
384         }
385         if cached, hit := ta.cache.Get(tok); !hit {
386                 // Fall through to database and OIDC provider checks
387                 // below
388         } else if exp, ok := cached.(time.Time); ok {
389                 // cached negative result (value is expiry time)
390                 if time.Now().Before(exp) {
391                         return nil
392                 }
393                 ta.cache.Remove(tok)
394         } else {
395                 // cached positive result
396                 aca := cached.(arvados.APIClientAuthorization)
397                 var expiring bool
398                 if aca.ExpiresAt != "" {
399                         t, err := time.Parse(time.RFC3339Nano, aca.ExpiresAt)
400                         if err != nil {
401                                 return fmt.Errorf("error parsing expires_at value: %w", err)
402                         }
403                         expiring = t.Before(time.Now().Add(time.Minute))
404                 }
405                 if !expiring {
406                         return nil
407                 }
408         }
409
410         db, err := ta.getdb(ctx)
411         if err != nil {
412                 return err
413         }
414         tx, err := db.Beginx()
415         if err != nil {
416                 return err
417         }
418         defer tx.Rollback()
419         ctx = ctrlctx.NewWithTransaction(ctx, tx)
420
421         // We use hmac-sha256(accesstoken,systemroottoken) as the
422         // secret part of our own token, and avoid storing the auth
423         // provider's real secret in our database.
424         mac := hmac.New(sha256.New, []byte(ta.ctrl.Cluster.SystemRootToken))
425         io.WriteString(mac, tok)
426         hmac := fmt.Sprintf("%x", mac.Sum(nil))
427
428         var expiring bool
429         err = tx.QueryRowContext(ctx, `select (expires_at is not null and expires_at - interval '1 minute' <= current_timestamp at time zone 'UTC') from api_client_authorizations where api_token=$1`, hmac).Scan(&expiring)
430         if err != nil && err != sql.ErrNoRows {
431                 return fmt.Errorf("database error while checking token: %w", err)
432         } else if err == nil && !expiring {
433                 // Token is already in the database as an Arvados
434                 // token, and isn't about to expire, so we can pass it
435                 // through to RailsAPI etc. regardless of whether it's
436                 // an OIDC access token.
437                 return nil
438         }
439         updating := err == nil
440
441         // Check whether the token is a valid OIDC access token. If
442         // so, swap it out for an Arvados token (creating/updating an
443         // api_client_authorizations row if needed) which downstream
444         // server components will accept.
445         err = ta.ctrl.setup()
446         if err != nil {
447                 return fmt.Errorf("error setting up OpenID Connect provider: %s", err)
448         }
449         oauth2Token := &oauth2.Token{
450                 AccessToken: tok,
451         }
452         userinfo, err := ta.ctrl.provider.UserInfo(ctx, oauth2.StaticTokenSource(oauth2Token))
453         if err != nil {
454                 ta.cache.Add(tok, time.Now().Add(tokenCacheNegativeTTL))
455                 return nil
456         }
457         ctxlog.FromContext(ctx).WithField("userinfo", userinfo).Debug("(*oidcTokenAuthorizer)registerToken: got userinfo")
458         authinfo, err := ta.ctrl.getAuthInfo(ctx, oauth2Token, userinfo)
459         if err != nil {
460                 return err
461         }
462
463         // Expiry time for our token is one minute longer than our
464         // cache TTL, so we don't pass it through to RailsAPI just as
465         // it's expiring.
466         exp := time.Now().UTC().Add(tokenCacheTTL + time.Minute)
467
468         var aca arvados.APIClientAuthorization
469         if updating {
470                 _, err = tx.ExecContext(ctx, `update api_client_authorizations set expires_at=$1 where api_token=$2`, exp, hmac)
471                 if err != nil {
472                         return fmt.Errorf("error updating token expiry time: %w", err)
473                 }
474                 ctxlog.FromContext(ctx).WithField("HMAC", hmac).Debug("(*oidcTokenAuthorizer)registerToken: updated api_client_authorizations row")
475         } else {
476                 aca, err = ta.ctrl.Parent.CreateAPIClientAuthorization(ctx, ta.ctrl.Cluster.SystemRootToken, *authinfo)
477                 if err != nil {
478                         return err
479                 }
480                 _, err = tx.ExecContext(ctx, `update api_client_authorizations set api_token=$1, expires_at=$2 where uuid=$3`, hmac, exp, aca.UUID)
481                 if err != nil {
482                         return fmt.Errorf("error adding OIDC access token to database: %w", err)
483                 }
484                 aca.APIToken = hmac
485                 ctxlog.FromContext(ctx).WithFields(logrus.Fields{"UUID": aca.UUID, "HMAC": hmac}).Debug("(*oidcTokenAuthorizer)registerToken: inserted api_client_authorizations row")
486         }
487         err = tx.Commit()
488         if err != nil {
489                 return err
490         }
491         ta.cache.Add(tok, aca)
492         return nil
493 }