1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
23 "git.curoverse.com/arvados.git/sdk/go/arvadostest"
24 "git.curoverse.com/arvados.git/sdk/go/keepclient"
29 // Gocheck boilerplate
30 func Test(t *testing.T) {
34 // Gocheck boilerplate
35 var _ = Suite(&ServerRequiredSuite{})
37 // Tests that require the Keep server running
38 type ServerRequiredSuite struct{}
40 // Gocheck boilerplate
41 var _ = Suite(&NoKeepServerSuite{})
43 // Test with no keepserver to simulate errors
44 type NoKeepServerSuite struct{}
46 var TestProxyUUID = "zzzzz-bi6l4-lrixqc4fxofbmzz"
48 // Wait (up to 1 second) for keepproxy to listen on a port. This
49 // avoids a race condition where we hit a "connection refused" error
50 // because we start testing the proxy too soon.
51 func waitForListener() {
55 for i := 0; listener == nil && i < 10000; i += ms {
56 time.Sleep(ms * time.Millisecond)
59 panic("Timed out waiting for listener to start")
63 func closeListener() {
69 func (s *ServerRequiredSuite) SetUpSuite(c *C) {
70 arvadostest.StartAPI()
71 arvadostest.StartKeep(2, false)
74 func (s *ServerRequiredSuite) SetUpTest(c *C) {
75 arvadostest.ResetEnv()
78 func (s *ServerRequiredSuite) TearDownSuite(c *C) {
79 arvadostest.StopKeep(2)
83 func (s *NoKeepServerSuite) SetUpSuite(c *C) {
84 arvadostest.StartAPI()
85 // We need API to have some keep services listed, but the
86 // services themselves should be unresponsive.
87 arvadostest.StartKeep(2, false)
88 arvadostest.StopKeep(2)
91 func (s *NoKeepServerSuite) SetUpTest(c *C) {
92 arvadostest.ResetEnv()
95 func (s *NoKeepServerSuite) TearDownSuite(c *C) {
99 func runProxy(c *C, args []string, bogusClientToken bool) *keepclient.KeepClient {
100 args = append([]string{"keepproxy"}, args...)
101 os.Args = append(args, "-listen=:0")
106 arv, err := arvadosclient.MakeArvadosClient()
107 c.Assert(err, Equals, nil)
108 if bogusClientToken {
109 arv.ApiToken = "bogus-token"
111 kc := keepclient.New(arv)
112 sr := map[string]string{
113 TestProxyUUID: "http://" + listener.Addr().String(),
115 kc.SetServiceRoots(sr, sr, sr)
116 kc.Arvados.External = true
121 func (s *ServerRequiredSuite) TestResponseViaHeader(c *C) {
122 runProxy(c, nil, false)
123 defer closeListener()
125 req, err := http.NewRequest("POST",
126 "http://"+listener.Addr().String()+"/",
127 strings.NewReader("TestViaHeader"))
128 req.Header.Add("Authorization", "OAuth2 "+arvadostest.ActiveToken)
129 resp, err := (&http.Client{}).Do(req)
130 c.Assert(err, Equals, nil)
131 c.Check(resp.Header.Get("Via"), Equals, "HTTP/1.1 keepproxy")
132 locator, err := ioutil.ReadAll(resp.Body)
133 c.Assert(err, Equals, nil)
136 req, err = http.NewRequest("GET",
137 "http://"+listener.Addr().String()+"/"+string(locator),
139 c.Assert(err, Equals, nil)
140 resp, err = (&http.Client{}).Do(req)
141 c.Assert(err, Equals, nil)
142 c.Check(resp.Header.Get("Via"), Equals, "HTTP/1.1 keepproxy")
146 func (s *ServerRequiredSuite) TestLoopDetection(c *C) {
147 kc := runProxy(c, nil, false)
148 defer closeListener()
150 sr := map[string]string{
151 TestProxyUUID: "http://" + listener.Addr().String(),
153 router.(*proxyHandler).KeepClient.SetServiceRoots(sr, sr, sr)
155 content := []byte("TestLoopDetection")
156 _, _, err := kc.PutB(content)
157 c.Check(err, ErrorMatches, `.*loop detected.*`)
159 hash := fmt.Sprintf("%x", md5.Sum(content))
160 _, _, _, err = kc.Get(hash)
161 c.Check(err, ErrorMatches, `.*loop detected.*`)
164 func (s *ServerRequiredSuite) TestDesiredReplicas(c *C) {
165 kc := runProxy(c, nil, false)
166 defer closeListener()
168 content := []byte("TestDesiredReplicas")
169 hash := fmt.Sprintf("%x", md5.Sum(content))
171 for _, kc.Want_replicas = range []int{0, 1, 2} {
172 locator, rep, err := kc.PutB(content)
173 c.Check(err, Equals, nil)
174 c.Check(rep, Equals, kc.Want_replicas)
176 c.Check(locator, Matches, fmt.Sprintf(`^%s\+%d(\+.+)?$`, hash, len(content)))
181 func (s *ServerRequiredSuite) TestPutWrongContentLength(c *C) {
182 kc := runProxy(c, nil, false)
183 defer closeListener()
185 content := []byte("TestPutWrongContentLength")
186 hash := fmt.Sprintf("%x", md5.Sum(content))
188 // If we use http.Client to send these requests to the network
189 // server we just started, the Go http library automatically
190 // fixes the invalid Content-Length header. In order to test
191 // our server behavior, we have to call the handler directly
192 // using an httptest.ResponseRecorder.
193 rtr := MakeRESTRouter(true, true, kc, 10*time.Second, "")
195 type testcase struct {
200 for _, t := range []testcase{
201 {"1", http.StatusBadRequest},
202 {"", http.StatusLengthRequired},
203 {"-1", http.StatusLengthRequired},
204 {"abcdef", http.StatusLengthRequired},
206 req, err := http.NewRequest("PUT",
207 fmt.Sprintf("http://%s/%s+%d", listener.Addr().String(), hash, len(content)),
208 bytes.NewReader(content))
210 req.Header.Set("Content-Length", t.sendLength)
211 req.Header.Set("Authorization", "OAuth2 "+arvadostest.ActiveToken)
212 req.Header.Set("Content-Type", "application/octet-stream")
214 resp := httptest.NewRecorder()
215 rtr.ServeHTTP(resp, req)
216 c.Check(resp.Code, Equals, t.expectStatus)
220 func (s *ServerRequiredSuite) TestManyFailedPuts(c *C) {
221 kc := runProxy(c, nil, false)
222 defer closeListener()
223 router.(*proxyHandler).timeout = time.Nanosecond
225 buf := make([]byte, 1<<20)
227 var wg sync.WaitGroup
228 for i := 0; i < 128; i++ {
235 done := make(chan bool)
242 case <-time.After(10 * time.Second):
247 func (s *ServerRequiredSuite) TestPutAskGet(c *C) {
248 kc := runProxy(c, nil, false)
249 defer closeListener()
251 hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
255 _, _, err := kc.Ask(hash)
256 c.Check(err, Equals, keepclient.BlockNotFound)
257 c.Log("Finished Ask (expected BlockNotFound)")
261 reader, _, _, err := kc.Get(hash)
262 c.Check(reader, Equals, nil)
263 c.Check(err, Equals, keepclient.BlockNotFound)
264 c.Log("Finished Get (expected BlockNotFound)")
267 // Note in bug #5309 among other errors keepproxy would set
268 // Content-Length incorrectly on the 404 BlockNotFound response, this
269 // would result in a protocol violation that would prevent reuse of the
270 // connection, which would manifest by the next attempt to use the
271 // connection (in this case the PutB below) failing. So to test for
272 // that bug it's necessary to trigger an error response (such as
273 // BlockNotFound) and then do something else with the same httpClient
279 hash2, rep, err = kc.PutB([]byte("foo"))
280 c.Check(hash2, Matches, fmt.Sprintf(`^%s\+3(\+.+)?$`, hash))
281 c.Check(rep, Equals, 2)
282 c.Check(err, Equals, nil)
283 c.Log("Finished PutB (expected success)")
287 blocklen, _, err := kc.Ask(hash2)
288 c.Assert(err, Equals, nil)
289 c.Check(blocklen, Equals, int64(3))
290 c.Log("Finished Ask (expected success)")
294 reader, blocklen, _, err := kc.Get(hash2)
295 c.Assert(err, Equals, nil)
296 all, err := ioutil.ReadAll(reader)
297 c.Check(all, DeepEquals, []byte("foo"))
298 c.Check(blocklen, Equals, int64(3))
299 c.Log("Finished Get (expected success)")
305 hash2, rep, err = kc.PutB([]byte(""))
306 c.Check(hash2, Matches, `^d41d8cd98f00b204e9800998ecf8427e\+0(\+.+)?$`)
307 c.Check(rep, Equals, 2)
308 c.Check(err, Equals, nil)
309 c.Log("Finished PutB zero block")
313 reader, blocklen, _, err := kc.Get("d41d8cd98f00b204e9800998ecf8427e")
314 c.Assert(err, Equals, nil)
315 all, err := ioutil.ReadAll(reader)
316 c.Check(all, DeepEquals, []byte(""))
317 c.Check(blocklen, Equals, int64(0))
318 c.Log("Finished Get zero block")
322 func (s *ServerRequiredSuite) TestPutAskGetForbidden(c *C) {
323 kc := runProxy(c, nil, true)
324 defer closeListener()
326 hash := fmt.Sprintf("%x", md5.Sum([]byte("bar")))
329 _, _, err := kc.Ask(hash)
330 errNotFound, _ := err.(keepclient.ErrNotFound)
331 c.Check(errNotFound, NotNil)
332 c.Assert(strings.Contains(err.Error(), "HTTP 403"), Equals, true)
337 hash2, rep, err := kc.PutB([]byte("bar"))
338 c.Check(hash2, Equals, "")
339 c.Check(rep, Equals, 0)
340 c.Check(err, FitsTypeOf, keepclient.InsufficientReplicasError(errors.New("")))
345 blocklen, _, err := kc.Ask(hash)
346 errNotFound, _ := err.(keepclient.ErrNotFound)
347 c.Check(errNotFound, NotNil)
348 c.Assert(strings.Contains(err.Error(), "HTTP 403"), Equals, true)
349 c.Check(blocklen, Equals, int64(0))
354 _, blocklen, _, err := kc.Get(hash)
355 errNotFound, _ := err.(keepclient.ErrNotFound)
356 c.Check(errNotFound, NotNil)
357 c.Assert(strings.Contains(err.Error(), "HTTP 403"), Equals, true)
358 c.Check(blocklen, Equals, int64(0))
363 func (s *ServerRequiredSuite) TestGetDisabled(c *C) {
364 kc := runProxy(c, []string{"-no-get"}, false)
365 defer closeListener()
367 hash := fmt.Sprintf("%x", md5.Sum([]byte("baz")))
370 _, _, err := kc.Ask(hash)
371 errNotFound, _ := err.(keepclient.ErrNotFound)
372 c.Check(errNotFound, NotNil)
373 c.Assert(strings.Contains(err.Error(), "HTTP 400"), Equals, true)
378 hash2, rep, err := kc.PutB([]byte("baz"))
379 c.Check(hash2, Matches, fmt.Sprintf(`^%s\+3(\+.+)?$`, hash))
380 c.Check(rep, Equals, 2)
381 c.Check(err, Equals, nil)
386 blocklen, _, err := kc.Ask(hash)
387 errNotFound, _ := err.(keepclient.ErrNotFound)
388 c.Check(errNotFound, NotNil)
389 c.Assert(strings.Contains(err.Error(), "HTTP 400"), Equals, true)
390 c.Check(blocklen, Equals, int64(0))
395 _, blocklen, _, err := kc.Get(hash)
396 errNotFound, _ := err.(keepclient.ErrNotFound)
397 c.Check(errNotFound, NotNil)
398 c.Assert(strings.Contains(err.Error(), "HTTP 400"), Equals, true)
399 c.Check(blocklen, Equals, int64(0))
404 func (s *ServerRequiredSuite) TestPutDisabled(c *C) {
405 kc := runProxy(c, []string{"-no-put"}, false)
406 defer closeListener()
408 hash2, rep, err := kc.PutB([]byte("quux"))
409 c.Check(hash2, Equals, "")
410 c.Check(rep, Equals, 0)
411 c.Check(err, FitsTypeOf, keepclient.InsufficientReplicasError(errors.New("")))
414 func (s *ServerRequiredSuite) TestCorsHeaders(c *C) {
415 runProxy(c, nil, false)
416 defer closeListener()
419 client := http.Client{}
420 req, err := http.NewRequest("OPTIONS",
421 fmt.Sprintf("http://%s/%x+3", listener.Addr().String(), md5.Sum([]byte("foo"))),
423 req.Header.Add("Access-Control-Request-Method", "PUT")
424 req.Header.Add("Access-Control-Request-Headers", "Authorization, X-Keep-Desired-Replicas")
425 resp, err := client.Do(req)
426 c.Check(err, Equals, nil)
427 c.Check(resp.StatusCode, Equals, 200)
428 body, err := ioutil.ReadAll(resp.Body)
429 c.Check(string(body), Equals, "")
430 c.Check(resp.Header.Get("Access-Control-Allow-Methods"), Equals, "GET, HEAD, POST, PUT, OPTIONS")
431 c.Check(resp.Header.Get("Access-Control-Allow-Origin"), Equals, "*")
435 resp, err := http.Get(
436 fmt.Sprintf("http://%s/%x+3", listener.Addr().String(), md5.Sum([]byte("foo"))))
437 c.Check(err, Equals, nil)
438 c.Check(resp.Header.Get("Access-Control-Allow-Headers"), Equals, "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
439 c.Check(resp.Header.Get("Access-Control-Allow-Origin"), Equals, "*")
443 func (s *ServerRequiredSuite) TestPostWithoutHash(c *C) {
444 runProxy(c, nil, false)
445 defer closeListener()
448 client := http.Client{}
449 req, err := http.NewRequest("POST",
450 "http://"+listener.Addr().String()+"/",
451 strings.NewReader("qux"))
452 req.Header.Add("Authorization", "OAuth2 "+arvadostest.ActiveToken)
453 req.Header.Add("Content-Type", "application/octet-stream")
454 resp, err := client.Do(req)
455 c.Check(err, Equals, nil)
456 body, err := ioutil.ReadAll(resp.Body)
457 c.Check(err, Equals, nil)
458 c.Check(string(body), Matches,
459 fmt.Sprintf(`^%x\+3(\+.+)?$`, md5.Sum([]byte("qux"))))
463 func (s *ServerRequiredSuite) TestStripHint(c *C) {
464 c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73+K@zzzzz", "$1"),
466 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73")
467 c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+K@zzzzz+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73", "$1"),
469 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73")
470 c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz", "$1"),
472 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz")
473 c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73", "$1"),
475 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73")
480 // Put one block, with 2 replicas
481 // With no prefix (expect the block locator, twice)
482 // With an existing prefix (expect the block locator, twice)
483 // With a valid but non-existing prefix (expect "\n")
484 // With an invalid prefix (expect error)
485 func (s *ServerRequiredSuite) TestGetIndex(c *C) {
486 kc := runProxy(c, nil, false)
487 defer closeListener()
489 // Put "index-data" blocks
490 data := []byte("index-data")
491 hash := fmt.Sprintf("%x", md5.Sum(data))
493 hash2, rep, err := kc.PutB(data)
494 c.Check(hash2, Matches, fmt.Sprintf(`^%s\+10(\+.+)?$`, hash))
495 c.Check(rep, Equals, 2)
496 c.Check(err, Equals, nil)
498 reader, blocklen, _, err := kc.Get(hash)
499 c.Assert(err, Equals, nil)
500 c.Check(blocklen, Equals, int64(10))
501 all, err := ioutil.ReadAll(reader)
502 c.Check(all, DeepEquals, data)
504 // Put some more blocks
505 _, rep, err = kc.PutB([]byte("some-more-index-data"))
506 c.Check(err, Equals, nil)
508 kc.Arvados.ApiToken = arvadostest.DataManagerToken
511 for _, spec := range []struct {
516 {"", true, true}, // with no prefix
517 {hash[:3], true, false}, // with matching prefix
518 {"abcdef", false, false}, // with no such prefix
520 indexReader, err := kc.GetIndex(TestProxyUUID, spec.prefix)
521 c.Assert(err, Equals, nil)
522 indexResp, err := ioutil.ReadAll(indexReader)
523 c.Assert(err, Equals, nil)
524 locators := strings.Split(string(indexResp), "\n")
527 for _, locator := range locators {
531 c.Check(locator[:len(spec.prefix)], Equals, spec.prefix)
532 if locator[:32] == hash {
538 c.Check(gotTestHash == 2, Equals, spec.expectTestHash)
539 c.Check(gotOther > 0, Equals, spec.expectOther)
542 // GetIndex with invalid prefix
543 _, err = kc.GetIndex(TestProxyUUID, "xyz")
544 c.Assert((err != nil), Equals, true)
547 func (s *ServerRequiredSuite) TestPutAskGetInvalidToken(c *C) {
548 kc := runProxy(c, nil, false)
549 defer closeListener()
552 hash, rep, err := kc.PutB([]byte("foo"))
553 c.Check(err, Equals, nil)
554 c.Check(rep, Equals, 2)
556 for _, token := range []string{
558 "2ym314ysp27sk7h943q6vtc378srb06se3pq6ghurylyf3pdmx", // expired
560 // Change token to given bad token
561 kc.Arvados.ApiToken = token
563 // Ask should result in error
564 _, _, err = kc.Ask(hash)
566 errNotFound, _ := err.(keepclient.ErrNotFound)
567 c.Check(errNotFound.Temporary(), Equals, false)
568 c.Assert(strings.Contains(err.Error(), "HTTP 403"), Equals, true)
570 // Get should result in error
571 _, _, _, err = kc.Get(hash)
573 errNotFound, _ = err.(keepclient.ErrNotFound)
574 c.Check(errNotFound.Temporary(), Equals, false)
575 c.Assert(strings.Contains(err.Error(), "HTTP 403 \"Missing or invalid Authorization header\""), Equals, true)
579 func (s *ServerRequiredSuite) TestAskGetKeepProxyConnectionError(c *C) {
580 arv, err := arvadosclient.MakeArvadosClient()
581 c.Assert(err, Equals, nil)
583 // keepclient with no such keep server
584 kc := keepclient.New(arv)
585 locals := map[string]string{
586 TestProxyUUID: "http://localhost:12345",
588 kc.SetServiceRoots(locals, nil, nil)
590 // Ask should result in temporary connection refused error
591 hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
592 _, _, err = kc.Ask(hash)
594 errNotFound, _ := err.(*keepclient.ErrNotFound)
595 c.Check(errNotFound.Temporary(), Equals, true)
596 c.Assert(strings.Contains(err.Error(), "connection refused"), Equals, true)
598 // Get should result in temporary connection refused error
599 _, _, _, err = kc.Get(hash)
601 errNotFound, _ = err.(*keepclient.ErrNotFound)
602 c.Check(errNotFound.Temporary(), Equals, true)
603 c.Assert(strings.Contains(err.Error(), "connection refused"), Equals, true)
606 func (s *NoKeepServerSuite) TestAskGetNoKeepServerError(c *C) {
607 kc := runProxy(c, nil, false)
608 defer closeListener()
610 hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
611 for _, f := range []func() error{
613 _, _, err := kc.Ask(hash)
617 _, _, _, err := kc.Get(hash)
622 c.Assert(err, NotNil)
623 errNotFound, _ := err.(*keepclient.ErrNotFound)
624 c.Check(errNotFound.Temporary(), Equals, true)
625 c.Check(err, ErrorMatches, `.*HTTP 502.*`)
629 func (s *ServerRequiredSuite) TestPing(c *C) {
630 kc := runProxy(c, nil, false)
631 defer closeListener()
633 rtr := MakeRESTRouter(true, true, kc, 10*time.Second, arvadostest.ManagementToken)
635 req, err := http.NewRequest("GET",
636 "http://"+listener.Addr().String()+"/_health/ping",
639 req.Header.Set("Authorization", "Bearer "+arvadostest.ManagementToken)
641 resp := httptest.NewRecorder()
642 rtr.ServeHTTP(resp, req)
643 c.Check(resp.Code, Equals, 200)
644 c.Assert(strings.Contains(resp.Body.String(), `{"health":"OK"}`), Equals, true)