21700: Install Bundler system-wide in Rails postinst
[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"
18         "net/http"
19         "net/url"
20         "regexp"
21         "strings"
22         "sync"
23         "text/template"
24         "time"
25
26         "git.arvados.org/arvados.git/lib/controller/api"
27         "git.arvados.org/arvados.git/lib/controller/rpc"
28         "git.arvados.org/arvados.git/lib/ctrlctx"
29         "git.arvados.org/arvados.git/sdk/go/arvados"
30         "git.arvados.org/arvados.git/sdk/go/auth"
31         "git.arvados.org/arvados.git/sdk/go/ctxlog"
32         "git.arvados.org/arvados.git/sdk/go/httpserver"
33         "github.com/coreos/go-oidc/v3/oidc"
34         lru "github.com/hashicorp/golang-lru"
35         "github.com/jmoiron/sqlx"
36         "github.com/lib/pq"
37         "github.com/sirupsen/logrus"
38         "golang.org/x/oauth2"
39         "google.golang.org/api/option"
40         "google.golang.org/api/people/v1"
41         "gopkg.in/square/go-jose.v2/jwt"
42 )
43
44 var (
45         tokenCacheSize        = 1000
46         tokenCacheNegativeTTL = time.Minute * 5
47         tokenCacheTTL         = time.Minute * 10
48         tokenCacheRaceWindow  = time.Minute
49         pqCodeUniqueViolation = pq.ErrorCode("23505")
50 )
51
52 type oidcLoginController struct {
53         Cluster                *arvados.Cluster
54         Parent                 *Conn
55         Issuer                 string // OIDC issuer URL, e.g., "https://accounts.google.com"
56         ClientID               string
57         ClientSecret           string
58         UseGooglePeopleAPI     bool              // Use Google People API to look up alternate email addresses
59         EmailClaim             string            // OpenID claim to use as email address; typically "email"
60         EmailVerifiedClaim     string            // If non-empty, ensure claim value is true before accepting EmailClaim; typically "email_verified"
61         UsernameClaim          string            // If non-empty, use as preferred username
62         AcceptAccessToken      bool              // Accept access tokens as API tokens
63         AcceptAccessTokenScope string            // If non-empty, don't accept access tokens as API tokens unless they contain this scope
64         AuthParams             map[string]string // Additional parameters to pass with authentication request
65
66         // override Google People API base URL for testing purposes
67         // (normally empty, set by google pkg to
68         // https://people.googleapis.com/)
69         peopleAPIBasePath string
70
71         provider      *oidc.Provider        // initialized by setup()
72         endSessionURL *url.URL              // initialized by setup()
73         oauth2conf    *oauth2.Config        // initialized by setup()
74         verifier      *oidc.IDTokenVerifier // initialized by setup()
75         mu            sync.Mutex            // protects setup()
76 }
77
78 // Initialize ctrl.provider and ctrl.oauth2conf.
79 func (ctrl *oidcLoginController) setup() error {
80         ctrl.mu.Lock()
81         defer ctrl.mu.Unlock()
82         if ctrl.provider != nil {
83                 // already set up
84                 return nil
85         }
86         redirURL, err := (*url.URL)(&ctrl.Cluster.Services.Controller.ExternalURL).Parse("/" + arvados.EndpointLogin.Path)
87         if err != nil {
88                 return fmt.Errorf("error making redirect URL: %s", err)
89         }
90         provider, err := oidc.NewProvider(context.Background(), ctrl.Issuer)
91         if err != nil {
92                 return err
93         }
94         ctrl.oauth2conf = &oauth2.Config{
95                 ClientID:     ctrl.ClientID,
96                 ClientSecret: ctrl.ClientSecret,
97                 Endpoint:     provider.Endpoint(),
98                 Scopes:       []string{oidc.ScopeOpenID, "profile", "email"},
99                 RedirectURL:  redirURL.String(),
100         }
101         ctrl.verifier = provider.Verifier(&oidc.Config{
102                 ClientID: ctrl.ClientID,
103         })
104         ctrl.provider = provider
105         var claims struct {
106                 EndSessionEndpoint string `json:"end_session_endpoint"`
107         }
108         err = provider.Claims(&claims)
109         if err != nil {
110                 return fmt.Errorf("error parsing OIDC discovery metadata: %v", err)
111         } else if claims.EndSessionEndpoint == "" {
112                 ctrl.endSessionURL = nil
113         } else {
114                 u, err := url.Parse(claims.EndSessionEndpoint)
115                 if err != nil {
116                         return fmt.Errorf("OIDC end_session_endpoint is not a valid URL: %v", err)
117                 } else if u.Scheme != "https" {
118                         return fmt.Errorf("OIDC end_session_endpoint MUST use HTTPS but does not: %v", u.String())
119                 } else {
120                         ctrl.endSessionURL = u
121                 }
122         }
123         return nil
124 }
125
126 func (ctrl *oidcLoginController) Logout(ctx context.Context, opts arvados.LogoutOptions) (arvados.LogoutResponse, error) {
127         err := ctrl.setup()
128         if err != nil {
129                 return arvados.LogoutResponse{}, fmt.Errorf("error setting up OpenID Connect provider: %s", err)
130         }
131         resp, err := logout(ctx, ctrl.Cluster, opts)
132         if err != nil {
133                 return arvados.LogoutResponse{}, err
134         }
135         creds, credsOK := auth.FromContext(ctx)
136         if ctrl.endSessionURL != nil && credsOK && len(creds.Tokens) > 0 {
137                 values := ctrl.endSessionURL.Query()
138                 values.Set("client_id", ctrl.ClientID)
139                 values.Set("post_logout_redirect_uri", resp.RedirectLocation)
140                 u := *ctrl.endSessionURL
141                 u.RawQuery = values.Encode()
142                 resp.RedirectLocation = u.String()
143         }
144         return resp, err
145 }
146
147 func (ctrl *oidcLoginController) Login(ctx context.Context, opts arvados.LoginOptions) (arvados.LoginResponse, error) {
148         err := ctrl.setup()
149         if err != nil {
150                 return loginError(fmt.Errorf("error setting up OpenID Connect provider: %s", err))
151         }
152         if opts.State == "" {
153                 // Initiate OIDC sign-in.
154                 if opts.ReturnTo == "" {
155                         return loginError(errors.New("missing return_to parameter"))
156                 }
157                 if err := validateLoginRedirectTarget(ctrl.Parent.cluster, opts.ReturnTo); err != nil {
158                         return loginError(fmt.Errorf("invalid return_to parameter: %s", err))
159                 }
160                 state := ctrl.newOAuth2State([]byte(ctrl.Cluster.SystemRootToken), opts.Remote, opts.ReturnTo)
161                 var authparams []oauth2.AuthCodeOption
162                 for k, v := range ctrl.AuthParams {
163                         authparams = append(authparams, oauth2.SetAuthURLParam(k, v))
164                 }
165                 return arvados.LoginResponse{
166                         RedirectLocation: ctrl.oauth2conf.AuthCodeURL(state.String(), authparams...),
167                 }, nil
168         }
169         // Callback after OIDC sign-in.
170         state := ctrl.parseOAuth2State(opts.State)
171         if !state.verify([]byte(ctrl.Cluster.SystemRootToken)) {
172                 return loginError(errors.New("invalid OAuth2 state"))
173         }
174         oauth2Token, err := ctrl.oauth2conf.Exchange(ctx, opts.Code)
175         if err != nil {
176                 return loginError(fmt.Errorf("error in OAuth2 exchange: %s", err))
177         }
178         ctxlog.FromContext(ctx).WithField("oauth2Token", oauth2Token).Debug("oauth2 exchange succeeded")
179         rawIDToken, ok := oauth2Token.Extra("id_token").(string)
180         if !ok {
181                 return loginError(errors.New("error in OAuth2 exchange: no ID token in OAuth2 token"))
182         }
183         ctxlog.FromContext(ctx).WithField("rawIDToken", rawIDToken).Debug("oauth2Token provided ID token")
184         idToken, err := ctrl.verifier.Verify(ctx, rawIDToken)
185         if err != nil {
186                 return loginError(fmt.Errorf("error verifying ID token: %s", err))
187         }
188         authinfo, err := ctrl.getAuthInfo(ctx, oauth2Token, idToken)
189         if err != nil {
190                 return loginError(err)
191         }
192         ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{ctrl.Cluster.SystemRootToken}})
193         resp, err := ctrl.Parent.UserSessionCreate(ctxRoot, rpc.UserSessionCreateOptions{
194                 ReturnTo: state.Remote + ",https://controller.api.client.invalid",
195                 AuthInfo: *authinfo,
196         })
197         if err != nil {
198                 return resp, err
199         }
200         // Extract token from rails' UserSessionCreate response, and
201         // attach it to our caller's desired ReturnTo URL.  The Rails
202         // handler explicitly disallows sending the real ReturnTo as a
203         // belt-and-suspenders defence against Rails accidentally
204         // exposing an additional login relay.
205         u, err := url.Parse(resp.RedirectLocation)
206         if err != nil {
207                 return resp, err
208         }
209         token := u.Query().Get("api_token")
210         if token == "" {
211                 resp.RedirectLocation = state.ReturnTo
212         } else {
213                 u, err := url.Parse(state.ReturnTo)
214                 if err != nil {
215                         return resp, err
216                 }
217                 q := u.Query()
218                 if q == nil {
219                         q = url.Values{}
220                 }
221                 q.Set("api_token", token)
222                 u.RawQuery = q.Encode()
223                 resp.RedirectLocation = u.String()
224         }
225         return resp, nil
226 }
227
228 func (ctrl *oidcLoginController) UserAuthenticate(ctx context.Context, opts arvados.UserAuthenticateOptions) (arvados.APIClientAuthorization, error) {
229         return arvados.APIClientAuthorization{}, httpserver.ErrorWithStatus(errors.New("username/password authentication is not available"), http.StatusBadRequest)
230 }
231
232 // claimser can decode arbitrary claims into a map. Implemented by
233 // *oauth2.IDToken and *oauth2.UserInfo.
234 type claimser interface {
235         Claims(interface{}) error
236 }
237
238 // Use a person's token to get all of their email addresses, with the
239 // primary address at index 0. The provided defaultAddr is always
240 // included in the returned slice, and is used as the primary if the
241 // Google API does not indicate one.
242 func (ctrl *oidcLoginController) getAuthInfo(ctx context.Context, token *oauth2.Token, claimser claimser) (*rpc.UserSessionAuthInfo, error) {
243         var ret rpc.UserSessionAuthInfo
244         defer ctxlog.FromContext(ctx).WithField("ret", &ret).Debug("getAuthInfo returned")
245
246         var claims map[string]interface{}
247         if err := claimser.Claims(&claims); err != nil {
248                 return nil, fmt.Errorf("error extracting claims from token: %s", err)
249         } else if verified, _ := claims[ctrl.EmailVerifiedClaim].(bool); verified || ctrl.EmailVerifiedClaim == "" {
250                 // Fall back to this info if the People API call
251                 // (below) doesn't return a primary && verified email.
252                 givenName, _ := claims["given_name"].(string)
253                 familyName, _ := claims["family_name"].(string)
254                 if givenName != "" && familyName != "" {
255                         ret.FirstName = givenName
256                         ret.LastName = familyName
257                 } else {
258                         name, _ := claims["name"].(string)
259                         if names := strings.Fields(strings.TrimSpace(name)); len(names) > 1 {
260                                 ret.FirstName = strings.Join(names[0:len(names)-1], " ")
261                                 ret.LastName = names[len(names)-1]
262                         } else if len(names) > 0 {
263                                 ret.FirstName = names[0]
264                         }
265                 }
266                 ret.Email, _ = claims[ctrl.EmailClaim].(string)
267         }
268
269         if ctrl.UsernameClaim != "" {
270                 ret.Username, _ = claims[ctrl.UsernameClaim].(string)
271         }
272
273         if !ctrl.UseGooglePeopleAPI {
274                 if ret.Email == "" {
275                         return nil, fmt.Errorf("cannot log in with unverified email address %q", claims[ctrl.EmailClaim])
276                 }
277                 return &ret, nil
278         }
279
280         svc, err := people.NewService(ctx, option.WithTokenSource(ctrl.oauth2conf.TokenSource(ctx, token)), option.WithScopes(people.UserEmailsReadScope))
281         if err != nil {
282                 return nil, fmt.Errorf("error setting up People API: %s", err)
283         }
284         if p := ctrl.peopleAPIBasePath; p != "" {
285                 // Override normal API endpoint (for testing)
286                 svc.BasePath = p
287         }
288         person, err := people.NewPeopleService(svc).Get("people/me").PersonFields("emailAddresses,names").Do()
289         if err != nil {
290                 if strings.Contains(err.Error(), "Error 403") && strings.Contains(err.Error(), "accessNotConfigured") {
291                         // Log the original API error, but display
292                         // only the "fix config" advice to the user.
293                         ctxlog.FromContext(ctx).WithError(err).WithField("email", ret.Email).Error("People API is not enabled")
294                         return nil, errors.New("configuration error: Login.GoogleAlternateEmailAddresses is true, but Google People API is not enabled")
295                 }
296                 return nil, fmt.Errorf("error getting profile info from People API: %s", err)
297         }
298
299         // The given/family names returned by the People API and
300         // flagged as "primary" (if any) take precedence over the
301         // split-by-whitespace result from above.
302         for _, name := range person.Names {
303                 if name.Metadata != nil && name.Metadata.Primary {
304                         ret.FirstName = name.GivenName
305                         ret.LastName = name.FamilyName
306                         break
307                 }
308         }
309
310         altEmails := map[string]bool{}
311         if ret.Email != "" {
312                 altEmails[ret.Email] = true
313         }
314         for _, ea := range person.EmailAddresses {
315                 if ea.Metadata == nil || !ea.Metadata.Verified {
316                         ctxlog.FromContext(ctx).WithField("address", ea.Value).Info("skipping unverified email address")
317                         continue
318                 }
319                 altEmails[ea.Value] = true
320                 if ea.Metadata.Primary || ret.Email == "" {
321                         ret.Email = ea.Value
322                 }
323         }
324         if len(altEmails) == 0 {
325                 return nil, errors.New("cannot log in without a verified email address")
326         }
327         for ae := range altEmails {
328                 if ae == ret.Email {
329                         continue
330                 }
331                 ret.AlternateEmails = append(ret.AlternateEmails, ae)
332                 if ret.Username == "" {
333                         i := strings.Index(ae, "@")
334                         if i > 0 && strings.ToLower(ae[i+1:]) == strings.ToLower(ctrl.Cluster.Users.PreferDomainForUsername) {
335                                 ret.Username = strings.SplitN(ae[:i], "+", 2)[0]
336                         }
337                 }
338         }
339         return &ret, nil
340 }
341
342 func loginError(sendError error) (resp arvados.LoginResponse, err error) {
343         tmpl, err := template.New("error").Parse(`<h2>Login error:</h2><p>{{.}}</p>`)
344         if err != nil {
345                 return
346         }
347         err = tmpl.Execute(&resp.HTML, sendError.Error())
348         return
349 }
350
351 func (ctrl *oidcLoginController) newOAuth2State(key []byte, remote, returnTo string) oauth2State {
352         s := oauth2State{
353                 Time:     time.Now().Unix(),
354                 Remote:   remote,
355                 ReturnTo: returnTo,
356         }
357         s.HMAC = s.computeHMAC(key)
358         return s
359 }
360
361 type oauth2State struct {
362         HMAC     []byte // hash of other fields; see computeHMAC()
363         Time     int64  // creation time (unix timestamp)
364         Remote   string // remote cluster if requesting a salted token, otherwise blank
365         ReturnTo string // redirect target
366 }
367
368 func (ctrl *oidcLoginController) parseOAuth2State(encoded string) (s oauth2State) {
369         // Errors are not checked. If decoding/parsing fails, the
370         // token will be rejected by verify().
371         decoded, _ := base64.RawURLEncoding.DecodeString(encoded)
372         f := strings.Split(string(decoded), "\n")
373         if len(f) != 4 {
374                 return
375         }
376         fmt.Sscanf(f[0], "%x", &s.HMAC)
377         fmt.Sscanf(f[1], "%x", &s.Time)
378         fmt.Sscanf(f[2], "%s", &s.Remote)
379         fmt.Sscanf(f[3], "%s", &s.ReturnTo)
380         return
381 }
382
383 func (s oauth2State) verify(key []byte) bool {
384         if delta := time.Now().Unix() - s.Time; delta < 0 || delta > 300 {
385                 return false
386         }
387         return hmac.Equal(s.computeHMAC(key), s.HMAC)
388 }
389
390 func (s oauth2State) String() string {
391         var buf bytes.Buffer
392         enc := base64.NewEncoder(base64.RawURLEncoding, &buf)
393         fmt.Fprintf(enc, "%x\n%x\n%s\n%s", s.HMAC, s.Time, s.Remote, s.ReturnTo)
394         enc.Close()
395         return buf.String()
396 }
397
398 func (s oauth2State) computeHMAC(key []byte) []byte {
399         mac := hmac.New(sha256.New, key)
400         fmt.Fprintf(mac, "%x %s %s", s.Time, s.Remote, s.ReturnTo)
401         return mac.Sum(nil)
402 }
403
404 func OIDCAccessTokenAuthorizer(cluster *arvados.Cluster, getdb func(context.Context) (*sqlx.DB, error)) *oidcTokenAuthorizer {
405         // We want ctrl to be nil if the chosen controller is not a
406         // *oidcLoginController, so we can ignore the 2nd return value
407         // of this type cast.
408         ctrl, _ := NewConn(context.Background(), cluster, getdb).loginController.(*oidcLoginController)
409         cache, err := lru.New2Q(tokenCacheSize)
410         if err != nil {
411                 panic(err)
412         }
413         return &oidcTokenAuthorizer{
414                 ctrl:  ctrl,
415                 getdb: getdb,
416                 cache: cache,
417         }
418 }
419
420 type oidcTokenAuthorizer struct {
421         ctrl  *oidcLoginController
422         getdb func(context.Context) (*sqlx.DB, error)
423         cache *lru.TwoQueueCache
424 }
425
426 func (ta *oidcTokenAuthorizer) Middleware(w http.ResponseWriter, r *http.Request, next http.Handler) {
427         if ta.ctrl == nil {
428                 // Not using a compatible (OIDC) login controller.
429         } else if authhdr := strings.Split(r.Header.Get("Authorization"), " "); len(authhdr) > 1 && (authhdr[0] == "OAuth2" || authhdr[0] == "Bearer") {
430                 err := ta.registerToken(r.Context(), authhdr[1])
431                 if err != nil {
432                         http.Error(w, err.Error(), http.StatusInternalServerError)
433                         return
434                 }
435         }
436         next.ServeHTTP(w, r)
437 }
438
439 func (ta *oidcTokenAuthorizer) WrapCalls(origFunc api.RoutableFunc) api.RoutableFunc {
440         if ta.ctrl == nil {
441                 // Not using a compatible (OIDC) login controller.
442                 return origFunc
443         }
444         return func(ctx context.Context, opts interface{}) (_ interface{}, err error) {
445                 creds, ok := auth.FromContext(ctx)
446                 if !ok {
447                         return origFunc(ctx, opts)
448                 }
449                 // Check each token in the incoming request. If any
450                 // are valid OAuth2 access tokens, insert/update them
451                 // in the database so RailsAPI's auth code accepts
452                 // them.
453                 for _, tok := range creds.Tokens {
454                         err = ta.registerToken(ctx, tok)
455                         if err != nil {
456                                 return nil, err
457                         }
458                 }
459                 return origFunc(ctx, opts)
460         }
461 }
462
463 // Matches error from oidc UserInfo() when receiving HTTP status 5xx
464 var re5xxError = regexp.MustCompile(`^5\d\d `)
465
466 // registerToken checks whether tok is a valid OIDC Access Token and,
467 // if so, ensures that an api_client_authorizations row exists so that
468 // RailsAPI will accept it as an Arvados token.
469 func (ta *oidcTokenAuthorizer) registerToken(ctx context.Context, tok string) error {
470         if tok == ta.ctrl.Cluster.SystemRootToken || strings.HasPrefix(tok, "v2/") {
471                 return nil
472         }
473         if cached, hit := ta.cache.Get(tok); !hit {
474                 // Fall through to database and OIDC provider checks
475                 // below
476         } else if exp, ok := cached.(time.Time); ok {
477                 // cached negative result (value is expiry time)
478                 if time.Now().Before(exp) {
479                         return nil
480                 }
481                 ta.cache.Remove(tok)
482         } else {
483                 // cached positive result
484                 aca := cached.(arvados.APIClientAuthorization)
485                 var expiring bool
486                 if !aca.ExpiresAt.IsZero() {
487                         t := aca.ExpiresAt
488                         expiring = t.Before(time.Now().Add(time.Minute))
489                 }
490                 if !expiring {
491                         return nil
492                 }
493         }
494
495         db, err := ta.getdb(ctx)
496         if err != nil {
497                 return err
498         }
499         tx, err := db.Beginx()
500         if err != nil {
501                 return err
502         }
503         defer tx.Rollback()
504         ctx = ctrlctx.NewWithTransaction(ctx, tx)
505
506         // We use hmac-sha256(accesstoken,systemroottoken) as the
507         // secret part of our own token, and avoid storing the auth
508         // provider's real secret in our database.
509         mac := hmac.New(sha256.New, []byte(ta.ctrl.Cluster.SystemRootToken))
510         io.WriteString(mac, tok)
511         hmac := fmt.Sprintf("%x", mac.Sum(nil))
512
513         var expiring bool
514         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)
515         if err != nil && err != sql.ErrNoRows {
516                 return fmt.Errorf("database error while checking token: %w", err)
517         } else if err == nil && !expiring {
518                 // Token is already in the database as an Arvados
519                 // token, and isn't about to expire, so we can pass it
520                 // through to RailsAPI etc. regardless of whether it's
521                 // an OIDC access token.
522                 return nil
523         }
524         updating := err == nil
525
526         // Check whether the token is a valid OIDC access token. If
527         // so, swap it out for an Arvados token (creating/updating an
528         // api_client_authorizations row if needed) which downstream
529         // server components will accept.
530         err = ta.ctrl.setup()
531         if err != nil {
532                 return fmt.Errorf("error setting up OpenID Connect provider: %s", err)
533         }
534         if ok, err := ta.checkAccessTokenScope(ctx, tok); err != nil || !ok {
535                 // Note checkAccessTokenScope logs any interesting errors
536                 ta.cache.Add(tok, time.Now().Add(tokenCacheNegativeTTL))
537                 return err
538         }
539         oauth2Token := &oauth2.Token{
540                 AccessToken: tok,
541         }
542         userinfo, err := ta.ctrl.provider.UserInfo(ctx, oauth2.StaticTokenSource(oauth2Token))
543         if err != nil {
544                 if neterr := net.Error(nil); errors.As(err, &neterr) || re5xxError.MatchString(err.Error()) {
545                         // If this token is in fact a valid OIDC
546                         // token, but we failed to validate it here
547                         // because of a network problem or internal
548                         // server error, we error out now with a 5xx
549                         // error, indicating to the client that they
550                         // can try again.  If we didn't error out now,
551                         // the unrecognized token would eventually
552                         // cause a 401 error further down the stack,
553                         // which the caller would interpret as an
554                         // unrecoverable failure.
555                         ctxlog.FromContext(ctx).WithError(err).Debugf("treating OIDC UserInfo lookup error type %T as transient; failing request instead of forwarding token blindly", err)
556                         return err
557                 }
558                 ctxlog.FromContext(ctx).WithError(err).WithField("HMAC", hmac).Debug("UserInfo failed (not an OIDC token?), caching negative result")
559                 ta.cache.Add(tok, time.Now().Add(tokenCacheNegativeTTL))
560                 return nil
561         }
562         ctxlog.FromContext(ctx).WithField("userinfo", userinfo).Debug("(*oidcTokenAuthorizer)registerToken: got userinfo")
563         authinfo, err := ta.ctrl.getAuthInfo(ctx, oauth2Token, userinfo)
564         if err != nil {
565                 return err
566         }
567
568         // Expiry time for our token is one minute longer than our
569         // cache TTL, so we don't pass it through to RailsAPI just as
570         // it's expiring.
571         exp := time.Now().UTC().Add(tokenCacheTTL + tokenCacheRaceWindow)
572
573         if updating {
574                 _, err = tx.ExecContext(ctx, `update api_client_authorizations set expires_at=$1 where api_token=$2`, exp, hmac)
575                 if err != nil {
576                         return fmt.Errorf("error updating token expiry time: %w", err)
577                 }
578                 ctxlog.FromContext(ctx).WithField("HMAC", hmac).Debug("(*oidcTokenAuthorizer)registerToken: updated api_client_authorizations row")
579         } else {
580                 aca, err := ta.ctrl.Parent.CreateAPIClientAuthorization(ctx, ta.ctrl.Cluster.SystemRootToken, *authinfo)
581                 if err != nil {
582                         return err
583                 }
584                 _, err = tx.ExecContext(ctx, `savepoint upd`)
585                 if err != nil {
586                         return err
587                 }
588                 _, err = tx.ExecContext(ctx, `update api_client_authorizations set api_token=$1, expires_at=$2 where uuid=$3`, hmac, exp, aca.UUID)
589                 if e, ok := err.(*pq.Error); ok && e.Code == pqCodeUniqueViolation {
590                         // unique_violation, given that the above
591                         // query did not find a row with matching
592                         // api_token, means another thread/process
593                         // also received this same token and won the
594                         // race to insert it -- in which case this
595                         // thread doesn't need to update the database.
596                         // Discard the redundant row.
597                         _, err = tx.ExecContext(ctx, `rollback to savepoint upd`)
598                         if err != nil {
599                                 return err
600                         }
601                         _, err = tx.ExecContext(ctx, `delete from api_client_authorizations where uuid=$1`, aca.UUID)
602                         if err != nil {
603                                 return err
604                         }
605                         ctxlog.FromContext(ctx).WithField("HMAC", hmac).Debug("(*oidcTokenAuthorizer)registerToken: api_client_authorizations row inserted by another thread")
606                 } else if err != nil {
607                         ctxlog.FromContext(ctx).Errorf("%#v", err)
608                         return fmt.Errorf("error adding OIDC access token to database: %w", err)
609                 } else {
610                         ctxlog.FromContext(ctx).WithFields(logrus.Fields{"UUID": aca.UUID, "HMAC": hmac}).Debug("(*oidcTokenAuthorizer)registerToken: inserted api_client_authorizations row")
611                 }
612         }
613         err = tx.Commit()
614         if err != nil {
615                 return err
616         }
617         ta.cache.Add(tok, arvados.APIClientAuthorization{ExpiresAt: exp})
618         return nil
619 }
620
621 // Check that the provided access token is a JWT with the required
622 // scope. If it is a valid JWT but missing the required scope, we
623 // return a 403 error, otherwise true (acceptable as an API token) or
624 // false (pass through unmodified).
625 //
626 // Return false if configured not to accept access tokens at all.
627 //
628 // Note we don't check signature or expiry here. We are relying on the
629 // caller to verify those separately (e.g., by calling the UserInfo
630 // endpoint).
631 func (ta *oidcTokenAuthorizer) checkAccessTokenScope(ctx context.Context, tok string) (bool, error) {
632         if !ta.ctrl.AcceptAccessToken {
633                 return false, nil
634         } else if ta.ctrl.AcceptAccessTokenScope == "" {
635                 return true, nil
636         }
637         var claims struct {
638                 Scope string `json:"scope"`
639         }
640         if t, err := jwt.ParseSigned(tok); err != nil {
641                 ctxlog.FromContext(ctx).WithError(err).Debug("error parsing jwt")
642                 return false, nil
643         } else if err = t.UnsafeClaimsWithoutVerification(&claims); err != nil {
644                 ctxlog.FromContext(ctx).WithError(err).Debug("error extracting jwt claims")
645                 return false, nil
646         }
647         for _, s := range strings.Split(claims.Scope, " ") {
648                 if s == ta.ctrl.AcceptAccessTokenScope {
649                         return true, nil
650                 }
651         }
652         ctxlog.FromContext(ctx).WithFields(logrus.Fields{"have": claims.Scope, "need": ta.ctrl.AcceptAccessTokenScope}).Info("unacceptable access token scope")
653         return false, httpserver.ErrorWithStatus(errors.New("unacceptable access token scope"), http.StatusUnauthorized)
654 }