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