1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
24 "git.arvados.org/arvados.git/lib/config"
25 "git.arvados.org/arvados.git/lib/controller/rpc"
26 "git.arvados.org/arvados.git/sdk/go/arvados"
27 "git.arvados.org/arvados.git/sdk/go/arvadostest"
28 "git.arvados.org/arvados.git/sdk/go/auth"
29 "git.arvados.org/arvados.git/sdk/go/ctxlog"
30 "github.com/jmoiron/sqlx"
31 check "gopkg.in/check.v1"
34 // Gocheck boilerplate
35 func Test(t *testing.T) {
39 var _ = check.Suite(&OIDCLoginSuite{})
41 type OIDCLoginSuite struct {
42 cluster *arvados.Cluster
44 railsSpy *arvadostest.Proxy
45 fakeProvider *arvadostest.OIDCProvider
48 func (s *OIDCLoginSuite) TearDownSuite(c *check.C) {
49 // Undo any changes/additions to the user database so they
50 // don't affect subsequent tests.
51 arvadostest.ResetEnv()
52 c.Check(arvados.NewClientFromEnv().RequestAndDecode(nil, "POST", "database/reset", nil, nil), check.IsNil)
55 func (s *OIDCLoginSuite) SetUpTest(c *check.C) {
56 s.fakeProvider = arvadostest.NewOIDCProvider(c)
57 s.fakeProvider.AuthEmail = "active-user@arvados.local"
58 s.fakeProvider.AuthEmailVerified = true
59 s.fakeProvider.AuthName = "Fake User Name"
60 s.fakeProvider.AuthGivenName = "Fake"
61 s.fakeProvider.AuthFamilyName = "User Name"
62 s.fakeProvider.ValidCode = fmt.Sprintf("abcdefgh-%d", time.Now().Unix())
63 s.fakeProvider.PeopleAPIResponse = map[string]interface{}{}
65 cfg, err := config.NewLoader(nil, ctxlog.TestLogger(c)).Load()
66 c.Assert(err, check.IsNil)
67 s.cluster, err = cfg.GetCluster("")
68 c.Assert(err, check.IsNil)
69 s.cluster.Login.Test.Enable = false
70 s.cluster.Login.Google.Enable = true
71 s.cluster.Login.Google.ClientID = "test%client$id"
72 s.cluster.Login.Google.ClientSecret = "test#client/secret"
73 s.cluster.Users.PreferDomainForUsername = "PreferDomainForUsername.example.com"
74 s.fakeProvider.ValidClientID = "test%client$id"
75 s.fakeProvider.ValidClientSecret = "test#client/secret"
77 s.localdb = NewConn(s.cluster)
78 c.Assert(s.localdb.loginController, check.FitsTypeOf, (*oidcLoginController)(nil))
79 s.localdb.loginController.(*oidcLoginController).Issuer = s.fakeProvider.Issuer.URL
80 s.localdb.loginController.(*oidcLoginController).peopleAPIBasePath = s.fakeProvider.PeopleAPI.URL
82 s.railsSpy = arvadostest.NewProxy(c, s.cluster.Services.RailsAPI)
83 *s.localdb.railsProxy = *rpc.NewConn(s.cluster.ClusterID, s.railsSpy.URL, true, rpc.PassthroughTokenProvider)
86 func (s *OIDCLoginSuite) TearDownTest(c *check.C) {
90 func (s *OIDCLoginSuite) TestGoogleLogout(c *check.C) {
91 resp, err := s.localdb.Logout(context.Background(), arvados.LogoutOptions{ReturnTo: "https://foo.example.com/bar"})
92 c.Check(err, check.IsNil)
93 c.Check(resp.RedirectLocation, check.Equals, "https://foo.example.com/bar")
96 func (s *OIDCLoginSuite) TestGoogleLogin_Start_Bogus(c *check.C) {
97 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{})
98 c.Check(err, check.IsNil)
99 c.Check(resp.RedirectLocation, check.Equals, "")
100 c.Check(resp.HTML.String(), check.Matches, `.*missing return_to parameter.*`)
103 func (s *OIDCLoginSuite) TestGoogleLogin_Start(c *check.C) {
104 for _, remote := range []string{"", "zzzzz"} {
105 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{Remote: remote, ReturnTo: "https://app.example.com/foo?bar"})
106 c.Check(err, check.IsNil)
107 target, err := url.Parse(resp.RedirectLocation)
108 c.Check(err, check.IsNil)
109 issuerURL, _ := url.Parse(s.fakeProvider.Issuer.URL)
110 c.Check(target.Host, check.Equals, issuerURL.Host)
112 c.Check(q.Get("client_id"), check.Equals, "test%client$id")
113 state := s.localdb.loginController.(*oidcLoginController).parseOAuth2State(q.Get("state"))
114 c.Check(state.verify([]byte(s.cluster.SystemRootToken)), check.Equals, true)
115 c.Check(state.Time, check.Not(check.Equals), 0)
116 c.Check(state.Remote, check.Equals, remote)
117 c.Check(state.ReturnTo, check.Equals, "https://app.example.com/foo?bar")
121 func (s *OIDCLoginSuite) TestGoogleLogin_InvalidCode(c *check.C) {
122 state := s.startLogin(c)
123 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
124 Code: "first-try-a-bogus-code",
127 c.Check(err, check.IsNil)
128 c.Check(resp.RedirectLocation, check.Equals, "")
129 c.Check(resp.HTML.String(), check.Matches, `(?ms).*error in OAuth2 exchange.*cannot fetch token.*`)
132 func (s *OIDCLoginSuite) TestGoogleLogin_InvalidState(c *check.C) {
134 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
135 Code: s.fakeProvider.ValidCode,
136 State: "bogus-state",
138 c.Check(err, check.IsNil)
139 c.Check(resp.RedirectLocation, check.Equals, "")
140 c.Check(resp.HTML.String(), check.Matches, `(?ms).*invalid OAuth2 state.*`)
143 func (s *OIDCLoginSuite) setupPeopleAPIError(c *check.C) {
144 s.fakeProvider.PeopleAPI = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
145 w.WriteHeader(http.StatusForbidden)
146 fmt.Fprintln(w, `Error 403: accessNotConfigured`)
148 s.localdb.loginController.(*oidcLoginController).peopleAPIBasePath = s.fakeProvider.PeopleAPI.URL
151 func (s *OIDCLoginSuite) TestGoogleLogin_PeopleAPIDisabled(c *check.C) {
152 s.localdb.loginController.(*oidcLoginController).UseGooglePeopleAPI = false
153 s.fakeProvider.AuthEmail = "joe.smith@primary.example.com"
154 s.setupPeopleAPIError(c)
155 state := s.startLogin(c)
156 _, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
157 Code: s.fakeProvider.ValidCode,
160 c.Check(err, check.IsNil)
161 authinfo := getCallbackAuthInfo(c, s.railsSpy)
162 c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
165 func (s *OIDCLoginSuite) TestConfig(c *check.C) {
166 s.cluster.Login.Google.Enable = false
167 s.cluster.Login.OpenIDConnect.Enable = true
168 s.cluster.Login.OpenIDConnect.Issuer = "https://accounts.example.com/"
169 s.cluster.Login.OpenIDConnect.ClientID = "oidc-client-id"
170 s.cluster.Login.OpenIDConnect.ClientSecret = "oidc-client-secret"
171 s.cluster.Login.OpenIDConnect.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"}
172 localdb := NewConn(s.cluster)
173 ctrl := localdb.loginController.(*oidcLoginController)
174 c.Check(ctrl.Issuer, check.Equals, "https://accounts.example.com/")
175 c.Check(ctrl.ClientID, check.Equals, "oidc-client-id")
176 c.Check(ctrl.ClientSecret, check.Equals, "oidc-client-secret")
177 c.Check(ctrl.UseGooglePeopleAPI, check.Equals, false)
178 c.Check(ctrl.AuthParams["testkey"], check.Equals, "testvalue")
180 for _, enableAltEmails := range []bool{false, true} {
181 s.cluster.Login.OpenIDConnect.Enable = false
182 s.cluster.Login.Google.Enable = true
183 s.cluster.Login.Google.ClientID = "google-client-id"
184 s.cluster.Login.Google.ClientSecret = "google-client-secret"
185 s.cluster.Login.Google.AlternateEmailAddresses = enableAltEmails
186 s.cluster.Login.Google.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"}
187 localdb = NewConn(s.cluster)
188 ctrl = localdb.loginController.(*oidcLoginController)
189 c.Check(ctrl.Issuer, check.Equals, "https://accounts.google.com")
190 c.Check(ctrl.ClientID, check.Equals, "google-client-id")
191 c.Check(ctrl.ClientSecret, check.Equals, "google-client-secret")
192 c.Check(ctrl.UseGooglePeopleAPI, check.Equals, enableAltEmails)
193 c.Check(ctrl.AuthParams["testkey"], check.Equals, "testvalue")
197 func (s *OIDCLoginSuite) TestGoogleLogin_PeopleAPIError(c *check.C) {
198 s.setupPeopleAPIError(c)
199 state := s.startLogin(c)
200 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
201 Code: s.fakeProvider.ValidCode,
204 c.Check(err, check.IsNil)
205 c.Check(resp.RedirectLocation, check.Equals, "")
208 func (s *OIDCLoginSuite) TestOIDCAuthorizer(c *check.C) {
209 s.cluster.Login.Google.Enable = false
210 s.cluster.Login.OpenIDConnect.Enable = true
211 json.Unmarshal([]byte(fmt.Sprintf("%q", s.fakeProvider.Issuer.URL)), &s.cluster.Login.OpenIDConnect.Issuer)
212 s.cluster.Login.OpenIDConnect.ClientID = "oidc#client#id"
213 s.cluster.Login.OpenIDConnect.ClientSecret = "oidc#client#secret"
214 s.cluster.Login.OpenIDConnect.AcceptAccessToken = true
215 s.cluster.Login.OpenIDConnect.AcceptAccessTokenScope = ""
216 s.fakeProvider.ValidClientID = "oidc#client#id"
217 s.fakeProvider.ValidClientSecret = "oidc#client#secret"
218 db := arvadostest.DB(c, s.cluster)
220 tokenCacheTTL = time.Millisecond
221 tokenCacheRaceWindow = time.Millisecond
222 tokenCacheNegativeTTL = time.Millisecond
224 oidcAuthorizer := OIDCAccessTokenAuthorizer(s.cluster, func(context.Context) (*sqlx.DB, error) { return db, nil })
225 accessToken := s.fakeProvider.ValidAccessToken()
227 mac := hmac.New(sha256.New, []byte(s.cluster.SystemRootToken))
228 io.WriteString(mac, accessToken)
229 apiToken := fmt.Sprintf("%x", mac.Sum(nil))
232 _, err := db.Exec(`delete from api_client_authorizations where api_token=$1`, apiToken)
233 c.Check(err, check.IsNil)
238 ctx := auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{accessToken}})
242 s.fakeProvider.HoldUserInfo = make(chan *http.Request)
243 s.fakeProvider.ReleaseUserInfo = make(chan struct{})
247 close(s.fakeProvider.ReleaseUserInfo)
249 <-s.fakeProvider.HoldUserInfo
252 var wg sync.WaitGroup
253 for i := 0; i < concurrent; i++ {
258 _, err := oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) {
259 c.Logf("concurrent req %d/%d", i, concurrent)
262 creds, ok := auth.FromContext(ctx)
263 c.Assert(ok, check.Equals, true)
264 c.Assert(creds.Tokens, check.HasLen, 1)
265 c.Check(creds.Tokens[0], check.Equals, accessToken)
267 err := db.QueryRowContext(ctx, `select expires_at at time zone 'UTC' from api_client_authorizations where api_token=$1`, apiToken).Scan(&exp)
268 c.Check(err, check.IsNil)
269 c.Check(exp.Sub(time.Now()) > -time.Second, check.Equals, true)
270 c.Check(exp.Sub(time.Now()) < time.Second, check.Equals, true)
276 c.Check(err, check.IsNil)
284 // If the token is used again after the in-memory cache
285 // expires, oidcAuthorizer must re-check the token and update
286 // the expires_at value in the database.
287 time.Sleep(3 * time.Millisecond)
288 oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) {
290 err := db.QueryRowContext(ctx, `select expires_at at time zone 'UTC' from api_client_authorizations where api_token=$1`, apiToken).Scan(&exp)
291 c.Check(err, check.IsNil)
292 c.Check(exp.Sub(exp1) > 0, check.Equals, true, check.Commentf("expect %v > 0", exp.Sub(exp1)))
293 c.Check(exp.Sub(exp1) < time.Second, check.Equals, true, check.Commentf("expect %v < 1s", exp.Sub(exp1)))
297 s.fakeProvider.AccessTokenPayload = map[string]interface{}{"scope": "openid profile foobar"}
298 accessToken = s.fakeProvider.ValidAccessToken()
299 ctx = auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{accessToken}})
301 mac = hmac.New(sha256.New, []byte(s.cluster.SystemRootToken))
302 io.WriteString(mac, accessToken)
303 apiToken = fmt.Sprintf("%x", mac.Sum(nil))
305 for _, trial := range []struct {
311 {true, "foobar", true, true},
312 {true, "foo", false, false},
313 {true, "", true, true},
314 {false, "", false, true},
315 {false, "foobar", false, true},
317 c.Logf("trial = %+v", trial)
319 s.cluster.Login.OpenIDConnect.AcceptAccessToken = trial.configEnable
320 s.cluster.Login.OpenIDConnect.AcceptAccessTokenScope = trial.configScope
321 oidcAuthorizer = OIDCAccessTokenAuthorizer(s.cluster, func(context.Context) (*sqlx.DB, error) { return db, nil })
323 oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) {
325 err := db.QueryRowContext(ctx, `select count(*) from api_client_authorizations where api_token=$1`, apiToken).Scan(&n)
326 c.Check(err, check.IsNil)
327 if trial.acceptable {
328 c.Check(n, check.Equals, 1)
330 c.Check(n, check.Equals, 0)
335 c.Check(checked, check.Equals, trial.shouldRun)
339 func (s *OIDCLoginSuite) TestGenericOIDCLogin(c *check.C) {
340 s.cluster.Login.Google.Enable = false
341 s.cluster.Login.OpenIDConnect.Enable = true
342 json.Unmarshal([]byte(fmt.Sprintf("%q", s.fakeProvider.Issuer.URL)), &s.cluster.Login.OpenIDConnect.Issuer)
343 s.cluster.Login.OpenIDConnect.ClientID = "oidc#client#id"
344 s.cluster.Login.OpenIDConnect.ClientSecret = "oidc#client#secret"
345 s.cluster.Login.OpenIDConnect.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"}
346 s.fakeProvider.ValidClientID = "oidc#client#id"
347 s.fakeProvider.ValidClientSecret = "oidc#client#secret"
348 for _, trial := range []struct {
349 expectEmail string // "" if failure expected
353 expectEmail: "user@oidc.example.com",
355 c.Log("=== succeed because email_verified is false but not required")
356 s.fakeProvider.AuthEmail = "user@oidc.example.com"
357 s.fakeProvider.AuthEmailVerified = false
358 s.cluster.Login.OpenIDConnect.EmailClaim = "email"
359 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = ""
360 s.cluster.Login.OpenIDConnect.UsernameClaim = ""
366 c.Log("=== fail because email_verified is false and required")
367 s.fakeProvider.AuthEmail = "user@oidc.example.com"
368 s.fakeProvider.AuthEmailVerified = false
369 s.cluster.Login.OpenIDConnect.EmailClaim = "email"
370 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = "email_verified"
371 s.cluster.Login.OpenIDConnect.UsernameClaim = ""
375 expectEmail: "user@oidc.example.com",
377 c.Log("=== succeed because email_verified is false but config uses custom 'verified' claim")
378 s.fakeProvider.AuthEmail = "user@oidc.example.com"
379 s.fakeProvider.AuthEmailVerified = false
380 s.cluster.Login.OpenIDConnect.EmailClaim = "email"
381 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = "alt_verified"
382 s.cluster.Login.OpenIDConnect.UsernameClaim = ""
386 expectEmail: "alt_email@example.com",
388 c.Log("=== succeed with custom 'email' and 'email_verified' claims")
389 s.fakeProvider.AuthEmail = "bad@wrong.example.com"
390 s.fakeProvider.AuthEmailVerified = false
391 s.cluster.Login.OpenIDConnect.EmailClaim = "alt_email"
392 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = "alt_verified"
393 s.cluster.Login.OpenIDConnect.UsernameClaim = "alt_username"
398 if s.railsSpy != nil {
401 s.railsSpy = arvadostest.NewProxy(c, s.cluster.Services.RailsAPI)
402 s.localdb = NewConn(s.cluster)
403 *s.localdb.railsProxy = *rpc.NewConn(s.cluster.ClusterID, s.railsSpy.URL, true, rpc.PassthroughTokenProvider)
405 state := s.startLogin(c, func(form url.Values) {
406 c.Check(form.Get("testkey"), check.Equals, "testvalue")
408 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
409 Code: s.fakeProvider.ValidCode,
412 c.Assert(err, check.IsNil)
413 if trial.expectEmail == "" {
414 c.Check(resp.HTML.String(), check.Matches, `(?ms).*Login error.*`)
415 c.Check(resp.RedirectLocation, check.Equals, "")
418 c.Check(resp.HTML.String(), check.Equals, "")
419 target, err := url.Parse(resp.RedirectLocation)
420 c.Assert(err, check.IsNil)
421 token := target.Query().Get("api_token")
422 c.Check(token, check.Matches, `v2/zzzzz-gj3su-.{15}/.{32,50}`)
423 authinfo := getCallbackAuthInfo(c, s.railsSpy)
424 c.Check(authinfo.Email, check.Equals, trial.expectEmail)
426 switch s.cluster.Login.OpenIDConnect.UsernameClaim {
428 c.Check(authinfo.Username, check.Equals, "desired-username")
430 c.Check(authinfo.Username, check.Equals, "")
432 c.Fail() // bad test case
437 func (s *OIDCLoginSuite) TestGoogleLogin_Success(c *check.C) {
438 s.cluster.Login.Google.AuthenticationRequestParameters["prompt"] = "consent"
439 s.cluster.Login.Google.AuthenticationRequestParameters["foo"] = "bar"
440 state := s.startLogin(c, func(form url.Values) {
441 c.Check(form.Get("foo"), check.Equals, "bar")
442 c.Check(form.Get("prompt"), check.Equals, "consent")
444 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
445 Code: s.fakeProvider.ValidCode,
448 c.Check(err, check.IsNil)
449 c.Check(resp.HTML.String(), check.Equals, "")
450 target, err := url.Parse(resp.RedirectLocation)
451 c.Check(err, check.IsNil)
452 c.Check(target.Host, check.Equals, "app.example.com")
453 c.Check(target.Path, check.Equals, "/foo")
454 token := target.Query().Get("api_token")
455 c.Check(token, check.Matches, `v2/zzzzz-gj3su-.{15}/.{32,50}`)
457 authinfo := getCallbackAuthInfo(c, s.railsSpy)
458 c.Check(authinfo.FirstName, check.Equals, "Fake")
459 c.Check(authinfo.LastName, check.Equals, "User Name")
460 c.Check(authinfo.Email, check.Equals, "active-user@arvados.local")
461 c.Check(authinfo.AlternateEmails, check.HasLen, 0)
463 // Try using the returned Arvados token.
464 c.Logf("trying an API call with new token %q", token)
465 ctx := auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{token}})
466 cl, err := s.localdb.CollectionList(ctx, arvados.ListOptions{Limit: -1})
467 c.Check(cl.ItemsAvailable, check.Not(check.Equals), 0)
468 c.Check(cl.Items, check.Not(check.HasLen), 0)
469 c.Check(err, check.IsNil)
471 // Might as well check that bogus tokens aren't accepted.
472 badtoken := token + "plussomeboguschars"
473 c.Logf("trying an API call with mangled token %q", badtoken)
474 ctx = auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{badtoken}})
475 cl, err = s.localdb.CollectionList(ctx, arvados.ListOptions{Limit: -1})
476 c.Check(cl.Items, check.HasLen, 0)
477 c.Check(err, check.NotNil)
478 c.Check(err, check.ErrorMatches, `.*401 Unauthorized: Not logged in.*`)
481 func (s *OIDCLoginSuite) TestGoogleLogin_RealName(c *check.C) {
482 s.fakeProvider.AuthEmail = "joe.smith@primary.example.com"
483 s.fakeProvider.AuthEmailVerified = true
484 s.fakeProvider.PeopleAPIResponse = map[string]interface{}{
485 "names": []map[string]interface{}{
487 "metadata": map[string]interface{}{"primary": false},
489 "familyName": "Smith",
492 "metadata": map[string]interface{}{"primary": true},
493 "givenName": "Joseph",
494 "familyName": "Psmith",
498 state := s.startLogin(c)
499 s.localdb.Login(context.Background(), arvados.LoginOptions{
500 Code: s.fakeProvider.ValidCode,
504 authinfo := getCallbackAuthInfo(c, s.railsSpy)
505 c.Check(authinfo.FirstName, check.Equals, "Joseph")
506 c.Check(authinfo.LastName, check.Equals, "Psmith")
509 func (s *OIDCLoginSuite) TestGoogleLogin_OIDCNameWithoutGivenAndFamilyNames(c *check.C) {
510 s.fakeProvider.AuthName = "Joe P. Smith"
511 s.fakeProvider.AuthGivenName = ""
512 s.fakeProvider.AuthFamilyName = ""
513 s.fakeProvider.AuthEmail = "joe.smith@primary.example.com"
514 state := s.startLogin(c)
515 s.localdb.Login(context.Background(), arvados.LoginOptions{
516 Code: s.fakeProvider.ValidCode,
520 authinfo := getCallbackAuthInfo(c, s.railsSpy)
521 c.Check(authinfo.FirstName, check.Equals, "Joe P.")
522 c.Check(authinfo.LastName, check.Equals, "Smith")
525 // People API returns some additional email addresses.
526 func (s *OIDCLoginSuite) TestGoogleLogin_AlternateEmailAddresses(c *check.C) {
527 s.fakeProvider.AuthEmail = "joe.smith@primary.example.com"
528 s.fakeProvider.PeopleAPIResponse = map[string]interface{}{
529 "emailAddresses": []map[string]interface{}{
531 "metadata": map[string]interface{}{"verified": true},
532 "value": "joe.smith@work.example.com",
535 "value": "joe.smith@unverified.example.com", // unverified, so this one will be ignored
538 "metadata": map[string]interface{}{"verified": true},
539 "value": "joe.smith@home.example.com",
543 state := s.startLogin(c)
544 s.localdb.Login(context.Background(), arvados.LoginOptions{
545 Code: s.fakeProvider.ValidCode,
549 authinfo := getCallbackAuthInfo(c, s.railsSpy)
550 c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
551 c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@home.example.com", "joe.smith@work.example.com"})
554 // Primary address is not the one initially returned by oidc.
555 func (s *OIDCLoginSuite) TestGoogleLogin_AlternateEmailAddresses_Primary(c *check.C) {
556 s.fakeProvider.AuthEmail = "joe.smith@alternate.example.com"
557 s.fakeProvider.PeopleAPIResponse = map[string]interface{}{
558 "emailAddresses": []map[string]interface{}{
560 "metadata": map[string]interface{}{"verified": true, "primary": true},
561 "value": "joe.smith@primary.example.com",
564 "metadata": map[string]interface{}{"verified": true},
565 "value": "joe.smith@alternate.example.com",
568 "metadata": map[string]interface{}{"verified": true},
569 "value": "jsmith+123@preferdomainforusername.example.com",
573 state := s.startLogin(c)
574 s.localdb.Login(context.Background(), arvados.LoginOptions{
575 Code: s.fakeProvider.ValidCode,
578 authinfo := getCallbackAuthInfo(c, s.railsSpy)
579 c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
580 c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@alternate.example.com", "jsmith+123@preferdomainforusername.example.com"})
581 c.Check(authinfo.Username, check.Equals, "jsmith")
584 func (s *OIDCLoginSuite) TestGoogleLogin_NoPrimaryEmailAddress(c *check.C) {
585 s.fakeProvider.AuthEmail = "joe.smith@unverified.example.com"
586 s.fakeProvider.AuthEmailVerified = false
587 s.fakeProvider.PeopleAPIResponse = map[string]interface{}{
588 "emailAddresses": []map[string]interface{}{
590 "metadata": map[string]interface{}{"verified": true},
591 "value": "joe.smith@work.example.com",
594 "metadata": map[string]interface{}{"verified": true},
595 "value": "joe.smith@home.example.com",
599 state := s.startLogin(c)
600 s.localdb.Login(context.Background(), arvados.LoginOptions{
601 Code: s.fakeProvider.ValidCode,
605 authinfo := getCallbackAuthInfo(c, s.railsSpy)
606 c.Check(authinfo.Email, check.Equals, "joe.smith@work.example.com") // first verified email in People response
607 c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@home.example.com"})
608 c.Check(authinfo.Username, check.Equals, "")
611 func (s *OIDCLoginSuite) startLogin(c *check.C, checks ...func(url.Values)) (state string) {
612 // Initiate login, but instead of following the redirect to
613 // the provider, just grab state from the redirect URL.
614 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{ReturnTo: "https://app.example.com/foo?bar"})
615 c.Check(err, check.IsNil)
616 target, err := url.Parse(resp.RedirectLocation)
617 c.Check(err, check.IsNil)
618 state = target.Query().Get("state")
619 c.Check(state, check.Not(check.Equals), "")
620 for _, fn := range checks {
623 s.cluster.Login.OpenIDConnect.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"}
627 func getCallbackAuthInfo(c *check.C, railsSpy *arvadostest.Proxy) (authinfo rpc.UserSessionAuthInfo) {
628 for _, dump := range railsSpy.RequestDumps {
629 c.Logf("spied request: %q", dump)
630 split := bytes.Split(dump, []byte("\r\n\r\n"))
631 c.Assert(split, check.HasLen, 2)
632 hdr, body := string(split[0]), string(split[1])
633 if strings.Contains(hdr, "POST /auth/controller/callback") {
634 vs, err := url.ParseQuery(body)
635 c.Check(json.Unmarshal([]byte(vs.Get("auth_info")), &authinfo), check.IsNil)
636 c.Check(err, check.IsNil)
637 sort.Strings(authinfo.AlternateEmails)
641 c.Error("callback not found")