Merge branch 'master' into wtsi-hgi-feature/arv-view
[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         locals := map[string]string{
119                 "proxy": fmt.Sprintf("http://localhost:%v", port),
120         }
121         writableLocals := map[string]string{
122                 "proxy": fmt.Sprintf("http://localhost:%v", port),
123         }
124         kc.SetServiceRoots(locals, writableLocals, nil)
125         c.Check(kc.Using_proxy, Equals, true)
126         c.Check(len(kc.LocalRoots()), Equals, 1)
127         for _, root := range kc.LocalRoots() {
128                 c.Check(root, Equals, fmt.Sprintf("http://localhost:%v", port))
129         }
130         log.Print("keepclient created")
131         if bogusClientToken {
132                 arvadostest.ResetEnv()
133         }
134
135         {
136                 os.Args = append(args, fmt.Sprintf("-listen=:%v", port))
137                 listener = nil
138                 go main()
139         }
140
141         return kc
142 }
143
144 func (s *ServerRequiredSuite) TestPutAskGet(c *C) {
145         log.Print("TestPutAndGet start")
146
147         os.Args = []string{"keepproxy", "-listen=:29950"}
148         listener = nil
149         go main()
150         time.Sleep(100 * time.Millisecond)
151
152         setupProxyService()
153
154         os.Setenv("ARVADOS_EXTERNAL_CLIENT", "true")
155         arv, err := arvadosclient.MakeArvadosClient()
156         c.Assert(err, Equals, nil)
157         kc, err := keepclient.MakeKeepClient(&arv)
158         c.Assert(err, Equals, nil)
159         c.Check(kc.Arvados.External, Equals, true)
160         c.Check(kc.Using_proxy, Equals, true)
161         c.Check(len(kc.LocalRoots()), Equals, 1)
162         for _, root := range kc.LocalRoots() {
163                 c.Check(root, Equals, "http://localhost:29950")
164         }
165         os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
166
167         waitForListener()
168         defer closeListener()
169
170         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
171         var hash2 string
172
173         {
174                 _, _, err := kc.Ask(hash)
175                 c.Check(err, Equals, keepclient.BlockNotFound)
176                 log.Print("Finished Ask (expected BlockNotFound)")
177         }
178
179         {
180                 reader, _, _, err := kc.Get(hash)
181                 c.Check(reader, Equals, nil)
182                 c.Check(err, Equals, keepclient.BlockNotFound)
183                 log.Print("Finished Get (expected BlockNotFound)")
184         }
185
186         // Note in bug #5309 among other errors keepproxy would set
187         // Content-Length incorrectly on the 404 BlockNotFound response, this
188         // would result in a protocol violation that would prevent reuse of the
189         // connection, which would manifest by the next attempt to use the
190         // connection (in this case the PutB below) failing.  So to test for
191         // that bug it's necessary to trigger an error response (such as
192         // BlockNotFound) and then do something else with the same httpClient
193         // connection.
194
195         {
196                 var rep int
197                 var err error
198                 hash2, rep, err = kc.PutB([]byte("foo"))
199                 c.Check(hash2, Matches, fmt.Sprintf(`^%s\+3(\+.+)?$`, hash))
200                 c.Check(rep, Equals, 2)
201                 c.Check(err, Equals, nil)
202                 log.Print("Finished PutB (expected success)")
203         }
204
205         {
206                 blocklen, _, err := kc.Ask(hash2)
207                 c.Assert(err, Equals, nil)
208                 c.Check(blocklen, Equals, int64(3))
209                 log.Print("Finished Ask (expected success)")
210         }
211
212         {
213                 reader, blocklen, _, err := kc.Get(hash2)
214                 c.Assert(err, Equals, nil)
215                 all, err := ioutil.ReadAll(reader)
216                 c.Check(all, DeepEquals, []byte("foo"))
217                 c.Check(blocklen, Equals, int64(3))
218                 log.Print("Finished Get (expected success)")
219         }
220
221         {
222                 var rep int
223                 var err error
224                 hash2, rep, err = kc.PutB([]byte(""))
225                 c.Check(hash2, Matches, `^d41d8cd98f00b204e9800998ecf8427e\+0(\+.+)?$`)
226                 c.Check(rep, Equals, 2)
227                 c.Check(err, Equals, nil)
228                 log.Print("Finished PutB zero block")
229         }
230
231         {
232                 reader, blocklen, _, err := kc.Get("d41d8cd98f00b204e9800998ecf8427e")
233                 c.Assert(err, Equals, nil)
234                 all, err := ioutil.ReadAll(reader)
235                 c.Check(all, DeepEquals, []byte(""))
236                 c.Check(blocklen, Equals, int64(0))
237                 log.Print("Finished Get zero block")
238         }
239
240         log.Print("TestPutAndGet done")
241 }
242
243 func (s *ServerRequiredSuite) TestPutAskGetForbidden(c *C) {
244         log.Print("TestPutAskGetForbidden start")
245
246         kc := runProxy(c, []string{"keepproxy"}, 29951, true)
247         waitForListener()
248         defer closeListener()
249
250         hash := fmt.Sprintf("%x", md5.Sum([]byte("bar")))
251
252         {
253                 _, _, err := kc.Ask(hash)
254                 c.Check(err, Equals, keepclient.BlockNotFound)
255                 log.Print("Ask 1")
256         }
257
258         {
259                 hash2, rep, err := kc.PutB([]byte("bar"))
260                 c.Check(hash2, Equals, "")
261                 c.Check(rep, Equals, 0)
262                 c.Check(err, Equals, keepclient.InsufficientReplicasError)
263                 log.Print("PutB")
264         }
265
266         {
267                 blocklen, _, err := kc.Ask(hash)
268                 c.Assert(err, Equals, keepclient.BlockNotFound)
269                 c.Check(blocklen, Equals, int64(0))
270                 log.Print("Ask 2")
271         }
272
273         {
274                 _, blocklen, _, err := kc.Get(hash)
275                 c.Assert(err, Equals, keepclient.BlockNotFound)
276                 c.Check(blocklen, Equals, int64(0))
277                 log.Print("Get")
278         }
279
280         log.Print("TestPutAskGetForbidden done")
281 }
282
283 func (s *ServerRequiredSuite) TestGetDisabled(c *C) {
284         log.Print("TestGetDisabled start")
285
286         kc := runProxy(c, []string{"keepproxy", "-no-get"}, 29952, false)
287         waitForListener()
288         defer closeListener()
289
290         hash := fmt.Sprintf("%x", md5.Sum([]byte("baz")))
291
292         {
293                 _, _, err := kc.Ask(hash)
294                 c.Check(err, Equals, keepclient.BlockNotFound)
295                 log.Print("Ask 1")
296         }
297
298         {
299                 hash2, rep, err := kc.PutB([]byte("baz"))
300                 c.Check(hash2, Matches, fmt.Sprintf(`^%s\+3(\+.+)?$`, hash))
301                 c.Check(rep, Equals, 2)
302                 c.Check(err, Equals, nil)
303                 log.Print("PutB")
304         }
305
306         {
307                 blocklen, _, err := kc.Ask(hash)
308                 c.Assert(err, Equals, keepclient.BlockNotFound)
309                 c.Check(blocklen, Equals, int64(0))
310                 log.Print("Ask 2")
311         }
312
313         {
314                 _, blocklen, _, err := kc.Get(hash)
315                 c.Assert(err, Equals, keepclient.BlockNotFound)
316                 c.Check(blocklen, Equals, int64(0))
317                 log.Print("Get")
318         }
319
320         log.Print("TestGetDisabled done")
321 }
322
323 func (s *ServerRequiredSuite) TestPutDisabled(c *C) {
324         log.Print("TestPutDisabled start")
325
326         kc := runProxy(c, []string{"keepproxy", "-no-put"}, 29953, false)
327         waitForListener()
328         defer closeListener()
329
330         {
331                 hash2, rep, err := kc.PutB([]byte("quux"))
332                 c.Check(hash2, Equals, "")
333                 c.Check(rep, Equals, 0)
334                 c.Check(err, Equals, keepclient.InsufficientReplicasError)
335                 log.Print("PutB")
336         }
337
338         log.Print("TestPutDisabled done")
339 }
340
341 func (s *ServerRequiredSuite) TestCorsHeaders(c *C) {
342         runProxy(c, []string{"keepproxy"}, 29954, false)
343         waitForListener()
344         defer closeListener()
345
346         {
347                 client := http.Client{}
348                 req, err := http.NewRequest("OPTIONS",
349                         fmt.Sprintf("http://localhost:29954/%x+3",
350                                 md5.Sum([]byte("foo"))),
351                         nil)
352                 req.Header.Add("Access-Control-Request-Method", "PUT")
353                 req.Header.Add("Access-Control-Request-Headers", "Authorization, X-Keep-Desired-Replicas")
354                 resp, err := client.Do(req)
355                 c.Check(err, Equals, nil)
356                 c.Check(resp.StatusCode, Equals, 200)
357                 body, err := ioutil.ReadAll(resp.Body)
358                 c.Check(string(body), Equals, "")
359                 c.Check(resp.Header.Get("Access-Control-Allow-Methods"), Equals, "GET, HEAD, POST, PUT, OPTIONS")
360                 c.Check(resp.Header.Get("Access-Control-Allow-Origin"), Equals, "*")
361         }
362
363         {
364                 resp, err := http.Get(
365                         fmt.Sprintf("http://localhost:29954/%x+3",
366                                 md5.Sum([]byte("foo"))))
367                 c.Check(err, Equals, nil)
368                 c.Check(resp.Header.Get("Access-Control-Allow-Headers"), Equals, "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
369                 c.Check(resp.Header.Get("Access-Control-Allow-Origin"), Equals, "*")
370         }
371 }
372
373 func (s *ServerRequiredSuite) TestPostWithoutHash(c *C) {
374         runProxy(c, []string{"keepproxy"}, 29955, false)
375         waitForListener()
376         defer closeListener()
377
378         {
379                 client := http.Client{}
380                 req, err := http.NewRequest("POST",
381                         "http://localhost:29955/",
382                         strings.NewReader("qux"))
383                 req.Header.Add("Authorization", "OAuth2 4axaw8zxe0qm22wa6urpp5nskcne8z88cvbupv653y1njyi05h")
384                 req.Header.Add("Content-Type", "application/octet-stream")
385                 resp, err := client.Do(req)
386                 c.Check(err, Equals, nil)
387                 body, err := ioutil.ReadAll(resp.Body)
388                 c.Check(err, Equals, nil)
389                 c.Check(string(body), Matches,
390                         fmt.Sprintf(`^%x\+3(\+.+)?$`, md5.Sum([]byte("qux"))))
391         }
392 }
393
394 func (s *ServerRequiredSuite) TestStripHint(c *C) {
395         c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73+K@zzzzz", "$1"),
396                 Equals,
397                 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73")
398         c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+K@zzzzz+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73", "$1"),
399                 Equals,
400                 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73")
401         c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz", "$1"),
402                 Equals,
403                 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz")
404         c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73", "$1"),
405                 Equals,
406                 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73")
407
408 }
409
410 // Test GetIndex
411 //   Put one block, with 2 replicas
412 //   With no prefix (expect the block locator, twice)
413 //   With an existing prefix (expect the block locator, twice)
414 //   With a valid but non-existing prefix (expect "\n")
415 //   With an invalid prefix (expect error)
416 func (s *ServerRequiredSuite) TestGetIndex(c *C) {
417         kc := runProxy(c, []string{"keepproxy"}, 28852, false)
418         waitForListener()
419         defer closeListener()
420
421         // Put "index-data" blocks
422         data := []byte("index-data")
423         hash := fmt.Sprintf("%x", md5.Sum(data))
424
425         hash2, rep, err := kc.PutB(data)
426         c.Check(hash2, Matches, fmt.Sprintf(`^%s\+10(\+.+)?$`, hash))
427         c.Check(rep, Equals, 2)
428         c.Check(err, Equals, nil)
429
430         reader, blocklen, _, err := kc.Get(hash)
431         c.Assert(err, Equals, nil)
432         c.Check(blocklen, Equals, int64(10))
433         all, err := ioutil.ReadAll(reader)
434         c.Check(all, DeepEquals, data)
435
436         // Put some more blocks
437         _, rep, err = kc.PutB([]byte("some-more-index-data"))
438         c.Check(err, Equals, nil)
439
440         // Invoke GetIndex
441         for _, spec := range []struct {
442                 prefix         string
443                 expectTestHash bool
444                 expectOther    bool
445         }{
446                 {"", true, true},         // with no prefix
447                 {hash[:3], true, false},  // with matching prefix
448                 {"abcdef", false, false}, // with no such prefix
449         } {
450                 indexReader, err := kc.GetIndex("proxy", spec.prefix)
451                 c.Assert(err, Equals, nil)
452                 indexResp, err := ioutil.ReadAll(indexReader)
453                 c.Assert(err, Equals, nil)
454                 locators := strings.Split(string(indexResp), "\n")
455                 gotTestHash := 0
456                 gotOther := 0
457                 for _, locator := range locators {
458                         if locator == "" {
459                                 continue
460                         }
461                         c.Check(locator[:len(spec.prefix)], Equals, spec.prefix)
462                         if locator[:32] == hash {
463                                 gotTestHash++
464                         } else {
465                                 gotOther++
466                         }
467                 }
468                 c.Check(gotTestHash == 2, Equals, spec.expectTestHash)
469                 c.Check(gotOther > 0, Equals, spec.expectOther)
470         }
471
472         // GetIndex with invalid prefix
473         _, err = kc.GetIndex("proxy", "xyz")
474         c.Assert((err != nil), Equals, true)
475 }