1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
26 "git.arvados.org/arvados.git/lib/controller/api"
27 "git.arvados.org/arvados.git/lib/controller/rpc"
28 "git.arvados.org/arvados.git/lib/ctrlctx"
29 "git.arvados.org/arvados.git/sdk/go/arvados"
30 "git.arvados.org/arvados.git/sdk/go/auth"
31 "git.arvados.org/arvados.git/sdk/go/ctxlog"
32 "git.arvados.org/arvados.git/sdk/go/httpserver"
33 "github.com/coreos/go-oidc/v3/oidc"
34 lru "github.com/hashicorp/golang-lru"
35 "github.com/jmoiron/sqlx"
37 "github.com/sirupsen/logrus"
39 "google.golang.org/api/option"
40 "google.golang.org/api/people/v1"
41 "gopkg.in/square/go-jose.v2/jwt"
46 tokenCacheNegativeTTL = time.Minute * 5
47 tokenCacheTTL = time.Minute * 10
48 tokenCacheRaceWindow = time.Minute
49 pqCodeUniqueViolation = pq.ErrorCode("23505")
52 type oidcLoginController struct {
53 Cluster *arvados.Cluster
55 Issuer string // OIDC issuer URL, e.g., "https://accounts.google.com"
58 UseGooglePeopleAPI bool // Use Google People API to look up alternate email addresses
59 EmailClaim string // OpenID claim to use as email address; typically "email"
60 EmailVerifiedClaim string // If non-empty, ensure claim value is true before accepting EmailClaim; typically "email_verified"
61 UsernameClaim string // If non-empty, use as preferred username
62 AcceptAccessToken bool // Accept access tokens as API tokens
63 AcceptAccessTokenScope string // If non-empty, don't accept access tokens as API tokens unless they contain this scope
64 AuthParams map[string]string // Additional parameters to pass with authentication request
66 // override Google People API base URL for testing purposes
67 // (normally empty, set by google pkg to
68 // https://people.googleapis.com/)
69 peopleAPIBasePath string
71 provider *oidc.Provider // initialized by setup()
72 oauth2conf *oauth2.Config // initialized by setup()
73 verifier *oidc.IDTokenVerifier // initialized by setup()
74 mu sync.Mutex // protects setup()
77 // Initialize ctrl.provider and ctrl.oauth2conf.
78 func (ctrl *oidcLoginController) setup() error {
80 defer ctrl.mu.Unlock()
81 if ctrl.provider != nil {
85 redirURL, err := (*url.URL)(&ctrl.Cluster.Services.Controller.ExternalURL).Parse("/" + arvados.EndpointLogin.Path)
87 return fmt.Errorf("error making redirect URL: %s", err)
89 provider, err := oidc.NewProvider(context.Background(), ctrl.Issuer)
93 ctrl.oauth2conf = &oauth2.Config{
94 ClientID: ctrl.ClientID,
95 ClientSecret: ctrl.ClientSecret,
96 Endpoint: provider.Endpoint(),
97 Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
98 RedirectURL: redirURL.String(),
100 ctrl.verifier = provider.Verifier(&oidc.Config{
101 ClientID: ctrl.ClientID,
103 ctrl.provider = provider
107 func (ctrl *oidcLoginController) Logout(ctx context.Context, opts arvados.LogoutOptions) (arvados.LogoutResponse, error) {
108 return logout(ctx, ctrl.Cluster, opts)
111 func (ctrl *oidcLoginController) Login(ctx context.Context, opts arvados.LoginOptions) (arvados.LoginResponse, error) {
114 return loginError(fmt.Errorf("error setting up OpenID Connect provider: %s", err))
116 if opts.State == "" {
117 // Initiate OIDC sign-in.
118 if opts.ReturnTo == "" {
119 return loginError(errors.New("missing return_to parameter"))
121 if err := validateLoginRedirectTarget(ctrl.Parent.cluster, opts.ReturnTo); err != nil {
122 return loginError(fmt.Errorf("invalid return_to parameter: %s", err))
124 state := ctrl.newOAuth2State([]byte(ctrl.Cluster.SystemRootToken), opts.Remote, opts.ReturnTo)
125 var authparams []oauth2.AuthCodeOption
126 for k, v := range ctrl.AuthParams {
127 authparams = append(authparams, oauth2.SetAuthURLParam(k, v))
129 return arvados.LoginResponse{
130 RedirectLocation: ctrl.oauth2conf.AuthCodeURL(state.String(), authparams...),
133 // Callback after OIDC sign-in.
134 state := ctrl.parseOAuth2State(opts.State)
135 if !state.verify([]byte(ctrl.Cluster.SystemRootToken)) {
136 return loginError(errors.New("invalid OAuth2 state"))
138 oauth2Token, err := ctrl.oauth2conf.Exchange(ctx, opts.Code)
140 return loginError(fmt.Errorf("error in OAuth2 exchange: %s", err))
142 ctxlog.FromContext(ctx).WithField("oauth2Token", oauth2Token).Debug("oauth2 exchange succeeded")
143 rawIDToken, ok := oauth2Token.Extra("id_token").(string)
145 return loginError(errors.New("error in OAuth2 exchange: no ID token in OAuth2 token"))
147 ctxlog.FromContext(ctx).WithField("rawIDToken", rawIDToken).Debug("oauth2Token provided ID token")
148 idToken, err := ctrl.verifier.Verify(ctx, rawIDToken)
150 return loginError(fmt.Errorf("error verifying ID token: %s", err))
152 authinfo, err := ctrl.getAuthInfo(ctx, oauth2Token, idToken)
154 return loginError(err)
156 ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{ctrl.Cluster.SystemRootToken}})
157 return ctrl.Parent.UserSessionCreate(ctxRoot, rpc.UserSessionCreateOptions{
158 ReturnTo: state.Remote + "," + state.ReturnTo,
163 func (ctrl *oidcLoginController) UserAuthenticate(ctx context.Context, opts arvados.UserAuthenticateOptions) (arvados.APIClientAuthorization, error) {
164 return arvados.APIClientAuthorization{}, httpserver.ErrorWithStatus(errors.New("username/password authentication is not available"), http.StatusBadRequest)
167 // claimser can decode arbitrary claims into a map. Implemented by
168 // *oauth2.IDToken and *oauth2.UserInfo.
169 type claimser interface {
170 Claims(interface{}) error
173 // Use a person's token to get all of their email addresses, with the
174 // primary address at index 0. The provided defaultAddr is always
175 // included in the returned slice, and is used as the primary if the
176 // Google API does not indicate one.
177 func (ctrl *oidcLoginController) getAuthInfo(ctx context.Context, token *oauth2.Token, claimser claimser) (*rpc.UserSessionAuthInfo, error) {
178 var ret rpc.UserSessionAuthInfo
179 defer ctxlog.FromContext(ctx).WithField("ret", &ret).Debug("getAuthInfo returned")
181 var claims map[string]interface{}
182 if err := claimser.Claims(&claims); err != nil {
183 return nil, fmt.Errorf("error extracting claims from token: %s", err)
184 } else if verified, _ := claims[ctrl.EmailVerifiedClaim].(bool); verified || ctrl.EmailVerifiedClaim == "" {
185 // Fall back to this info if the People API call
186 // (below) doesn't return a primary && verified email.
187 givenName, _ := claims["given_name"].(string)
188 familyName, _ := claims["family_name"].(string)
189 if givenName != "" && familyName != "" {
190 ret.FirstName = givenName
191 ret.LastName = familyName
193 name, _ := claims["name"].(string)
194 if names := strings.Fields(strings.TrimSpace(name)); len(names) > 1 {
195 ret.FirstName = strings.Join(names[0:len(names)-1], " ")
196 ret.LastName = names[len(names)-1]
197 } else if len(names) > 0 {
198 ret.FirstName = names[0]
201 ret.Email, _ = claims[ctrl.EmailClaim].(string)
204 if ctrl.UsernameClaim != "" {
205 ret.Username, _ = claims[ctrl.UsernameClaim].(string)
208 if !ctrl.UseGooglePeopleAPI {
210 return nil, fmt.Errorf("cannot log in with unverified email address %q", claims[ctrl.EmailClaim])
215 svc, err := people.NewService(ctx, option.WithTokenSource(ctrl.oauth2conf.TokenSource(ctx, token)), option.WithScopes(people.UserEmailsReadScope))
217 return nil, fmt.Errorf("error setting up People API: %s", err)
219 if p := ctrl.peopleAPIBasePath; p != "" {
220 // Override normal API endpoint (for testing)
223 person, err := people.NewPeopleService(svc).Get("people/me").PersonFields("emailAddresses,names").Do()
225 if strings.Contains(err.Error(), "Error 403") && strings.Contains(err.Error(), "accessNotConfigured") {
226 // Log the original API error, but display
227 // only the "fix config" advice to the user.
228 ctxlog.FromContext(ctx).WithError(err).WithField("email", ret.Email).Error("People API is not enabled")
229 return nil, errors.New("configuration error: Login.GoogleAlternateEmailAddresses is true, but Google People API is not enabled")
231 return nil, fmt.Errorf("error getting profile info from People API: %s", err)
234 // The given/family names returned by the People API and
235 // flagged as "primary" (if any) take precedence over the
236 // split-by-whitespace result from above.
237 for _, name := range person.Names {
238 if name.Metadata != nil && name.Metadata.Primary {
239 ret.FirstName = name.GivenName
240 ret.LastName = name.FamilyName
245 altEmails := map[string]bool{}
247 altEmails[ret.Email] = true
249 for _, ea := range person.EmailAddresses {
250 if ea.Metadata == nil || !ea.Metadata.Verified {
251 ctxlog.FromContext(ctx).WithField("address", ea.Value).Info("skipping unverified email address")
254 altEmails[ea.Value] = true
255 if ea.Metadata.Primary || ret.Email == "" {
259 if len(altEmails) == 0 {
260 return nil, errors.New("cannot log in without a verified email address")
262 for ae := range altEmails {
266 ret.AlternateEmails = append(ret.AlternateEmails, ae)
267 if ret.Username == "" {
268 i := strings.Index(ae, "@")
269 if i > 0 && strings.ToLower(ae[i+1:]) == strings.ToLower(ctrl.Cluster.Users.PreferDomainForUsername) {
270 ret.Username = strings.SplitN(ae[:i], "+", 2)[0]
277 func loginError(sendError error) (resp arvados.LoginResponse, err error) {
278 tmpl, err := template.New("error").Parse(`<h2>Login error:</h2><p>{{.}}</p>`)
282 err = tmpl.Execute(&resp.HTML, sendError.Error())
286 func (ctrl *oidcLoginController) newOAuth2State(key []byte, remote, returnTo string) oauth2State {
288 Time: time.Now().Unix(),
292 s.HMAC = s.computeHMAC(key)
296 type oauth2State struct {
297 HMAC []byte // hash of other fields; see computeHMAC()
298 Time int64 // creation time (unix timestamp)
299 Remote string // remote cluster if requesting a salted token, otherwise blank
300 ReturnTo string // redirect target
303 func (ctrl *oidcLoginController) parseOAuth2State(encoded string) (s oauth2State) {
304 // Errors are not checked. If decoding/parsing fails, the
305 // token will be rejected by verify().
306 decoded, _ := base64.RawURLEncoding.DecodeString(encoded)
307 f := strings.Split(string(decoded), "\n")
311 fmt.Sscanf(f[0], "%x", &s.HMAC)
312 fmt.Sscanf(f[1], "%x", &s.Time)
313 fmt.Sscanf(f[2], "%s", &s.Remote)
314 fmt.Sscanf(f[3], "%s", &s.ReturnTo)
318 func (s oauth2State) verify(key []byte) bool {
319 if delta := time.Now().Unix() - s.Time; delta < 0 || delta > 300 {
322 return hmac.Equal(s.computeHMAC(key), s.HMAC)
325 func (s oauth2State) String() string {
327 enc := base64.NewEncoder(base64.RawURLEncoding, &buf)
328 fmt.Fprintf(enc, "%x\n%x\n%s\n%s", s.HMAC, s.Time, s.Remote, s.ReturnTo)
333 func (s oauth2State) computeHMAC(key []byte) []byte {
334 mac := hmac.New(sha256.New, key)
335 fmt.Fprintf(mac, "%x %s %s", s.Time, s.Remote, s.ReturnTo)
339 func OIDCAccessTokenAuthorizer(cluster *arvados.Cluster, getdb func(context.Context) (*sqlx.DB, error)) *oidcTokenAuthorizer {
340 // We want ctrl to be nil if the chosen controller is not a
341 // *oidcLoginController, so we can ignore the 2nd return value
342 // of this type cast.
343 ctrl, _ := NewConn(context.Background(), cluster, getdb).loginController.(*oidcLoginController)
344 cache, err := lru.New2Q(tokenCacheSize)
348 return &oidcTokenAuthorizer{
355 type oidcTokenAuthorizer struct {
356 ctrl *oidcLoginController
357 getdb func(context.Context) (*sqlx.DB, error)
358 cache *lru.TwoQueueCache
361 func (ta *oidcTokenAuthorizer) Middleware(w http.ResponseWriter, r *http.Request, next http.Handler) {
363 // Not using a compatible (OIDC) login controller.
364 } else if authhdr := strings.Split(r.Header.Get("Authorization"), " "); len(authhdr) > 1 && (authhdr[0] == "OAuth2" || authhdr[0] == "Bearer") {
365 err := ta.registerToken(r.Context(), authhdr[1])
367 http.Error(w, err.Error(), http.StatusInternalServerError)
374 func (ta *oidcTokenAuthorizer) WrapCalls(origFunc api.RoutableFunc) api.RoutableFunc {
376 // Not using a compatible (OIDC) login controller.
379 return func(ctx context.Context, opts interface{}) (_ interface{}, err error) {
380 creds, ok := auth.FromContext(ctx)
382 return origFunc(ctx, opts)
384 // Check each token in the incoming request. If any
385 // are valid OAuth2 access tokens, insert/update them
386 // in the database so RailsAPI's auth code accepts
388 for _, tok := range creds.Tokens {
389 err = ta.registerToken(ctx, tok)
394 return origFunc(ctx, opts)
398 // Matches error from oidc UserInfo() when receiving HTTP status 5xx
399 var re5xxError = regexp.MustCompile(`^5\d\d `)
401 // registerToken checks whether tok is a valid OIDC Access Token and,
402 // if so, ensures that an api_client_authorizations row exists so that
403 // RailsAPI will accept it as an Arvados token.
404 func (ta *oidcTokenAuthorizer) registerToken(ctx context.Context, tok string) error {
405 if tok == ta.ctrl.Cluster.SystemRootToken || strings.HasPrefix(tok, "v2/") {
408 if cached, hit := ta.cache.Get(tok); !hit {
409 // Fall through to database and OIDC provider checks
411 } else if exp, ok := cached.(time.Time); ok {
412 // cached negative result (value is expiry time)
413 if time.Now().Before(exp) {
418 // cached positive result
419 aca := cached.(arvados.APIClientAuthorization)
421 if !aca.ExpiresAt.IsZero() {
423 expiring = t.Before(time.Now().Add(time.Minute))
430 db, err := ta.getdb(ctx)
434 tx, err := db.Beginx()
439 ctx = ctrlctx.NewWithTransaction(ctx, tx)
441 // We use hmac-sha256(accesstoken,systemroottoken) as the
442 // secret part of our own token, and avoid storing the auth
443 // provider's real secret in our database.
444 mac := hmac.New(sha256.New, []byte(ta.ctrl.Cluster.SystemRootToken))
445 io.WriteString(mac, tok)
446 hmac := fmt.Sprintf("%x", mac.Sum(nil))
449 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)
450 if err != nil && err != sql.ErrNoRows {
451 return fmt.Errorf("database error while checking token: %w", err)
452 } else if err == nil && !expiring {
453 // Token is already in the database as an Arvados
454 // token, and isn't about to expire, so we can pass it
455 // through to RailsAPI etc. regardless of whether it's
456 // an OIDC access token.
459 updating := err == nil
461 // Check whether the token is a valid OIDC access token. If
462 // so, swap it out for an Arvados token (creating/updating an
463 // api_client_authorizations row if needed) which downstream
464 // server components will accept.
465 err = ta.ctrl.setup()
467 return fmt.Errorf("error setting up OpenID Connect provider: %s", err)
469 if ok, err := ta.checkAccessTokenScope(ctx, tok); err != nil || !ok {
470 // Note checkAccessTokenScope logs any interesting errors
471 ta.cache.Add(tok, time.Now().Add(tokenCacheNegativeTTL))
474 oauth2Token := &oauth2.Token{
477 userinfo, err := ta.ctrl.provider.UserInfo(ctx, oauth2.StaticTokenSource(oauth2Token))
479 if neterr := net.Error(nil); errors.As(err, &neterr) || re5xxError.MatchString(err.Error()) {
480 // If this token is in fact a valid OIDC
481 // token, but we failed to validate it here
482 // because of a network problem or internal
483 // server error, we error out now with a 5xx
484 // error, indicating to the client that they
485 // can try again. If we didn't error out now,
486 // the unrecognized token would eventually
487 // cause a 401 error further down the stack,
488 // which the caller would interpret as an
489 // unrecoverable failure.
490 ctxlog.FromContext(ctx).WithError(err).Debugf("treating OIDC UserInfo lookup error type %T as transient; failing request instead of forwarding token blindly", err)
493 ctxlog.FromContext(ctx).WithError(err).WithField("HMAC", hmac).Debug("UserInfo failed (not an OIDC token?), caching negative result")
494 ta.cache.Add(tok, time.Now().Add(tokenCacheNegativeTTL))
497 ctxlog.FromContext(ctx).WithField("userinfo", userinfo).Debug("(*oidcTokenAuthorizer)registerToken: got userinfo")
498 authinfo, err := ta.ctrl.getAuthInfo(ctx, oauth2Token, userinfo)
503 // Expiry time for our token is one minute longer than our
504 // cache TTL, so we don't pass it through to RailsAPI just as
506 exp := time.Now().UTC().Add(tokenCacheTTL + tokenCacheRaceWindow)
509 _, err = tx.ExecContext(ctx, `update api_client_authorizations set expires_at=$1 where api_token=$2`, exp, hmac)
511 return fmt.Errorf("error updating token expiry time: %w", err)
513 ctxlog.FromContext(ctx).WithField("HMAC", hmac).Debug("(*oidcTokenAuthorizer)registerToken: updated api_client_authorizations row")
515 aca, err := ta.ctrl.Parent.CreateAPIClientAuthorization(ctx, ta.ctrl.Cluster.SystemRootToken, *authinfo)
519 _, err = tx.ExecContext(ctx, `savepoint upd`)
523 _, err = tx.ExecContext(ctx, `update api_client_authorizations set api_token=$1, expires_at=$2 where uuid=$3`, hmac, exp, aca.UUID)
524 if e, ok := err.(*pq.Error); ok && e.Code == pqCodeUniqueViolation {
525 // unique_violation, given that the above
526 // query did not find a row with matching
527 // api_token, means another thread/process
528 // also received this same token and won the
529 // race to insert it -- in which case this
530 // thread doesn't need to update the database.
531 // Discard the redundant row.
532 _, err = tx.ExecContext(ctx, `rollback to savepoint upd`)
536 _, err = tx.ExecContext(ctx, `delete from api_client_authorizations where uuid=$1`, aca.UUID)
540 ctxlog.FromContext(ctx).WithField("HMAC", hmac).Debug("(*oidcTokenAuthorizer)registerToken: api_client_authorizations row inserted by another thread")
541 } else if err != nil {
542 ctxlog.FromContext(ctx).Errorf("%#v", err)
543 return fmt.Errorf("error adding OIDC access token to database: %w", err)
545 ctxlog.FromContext(ctx).WithFields(logrus.Fields{"UUID": aca.UUID, "HMAC": hmac}).Debug("(*oidcTokenAuthorizer)registerToken: inserted api_client_authorizations row")
552 ta.cache.Add(tok, arvados.APIClientAuthorization{ExpiresAt: exp})
556 // Check that the provided access token is a JWT with the required
557 // scope. If it is a valid JWT but missing the required scope, we
558 // return a 403 error, otherwise true (acceptable as an API token) or
559 // false (pass through unmodified).
561 // Return false if configured not to accept access tokens at all.
563 // Note we don't check signature or expiry here. We are relying on the
564 // caller to verify those separately (e.g., by calling the UserInfo
566 func (ta *oidcTokenAuthorizer) checkAccessTokenScope(ctx context.Context, tok string) (bool, error) {
567 if !ta.ctrl.AcceptAccessToken {
569 } else if ta.ctrl.AcceptAccessTokenScope == "" {
573 Scope string `json:"scope"`
575 if t, err := jwt.ParseSigned(tok); err != nil {
576 ctxlog.FromContext(ctx).WithError(err).Debug("error parsing jwt")
578 } else if err = t.UnsafeClaimsWithoutVerification(&claims); err != nil {
579 ctxlog.FromContext(ctx).WithError(err).Debug("error extracting jwt claims")
582 for _, s := range strings.Split(claims.Scope, " ") {
583 if s == ta.ctrl.AcceptAccessTokenScope {
587 ctxlog.FromContext(ctx).WithFields(logrus.Fields{"have": claims.Scope, "need": ta.ctrl.AcceptAccessTokenScope}).Info("unacceptable access token scope")
588 return false, httpserver.ErrorWithStatus(errors.New("unacceptable access token scope"), http.StatusUnauthorized)