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 c.Assert(err, Equals, nil)
129 req.Header.Add("Authorization", "OAuth2 "+arvadostest.ActiveToken)
130 resp, err := (&http.Client{}).Do(req)
131 c.Assert(err, Equals, nil)
132 c.Check(resp.Header.Get("Via"), Equals, "HTTP/1.1 keepproxy")
133 locator, err := ioutil.ReadAll(resp.Body)
134 c.Assert(err, Equals, nil)
137 req, err = http.NewRequest("GET",
138 "http://"+listener.Addr().String()+"/"+string(locator),
140 c.Assert(err, Equals, nil)
141 resp, err = (&http.Client{}).Do(req)
142 c.Assert(err, Equals, nil)
143 c.Check(resp.Header.Get("Via"), Equals, "HTTP/1.1 keepproxy")
147 func (s *ServerRequiredSuite) TestLoopDetection(c *C) {
148 kc := runProxy(c, nil, false)
149 defer closeListener()
151 sr := map[string]string{
152 TestProxyUUID: "http://" + listener.Addr().String(),
154 router.(*proxyHandler).KeepClient.SetServiceRoots(sr, sr, sr)
156 content := []byte("TestLoopDetection")
157 _, _, err := kc.PutB(content)
158 c.Check(err, ErrorMatches, `.*loop detected.*`)
160 hash := fmt.Sprintf("%x", md5.Sum(content))
161 _, _, _, err = kc.Get(hash)
162 c.Check(err, ErrorMatches, `.*loop detected.*`)
165 func (s *ServerRequiredSuite) TestStorageClassesHeader(c *C) {
166 kc := runProxy(c, nil, false)
167 defer closeListener()
169 // Set up fake keepstore to record request headers
171 ts := httptest.NewServer(http.HandlerFunc(
172 func(w http.ResponseWriter, r *http.Request) {
174 http.Error(w, "Error", http.StatusInternalServerError)
178 // Point keepproxy router's keepclient to the fake keepstore
179 sr := map[string]string{
180 TestProxyUUID: ts.URL,
182 router.(*proxyHandler).KeepClient.SetServiceRoots(sr, sr, sr)
184 // Set up client to ask for storage classes to keepproxy
185 kc.StorageClasses = []string{"secure"}
186 content := []byte("Very important data")
187 _, _, err := kc.PutB(content)
189 c.Check(hdr.Get("X-Keep-Storage-Classes"), Equals, "secure")
192 func (s *ServerRequiredSuite) TestDesiredReplicas(c *C) {
193 kc := runProxy(c, nil, false)
194 defer closeListener()
196 content := []byte("TestDesiredReplicas")
197 hash := fmt.Sprintf("%x", md5.Sum(content))
199 for _, kc.Want_replicas = range []int{0, 1, 2} {
200 locator, rep, err := kc.PutB(content)
201 c.Check(err, Equals, nil)
202 c.Check(rep, Equals, kc.Want_replicas)
204 c.Check(locator, Matches, fmt.Sprintf(`^%s\+%d(\+.+)?$`, hash, len(content)))
209 func (s *ServerRequiredSuite) TestPutWrongContentLength(c *C) {
210 kc := runProxy(c, nil, false)
211 defer closeListener()
213 content := []byte("TestPutWrongContentLength")
214 hash := fmt.Sprintf("%x", md5.Sum(content))
216 // If we use http.Client to send these requests to the network
217 // server we just started, the Go http library automatically
218 // fixes the invalid Content-Length header. In order to test
219 // our server behavior, we have to call the handler directly
220 // using an httptest.ResponseRecorder.
221 rtr := MakeRESTRouter(kc, 10*time.Second, "")
223 type testcase struct {
228 for _, t := range []testcase{
229 {"1", http.StatusBadRequest},
230 {"", http.StatusLengthRequired},
231 {"-1", http.StatusLengthRequired},
232 {"abcdef", http.StatusLengthRequired},
234 req, err := http.NewRequest("PUT",
235 fmt.Sprintf("http://%s/%s+%d", listener.Addr().String(), hash, len(content)),
236 bytes.NewReader(content))
238 req.Header.Set("Content-Length", t.sendLength)
239 req.Header.Set("Authorization", "OAuth2 "+arvadostest.ActiveToken)
240 req.Header.Set("Content-Type", "application/octet-stream")
242 resp := httptest.NewRecorder()
243 rtr.ServeHTTP(resp, req)
244 c.Check(resp.Code, Equals, t.expectStatus)
248 func (s *ServerRequiredSuite) TestManyFailedPuts(c *C) {
249 kc := runProxy(c, nil, false)
250 defer closeListener()
251 router.(*proxyHandler).timeout = time.Nanosecond
253 buf := make([]byte, 1<<20)
255 var wg sync.WaitGroup
256 for i := 0; i < 128; i++ {
263 done := make(chan bool)
270 case <-time.After(10 * time.Second):
275 func (s *ServerRequiredSuite) TestPutAskGet(c *C) {
276 kc := runProxy(c, nil, false)
277 defer closeListener()
279 hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
283 _, _, err := kc.Ask(hash)
284 c.Check(err, Equals, keepclient.BlockNotFound)
285 c.Log("Finished Ask (expected BlockNotFound)")
289 reader, _, _, err := kc.Get(hash)
290 c.Check(reader, Equals, nil)
291 c.Check(err, Equals, keepclient.BlockNotFound)
292 c.Log("Finished Get (expected BlockNotFound)")
295 // Note in bug #5309 among other errors keepproxy would set
296 // Content-Length incorrectly on the 404 BlockNotFound response, this
297 // would result in a protocol violation that would prevent reuse of the
298 // connection, which would manifest by the next attempt to use the
299 // connection (in this case the PutB below) failing. So to test for
300 // that bug it's necessary to trigger an error response (such as
301 // BlockNotFound) and then do something else with the same httpClient
307 hash2, rep, err = kc.PutB([]byte("foo"))
308 c.Check(hash2, Matches, fmt.Sprintf(`^%s\+3(\+.+)?$`, hash))
309 c.Check(rep, Equals, 2)
310 c.Check(err, Equals, nil)
311 c.Log("Finished PutB (expected success)")
315 blocklen, _, err := kc.Ask(hash2)
316 c.Assert(err, Equals, nil)
317 c.Check(blocklen, Equals, int64(3))
318 c.Log("Finished Ask (expected success)")
322 reader, blocklen, _, err := kc.Get(hash2)
323 c.Assert(err, Equals, nil)
324 all, err := ioutil.ReadAll(reader)
326 c.Check(all, DeepEquals, []byte("foo"))
327 c.Check(blocklen, Equals, int64(3))
328 c.Log("Finished Get (expected success)")
334 hash2, rep, err = kc.PutB([]byte(""))
335 c.Check(hash2, Matches, `^d41d8cd98f00b204e9800998ecf8427e\+0(\+.+)?$`)
336 c.Check(rep, Equals, 2)
337 c.Check(err, Equals, nil)
338 c.Log("Finished PutB zero block")
342 reader, blocklen, _, err := kc.Get("d41d8cd98f00b204e9800998ecf8427e")
343 c.Assert(err, Equals, nil)
344 all, err := ioutil.ReadAll(reader)
346 c.Check(all, DeepEquals, []byte(""))
347 c.Check(blocklen, Equals, int64(0))
348 c.Log("Finished Get zero block")
352 func (s *ServerRequiredSuite) TestPutAskGetForbidden(c *C) {
353 kc := runProxy(c, nil, true)
354 defer closeListener()
356 hash := fmt.Sprintf("%x+3", md5.Sum([]byte("bar")))
358 _, _, err := kc.Ask(hash)
359 c.Check(err, FitsTypeOf, &keepclient.ErrNotFound{})
361 hash2, rep, err := kc.PutB([]byte("bar"))
362 c.Check(hash2, Equals, "")
363 c.Check(rep, Equals, 0)
364 c.Check(err, FitsTypeOf, keepclient.InsufficientReplicasError(errors.New("")))
366 blocklen, _, err := kc.Ask(hash)
367 c.Check(err, FitsTypeOf, &keepclient.ErrNotFound{})
368 c.Check(err, ErrorMatches, ".*not found.*")
369 c.Check(blocklen, Equals, int64(0))
371 _, blocklen, _, err = kc.Get(hash)
372 c.Check(err, FitsTypeOf, &keepclient.ErrNotFound{})
373 c.Check(err, ErrorMatches, ".*not found.*")
374 c.Check(blocklen, Equals, int64(0))
378 func (s *ServerRequiredSuite) TestCorsHeaders(c *C) {
379 runProxy(c, nil, false)
380 defer closeListener()
383 client := http.Client{}
384 req, err := http.NewRequest("OPTIONS",
385 fmt.Sprintf("http://%s/%x+3", listener.Addr().String(), md5.Sum([]byte("foo"))),
388 req.Header.Add("Access-Control-Request-Method", "PUT")
389 req.Header.Add("Access-Control-Request-Headers", "Authorization, X-Keep-Desired-Replicas")
390 resp, err := client.Do(req)
391 c.Check(err, Equals, nil)
392 c.Check(resp.StatusCode, Equals, 200)
393 body, err := ioutil.ReadAll(resp.Body)
395 c.Check(string(body), Equals, "")
396 c.Check(resp.Header.Get("Access-Control-Allow-Methods"), Equals, "GET, HEAD, POST, PUT, OPTIONS")
397 c.Check(resp.Header.Get("Access-Control-Allow-Origin"), Equals, "*")
401 resp, err := http.Get(
402 fmt.Sprintf("http://%s/%x+3", listener.Addr().String(), md5.Sum([]byte("foo"))))
403 c.Check(err, Equals, nil)
404 c.Check(resp.Header.Get("Access-Control-Allow-Headers"), Equals, "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
405 c.Check(resp.Header.Get("Access-Control-Allow-Origin"), Equals, "*")
409 func (s *ServerRequiredSuite) TestPostWithoutHash(c *C) {
410 runProxy(c, nil, false)
411 defer closeListener()
414 client := http.Client{}
415 req, err := http.NewRequest("POST",
416 "http://"+listener.Addr().String()+"/",
417 strings.NewReader("qux"))
419 req.Header.Add("Authorization", "OAuth2 "+arvadostest.ActiveToken)
420 req.Header.Add("Content-Type", "application/octet-stream")
421 resp, err := client.Do(req)
422 c.Check(err, Equals, nil)
423 body, err := ioutil.ReadAll(resp.Body)
424 c.Check(err, Equals, nil)
425 c.Check(string(body), Matches,
426 fmt.Sprintf(`^%x\+3(\+.+)?$`, md5.Sum([]byte("qux"))))
430 func (s *ServerRequiredSuite) TestStripHint(c *C) {
431 c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73+K@zzzzz", "$1"),
433 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73")
434 c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+K@zzzzz+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73", "$1"),
436 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73")
437 c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz", "$1"),
439 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz")
440 c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73", "$1"),
442 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73")
447 // Put one block, with 2 replicas
448 // With no prefix (expect the block locator, twice)
449 // With an existing prefix (expect the block locator, twice)
450 // With a valid but non-existing prefix (expect "\n")
451 // With an invalid prefix (expect error)
452 func (s *ServerRequiredSuite) TestGetIndex(c *C) {
453 kc := runProxy(c, nil, false)
454 defer closeListener()
456 // Put "index-data" blocks
457 data := []byte("index-data")
458 hash := fmt.Sprintf("%x", md5.Sum(data))
460 hash2, rep, err := kc.PutB(data)
461 c.Check(hash2, Matches, fmt.Sprintf(`^%s\+10(\+.+)?$`, hash))
462 c.Check(rep, Equals, 2)
463 c.Check(err, Equals, nil)
465 reader, blocklen, _, err := kc.Get(hash)
467 c.Check(blocklen, Equals, int64(10))
468 all, err := ioutil.ReadAll(reader)
470 c.Check(all, DeepEquals, data)
472 // Put some more blocks
473 _, _, err = kc.PutB([]byte("some-more-index-data"))
476 kc.Arvados.ApiToken = arvadostest.DataManagerToken
479 for _, spec := range []struct {
484 {"", true, true}, // with no prefix
485 {hash[:3], true, false}, // with matching prefix
486 {"abcdef", false, false}, // with no such prefix
488 indexReader, err := kc.GetIndex(TestProxyUUID, spec.prefix)
489 c.Assert(err, Equals, nil)
490 indexResp, err := ioutil.ReadAll(indexReader)
491 c.Assert(err, Equals, nil)
492 locators := strings.Split(string(indexResp), "\n")
495 for _, locator := range locators {
499 c.Check(locator[:len(spec.prefix)], Equals, spec.prefix)
500 if locator[:32] == hash {
506 c.Check(gotTestHash == 2, Equals, spec.expectTestHash)
507 c.Check(gotOther > 0, Equals, spec.expectOther)
510 // GetIndex with invalid prefix
511 _, err = kc.GetIndex(TestProxyUUID, "xyz")
512 c.Assert((err != nil), Equals, true)
515 func (s *ServerRequiredSuite) TestCollectionSharingToken(c *C) {
516 kc := runProxy(c, nil, false)
517 defer closeListener()
518 hash, _, err := kc.PutB([]byte("shareddata"))
520 kc.Arvados.ApiToken = arvadostest.FooCollectionSharingToken
521 rdr, _, _, err := kc.Get(hash)
523 data, err := ioutil.ReadAll(rdr)
525 c.Check(data, DeepEquals, []byte("shareddata"))
528 func (s *ServerRequiredSuite) TestPutAskGetInvalidToken(c *C) {
529 kc := runProxy(c, nil, false)
530 defer closeListener()
533 hash, rep, err := kc.PutB([]byte("foo"))
535 c.Check(rep, Equals, 2)
537 for _, badToken := range []string{
539 "2ym314ysp27sk7h943q6vtc378srb06se3pq6ghurylyf3pdmx", // expired
541 kc.Arvados.ApiToken = badToken
543 // Ask and Get will fail only if the upstream
544 // keepstore server checks for valid signatures.
545 // Without knowing the blob signing key, there is no
546 // way for keepproxy to know whether a given token is
547 // permitted to read a block. So these tests fail:
549 _, _, err = kc.Ask(hash)
550 c.Assert(err, FitsTypeOf, &keepclient.ErrNotFound{})
551 c.Check(err.(*keepclient.ErrNotFound).Temporary(), Equals, false)
552 c.Check(err, ErrorMatches, ".*HTTP 403.*")
554 _, _, _, err = kc.Get(hash)
555 c.Assert(err, FitsTypeOf, &keepclient.ErrNotFound{})
556 c.Check(err.(*keepclient.ErrNotFound).Temporary(), Equals, false)
557 c.Check(err, ErrorMatches, ".*HTTP 403 \"Missing or invalid Authorization header\".*")
560 _, _, err = kc.PutB([]byte("foo"))
561 c.Check(err, ErrorMatches, ".*403.*Missing or invalid Authorization header")
565 func (s *ServerRequiredSuite) TestAskGetKeepProxyConnectionError(c *C) {
566 kc := runProxy(c, nil, false)
567 defer closeListener()
569 // Point keepproxy at a non-existent keepstore
570 locals := map[string]string{
571 TestProxyUUID: "http://localhost:12345",
573 router.(*proxyHandler).KeepClient.SetServiceRoots(locals, nil, nil)
575 // Ask should result in temporary bad gateway error
576 hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
577 _, _, err := kc.Ask(hash)
579 errNotFound, _ := err.(*keepclient.ErrNotFound)
580 c.Check(errNotFound.Temporary(), Equals, true)
581 c.Assert(err, ErrorMatches, ".*HTTP 502.*")
583 // Get should result in temporary bad gateway error
584 _, _, _, err = kc.Get(hash)
586 errNotFound, _ = err.(*keepclient.ErrNotFound)
587 c.Check(errNotFound.Temporary(), Equals, true)
588 c.Assert(err, ErrorMatches, ".*HTTP 502.*")
591 func (s *NoKeepServerSuite) TestAskGetNoKeepServerError(c *C) {
592 kc := runProxy(c, nil, false)
593 defer closeListener()
595 hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
596 for _, f := range []func() error{
598 _, _, err := kc.Ask(hash)
602 _, _, _, err := kc.Get(hash)
607 c.Assert(err, NotNil)
608 errNotFound, _ := err.(*keepclient.ErrNotFound)
609 c.Check(errNotFound.Temporary(), Equals, true)
610 c.Check(err, ErrorMatches, `.*HTTP 502.*`)
614 func (s *ServerRequiredSuite) TestPing(c *C) {
615 kc := runProxy(c, nil, false)
616 defer closeListener()
618 rtr := MakeRESTRouter(kc, 10*time.Second, arvadostest.ManagementToken)
620 req, err := http.NewRequest("GET",
621 "http://"+listener.Addr().String()+"/_health/ping",
624 req.Header.Set("Authorization", "Bearer "+arvadostest.ManagementToken)
626 resp := httptest.NewRecorder()
627 rtr.ServeHTTP(resp, req)
628 c.Check(resp.Code, Equals, 200)
629 c.Assert(resp.Body.String(), Matches, `{"health":"OK"}\n?`)