1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "git.arvados.org/arvados.git/lib/config"
23 "git.arvados.org/arvados.git/lib/controller/rpc"
24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 "git.arvados.org/arvados.git/sdk/go/arvadostest"
26 "git.arvados.org/arvados.git/sdk/go/auth"
27 "git.arvados.org/arvados.git/sdk/go/ctxlog"
28 check "gopkg.in/check.v1"
29 jose "gopkg.in/square/go-jose.v2"
32 // Gocheck boilerplate
33 func Test(t *testing.T) {
37 var _ = check.Suite(&LoginSuite{})
39 type LoginSuite struct {
40 cluster *arvados.Cluster
43 railsSpy *arvadostest.Proxy
44 fakeIssuer *httptest.Server
45 fakePeopleAPI *httptest.Server
46 fakePeopleAPIResponse map[string]interface{}
47 issuerKey *rsa.PrivateKey
49 // expected token request
51 // desired response from token endpoint
53 authEmailVerified bool
57 func (s *LoginSuite) TearDownSuite(c *check.C) {
58 // Undo any changes/additions to the user database so they
59 // don't affect subsequent tests.
60 arvadostest.ResetEnv()
61 c.Check(arvados.NewClientFromEnv().RequestAndDecode(nil, "POST", "database/reset", nil, nil), check.IsNil)
64 func (s *LoginSuite) SetUpTest(c *check.C) {
66 s.issuerKey, err = rsa.GenerateKey(rand.Reader, 2048)
67 c.Assert(err, check.IsNil)
69 s.authEmail = "active-user@arvados.local"
70 s.authEmailVerified = true
71 s.authName = "Fake User Name"
72 s.fakeIssuer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
74 c.Logf("fakeIssuer: got req: %s %s %s", req.Method, req.URL, req.Form)
75 w.Header().Set("Content-Type", "application/json")
77 case "/.well-known/openid-configuration":
78 json.NewEncoder(w).Encode(map[string]interface{}{
79 "issuer": s.fakeIssuer.URL,
80 "authorization_endpoint": s.fakeIssuer.URL + "/auth",
81 "token_endpoint": s.fakeIssuer.URL + "/token",
82 "jwks_uri": s.fakeIssuer.URL + "/jwks",
83 "userinfo_endpoint": s.fakeIssuer.URL + "/userinfo",
86 if req.Form.Get("code") != s.validCode || s.validCode == "" {
87 w.WriteHeader(http.StatusUnauthorized)
90 idToken, _ := json.Marshal(map[string]interface{}{
91 "iss": s.fakeIssuer.URL,
92 "aud": []string{"test%client$id"},
93 "sub": "fake-user-id",
94 "exp": time.Now().UTC().Add(time.Minute).UnixNano(),
95 "iat": time.Now().UTC().UnixNano(),
96 "nonce": "fake-nonce",
98 "email_verified": s.authEmailVerified,
101 json.NewEncoder(w).Encode(struct {
102 AccessToken string `json:"access_token"`
103 TokenType string `json:"token_type"`
104 RefreshToken string `json:"refresh_token"`
105 ExpiresIn int32 `json:"expires_in"`
106 IDToken string `json:"id_token"`
108 AccessToken: s.fakeToken(c, []byte("fake access token")),
110 RefreshToken: "test-refresh-token",
112 IDToken: s.fakeToken(c, idToken),
115 json.NewEncoder(w).Encode(jose.JSONWebKeySet{
116 Keys: []jose.JSONWebKey{
117 {Key: s.issuerKey.Public(), Algorithm: string(jose.RS256), KeyID: ""},
121 w.WriteHeader(http.StatusInternalServerError)
123 w.WriteHeader(http.StatusInternalServerError)
125 w.WriteHeader(http.StatusNotFound)
128 s.validCode = fmt.Sprintf("abcdefgh-%d", time.Now().Unix())
130 s.fakePeopleAPI = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
132 c.Logf("fakePeopleAPI: got req: %s %s %s", req.Method, req.URL, req.Form)
133 w.Header().Set("Content-Type", "application/json")
134 switch req.URL.Path {
135 case "/v1/people/me":
136 if f := req.Form.Get("personFields"); f != "emailAddresses,names" {
137 w.WriteHeader(http.StatusBadRequest)
140 json.NewEncoder(w).Encode(s.fakePeopleAPIResponse)
142 w.WriteHeader(http.StatusNotFound)
145 s.fakePeopleAPIResponse = map[string]interface{}{}
147 cfg, err := config.NewLoader(nil, ctxlog.TestLogger(c)).Load()
148 s.cluster, err = cfg.GetCluster("")
149 s.cluster.Login.ProviderAppID = ""
150 s.cluster.Login.ProviderAppSecret = ""
151 s.cluster.Login.GoogleClientID = "test%client$id"
152 s.cluster.Login.GoogleClientSecret = "test#client/secret"
153 s.cluster.Users.PreferDomainForUsername = "PreferDomainForUsername.example.com"
154 c.Assert(err, check.IsNil)
156 s.localdb = NewConn(s.cluster)
157 s.localdb.googleLoginController.issuer = s.fakeIssuer.URL
158 s.localdb.googleLoginController.peopleAPIBasePath = s.fakePeopleAPI.URL
160 s.railsSpy = arvadostest.NewProxy(c, s.cluster.Services.RailsAPI)
161 s.localdb.railsProxy = rpc.NewConn(s.cluster.ClusterID, s.railsSpy.URL, true, rpc.PassthroughTokenProvider)
164 func (s *LoginSuite) TearDownTest(c *check.C) {
168 func (s *LoginSuite) TestGoogleLogout(c *check.C) {
169 resp, err := s.localdb.Logout(context.Background(), arvados.LogoutOptions{ReturnTo: "https://foo.example.com/bar"})
170 c.Check(err, check.IsNil)
171 c.Check(resp.RedirectLocation, check.Equals, "https://foo.example.com/bar")
174 func (s *LoginSuite) TestGoogleLogin_Start_Bogus(c *check.C) {
175 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{})
176 c.Check(err, check.IsNil)
177 c.Check(resp.RedirectLocation, check.Equals, "")
178 c.Check(resp.HTML.String(), check.Matches, `.*missing return_to parameter.*`)
181 func (s *LoginSuite) TestGoogleLogin_Start(c *check.C) {
182 for _, remote := range []string{"", "zzzzz"} {
183 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{Remote: remote, ReturnTo: "https://app.example.com/foo?bar"})
184 c.Check(err, check.IsNil)
185 target, err := url.Parse(resp.RedirectLocation)
186 c.Check(err, check.IsNil)
187 issuerURL, _ := url.Parse(s.fakeIssuer.URL)
188 c.Check(target.Host, check.Equals, issuerURL.Host)
190 c.Check(q.Get("client_id"), check.Equals, "test%client$id")
191 state := s.localdb.googleLoginController.parseOAuth2State(q.Get("state"))
192 c.Check(state.verify([]byte(s.cluster.SystemRootToken)), check.Equals, true)
193 c.Check(state.Time, check.Not(check.Equals), 0)
194 c.Check(state.Remote, check.Equals, remote)
195 c.Check(state.ReturnTo, check.Equals, "https://app.example.com/foo?bar")
199 func (s *LoginSuite) TestGoogleLogin_InvalidCode(c *check.C) {
200 state := s.startLogin(c)
201 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
202 Code: "first-try-a-bogus-code",
205 c.Check(err, check.IsNil)
206 c.Check(resp.RedirectLocation, check.Equals, "")
207 c.Check(resp.HTML.String(), check.Matches, `(?ms).*error in OAuth2 exchange.*cannot fetch token.*`)
210 func (s *LoginSuite) TestGoogleLogin_InvalidState(c *check.C) {
212 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
214 State: "bogus-state",
216 c.Check(err, check.IsNil)
217 c.Check(resp.RedirectLocation, check.Equals, "")
218 c.Check(resp.HTML.String(), check.Matches, `(?ms).*invalid OAuth2 state.*`)
221 func (s *LoginSuite) setupPeopleAPIError(c *check.C) {
222 s.fakePeopleAPI = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
223 w.WriteHeader(http.StatusForbidden)
224 fmt.Fprintln(w, `Error 403: accessNotConfigured`)
226 s.localdb.googleLoginController.peopleAPIBasePath = s.fakePeopleAPI.URL
229 func (s *LoginSuite) TestGoogleLogin_PeopleAPIDisabled(c *check.C) {
230 s.cluster.Login.GoogleAlternateEmailAddresses = false
231 s.authEmail = "joe.smith@primary.example.com"
232 s.setupPeopleAPIError(c)
233 state := s.startLogin(c)
234 _, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
238 c.Check(err, check.IsNil)
239 authinfo := s.getCallbackAuthInfo(c)
240 c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
243 func (s *LoginSuite) TestGoogleLogin_PeopleAPIError(c *check.C) {
244 s.setupPeopleAPIError(c)
245 state := s.startLogin(c)
246 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
250 c.Check(err, check.IsNil)
251 c.Check(resp.RedirectLocation, check.Equals, "")
254 func (s *LoginSuite) TestGoogleLogin_Success(c *check.C) {
255 state := s.startLogin(c)
256 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{
260 c.Check(err, check.IsNil)
261 c.Check(resp.HTML.String(), check.Equals, "")
262 target, err := url.Parse(resp.RedirectLocation)
263 c.Check(err, check.IsNil)
264 c.Check(target.Host, check.Equals, "app.example.com")
265 c.Check(target.Path, check.Equals, "/foo")
266 token := target.Query().Get("api_token")
267 c.Check(token, check.Matches, `v2/zzzzz-gj3su-.{15}/.{32,50}`)
269 authinfo := s.getCallbackAuthInfo(c)
270 c.Check(authinfo.FirstName, check.Equals, "Fake User")
271 c.Check(authinfo.LastName, check.Equals, "Name")
272 c.Check(authinfo.Email, check.Equals, "active-user@arvados.local")
273 c.Check(authinfo.AlternateEmails, check.HasLen, 0)
275 // Try using the returned Arvados token.
276 c.Logf("trying an API call with new token %q", token)
277 ctx := auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{token}})
278 cl, err := s.localdb.CollectionList(ctx, arvados.ListOptions{Limit: -1})
279 c.Check(cl.ItemsAvailable, check.Not(check.Equals), 0)
280 c.Check(cl.Items, check.Not(check.HasLen), 0)
281 c.Check(err, check.IsNil)
283 // Might as well check that bogus tokens aren't accepted.
284 badtoken := token + "plussomeboguschars"
285 c.Logf("trying an API call with mangled token %q", badtoken)
286 ctx = auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{badtoken}})
287 cl, err = s.localdb.CollectionList(ctx, arvados.ListOptions{Limit: -1})
288 c.Check(cl.Items, check.HasLen, 0)
289 c.Check(err, check.NotNil)
290 c.Check(err, check.ErrorMatches, `.*401 Unauthorized: Not logged in.*`)
293 func (s *LoginSuite) TestGoogleLogin_RealName(c *check.C) {
294 s.authEmail = "joe.smith@primary.example.com"
295 s.fakePeopleAPIResponse = map[string]interface{}{
296 "names": []map[string]interface{}{
298 "metadata": map[string]interface{}{"primary": false},
300 "familyName": "Smith",
303 "metadata": map[string]interface{}{"primary": true},
304 "givenName": "Joseph",
305 "familyName": "Psmith",
309 state := s.startLogin(c)
310 s.localdb.Login(context.Background(), arvados.LoginOptions{
315 authinfo := s.getCallbackAuthInfo(c)
316 c.Check(authinfo.FirstName, check.Equals, "Joseph")
317 c.Check(authinfo.LastName, check.Equals, "Psmith")
320 func (s *LoginSuite) TestGoogleLogin_OIDCRealName(c *check.C) {
321 s.authName = "Joe P. Smith"
322 s.authEmail = "joe.smith@primary.example.com"
323 state := s.startLogin(c)
324 s.localdb.Login(context.Background(), arvados.LoginOptions{
329 authinfo := s.getCallbackAuthInfo(c)
330 c.Check(authinfo.FirstName, check.Equals, "Joe P.")
331 c.Check(authinfo.LastName, check.Equals, "Smith")
334 // People API returns some additional email addresses.
335 func (s *LoginSuite) TestGoogleLogin_AlternateEmailAddresses(c *check.C) {
336 s.authEmail = "joe.smith@primary.example.com"
337 s.fakePeopleAPIResponse = map[string]interface{}{
338 "emailAddresses": []map[string]interface{}{
340 "metadata": map[string]interface{}{"verified": true},
341 "value": "joe.smith@work.example.com",
344 "value": "joe.smith@unverified.example.com", // unverified, so this one will be ignored
347 "metadata": map[string]interface{}{"verified": true},
348 "value": "joe.smith@home.example.com",
352 state := s.startLogin(c)
353 s.localdb.Login(context.Background(), arvados.LoginOptions{
358 authinfo := s.getCallbackAuthInfo(c)
359 c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
360 c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@home.example.com", "joe.smith@work.example.com"})
363 // Primary address is not the one initially returned by oidc.
364 func (s *LoginSuite) TestGoogleLogin_AlternateEmailAddresses_Primary(c *check.C) {
365 s.authEmail = "joe.smith@alternate.example.com"
366 s.fakePeopleAPIResponse = map[string]interface{}{
367 "emailAddresses": []map[string]interface{}{
369 "metadata": map[string]interface{}{"verified": true, "primary": true},
370 "value": "joe.smith@primary.example.com",
373 "metadata": map[string]interface{}{"verified": true},
374 "value": "joe.smith@alternate.example.com",
377 "metadata": map[string]interface{}{"verified": true},
378 "value": "jsmith+123@preferdomainforusername.example.com",
382 state := s.startLogin(c)
383 s.localdb.Login(context.Background(), arvados.LoginOptions{
387 authinfo := s.getCallbackAuthInfo(c)
388 c.Check(authinfo.Email, check.Equals, "joe.smith@primary.example.com")
389 c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@alternate.example.com", "jsmith+123@preferdomainforusername.example.com"})
390 c.Check(authinfo.Username, check.Equals, "jsmith")
393 func (s *LoginSuite) TestGoogleLogin_NoPrimaryEmailAddress(c *check.C) {
394 s.authEmail = "joe.smith@unverified.example.com"
395 s.authEmailVerified = false
396 s.fakePeopleAPIResponse = map[string]interface{}{
397 "emailAddresses": []map[string]interface{}{
399 "metadata": map[string]interface{}{"verified": true},
400 "value": "joe.smith@work.example.com",
403 "metadata": map[string]interface{}{"verified": true},
404 "value": "joe.smith@home.example.com",
408 state := s.startLogin(c)
409 s.localdb.Login(context.Background(), arvados.LoginOptions{
414 authinfo := s.getCallbackAuthInfo(c)
415 c.Check(authinfo.Email, check.Equals, "joe.smith@work.example.com") // first verified email in People response
416 c.Check(authinfo.AlternateEmails, check.DeepEquals, []string{"joe.smith@home.example.com"})
417 c.Check(authinfo.Username, check.Equals, "")
420 func (s *LoginSuite) getCallbackAuthInfo(c *check.C) (authinfo rpc.UserSessionAuthInfo) {
421 for _, dump := range s.railsSpy.RequestDumps {
422 c.Logf("spied request: %q", dump)
423 split := bytes.Split(dump, []byte("\r\n\r\n"))
424 c.Assert(split, check.HasLen, 2)
425 hdr, body := string(split[0]), string(split[1])
426 if strings.Contains(hdr, "POST /auth/controller/callback") {
427 vs, err := url.ParseQuery(body)
428 c.Check(json.Unmarshal([]byte(vs.Get("auth_info")), &authinfo), check.IsNil)
429 c.Check(err, check.IsNil)
430 sort.Strings(authinfo.AlternateEmails)
434 c.Error("callback not found")
438 func (s *LoginSuite) startLogin(c *check.C) (state string) {
439 // Initiate login, but instead of following the redirect to
440 // the provider, just grab state from the redirect URL.
441 resp, err := s.localdb.Login(context.Background(), arvados.LoginOptions{ReturnTo: "https://app.example.com/foo?bar"})
442 c.Check(err, check.IsNil)
443 target, err := url.Parse(resp.RedirectLocation)
444 c.Check(err, check.IsNil)
445 state = target.Query().Get("state")
446 c.Check(state, check.Not(check.Equals), "")
450 func (s *LoginSuite) fakeToken(c *check.C, payload []byte) string {
451 signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: s.issuerKey}, nil)
455 object, err := signer.Sign(payload)
459 t, err := object.CompactSerialize()
463 c.Logf("fakeToken(%q) == %q", payload, t)