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.
29 "git.curoverse.com/arvados.git/sdk/go/arvados"
30 "git.curoverse.com/arvados.git/sdk/go/arvadostest"
31 "github.com/prometheus/client_golang/prometheus"
34 var testCluster = &arvados.Cluster{
38 // A RequestTester represents the parameters for an HTTP request to
39 // be issued on behalf of a unit test.
40 type RequestTester struct {
47 // Test GetBlockHandler on the following situations:
48 // - permissions off, unauthenticated request, unsigned locator
49 // - permissions on, authenticated request, signed locator
50 // - permissions on, authenticated request, unsigned locator
51 // - permissions on, unauthenticated request, signed locator
52 // - permissions on, authenticated request, expired locator
54 func TestGetHandler(t *testing.T) {
57 // Prepare two test Keep volumes. Our block is stored on the second volume.
58 KeepVM = MakeTestVolumeManager(2)
61 vols := KeepVM.AllWritable()
62 if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
66 // Create locators for testing.
67 // Turn on permission settings so we can generate signed locators.
68 theConfig.RequireSignatures = true
69 theConfig.blobSigningKey = []byte(knownKey)
70 theConfig.BlobSignatureTTL.Set("5m")
73 unsignedLocator = "/" + TestHash
74 validTimestamp = time.Now().Add(theConfig.BlobSignatureTTL.Duration())
75 expiredTimestamp = time.Now().Add(-time.Hour)
76 signedLocator = "/" + SignLocator(TestHash, knownToken, validTimestamp)
77 expiredLocator = "/" + SignLocator(TestHash, knownToken, expiredTimestamp)
81 // Test unauthenticated request with permissions off.
82 theConfig.RequireSignatures = false
84 // Unauthenticated request, unsigned locator
86 response := IssueRequest(
92 "Unauthenticated request, unsigned locator", http.StatusOK, response)
94 "Unauthenticated request, unsigned locator",
98 receivedLen := response.Header().Get("Content-Length")
99 expectedLen := fmt.Sprintf("%d", len(TestBlock))
100 if receivedLen != expectedLen {
101 t.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
106 theConfig.RequireSignatures = true
108 // Authenticated request, signed locator
110 response = IssueRequest(&RequestTester{
113 apiToken: knownToken,
116 "Authenticated request, signed locator", http.StatusOK, response)
118 "Authenticated request, signed locator", string(TestBlock), response)
120 receivedLen = response.Header().Get("Content-Length")
121 expectedLen = fmt.Sprintf("%d", len(TestBlock))
122 if receivedLen != expectedLen {
123 t.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
126 // Authenticated request, unsigned locator
127 // => PermissionError
128 response = IssueRequest(&RequestTester{
130 uri: unsignedLocator,
131 apiToken: knownToken,
133 ExpectStatusCode(t, "unsigned locator", PermissionError.HTTPCode, response)
135 // Unauthenticated request, signed locator
136 // => PermissionError
137 response = IssueRequest(&RequestTester{
142 "Unauthenticated request, signed locator",
143 PermissionError.HTTPCode, response)
145 // Authenticated request, expired locator
147 response = IssueRequest(&RequestTester{
150 apiToken: knownToken,
153 "Authenticated request, expired locator",
154 ExpiredError.HTTPCode, response)
157 // Test PutBlockHandler on the following situations:
159 // - with server key, authenticated request, unsigned locator
160 // - with server key, unauthenticated request, unsigned locator
162 func TestPutHandler(t *testing.T) {
165 // Prepare two test Keep volumes.
166 KeepVM = MakeTestVolumeManager(2)
172 // Unauthenticated request, no server key
173 // => OK (unsigned response)
174 unsignedLocator := "/" + TestHash
175 response := IssueRequest(
178 uri: unsignedLocator,
179 requestBody: TestBlock,
183 "Unauthenticated request, no server key", http.StatusOK, response)
185 "Unauthenticated request, no server key",
186 TestHashPutResp, response)
188 // ------------------
189 // With a server key.
191 theConfig.blobSigningKey = []byte(knownKey)
192 theConfig.BlobSignatureTTL.Set("5m")
194 // When a permission key is available, the locator returned
195 // from an authenticated PUT request will be signed.
197 // Authenticated PUT, signed locator
198 // => OK (signed response)
199 response = IssueRequest(
202 uri: unsignedLocator,
203 requestBody: TestBlock,
204 apiToken: knownToken,
208 "Authenticated PUT, signed locator, with server key",
209 http.StatusOK, response)
210 responseLocator := strings.TrimSpace(response.Body.String())
211 if VerifySignature(responseLocator, knownToken) != nil {
212 t.Errorf("Authenticated PUT, signed locator, with server key:\n"+
213 "response '%s' does not contain a valid signature",
217 // Unauthenticated PUT, unsigned locator
219 response = IssueRequest(
222 uri: unsignedLocator,
223 requestBody: TestBlock,
227 "Unauthenticated PUT, unsigned locator, with server key",
228 http.StatusOK, response)
230 "Unauthenticated PUT, unsigned locator, with server key",
231 TestHashPutResp, response)
234 func TestPutAndDeleteSkipReadonlyVolumes(t *testing.T) {
236 theConfig.systemAuthToken = "fake-data-manager-token"
237 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
238 vols[0].Readonly = true
239 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
245 requestBody: TestBlock,
247 defer func(orig bool) {
248 theConfig.EnableDelete = orig
249 }(theConfig.EnableDelete)
250 theConfig.EnableDelete = true
255 requestBody: TestBlock,
256 apiToken: theConfig.systemAuthToken,
263 for _, e := range []expect{
275 if calls := vols[e.volnum].CallCount(e.method); calls != e.callcount {
276 t.Errorf("Got %d %s() on vol %d, expect %d", calls, e.method, e.volnum, e.callcount)
281 // Test /index requests:
282 // - unauthenticated /index request
283 // - unauthenticated /index/prefix request
284 // - authenticated /index request | non-superuser
285 // - authenticated /index/prefix request | non-superuser
286 // - authenticated /index request | superuser
287 // - authenticated /index/prefix request | superuser
289 // The only /index requests that should succeed are those issued by the
290 // superuser. They should pass regardless of the value of RequireSignatures.
292 func TestIndexHandler(t *testing.T) {
295 // Set up Keep volumes and populate them.
296 // Include multiple blocks on different volumes, and
297 // some metadata files (which should be omitted from index listings)
298 KeepVM = MakeTestVolumeManager(2)
301 vols := KeepVM.AllWritable()
302 vols[0].Put(context.Background(), TestHash, TestBlock)
303 vols[1].Put(context.Background(), TestHash2, TestBlock2)
304 vols[0].Put(context.Background(), TestHash+".meta", []byte("metadata"))
305 vols[1].Put(context.Background(), TestHash2+".meta", []byte("metadata"))
307 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
309 unauthenticatedReq := &RequestTester{
313 authenticatedReq := &RequestTester{
316 apiToken: knownToken,
318 superuserReq := &RequestTester{
321 apiToken: theConfig.systemAuthToken,
323 unauthPrefixReq := &RequestTester{
325 uri: "/index/" + TestHash[0:3],
327 authPrefixReq := &RequestTester{
329 uri: "/index/" + TestHash[0:3],
330 apiToken: knownToken,
332 superuserPrefixReq := &RequestTester{
334 uri: "/index/" + TestHash[0:3],
335 apiToken: theConfig.systemAuthToken,
337 superuserNoSuchPrefixReq := &RequestTester{
340 apiToken: theConfig.systemAuthToken,
342 superuserInvalidPrefixReq := &RequestTester{
345 apiToken: theConfig.systemAuthToken,
348 // -------------------------------------------------------------
349 // Only the superuser should be allowed to issue /index requests.
351 // ---------------------------
352 // RequireSignatures enabled
353 // This setting should not affect tests passing.
354 theConfig.RequireSignatures = true
356 // unauthenticated /index request
357 // => UnauthorizedError
358 response := IssueRequest(unauthenticatedReq)
360 "RequireSignatures on, unauthenticated request",
361 UnauthorizedError.HTTPCode,
364 // unauthenticated /index/prefix request
365 // => UnauthorizedError
366 response = IssueRequest(unauthPrefixReq)
368 "permissions on, unauthenticated /index/prefix request",
369 UnauthorizedError.HTTPCode,
372 // authenticated /index request, non-superuser
373 // => UnauthorizedError
374 response = IssueRequest(authenticatedReq)
376 "permissions on, authenticated request, non-superuser",
377 UnauthorizedError.HTTPCode,
380 // authenticated /index/prefix request, non-superuser
381 // => UnauthorizedError
382 response = IssueRequest(authPrefixReq)
384 "permissions on, authenticated /index/prefix request, non-superuser",
385 UnauthorizedError.HTTPCode,
388 // superuser /index request
390 response = IssueRequest(superuserReq)
392 "permissions on, superuser request",
396 // ----------------------------
397 // RequireSignatures disabled
398 // Valid Request should still pass.
399 theConfig.RequireSignatures = false
401 // superuser /index request
403 response = IssueRequest(superuserReq)
405 "permissions on, superuser request",
409 expected := `^` + TestHash + `\+\d+ \d+\n` +
410 TestHash2 + `\+\d+ \d+\n\n$`
411 match, _ := regexp.MatchString(expected, response.Body.String())
414 "permissions on, superuser request: expected %s, got:\n%s",
415 expected, response.Body.String())
418 // superuser /index/prefix request
420 response = IssueRequest(superuserPrefixReq)
422 "permissions on, superuser request",
426 expected = `^` + TestHash + `\+\d+ \d+\n\n$`
427 match, _ = regexp.MatchString(expected, response.Body.String())
430 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
431 expected, response.Body.String())
434 // superuser /index/{no-such-prefix} request
436 response = IssueRequest(superuserNoSuchPrefixReq)
438 "permissions on, superuser request",
442 if "\n" != response.Body.String() {
443 t.Errorf("Expected empty response for %s. Found %s", superuserNoSuchPrefixReq.uri, response.Body.String())
446 // superuser /index/{invalid-prefix} request
447 // => StatusBadRequest
448 response = IssueRequest(superuserInvalidPrefixReq)
450 "permissions on, superuser request",
451 http.StatusBadRequest,
459 // With no token and with a non-data-manager token:
460 // * Delete existing block
461 // (test for 403 Forbidden, confirm block not deleted)
463 // With data manager token:
465 // * Delete existing block
466 // (test for 200 OK, response counts, confirm block deleted)
468 // * Delete nonexistent block
469 // (test for 200 OK, response counts)
473 // * Delete block on read-only and read-write volume
474 // (test for 200 OK, response with copies_deleted=1,
475 // copies_failed=1, confirm block deleted only on r/w volume)
477 // * Delete block on read-only volume only
478 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
479 // confirm block not deleted)
481 func TestDeleteHandler(t *testing.T) {
484 // Set up Keep volumes and populate them.
485 // Include multiple blocks on different volumes, and
486 // some metadata files (which should be omitted from index listings)
487 KeepVM = MakeTestVolumeManager(2)
490 vols := KeepVM.AllWritable()
491 vols[0].Put(context.Background(), TestHash, TestBlock)
493 // Explicitly set the BlobSignatureTTL to 0 for these
494 // tests, to ensure the MockVolume deletes the blocks
495 // even though they have just been created.
496 theConfig.BlobSignatureTTL = arvados.Duration(0)
498 var userToken = "NOT DATA MANAGER TOKEN"
499 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
501 theConfig.EnableDelete = true
503 unauthReq := &RequestTester{
508 userReq := &RequestTester{
514 superuserExistingBlockReq := &RequestTester{
517 apiToken: theConfig.systemAuthToken,
520 superuserNonexistentBlockReq := &RequestTester{
522 uri: "/" + TestHash2,
523 apiToken: theConfig.systemAuthToken,
526 // Unauthenticated request returns PermissionError.
527 var response *httptest.ResponseRecorder
528 response = IssueRequest(unauthReq)
530 "unauthenticated request",
531 PermissionError.HTTPCode,
534 // Authenticated non-admin request returns PermissionError.
535 response = IssueRequest(userReq)
537 "authenticated non-admin request",
538 PermissionError.HTTPCode,
541 // Authenticated admin request for nonexistent block.
542 type deletecounter struct {
543 Deleted int `json:"copies_deleted"`
544 Failed int `json:"copies_failed"`
546 var responseDc, expectedDc deletecounter
548 response = IssueRequest(superuserNonexistentBlockReq)
550 "data manager request, nonexistent block",
554 // Authenticated admin request for existing block while EnableDelete is false.
555 theConfig.EnableDelete = false
556 response = IssueRequest(superuserExistingBlockReq)
558 "authenticated request, existing block, method disabled",
559 MethodDisabledError.HTTPCode,
561 theConfig.EnableDelete = true
563 // Authenticated admin request for existing block.
564 response = IssueRequest(superuserExistingBlockReq)
566 "data manager request, existing block",
569 // Expect response {"copies_deleted":1,"copies_failed":0}
570 expectedDc = deletecounter{1, 0}
571 json.NewDecoder(response.Body).Decode(&responseDc)
572 if responseDc != expectedDc {
573 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
574 expectedDc, responseDc)
576 // Confirm the block has been deleted
577 buf := make([]byte, BlockSize)
578 _, err := vols[0].Get(context.Background(), TestHash, buf)
579 var blockDeleted = os.IsNotExist(err)
581 t.Error("superuserExistingBlockReq: block not deleted")
584 // A DELETE request on a block newer than BlobSignatureTTL
585 // should return success but leave the block on the volume.
586 vols[0].Put(context.Background(), TestHash, TestBlock)
587 theConfig.BlobSignatureTTL = arvados.Duration(time.Hour)
589 response = IssueRequest(superuserExistingBlockReq)
591 "data manager request, existing block",
594 // Expect response {"copies_deleted":1,"copies_failed":0}
595 expectedDc = deletecounter{1, 0}
596 json.NewDecoder(response.Body).Decode(&responseDc)
597 if responseDc != expectedDc {
598 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
599 expectedDc, responseDc)
601 // Confirm the block has NOT been deleted.
602 _, err = vols[0].Get(context.Background(), TestHash, buf)
604 t.Errorf("testing delete on new block: %s\n", err)
610 // Test handling of the PUT /pull statement.
612 // Cases tested: syntactically valid and invalid pull lists, from the
613 // data manager and from unprivileged users:
615 // 1. Valid pull list from an ordinary user
616 // (expected result: 401 Unauthorized)
618 // 2. Invalid pull request from an ordinary user
619 // (expected result: 401 Unauthorized)
621 // 3. Valid pull request from the data manager
622 // (expected result: 200 OK with request body "Received 3 pull
625 // 4. Invalid pull request from the data manager
626 // (expected result: 400 Bad Request)
628 // Test that in the end, the pull manager received a good pull list with
629 // the expected number of requests.
631 // TODO(twp): test concurrency: launch 100 goroutines to update the
632 // pull list simultaneously. Make sure that none of them return 400
633 // Bad Request and that pullq.GetList() returns a valid list.
635 func TestPullHandler(t *testing.T) {
638 var userToken = "USER TOKEN"
639 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
641 pullq = NewWorkQueue()
643 goodJSON := []byte(`[
645 "locator":"locator_with_two_servers",
652 "locator":"locator_with_no_servers",
657 "servers":["empty_locator"]
661 badJSON := []byte(`{ "key":"I'm a little teapot" }`)
663 type pullTest struct {
669 var testcases = []pullTest{
671 "Valid pull list from an ordinary user",
672 RequestTester{"/pull", userToken, "PUT", goodJSON},
673 http.StatusUnauthorized,
677 "Invalid pull request from an ordinary user",
678 RequestTester{"/pull", userToken, "PUT", badJSON},
679 http.StatusUnauthorized,
683 "Valid pull request from the data manager",
684 RequestTester{"/pull", theConfig.systemAuthToken, "PUT", goodJSON},
686 "Received 3 pull requests\n",
689 "Invalid pull request from the data manager",
690 RequestTester{"/pull", theConfig.systemAuthToken, "PUT", badJSON},
691 http.StatusBadRequest,
696 for _, tst := range testcases {
697 response := IssueRequest(&tst.req)
698 ExpectStatusCode(t, tst.name, tst.responseCode, response)
699 ExpectBody(t, tst.name, tst.responseBody, response)
702 // The Keep pull manager should have received one good list with 3
704 for i := 0; i < 3; i++ {
705 item := <-pullq.NextItem
706 if _, ok := item.(PullRequest); !ok {
707 t.Errorf("item %v could not be parsed as a PullRequest", item)
711 expectChannelEmpty(t, pullq.NextItem)
718 // Cases tested: syntactically valid and invalid trash lists, from the
719 // data manager and from unprivileged users:
721 // 1. Valid trash list from an ordinary user
722 // (expected result: 401 Unauthorized)
724 // 2. Invalid trash list from an ordinary user
725 // (expected result: 401 Unauthorized)
727 // 3. Valid trash list from the data manager
728 // (expected result: 200 OK with request body "Received 3 trash
731 // 4. Invalid trash list from the data manager
732 // (expected result: 400 Bad Request)
734 // Test that in the end, the trash collector received a good list
735 // trash list with the expected number of requests.
737 // TODO(twp): test concurrency: launch 100 goroutines to update the
738 // pull list simultaneously. Make sure that none of them return 400
739 // Bad Request and that replica.Dump() returns a valid list.
741 func TestTrashHandler(t *testing.T) {
744 var userToken = "USER TOKEN"
745 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
747 trashq = NewWorkQueue()
749 goodJSON := []byte(`[
752 "block_mtime":1409082153
756 "block_mtime":1409082153
760 "block_mtime":1409082153
764 badJSON := []byte(`I am not a valid JSON string`)
766 type trashTest struct {
773 var testcases = []trashTest{
775 "Valid trash list from an ordinary user",
776 RequestTester{"/trash", userToken, "PUT", goodJSON},
777 http.StatusUnauthorized,
781 "Invalid trash list from an ordinary user",
782 RequestTester{"/trash", userToken, "PUT", badJSON},
783 http.StatusUnauthorized,
787 "Valid trash list from the data manager",
788 RequestTester{"/trash", theConfig.systemAuthToken, "PUT", goodJSON},
790 "Received 3 trash requests\n",
793 "Invalid trash list from the data manager",
794 RequestTester{"/trash", theConfig.systemAuthToken, "PUT", badJSON},
795 http.StatusBadRequest,
800 for _, tst := range testcases {
801 response := IssueRequest(&tst.req)
802 ExpectStatusCode(t, tst.name, tst.responseCode, response)
803 ExpectBody(t, tst.name, tst.responseBody, response)
806 // The trash collector should have received one good list with 3
808 for i := 0; i < 3; i++ {
809 item := <-trashq.NextItem
810 if _, ok := item.(TrashRequest); !ok {
811 t.Errorf("item %v could not be parsed as a TrashRequest", item)
815 expectChannelEmpty(t, trashq.NextItem)
818 // ====================
820 // ====================
822 // IssueTestRequest executes an HTTP request described by rt, to a
823 // REST router. It returns the HTTP response to the request.
824 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
825 response := httptest.NewRecorder()
826 body := bytes.NewReader(rt.requestBody)
827 req, _ := http.NewRequest(rt.method, rt.uri, body)
828 if rt.apiToken != "" {
829 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
831 loggingRouter := MakeRESTRouter(testCluster, prometheus.NewRegistry())
832 loggingRouter.ServeHTTP(response, req)
836 func IssueHealthCheckRequest(rt *RequestTester) *httptest.ResponseRecorder {
837 response := httptest.NewRecorder()
838 body := bytes.NewReader(rt.requestBody)
839 req, _ := http.NewRequest(rt.method, rt.uri, body)
840 if rt.apiToken != "" {
841 req.Header.Set("Authorization", "Bearer "+rt.apiToken)
843 loggingRouter := MakeRESTRouter(testCluster, prometheus.NewRegistry())
844 loggingRouter.ServeHTTP(response, req)
848 // ExpectStatusCode checks whether a response has the specified status code,
849 // and reports a test failure if not.
850 func ExpectStatusCode(
854 response *httptest.ResponseRecorder) {
855 if response.Code != expectedStatus {
856 t.Errorf("%s: expected status %d, got %+v",
857 testname, expectedStatus, response)
865 response *httptest.ResponseRecorder) {
866 if expectedBody != "" && response.Body.String() != expectedBody {
867 t.Errorf("%s: expected response body '%s', got %+v",
868 testname, expectedBody, response)
873 func TestPutNeedsOnlyOneBuffer(t *testing.T) {
875 KeepVM = MakeTestVolumeManager(1)
878 defer func(orig *bufferPool) {
881 bufs = newBufferPool(1, BlockSize)
883 ok := make(chan struct{})
885 for i := 0; i < 2; i++ {
886 response := IssueRequest(
890 requestBody: TestBlock,
893 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
900 case <-time.After(time.Second):
901 t.Fatal("PUT deadlocks with MaxBuffers==1")
905 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
907 func TestPutHandlerNoBufferleak(t *testing.T) {
910 // Prepare two test Keep volumes.
911 KeepVM = MakeTestVolumeManager(2)
914 ok := make(chan bool)
916 for i := 0; i < theConfig.MaxBuffers+1; i++ {
917 // Unauthenticated request, no server key
918 // => OK (unsigned response)
919 unsignedLocator := "/" + TestHash
920 response := IssueRequest(
923 uri: unsignedLocator,
924 requestBody: TestBlock,
927 "TestPutHandlerBufferleak", http.StatusOK, response)
929 "TestPutHandlerBufferleak",
930 TestHashPutResp, response)
935 case <-time.After(20 * time.Second):
936 // If the buffer pool leaks, the test goroutine hangs.
937 t.Fatal("test did not finish, assuming pool leaked")
942 type notifyingResponseRecorder struct {
943 *httptest.ResponseRecorder
947 func (r *notifyingResponseRecorder) CloseNotify() <-chan bool {
951 func TestGetHandlerClientDisconnect(t *testing.T) {
952 defer func(was bool) {
953 theConfig.RequireSignatures = was
954 }(theConfig.RequireSignatures)
955 theConfig.RequireSignatures = false
957 defer func(orig *bufferPool) {
960 bufs = newBufferPool(1, BlockSize)
961 defer bufs.Put(bufs.Get(BlockSize))
963 KeepVM = MakeTestVolumeManager(2)
966 if err := KeepVM.AllWritable()[0].Put(context.Background(), TestHash, TestBlock); err != nil {
970 resp := ¬ifyingResponseRecorder{
971 ResponseRecorder: httptest.NewRecorder(),
972 closer: make(chan bool, 1),
974 if _, ok := http.ResponseWriter(resp).(http.CloseNotifier); !ok {
975 t.Fatal("notifyingResponseRecorder is broken")
977 // If anyone asks, the client has disconnected.
980 ok := make(chan struct{})
982 req, _ := http.NewRequest("GET", fmt.Sprintf("/%s+%d", TestHash, len(TestBlock)), nil)
983 MakeRESTRouter(testCluster, prometheus.NewRegistry()).ServeHTTP(resp, req)
988 case <-time.After(20 * time.Second):
989 t.Fatal("request took >20s, close notifier must be broken")
993 ExpectStatusCode(t, "client disconnect", http.StatusServiceUnavailable, resp.ResponseRecorder)
994 for i, v := range KeepVM.AllWritable() {
995 if calls := v.(*MockVolume).called["GET"]; calls != 0 {
996 t.Errorf("volume %d got %d calls, expected 0", i, calls)
1001 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
1003 func TestGetHandlerNoBufferLeak(t *testing.T) {
1006 // Prepare two test Keep volumes. Our block is stored on the second volume.
1007 KeepVM = MakeTestVolumeManager(2)
1008 defer KeepVM.Close()
1010 vols := KeepVM.AllWritable()
1011 if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
1015 ok := make(chan bool)
1017 for i := 0; i < theConfig.MaxBuffers+1; i++ {
1018 // Unauthenticated request, unsigned locator
1020 unsignedLocator := "/" + TestHash
1021 response := IssueRequest(
1024 uri: unsignedLocator,
1027 "Unauthenticated request, unsigned locator", http.StatusOK, response)
1029 "Unauthenticated request, unsigned locator",
1036 case <-time.After(20 * time.Second):
1037 // If the buffer pool leaks, the test goroutine hangs.
1038 t.Fatal("test did not finish, assuming pool leaked")
1043 func TestPutReplicationHeader(t *testing.T) {
1046 KeepVM = MakeTestVolumeManager(2)
1047 defer KeepVM.Close()
1049 resp := IssueRequest(&RequestTester{
1051 uri: "/" + TestHash,
1052 requestBody: TestBlock,
1054 if r := resp.Header().Get("X-Keep-Replicas-Stored"); r != "1" {
1055 t.Errorf("Got X-Keep-Replicas-Stored: %q, expected %q", r, "1")
1059 func TestUntrashHandler(t *testing.T) {
1062 // Set up Keep volumes
1063 KeepVM = MakeTestVolumeManager(2)
1064 defer KeepVM.Close()
1065 vols := KeepVM.AllWritable()
1066 vols[0].Put(context.Background(), TestHash, TestBlock)
1068 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
1070 // unauthenticatedReq => UnauthorizedError
1071 unauthenticatedReq := &RequestTester{
1073 uri: "/untrash/" + TestHash,
1075 response := IssueRequest(unauthenticatedReq)
1077 "Unauthenticated request",
1078 UnauthorizedError.HTTPCode,
1081 // notDataManagerReq => UnauthorizedError
1082 notDataManagerReq := &RequestTester{
1084 uri: "/untrash/" + TestHash,
1085 apiToken: knownToken,
1088 response = IssueRequest(notDataManagerReq)
1090 "Non-datamanager token",
1091 UnauthorizedError.HTTPCode,
1094 // datamanagerWithBadHashReq => StatusBadRequest
1095 datamanagerWithBadHashReq := &RequestTester{
1097 uri: "/untrash/thisisnotalocator",
1098 apiToken: theConfig.systemAuthToken,
1100 response = IssueRequest(datamanagerWithBadHashReq)
1102 "Bad locator in untrash request",
1103 http.StatusBadRequest,
1106 // datamanagerWrongMethodReq => StatusBadRequest
1107 datamanagerWrongMethodReq := &RequestTester{
1109 uri: "/untrash/" + TestHash,
1110 apiToken: theConfig.systemAuthToken,
1112 response = IssueRequest(datamanagerWrongMethodReq)
1114 "Only PUT method is supported for untrash",
1115 http.StatusMethodNotAllowed,
1118 // datamanagerReq => StatusOK
1119 datamanagerReq := &RequestTester{
1121 uri: "/untrash/" + TestHash,
1122 apiToken: theConfig.systemAuthToken,
1124 response = IssueRequest(datamanagerReq)
1129 expected := "Successfully untrashed on: [MockVolume],[MockVolume]"
1130 if response.Body.String() != expected {
1132 "Untrash response mismatched: expected %s, got:\n%s",
1133 expected, response.Body.String())
1137 func TestUntrashHandlerWithNoWritableVolumes(t *testing.T) {
1140 // Set up readonly Keep volumes
1141 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
1142 vols[0].Readonly = true
1143 vols[1].Readonly = true
1144 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
1145 defer KeepVM.Close()
1147 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
1149 // datamanagerReq => StatusOK
1150 datamanagerReq := &RequestTester{
1152 uri: "/untrash/" + TestHash,
1153 apiToken: theConfig.systemAuthToken,
1155 response := IssueRequest(datamanagerReq)
1157 "No writable volumes",
1158 http.StatusNotFound,
1162 func TestHealthCheckPing(t *testing.T) {
1163 theConfig.ManagementToken = arvadostest.ManagementToken
1164 pingReq := &RequestTester{
1166 uri: "/_health/ping",
1167 apiToken: arvadostest.ManagementToken,
1169 response := IssueHealthCheckRequest(pingReq)
1174 want := `{"health":"OK"}`
1175 if !strings.Contains(response.Body.String(), want) {
1176 t.Errorf("expected response to include %s: got %s", want, response.Body.String())