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