18691: Disallow freezing projects with active container requests.
[arvados.git] / lib / controller / localdb / login_oidc_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package localdb
6
7 import (
8         "bytes"
9         "context"
10         "crypto/hmac"
11         "crypto/sha256"
12         "encoding/json"
13         "fmt"
14         "io"
15         "net/http"
16         "net/http/httptest"
17         "net/url"
18         "sort"
19         "strings"
20         "testing"
21         "time"
22
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"
31 )
32
33 // Gocheck boilerplate
34 func Test(t *testing.T) {
35         check.TestingT(t)
36 }
37
38 var _ = check.Suite(&OIDCLoginSuite{})
39
40 type OIDCLoginSuite struct {
41         cluster      *arvados.Cluster
42         localdb      *Conn
43         railsSpy     *arvadostest.Proxy
44         fakeProvider *arvadostest.OIDCProvider
45 }
46
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)
52 }
53
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{}{}
63
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"
75
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
80
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)
83 }
84
85 func (s *OIDCLoginSuite) TearDownTest(c *check.C) {
86         s.railsSpy.Close()
87 }
88
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")
93 }
94
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.*`)
100 }
101
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)
110                 q := target.Query()
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")
117         }
118 }
119
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",
124                 State: state,
125         })
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.*`)
129 }
130
131 func (s *OIDCLoginSuite) TestGoogleLogin_InvalidState(c *check.C) {
132         s.startLogin(c)
133         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
134                 Code:  s.fakeProvider.ValidCode,
135                 State: "bogus-state",
136         })
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.*`)
140 }
141
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`)
146         }))
147         s.localdb.loginController.(*oidcLoginController).peopleAPIBasePath = s.fakeProvider.PeopleAPI.URL
148 }
149
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,
157                 State: state,
158         })
159         c.Check(err, check.IsNil)
160         authinfo := getCallbackAuthInfo(c, s.railsSpy)
161         c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
162 }
163
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")
178
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")
193         }
194 }
195
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,
201                 State: state,
202         })
203         c.Check(err, check.IsNil)
204         c.Check(resp.RedirectLocation, check.Equals, "")
205 }
206
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)
218
219         tokenCacheTTL = time.Millisecond
220         tokenCacheRaceWindow = time.Millisecond
221         tokenCacheNegativeTTL = time.Millisecond
222
223         oidcAuthorizer := OIDCAccessTokenAuthorizer(s.cluster, func(context.Context) (*sqlx.DB, error) { return db, nil })
224         accessToken := s.fakeProvider.ValidAccessToken()
225
226         mac := hmac.New(sha256.New, []byte(s.cluster.SystemRootToken))
227         io.WriteString(mac, accessToken)
228         apiToken := fmt.Sprintf("%x", mac.Sum(nil))
229
230         cleanup := func() {
231                 _, err := db.Exec(`delete from api_client_authorizations where api_token=$1`, apiToken)
232                 c.Check(err, check.IsNil)
233         }
234         cleanup()
235         defer cleanup()
236
237         ctx := auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{accessToken}})
238         var exp1 time.Time
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)
244
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)
249                 return nil, nil
250         })(ctx, nil)
251
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) {
257                 var exp time.Time
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)
262                 return nil, nil
263         })(ctx, nil)
264
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}})
268
269         mac = hmac.New(sha256.New, []byte(s.cluster.SystemRootToken))
270         io.WriteString(mac, accessToken)
271         apiToken = fmt.Sprintf("%x", mac.Sum(nil))
272
273         for _, trial := range []struct {
274                 configEnable bool
275                 configScope  string
276                 acceptable   bool
277                 shouldRun    bool
278         }{
279                 {true, "foobar", true, true},
280                 {true, "foo", false, false},
281                 {true, "", true, true},
282                 {false, "", false, true},
283                 {false, "foobar", false, true},
284         } {
285                 c.Logf("trial = %+v", trial)
286                 cleanup()
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 })
290                 checked := false
291                 oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) {
292                         var n int
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)
297                         } else {
298                                 c.Check(n, check.Equals, 0)
299                         }
300                         checked = true
301                         return nil, nil
302                 })(ctx, nil)
303                 c.Check(checked, check.Equals, trial.shouldRun)
304         }
305 }
306
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
318                 setup       func()
319         }{
320                 {
321                         expectEmail: "user@oidc.example.com",
322                         setup: func() {
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 = ""
329                         },
330                 },
331                 {
332                         expectEmail: "",
333                         setup: func() {
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 = ""
340                         },
341                 },
342                 {
343                         expectEmail: "user@oidc.example.com",
344                         setup: func() {
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 = ""
351                         },
352                 },
353                 {
354                         expectEmail: "alt_email@example.com",
355                         setup: func() {
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"
362                         },
363                 },
364         } {
365                 trial.setup()
366                 if s.railsSpy != nil {
367                         s.railsSpy.Close()
368                 }
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)
372
373                 state := s.startLogin(c, func(form url.Values) {
374                         c.Check(form.Get("testkey"), check.Equals, "testvalue")
375                 })
376                 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
377                         Code:  s.fakeProvider.ValidCode,
378                         State: state,
379                 })
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, "")
384                         continue
385                 }
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)
393
394                 switch s.cluster.Login.OpenIDConnect.UsernameClaim {
395                 case "alt_username":
396                         c.Check(authinfo.Username, check.Equals, "desired-username")
397                 case "":
398                         c.Check(authinfo.Username, check.Equals, "")
399                 default:
400                         c.Fail() // bad test case
401                 }
402         }
403 }
404
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")
411         })
412         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
413                 Code:  s.fakeProvider.ValidCode,
414                 State: state,
415         })
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}`)
424
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)
430
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)
438
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.*`)
447 }
448
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{}{
454                         {
455                                 "metadata":   map[string]interface{}{"primary": false},
456                                 "givenName":  "Joe",
457                                 "familyName": "Smith",
458                         },
459                         {
460                                 "metadata":   map[string]interface{}{"primary": true},
461                                 "givenName":  "Joseph",
462                                 "familyName": "Psmith",
463                         },
464                 },
465         }
466         state := s.startLogin(c)
467         s.localdb.Login(context.Background(), arvados.LoginOptions{
468                 Code:  s.fakeProvider.ValidCode,
469                 State: state,
470         })
471
472         authinfo := getCallbackAuthInfo(c, s.railsSpy)
473         c.Check(authinfo.FirstName, check.Equals, "Joseph")
474         c.Check(authinfo.LastName, check.Equals, "Psmith")
475 }
476
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,
485                 State: state,
486         })
487
488         authinfo := getCallbackAuthInfo(c, s.railsSpy)
489         c.Check(authinfo.FirstName, check.Equals, "Joe P.")
490         c.Check(authinfo.LastName, check.Equals, "Smith")
491 }
492
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{}{
498                         {
499                                 "metadata": map[string]interface{}{"verified": true},
500                                 "value":    "joe.smith@work.example.com",
501                         },
502                         {
503                                 "value": "joe.smith@unverified.example.com", // unverified, so this one will be ignored
504                         },
505                         {
506                                 "metadata": map[string]interface{}{"verified": true},
507                                 "value":    "joe.smith@home.example.com",
508                         },
509                 },
510         }
511         state := s.startLogin(c)
512         s.localdb.Login(context.Background(), arvados.LoginOptions{
513                 Code:  s.fakeProvider.ValidCode,
514                 State: state,
515         })
516
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"})
520 }
521
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{}{
527                         {
528                                 "metadata": map[string]interface{}{"verified": true, "primary": true},
529                                 "value":    "joe.smith@primary.example.com",
530                         },
531                         {
532                                 "metadata": map[string]interface{}{"verified": true},
533                                 "value":    "joe.smith@alternate.example.com",
534                         },
535                         {
536                                 "metadata": map[string]interface{}{"verified": true},
537                                 "value":    "jsmith+123@preferdomainforusername.example.com",
538                         },
539                 },
540         }
541         state := s.startLogin(c)
542         s.localdb.Login(context.Background(), arvados.LoginOptions{
543                 Code:  s.fakeProvider.ValidCode,
544                 State: state,
545         })
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")
550 }
551
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{}{
557                         {
558                                 "metadata": map[string]interface{}{"verified": true},
559                                 "value":    "joe.smith@work.example.com",
560                         },
561                         {
562                                 "metadata": map[string]interface{}{"verified": true},
563                                 "value":    "joe.smith@home.example.com",
564                         },
565                 },
566         }
567         state := s.startLogin(c)
568         s.localdb.Login(context.Background(), arvados.LoginOptions{
569                 Code:  s.fakeProvider.ValidCode,
570                 State: state,
571         })
572
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, "")
577 }
578
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 {
589                 fn(target.Query())
590         }
591         s.cluster.Login.OpenIDConnect.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"}
592         return
593 }
594
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)
606                         return
607                 }
608         }
609         c.Error("callback not found")
610         return
611 }