1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
23 "git.arvados.org/arvados.git/lib/config"
24 "git.arvados.org/arvados.git/lib/controller/rpc"
25 "git.arvados.org/arvados.git/sdk/go/arvados"
26 "git.arvados.org/arvados.git/sdk/go/arvadostest"
27 "git.arvados.org/arvados.git/sdk/go/auth"
28 "git.arvados.org/arvados.git/sdk/go/ctxlog"
29 "github.com/jmoiron/sqlx"
30 check "gopkg.in/check.v1"
33 // Gocheck boilerplate
34 func Test(t *testing.T) {
38 var _ = check.Suite(&OIDCLoginSuite{})
40 type OIDCLoginSuite struct {
41 cluster *arvados.Cluster
43 railsSpy *arvadostest.Proxy
44 fakeProvider *arvadostest.OIDCProvider
47 func (s *OIDCLoginSuite) TearDownSuite(c *check.C) {
48 // Undo any changes/additions to the user database so they
49 // don't affect subsequent tests.
50 arvadostest.ResetEnv()
51 c.Check(arvados.NewClientFromEnv().RequestAndDecode(nil, "POST", "database/reset", nil, nil), check.IsNil)
54 func (s *OIDCLoginSuite) SetUpTest(c *check.C) {
55 s.fakeProvider = arvadostest.NewOIDCProvider(c)
56 s.fakeProvider.AuthEmail = "active-user@arvados.local"
57 s.fakeProvider.AuthEmailVerified = true
58 s.fakeProvider.AuthName = "Fake User Name"
59 s.fakeProvider.AuthGivenName = "Fake"
60 s.fakeProvider.AuthFamilyName = "User Name"
61 s.fakeProvider.ValidCode = fmt.Sprintf("abcdefgh-%d", time.Now().Unix())
62 s.fakeProvider.PeopleAPIResponse = map[string]interface{}{}
64 cfg, err := config.NewLoader(nil, ctxlog.TestLogger(c)).Load()
65 c.Assert(err, check.IsNil)
66 s.cluster, err = cfg.GetCluster("")
67 c.Assert(err, check.IsNil)
68 s.cluster.Login.Test.Enable = false
69 s.cluster.Login.Google.Enable = true
70 s.cluster.Login.Google.ClientID = "test%client$id"
71 s.cluster.Login.Google.ClientSecret = "test#client/secret"
72 s.cluster.Users.PreferDomainForUsername = "PreferDomainForUsername.example.com"
73 s.fakeProvider.ValidClientID = "test%client$id"
74 s.fakeProvider.ValidClientSecret = "test#client/secret"
76 s.localdb = NewConn(s.cluster)
77 c.Assert(s.localdb.loginController, check.FitsTypeOf, (*oidcLoginController)(nil))
78 s.localdb.loginController.(*oidcLoginController).Issuer = s.fakeProvider.Issuer.URL
79 s.localdb.loginController.(*oidcLoginController).peopleAPIBasePath = s.fakeProvider.PeopleAPI.URL
81 s.railsSpy = arvadostest.NewProxy(c, s.cluster.Services.RailsAPI)
82 *s.localdb.railsProxy = *rpc.NewConn(s.cluster.ClusterID, s.railsSpy.URL, true, rpc.PassthroughTokenProvider)
85 func (s *OIDCLoginSuite) TearDownTest(c *check.C) {
89 func (s *OIDCLoginSuite) TestGoogleLogout(c *check.C) {
90 resp, err := s.localdb.Logout(context.Background(), arvados.LogoutOptions{ReturnTo: "https://foo.example.com/bar"})
91 c.Check(err, check.IsNil)
92 c.Check(resp.RedirectLocation, check.Equals, "https://foo.example.com/bar")
95 func (s *OIDCLoginSuite) TestGoogleLogin_Start_Bogus(c *check.C) {
96 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{})
97 c.Check(err, check.IsNil)
98 c.Check(resp.RedirectLocation, check.Equals, "")
99 c.Check(resp.HTML.String(), check.Matches, `.*missing return_to parameter.*`)
102 func (s *OIDCLoginSuite) TestGoogleLogin_Start(c *check.C) {
103 for _, remote := range []string{"", "zzzzz"} {
104 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{Remote: remote, ReturnTo: "https://app.example.com/foo?bar"})
105 c.Check(err, check.IsNil)
106 target, err := url.Parse(resp.RedirectLocation)
107 c.Check(err, check.IsNil)
108 issuerURL, _ := url.Parse(s.fakeProvider.Issuer.URL)
109 c.Check(target.Host, check.Equals, issuerURL.Host)
111 c.Check(q.Get("client_id"), check.Equals, "test%client$id")
112 state := s.localdb.loginController.(*oidcLoginController).parseOAuth2State(q.Get("state"))
113 c.Check(state.verify([]byte(s.cluster.SystemRootToken)), check.Equals, true)
114 c.Check(state.Time, check.Not(check.Equals), 0)
115 c.Check(state.Remote, check.Equals, remote)
116 c.Check(state.ReturnTo, check.Equals, "https://app.example.com/foo?bar")
120 func (s *OIDCLoginSuite) TestGoogleLogin_InvalidCode(c *check.C) {
121 state := s.startLogin(c)
122 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
123 Code: "first-try-a-bogus-code",
126 c.Check(err, check.IsNil)
127 c.Check(resp.RedirectLocation, check.Equals, "")
128 c.Check(resp.HTML.String(), check.Matches, `(?ms).*error in OAuth2 exchange.*cannot fetch token.*`)
131 func (s *OIDCLoginSuite) TestGoogleLogin_InvalidState(c *check.C) {
133 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
134 Code: s.fakeProvider.ValidCode,
135 State: "bogus-state",
137 c.Check(err, check.IsNil)
138 c.Check(resp.RedirectLocation, check.Equals, "")
139 c.Check(resp.HTML.String(), check.Matches, `(?ms).*invalid OAuth2 state.*`)
142 func (s *OIDCLoginSuite) setupPeopleAPIError(c *check.C) {
143 s.fakeProvider.PeopleAPI = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
144 w.WriteHeader(http.StatusForbidden)
145 fmt.Fprintln(w, `Error 403: accessNotConfigured`)
147 s.localdb.loginController.(*oidcLoginController).peopleAPIBasePath = s.fakeProvider.PeopleAPI.URL
150 func (s *OIDCLoginSuite) TestGoogleLogin_PeopleAPIDisabled(c *check.C) {
151 s.localdb.loginController.(*oidcLoginController).UseGooglePeopleAPI = false
152 s.fakeProvider.AuthEmail = "joe.smith@primary.example.com"
153 s.setupPeopleAPIError(c)
154 state := s.startLogin(c)
155 _, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
156 Code: s.fakeProvider.ValidCode,
159 c.Check(err, check.IsNil)
160 authinfo := getCallbackAuthInfo(c, s.railsSpy)
161 c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
164 func (s *OIDCLoginSuite) TestConfig(c *check.C) {
165 s.cluster.Login.Google.Enable = false
166 s.cluster.Login.OpenIDConnect.Enable = true
167 s.cluster.Login.OpenIDConnect.Issuer = "https://accounts.example.com/"
168 s.cluster.Login.OpenIDConnect.ClientID = "oidc-client-id"
169 s.cluster.Login.OpenIDConnect.ClientSecret = "oidc-client-secret"
170 s.cluster.Login.OpenIDConnect.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"}
171 localdb := NewConn(s.cluster)
172 ctrl := localdb.loginController.(*oidcLoginController)
173 c.Check(ctrl.Issuer, check.Equals, "https://accounts.example.com/")
174 c.Check(ctrl.ClientID, check.Equals, "oidc-client-id")
175 c.Check(ctrl.ClientSecret, check.Equals, "oidc-client-secret")
176 c.Check(ctrl.UseGooglePeopleAPI, check.Equals, false)
177 c.Check(ctrl.AuthParams["testkey"], check.Equals, "testvalue")
179 for _, enableAltEmails := range []bool{false, true} {
180 s.cluster.Login.OpenIDConnect.Enable = false
181 s.cluster.Login.Google.Enable = true
182 s.cluster.Login.Google.ClientID = "google-client-id"
183 s.cluster.Login.Google.ClientSecret = "google-client-secret"
184 s.cluster.Login.Google.AlternateEmailAddresses = enableAltEmails
185 s.cluster.Login.Google.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"}
186 localdb = NewConn(s.cluster)
187 ctrl = localdb.loginController.(*oidcLoginController)
188 c.Check(ctrl.Issuer, check.Equals, "https://accounts.google.com")
189 c.Check(ctrl.ClientID, check.Equals, "google-client-id")
190 c.Check(ctrl.ClientSecret, check.Equals, "google-client-secret")
191 c.Check(ctrl.UseGooglePeopleAPI, check.Equals, enableAltEmails)
192 c.Check(ctrl.AuthParams["testkey"], check.Equals, "testvalue")
196 func (s *OIDCLoginSuite) TestGoogleLogin_PeopleAPIError(c *check.C) {
197 s.setupPeopleAPIError(c)
198 state := s.startLogin(c)
199 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
200 Code: s.fakeProvider.ValidCode,
203 c.Check(err, check.IsNil)
204 c.Check(resp.RedirectLocation, check.Equals, "")
207 func (s *OIDCLoginSuite) TestOIDCAuthorizer(c *check.C) {
208 s.cluster.Login.Google.Enable = false
209 s.cluster.Login.OpenIDConnect.Enable = true
210 json.Unmarshal([]byte(fmt.Sprintf("%q", s.fakeProvider.Issuer.URL)), &s.cluster.Login.OpenIDConnect.Issuer)
211 s.cluster.Login.OpenIDConnect.ClientID = "oidc#client#id"
212 s.cluster.Login.OpenIDConnect.ClientSecret = "oidc#client#secret"
213 s.cluster.Login.OpenIDConnect.AcceptAccessToken = true
214 s.cluster.Login.OpenIDConnect.AcceptAccessTokenScope = ""
215 s.fakeProvider.ValidClientID = "oidc#client#id"
216 s.fakeProvider.ValidClientSecret = "oidc#client#secret"
217 db := arvadostest.DB(c, s.cluster)
219 tokenCacheTTL = time.Millisecond
220 tokenCacheRaceWindow = time.Millisecond
221 tokenCacheNegativeTTL = time.Millisecond
223 oidcAuthorizer := OIDCAccessTokenAuthorizer(s.cluster, func(context.Context) (*sqlx.DB, error) { return db, nil })
224 accessToken := s.fakeProvider.ValidAccessToken()
226 mac := hmac.New(sha256.New, []byte(s.cluster.SystemRootToken))
227 io.WriteString(mac, accessToken)
228 apiToken := fmt.Sprintf("%x", mac.Sum(nil))
231 _, err := db.Exec(`delete from api_client_authorizations where api_token=$1`, apiToken)
232 c.Check(err, check.IsNil)
237 ctx := auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{accessToken}})
239 oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) {
240 creds, ok := auth.FromContext(ctx)
241 c.Assert(ok, check.Equals, true)
242 c.Assert(creds.Tokens, check.HasLen, 1)
243 c.Check(creds.Tokens[0], check.Equals, accessToken)
245 err := db.QueryRowContext(ctx, `select expires_at at time zone 'UTC' from api_client_authorizations where api_token=$1`, apiToken).Scan(&exp1)
246 c.Check(err, check.IsNil)
247 c.Check(exp1.Sub(time.Now()) > -time.Second, check.Equals, true)
248 c.Check(exp1.Sub(time.Now()) < time.Second, check.Equals, true)
252 // If the token is used again after the in-memory cache
253 // expires, oidcAuthorizer must re-check the token and update
254 // the expires_at value in the database.
255 time.Sleep(3 * time.Millisecond)
256 oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) {
258 err := db.QueryRowContext(ctx, `select expires_at at time zone 'UTC' from api_client_authorizations where api_token=$1`, apiToken).Scan(&exp)
259 c.Check(err, check.IsNil)
260 c.Check(exp.Sub(exp1) > 0, check.Equals, true)
261 c.Check(exp.Sub(exp1) < time.Second, check.Equals, true)
265 s.fakeProvider.AccessTokenPayload = map[string]interface{}{"scope": "openid profile foobar"}
266 accessToken = s.fakeProvider.ValidAccessToken()
267 ctx = auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{accessToken}})
269 mac = hmac.New(sha256.New, []byte(s.cluster.SystemRootToken))
270 io.WriteString(mac, accessToken)
271 apiToken = fmt.Sprintf("%x", mac.Sum(nil))
273 for _, trial := range []struct {
279 {true, "foobar", true, true},
280 {true, "foo", false, false},
281 {true, "", true, true},
282 {false, "", false, true},
283 {false, "foobar", false, true},
285 c.Logf("trial = %+v", trial)
287 s.cluster.Login.OpenIDConnect.AcceptAccessToken = trial.configEnable
288 s.cluster.Login.OpenIDConnect.AcceptAccessTokenScope = trial.configScope
289 oidcAuthorizer = OIDCAccessTokenAuthorizer(s.cluster, func(context.Context) (*sqlx.DB, error) { return db, nil })
291 oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) {
293 err := db.QueryRowContext(ctx, `select count(*) from api_client_authorizations where api_token=$1`, apiToken).Scan(&n)
294 c.Check(err, check.IsNil)
295 if trial.acceptable {
296 c.Check(n, check.Equals, 1)
298 c.Check(n, check.Equals, 0)
303 c.Check(checked, check.Equals, trial.shouldRun)
307 func (s *OIDCLoginSuite) TestGenericOIDCLogin(c *check.C) {
308 s.cluster.Login.Google.Enable = false
309 s.cluster.Login.OpenIDConnect.Enable = true
310 json.Unmarshal([]byte(fmt.Sprintf("%q", s.fakeProvider.Issuer.URL)), &s.cluster.Login.OpenIDConnect.Issuer)
311 s.cluster.Login.OpenIDConnect.ClientID = "oidc#client#id"
312 s.cluster.Login.OpenIDConnect.ClientSecret = "oidc#client#secret"
313 s.cluster.Login.OpenIDConnect.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"}
314 s.fakeProvider.ValidClientID = "oidc#client#id"
315 s.fakeProvider.ValidClientSecret = "oidc#client#secret"
316 for _, trial := range []struct {
317 expectEmail string // "" if failure expected
321 expectEmail: "user@oidc.example.com",
323 c.Log("=== succeed because email_verified is false but not required")
324 s.fakeProvider.AuthEmail = "user@oidc.example.com"
325 s.fakeProvider.AuthEmailVerified = false
326 s.cluster.Login.OpenIDConnect.EmailClaim = "email"
327 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = ""
328 s.cluster.Login.OpenIDConnect.UsernameClaim = ""
334 c.Log("=== fail because email_verified is false and required")
335 s.fakeProvider.AuthEmail = "user@oidc.example.com"
336 s.fakeProvider.AuthEmailVerified = false
337 s.cluster.Login.OpenIDConnect.EmailClaim = "email"
338 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = "email_verified"
339 s.cluster.Login.OpenIDConnect.UsernameClaim = ""
343 expectEmail: "user@oidc.example.com",
345 c.Log("=== succeed because email_verified is false but config uses custom 'verified' claim")
346 s.fakeProvider.AuthEmail = "user@oidc.example.com"
347 s.fakeProvider.AuthEmailVerified = false
348 s.cluster.Login.OpenIDConnect.EmailClaim = "email"
349 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = "alt_verified"
350 s.cluster.Login.OpenIDConnect.UsernameClaim = ""
354 expectEmail: "alt_email@example.com",
356 c.Log("=== succeed with custom 'email' and 'email_verified' claims")
357 s.fakeProvider.AuthEmail = "bad@wrong.example.com"
358 s.fakeProvider.AuthEmailVerified = false
359 s.cluster.Login.OpenIDConnect.EmailClaim = "alt_email"
360 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = "alt_verified"
361 s.cluster.Login.OpenIDConnect.UsernameClaim = "alt_username"
366 if s.railsSpy != nil {
369 s.railsSpy = arvadostest.NewProxy(c, s.cluster.Services.RailsAPI)
370 s.localdb = NewConn(s.cluster)
371 *s.localdb.railsProxy = *rpc.NewConn(s.cluster.ClusterID, s.railsSpy.URL, true, rpc.PassthroughTokenProvider)
373 state := s.startLogin(c, func(form url.Values) {
374 c.Check(form.Get("testkey"), check.Equals, "testvalue")
376 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
377 Code: s.fakeProvider.ValidCode,
380 c.Assert(err, check.IsNil)
381 if trial.expectEmail == "" {
382 c.Check(resp.HTML.String(), check.Matches, `(?ms).*Login error.*`)
383 c.Check(resp.RedirectLocation, check.Equals, "")
386 c.Check(resp.HTML.String(), check.Equals, "")
387 target, err := url.Parse(resp.RedirectLocation)
388 c.Assert(err, check.IsNil)
389 token := target.Query().Get("api_token")
390 c.Check(token, check.Matches, `v2/zzzzz-gj3su-.{15}/.{32,50}`)
391 authinfo := getCallbackAuthInfo(c, s.railsSpy)
392 c.Check(authinfo.Email, check.Equals, trial.expectEmail)
394 switch s.cluster.Login.OpenIDConnect.UsernameClaim {
396 c.Check(authinfo.Username, check.Equals, "desired-username")
398 c.Check(authinfo.Username, check.Equals, "")
400 c.Fail() // bad test case
405 func (s *OIDCLoginSuite) TestGoogleLogin_Success(c *check.C) {
406 s.cluster.Login.Google.AuthenticationRequestParameters["prompt"] = "consent"
407 s.cluster.Login.Google.AuthenticationRequestParameters["foo"] = "bar"
408 state := s.startLogin(c, func(form url.Values) {
409 c.Check(form.Get("foo"), check.Equals, "bar")
410 c.Check(form.Get("prompt"), check.Equals, "consent")
412 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
413 Code: s.fakeProvider.ValidCode,
416 c.Check(err, check.IsNil)
417 c.Check(resp.HTML.String(), check.Equals, "")
418 target, err := url.Parse(resp.RedirectLocation)
419 c.Check(err, check.IsNil)
420 c.Check(target.Host, check.Equals, "app.example.com")
421 c.Check(target.Path, check.Equals, "/foo")
422 token := target.Query().Get("api_token")
423 c.Check(token, check.Matches, `v2/zzzzz-gj3su-.{15}/.{32,50}`)
425 authinfo := getCallbackAuthInfo(c, s.railsSpy)
426 c.Check(authinfo.FirstName, check.Equals, "Fake")
427 c.Check(authinfo.LastName, check.Equals, "User Name")
428 c.Check(authinfo.Email, check.Equals, "active-user@arvados.local")
429 c.Check(authinfo.AlternateEmails, check.HasLen, 0)
431 // Try using the returned Arvados token.
432 c.Logf("trying an API call with new token %q", token)
433 ctx := auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{token}})
434 cl, err := s.localdb.CollectionList(ctx, arvados.ListOptions{Limit: -1})
435 c.Check(cl.ItemsAvailable, check.Not(check.Equals), 0)
436 c.Check(cl.Items, check.Not(check.HasLen), 0)
437 c.Check(err, check.IsNil)
439 // Might as well check that bogus tokens aren't accepted.
440 badtoken := token + "plussomeboguschars"
441 c.Logf("trying an API call with mangled token %q", badtoken)
442 ctx = auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{badtoken}})
443 cl, err = s.localdb.CollectionList(ctx, arvados.ListOptions{Limit: -1})
444 c.Check(cl.Items, check.HasLen, 0)
445 c.Check(err, check.NotNil)
446 c.Check(err, check.ErrorMatches, `.*401 Unauthorized: Not logged in.*`)
449 func (s *OIDCLoginSuite) TestGoogleLogin_RealName(c *check.C) {
450 s.fakeProvider.AuthEmail = "joe.smith@primary.example.com"
451 s.fakeProvider.AuthEmailVerified = true
452 s.fakeProvider.PeopleAPIResponse = map[string]interface{}{
453 "names": []map[string]interface{}{
455 "metadata": map[string]interface{}{"primary": false},
457 "familyName": "Smith",
460 "metadata": map[string]interface{}{"primary": true},
461 "givenName": "Joseph",
462 "familyName": "Psmith",
466 state := s.startLogin(c)
467 s.localdb.Login(context.Background(), arvados.LoginOptions{
468 Code: s.fakeProvider.ValidCode,
472 authinfo := getCallbackAuthInfo(c, s.railsSpy)
473 c.Check(authinfo.FirstName, check.Equals, "Joseph")
474 c.Check(authinfo.LastName, check.Equals, "Psmith")
477 func (s *OIDCLoginSuite) TestGoogleLogin_OIDCNameWithoutGivenAndFamilyNames(c *check.C) {
478 s.fakeProvider.AuthName = "Joe P. Smith"
479 s.fakeProvider.AuthGivenName = ""
480 s.fakeProvider.AuthFamilyName = ""
481 s.fakeProvider.AuthEmail = "joe.smith@primary.example.com"
482 state := s.startLogin(c)
483 s.localdb.Login(context.Background(), arvados.LoginOptions{
484 Code: s.fakeProvider.ValidCode,
488 authinfo := getCallbackAuthInfo(c, s.railsSpy)
489 c.Check(authinfo.FirstName, check.Equals, "Joe P.")
490 c.Check(authinfo.LastName, check.Equals, "Smith")
493 // People API returns some additional email addresses.
494 func (s *OIDCLoginSuite) TestGoogleLogin_AlternateEmailAddresses(c *check.C) {
495 s.fakeProvider.AuthEmail = "joe.smith@primary.example.com"
496 s.fakeProvider.PeopleAPIResponse = map[string]interface{}{
497 "emailAddresses": []map[string]interface{}{
499 "metadata": map[string]interface{}{"verified": true},
500 "value": "joe.smith@work.example.com",
503 "value": "joe.smith@unverified.example.com", // unverified, so this one will be ignored
506 "metadata": map[string]interface{}{"verified": true},
507 "value": "joe.smith@home.example.com",
511 state := s.startLogin(c)
512 s.localdb.Login(context.Background(), arvados.LoginOptions{
513 Code: s.fakeProvider.ValidCode,
517 authinfo := getCallbackAuthInfo(c, s.railsSpy)
518 c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
519 c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@home.example.com", "joe.smith@work.example.com"})
522 // Primary address is not the one initially returned by oidc.
523 func (s *OIDCLoginSuite) TestGoogleLogin_AlternateEmailAddresses_Primary(c *check.C) {
524 s.fakeProvider.AuthEmail = "joe.smith@alternate.example.com"
525 s.fakeProvider.PeopleAPIResponse = map[string]interface{}{
526 "emailAddresses": []map[string]interface{}{
528 "metadata": map[string]interface{}{"verified": true, "primary": true},
529 "value": "joe.smith@primary.example.com",
532 "metadata": map[string]interface{}{"verified": true},
533 "value": "joe.smith@alternate.example.com",
536 "metadata": map[string]interface{}{"verified": true},
537 "value": "jsmith+123@preferdomainforusername.example.com",
541 state := s.startLogin(c)
542 s.localdb.Login(context.Background(), arvados.LoginOptions{
543 Code: s.fakeProvider.ValidCode,
546 authinfo := getCallbackAuthInfo(c, s.railsSpy)
547 c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
548 c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@alternate.example.com", "jsmith+123@preferdomainforusername.example.com"})
549 c.Check(authinfo.Username, check.Equals, "jsmith")
552 func (s *OIDCLoginSuite) TestGoogleLogin_NoPrimaryEmailAddress(c *check.C) {
553 s.fakeProvider.AuthEmail = "joe.smith@unverified.example.com"
554 s.fakeProvider.AuthEmailVerified = false
555 s.fakeProvider.PeopleAPIResponse = map[string]interface{}{
556 "emailAddresses": []map[string]interface{}{
558 "metadata": map[string]interface{}{"verified": true},
559 "value": "joe.smith@work.example.com",
562 "metadata": map[string]interface{}{"verified": true},
563 "value": "joe.smith@home.example.com",
567 state := s.startLogin(c)
568 s.localdb.Login(context.Background(), arvados.LoginOptions{
569 Code: s.fakeProvider.ValidCode,
573 authinfo := getCallbackAuthInfo(c, s.railsSpy)
574 c.Check(authinfo.Email, check.Equals, "joe.smith@work.example.com") // first verified email in People response
575 c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@home.example.com"})
576 c.Check(authinfo.Username, check.Equals, "")
579 func (s *OIDCLoginSuite) startLogin(c *check.C, checks ...func(url.Values)) (state string) {
580 // Initiate login, but instead of following the redirect to
581 // the provider, just grab state from the redirect URL.
582 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{ReturnTo: "https://app.example.com/foo?bar"})
583 c.Check(err, check.IsNil)
584 target, err := url.Parse(resp.RedirectLocation)
585 c.Check(err, check.IsNil)
586 state = target.Query().Get("state")
587 c.Check(state, check.Not(check.Equals), "")
588 for _, fn := range checks {
591 s.cluster.Login.OpenIDConnect.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"}
595 func getCallbackAuthInfo(c *check.C, railsSpy *arvadostest.Proxy) (authinfo rpc.UserSessionAuthInfo) {
596 for _, dump := range railsSpy.RequestDumps {
597 c.Logf("spied request: %q", dump)
598 split := bytes.Split(dump, []byte("\r\n\r\n"))
599 c.Assert(split, check.HasLen, 2)
600 hdr, body := string(split[0]), string(split[1])
601 if strings.Contains(hdr, "POST /auth/controller/callback") {
602 vs, err := url.ParseQuery(body)
603 c.Check(json.Unmarshal([]byte(vs.Get("auth_info")), &authinfo), check.IsNil)
604 c.Check(err, check.IsNil)
605 sort.Strings(authinfo.AlternateEmails)
609 c.Error("callback not found")