Merge branch 'master' into 4823-python-sdk-writable-collection-api
[arvados.git] / services / keepproxy / keepproxy_test.go
1 package main
2
3 import (
4         "crypto/md5"
5         "crypto/tls"
6         "fmt"
7         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
8         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
9         "git.curoverse.com/arvados.git/sdk/go/keepclient"
10         . "gopkg.in/check.v1"
11         "io"
12         "io/ioutil"
13         "log"
14         "net/http"
15         "net/url"
16         "os"
17         "strings"
18         "testing"
19         "time"
20 )
21
22 // Gocheck boilerplate
23 func Test(t *testing.T) {
24         TestingT(t)
25 }
26
27 // Gocheck boilerplate
28 var _ = Suite(&ServerRequiredSuite{})
29
30 // Tests that require the Keep server running
31 type ServerRequiredSuite struct{}
32
33 // Wait (up to 1 second) for keepproxy to listen on a port. This
34 // avoids a race condition where we hit a "connection refused" error
35 // because we start testing the proxy too soon.
36 func waitForListener() {
37         const (
38                 ms = 5
39         )
40         for i := 0; listener == nil && i < 1000; i += ms {
41                 time.Sleep(ms * time.Millisecond)
42         }
43         if listener == nil {
44                 log.Fatalf("Timed out waiting for listener to start")
45         }
46 }
47
48 func closeListener() {
49         if listener != nil {
50                 listener.Close()
51         }
52 }
53
54 func (s *ServerRequiredSuite) SetUpSuite(c *C) {
55         arvadostest.StartAPI()
56         arvadostest.StartKeep()
57 }
58
59 func (s *ServerRequiredSuite) SetUpTest(c *C) {
60         arvadostest.ResetEnv()
61 }
62
63 func (s *ServerRequiredSuite) TearDownSuite(c *C) {
64         arvadostest.StopKeep()
65         arvadostest.StopAPI()
66 }
67
68 func setupProxyService() {
69
70         client := &http.Client{Transport: &http.Transport{
71                 TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}}
72
73         var req *http.Request
74         var err error
75         if req, err = http.NewRequest("POST", fmt.Sprintf("https://%s/arvados/v1/keep_services", os.Getenv("ARVADOS_API_HOST")), nil); err != nil {
76                 panic(err.Error())
77         }
78         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", os.Getenv("ARVADOS_API_TOKEN")))
79
80         reader, writer := io.Pipe()
81
82         req.Body = reader
83
84         go func() {
85                 data := url.Values{}
86                 data.Set("keep_service", `{
87   "service_host": "localhost",
88   "service_port": 29950,
89   "service_ssl_flag": false,
90   "service_type": "proxy"
91 }`)
92
93                 writer.Write([]byte(data.Encode()))
94                 writer.Close()
95         }()
96
97         var resp *http.Response
98         if resp, err = client.Do(req); err != nil {
99                 panic(err.Error())
100         }
101         if resp.StatusCode != 200 {
102                 panic(resp.Status)
103         }
104 }
105
106 func runProxy(c *C, args []string, port int, bogusClientToken bool) keepclient.KeepClient {
107         if bogusClientToken {
108                 os.Setenv("ARVADOS_API_TOKEN", "bogus-token")
109         }
110         arv, err := arvadosclient.MakeArvadosClient()
111         c.Assert(err, Equals, nil)
112         kc := keepclient.KeepClient{
113                 Arvados: &arv,
114                 Want_replicas: 2,
115                 Using_proxy: true,
116                 Client: &http.Client{},
117         }
118         kc.SetServiceRoots(map[string]string{
119                 "proxy": fmt.Sprintf("http://localhost:%v", port),
120         })
121         c.Check(kc.Using_proxy, Equals, true)
122         c.Check(len(kc.ServiceRoots()), Equals, 1)
123         for _, root := range kc.ServiceRoots() {
124                 c.Check(root, Equals, fmt.Sprintf("http://localhost:%v", port))
125         }
126         log.Print("keepclient created")
127         if bogusClientToken {
128                 arvadostest.ResetEnv()
129         }
130
131         {
132                 os.Args = append(args, fmt.Sprintf("-listen=:%v", port))
133                 listener = nil
134                 go main()
135         }
136
137         return kc
138 }
139
140 func (s *ServerRequiredSuite) TestPutAskGet(c *C) {
141         log.Print("TestPutAndGet start")
142
143         os.Args = []string{"keepproxy", "-listen=:29950"}
144         listener = nil
145         go main()
146         time.Sleep(100 * time.Millisecond)
147
148         setupProxyService()
149
150         os.Setenv("ARVADOS_EXTERNAL_CLIENT", "true")
151         arv, err := arvadosclient.MakeArvadosClient()
152         c.Assert(err, Equals, nil)
153         kc, err := keepclient.MakeKeepClient(&arv)
154         c.Assert(err, Equals, nil)
155         c.Check(kc.Arvados.External, Equals, true)
156         c.Check(kc.Using_proxy, Equals, true)
157         c.Check(len(kc.ServiceRoots()), Equals, 1)
158         for _, root := range kc.ServiceRoots() {
159                 c.Check(root, Equals, "http://localhost:29950")
160         }
161         os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
162
163         waitForListener()
164         defer closeListener()
165
166         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
167         var hash2 string
168
169         {
170                 _, _, err := kc.Ask(hash)
171                 c.Check(err, Equals, keepclient.BlockNotFound)
172                 log.Print("Ask 1")
173         }
174
175         {
176                 var rep int
177                 var err error
178                 hash2, rep, err = kc.PutB([]byte("foo"))
179                 c.Check(hash2, Matches, fmt.Sprintf(`^%s\+3(\+.+)?$`, hash))
180                 c.Check(rep, Equals, 2)
181                 c.Check(err, Equals, nil)
182                 log.Print("PutB")
183         }
184
185         {
186                 blocklen, _, err := kc.Ask(hash2)
187                 c.Assert(err, Equals, nil)
188                 c.Check(blocklen, Equals, int64(3))
189                 log.Print("Ask 2")
190         }
191
192         {
193                 reader, blocklen, _, err := kc.Get(hash2)
194                 c.Assert(err, Equals, nil)
195                 all, err := ioutil.ReadAll(reader)
196                 c.Check(all, DeepEquals, []byte("foo"))
197                 c.Check(blocklen, Equals, int64(3))
198                 log.Print("Get")
199         }
200
201         {
202                 var rep int
203                 var err error
204                 hash2, rep, err = kc.PutB([]byte(""))
205                 c.Check(hash2, Matches, `^d41d8cd98f00b204e9800998ecf8427e\+0(\+.+)?$`)
206                 c.Check(rep, Equals, 2)
207                 c.Check(err, Equals, nil)
208                 log.Print("PutB zero block")
209         }
210
211         {
212                 reader, blocklen, _, err := kc.Get("d41d8cd98f00b204e9800998ecf8427e")
213                 c.Assert(err, Equals, nil)
214                 all, err := ioutil.ReadAll(reader)
215                 c.Check(all, DeepEquals, []byte(""))
216                 c.Check(blocklen, Equals, int64(0))
217                 log.Print("Get zero block")
218         }
219
220         log.Print("TestPutAndGet done")
221 }
222
223 func (s *ServerRequiredSuite) TestPutAskGetForbidden(c *C) {
224         log.Print("TestPutAskGetForbidden start")
225
226         kc := runProxy(c, []string{"keepproxy"}, 29951, true)
227         waitForListener()
228         defer closeListener()
229
230         hash := fmt.Sprintf("%x", md5.Sum([]byte("bar")))
231
232         {
233                 _, _, err := kc.Ask(hash)
234                 c.Check(err, Equals, keepclient.BlockNotFound)
235                 log.Print("Ask 1")
236         }
237
238         {
239                 hash2, rep, err := kc.PutB([]byte("bar"))
240                 c.Check(hash2, Equals, "")
241                 c.Check(rep, Equals, 0)
242                 c.Check(err, Equals, keepclient.InsufficientReplicasError)
243                 log.Print("PutB")
244         }
245
246         {
247                 blocklen, _, err := kc.Ask(hash)
248                 c.Assert(err, Equals, keepclient.BlockNotFound)
249                 c.Check(blocklen, Equals, int64(0))
250                 log.Print("Ask 2")
251         }
252
253         {
254                 _, blocklen, _, err := kc.Get(hash)
255                 c.Assert(err, Equals, keepclient.BlockNotFound)
256                 c.Check(blocklen, Equals, int64(0))
257                 log.Print("Get")
258         }
259
260         log.Print("TestPutAskGetForbidden done")
261 }
262
263 func (s *ServerRequiredSuite) TestGetDisabled(c *C) {
264         log.Print("TestGetDisabled start")
265
266         kc := runProxy(c, []string{"keepproxy", "-no-get"}, 29952, false)
267         waitForListener()
268         defer closeListener()
269
270         hash := fmt.Sprintf("%x", md5.Sum([]byte("baz")))
271
272         {
273                 _, _, err := kc.Ask(hash)
274                 c.Check(err, Equals, keepclient.BlockNotFound)
275                 log.Print("Ask 1")
276         }
277
278         {
279                 hash2, rep, err := kc.PutB([]byte("baz"))
280                 c.Check(hash2, Matches, fmt.Sprintf(`^%s\+3(\+.+)?$`, hash))
281                 c.Check(rep, Equals, 2)
282                 c.Check(err, Equals, nil)
283                 log.Print("PutB")
284         }
285
286         {
287                 blocklen, _, err := kc.Ask(hash)
288                 c.Assert(err, Equals, keepclient.BlockNotFound)
289                 c.Check(blocklen, Equals, int64(0))
290                 log.Print("Ask 2")
291         }
292
293         {
294                 _, blocklen, _, err := kc.Get(hash)
295                 c.Assert(err, Equals, keepclient.BlockNotFound)
296                 c.Check(blocklen, Equals, int64(0))
297                 log.Print("Get")
298         }
299
300         log.Print("TestGetDisabled done")
301 }
302
303 func (s *ServerRequiredSuite) TestPutDisabled(c *C) {
304         log.Print("TestPutDisabled start")
305
306         kc := runProxy(c, []string{"keepproxy", "-no-put"}, 29953, false)
307         waitForListener()
308         defer closeListener()
309
310         {
311                 hash2, rep, err := kc.PutB([]byte("quux"))
312                 c.Check(hash2, Equals, "")
313                 c.Check(rep, Equals, 0)
314                 c.Check(err, Equals, keepclient.InsufficientReplicasError)
315                 log.Print("PutB")
316         }
317
318         log.Print("TestPutDisabled done")
319 }
320
321 func (s *ServerRequiredSuite) TestCorsHeaders(c *C) {
322         runProxy(c, []string{"keepproxy"}, 29954, false)
323         waitForListener()
324         defer closeListener()
325
326         {
327                 client := http.Client{}
328                 req, err := http.NewRequest("OPTIONS",
329                         fmt.Sprintf("http://localhost:29954/%x+3",
330                                 md5.Sum([]byte("foo"))),
331                         nil)
332                 req.Header.Add("Access-Control-Request-Method", "PUT")
333                 req.Header.Add("Access-Control-Request-Headers", "Authorization, X-Keep-Desired-Replicas")
334                 resp, err := client.Do(req)
335                 c.Check(err, Equals, nil)
336                 c.Check(resp.StatusCode, Equals, 200)
337                 body, err := ioutil.ReadAll(resp.Body)
338                 c.Check(string(body), Equals, "")
339                 c.Check(resp.Header.Get("Access-Control-Allow-Methods"), Equals, "GET, HEAD, POST, PUT, OPTIONS")
340                 c.Check(resp.Header.Get("Access-Control-Allow-Origin"), Equals, "*")
341         }
342
343         {
344                 resp, err := http.Get(
345                         fmt.Sprintf("http://localhost:29954/%x+3",
346                                 md5.Sum([]byte("foo"))))
347                 c.Check(err, Equals, nil)
348                 c.Check(resp.Header.Get("Access-Control-Allow-Headers"), Equals, "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
349                 c.Check(resp.Header.Get("Access-Control-Allow-Origin"), Equals, "*")
350         }
351 }
352
353 func (s *ServerRequiredSuite) TestPostWithoutHash(c *C) {
354         runProxy(c, []string{"keepproxy"}, 29955, false)
355         waitForListener()
356         defer closeListener()
357
358         {
359                 client := http.Client{}
360                 req, err := http.NewRequest("POST",
361                         "http://localhost:29955/",
362                         strings.NewReader("qux"))
363                 req.Header.Add("Authorization", "OAuth2 4axaw8zxe0qm22wa6urpp5nskcne8z88cvbupv653y1njyi05h")
364                 req.Header.Add("Content-Type", "application/octet-stream")
365                 resp, err := client.Do(req)
366                 c.Check(err, Equals, nil)
367                 body, err := ioutil.ReadAll(resp.Body)
368                 c.Check(err, Equals, nil)
369                 c.Check(string(body), Equals,
370                         fmt.Sprintf("%x+%d", md5.Sum([]byte("qux")), 3))
371         }
372 }