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