1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
24 "git.arvados.org/arvados.git/lib/controller/api"
25 "git.arvados.org/arvados.git/lib/controller/railsproxy"
26 "git.arvados.org/arvados.git/lib/controller/rpc"
27 "git.arvados.org/arvados.git/lib/ctrlctx"
28 "git.arvados.org/arvados.git/sdk/go/arvados"
29 "git.arvados.org/arvados.git/sdk/go/auth"
30 "git.arvados.org/arvados.git/sdk/go/ctxlog"
31 "git.arvados.org/arvados.git/sdk/go/httpserver"
32 "github.com/coreos/go-oidc"
33 lru "github.com/hashicorp/golang-lru"
34 "github.com/jmoiron/sqlx"
35 "github.com/sirupsen/logrus"
37 "google.golang.org/api/option"
38 "google.golang.org/api/people/v1"
43 tokenCacheNegativeTTL = time.Minute * 5
44 tokenCacheTTL = time.Minute * 10
47 type oidcLoginController struct {
48 Cluster *arvados.Cluster
49 RailsProxy *railsProxy
50 Issuer string // OIDC issuer URL, e.g., "https://accounts.google.com"
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
58 // override Google People API base URL for testing purposes
59 // (normally empty, set by google pkg to
60 // https://people.googleapis.com/)
61 peopleAPIBasePath string
63 provider *oidc.Provider // initialized by setup()
64 oauth2conf *oauth2.Config // initialized by setup()
65 verifier *oidc.IDTokenVerifier // initialized by setup()
66 mu sync.Mutex // protects setup()
69 // Initialize ctrl.provider and ctrl.oauth2conf.
70 func (ctrl *oidcLoginController) setup() error {
72 defer ctrl.mu.Unlock()
73 if ctrl.provider != nil {
77 redirURL, err := (*url.URL)(&ctrl.Cluster.Services.Controller.ExternalURL).Parse("/" + arvados.EndpointLogin.Path)
79 return fmt.Errorf("error making redirect URL: %s", err)
81 provider, err := oidc.NewProvider(context.Background(), ctrl.Issuer)
85 ctrl.oauth2conf = &oauth2.Config{
86 ClientID: ctrl.ClientID,
87 ClientSecret: ctrl.ClientSecret,
88 Endpoint: provider.Endpoint(),
89 Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
90 RedirectURL: redirURL.String(),
92 ctrl.verifier = provider.Verifier(&oidc.Config{
93 ClientID: ctrl.ClientID,
95 ctrl.provider = provider
99 func (ctrl *oidcLoginController) Logout(ctx context.Context, opts arvados.LogoutOptions) (arvados.LogoutResponse, error) {
100 return noopLogout(ctrl.Cluster, opts)
103 func (ctrl *oidcLoginController) Login(ctx context.Context, opts arvados.LoginOptions) (arvados.LoginResponse, error) {
106 return loginError(fmt.Errorf("error setting up OpenID Connect provider: %s", err))
108 if opts.State == "" {
109 // Initiate OIDC sign-in.
110 if opts.ReturnTo == "" {
111 return loginError(errors.New("missing return_to parameter"))
113 state := ctrl.newOAuth2State([]byte(ctrl.Cluster.SystemRootToken), opts.Remote, opts.ReturnTo)
114 return arvados.LoginResponse{
115 RedirectLocation: ctrl.oauth2conf.AuthCodeURL(state.String(),
116 // prompt=select_account tells Google
117 // to show the "choose which Google
118 // account" page, even if the client
119 // is currently logged in to exactly
120 // one Google account.
121 oauth2.SetAuthURLParam("prompt", "select_account")),
124 // Callback after OIDC sign-in.
125 state := ctrl.parseOAuth2State(opts.State)
126 if !state.verify([]byte(ctrl.Cluster.SystemRootToken)) {
127 return loginError(errors.New("invalid OAuth2 state"))
129 oauth2Token, err := ctrl.oauth2conf.Exchange(ctx, opts.Code)
131 return loginError(fmt.Errorf("error in OAuth2 exchange: %s", err))
133 rawIDToken, ok := oauth2Token.Extra("id_token").(string)
135 return loginError(errors.New("error in OAuth2 exchange: no ID token in OAuth2 token"))
137 idToken, err := ctrl.verifier.Verify(ctx, rawIDToken)
139 return loginError(fmt.Errorf("error verifying ID token: %s", err))
141 authinfo, err := ctrl.getAuthInfo(ctx, oauth2Token, idToken)
143 return loginError(err)
145 ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{ctrl.Cluster.SystemRootToken}})
146 return ctrl.RailsProxy.UserSessionCreate(ctxRoot, rpc.UserSessionCreateOptions{
147 ReturnTo: state.Remote + "," + state.ReturnTo,
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)
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
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")
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]
181 ret.FirstName = names[0]
183 ret.Email, _ = claims[ctrl.EmailClaim].(string)
186 if ctrl.UsernameClaim != "" {
187 ret.Username, _ = claims[ctrl.UsernameClaim].(string)
190 if !ctrl.UseGooglePeopleAPI {
192 return nil, fmt.Errorf("cannot log in with unverified email address %q", claims[ctrl.EmailClaim])
197 svc, err := people.NewService(ctx, option.WithTokenSource(ctrl.oauth2conf.TokenSource(ctx, token)), option.WithScopes(people.UserEmailsReadScope))
199 return nil, fmt.Errorf("error setting up People API: %s", err)
201 if p := ctrl.peopleAPIBasePath; p != "" {
202 // Override normal API endpoint (for testing)
205 person, err := people.NewPeopleService(svc).Get("people/me").PersonFields("emailAddresses,names").Do()
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")
213 return nil, fmt.Errorf("error getting profile info from People API: %s", err)
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
227 altEmails := map[string]bool{}
229 altEmails[ret.Email] = true
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")
236 altEmails[ea.Value] = true
237 if ea.Metadata.Primary || ret.Email == "" {
241 if len(altEmails) == 0 {
242 return nil, errors.New("cannot log in without a verified email address")
244 for ae := range altEmails {
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]
259 func loginError(sendError error) (resp arvados.LoginResponse, err error) {
260 tmpl, err := template.New("error").Parse(`<h2>Login error:</h2><p>{{.}}</p>`)
264 err = tmpl.Execute(&resp.HTML, sendError.Error())
268 func (ctrl *oidcLoginController) newOAuth2State(key []byte, remote, returnTo string) oauth2State {
270 Time: time.Now().Unix(),
274 s.HMAC = s.computeHMAC(key)
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
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")
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)
300 func (s oauth2State) verify(key []byte) bool {
301 if delta := time.Now().Unix() - s.Time; delta < 0 || delta > 300 {
304 return hmac.Equal(s.computeHMAC(key), s.HMAC)
307 func (s oauth2State) String() string {
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)
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)
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, _ := chooseLoginController(cluster, railsproxy.NewConn(cluster)).(*oidcLoginController)
326 cache, err := lru.New2Q(tokenCacheSize)
330 return &oidcTokenAuthorizer{
337 type oidcTokenAuthorizer struct {
338 ctrl *oidcLoginController
339 getdb func(context.Context) (*sqlx.DB, error)
340 cache *lru.TwoQueueCache
343 func (ta *oidcTokenAuthorizer) Middleware(w http.ResponseWriter, r *http.Request, next http.Handler) {
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])
349 http.Error(w, err.Error(), http.StatusInternalServerError)
356 func (ta *oidcTokenAuthorizer) WrapCalls(origFunc api.RoutableFunc) api.RoutableFunc {
358 // Not using a compatible (OIDC) login controller.
361 return func(ctx context.Context, opts interface{}) (_ interface{}, err error) {
362 creds, ok := auth.FromContext(ctx)
364 return origFunc(ctx, opts)
366 // Check each token in the incoming request. If any
367 // are OAuth2 access tokens, swap them out for Arvados
369 for _, tok := range creds.Tokens {
370 err = ta.registerToken(ctx, tok)
375 return origFunc(ctx, opts)
379 // registerToken checks whether tok is a valid OIDC Access Token and,
380 // if so, ensures that an api_client_authorizations row exists so that
381 // RailsAPI will accept it as an Arvados token.
382 func (ta *oidcTokenAuthorizer) registerToken(ctx context.Context, tok string) error {
383 if strings.HasPrefix(tok, "v2/") {
386 if cached, hit := ta.cache.Get(tok); !hit {
387 // Fall through to database and OIDC provider checks
389 } else if exp, ok := cached.(time.Time); ok {
390 // cached negative result (value is expiry time)
391 if time.Now().Before(exp) {
397 // cached positive result
398 aca := cached.(arvados.APIClientAuthorization)
400 if aca.ExpiresAt != "" {
401 t, err := time.Parse(time.RFC3339Nano, aca.ExpiresAt)
403 return fmt.Errorf("error parsing expires_at value: %w", err)
405 expiring = t.Before(time.Now().Add(time.Minute))
412 db, err := ta.getdb(ctx)
416 tx, err := db.Beginx()
421 ctx = ctrlctx.NewWithTransaction(ctx, tx)
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))
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.
441 updating := err == nil
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()
449 return fmt.Errorf("error setting up OpenID Connect provider: %s", err)
451 oauth2Token := &oauth2.Token{
454 userinfo, err := ta.ctrl.provider.UserInfo(ctx, oauth2.StaticTokenSource(oauth2Token))
456 ta.cache.Add(tok, time.Now().Add(tokenCacheNegativeTTL))
459 ctxlog.FromContext(ctx).WithField("userinfo", userinfo).Debug("(*oidcTokenAuthorizer)registerToken: got userinfo")
460 authinfo, err := ta.ctrl.getAuthInfo(ctx, oauth2Token, userinfo)
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
468 exp := time.Now().UTC().Add(tokenCacheTTL + time.Minute)
470 var aca arvados.APIClientAuthorization
472 _, err = tx.ExecContext(ctx, `update api_client_authorizations set expires_at=$1 where api_token=$2`, exp, hmac)
474 return fmt.Errorf("error updating token expiry time: %w", err)
476 ctxlog.FromContext(ctx).WithField("HMAC", hmac).Debug("(*oidcTokenAuthorizer)registerToken: updated api_client_authorizations row")
478 aca, err = createAPIClientAuthorization(ctx, ta.ctrl.RailsProxy, ta.ctrl.Cluster.SystemRootToken, *authinfo)
482 _, err = tx.ExecContext(ctx, `update api_client_authorizations set api_token=$1, expires_at=$2 where uuid=$3`, hmac, exp, aca.UUID)
484 return fmt.Errorf("error adding OIDC access token to database: %w", err)
487 ctxlog.FromContext(ctx).WithFields(logrus.Fields{"UUID": aca.UUID, "HMAC": hmac}).Debug("(*oidcTokenAuthorizer)registerToken: inserted api_client_authorizations row")
493 ta.cache.Add(tok, aca)