Merge branch '18947-githttpd'
[arvados.git] / lib / controller / localdb / login_testuser_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         "context"
9         "database/sql"
10
11         "git.arvados.org/arvados.git/lib/config"
12         "git.arvados.org/arvados.git/lib/controller/rpc"
13         "git.arvados.org/arvados.git/lib/ctrlctx"
14         "git.arvados.org/arvados.git/sdk/go/arvados"
15         "git.arvados.org/arvados.git/sdk/go/arvadostest"
16         "git.arvados.org/arvados.git/sdk/go/auth"
17         "git.arvados.org/arvados.git/sdk/go/ctxlog"
18         "github.com/jmoiron/sqlx"
19         check "gopkg.in/check.v1"
20 )
21
22 var _ = check.Suite(&TestUserSuite{})
23
24 type TestUserSuite struct {
25         cluster  *arvados.Cluster
26         ctrl     *testLoginController
27         railsSpy *arvadostest.Proxy
28         db       *sqlx.DB
29
30         // transaction context
31         ctx context.Context
32         tx  *sqlx.Tx
33 }
34
35 func (s *TestUserSuite) SetUpSuite(c *check.C) {
36         cfg, err := config.NewLoader(nil, ctxlog.TestLogger(c)).Load()
37         c.Assert(err, check.IsNil)
38         s.cluster, err = cfg.GetCluster("")
39         c.Assert(err, check.IsNil)
40         s.cluster.Login.Test.Enable = true
41         s.cluster.Login.Test.Users = map[string]arvados.TestUser{
42                 "valid": {Email: "valid@example.com", Password: "v@l1d"},
43         }
44         s.railsSpy = arvadostest.NewProxy(c, s.cluster.Services.RailsAPI)
45         s.ctrl = &testLoginController{
46                 Cluster: s.cluster,
47                 Parent:  &Conn{railsProxy: rpc.NewConn(s.cluster.ClusterID, s.railsSpy.URL, true, rpc.PassthroughTokenProvider)},
48         }
49         s.db = arvadostest.DB(c, s.cluster)
50 }
51
52 func (s *TestUserSuite) SetUpTest(c *check.C) {
53         tx, err := s.db.Beginx()
54         c.Assert(err, check.IsNil)
55         s.ctx = ctrlctx.NewWithTransaction(context.Background(), tx)
56         s.tx = tx
57 }
58
59 func (s *TestUserSuite) TearDownTest(c *check.C) {
60         s.tx.Rollback()
61 }
62
63 func (s *TestUserSuite) TestLogin(c *check.C) {
64         for _, trial := range []struct {
65                 success  bool
66                 username string
67                 password string
68         }{
69                 {false, "foo", "bar"},
70                 {false, "", ""},
71                 {false, "valid", ""},
72                 {false, "", "v@l1d"},
73                 {true, "valid", "v@l1d"},
74                 {true, "valid@example.com", "v@l1d"},
75         } {
76                 c.Logf("=== %#v", trial)
77                 resp, err := s.ctrl.UserAuthenticate(s.ctx, arvados.UserAuthenticateOptions{
78                         Username: trial.username,
79                         Password: trial.password,
80                 })
81                 if trial.success {
82                         c.Check(err, check.IsNil)
83                         c.Check(resp.APIToken, check.Not(check.Equals), "")
84                         c.Check(resp.UUID, check.Matches, `zzzzz-gj3su-.*`)
85                         c.Check(resp.Scopes, check.DeepEquals, []string{"all"})
86
87                         authinfo := getCallbackAuthInfo(c, s.railsSpy)
88                         c.Check(authinfo.Email, check.Equals, "valid@example.com")
89                         c.Check(authinfo.AlternateEmails, check.DeepEquals, []string(nil))
90                 } else {
91                         c.Check(err, check.ErrorMatches, `authentication failed.*`)
92                 }
93         }
94 }
95
96 func (s *TestUserSuite) TestLoginForm(c *check.C) {
97         resp, err := s.ctrl.Login(s.ctx, arvados.LoginOptions{
98                 ReturnTo: "https://localhost:12345/example",
99         })
100         c.Check(err, check.IsNil)
101         c.Check(resp.HTML.String(), check.Matches, `(?ms).*<form method="POST".*`)
102         c.Check(resp.HTML.String(), check.Matches, `(?ms).*<input id="return_to" type="hidden" name="return_to" value="https://localhost:12345/example">.*`)
103 }
104
105 func (s *TestUserSuite) TestExpireTokenOnLogout(c *check.C) {
106         returnTo := "https://localhost:12345/logout"
107         for _, trial := range []struct {
108                 requestToken      string
109                 expiringTokenUUID string
110                 shouldExpireToken bool
111         }{
112                 // v2 token
113                 {arvadostest.ActiveTokenV2, arvadostest.ActiveTokenUUID, true},
114                 // v1 token
115                 {arvadostest.AdminToken, arvadostest.AdminTokenUUID, true},
116                 // inexistent v1 token -- logout shouldn't fail
117                 {"thisdoesntexistasatoken", "", false},
118                 // inexistent v2 token -- logout shouldn't fail
119                 {"v2/some-fake-uuid/thisdoesntexistasatoken", "", false},
120         } {
121                 c.Logf("=== %#v", trial)
122                 ctx := auth.NewContext(s.ctx, &auth.Credentials{
123                         Tokens: []string{trial.requestToken},
124                 })
125
126                 var tokenUUID string
127                 var err error
128                 qry := `SELECT uuid FROM api_client_authorizations WHERE uuid=$1 AND (expires_at IS NULL OR expires_at > current_timestamp AT TIME ZONE 'UTC') LIMIT 1`
129
130                 if trial.shouldExpireToken {
131                         err = s.tx.QueryRowContext(ctx, qry, trial.expiringTokenUUID).Scan(&tokenUUID)
132                         c.Check(err, check.IsNil)
133                 }
134
135                 resp, err := s.ctrl.Logout(ctx, arvados.LogoutOptions{
136                         ReturnTo: returnTo,
137                 })
138                 c.Check(err, check.IsNil)
139                 c.Check(resp.RedirectLocation, check.Equals, returnTo)
140
141                 if trial.shouldExpireToken {
142                         err = s.tx.QueryRowContext(ctx, qry, trial.expiringTokenUUID).Scan(&tokenUUID)
143                         c.Check(err, check.Equals, sql.ErrNoRows)
144                 }
145         }
146 }