Merge branch '16791-api-flaky-test-fix'
[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/rand"
11         "crypto/rsa"
12         "encoding/base64"
13         "encoding/json"
14         "fmt"
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         check "gopkg.in/check.v1"
30         jose "gopkg.in/square/go-jose.v2"
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         fakeIssuer            *httptest.Server
45         fakePeopleAPI         *httptest.Server
46         fakePeopleAPIResponse map[string]interface{}
47         issuerKey             *rsa.PrivateKey
48
49         // expected token request
50         validCode         string
51         validClientID     string
52         validClientSecret string
53         // desired response from token endpoint
54         authEmail         string
55         authEmailVerified bool
56         authName          string
57 }
58
59 func (s *OIDCLoginSuite) TearDownSuite(c *check.C) {
60         // Undo any changes/additions to the user database so they
61         // don't affect subsequent tests.
62         arvadostest.ResetEnv()
63         c.Check(arvados.NewClientFromEnv().RequestAndDecode(nil, "POST", "database/reset", nil, nil), check.IsNil)
64 }
65
66 func (s *OIDCLoginSuite) SetUpTest(c *check.C) {
67         var err error
68         s.issuerKey, err = rsa.GenerateKey(rand.Reader, 2048)
69         c.Assert(err, check.IsNil)
70
71         s.authEmail = "active-user@arvados.local"
72         s.authEmailVerified = true
73         s.authName = "Fake User Name"
74         s.fakeIssuer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
75                 req.ParseForm()
76                 c.Logf("fakeIssuer: got req: %s %s %s", req.Method, req.URL, req.Form)
77                 w.Header().Set("Content-Type", "application/json")
78                 switch req.URL.Path {
79                 case "/.well-known/openid-configuration":
80                         json.NewEncoder(w).Encode(map[string]interface{}{
81                                 "issuer":                 s.fakeIssuer.URL,
82                                 "authorization_endpoint": s.fakeIssuer.URL + "/auth",
83                                 "token_endpoint":         s.fakeIssuer.URL + "/token",
84                                 "jwks_uri":               s.fakeIssuer.URL + "/jwks",
85                                 "userinfo_endpoint":      s.fakeIssuer.URL + "/userinfo",
86                         })
87                 case "/token":
88                         var clientID, clientSecret string
89                         auth, _ := base64.StdEncoding.DecodeString(strings.TrimPrefix(req.Header.Get("Authorization"), "Basic "))
90                         authsplit := strings.Split(string(auth), ":")
91                         if len(authsplit) == 2 {
92                                 clientID, _ = url.QueryUnescape(authsplit[0])
93                                 clientSecret, _ = url.QueryUnescape(authsplit[1])
94                         }
95                         if clientID != s.validClientID || clientSecret != s.validClientSecret {
96                                 c.Logf("fakeIssuer: expected (%q, %q) got (%q, %q)", s.validClientID, s.validClientSecret, clientID, clientSecret)
97                                 w.WriteHeader(http.StatusUnauthorized)
98                                 return
99                         }
100
101                         if req.Form.Get("code") != s.validCode || s.validCode == "" {
102                                 w.WriteHeader(http.StatusUnauthorized)
103                                 return
104                         }
105                         idToken, _ := json.Marshal(map[string]interface{}{
106                                 "iss":            s.fakeIssuer.URL,
107                                 "aud":            []string{clientID},
108                                 "sub":            "fake-user-id",
109                                 "exp":            time.Now().UTC().Add(time.Minute).Unix(),
110                                 "iat":            time.Now().UTC().Unix(),
111                                 "nonce":          "fake-nonce",
112                                 "email":          s.authEmail,
113                                 "email_verified": s.authEmailVerified,
114                                 "name":           s.authName,
115                                 "alt_verified":   true,                    // for custom claim tests
116                                 "alt_email":      "alt_email@example.com", // for custom claim tests
117                                 "alt_username":   "desired-username",      // for custom claim tests
118                         })
119                         json.NewEncoder(w).Encode(struct {
120                                 AccessToken  string `json:"access_token"`
121                                 TokenType    string `json:"token_type"`
122                                 RefreshToken string `json:"refresh_token"`
123                                 ExpiresIn    int32  `json:"expires_in"`
124                                 IDToken      string `json:"id_token"`
125                         }{
126                                 AccessToken:  s.fakeToken(c, []byte("fake access token")),
127                                 TokenType:    "Bearer",
128                                 RefreshToken: "test-refresh-token",
129                                 ExpiresIn:    30,
130                                 IDToken:      s.fakeToken(c, idToken),
131                         })
132                 case "/jwks":
133                         json.NewEncoder(w).Encode(jose.JSONWebKeySet{
134                                 Keys: []jose.JSONWebKey{
135                                         {Key: s.issuerKey.Public(), Algorithm: string(jose.RS256), KeyID: ""},
136                                 },
137                         })
138                 case "/auth":
139                         w.WriteHeader(http.StatusInternalServerError)
140                 case "/userinfo":
141                         w.WriteHeader(http.StatusInternalServerError)
142                 default:
143                         w.WriteHeader(http.StatusNotFound)
144                 }
145         }))
146         s.validCode = fmt.Sprintf("abcdefgh-%d", time.Now().Unix())
147
148         s.fakePeopleAPI = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
149                 req.ParseForm()
150                 c.Logf("fakePeopleAPI: got req: %s %s %s", req.Method, req.URL, req.Form)
151                 w.Header().Set("Content-Type", "application/json")
152                 switch req.URL.Path {
153                 case "/v1/people/me":
154                         if f := req.Form.Get("personFields"); f != "emailAddresses,names" {
155                                 w.WriteHeader(http.StatusBadRequest)
156                                 break
157                         }
158                         json.NewEncoder(w).Encode(s.fakePeopleAPIResponse)
159                 default:
160                         w.WriteHeader(http.StatusNotFound)
161                 }
162         }))
163         s.fakePeopleAPIResponse = map[string]interface{}{}
164
165         cfg, err := config.NewLoader(nil, ctxlog.TestLogger(c)).Load()
166         c.Assert(err, check.IsNil)
167         s.cluster, err = cfg.GetCluster("")
168         c.Assert(err, check.IsNil)
169         s.cluster.Login.SSO.Enable = false
170         s.cluster.Login.Google.Enable = true
171         s.cluster.Login.Google.ClientID = "test%client$id"
172         s.cluster.Login.Google.ClientSecret = "test#client/secret"
173         s.cluster.Users.PreferDomainForUsername = "PreferDomainForUsername.example.com"
174         s.validClientID = "test%client$id"
175         s.validClientSecret = "test#client/secret"
176
177         s.localdb = NewConn(s.cluster)
178         c.Assert(s.localdb.loginController, check.FitsTypeOf, (*oidcLoginController)(nil))
179         s.localdb.loginController.(*oidcLoginController).Issuer = s.fakeIssuer.URL
180         s.localdb.loginController.(*oidcLoginController).peopleAPIBasePath = s.fakePeopleAPI.URL
181
182         s.railsSpy = arvadostest.NewProxy(c, s.cluster.Services.RailsAPI)
183         *s.localdb.railsProxy = *rpc.NewConn(s.cluster.ClusterID, s.railsSpy.URL, true, rpc.PassthroughTokenProvider)
184 }
185
186 func (s *OIDCLoginSuite) TearDownTest(c *check.C) {
187         s.railsSpy.Close()
188 }
189
190 func (s *OIDCLoginSuite) TestGoogleLogout(c *check.C) {
191         resp, err := s.localdb.Logout(context.Background(), arvados.LogoutOptions{ReturnTo: "https://foo.example.com/bar"})
192         c.Check(err, check.IsNil)
193         c.Check(resp.RedirectLocation, check.Equals, "https://foo.example.com/bar")
194 }
195
196 func (s *OIDCLoginSuite) TestGoogleLogin_Start_Bogus(c *check.C) {
197         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{})
198         c.Check(err, check.IsNil)
199         c.Check(resp.RedirectLocation, check.Equals, "")
200         c.Check(resp.HTML.String(), check.Matches, `.*missing return_to parameter.*`)
201 }
202
203 func (s *OIDCLoginSuite) TestGoogleLogin_Start(c *check.C) {
204         for _, remote := range []string{"", "zzzzz"} {
205                 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{Remote: remote, ReturnTo: "https://app.example.com/foo?bar"})
206                 c.Check(err, check.IsNil)
207                 target, err := url.Parse(resp.RedirectLocation)
208                 c.Check(err, check.IsNil)
209                 issuerURL, _ := url.Parse(s.fakeIssuer.URL)
210                 c.Check(target.Host, check.Equals, issuerURL.Host)
211                 q := target.Query()
212                 c.Check(q.Get("client_id"), check.Equals, "test%client$id")
213                 state := s.localdb.loginController.(*oidcLoginController).parseOAuth2State(q.Get("state"))
214                 c.Check(state.verify([]byte(s.cluster.SystemRootToken)), check.Equals, true)
215                 c.Check(state.Time, check.Not(check.Equals), 0)
216                 c.Check(state.Remote, check.Equals, remote)
217                 c.Check(state.ReturnTo, check.Equals, "https://app.example.com/foo?bar")
218         }
219 }
220
221 func (s *OIDCLoginSuite) TestGoogleLogin_InvalidCode(c *check.C) {
222         state := s.startLogin(c)
223         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
224                 Code:  "first-try-a-bogus-code",
225                 State: state,
226         })
227         c.Check(err, check.IsNil)
228         c.Check(resp.RedirectLocation, check.Equals, "")
229         c.Check(resp.HTML.String(), check.Matches, `(?ms).*error in OAuth2 exchange.*cannot fetch token.*`)
230 }
231
232 func (s *OIDCLoginSuite) TestGoogleLogin_InvalidState(c *check.C) {
233         s.startLogin(c)
234         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
235                 Code:  s.validCode,
236                 State: "bogus-state",
237         })
238         c.Check(err, check.IsNil)
239         c.Check(resp.RedirectLocation, check.Equals, "")
240         c.Check(resp.HTML.String(), check.Matches, `(?ms).*invalid OAuth2 state.*`)
241 }
242
243 func (s *OIDCLoginSuite) setupPeopleAPIError(c *check.C) {
244         s.fakePeopleAPI = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
245                 w.WriteHeader(http.StatusForbidden)
246                 fmt.Fprintln(w, `Error 403: accessNotConfigured`)
247         }))
248         s.localdb.loginController.(*oidcLoginController).peopleAPIBasePath = s.fakePeopleAPI.URL
249 }
250
251 func (s *OIDCLoginSuite) TestGoogleLogin_PeopleAPIDisabled(c *check.C) {
252         s.localdb.loginController.(*oidcLoginController).UseGooglePeopleAPI = false
253         s.authEmail = "joe.smith@primary.example.com"
254         s.setupPeopleAPIError(c)
255         state := s.startLogin(c)
256         _, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
257                 Code:  s.validCode,
258                 State: state,
259         })
260         c.Check(err, check.IsNil)
261         authinfo := getCallbackAuthInfo(c, s.railsSpy)
262         c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
263 }
264
265 func (s *OIDCLoginSuite) TestConfig(c *check.C) {
266         s.cluster.Login.Google.Enable = false
267         s.cluster.Login.OpenIDConnect.Enable = true
268         s.cluster.Login.OpenIDConnect.Issuer = "https://accounts.example.com/"
269         s.cluster.Login.OpenIDConnect.ClientID = "oidc-client-id"
270         s.cluster.Login.OpenIDConnect.ClientSecret = "oidc-client-secret"
271         localdb := NewConn(s.cluster)
272         ctrl := localdb.loginController.(*oidcLoginController)
273         c.Check(ctrl.Issuer, check.Equals, "https://accounts.example.com/")
274         c.Check(ctrl.ClientID, check.Equals, "oidc-client-id")
275         c.Check(ctrl.ClientSecret, check.Equals, "oidc-client-secret")
276         c.Check(ctrl.UseGooglePeopleAPI, check.Equals, false)
277
278         for _, enableAltEmails := range []bool{false, true} {
279                 s.cluster.Login.OpenIDConnect.Enable = false
280                 s.cluster.Login.Google.Enable = true
281                 s.cluster.Login.Google.ClientID = "google-client-id"
282                 s.cluster.Login.Google.ClientSecret = "google-client-secret"
283                 s.cluster.Login.Google.AlternateEmailAddresses = enableAltEmails
284                 localdb = NewConn(s.cluster)
285                 ctrl = localdb.loginController.(*oidcLoginController)
286                 c.Check(ctrl.Issuer, check.Equals, "https://accounts.google.com")
287                 c.Check(ctrl.ClientID, check.Equals, "google-client-id")
288                 c.Check(ctrl.ClientSecret, check.Equals, "google-client-secret")
289                 c.Check(ctrl.UseGooglePeopleAPI, check.Equals, enableAltEmails)
290         }
291 }
292
293 func (s *OIDCLoginSuite) TestGoogleLogin_PeopleAPIError(c *check.C) {
294         s.setupPeopleAPIError(c)
295         state := s.startLogin(c)
296         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
297                 Code:  s.validCode,
298                 State: state,
299         })
300         c.Check(err, check.IsNil)
301         c.Check(resp.RedirectLocation, check.Equals, "")
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.fakeIssuer.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.validClientID = "oidc#client#id"
311         s.validClientSecret = "oidc#client#secret"
312         for _, trial := range []struct {
313                 expectEmail string // "" if failure expected
314                 setup       func()
315         }{
316                 {
317                         expectEmail: "user@oidc.example.com",
318                         setup: func() {
319                                 c.Log("=== succeed because email_verified is false but not required")
320                                 s.authEmail = "user@oidc.example.com"
321                                 s.authEmailVerified = false
322                                 s.cluster.Login.OpenIDConnect.EmailClaim = "email"
323                                 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = ""
324                                 s.cluster.Login.OpenIDConnect.UsernameClaim = ""
325                         },
326                 },
327                 {
328                         expectEmail: "",
329                         setup: func() {
330                                 c.Log("=== fail because email_verified is false and required")
331                                 s.authEmail = "user@oidc.example.com"
332                                 s.authEmailVerified = false
333                                 s.cluster.Login.OpenIDConnect.EmailClaim = "email"
334                                 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = "email_verified"
335                                 s.cluster.Login.OpenIDConnect.UsernameClaim = ""
336                         },
337                 },
338                 {
339                         expectEmail: "user@oidc.example.com",
340                         setup: func() {
341                                 c.Log("=== succeed because email_verified is false but config uses custom 'verified' claim")
342                                 s.authEmail = "user@oidc.example.com"
343                                 s.authEmailVerified = false
344                                 s.cluster.Login.OpenIDConnect.EmailClaim = "email"
345                                 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = "alt_verified"
346                                 s.cluster.Login.OpenIDConnect.UsernameClaim = ""
347                         },
348                 },
349                 {
350                         expectEmail: "alt_email@example.com",
351                         setup: func() {
352                                 c.Log("=== succeed with custom 'email' and 'email_verified' claims")
353                                 s.authEmail = "bad@wrong.example.com"
354                                 s.authEmailVerified = false
355                                 s.cluster.Login.OpenIDConnect.EmailClaim = "alt_email"
356                                 s.cluster.Login.OpenIDConnect.EmailVerifiedClaim = "alt_verified"
357                                 s.cluster.Login.OpenIDConnect.UsernameClaim = "alt_username"
358                         },
359                 },
360         } {
361                 trial.setup()
362                 if s.railsSpy != nil {
363                         s.railsSpy.Close()
364                 }
365                 s.railsSpy = arvadostest.NewProxy(c, s.cluster.Services.RailsAPI)
366                 s.localdb = NewConn(s.cluster)
367                 *s.localdb.railsProxy = *rpc.NewConn(s.cluster.ClusterID, s.railsSpy.URL, true, rpc.PassthroughTokenProvider)
368
369                 state := s.startLogin(c)
370                 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
371                         Code:  s.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         state := s.startLogin(c)
401         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
402                 Code:  s.validCode,
403                 State: state,
404         })
405         c.Check(err, check.IsNil)
406         c.Check(resp.HTML.String(), check.Equals, "")
407         target, err := url.Parse(resp.RedirectLocation)
408         c.Check(err, check.IsNil)
409         c.Check(target.Host, check.Equals, "app.example.com")
410         c.Check(target.Path, check.Equals, "/foo")
411         token := target.Query().Get("api_token")
412         c.Check(token, check.Matches, `v2/zzzzz-gj3su-.{15}/.{32,50}`)
413
414         authinfo := getCallbackAuthInfo(c, s.railsSpy)
415         c.Check(authinfo.FirstName, check.Equals, "Fake User")
416         c.Check(authinfo.LastName, check.Equals, "Name")
417         c.Check(authinfo.Email, check.Equals, "active-user@arvados.local")
418         c.Check(authinfo.AlternateEmails, check.HasLen, 0)
419
420         // Try using the returned Arvados token.
421         c.Logf("trying an API call with new token %q", token)
422         ctx := auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{token}})
423         cl, err := s.localdb.CollectionList(ctx, arvados.ListOptions{Limit: -1})
424         c.Check(cl.ItemsAvailable, check.Not(check.Equals), 0)
425         c.Check(cl.Items, check.Not(check.HasLen), 0)
426         c.Check(err, check.IsNil)
427
428         // Might as well check that bogus tokens aren't accepted.
429         badtoken := token + "plussomeboguschars"
430         c.Logf("trying an API call with mangled token %q", badtoken)
431         ctx = auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{badtoken}})
432         cl, err = s.localdb.CollectionList(ctx, arvados.ListOptions{Limit: -1})
433         c.Check(cl.Items, check.HasLen, 0)
434         c.Check(err, check.NotNil)
435         c.Check(err, check.ErrorMatches, `.*401 Unauthorized: Not logged in.*`)
436 }
437
438 func (s *OIDCLoginSuite) TestGoogleLogin_RealName(c *check.C) {
439         s.authEmail = "joe.smith@primary.example.com"
440         s.fakePeopleAPIResponse = map[string]interface{}{
441                 "names": []map[string]interface{}{
442                         {
443                                 "metadata":   map[string]interface{}{"primary": false},
444                                 "givenName":  "Joe",
445                                 "familyName": "Smith",
446                         },
447                         {
448                                 "metadata":   map[string]interface{}{"primary": true},
449                                 "givenName":  "Joseph",
450                                 "familyName": "Psmith",
451                         },
452                 },
453         }
454         state := s.startLogin(c)
455         s.localdb.Login(context.Background(), arvados.LoginOptions{
456                 Code:  s.validCode,
457                 State: state,
458         })
459
460         authinfo := getCallbackAuthInfo(c, s.railsSpy)
461         c.Check(authinfo.FirstName, check.Equals, "Joseph")
462         c.Check(authinfo.LastName, check.Equals, "Psmith")
463 }
464
465 func (s *OIDCLoginSuite) TestGoogleLogin_OIDCRealName(c *check.C) {
466         s.authName = "Joe P. Smith"
467         s.authEmail = "joe.smith@primary.example.com"
468         state := s.startLogin(c)
469         s.localdb.Login(context.Background(), arvados.LoginOptions{
470                 Code:  s.validCode,
471                 State: state,
472         })
473
474         authinfo := getCallbackAuthInfo(c, s.railsSpy)
475         c.Check(authinfo.FirstName, check.Equals, "Joe P.")
476         c.Check(authinfo.LastName, check.Equals, "Smith")
477 }
478
479 // People API returns some additional email addresses.
480 func (s *OIDCLoginSuite) TestGoogleLogin_AlternateEmailAddresses(c *check.C) {
481         s.authEmail = "joe.smith@primary.example.com"
482         s.fakePeopleAPIResponse = map[string]interface{}{
483                 "emailAddresses": []map[string]interface{}{
484                         {
485                                 "metadata": map[string]interface{}{"verified": true},
486                                 "value":    "joe.smith@work.example.com",
487                         },
488                         {
489                                 "value": "joe.smith@unverified.example.com", // unverified, so this one will be ignored
490                         },
491                         {
492                                 "metadata": map[string]interface{}{"verified": true},
493                                 "value":    "joe.smith@home.example.com",
494                         },
495                 },
496         }
497         state := s.startLogin(c)
498         s.localdb.Login(context.Background(), arvados.LoginOptions{
499                 Code:  s.validCode,
500                 State: state,
501         })
502
503         authinfo := getCallbackAuthInfo(c, s.railsSpy)
504         c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
505         c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@home.example.com", "joe.smith@work.example.com"})
506 }
507
508 // Primary address is not the one initially returned by oidc.
509 func (s *OIDCLoginSuite) TestGoogleLogin_AlternateEmailAddresses_Primary(c *check.C) {
510         s.authEmail = "joe.smith@alternate.example.com"
511         s.fakePeopleAPIResponse = map[string]interface{}{
512                 "emailAddresses": []map[string]interface{}{
513                         {
514                                 "metadata": map[string]interface{}{"verified": true, "primary": true},
515                                 "value":    "joe.smith@primary.example.com",
516                         },
517                         {
518                                 "metadata": map[string]interface{}{"verified": true},
519                                 "value":    "joe.smith@alternate.example.com",
520                         },
521                         {
522                                 "metadata": map[string]interface{}{"verified": true},
523                                 "value":    "jsmith+123@preferdomainforusername.example.com",
524                         },
525                 },
526         }
527         state := s.startLogin(c)
528         s.localdb.Login(context.Background(), arvados.LoginOptions{
529                 Code:  s.validCode,
530                 State: state,
531         })
532         authinfo := getCallbackAuthInfo(c, s.railsSpy)
533         c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
534         c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@alternate.example.com", "jsmith+123@preferdomainforusername.example.com"})
535         c.Check(authinfo.Username, check.Equals, "jsmith")
536 }
537
538 func (s *OIDCLoginSuite) TestGoogleLogin_NoPrimaryEmailAddress(c *check.C) {
539         s.authEmail = "joe.smith@unverified.example.com"
540         s.authEmailVerified = false
541         s.fakePeopleAPIResponse = map[string]interface{}{
542                 "emailAddresses": []map[string]interface{}{
543                         {
544                                 "metadata": map[string]interface{}{"verified": true},
545                                 "value":    "joe.smith@work.example.com",
546                         },
547                         {
548                                 "metadata": map[string]interface{}{"verified": true},
549                                 "value":    "joe.smith@home.example.com",
550                         },
551                 },
552         }
553         state := s.startLogin(c)
554         s.localdb.Login(context.Background(), arvados.LoginOptions{
555                 Code:  s.validCode,
556                 State: state,
557         })
558
559         authinfo := getCallbackAuthInfo(c, s.railsSpy)
560         c.Check(authinfo.Email, check.Equals, "joe.smith@work.example.com") // first verified email in People response
561         c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@home.example.com"})
562         c.Check(authinfo.Username, check.Equals, "")
563 }
564
565 func (s *OIDCLoginSuite) startLogin(c *check.C) (state string) {
566         // Initiate login, but instead of following the redirect to
567         // the provider, just grab state from the redirect URL.
568         resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{ReturnTo: "https://app.example.com/foo?bar"})
569         c.Check(err, check.IsNil)
570         target, err := url.Parse(resp.RedirectLocation)
571         c.Check(err, check.IsNil)
572         state = target.Query().Get("state")
573         c.Check(state, check.Not(check.Equals), "")
574         return
575 }
576
577 func (s *OIDCLoginSuite) fakeToken(c *check.C, payload []byte) string {
578         signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: s.issuerKey}, nil)
579         if err != nil {
580                 c.Error(err)
581         }
582         object, err := signer.Sign(payload)
583         if err != nil {
584                 c.Error(err)
585         }
586         t, err := object.CompactSerialize()
587         if err != nil {
588                 c.Error(err)
589         }
590         c.Logf("fakeToken(%q) == %q", payload, t)
591         return t
592 }
593
594 func getCallbackAuthInfo(c *check.C, railsSpy *arvadostest.Proxy) (authinfo rpc.UserSessionAuthInfo) {
595         for _, dump := range railsSpy.RequestDumps {
596                 c.Logf("spied request: %q", dump)
597                 split := bytes.Split(dump, []byte("\r\n\r\n"))
598                 c.Assert(split, check.HasLen, 2)
599                 hdr, body := string(split[0]), string(split[1])
600                 if strings.Contains(hdr, "POST /auth/controller/callback") {
601                         vs, err := url.ParseQuery(body)
602                         c.Check(json.Unmarshal([]byte(vs.Get("auth_info")), &authinfo), check.IsNil)
603                         c.Check(err, check.IsNil)
604                         sort.Strings(authinfo.AlternateEmails)
605                         return
606                 }
607         }
608         c.Error("callback not found")
609         return
610 }