0c94fa6c0e21be72949f6fd5b402ae252d7ce1cc
[arvados.git] / lib / controller / localdb / login_ldap_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         "encoding/json"
10         "net"
11         "net/http"
12
13         "git.arvados.org/arvados.git/lib/config"
14         "git.arvados.org/arvados.git/lib/controller/railsproxy"
15         "git.arvados.org/arvados.git/lib/ctrlctx"
16         "git.arvados.org/arvados.git/sdk/go/arvados"
17         "git.arvados.org/arvados.git/sdk/go/arvadostest"
18         "git.arvados.org/arvados.git/sdk/go/auth"
19         "git.arvados.org/arvados.git/sdk/go/ctxlog"
20         "github.com/bradleypeabody/godap"
21         "github.com/jmoiron/sqlx"
22         check "gopkg.in/check.v1"
23 )
24
25 var _ = check.Suite(&LDAPSuite{})
26
27 type LDAPSuite struct {
28         cluster *arvados.Cluster
29         ctrl    *ldapLoginController
30         ldap    *godap.LDAPServer // fake ldap server that accepts auth goodusername/goodpassword
31         db      *sqlx.DB
32
33         // transaction context
34         ctx      context.Context
35         rollback func() error
36 }
37
38 func (s *LDAPSuite) TearDownSuite(c *check.C) {
39         // Undo any changes/additions to the user database so they
40         // don't affect subsequent tests.
41         arvadostest.ResetEnv()
42         c.Check(arvados.NewClientFromEnv().RequestAndDecode(nil, "POST", "database/reset", nil, nil), check.IsNil)
43 }
44
45 func (s *LDAPSuite) SetUpSuite(c *check.C) {
46         cfg, err := config.NewLoader(nil, ctxlog.TestLogger(c)).Load()
47         c.Assert(err, check.IsNil)
48         s.cluster, err = cfg.GetCluster("")
49         c.Assert(err, check.IsNil)
50
51         ln, err := net.Listen("tcp", "127.0.0.1:0")
52         s.ldap = &godap.LDAPServer{
53                 Listener: ln,
54                 Handlers: []godap.LDAPRequestHandler{
55                         &godap.LDAPBindFuncHandler{
56                                 LDAPBindFunc: func(binddn string, bindpw []byte) bool {
57                                         return binddn == "cn=goodusername,dc=example,dc=com" && string(bindpw) == "goodpassword"
58                                 },
59                         },
60                         &godap.LDAPSimpleSearchFuncHandler{
61                                 LDAPSimpleSearchFunc: func(req *godap.LDAPSimpleSearchRequest) []*godap.LDAPSimpleSearchResultEntry {
62                                         if req.FilterAttr != "uid" || req.BaseDN != "dc=example,dc=com" {
63                                                 return []*godap.LDAPSimpleSearchResultEntry{}
64                                         }
65                                         return []*godap.LDAPSimpleSearchResultEntry{
66                                                 &godap.LDAPSimpleSearchResultEntry{
67                                                         DN: "cn=" + req.FilterValue + "," + req.BaseDN,
68                                                         Attrs: map[string]interface{}{
69                                                                 "SN":   req.FilterValue,
70                                                                 "CN":   req.FilterValue,
71                                                                 "uid":  req.FilterValue,
72                                                                 "mail": req.FilterValue + "@example.com",
73                                                         },
74                                                 },
75                                         }
76                                 },
77                         },
78                 },
79         }
80         go func() {
81                 ctxlog.TestLogger(c).Print(s.ldap.Serve())
82         }()
83
84         s.cluster.Login.LDAP.Enable = true
85         err = json.Unmarshal([]byte(`"ldap://`+ln.Addr().String()+`"`), &s.cluster.Login.LDAP.URL)
86         s.cluster.Login.LDAP.StartTLS = false
87         s.cluster.Login.LDAP.SearchBindUser = "cn=goodusername,dc=example,dc=com"
88         s.cluster.Login.LDAP.SearchBindPassword = "goodpassword"
89         s.cluster.Login.LDAP.SearchBase = "dc=example,dc=com"
90         c.Assert(err, check.IsNil)
91         s.ctrl = &ldapLoginController{
92                 Cluster:    s.cluster,
93                 RailsProxy: railsproxy.NewConn(s.cluster),
94         }
95         s.db = arvadostest.DB(c, s.cluster)
96 }
97
98 func (s *LDAPSuite) SetUpTest(c *check.C) {
99         tx, err := s.db.Beginx()
100         c.Assert(err, check.IsNil)
101         s.ctx = ctrlctx.NewWithTransaction(context.Background(), tx)
102         s.rollback = tx.Rollback
103 }
104
105 func (s *LDAPSuite) TearDownTest(c *check.C) {
106         if s.rollback != nil {
107                 s.rollback()
108         }
109 }
110
111 func (s *LDAPSuite) TestLoginSuccess(c *check.C) {
112         conn := NewConn(s.cluster)
113         conn.loginController = s.ctrl
114         resp, err := conn.UserAuthenticate(s.ctx, arvados.UserAuthenticateOptions{
115                 Username: "goodusername",
116                 Password: "goodpassword",
117         })
118         c.Check(err, check.IsNil)
119         c.Check(resp.APIToken, check.Not(check.Equals), "")
120         c.Check(resp.UUID, check.Matches, `zzzzz-gj3su-.*`)
121         c.Check(resp.Scopes, check.DeepEquals, []string{"all"})
122
123         ctx := auth.NewContext(s.ctx, &auth.Credentials{Tokens: []string{"v2/" + resp.UUID + "/" + resp.APIToken}})
124         user, err := railsproxy.NewConn(s.cluster).UserGetCurrent(ctx, arvados.GetOptions{})
125         c.Check(err, check.IsNil)
126         c.Check(user.Email, check.Equals, "goodusername@example.com")
127         c.Check(user.Username, check.Equals, "goodusername")
128 }
129
130 func (s *LDAPSuite) TestLoginFailure(c *check.C) {
131         // search returns no results
132         s.cluster.Login.LDAP.SearchBase = "dc=example,dc=invalid"
133         resp, err := s.ctrl.UserAuthenticate(s.ctx, arvados.UserAuthenticateOptions{
134                 Username: "goodusername",
135                 Password: "goodpassword",
136         })
137         c.Check(err, check.ErrorMatches, `LDAP: Authentication failure \(with username "goodusername" and password\)`)
138         hs, ok := err.(interface{ HTTPStatus() int })
139         if c.Check(ok, check.Equals, true) {
140                 c.Check(hs.HTTPStatus(), check.Equals, http.StatusUnauthorized)
141         }
142         c.Check(resp.APIToken, check.Equals, "")
143
144         // search returns result, but auth fails
145         s.cluster.Login.LDAP.SearchBase = "dc=example,dc=com"
146         resp, err = s.ctrl.UserAuthenticate(s.ctx, arvados.UserAuthenticateOptions{
147                 Username: "badusername",
148                 Password: "badpassword",
149         })
150         c.Check(err, check.ErrorMatches, `LDAP: Authentication failure \(with username "badusername" and password\)`)
151         hs, ok = err.(interface{ HTTPStatus() int })
152         if c.Check(ok, check.Equals, true) {
153                 c.Check(hs.HTTPStatus(), check.Equals, http.StatusUnauthorized)
154         }
155         c.Check(resp.APIToken, check.Equals, "")
156 }