19518: Check account access permission during pam auth.
[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         "sync"
21         "testing"
22         "time"
23
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"
32 )
33
34 // Gocheck boilerplate
35 func Test(t *testing.T) {
36         check.TestingT(t)
37 }
38
39 var _ = check.Suite(&OIDCLoginSuite{})
40
41 type OIDCLoginSuite struct {
42         cluster      *arvados.Cluster
43         localdb      *Conn
44         railsSpy     *arvadostest.Proxy
45         fakeProvider *arvadostest.OIDCProvider
46 }
47
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)
53 }
54
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{}{}
64
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"
76
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
81
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)
84 }
85
86 func (s *OIDCLoginSuite) TearDownTest(c *check.C) {
87         s.railsSpy.Close()
88 }
89
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")
94 }
95
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.*`)
101 }
102
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)
111                 q := target.Query()
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")
118         }
119 }
120
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",
125                 State: state,
126         })
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.*`)
130 }
131
132 func (s *OIDCLoginSuite) TestGoogleLogin_InvalidState(c *check.C) {
133         s.startLogin(c)
134         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
135                 Code:  s.fakeProvider.ValidCode,
136                 State: "bogus-state",
137         })
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.*`)
141 }
142
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`)
147         }))
148         s.localdb.loginController.(*oidcLoginController).peopleAPIBasePath = s.fakeProvider.PeopleAPI.URL
149 }
150
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,
158                 State: state,
159         })
160         c.Check(err, check.IsNil)
161         authinfo := getCallbackAuthInfo(c, s.railsSpy)
162         c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
163 }
164
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")
179
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")
194         }
195 }
196
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,
202                 State: state,
203         })
204         c.Check(err, check.IsNil)
205         c.Check(resp.RedirectLocation, check.Equals, "")
206 }
207
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)
219
220         tokenCacheTTL = time.Millisecond
221         tokenCacheRaceWindow = time.Millisecond
222         tokenCacheNegativeTTL = time.Millisecond
223
224         oidcAuthorizer := OIDCAccessTokenAuthorizer(s.cluster, func(context.Context) (*sqlx.DB, error) { return db, nil })
225         accessToken := s.fakeProvider.ValidAccessToken()
226
227         mac := hmac.New(sha256.New, []byte(s.cluster.SystemRootToken))
228         io.WriteString(mac, accessToken)
229         apiToken := fmt.Sprintf("%x", mac.Sum(nil))
230
231         cleanup := func() {
232                 _, err := db.Exec(`delete from api_client_authorizations where api_token=$1`, apiToken)
233                 c.Check(err, check.IsNil)
234         }
235         cleanup()
236         defer cleanup()
237
238         ctx := auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{accessToken}})
239         var exp1 time.Time
240
241         concurrent := 4
242         s.fakeProvider.HoldUserInfo = make(chan *http.Request)
243         s.fakeProvider.ReleaseUserInfo = make(chan struct{})
244         go func() {
245                 for i := 0; ; i++ {
246                         if i == concurrent {
247                                 close(s.fakeProvider.ReleaseUserInfo)
248                         }
249                         <-s.fakeProvider.HoldUserInfo
250                 }
251         }()
252         var wg sync.WaitGroup
253         for i := 0; i < concurrent; i++ {
254                 i := i
255                 wg.Add(1)
256                 go func() {
257                         defer wg.Done()
258                         _, err := oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) {
259                                 c.Logf("concurrent req %d/%d", i, concurrent)
260                                 var exp time.Time
261
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)
266
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)
271                                 if i == 0 {
272                                         exp1 = exp
273                                 }
274                                 return nil, nil
275                         })(ctx, nil)
276                         c.Check(err, check.IsNil)
277                 }()
278         }
279         wg.Wait()
280         if c.Failed() {
281                 c.Fatal("giving up")
282         }
283
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) {
289                 var exp time.Time
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)))
294                 return nil, nil
295         })(ctx, nil)
296
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}})
300
301         mac = hmac.New(sha256.New, []byte(s.cluster.SystemRootToken))
302         io.WriteString(mac, accessToken)
303         apiToken = fmt.Sprintf("%x", mac.Sum(nil))
304
305         for _, trial := range []struct {
306                 configEnable bool
307                 configScope  string
308                 acceptable   bool
309                 shouldRun    bool
310         }{
311                 {true, "foobar", true, true},
312                 {true, "foo", false, false},
313                 {true, "", true, true},
314                 {false, "", false, true},
315                 {false, "foobar", false, true},
316         } {
317                 c.Logf("trial = %+v", trial)
318                 cleanup()
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 })
322                 checked := false
323                 oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) {
324                         var n int
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)
329                         } else {
330                                 c.Check(n, check.Equals, 0)
331                         }
332                         checked = true
333                         return nil, nil
334                 })(ctx, nil)
335                 c.Check(checked, check.Equals, trial.shouldRun)
336         }
337 }
338
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
350                 setup       func()
351         }{
352                 {
353                         expectEmail: "user@oidc.example.com",
354                         setup: func() {
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 = ""
361                         },
362                 },
363                 {
364                         expectEmail: "",
365                         setup: func() {
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 = ""
372                         },
373                 },
374                 {
375                         expectEmail: "user@oidc.example.com",
376                         setup: func() {
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 = ""
383                         },
384                 },
385                 {
386                         expectEmail: "alt_email@example.com",
387                         setup: func() {
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"
394                         },
395                 },
396         } {
397                 trial.setup()
398                 if s.railsSpy != nil {
399                         s.railsSpy.Close()
400                 }
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)
404
405                 state := s.startLogin(c, func(form url.Values) {
406                         c.Check(form.Get("testkey"), check.Equals, "testvalue")
407                 })
408                 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
409                         Code:  s.fakeProvider.ValidCode,
410                         State: state,
411                 })
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, "")
416                         continue
417                 }
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)
425
426                 switch s.cluster.Login.OpenIDConnect.UsernameClaim {
427                 case "alt_username":
428                         c.Check(authinfo.Username, check.Equals, "desired-username")
429                 case "":
430                         c.Check(authinfo.Username, check.Equals, "")
431                 default:
432                         c.Fail() // bad test case
433                 }
434         }
435 }
436
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")
443         })
444         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
445                 Code:  s.fakeProvider.ValidCode,
446                 State: state,
447         })
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}`)
456
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)
462
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)
470
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.*`)
479 }
480
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{}{
486                         {
487                                 "metadata":   map[string]interface{}{"primary": false},
488                                 "givenName":  "Joe",
489                                 "familyName": "Smith",
490                         },
491                         {
492                                 "metadata":   map[string]interface{}{"primary": true},
493                                 "givenName":  "Joseph",
494                                 "familyName": "Psmith",
495                         },
496                 },
497         }
498         state := s.startLogin(c)
499         s.localdb.Login(context.Background(), arvados.LoginOptions{
500                 Code:  s.fakeProvider.ValidCode,
501                 State: state,
502         })
503
504         authinfo := getCallbackAuthInfo(c, s.railsSpy)
505         c.Check(authinfo.FirstName, check.Equals, "Joseph")
506         c.Check(authinfo.LastName, check.Equals, "Psmith")
507 }
508
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,
517                 State: state,
518         })
519
520         authinfo := getCallbackAuthInfo(c, s.railsSpy)
521         c.Check(authinfo.FirstName, check.Equals, "Joe P.")
522         c.Check(authinfo.LastName, check.Equals, "Smith")
523 }
524
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{}{
530                         {
531                                 "metadata": map[string]interface{}{"verified": true},
532                                 "value":    "joe.smith@work.example.com",
533                         },
534                         {
535                                 "value": "joe.smith@unverified.example.com", // unverified, so this one will be ignored
536                         },
537                         {
538                                 "metadata": map[string]interface{}{"verified": true},
539                                 "value":    "joe.smith@home.example.com",
540                         },
541                 },
542         }
543         state := s.startLogin(c)
544         s.localdb.Login(context.Background(), arvados.LoginOptions{
545                 Code:  s.fakeProvider.ValidCode,
546                 State: state,
547         })
548
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"})
552 }
553
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{}{
559                         {
560                                 "metadata": map[string]interface{}{"verified": true, "primary": true},
561                                 "value":    "joe.smith@primary.example.com",
562                         },
563                         {
564                                 "metadata": map[string]interface{}{"verified": true},
565                                 "value":    "joe.smith@alternate.example.com",
566                         },
567                         {
568                                 "metadata": map[string]interface{}{"verified": true},
569                                 "value":    "jsmith+123@preferdomainforusername.example.com",
570                         },
571                 },
572         }
573         state := s.startLogin(c)
574         s.localdb.Login(context.Background(), arvados.LoginOptions{
575                 Code:  s.fakeProvider.ValidCode,
576                 State: state,
577         })
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")
582 }
583
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{}{
589                         {
590                                 "metadata": map[string]interface{}{"verified": true},
591                                 "value":    "joe.smith@work.example.com",
592                         },
593                         {
594                                 "metadata": map[string]interface{}{"verified": true},
595                                 "value":    "joe.smith@home.example.com",
596                         },
597                 },
598         }
599         state := s.startLogin(c)
600         s.localdb.Login(context.Background(), arvados.LoginOptions{
601                 Code:  s.fakeProvider.ValidCode,
602                 State: state,
603         })
604
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, "")
609 }
610
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 {
621                 fn(target.Query())
622         }
623         s.cluster.Login.OpenIDConnect.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"}
624         return
625 }
626
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)
638                         return
639                 }
640         }
641         c.Error("callback not found")
642         return
643 }