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 endSessionURL *url.URL // initialized by setup()
73 oauth2conf *oauth2.Config // initialized by setup()
74 verifier *oidc.IDTokenVerifier // initialized by setup()
75 mu sync.Mutex // protects setup()
78 // Initialize ctrl.provider and ctrl.oauth2conf.
79 func (ctrl *oidcLoginController) setup() error {
81 defer ctrl.mu.Unlock()
82 if ctrl.provider != nil {
86 redirURL, err := (*url.URL)(&ctrl.Cluster.Services.Controller.ExternalURL).Parse("/" + arvados.EndpointLogin.Path)
88 return fmt.Errorf("error making redirect URL: %s", err)
90 provider, err := oidc.NewProvider(context.Background(), ctrl.Issuer)
94 ctrl.oauth2conf = &oauth2.Config{
95 ClientID: ctrl.ClientID,
96 ClientSecret: ctrl.ClientSecret,
97 Endpoint: provider.Endpoint(),
98 Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
99 RedirectURL: redirURL.String(),
101 ctrl.verifier = provider.Verifier(&oidc.Config{
102 ClientID: ctrl.ClientID,
104 ctrl.provider = provider
106 EndSessionEndpoint string `json:"end_session_endpoint"`
108 err = provider.Claims(&claims)
110 return fmt.Errorf("error parsing OIDC discovery metadata: %v", err)
111 } else if claims.EndSessionEndpoint == "" {
112 ctrl.endSessionURL = nil
114 u, err := url.Parse(claims.EndSessionEndpoint)
116 return fmt.Errorf("OIDC end_session_endpoint is not a valid URL: %v", err)
117 } else if u.Scheme != "https" {
118 return fmt.Errorf("OIDC end_session_endpoint MUST use HTTPS but does not: %v", u.String())
120 ctrl.endSessionURL = u
126 func (ctrl *oidcLoginController) Logout(ctx context.Context, opts arvados.LogoutOptions) (arvados.LogoutResponse, error) {
129 return arvados.LogoutResponse{}, fmt.Errorf("error setting up OpenID Connect provider: %s", err)
131 resp, err := logout(ctx, ctrl.Cluster, opts)
133 return arvados.LogoutResponse{}, err
135 creds, credsOK := auth.FromContext(ctx)
136 if ctrl.endSessionURL != nil && credsOK && len(creds.Tokens) > 0 {
137 values := ctrl.endSessionURL.Query()
138 values.Set("client_id", ctrl.ClientID)
139 values.Set("post_logout_redirect_uri", resp.RedirectLocation)
140 u := *ctrl.endSessionURL
141 u.RawQuery = values.Encode()
142 resp.RedirectLocation = u.String()
147 func (ctrl *oidcLoginController) Login(ctx context.Context, opts arvados.LoginOptions) (arvados.LoginResponse, error) {
150 return loginError(fmt.Errorf("error setting up OpenID Connect provider: %s", err))
152 if opts.State == "" {
153 // Initiate OIDC sign-in.
154 if opts.ReturnTo == "" {
155 return loginError(errors.New("missing return_to parameter"))
157 if err := validateLoginRedirectTarget(ctrl.Parent.cluster, opts.ReturnTo); err != nil {
158 return loginError(fmt.Errorf("invalid return_to parameter: %s", err))
160 state := ctrl.newOAuth2State([]byte(ctrl.Cluster.SystemRootToken), opts.Remote, opts.ReturnTo)
161 var authparams []oauth2.AuthCodeOption
162 for k, v := range ctrl.AuthParams {
163 authparams = append(authparams, oauth2.SetAuthURLParam(k, v))
165 return arvados.LoginResponse{
166 RedirectLocation: ctrl.oauth2conf.AuthCodeURL(state.String(), authparams...),
169 // Callback after OIDC sign-in.
170 state := ctrl.parseOAuth2State(opts.State)
171 if !state.verify([]byte(ctrl.Cluster.SystemRootToken)) {
172 return loginError(errors.New("invalid OAuth2 state"))
174 oauth2Token, err := ctrl.oauth2conf.Exchange(ctx, opts.Code)
176 return loginError(fmt.Errorf("error in OAuth2 exchange: %s", err))
178 ctxlog.FromContext(ctx).WithField("oauth2Token", oauth2Token).Debug("oauth2 exchange succeeded")
179 rawIDToken, ok := oauth2Token.Extra("id_token").(string)
181 return loginError(errors.New("error in OAuth2 exchange: no ID token in OAuth2 token"))
183 ctxlog.FromContext(ctx).WithField("rawIDToken", rawIDToken).Debug("oauth2Token provided ID token")
184 idToken, err := ctrl.verifier.Verify(ctx, rawIDToken)
186 return loginError(fmt.Errorf("error verifying ID token: %s", err))
188 authinfo, err := ctrl.getAuthInfo(ctx, oauth2Token, idToken)
190 return loginError(err)
192 ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{ctrl.Cluster.SystemRootToken}})
193 resp, err := ctrl.Parent.UserSessionCreate(ctxRoot, rpc.UserSessionCreateOptions{
194 ReturnTo: state.Remote + ",https://controller.api.client.invalid",
200 // Extract token from rails' UserSessionCreate response, and
201 // attach it to our caller's desired ReturnTo URL. The Rails
202 // handler explicitly disallows sending the real ReturnTo as a
203 // belt-and-suspenders defence against Rails accidentally
204 // exposing an additional login relay.
205 u, err := url.Parse(resp.RedirectLocation)
209 token := u.Query().Get("api_token")
211 resp.RedirectLocation = state.ReturnTo
213 u, err := url.Parse(state.ReturnTo)
221 q.Set("api_token", token)
222 u.RawQuery = q.Encode()
223 resp.RedirectLocation = u.String()
228 func (ctrl *oidcLoginController) UserAuthenticate(ctx context.Context, opts arvados.UserAuthenticateOptions) (arvados.APIClientAuthorization, error) {
229 return arvados.APIClientAuthorization{}, httpserver.ErrorWithStatus(errors.New("username/password authentication is not available"), http.StatusBadRequest)
232 // claimser can decode arbitrary claims into a map. Implemented by
233 // *oauth2.IDToken and *oauth2.UserInfo.
234 type claimser interface {
235 Claims(interface{}) error
238 // Use a person's token to get all of their email addresses, with the
239 // primary address at index 0. The provided defaultAddr is always
240 // included in the returned slice, and is used as the primary if the
241 // Google API does not indicate one.
242 func (ctrl *oidcLoginController) getAuthInfo(ctx context.Context, token *oauth2.Token, claimser claimser) (*rpc.UserSessionAuthInfo, error) {
243 var ret rpc.UserSessionAuthInfo
244 defer ctxlog.FromContext(ctx).WithField("ret", &ret).Debug("getAuthInfo returned")
246 var claims map[string]interface{}
247 if err := claimser.Claims(&claims); err != nil {
248 return nil, fmt.Errorf("error extracting claims from token: %s", err)
249 } else if verified, _ := claims[ctrl.EmailVerifiedClaim].(bool); verified || ctrl.EmailVerifiedClaim == "" {
250 // Fall back to this info if the People API call
251 // (below) doesn't return a primary && verified email.
252 givenName, _ := claims["given_name"].(string)
253 familyName, _ := claims["family_name"].(string)
254 if givenName != "" && familyName != "" {
255 ret.FirstName = givenName
256 ret.LastName = familyName
258 name, _ := claims["name"].(string)
259 if names := strings.Fields(strings.TrimSpace(name)); len(names) > 1 {
260 ret.FirstName = strings.Join(names[0:len(names)-1], " ")
261 ret.LastName = names[len(names)-1]
262 } else if len(names) > 0 {
263 ret.FirstName = names[0]
266 ret.Email, _ = claims[ctrl.EmailClaim].(string)
269 if ctrl.UsernameClaim != "" {
270 ret.Username, _ = claims[ctrl.UsernameClaim].(string)
273 if !ctrl.UseGooglePeopleAPI {
275 return nil, fmt.Errorf("cannot log in with unverified email address %q", claims[ctrl.EmailClaim])
280 svc, err := people.NewService(ctx, option.WithTokenSource(ctrl.oauth2conf.TokenSource(ctx, token)), option.WithScopes(people.UserEmailsReadScope))
282 return nil, fmt.Errorf("error setting up People API: %s", err)
284 if p := ctrl.peopleAPIBasePath; p != "" {
285 // Override normal API endpoint (for testing)
288 person, err := people.NewPeopleService(svc).Get("people/me").PersonFields("emailAddresses,names").Do()
290 if strings.Contains(err.Error(), "Error 403") && strings.Contains(err.Error(), "accessNotConfigured") {
291 // Log the original API error, but display
292 // only the "fix config" advice to the user.
293 ctxlog.FromContext(ctx).WithError(err).WithField("email", ret.Email).Error("People API is not enabled")
294 return nil, errors.New("configuration error: Login.GoogleAlternateEmailAddresses is true, but Google People API is not enabled")
296 return nil, fmt.Errorf("error getting profile info from People API: %s", err)
299 // The given/family names returned by the People API and
300 // flagged as "primary" (if any) take precedence over the
301 // split-by-whitespace result from above.
302 for _, name := range person.Names {
303 if name.Metadata != nil && name.Metadata.Primary {
304 ret.FirstName = name.GivenName
305 ret.LastName = name.FamilyName
310 altEmails := map[string]bool{}
312 altEmails[ret.Email] = true
314 for _, ea := range person.EmailAddresses {
315 if ea.Metadata == nil || !ea.Metadata.Verified {
316 ctxlog.FromContext(ctx).WithField("address", ea.Value).Info("skipping unverified email address")
319 altEmails[ea.Value] = true
320 if ea.Metadata.Primary || ret.Email == "" {
324 if len(altEmails) == 0 {
325 return nil, errors.New("cannot log in without a verified email address")
327 for ae := range altEmails {
331 ret.AlternateEmails = append(ret.AlternateEmails, ae)
332 if ret.Username == "" {
333 i := strings.Index(ae, "@")
334 if i > 0 && strings.ToLower(ae[i+1:]) == strings.ToLower(ctrl.Cluster.Users.PreferDomainForUsername) {
335 ret.Username = strings.SplitN(ae[:i], "+", 2)[0]
342 func loginError(sendError error) (resp arvados.LoginResponse, err error) {
343 tmpl, err := template.New("error").Parse(`<h2>Login error:</h2><p>{{.}}</p>`)
347 err = tmpl.Execute(&resp.HTML, sendError.Error())
351 func (ctrl *oidcLoginController) newOAuth2State(key []byte, remote, returnTo string) oauth2State {
353 Time: time.Now().Unix(),
357 s.HMAC = s.computeHMAC(key)
361 type oauth2State struct {
362 HMAC []byte // hash of other fields; see computeHMAC()
363 Time int64 // creation time (unix timestamp)
364 Remote string // remote cluster if requesting a salted token, otherwise blank
365 ReturnTo string // redirect target
368 func (ctrl *oidcLoginController) parseOAuth2State(encoded string) (s oauth2State) {
369 // Errors are not checked. If decoding/parsing fails, the
370 // token will be rejected by verify().
371 decoded, _ := base64.RawURLEncoding.DecodeString(encoded)
372 f := strings.Split(string(decoded), "\n")
376 fmt.Sscanf(f[0], "%x", &s.HMAC)
377 fmt.Sscanf(f[1], "%x", &s.Time)
378 fmt.Sscanf(f[2], "%s", &s.Remote)
379 fmt.Sscanf(f[3], "%s", &s.ReturnTo)
383 func (s oauth2State) verify(key []byte) bool {
384 if delta := time.Now().Unix() - s.Time; delta < 0 || delta > 300 {
387 return hmac.Equal(s.computeHMAC(key), s.HMAC)
390 func (s oauth2State) String() string {
392 enc := base64.NewEncoder(base64.RawURLEncoding, &buf)
393 fmt.Fprintf(enc, "%x\n%x\n%s\n%s", s.HMAC, s.Time, s.Remote, s.ReturnTo)
398 func (s oauth2State) computeHMAC(key []byte) []byte {
399 mac := hmac.New(sha256.New, key)
400 fmt.Fprintf(mac, "%x %s %s", s.Time, s.Remote, s.ReturnTo)
404 func OIDCAccessTokenAuthorizer(cluster *arvados.Cluster, getdb func(context.Context) (*sqlx.DB, error)) *oidcTokenAuthorizer {
405 // We want ctrl to be nil if the chosen controller is not a
406 // *oidcLoginController, so we can ignore the 2nd return value
407 // of this type cast.
408 ctrl, _ := NewConn(context.Background(), cluster, getdb).loginController.(*oidcLoginController)
409 cache, err := lru.New2Q(tokenCacheSize)
413 return &oidcTokenAuthorizer{
420 type oidcTokenAuthorizer struct {
421 ctrl *oidcLoginController
422 getdb func(context.Context) (*sqlx.DB, error)
423 cache *lru.TwoQueueCache
426 func (ta *oidcTokenAuthorizer) Middleware(w http.ResponseWriter, r *http.Request, next http.Handler) {
428 // Not using a compatible (OIDC) login controller.
429 } else if authhdr := strings.Split(r.Header.Get("Authorization"), " "); len(authhdr) > 1 && (authhdr[0] == "OAuth2" || authhdr[0] == "Bearer") {
430 err := ta.registerToken(r.Context(), authhdr[1])
432 http.Error(w, err.Error(), http.StatusInternalServerError)
439 func (ta *oidcTokenAuthorizer) WrapCalls(origFunc api.RoutableFunc) api.RoutableFunc {
441 // Not using a compatible (OIDC) login controller.
444 return func(ctx context.Context, opts interface{}) (_ interface{}, err error) {
445 creds, ok := auth.FromContext(ctx)
447 return origFunc(ctx, opts)
449 // Check each token in the incoming request. If any
450 // are valid OAuth2 access tokens, insert/update them
451 // in the database so RailsAPI's auth code accepts
453 for _, tok := range creds.Tokens {
454 err = ta.registerToken(ctx, tok)
459 return origFunc(ctx, opts)
463 // Matches error from oidc UserInfo() when receiving HTTP status 5xx
464 var re5xxError = regexp.MustCompile(`^5\d\d `)
466 // registerToken checks whether tok is a valid OIDC Access Token and,
467 // if so, ensures that an api_client_authorizations row exists so that
468 // RailsAPI will accept it as an Arvados token.
469 func (ta *oidcTokenAuthorizer) registerToken(ctx context.Context, tok string) error {
470 if tok == ta.ctrl.Cluster.SystemRootToken || strings.HasPrefix(tok, "v2/") {
473 if cached, hit := ta.cache.Get(tok); !hit {
474 // Fall through to database and OIDC provider checks
476 } else if exp, ok := cached.(time.Time); ok {
477 // cached negative result (value is expiry time)
478 if time.Now().Before(exp) {
483 // cached positive result
484 aca := cached.(arvados.APIClientAuthorization)
486 if !aca.ExpiresAt.IsZero() {
488 expiring = t.Before(time.Now().Add(time.Minute))
495 db, err := ta.getdb(ctx)
499 tx, err := db.Beginx()
504 ctx = ctrlctx.NewWithTransaction(ctx, tx)
506 // We use hmac-sha256(accesstoken,systemroottoken) as the
507 // secret part of our own token, and avoid storing the auth
508 // provider's real secret in our database.
509 mac := hmac.New(sha256.New, []byte(ta.ctrl.Cluster.SystemRootToken))
510 io.WriteString(mac, tok)
511 hmac := fmt.Sprintf("%x", mac.Sum(nil))
514 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)
515 if err != nil && err != sql.ErrNoRows {
516 return fmt.Errorf("database error while checking token: %w", err)
517 } else if err == nil && !expiring {
518 // Token is already in the database as an Arvados
519 // token, and isn't about to expire, so we can pass it
520 // through to RailsAPI etc. regardless of whether it's
521 // an OIDC access token.
524 updating := err == nil
526 // Check whether the token is a valid OIDC access token. If
527 // so, swap it out for an Arvados token (creating/updating an
528 // api_client_authorizations row if needed) which downstream
529 // server components will accept.
530 err = ta.ctrl.setup()
532 return fmt.Errorf("error setting up OpenID Connect provider: %s", err)
534 if ok, err := ta.checkAccessTokenScope(ctx, tok); err != nil || !ok {
535 // Note checkAccessTokenScope logs any interesting errors
536 ta.cache.Add(tok, time.Now().Add(tokenCacheNegativeTTL))
539 oauth2Token := &oauth2.Token{
542 userinfo, err := ta.ctrl.provider.UserInfo(ctx, oauth2.StaticTokenSource(oauth2Token))
544 if neterr := net.Error(nil); errors.As(err, &neterr) || re5xxError.MatchString(err.Error()) {
545 // If this token is in fact a valid OIDC
546 // token, but we failed to validate it here
547 // because of a network problem or internal
548 // server error, we error out now with a 5xx
549 // error, indicating to the client that they
550 // can try again. If we didn't error out now,
551 // the unrecognized token would eventually
552 // cause a 401 error further down the stack,
553 // which the caller would interpret as an
554 // unrecoverable failure.
555 ctxlog.FromContext(ctx).WithError(err).Debugf("treating OIDC UserInfo lookup error type %T as transient; failing request instead of forwarding token blindly", err)
558 ctxlog.FromContext(ctx).WithError(err).WithField("HMAC", hmac).Debug("UserInfo failed (not an OIDC token?), caching negative result")
559 ta.cache.Add(tok, time.Now().Add(tokenCacheNegativeTTL))
562 ctxlog.FromContext(ctx).WithField("userinfo", userinfo).Debug("(*oidcTokenAuthorizer)registerToken: got userinfo")
563 authinfo, err := ta.ctrl.getAuthInfo(ctx, oauth2Token, userinfo)
568 // Expiry time for our token is one minute longer than our
569 // cache TTL, so we don't pass it through to RailsAPI just as
571 exp := time.Now().UTC().Add(tokenCacheTTL + tokenCacheRaceWindow)
574 _, err = tx.ExecContext(ctx, `update api_client_authorizations set expires_at=$1 where api_token=$2`, exp, hmac)
576 return fmt.Errorf("error updating token expiry time: %w", err)
578 ctxlog.FromContext(ctx).WithField("HMAC", hmac).Debug("(*oidcTokenAuthorizer)registerToken: updated api_client_authorizations row")
580 aca, err := ta.ctrl.Parent.CreateAPIClientAuthorization(ctx, ta.ctrl.Cluster.SystemRootToken, *authinfo)
584 _, err = tx.ExecContext(ctx, `savepoint upd`)
588 _, err = tx.ExecContext(ctx, `update api_client_authorizations set api_token=$1, expires_at=$2 where uuid=$3`, hmac, exp, aca.UUID)
589 if e, ok := err.(*pq.Error); ok && e.Code == pqCodeUniqueViolation {
590 // unique_violation, given that the above
591 // query did not find a row with matching
592 // api_token, means another thread/process
593 // also received this same token and won the
594 // race to insert it -- in which case this
595 // thread doesn't need to update the database.
596 // Discard the redundant row.
597 _, err = tx.ExecContext(ctx, `rollback to savepoint upd`)
601 _, err = tx.ExecContext(ctx, `delete from api_client_authorizations where uuid=$1`, aca.UUID)
605 ctxlog.FromContext(ctx).WithField("HMAC", hmac).Debug("(*oidcTokenAuthorizer)registerToken: api_client_authorizations row inserted by another thread")
606 } else if err != nil {
607 ctxlog.FromContext(ctx).Errorf("%#v", err)
608 return fmt.Errorf("error adding OIDC access token to database: %w", err)
610 ctxlog.FromContext(ctx).WithFields(logrus.Fields{"UUID": aca.UUID, "HMAC": hmac}).Debug("(*oidcTokenAuthorizer)registerToken: inserted api_client_authorizations row")
617 ta.cache.Add(tok, arvados.APIClientAuthorization{ExpiresAt: exp})
621 // Check that the provided access token is a JWT with the required
622 // scope. If it is a valid JWT but missing the required scope, we
623 // return a 403 error, otherwise true (acceptable as an API token) or
624 // false (pass through unmodified).
626 // Return false if configured not to accept access tokens at all.
628 // Note we don't check signature or expiry here. We are relying on the
629 // caller to verify those separately (e.g., by calling the UserInfo
631 func (ta *oidcTokenAuthorizer) checkAccessTokenScope(ctx context.Context, tok string) (bool, error) {
632 if !ta.ctrl.AcceptAccessToken {
634 } else if ta.ctrl.AcceptAccessTokenScope == "" {
638 Scope string `json:"scope"`
640 if t, err := jwt.ParseSigned(tok); err != nil {
641 ctxlog.FromContext(ctx).WithError(err).Debug("error parsing jwt")
643 } else if err = t.UnsafeClaimsWithoutVerification(&claims); err != nil {
644 ctxlog.FromContext(ctx).WithError(err).Debug("error extracting jwt claims")
647 for _, s := range strings.Split(claims.Scope, " ") {
648 if s == ta.ctrl.AcceptAccessTokenScope {
652 ctxlog.FromContext(ctx).WithFields(logrus.Fields{"have": claims.Scope, "need": ta.ctrl.AcceptAccessTokenScope}).Info("unacceptable access token scope")
653 return false, httpserver.ErrorWithStatus(errors.New("unacceptable access token scope"), http.StatusUnauthorized)