1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 // Tests for Keep HTTP handlers:
11 // The HTTP handlers are responsible for enforcing permission policy,
12 // so these tests must exercise all possible permission permutations.
28 "git.curoverse.com/arvados.git/lib/config"
29 "git.curoverse.com/arvados.git/sdk/go/arvados"
30 "git.curoverse.com/arvados.git/sdk/go/arvadostest"
31 "git.curoverse.com/arvados.git/sdk/go/ctxlog"
32 "github.com/prometheus/client_golang/prometheus"
33 check "gopkg.in/check.v1"
36 var testServiceURL = func() arvados.URL {
37 return arvados.URL{Host: "localhost:12345", Scheme: "http"}
40 func testCluster(t TB) *arvados.Cluster {
41 cfg, err := config.NewLoader(bytes.NewBufferString("Clusters: {zzzzz: {}}"), ctxlog.TestLogger(t)).Load()
45 cluster, err := cfg.GetCluster("")
49 cluster.SystemRootToken = arvadostest.SystemRootToken
50 cluster.ManagementToken = arvadostest.ManagementToken
51 cluster.Collections.BlobSigning = false
55 var _ = check.Suite(&HandlerSuite{})
57 type HandlerSuite struct {
58 cluster *arvados.Cluster
62 func (s *HandlerSuite) SetUpTest(c *check.C) {
63 s.cluster = testCluster(c)
64 s.cluster.Volumes = map[string]arvados.Volume{
65 "zzzzz-nyw5e-000000000000000": {Replication: 1, Driver: "mock"},
66 "zzzzz-nyw5e-111111111111111": {Replication: 1, Driver: "mock"},
68 s.handler = &handler{}
71 // A RequestTester represents the parameters for an HTTP request to
72 // be issued on behalf of a unit test.
73 type RequestTester struct {
80 // Test GetBlockHandler on the following situations:
81 // - permissions off, unauthenticated request, unsigned locator
82 // - permissions on, authenticated request, signed locator
83 // - permissions on, authenticated request, unsigned locator
84 // - permissions on, unauthenticated request, signed locator
85 // - permissions on, authenticated request, expired locator
86 // - permissions on, authenticated request, signed locator, transient error from backend
88 func (s *HandlerSuite) TestGetHandler(c *check.C) {
89 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
91 vols := s.handler.volmgr.AllWritable()
92 err := vols[0].Put(context.Background(), TestHash, TestBlock)
93 c.Check(err, check.IsNil)
95 // Create locators for testing.
96 // Turn on permission settings so we can generate signed locators.
97 s.cluster.Collections.BlobSigning = true
98 s.cluster.Collections.BlobSigningKey = knownKey
99 s.cluster.Collections.BlobSigningTTL.Set("5m")
102 unsignedLocator = "/" + TestHash
103 validTimestamp = time.Now().Add(s.cluster.Collections.BlobSigningTTL.Duration())
104 expiredTimestamp = time.Now().Add(-time.Hour)
105 signedLocator = "/" + SignLocator(s.cluster, TestHash, knownToken, validTimestamp)
106 expiredLocator = "/" + SignLocator(s.cluster, TestHash, knownToken, expiredTimestamp)
110 // Test unauthenticated request with permissions off.
111 s.cluster.Collections.BlobSigning = false
113 // Unauthenticated request, unsigned locator
115 response := IssueRequest(s.handler,
118 uri: unsignedLocator,
121 "Unauthenticated request, unsigned locator", http.StatusOK, response)
123 "Unauthenticated request, unsigned locator",
127 receivedLen := response.Header().Get("Content-Length")
128 expectedLen := fmt.Sprintf("%d", len(TestBlock))
129 if receivedLen != expectedLen {
130 c.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
135 s.cluster.Collections.BlobSigning = true
137 // Authenticated request, signed locator
139 response = IssueRequest(s.handler, &RequestTester{
142 apiToken: knownToken,
145 "Authenticated request, signed locator", http.StatusOK, response)
147 "Authenticated request, signed locator", string(TestBlock), response)
149 receivedLen = response.Header().Get("Content-Length")
150 expectedLen = fmt.Sprintf("%d", len(TestBlock))
151 if receivedLen != expectedLen {
152 c.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
155 // Authenticated request, unsigned locator
156 // => PermissionError
157 response = IssueRequest(s.handler, &RequestTester{
159 uri: unsignedLocator,
160 apiToken: knownToken,
162 ExpectStatusCode(c, "unsigned locator", PermissionError.HTTPCode, response)
164 // Unauthenticated request, signed locator
165 // => PermissionError
166 response = IssueRequest(s.handler, &RequestTester{
171 "Unauthenticated request, signed locator",
172 PermissionError.HTTPCode, response)
174 // Authenticated request, expired locator
176 response = IssueRequest(s.handler, &RequestTester{
179 apiToken: knownToken,
182 "Authenticated request, expired locator",
183 ExpiredError.HTTPCode, response)
185 // Authenticated request, signed locator
186 // => 503 Server busy (transient error)
188 // Set up the block owning volume to respond with errors
189 vols[0].Volume.(*MockVolume).Bad = true
190 vols[0].Volume.(*MockVolume).BadVolumeError = VolumeBusyError
191 response = IssueRequest(s.handler, &RequestTester{
194 apiToken: knownToken,
196 // A transient error from one volume while the other doesn't find the block
197 // should make the service return a 503 so that clients can retry.
199 "Volume backend busy",
203 // Test PutBlockHandler on the following situations:
205 // - with server key, authenticated request, unsigned locator
206 // - with server key, unauthenticated request, unsigned locator
208 func (s *HandlerSuite) TestPutHandler(c *check.C) {
209 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
214 s.cluster.Collections.BlobSigningKey = ""
216 // Unauthenticated request, no server key
217 // => OK (unsigned response)
218 unsignedLocator := "/" + TestHash
219 response := IssueRequest(s.handler,
222 uri: unsignedLocator,
223 requestBody: TestBlock,
227 "Unauthenticated request, no server key", http.StatusOK, response)
229 "Unauthenticated request, no server key",
230 TestHashPutResp, response)
232 // ------------------
233 // With a server key.
235 s.cluster.Collections.BlobSigningKey = knownKey
236 s.cluster.Collections.BlobSigningTTL.Set("5m")
238 // When a permission key is available, the locator returned
239 // from an authenticated PUT request will be signed.
241 // Authenticated PUT, signed locator
242 // => OK (signed response)
243 response = IssueRequest(s.handler,
246 uri: unsignedLocator,
247 requestBody: TestBlock,
248 apiToken: knownToken,
252 "Authenticated PUT, signed locator, with server key",
253 http.StatusOK, response)
254 responseLocator := strings.TrimSpace(response.Body.String())
255 if VerifySignature(s.cluster, responseLocator, knownToken) != nil {
256 c.Errorf("Authenticated PUT, signed locator, with server key:\n"+
257 "response '%s' does not contain a valid signature",
261 // Unauthenticated PUT, unsigned locator
263 response = IssueRequest(s.handler,
266 uri: unsignedLocator,
267 requestBody: TestBlock,
271 "Unauthenticated PUT, unsigned locator, with server key",
272 http.StatusOK, response)
274 "Unauthenticated PUT, unsigned locator, with server key",
275 TestHashPutResp, response)
278 func (s *HandlerSuite) TestPutAndDeleteSkipReadonlyVolumes(c *check.C) {
279 s.cluster.Volumes["zzzzz-nyw5e-000000000000000"] = arvados.Volume{Driver: "mock", ReadOnly: true}
280 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
282 s.cluster.SystemRootToken = "fake-data-manager-token"
283 IssueRequest(s.handler,
287 requestBody: TestBlock,
290 s.cluster.Collections.BlobTrash = true
291 IssueRequest(s.handler,
295 requestBody: TestBlock,
296 apiToken: s.cluster.SystemRootToken,
303 for _, e := range []expect{
304 {"zzzzz-nyw5e-000000000000000", "Get", 0},
305 {"zzzzz-nyw5e-000000000000000", "Compare", 0},
306 {"zzzzz-nyw5e-000000000000000", "Touch", 0},
307 {"zzzzz-nyw5e-000000000000000", "Put", 0},
308 {"zzzzz-nyw5e-000000000000000", "Delete", 0},
309 {"zzzzz-nyw5e-111111111111111", "Get", 0},
310 {"zzzzz-nyw5e-111111111111111", "Compare", 1},
311 {"zzzzz-nyw5e-111111111111111", "Touch", 1},
312 {"zzzzz-nyw5e-111111111111111", "Put", 1},
313 {"zzzzz-nyw5e-111111111111111", "Delete", 1},
315 if calls := s.handler.volmgr.mountMap[e.volid].Volume.(*MockVolume).CallCount(e.method); calls != e.callcount {
316 c.Errorf("Got %d %s() on vol %s, expect %d", calls, e.method, e.volid, e.callcount)
321 // Test /index requests:
322 // - unauthenticated /index request
323 // - unauthenticated /index/prefix request
324 // - authenticated /index request | non-superuser
325 // - authenticated /index/prefix request | non-superuser
326 // - authenticated /index request | superuser
327 // - authenticated /index/prefix request | superuser
329 // The only /index requests that should succeed are those issued by the
330 // superuser. They should pass regardless of the value of BlobSigning.
332 func (s *HandlerSuite) TestIndexHandler(c *check.C) {
333 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
335 // Include multiple blocks on different volumes, and
336 // some metadata files (which should be omitted from index listings)
337 vols := s.handler.volmgr.AllWritable()
338 vols[0].Put(context.Background(), TestHash, TestBlock)
339 vols[1].Put(context.Background(), TestHash2, TestBlock2)
340 vols[0].Put(context.Background(), TestHash+".meta", []byte("metadata"))
341 vols[1].Put(context.Background(), TestHash2+".meta", []byte("metadata"))
343 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
345 unauthenticatedReq := &RequestTester{
349 authenticatedReq := &RequestTester{
352 apiToken: knownToken,
354 superuserReq := &RequestTester{
357 apiToken: s.cluster.SystemRootToken,
359 unauthPrefixReq := &RequestTester{
361 uri: "/index/" + TestHash[0:3],
363 authPrefixReq := &RequestTester{
365 uri: "/index/" + TestHash[0:3],
366 apiToken: knownToken,
368 superuserPrefixReq := &RequestTester{
370 uri: "/index/" + TestHash[0:3],
371 apiToken: s.cluster.SystemRootToken,
373 superuserNoSuchPrefixReq := &RequestTester{
376 apiToken: s.cluster.SystemRootToken,
378 superuserInvalidPrefixReq := &RequestTester{
381 apiToken: s.cluster.SystemRootToken,
384 // -------------------------------------------------------------
385 // Only the superuser should be allowed to issue /index requests.
387 // ---------------------------
388 // BlobSigning enabled
389 // This setting should not affect tests passing.
390 s.cluster.Collections.BlobSigning = true
392 // unauthenticated /index request
393 // => UnauthorizedError
394 response := IssueRequest(s.handler, unauthenticatedReq)
396 "permissions on, unauthenticated request",
397 UnauthorizedError.HTTPCode,
400 // unauthenticated /index/prefix request
401 // => UnauthorizedError
402 response = IssueRequest(s.handler, unauthPrefixReq)
404 "permissions on, unauthenticated /index/prefix request",
405 UnauthorizedError.HTTPCode,
408 // authenticated /index request, non-superuser
409 // => UnauthorizedError
410 response = IssueRequest(s.handler, authenticatedReq)
412 "permissions on, authenticated request, non-superuser",
413 UnauthorizedError.HTTPCode,
416 // authenticated /index/prefix request, non-superuser
417 // => UnauthorizedError
418 response = IssueRequest(s.handler, authPrefixReq)
420 "permissions on, authenticated /index/prefix request, non-superuser",
421 UnauthorizedError.HTTPCode,
424 // superuser /index request
426 response = IssueRequest(s.handler, superuserReq)
428 "permissions on, superuser request",
432 // ----------------------------
433 // BlobSigning disabled
434 // Valid Request should still pass.
435 s.cluster.Collections.BlobSigning = false
437 // superuser /index request
439 response = IssueRequest(s.handler, superuserReq)
441 "permissions on, superuser request",
445 expected := `^` + TestHash + `\+\d+ \d+\n` +
446 TestHash2 + `\+\d+ \d+\n\n$`
447 match, _ := regexp.MatchString(expected, response.Body.String())
450 "permissions on, superuser request: expected %s, got:\n%s",
451 expected, response.Body.String())
454 // superuser /index/prefix request
456 response = IssueRequest(s.handler, superuserPrefixReq)
458 "permissions on, superuser request",
462 expected = `^` + TestHash + `\+\d+ \d+\n\n$`
463 match, _ = regexp.MatchString(expected, response.Body.String())
466 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
467 expected, response.Body.String())
470 // superuser /index/{no-such-prefix} request
472 response = IssueRequest(s.handler, superuserNoSuchPrefixReq)
474 "permissions on, superuser request",
478 if "\n" != response.Body.String() {
479 c.Errorf("Expected empty response for %s. Found %s", superuserNoSuchPrefixReq.uri, response.Body.String())
482 // superuser /index/{invalid-prefix} request
483 // => StatusBadRequest
484 response = IssueRequest(s.handler, superuserInvalidPrefixReq)
486 "permissions on, superuser request",
487 http.StatusBadRequest,
495 // With no token and with a non-data-manager token:
496 // * Delete existing block
497 // (test for 403 Forbidden, confirm block not deleted)
499 // With data manager token:
501 // * Delete existing block
502 // (test for 200 OK, response counts, confirm block deleted)
504 // * Delete nonexistent block
505 // (test for 200 OK, response counts)
509 // * Delete block on read-only and read-write volume
510 // (test for 200 OK, response with copies_deleted=1,
511 // copies_failed=1, confirm block deleted only on r/w volume)
513 // * Delete block on read-only volume only
514 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
515 // confirm block not deleted)
517 func (s *HandlerSuite) TestDeleteHandler(c *check.C) {
518 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
520 vols := s.handler.volmgr.AllWritable()
521 vols[0].Put(context.Background(), TestHash, TestBlock)
523 // Explicitly set the BlobSigningTTL to 0 for these
524 // tests, to ensure the MockVolume deletes the blocks
525 // even though they have just been created.
526 s.cluster.Collections.BlobSigningTTL = arvados.Duration(0)
528 var userToken = "NOT DATA MANAGER TOKEN"
529 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
531 s.cluster.Collections.BlobTrash = true
533 unauthReq := &RequestTester{
538 userReq := &RequestTester{
544 superuserExistingBlockReq := &RequestTester{
547 apiToken: s.cluster.SystemRootToken,
550 superuserNonexistentBlockReq := &RequestTester{
552 uri: "/" + TestHash2,
553 apiToken: s.cluster.SystemRootToken,
556 // Unauthenticated request returns PermissionError.
557 var response *httptest.ResponseRecorder
558 response = IssueRequest(s.handler, unauthReq)
560 "unauthenticated request",
561 PermissionError.HTTPCode,
564 // Authenticated non-admin request returns PermissionError.
565 response = IssueRequest(s.handler, userReq)
567 "authenticated non-admin request",
568 PermissionError.HTTPCode,
571 // Authenticated admin request for nonexistent block.
572 type deletecounter struct {
573 Deleted int `json:"copies_deleted"`
574 Failed int `json:"copies_failed"`
576 var responseDc, expectedDc deletecounter
578 response = IssueRequest(s.handler, superuserNonexistentBlockReq)
580 "data manager request, nonexistent block",
584 // Authenticated admin request for existing block while BlobTrash is false.
585 s.cluster.Collections.BlobTrash = false
586 response = IssueRequest(s.handler, superuserExistingBlockReq)
588 "authenticated request, existing block, method disabled",
589 MethodDisabledError.HTTPCode,
591 s.cluster.Collections.BlobTrash = true
593 // Authenticated admin request for existing block.
594 response = IssueRequest(s.handler, superuserExistingBlockReq)
596 "data manager request, existing block",
599 // Expect response {"copies_deleted":1,"copies_failed":0}
600 expectedDc = deletecounter{1, 0}
601 json.NewDecoder(response.Body).Decode(&responseDc)
602 if responseDc != expectedDc {
603 c.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
604 expectedDc, responseDc)
606 // Confirm the block has been deleted
607 buf := make([]byte, BlockSize)
608 _, err := vols[0].Get(context.Background(), TestHash, buf)
609 var blockDeleted = os.IsNotExist(err)
611 c.Error("superuserExistingBlockReq: block not deleted")
614 // A DELETE request on a block newer than BlobSigningTTL
615 // should return success but leave the block on the volume.
616 vols[0].Put(context.Background(), TestHash, TestBlock)
617 s.cluster.Collections.BlobSigningTTL = arvados.Duration(time.Hour)
619 response = IssueRequest(s.handler, superuserExistingBlockReq)
621 "data manager request, existing block",
624 // Expect response {"copies_deleted":1,"copies_failed":0}
625 expectedDc = deletecounter{1, 0}
626 json.NewDecoder(response.Body).Decode(&responseDc)
627 if responseDc != expectedDc {
628 c.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
629 expectedDc, responseDc)
631 // Confirm the block has NOT been deleted.
632 _, err = vols[0].Get(context.Background(), TestHash, buf)
634 c.Errorf("testing delete on new block: %s\n", err)
640 // Test handling of the PUT /pull statement.
642 // Cases tested: syntactically valid and invalid pull lists, from the
643 // data manager and from unprivileged users:
645 // 1. Valid pull list from an ordinary user
646 // (expected result: 401 Unauthorized)
648 // 2. Invalid pull request from an ordinary user
649 // (expected result: 401 Unauthorized)
651 // 3. Valid pull request from the data manager
652 // (expected result: 200 OK with request body "Received 3 pull
655 // 4. Invalid pull request from the data manager
656 // (expected result: 400 Bad Request)
658 // Test that in the end, the pull manager received a good pull list with
659 // the expected number of requests.
661 // TODO(twp): test concurrency: launch 100 goroutines to update the
662 // pull list simultaneously. Make sure that none of them return 400
663 // Bad Request and that pullq.GetList() returns a valid list.
665 func (s *HandlerSuite) TestPullHandler(c *check.C) {
666 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
668 // Replace the router's pullq -- which the worker goroutines
669 // started by setup() are now receiving from -- with a new
670 // one, so we can see what the handler sends to it.
671 pullq := NewWorkQueue()
672 s.handler.Handler.(*router).pullq = pullq
674 var userToken = "USER TOKEN"
675 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
677 goodJSON := []byte(`[
679 "locator":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+12345",
686 "locator":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb+12345",
690 "locator":"cccccccccccccccccccccccccccccccc+12345",
691 "servers":["http://server1"]
695 badJSON := []byte(`{ "key":"I'm a little teapot" }`)
697 type pullTest struct {
703 var testcases = []pullTest{
705 "Valid pull list from an ordinary user",
706 RequestTester{"/pull", userToken, "PUT", goodJSON},
707 http.StatusUnauthorized,
711 "Invalid pull request from an ordinary user",
712 RequestTester{"/pull", userToken, "PUT", badJSON},
713 http.StatusUnauthorized,
717 "Valid pull request from the data manager",
718 RequestTester{"/pull", s.cluster.SystemRootToken, "PUT", goodJSON},
720 "Received 3 pull requests\n",
723 "Invalid pull request from the data manager",
724 RequestTester{"/pull", s.cluster.SystemRootToken, "PUT", badJSON},
725 http.StatusBadRequest,
730 for _, tst := range testcases {
731 response := IssueRequest(s.handler, &tst.req)
732 ExpectStatusCode(c, tst.name, tst.responseCode, response)
733 ExpectBody(c, tst.name, tst.responseBody, response)
736 // The Keep pull manager should have received one good list with 3
738 for i := 0; i < 3; i++ {
741 case item = <-pullq.NextItem:
742 case <-time.After(time.Second):
745 if _, ok := item.(PullRequest); !ok {
746 c.Errorf("item %v could not be parsed as a PullRequest", item)
750 expectChannelEmpty(c, pullq.NextItem)
757 // Cases tested: syntactically valid and invalid trash lists, from the
758 // data manager and from unprivileged users:
760 // 1. Valid trash list from an ordinary user
761 // (expected result: 401 Unauthorized)
763 // 2. Invalid trash list from an ordinary user
764 // (expected result: 401 Unauthorized)
766 // 3. Valid trash list from the data manager
767 // (expected result: 200 OK with request body "Received 3 trash
770 // 4. Invalid trash list from the data manager
771 // (expected result: 400 Bad Request)
773 // Test that in the end, the trash collector received a good list
774 // trash list with the expected number of requests.
776 // TODO(twp): test concurrency: launch 100 goroutines to update the
777 // pull list simultaneously. Make sure that none of them return 400
778 // Bad Request and that replica.Dump() returns a valid list.
780 func (s *HandlerSuite) TestTrashHandler(c *check.C) {
781 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
782 // Replace the router's trashq -- which the worker goroutines
783 // started by setup() are now receiving from -- with a new
784 // one, so we can see what the handler sends to it.
785 trashq := NewWorkQueue()
786 s.handler.Handler.(*router).trashq = trashq
788 var userToken = "USER TOKEN"
789 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
791 goodJSON := []byte(`[
794 "block_mtime":1409082153
798 "block_mtime":1409082153
802 "block_mtime":1409082153
806 badJSON := []byte(`I am not a valid JSON string`)
808 type trashTest struct {
815 var testcases = []trashTest{
817 "Valid trash list from an ordinary user",
818 RequestTester{"/trash", userToken, "PUT", goodJSON},
819 http.StatusUnauthorized,
823 "Invalid trash list from an ordinary user",
824 RequestTester{"/trash", userToken, "PUT", badJSON},
825 http.StatusUnauthorized,
829 "Valid trash list from the data manager",
830 RequestTester{"/trash", s.cluster.SystemRootToken, "PUT", goodJSON},
832 "Received 3 trash requests\n",
835 "Invalid trash list from the data manager",
836 RequestTester{"/trash", s.cluster.SystemRootToken, "PUT", badJSON},
837 http.StatusBadRequest,
842 for _, tst := range testcases {
843 response := IssueRequest(s.handler, &tst.req)
844 ExpectStatusCode(c, tst.name, tst.responseCode, response)
845 ExpectBody(c, tst.name, tst.responseBody, response)
848 // The trash collector should have received one good list with 3
850 for i := 0; i < 3; i++ {
851 item := <-trashq.NextItem
852 if _, ok := item.(TrashRequest); !ok {
853 c.Errorf("item %v could not be parsed as a TrashRequest", item)
857 expectChannelEmpty(c, trashq.NextItem)
860 // ====================
862 // ====================
864 // IssueTestRequest executes an HTTP request described by rt, to a
865 // REST router. It returns the HTTP response to the request.
866 func IssueRequest(handler http.Handler, rt *RequestTester) *httptest.ResponseRecorder {
867 response := httptest.NewRecorder()
868 body := bytes.NewReader(rt.requestBody)
869 req, _ := http.NewRequest(rt.method, rt.uri, body)
870 if rt.apiToken != "" {
871 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
873 handler.ServeHTTP(response, req)
877 func IssueHealthCheckRequest(handler http.Handler, rt *RequestTester) *httptest.ResponseRecorder {
878 response := httptest.NewRecorder()
879 body := bytes.NewReader(rt.requestBody)
880 req, _ := http.NewRequest(rt.method, rt.uri, body)
881 if rt.apiToken != "" {
882 req.Header.Set("Authorization", "Bearer "+rt.apiToken)
884 handler.ServeHTTP(response, req)
888 // ExpectStatusCode checks whether a response has the specified status code,
889 // and reports a test failure if not.
890 func ExpectStatusCode(
894 response *httptest.ResponseRecorder) {
895 c.Check(response.Code, check.Equals, expectedStatus, check.Commentf("%s", testname))
902 response *httptest.ResponseRecorder) {
903 if expectedBody != "" && response.Body.String() != expectedBody {
904 c.Errorf("%s: expected response body '%s', got %+v",
905 testname, expectedBody, response)
910 func (s *HandlerSuite) TestPutNeedsOnlyOneBuffer(c *check.C) {
911 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
913 defer func(orig *bufferPool) {
916 bufs = newBufferPool(ctxlog.TestLogger(c), 1, BlockSize)
918 ok := make(chan struct{})
920 for i := 0; i < 2; i++ {
921 response := IssueRequest(s.handler,
925 requestBody: TestBlock,
928 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
935 case <-time.After(time.Second):
936 c.Fatal("PUT deadlocks with MaxKeepBlobBuffers==1")
940 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
942 func (s *HandlerSuite) TestPutHandlerNoBufferleak(c *check.C) {
943 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
945 ok := make(chan bool)
947 for i := 0; i < s.cluster.API.MaxKeepBlobBuffers+1; i++ {
948 // Unauthenticated request, no server key
949 // => OK (unsigned response)
950 unsignedLocator := "/" + TestHash
951 response := IssueRequest(s.handler,
954 uri: unsignedLocator,
955 requestBody: TestBlock,
958 "TestPutHandlerBufferleak", http.StatusOK, response)
960 "TestPutHandlerBufferleak",
961 TestHashPutResp, response)
966 case <-time.After(20 * time.Second):
967 // If the buffer pool leaks, the test goroutine hangs.
968 c.Fatal("test did not finish, assuming pool leaked")
973 type notifyingResponseRecorder struct {
974 *httptest.ResponseRecorder
978 func (r *notifyingResponseRecorder) CloseNotify() <-chan bool {
982 func (s *HandlerSuite) TestGetHandlerClientDisconnect(c *check.C) {
983 s.cluster.Collections.BlobSigning = false
984 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
986 defer func(orig *bufferPool) {
989 bufs = newBufferPool(ctxlog.TestLogger(c), 1, BlockSize)
990 defer bufs.Put(bufs.Get(BlockSize))
992 if err := s.handler.volmgr.AllWritable()[0].Put(context.Background(), TestHash, TestBlock); err != nil {
996 resp := ¬ifyingResponseRecorder{
997 ResponseRecorder: httptest.NewRecorder(),
998 closer: make(chan bool, 1),
1000 if _, ok := http.ResponseWriter(resp).(http.CloseNotifier); !ok {
1001 c.Fatal("notifyingResponseRecorder is broken")
1003 // If anyone asks, the client has disconnected.
1006 ok := make(chan struct{})
1008 req, _ := http.NewRequest("GET", fmt.Sprintf("/%s+%d", TestHash, len(TestBlock)), nil)
1009 s.handler.ServeHTTP(resp, req)
1014 case <-time.After(20 * time.Second):
1015 c.Fatal("request took >20s, close notifier must be broken")
1019 ExpectStatusCode(c, "client disconnect", http.StatusServiceUnavailable, resp.ResponseRecorder)
1020 for i, v := range s.handler.volmgr.AllWritable() {
1021 if calls := v.Volume.(*MockVolume).called["GET"]; calls != 0 {
1022 c.Errorf("volume %d got %d calls, expected 0", i, calls)
1027 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
1029 func (s *HandlerSuite) TestGetHandlerNoBufferLeak(c *check.C) {
1030 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1032 vols := s.handler.volmgr.AllWritable()
1033 if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
1037 ok := make(chan bool)
1039 for i := 0; i < s.cluster.API.MaxKeepBlobBuffers+1; i++ {
1040 // Unauthenticated request, unsigned locator
1042 unsignedLocator := "/" + TestHash
1043 response := IssueRequest(s.handler,
1046 uri: unsignedLocator,
1049 "Unauthenticated request, unsigned locator", http.StatusOK, response)
1051 "Unauthenticated request, unsigned locator",
1058 case <-time.After(20 * time.Second):
1059 // If the buffer pool leaks, the test goroutine hangs.
1060 c.Fatal("test did not finish, assuming pool leaked")
1065 func (s *HandlerSuite) TestPutReplicationHeader(c *check.C) {
1066 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1068 resp := IssueRequest(s.handler, &RequestTester{
1070 uri: "/" + TestHash,
1071 requestBody: TestBlock,
1073 if r := resp.Header().Get("X-Keep-Replicas-Stored"); r != "1" {
1075 c.Errorf("Got X-Keep-Replicas-Stored: %q, expected %q", r, "1")
1079 func (s *HandlerSuite) TestUntrashHandler(c *check.C) {
1080 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1082 // Set up Keep volumes
1083 vols := s.handler.volmgr.AllWritable()
1084 vols[0].Put(context.Background(), TestHash, TestBlock)
1086 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
1088 // unauthenticatedReq => UnauthorizedError
1089 unauthenticatedReq := &RequestTester{
1091 uri: "/untrash/" + TestHash,
1093 response := IssueRequest(s.handler, unauthenticatedReq)
1095 "Unauthenticated request",
1096 UnauthorizedError.HTTPCode,
1099 // notDataManagerReq => UnauthorizedError
1100 notDataManagerReq := &RequestTester{
1102 uri: "/untrash/" + TestHash,
1103 apiToken: knownToken,
1106 response = IssueRequest(s.handler, notDataManagerReq)
1108 "Non-datamanager token",
1109 UnauthorizedError.HTTPCode,
1112 // datamanagerWithBadHashReq => StatusBadRequest
1113 datamanagerWithBadHashReq := &RequestTester{
1115 uri: "/untrash/thisisnotalocator",
1116 apiToken: s.cluster.SystemRootToken,
1118 response = IssueRequest(s.handler, datamanagerWithBadHashReq)
1120 "Bad locator in untrash request",
1121 http.StatusBadRequest,
1124 // datamanagerWrongMethodReq => StatusBadRequest
1125 datamanagerWrongMethodReq := &RequestTester{
1127 uri: "/untrash/" + TestHash,
1128 apiToken: s.cluster.SystemRootToken,
1130 response = IssueRequest(s.handler, datamanagerWrongMethodReq)
1132 "Only PUT method is supported for untrash",
1133 http.StatusMethodNotAllowed,
1136 // datamanagerReq => StatusOK
1137 datamanagerReq := &RequestTester{
1139 uri: "/untrash/" + TestHash,
1140 apiToken: s.cluster.SystemRootToken,
1142 response = IssueRequest(s.handler, datamanagerReq)
1147 c.Check(response.Body.String(), check.Equals, "Successfully untrashed on: [MockVolume], [MockVolume]\n")
1150 func (s *HandlerSuite) TestUntrashHandlerWithNoWritableVolumes(c *check.C) {
1151 // Change all volumes to read-only
1152 for uuid, v := range s.cluster.Volumes {
1154 s.cluster.Volumes[uuid] = v
1156 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1158 // datamanagerReq => StatusOK
1159 datamanagerReq := &RequestTester{
1161 uri: "/untrash/" + TestHash,
1162 apiToken: s.cluster.SystemRootToken,
1164 response := IssueRequest(s.handler, datamanagerReq)
1166 "No writable volumes",
1167 http.StatusNotFound,
1171 func (s *HandlerSuite) TestHealthCheckPing(c *check.C) {
1172 s.cluster.ManagementToken = arvadostest.ManagementToken
1173 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1174 pingReq := &RequestTester{
1176 uri: "/_health/ping",
1177 apiToken: arvadostest.ManagementToken,
1179 response := IssueHealthCheckRequest(s.handler, pingReq)
1184 want := `{"health":"OK"}`
1185 if !strings.Contains(response.Body.String(), want) {
1186 c.Errorf("expected response to include %s: got %s", want, response.Body.String())