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