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