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