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