X-Git-Url: https://git.arvados.org/arvados.git/blobdiff_plain/8cd08f2ce640e0b1967db489d29e3761ac63f0d7..c89213f5a5e303050caaebe4f8fdf2980fc65605:/lib/controller/localdb/login_oidc.go diff --git a/lib/controller/localdb/login_oidc.go b/lib/controller/localdb/login_oidc.go index b99a1c2aa5..61dc5c816b 100644 --- a/lib/controller/localdb/login_oidc.go +++ b/lib/controller/localdb/login_oidc.go @@ -35,24 +35,29 @@ import ( "golang.org/x/oauth2" "google.golang.org/api/option" "google.golang.org/api/people/v1" + "gopkg.in/square/go-jose.v2/jwt" ) -const ( +var ( tokenCacheSize = 1000 tokenCacheNegativeTTL = time.Minute * 5 tokenCacheTTL = time.Minute * 10 + tokenCacheRaceWindow = time.Minute ) type oidcLoginController struct { - Cluster *arvados.Cluster - Parent *Conn - Issuer string // OIDC issuer URL, e.g., "https://accounts.google.com" - ClientID string - ClientSecret string - UseGooglePeopleAPI bool // Use Google People API to look up alternate email addresses - EmailClaim string // OpenID claim to use as email address; typically "email" - EmailVerifiedClaim string // If non-empty, ensure claim value is true before accepting EmailClaim; typically "email_verified" - UsernameClaim string // If non-empty, use as preferred username + Cluster *arvados.Cluster + Parent *Conn + Issuer string // OIDC issuer URL, e.g., "https://accounts.google.com" + ClientID string + ClientSecret string + UseGooglePeopleAPI bool // Use Google People API to look up alternate email addresses + EmailClaim string // OpenID claim to use as email address; typically "email" + EmailVerifiedClaim string // If non-empty, ensure claim value is true before accepting EmailClaim; typically "email_verified" + UsernameClaim string // If non-empty, use as preferred username + AcceptAccessToken bool // Accept access tokens as API tokens + AcceptAccessTokenScope string // If non-empty, don't accept access tokens as API tokens unless they contain this scope + AuthParams map[string]string // Additional parameters to pass with authentication request // override Google People API base URL for testing purposes // (normally empty, set by google pkg to @@ -96,7 +101,7 @@ func (ctrl *oidcLoginController) setup() error { } func (ctrl *oidcLoginController) Logout(ctx context.Context, opts arvados.LogoutOptions) (arvados.LogoutResponse, error) { - return noopLogout(ctrl.Cluster, opts) + return logout(ctx, ctrl.Cluster, opts) } func (ctrl *oidcLoginController) Login(ctx context.Context, opts arvados.LoginOptions) (arvados.LoginResponse, error) { @@ -110,14 +115,12 @@ func (ctrl *oidcLoginController) Login(ctx context.Context, opts arvados.LoginOp return loginError(errors.New("missing return_to parameter")) } state := ctrl.newOAuth2State([]byte(ctrl.Cluster.SystemRootToken), opts.Remote, opts.ReturnTo) + var authparams []oauth2.AuthCodeOption + for k, v := range ctrl.AuthParams { + authparams = append(authparams, oauth2.SetAuthURLParam(k, v)) + } return arvados.LoginResponse{ - RedirectLocation: ctrl.oauth2conf.AuthCodeURL(state.String(), - // prompt=select_account tells Google - // to show the "choose which Google - // account" page, even if the client - // is currently logged in to exactly - // one Google account. - oauth2.SetAuthURLParam("prompt", "select_account")), + RedirectLocation: ctrl.oauth2conf.AuthCodeURL(state.String(), authparams...), }, nil } // Callback after OIDC sign-in. @@ -129,10 +132,12 @@ func (ctrl *oidcLoginController) Login(ctx context.Context, opts arvados.LoginOp if err != nil { return loginError(fmt.Errorf("error in OAuth2 exchange: %s", err)) } + ctxlog.FromContext(ctx).WithField("oauth2Token", oauth2Token).Debug("oauth2 exchange succeeded") rawIDToken, ok := oauth2Token.Extra("id_token").(string) if !ok { return loginError(errors.New("error in OAuth2 exchange: no ID token in OAuth2 token")) } + ctxlog.FromContext(ctx).WithField("rawIDToken", rawIDToken).Debug("oauth2Token provided ID token") idToken, err := ctrl.verifier.Verify(ctx, rawIDToken) if err != nil { return loginError(fmt.Errorf("error verifying ID token: %s", err)) @@ -176,7 +181,7 @@ func (ctrl *oidcLoginController) getAuthInfo(ctx context.Context, token *oauth2. if names := strings.Fields(strings.TrimSpace(name)); len(names) > 1 { ret.FirstName = strings.Join(names[0:len(names)-1], " ") ret.LastName = names[len(names)-1] - } else { + } else if len(names) > 0 { ret.FirstName = names[0] } ret.Email, _ = claims[ctrl.EmailClaim].(string) @@ -363,8 +368,9 @@ func (ta *oidcTokenAuthorizer) WrapCalls(origFunc api.RoutableFunc) api.Routable return origFunc(ctx, opts) } // Check each token in the incoming request. If any - // are OAuth2 access tokens, swap them out for Arvados - // tokens. + // are valid OAuth2 access tokens, insert/update them + // in the database so RailsAPI's auth code accepts + // them. for _, tok := range creds.Tokens { err = ta.registerToken(ctx, tok) if err != nil { @@ -446,6 +452,10 @@ func (ta *oidcTokenAuthorizer) registerToken(ctx context.Context, tok string) er if err != nil { return fmt.Errorf("error setting up OpenID Connect provider: %s", err) } + if ok, err := ta.checkAccessTokenScope(ctx, tok); err != nil || !ok { + ta.cache.Add(tok, time.Now().Add(tokenCacheNegativeTTL)) + return err + } oauth2Token := &oauth2.Token{ AccessToken: tok, } @@ -463,7 +473,7 @@ func (ta *oidcTokenAuthorizer) registerToken(ctx context.Context, tok string) er // Expiry time for our token is one minute longer than our // cache TTL, so we don't pass it through to RailsAPI just as // it's expiring. - exp := time.Now().UTC().Add(tokenCacheTTL + time.Minute) + exp := time.Now().UTC().Add(tokenCacheTTL + tokenCacheRaceWindow) var aca arvados.APIClientAuthorization if updating { @@ -488,6 +498,42 @@ func (ta *oidcTokenAuthorizer) registerToken(ctx context.Context, tok string) er if err != nil { return err } + aca.ExpiresAt = exp.Format(time.RFC3339Nano) ta.cache.Add(tok, aca) return nil } + +// Check that the provided access token is a JWT with the required +// scope. If it is a valid JWT but missing the required scope, we +// return a 403 error, otherwise true (acceptable as an API token) or +// false (pass through unmodified). +// +// Return false if configured not to accept access tokens at all. +// +// Note we don't check signature or expiry here. We are relying on the +// caller to verify those separately (e.g., by calling the UserInfo +// endpoint). +func (ta *oidcTokenAuthorizer) checkAccessTokenScope(ctx context.Context, tok string) (bool, error) { + if !ta.ctrl.AcceptAccessToken { + return false, nil + } else if ta.ctrl.AcceptAccessTokenScope == "" { + return true, nil + } + var claims struct { + Scope string `json:"scope"` + } + if t, err := jwt.ParseSigned(tok); err != nil { + ctxlog.FromContext(ctx).WithError(err).Debug("error parsing jwt") + return false, nil + } else if err = t.UnsafeClaimsWithoutVerification(&claims); err != nil { + ctxlog.FromContext(ctx).WithError(err).Debug("error extracting jwt claims") + return false, nil + } + for _, s := range strings.Split(claims.Scope, " ") { + if s == ta.ctrl.AcceptAccessTokenScope { + return true, nil + } + } + ctxlog.FromContext(ctx).WithFields(logrus.Fields{"have": claims.Scope, "need": ta.ctrl.AcceptAccessTokenScope}).Infof("unacceptable access token scope") + return false, httpserver.ErrorWithStatus(errors.New("unacceptable access token scope"), http.StatusUnauthorized) +}