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