17704: Check scope before accepting OIDC access tokens.
[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.ValidCode = fmt.Sprintf("abcdefgh-%d", time.Now().Unix())
60         s.fakeProvider.PeopleAPIResponse = map[string]interface{}{}
61
62         cfg, err := config.NewLoader(nil, ctxlog.TestLogger(c)).Load()
63         c.Assert(err, check.IsNil)
64         s.cluster, err = cfg.GetCluster("")
65         c.Assert(err, check.IsNil)
66         s.cluster.Login.SSO.Enable = false
67         s.cluster.Login.Google.Enable = true
68         s.cluster.Login.Google.ClientID = "test%client$id"
69         s.cluster.Login.Google.ClientSecret = "test#client/secret"
70         s.cluster.Users.PreferDomainForUsername = "PreferDomainForUsername.example.com"
71         s.fakeProvider.ValidClientID = "test%client$id"
72         s.fakeProvider.ValidClientSecret = "test#client/secret"
73
74         s.localdb = NewConn(s.cluster)
75         c.Assert(s.localdb.loginController, check.FitsTypeOf, (*oidcLoginController)(nil))
76         s.localdb.loginController.(*oidcLoginController).Issuer = s.fakeProvider.Issuer.URL
77         s.localdb.loginController.(*oidcLoginController).peopleAPIBasePath = s.fakeProvider.PeopleAPI.URL
78
79         s.railsSpy = arvadostest.NewProxy(c, s.cluster.Services.RailsAPI)
80         *s.localdb.railsProxy = *rpc.NewConn(s.cluster.ClusterID, s.railsSpy.URL, true, rpc.PassthroughTokenProvider)
81 }
82
83 func (s *OIDCLoginSuite) TearDownTest(c *check.C) {
84         s.railsSpy.Close()
85 }
86
87 func (s *OIDCLoginSuite) TestGoogleLogout(c *check.C) {
88         resp, err := s.localdb.Logout(context.Background(), arvados.LogoutOptions{ReturnTo: "https://foo.example.com/bar"})
89         c.Check(err, check.IsNil)
90         c.Check(resp.RedirectLocation, check.Equals, "https://foo.example.com/bar")
91 }
92
93 func (s *OIDCLoginSuite) TestGoogleLogin_Start_Bogus(c *check.C) {
94         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{})
95         c.Check(err, check.IsNil)
96         c.Check(resp.RedirectLocation, check.Equals, "")
97         c.Check(resp.HTML.String(), check.Matches, `.*missing return_to parameter.*`)
98 }
99
100 func (s *OIDCLoginSuite) TestGoogleLogin_Start(c *check.C) {
101         for _, remote := range []string{"", "zzzzz"} {
102                 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{Remote: remote, ReturnTo: "https://app.example.com/foo?bar"})
103                 c.Check(err, check.IsNil)
104                 target, err := url.Parse(resp.RedirectLocation)
105                 c.Check(err, check.IsNil)
106                 issuerURL, _ := url.Parse(s.fakeProvider.Issuer.URL)
107                 c.Check(target.Host, check.Equals, issuerURL.Host)
108                 q := target.Query()
109                 c.Check(q.Get("client_id"), check.Equals, "test%client$id")
110                 state := s.localdb.loginController.(*oidcLoginController).parseOAuth2State(q.Get("state"))
111                 c.Check(state.verify([]byte(s.cluster.SystemRootToken)), check.Equals, true)
112                 c.Check(state.Time, check.Not(check.Equals), 0)
113                 c.Check(state.Remote, check.Equals, remote)
114                 c.Check(state.ReturnTo, check.Equals, "https://app.example.com/foo?bar")
115         }
116 }
117
118 func (s *OIDCLoginSuite) TestGoogleLogin_InvalidCode(c *check.C) {
119         state := s.startLogin(c)
120         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
121                 Code:  "first-try-a-bogus-code",
122                 State: state,
123         })
124         c.Check(err, check.IsNil)
125         c.Check(resp.RedirectLocation, check.Equals, "")
126         c.Check(resp.HTML.String(), check.Matches, `(?ms).*error in OAuth2 exchange.*cannot fetch token.*`)
127 }
128
129 func (s *OIDCLoginSuite) TestGoogleLogin_InvalidState(c *check.C) {
130         s.startLogin(c)
131         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
132                 Code:  s.fakeProvider.ValidCode,
133                 State: "bogus-state",
134         })
135         c.Check(err, check.IsNil)
136         c.Check(resp.RedirectLocation, check.Equals, "")
137         c.Check(resp.HTML.String(), check.Matches, `(?ms).*invalid OAuth2 state.*`)
138 }
139
140 func (s *OIDCLoginSuite) setupPeopleAPIError(c *check.C) {
141         s.fakeProvider.PeopleAPI = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
142                 w.WriteHeader(http.StatusForbidden)
143                 fmt.Fprintln(w, `Error 403: accessNotConfigured`)
144         }))
145         s.localdb.loginController.(*oidcLoginController).peopleAPIBasePath = s.fakeProvider.PeopleAPI.URL
146 }
147
148 func (s *OIDCLoginSuite) TestGoogleLogin_PeopleAPIDisabled(c *check.C) {
149         s.localdb.loginController.(*oidcLoginController).UseGooglePeopleAPI = false
150         s.fakeProvider.AuthEmail = "joe.smith@primary.example.com"
151         s.setupPeopleAPIError(c)
152         state := s.startLogin(c)
153         _, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
154                 Code:  s.fakeProvider.ValidCode,
155                 State: state,
156         })
157         c.Check(err, check.IsNil)
158         authinfo := getCallbackAuthInfo(c, s.railsSpy)
159         c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
160 }
161
162 func (s *OIDCLoginSuite) TestConfig(c *check.C) {
163         s.cluster.Login.Google.Enable = false
164         s.cluster.Login.OpenIDConnect.Enable = true
165         s.cluster.Login.OpenIDConnect.Issuer = "https://accounts.example.com/"
166         s.cluster.Login.OpenIDConnect.ClientID = "oidc-client-id"
167         s.cluster.Login.OpenIDConnect.ClientSecret = "oidc-client-secret"
168         s.cluster.Login.OpenIDConnect.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"}
169         localdb := NewConn(s.cluster)
170         ctrl := localdb.loginController.(*oidcLoginController)
171         c.Check(ctrl.Issuer, check.Equals, "https://accounts.example.com/")
172         c.Check(ctrl.ClientID, check.Equals, "oidc-client-id")
173         c.Check(ctrl.ClientSecret, check.Equals, "oidc-client-secret")
174         c.Check(ctrl.UseGooglePeopleAPI, check.Equals, false)
175         c.Check(ctrl.AuthParams["testkey"], check.Equals, "testvalue")
176
177         for _, enableAltEmails := range []bool{false, true} {
178                 s.cluster.Login.OpenIDConnect.Enable = false
179                 s.cluster.Login.Google.Enable = true
180                 s.cluster.Login.Google.ClientID = "google-client-id"
181                 s.cluster.Login.Google.ClientSecret = "google-client-secret"
182                 s.cluster.Login.Google.AlternateEmailAddresses = enableAltEmails
183                 s.cluster.Login.Google.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"}
184                 localdb = NewConn(s.cluster)
185                 ctrl = localdb.loginController.(*oidcLoginController)
186                 c.Check(ctrl.Issuer, check.Equals, "https://accounts.google.com")
187                 c.Check(ctrl.ClientID, check.Equals, "google-client-id")
188                 c.Check(ctrl.ClientSecret, check.Equals, "google-client-secret")
189                 c.Check(ctrl.UseGooglePeopleAPI, check.Equals, enableAltEmails)
190                 c.Check(ctrl.AuthParams["testkey"], check.Equals, "testvalue")
191         }
192 }
193
194 func (s *OIDCLoginSuite) TestGoogleLogin_PeopleAPIError(c *check.C) {
195         s.setupPeopleAPIError(c)
196         state := s.startLogin(c)
197         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
198                 Code:  s.fakeProvider.ValidCode,
199                 State: state,
200         })
201         c.Check(err, check.IsNil)
202         c.Check(resp.RedirectLocation, check.Equals, "")
203 }
204
205 func (s *OIDCLoginSuite) TestOIDCAuthorizer(c *check.C) {
206         s.cluster.Login.Google.Enable = false
207         s.cluster.Login.OpenIDConnect.Enable = true
208         json.Unmarshal([]byte(fmt.Sprintf("%q", s.fakeProvider.Issuer.URL)), &s.cluster.Login.OpenIDConnect.Issuer)
209         s.cluster.Login.OpenIDConnect.ClientID = "oidc#client#id"
210         s.cluster.Login.OpenIDConnect.ClientSecret = "oidc#client#secret"
211         s.cluster.Login.OpenIDConnect.AcceptAccessTokenScope = "*"
212         s.fakeProvider.ValidClientID = "oidc#client#id"
213         s.fakeProvider.ValidClientSecret = "oidc#client#secret"
214         db := arvadostest.DB(c, s.cluster)
215
216         tokenCacheTTL = time.Millisecond
217         tokenCacheRaceWindow = time.Millisecond
218         tokenCacheNegativeTTL = time.Millisecond
219
220         oidcAuthorizer := OIDCAccessTokenAuthorizer(s.cluster, func(context.Context) (*sqlx.DB, error) { return db, nil })
221         accessToken := s.fakeProvider.ValidAccessToken()
222
223         mac := hmac.New(sha256.New, []byte(s.cluster.SystemRootToken))
224         io.WriteString(mac, accessToken)
225         apiToken := fmt.Sprintf("%x", mac.Sum(nil))
226
227         cleanup := func() {
228                 _, err := db.Exec(`delete from api_client_authorizations where api_token=$1`, apiToken)
229                 c.Check(err, check.IsNil)
230         }
231         cleanup()
232         defer cleanup()
233
234         ctx := auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{accessToken}})
235         var exp1 time.Time
236         oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) {
237                 creds, ok := auth.FromContext(ctx)
238                 c.Assert(ok, check.Equals, true)
239                 c.Assert(creds.Tokens, check.HasLen, 1)
240                 c.Check(creds.Tokens[0], check.Equals, accessToken)
241
242                 err := db.QueryRowContext(ctx, `select expires_at at time zone 'UTC' from api_client_authorizations where api_token=$1`, apiToken).Scan(&exp1)
243                 c.Check(err, check.IsNil)
244                 c.Check(exp1.Sub(time.Now()) > -time.Second, check.Equals, true)
245                 c.Check(exp1.Sub(time.Now()) < time.Second, check.Equals, true)
246                 return nil, nil
247         })(ctx, nil)
248
249         // If the token is used again after the in-memory cache
250         // expires, oidcAuthorizer must re-check the token and update
251         // the expires_at value in the database.
252         time.Sleep(3 * time.Millisecond)
253         oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) {
254                 var exp time.Time
255                 err := db.QueryRowContext(ctx, `select expires_at at time zone 'UTC' from api_client_authorizations where api_token=$1`, apiToken).Scan(&exp)
256                 c.Check(err, check.IsNil)
257                 c.Check(exp.Sub(exp1) > 0, check.Equals, true)
258                 c.Check(exp.Sub(exp1) < time.Second, check.Equals, true)
259                 return nil, nil
260         })(ctx, nil)
261
262         s.fakeProvider.AccessTokenPayload = map[string]interface{}{"scope": "openid profile foobar"}
263         accessToken = s.fakeProvider.ValidAccessToken()
264         ctx = auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{accessToken}})
265
266         mac = hmac.New(sha256.New, []byte(s.cluster.SystemRootToken))
267         io.WriteString(mac, accessToken)
268         apiToken = fmt.Sprintf("%x", mac.Sum(nil))
269
270         for _, trial := range []struct {
271                 configScope string
272                 acceptable  bool
273                 shouldRun   bool
274         }{
275                 {"foobar", true, true},
276                 {"foo", false, false},
277                 {"*", true, true},
278                 {"", false, true},
279         } {
280                 c.Logf("trial = %+v", trial)
281                 cleanup()
282                 s.cluster.Login.OpenIDConnect.AcceptAccessTokenScope = trial.configScope
283                 oidcAuthorizer = OIDCAccessTokenAuthorizer(s.cluster, func(context.Context) (*sqlx.DB, error) { return db, nil })
284                 checked := false
285                 oidcAuthorizer.WrapCalls(func(ctx context.Context, opts interface{}) (interface{}, error) {
286                         var n int
287                         err := db.QueryRowContext(ctx, `select count(*) from api_client_authorizations where api_token=$1`, apiToken).Scan(&n)
288                         c.Check(err, check.IsNil)
289                         if trial.acceptable {
290                                 c.Check(n, check.Equals, 1)
291                         } else {
292                                 c.Check(n, check.Equals, 0)
293                         }
294                         checked = true
295                         return nil, nil
296                 })(ctx, nil)
297                 c.Check(checked, check.Equals, trial.shouldRun)
298         }
299 }
300
301 func (s *OIDCLoginSuite) TestGenericOIDCLogin(c *check.C) {
302         s.cluster.Login.Google.Enable = false
303         s.cluster.Login.OpenIDConnect.Enable = true
304         json.Unmarshal([]byte(fmt.Sprintf("%q", s.fakeProvider.Issuer.URL)), &s.cluster.Login.OpenIDConnect.Issuer)
305         s.cluster.Login.OpenIDConnect.ClientID = "oidc#client#id"
306         s.cluster.Login.OpenIDConnect.ClientSecret = "oidc#client#secret"
307         s.cluster.Login.OpenIDConnect.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"}
308         s.fakeProvider.ValidClientID = "oidc#client#id"
309         s.fakeProvider.ValidClientSecret = "oidc#client#secret"
310         for _, trial := range []struct {
311                 expectEmail string // "" if failure expected
312                 setup       func()
313         }{
314                 {
315                         expectEmail: "user@oidc.example.com",
316                         setup: func() {
317                                 c.Log("=== succeed because email_verified is false but not required")
318                                 s.fakeProvider.AuthEmail = "user@oidc.example.com"
319                                 s.fakeProvider.AuthEmailVerified = false
320                                 s.cluster.Login.OpenIDConnect.EmailClaim = "email"
321                                 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = ""
322                                 s.cluster.Login.OpenIDConnect.UsernameClaim = ""
323                         },
324                 },
325                 {
326                         expectEmail: "",
327                         setup: func() {
328                                 c.Log("=== fail because email_verified is false and required")
329                                 s.fakeProvider.AuthEmail = "user@oidc.example.com"
330                                 s.fakeProvider.AuthEmailVerified = false
331                                 s.cluster.Login.OpenIDConnect.EmailClaim = "email"
332                                 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = "email_verified"
333                                 s.cluster.Login.OpenIDConnect.UsernameClaim = ""
334                         },
335                 },
336                 {
337                         expectEmail: "user@oidc.example.com",
338                         setup: func() {
339                                 c.Log("=== succeed because email_verified is false but config uses custom 'verified' claim")
340                                 s.fakeProvider.AuthEmail = "user@oidc.example.com"
341                                 s.fakeProvider.AuthEmailVerified = false
342                                 s.cluster.Login.OpenIDConnect.EmailClaim = "email"
343                                 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = "alt_verified"
344                                 s.cluster.Login.OpenIDConnect.UsernameClaim = ""
345                         },
346                 },
347                 {
348                         expectEmail: "alt_email@example.com",
349                         setup: func() {
350                                 c.Log("=== succeed with custom 'email' and 'email_verified' claims")
351                                 s.fakeProvider.AuthEmail = "bad@wrong.example.com"
352                                 s.fakeProvider.AuthEmailVerified = false
353                                 s.cluster.Login.OpenIDConnect.EmailClaim = "alt_email"
354                                 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = "alt_verified"
355                                 s.cluster.Login.OpenIDConnect.UsernameClaim = "alt_username"
356                         },
357                 },
358         } {
359                 trial.setup()
360                 if s.railsSpy != nil {
361                         s.railsSpy.Close()
362                 }
363                 s.railsSpy = arvadostest.NewProxy(c, s.cluster.Services.RailsAPI)
364                 s.localdb = NewConn(s.cluster)
365                 *s.localdb.railsProxy = *rpc.NewConn(s.cluster.ClusterID, s.railsSpy.URL, true, rpc.PassthroughTokenProvider)
366
367                 state := s.startLogin(c, func(form url.Values) {
368                         c.Check(form.Get("testkey"), check.Equals, "testvalue")
369                 })
370                 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
371                         Code:  s.fakeProvider.ValidCode,
372                         State: state,
373                 })
374                 c.Assert(err, check.IsNil)
375                 if trial.expectEmail == "" {
376                         c.Check(resp.HTML.String(), check.Matches, `(?ms).*Login error.*`)
377                         c.Check(resp.RedirectLocation, check.Equals, "")
378                         continue
379                 }
380                 c.Check(resp.HTML.String(), check.Equals, "")
381                 target, err := url.Parse(resp.RedirectLocation)
382                 c.Assert(err, check.IsNil)
383                 token := target.Query().Get("api_token")
384                 c.Check(token, check.Matches, `v2/zzzzz-gj3su-.{15}/.{32,50}`)
385                 authinfo := getCallbackAuthInfo(c, s.railsSpy)
386                 c.Check(authinfo.Email, check.Equals, trial.expectEmail)
387
388                 switch s.cluster.Login.OpenIDConnect.UsernameClaim {
389                 case "alt_username":
390                         c.Check(authinfo.Username, check.Equals, "desired-username")
391                 case "":
392                         c.Check(authinfo.Username, check.Equals, "")
393                 default:
394                         c.Fail() // bad test case
395                 }
396         }
397 }
398
399 func (s *OIDCLoginSuite) TestGoogleLogin_Success(c *check.C) {
400         s.cluster.Login.Google.AuthenticationRequestParameters["prompt"] = "consent"
401         s.cluster.Login.Google.AuthenticationRequestParameters["foo"] = "bar"
402         state := s.startLogin(c, func(form url.Values) {
403                 c.Check(form.Get("foo"), check.Equals, "bar")
404                 c.Check(form.Get("prompt"), check.Equals, "consent")
405         })
406         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
407                 Code:  s.fakeProvider.ValidCode,
408                 State: state,
409         })
410         c.Check(err, check.IsNil)
411         c.Check(resp.HTML.String(), check.Equals, "")
412         target, err := url.Parse(resp.RedirectLocation)
413         c.Check(err, check.IsNil)
414         c.Check(target.Host, check.Equals, "app.example.com")
415         c.Check(target.Path, check.Equals, "/foo")
416         token := target.Query().Get("api_token")
417         c.Check(token, check.Matches, `v2/zzzzz-gj3su-.{15}/.{32,50}`)
418
419         authinfo := getCallbackAuthInfo(c, s.railsSpy)
420         c.Check(authinfo.FirstName, check.Equals, "Fake User")
421         c.Check(authinfo.LastName, check.Equals, "Name")
422         c.Check(authinfo.Email, check.Equals, "active-user@arvados.local")
423         c.Check(authinfo.AlternateEmails, check.HasLen, 0)
424
425         // Try using the returned Arvados token.
426         c.Logf("trying an API call with new token %q", token)
427         ctx := auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{token}})
428         cl, err := s.localdb.CollectionList(ctx, arvados.ListOptions{Limit: -1})
429         c.Check(cl.ItemsAvailable, check.Not(check.Equals), 0)
430         c.Check(cl.Items, check.Not(check.HasLen), 0)
431         c.Check(err, check.IsNil)
432
433         // Might as well check that bogus tokens aren't accepted.
434         badtoken := token + "plussomeboguschars"
435         c.Logf("trying an API call with mangled token %q", badtoken)
436         ctx = auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{badtoken}})
437         cl, err = s.localdb.CollectionList(ctx, arvados.ListOptions{Limit: -1})
438         c.Check(cl.Items, check.HasLen, 0)
439         c.Check(err, check.NotNil)
440         c.Check(err, check.ErrorMatches, `.*401 Unauthorized: Not logged in.*`)
441 }
442
443 func (s *OIDCLoginSuite) TestGoogleLogin_RealName(c *check.C) {
444         s.fakeProvider.AuthEmail = "joe.smith@primary.example.com"
445         s.fakeProvider.PeopleAPIResponse = map[string]interface{}{
446                 "names": []map[string]interface{}{
447                         {
448                                 "metadata":   map[string]interface{}{"primary": false},
449                                 "givenName":  "Joe",
450                                 "familyName": "Smith",
451                         },
452                         {
453                                 "metadata":   map[string]interface{}{"primary": true},
454                                 "givenName":  "Joseph",
455                                 "familyName": "Psmith",
456                         },
457                 },
458         }
459         state := s.startLogin(c)
460         s.localdb.Login(context.Background(), arvados.LoginOptions{
461                 Code:  s.fakeProvider.ValidCode,
462                 State: state,
463         })
464
465         authinfo := getCallbackAuthInfo(c, s.railsSpy)
466         c.Check(authinfo.FirstName, check.Equals, "Joseph")
467         c.Check(authinfo.LastName, check.Equals, "Psmith")
468 }
469
470 func (s *OIDCLoginSuite) TestGoogleLogin_OIDCRealName(c *check.C) {
471         s.fakeProvider.AuthName = "Joe P. Smith"
472         s.fakeProvider.AuthEmail = "joe.smith@primary.example.com"
473         state := s.startLogin(c)
474         s.localdb.Login(context.Background(), arvados.LoginOptions{
475                 Code:  s.fakeProvider.ValidCode,
476                 State: state,
477         })
478
479         authinfo := getCallbackAuthInfo(c, s.railsSpy)
480         c.Check(authinfo.FirstName, check.Equals, "Joe P.")
481         c.Check(authinfo.LastName, check.Equals, "Smith")
482 }
483
484 // People API returns some additional email addresses.
485 func (s *OIDCLoginSuite) TestGoogleLogin_AlternateEmailAddresses(c *check.C) {
486         s.fakeProvider.AuthEmail = "joe.smith@primary.example.com"
487         s.fakeProvider.PeopleAPIResponse = map[string]interface{}{
488                 "emailAddresses": []map[string]interface{}{
489                         {
490                                 "metadata": map[string]interface{}{"verified": true},
491                                 "value":    "joe.smith@work.example.com",
492                         },
493                         {
494                                 "value": "joe.smith@unverified.example.com", // unverified, so this one will be ignored
495                         },
496                         {
497                                 "metadata": map[string]interface{}{"verified": true},
498                                 "value":    "joe.smith@home.example.com",
499                         },
500                 },
501         }
502         state := s.startLogin(c)
503         s.localdb.Login(context.Background(), arvados.LoginOptions{
504                 Code:  s.fakeProvider.ValidCode,
505                 State: state,
506         })
507
508         authinfo := getCallbackAuthInfo(c, s.railsSpy)
509         c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
510         c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@home.example.com", "joe.smith@work.example.com"})
511 }
512
513 // Primary address is not the one initially returned by oidc.
514 func (s *OIDCLoginSuite) TestGoogleLogin_AlternateEmailAddresses_Primary(c *check.C) {
515         s.fakeProvider.AuthEmail = "joe.smith@alternate.example.com"
516         s.fakeProvider.PeopleAPIResponse = map[string]interface{}{
517                 "emailAddresses": []map[string]interface{}{
518                         {
519                                 "metadata": map[string]interface{}{"verified": true, "primary": true},
520                                 "value":    "joe.smith@primary.example.com",
521                         },
522                         {
523                                 "metadata": map[string]interface{}{"verified": true},
524                                 "value":    "joe.smith@alternate.example.com",
525                         },
526                         {
527                                 "metadata": map[string]interface{}{"verified": true},
528                                 "value":    "jsmith+123@preferdomainforusername.example.com",
529                         },
530                 },
531         }
532         state := s.startLogin(c)
533         s.localdb.Login(context.Background(), arvados.LoginOptions{
534                 Code:  s.fakeProvider.ValidCode,
535                 State: state,
536         })
537         authinfo := getCallbackAuthInfo(c, s.railsSpy)
538         c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
539         c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@alternate.example.com", "jsmith+123@preferdomainforusername.example.com"})
540         c.Check(authinfo.Username, check.Equals, "jsmith")
541 }
542
543 func (s *OIDCLoginSuite) TestGoogleLogin_NoPrimaryEmailAddress(c *check.C) {
544         s.fakeProvider.AuthEmail = "joe.smith@unverified.example.com"
545         s.fakeProvider.AuthEmailVerified = false
546         s.fakeProvider.PeopleAPIResponse = map[string]interface{}{
547                 "emailAddresses": []map[string]interface{}{
548                         {
549                                 "metadata": map[string]interface{}{"verified": true},
550                                 "value":    "joe.smith@work.example.com",
551                         },
552                         {
553                                 "metadata": map[string]interface{}{"verified": true},
554                                 "value":    "joe.smith@home.example.com",
555                         },
556                 },
557         }
558         state := s.startLogin(c)
559         s.localdb.Login(context.Background(), arvados.LoginOptions{
560                 Code:  s.fakeProvider.ValidCode,
561                 State: state,
562         })
563
564         authinfo := getCallbackAuthInfo(c, s.railsSpy)
565         c.Check(authinfo.Email, check.Equals, "joe.smith@work.example.com") // first verified email in People response
566         c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@home.example.com"})
567         c.Check(authinfo.Username, check.Equals, "")
568 }
569
570 func (s *OIDCLoginSuite) startLogin(c *check.C, checks ...func(url.Values)) (state string) {
571         // Initiate login, but instead of following the redirect to
572         // the provider, just grab state from the redirect URL.
573         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{ReturnTo: "https://app.example.com/foo?bar"})
574         c.Check(err, check.IsNil)
575         target, err := url.Parse(resp.RedirectLocation)
576         c.Check(err, check.IsNil)
577         state = target.Query().Get("state")
578         c.Check(state, check.Not(check.Equals), "")
579         for _, fn := range checks {
580                 fn(target.Query())
581         }
582         s.cluster.Login.OpenIDConnect.AuthenticationRequestParameters = map[string]string{"testkey": "testvalue"}
583         return
584 }
585
586 func getCallbackAuthInfo(c *check.C, railsSpy *arvadostest.Proxy) (authinfo rpc.UserSessionAuthInfo) {
587         for _, dump := range railsSpy.RequestDumps {
588                 c.Logf("spied request: %q", dump)
589                 split := bytes.Split(dump, []byte("\r\n\r\n"))
590                 c.Assert(split, check.HasLen, 2)
591                 hdr, body := string(split[0]), string(split[1])
592                 if strings.Contains(hdr, "POST /auth/controller/callback") {
593                         vs, err := url.ParseQuery(body)
594                         c.Check(json.Unmarshal([]byte(vs.Get("auth_info")), &authinfo), check.IsNil)
595                         c.Check(err, check.IsNil)
596                         sort.Strings(authinfo.AlternateEmails)
597                         return
598                 }
599         }
600         c.Error("callback not found")
601         return
602 }