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"
33 var testCluster = &arvados.Cluster{
37 // A RequestTester represents the parameters for an HTTP request to
38 // be issued on behalf of a unit test.
39 type RequestTester struct {
46 // Test GetBlockHandler on the following situations:
47 // - permissions off, unauthenticated request, unsigned locator
48 // - permissions on, authenticated request, signed locator
49 // - permissions on, authenticated request, unsigned locator
50 // - permissions on, unauthenticated request, signed locator
51 // - permissions on, authenticated request, expired locator
53 func TestGetHandler(t *testing.T) {
56 // Prepare two test Keep volumes. Our block is stored on the second volume.
57 KeepVM = MakeTestVolumeManager(2)
60 vols := KeepVM.AllWritable()
61 if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
65 // Create locators for testing.
66 // Turn on permission settings so we can generate signed locators.
67 theConfig.RequireSignatures = true
68 theConfig.blobSigningKey = []byte(knownKey)
69 theConfig.BlobSignatureTTL.Set("5m")
72 unsignedLocator = "/" + TestHash
73 validTimestamp = time.Now().Add(theConfig.BlobSignatureTTL.Duration())
74 expiredTimestamp = time.Now().Add(-time.Hour)
75 signedLocator = "/" + SignLocator(TestHash, knownToken, validTimestamp)
76 expiredLocator = "/" + SignLocator(TestHash, knownToken, expiredTimestamp)
80 // Test unauthenticated request with permissions off.
81 theConfig.RequireSignatures = false
83 // Unauthenticated request, unsigned locator
85 response := IssueRequest(
91 "Unauthenticated request, unsigned locator", http.StatusOK, response)
93 "Unauthenticated request, unsigned locator",
97 receivedLen := response.Header().Get("Content-Length")
98 expectedLen := fmt.Sprintf("%d", len(TestBlock))
99 if receivedLen != expectedLen {
100 t.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
105 theConfig.RequireSignatures = true
107 // Authenticated request, signed locator
109 response = IssueRequest(&RequestTester{
112 apiToken: knownToken,
115 "Authenticated request, signed locator", http.StatusOK, response)
117 "Authenticated request, signed locator", string(TestBlock), response)
119 receivedLen = response.Header().Get("Content-Length")
120 expectedLen = fmt.Sprintf("%d", len(TestBlock))
121 if receivedLen != expectedLen {
122 t.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
125 // Authenticated request, unsigned locator
126 // => PermissionError
127 response = IssueRequest(&RequestTester{
129 uri: unsignedLocator,
130 apiToken: knownToken,
132 ExpectStatusCode(t, "unsigned locator", PermissionError.HTTPCode, response)
134 // Unauthenticated request, signed locator
135 // => PermissionError
136 response = IssueRequest(&RequestTester{
141 "Unauthenticated request, signed locator",
142 PermissionError.HTTPCode, response)
144 // Authenticated request, expired locator
146 response = IssueRequest(&RequestTester{
149 apiToken: knownToken,
152 "Authenticated request, expired locator",
153 ExpiredError.HTTPCode, response)
155 // Authenticated request, signed locator
156 // => 503 Server busy (transient error)
158 // Set up the block owning volume to respond with errors
159 vols[0].(*MockVolume).Bad = true
160 vols[0].(*MockVolume).BadVolumeError = VolumeBusyError
161 response = IssueRequest(&RequestTester{
164 apiToken: knownToken,
166 // A transient error from one volume while the other doesn't find the block
167 // should make the service return a 503 so that clients can retry.
169 "Volume backend busy",
173 // Test PutBlockHandler on the following situations:
175 // - with server key, authenticated request, unsigned locator
176 // - with server key, unauthenticated request, unsigned locator
178 func TestPutHandler(t *testing.T) {
181 // Prepare two test Keep volumes.
182 KeepVM = MakeTestVolumeManager(2)
188 // Unauthenticated request, no server key
189 // => OK (unsigned response)
190 unsignedLocator := "/" + TestHash
191 response := IssueRequest(
194 uri: unsignedLocator,
195 requestBody: TestBlock,
199 "Unauthenticated request, no server key", http.StatusOK, response)
201 "Unauthenticated request, no server key",
202 TestHashPutResp, response)
204 // ------------------
205 // With a server key.
207 theConfig.blobSigningKey = []byte(knownKey)
208 theConfig.BlobSignatureTTL.Set("5m")
210 // When a permission key is available, the locator returned
211 // from an authenticated PUT request will be signed.
213 // Authenticated PUT, signed locator
214 // => OK (signed response)
215 response = IssueRequest(
218 uri: unsignedLocator,
219 requestBody: TestBlock,
220 apiToken: knownToken,
224 "Authenticated PUT, signed locator, with server key",
225 http.StatusOK, response)
226 responseLocator := strings.TrimSpace(response.Body.String())
227 if VerifySignature(responseLocator, knownToken) != nil {
228 t.Errorf("Authenticated PUT, signed locator, with server key:\n"+
229 "response '%s' does not contain a valid signature",
233 // Unauthenticated PUT, unsigned locator
235 response = IssueRequest(
238 uri: unsignedLocator,
239 requestBody: TestBlock,
243 "Unauthenticated PUT, unsigned locator, with server key",
244 http.StatusOK, response)
246 "Unauthenticated PUT, unsigned locator, with server key",
247 TestHashPutResp, response)
250 func TestPutAndDeleteSkipReadonlyVolumes(t *testing.T) {
252 theConfig.systemAuthToken = "fake-data-manager-token"
253 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
254 vols[0].Readonly = true
255 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
261 requestBody: TestBlock,
263 defer func(orig bool) {
264 theConfig.EnableDelete = orig
265 }(theConfig.EnableDelete)
266 theConfig.EnableDelete = true
271 requestBody: TestBlock,
272 apiToken: theConfig.systemAuthToken,
279 for _, e := range []expect{
291 if calls := vols[e.volnum].CallCount(e.method); calls != e.callcount {
292 t.Errorf("Got %d %s() on vol %d, expect %d", calls, e.method, e.volnum, e.callcount)
297 // Test /index requests:
298 // - unauthenticated /index request
299 // - unauthenticated /index/prefix request
300 // - authenticated /index request | non-superuser
301 // - authenticated /index/prefix request | non-superuser
302 // - authenticated /index request | superuser
303 // - authenticated /index/prefix request | superuser
305 // The only /index requests that should succeed are those issued by the
306 // superuser. They should pass regardless of the value of RequireSignatures.
308 func TestIndexHandler(t *testing.T) {
311 // Set up Keep volumes and populate them.
312 // Include multiple blocks on different volumes, and
313 // some metadata files (which should be omitted from index listings)
314 KeepVM = MakeTestVolumeManager(2)
317 vols := KeepVM.AllWritable()
318 vols[0].Put(context.Background(), TestHash, TestBlock)
319 vols[1].Put(context.Background(), TestHash2, TestBlock2)
320 vols[0].Put(context.Background(), TestHash+".meta", []byte("metadata"))
321 vols[1].Put(context.Background(), TestHash2+".meta", []byte("metadata"))
323 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
325 unauthenticatedReq := &RequestTester{
329 authenticatedReq := &RequestTester{
332 apiToken: knownToken,
334 superuserReq := &RequestTester{
337 apiToken: theConfig.systemAuthToken,
339 unauthPrefixReq := &RequestTester{
341 uri: "/index/" + TestHash[0:3],
343 authPrefixReq := &RequestTester{
345 uri: "/index/" + TestHash[0:3],
346 apiToken: knownToken,
348 superuserPrefixReq := &RequestTester{
350 uri: "/index/" + TestHash[0:3],
351 apiToken: theConfig.systemAuthToken,
353 superuserNoSuchPrefixReq := &RequestTester{
356 apiToken: theConfig.systemAuthToken,
358 superuserInvalidPrefixReq := &RequestTester{
361 apiToken: theConfig.systemAuthToken,
364 // -------------------------------------------------------------
365 // Only the superuser should be allowed to issue /index requests.
367 // ---------------------------
368 // RequireSignatures enabled
369 // This setting should not affect tests passing.
370 theConfig.RequireSignatures = true
372 // unauthenticated /index request
373 // => UnauthorizedError
374 response := IssueRequest(unauthenticatedReq)
376 "RequireSignatures on, unauthenticated request",
377 UnauthorizedError.HTTPCode,
380 // unauthenticated /index/prefix request
381 // => UnauthorizedError
382 response = IssueRequest(unauthPrefixReq)
384 "permissions on, unauthenticated /index/prefix request",
385 UnauthorizedError.HTTPCode,
388 // authenticated /index request, non-superuser
389 // => UnauthorizedError
390 response = IssueRequest(authenticatedReq)
392 "permissions on, authenticated request, non-superuser",
393 UnauthorizedError.HTTPCode,
396 // authenticated /index/prefix request, non-superuser
397 // => UnauthorizedError
398 response = IssueRequest(authPrefixReq)
400 "permissions on, authenticated /index/prefix request, non-superuser",
401 UnauthorizedError.HTTPCode,
404 // superuser /index request
406 response = IssueRequest(superuserReq)
408 "permissions on, superuser request",
412 // ----------------------------
413 // RequireSignatures disabled
414 // Valid Request should still pass.
415 theConfig.RequireSignatures = false
417 // superuser /index request
419 response = IssueRequest(superuserReq)
421 "permissions on, superuser request",
425 expected := `^` + TestHash + `\+\d+ \d+\n` +
426 TestHash2 + `\+\d+ \d+\n\n$`
427 match, _ := regexp.MatchString(expected, response.Body.String())
430 "permissions on, superuser request: expected %s, got:\n%s",
431 expected, response.Body.String())
434 // superuser /index/prefix request
436 response = IssueRequest(superuserPrefixReq)
438 "permissions on, superuser request",
442 expected = `^` + TestHash + `\+\d+ \d+\n\n$`
443 match, _ = regexp.MatchString(expected, response.Body.String())
446 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
447 expected, response.Body.String())
450 // superuser /index/{no-such-prefix} request
452 response = IssueRequest(superuserNoSuchPrefixReq)
454 "permissions on, superuser request",
458 if "\n" != response.Body.String() {
459 t.Errorf("Expected empty response for %s. Found %s", superuserNoSuchPrefixReq.uri, response.Body.String())
462 // superuser /index/{invalid-prefix} request
463 // => StatusBadRequest
464 response = IssueRequest(superuserInvalidPrefixReq)
466 "permissions on, superuser request",
467 http.StatusBadRequest,
475 // With no token and with a non-data-manager token:
476 // * Delete existing block
477 // (test for 403 Forbidden, confirm block not deleted)
479 // With data manager token:
481 // * Delete existing block
482 // (test for 200 OK, response counts, confirm block deleted)
484 // * Delete nonexistent block
485 // (test for 200 OK, response counts)
489 // * Delete block on read-only and read-write volume
490 // (test for 200 OK, response with copies_deleted=1,
491 // copies_failed=1, confirm block deleted only on r/w volume)
493 // * Delete block on read-only volume only
494 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
495 // confirm block not deleted)
497 func TestDeleteHandler(t *testing.T) {
500 // Set up Keep volumes and populate them.
501 // Include multiple blocks on different volumes, and
502 // some metadata files (which should be omitted from index listings)
503 KeepVM = MakeTestVolumeManager(2)
506 vols := KeepVM.AllWritable()
507 vols[0].Put(context.Background(), TestHash, TestBlock)
509 // Explicitly set the BlobSignatureTTL to 0 for these
510 // tests, to ensure the MockVolume deletes the blocks
511 // even though they have just been created.
512 theConfig.BlobSignatureTTL = arvados.Duration(0)
514 var userToken = "NOT DATA MANAGER TOKEN"
515 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
517 theConfig.EnableDelete = true
519 unauthReq := &RequestTester{
524 userReq := &RequestTester{
530 superuserExistingBlockReq := &RequestTester{
533 apiToken: theConfig.systemAuthToken,
536 superuserNonexistentBlockReq := &RequestTester{
538 uri: "/" + TestHash2,
539 apiToken: theConfig.systemAuthToken,
542 // Unauthenticated request returns PermissionError.
543 var response *httptest.ResponseRecorder
544 response = IssueRequest(unauthReq)
546 "unauthenticated request",
547 PermissionError.HTTPCode,
550 // Authenticated non-admin request returns PermissionError.
551 response = IssueRequest(userReq)
553 "authenticated non-admin request",
554 PermissionError.HTTPCode,
557 // Authenticated admin request for nonexistent block.
558 type deletecounter struct {
559 Deleted int `json:"copies_deleted"`
560 Failed int `json:"copies_failed"`
562 var responseDc, expectedDc deletecounter
564 response = IssueRequest(superuserNonexistentBlockReq)
566 "data manager request, nonexistent block",
570 // Authenticated admin request for existing block while EnableDelete is false.
571 theConfig.EnableDelete = false
572 response = IssueRequest(superuserExistingBlockReq)
574 "authenticated request, existing block, method disabled",
575 MethodDisabledError.HTTPCode,
577 theConfig.EnableDelete = true
579 // Authenticated admin request for existing block.
580 response = IssueRequest(superuserExistingBlockReq)
582 "data manager request, existing block",
585 // Expect response {"copies_deleted":1,"copies_failed":0}
586 expectedDc = deletecounter{1, 0}
587 json.NewDecoder(response.Body).Decode(&responseDc)
588 if responseDc != expectedDc {
589 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
590 expectedDc, responseDc)
592 // Confirm the block has been deleted
593 buf := make([]byte, BlockSize)
594 _, err := vols[0].Get(context.Background(), TestHash, buf)
595 var blockDeleted = os.IsNotExist(err)
597 t.Error("superuserExistingBlockReq: block not deleted")
600 // A DELETE request on a block newer than BlobSignatureTTL
601 // should return success but leave the block on the volume.
602 vols[0].Put(context.Background(), TestHash, TestBlock)
603 theConfig.BlobSignatureTTL = arvados.Duration(time.Hour)
605 response = IssueRequest(superuserExistingBlockReq)
607 "data manager request, existing block",
610 // Expect response {"copies_deleted":1,"copies_failed":0}
611 expectedDc = deletecounter{1, 0}
612 json.NewDecoder(response.Body).Decode(&responseDc)
613 if responseDc != expectedDc {
614 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
615 expectedDc, responseDc)
617 // Confirm the block has NOT been deleted.
618 _, err = vols[0].Get(context.Background(), TestHash, buf)
620 t.Errorf("testing delete on new block: %s\n", err)
626 // Test handling of the PUT /pull statement.
628 // Cases tested: syntactically valid and invalid pull lists, from the
629 // data manager and from unprivileged users:
631 // 1. Valid pull list from an ordinary user
632 // (expected result: 401 Unauthorized)
634 // 2. Invalid pull request from an ordinary user
635 // (expected result: 401 Unauthorized)
637 // 3. Valid pull request from the data manager
638 // (expected result: 200 OK with request body "Received 3 pull
641 // 4. Invalid pull request from the data manager
642 // (expected result: 400 Bad Request)
644 // Test that in the end, the pull manager received a good pull list with
645 // the expected number of requests.
647 // TODO(twp): test concurrency: launch 100 goroutines to update the
648 // pull list simultaneously. Make sure that none of them return 400
649 // Bad Request and that pullq.GetList() returns a valid list.
651 func TestPullHandler(t *testing.T) {
654 var userToken = "USER TOKEN"
655 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
657 pullq = NewWorkQueue()
659 goodJSON := []byte(`[
661 "locator":"locator_with_two_servers",
668 "locator":"locator_with_no_servers",
673 "servers":["empty_locator"]
677 badJSON := []byte(`{ "key":"I'm a little teapot" }`)
679 type pullTest struct {
685 var testcases = []pullTest{
687 "Valid pull list from an ordinary user",
688 RequestTester{"/pull", userToken, "PUT", goodJSON},
689 http.StatusUnauthorized,
693 "Invalid pull request from an ordinary user",
694 RequestTester{"/pull", userToken, "PUT", badJSON},
695 http.StatusUnauthorized,
699 "Valid pull request from the data manager",
700 RequestTester{"/pull", theConfig.systemAuthToken, "PUT", goodJSON},
702 "Received 3 pull requests\n",
705 "Invalid pull request from the data manager",
706 RequestTester{"/pull", theConfig.systemAuthToken, "PUT", badJSON},
707 http.StatusBadRequest,
712 for _, tst := range testcases {
713 response := IssueRequest(&tst.req)
714 ExpectStatusCode(t, tst.name, tst.responseCode, response)
715 ExpectBody(t, tst.name, tst.responseBody, response)
718 // The Keep pull manager should have received one good list with 3
720 for i := 0; i < 3; i++ {
721 item := <-pullq.NextItem
722 if _, ok := item.(PullRequest); !ok {
723 t.Errorf("item %v could not be parsed as a PullRequest", item)
727 expectChannelEmpty(t, pullq.NextItem)
734 // Cases tested: syntactically valid and invalid trash lists, from the
735 // data manager and from unprivileged users:
737 // 1. Valid trash list from an ordinary user
738 // (expected result: 401 Unauthorized)
740 // 2. Invalid trash list from an ordinary user
741 // (expected result: 401 Unauthorized)
743 // 3. Valid trash list from the data manager
744 // (expected result: 200 OK with request body "Received 3 trash
747 // 4. Invalid trash list from the data manager
748 // (expected result: 400 Bad Request)
750 // Test that in the end, the trash collector received a good list
751 // trash list with the expected number of requests.
753 // TODO(twp): test concurrency: launch 100 goroutines to update the
754 // pull list simultaneously. Make sure that none of them return 400
755 // Bad Request and that replica.Dump() returns a valid list.
757 func TestTrashHandler(t *testing.T) {
760 var userToken = "USER TOKEN"
761 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
763 trashq = NewWorkQueue()
765 goodJSON := []byte(`[
768 "block_mtime":1409082153
772 "block_mtime":1409082153
776 "block_mtime":1409082153
780 badJSON := []byte(`I am not a valid JSON string`)
782 type trashTest struct {
789 var testcases = []trashTest{
791 "Valid trash list from an ordinary user",
792 RequestTester{"/trash", userToken, "PUT", goodJSON},
793 http.StatusUnauthorized,
797 "Invalid trash list from an ordinary user",
798 RequestTester{"/trash", userToken, "PUT", badJSON},
799 http.StatusUnauthorized,
803 "Valid trash list from the data manager",
804 RequestTester{"/trash", theConfig.systemAuthToken, "PUT", goodJSON},
806 "Received 3 trash requests\n",
809 "Invalid trash list from the data manager",
810 RequestTester{"/trash", theConfig.systemAuthToken, "PUT", badJSON},
811 http.StatusBadRequest,
816 for _, tst := range testcases {
817 response := IssueRequest(&tst.req)
818 ExpectStatusCode(t, tst.name, tst.responseCode, response)
819 ExpectBody(t, tst.name, tst.responseBody, response)
822 // The trash collector should have received one good list with 3
824 for i := 0; i < 3; i++ {
825 item := <-trashq.NextItem
826 if _, ok := item.(TrashRequest); !ok {
827 t.Errorf("item %v could not be parsed as a TrashRequest", item)
831 expectChannelEmpty(t, trashq.NextItem)
834 // ====================
836 // ====================
838 // IssueTestRequest executes an HTTP request described by rt, to a
839 // REST router. It returns the HTTP response to the request.
840 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
841 response := httptest.NewRecorder()
842 body := bytes.NewReader(rt.requestBody)
843 req, _ := http.NewRequest(rt.method, rt.uri, body)
844 if rt.apiToken != "" {
845 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
847 loggingRouter := MakeRESTRouter(testCluster)
848 loggingRouter.ServeHTTP(response, req)
852 func IssueHealthCheckRequest(rt *RequestTester) *httptest.ResponseRecorder {
853 response := httptest.NewRecorder()
854 body := bytes.NewReader(rt.requestBody)
855 req, _ := http.NewRequest(rt.method, rt.uri, body)
856 if rt.apiToken != "" {
857 req.Header.Set("Authorization", "Bearer "+rt.apiToken)
859 loggingRouter := MakeRESTRouter(testCluster)
860 loggingRouter.ServeHTTP(response, req)
864 // ExpectStatusCode checks whether a response has the specified status code,
865 // and reports a test failure if not.
866 func ExpectStatusCode(
870 response *httptest.ResponseRecorder) {
871 if response.Code != expectedStatus {
872 t.Errorf("%s: expected status %d, got %+v",
873 testname, expectedStatus, response)
881 response *httptest.ResponseRecorder) {
882 if expectedBody != "" && response.Body.String() != expectedBody {
883 t.Errorf("%s: expected response body '%s', got %+v",
884 testname, expectedBody, response)
889 func TestPutNeedsOnlyOneBuffer(t *testing.T) {
891 KeepVM = MakeTestVolumeManager(1)
894 defer func(orig *bufferPool) {
897 bufs = newBufferPool(1, BlockSize)
899 ok := make(chan struct{})
901 for i := 0; i < 2; i++ {
902 response := IssueRequest(
906 requestBody: TestBlock,
909 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
916 case <-time.After(time.Second):
917 t.Fatal("PUT deadlocks with MaxBuffers==1")
921 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
923 func TestPutHandlerNoBufferleak(t *testing.T) {
926 // Prepare two test Keep volumes.
927 KeepVM = MakeTestVolumeManager(2)
930 ok := make(chan bool)
932 for i := 0; i < theConfig.MaxBuffers+1; i++ {
933 // Unauthenticated request, no server key
934 // => OK (unsigned response)
935 unsignedLocator := "/" + TestHash
936 response := IssueRequest(
939 uri: unsignedLocator,
940 requestBody: TestBlock,
943 "TestPutHandlerBufferleak", http.StatusOK, response)
945 "TestPutHandlerBufferleak",
946 TestHashPutResp, response)
951 case <-time.After(20 * time.Second):
952 // If the buffer pool leaks, the test goroutine hangs.
953 t.Fatal("test did not finish, assuming pool leaked")
958 type notifyingResponseRecorder struct {
959 *httptest.ResponseRecorder
963 func (r *notifyingResponseRecorder) CloseNotify() <-chan bool {
967 func TestGetHandlerClientDisconnect(t *testing.T) {
968 defer func(was bool) {
969 theConfig.RequireSignatures = was
970 }(theConfig.RequireSignatures)
971 theConfig.RequireSignatures = false
973 defer func(orig *bufferPool) {
976 bufs = newBufferPool(1, BlockSize)
977 defer bufs.Put(bufs.Get(BlockSize))
979 KeepVM = MakeTestVolumeManager(2)
982 if err := KeepVM.AllWritable()[0].Put(context.Background(), TestHash, TestBlock); err != nil {
986 resp := ¬ifyingResponseRecorder{
987 ResponseRecorder: httptest.NewRecorder(),
988 closer: make(chan bool, 1),
990 if _, ok := http.ResponseWriter(resp).(http.CloseNotifier); !ok {
991 t.Fatal("notifyingResponseRecorder is broken")
993 // If anyone asks, the client has disconnected.
996 ok := make(chan struct{})
998 req, _ := http.NewRequest("GET", fmt.Sprintf("/%s+%d", TestHash, len(TestBlock)), nil)
999 MakeRESTRouter(testCluster).ServeHTTP(resp, req)
1004 case <-time.After(20 * time.Second):
1005 t.Fatal("request took >20s, close notifier must be broken")
1009 ExpectStatusCode(t, "client disconnect", http.StatusServiceUnavailable, resp.ResponseRecorder)
1010 for i, v := range KeepVM.AllWritable() {
1011 if calls := v.(*MockVolume).called["GET"]; calls != 0 {
1012 t.Errorf("volume %d got %d calls, expected 0", i, calls)
1017 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
1019 func TestGetHandlerNoBufferLeak(t *testing.T) {
1022 // Prepare two test Keep volumes. Our block is stored on the second volume.
1023 KeepVM = MakeTestVolumeManager(2)
1024 defer KeepVM.Close()
1026 vols := KeepVM.AllWritable()
1027 if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
1031 ok := make(chan bool)
1033 for i := 0; i < theConfig.MaxBuffers+1; i++ {
1034 // Unauthenticated request, unsigned locator
1036 unsignedLocator := "/" + TestHash
1037 response := IssueRequest(
1040 uri: unsignedLocator,
1043 "Unauthenticated request, unsigned locator", http.StatusOK, response)
1045 "Unauthenticated request, unsigned locator",
1052 case <-time.After(20 * time.Second):
1053 // If the buffer pool leaks, the test goroutine hangs.
1054 t.Fatal("test did not finish, assuming pool leaked")
1059 func TestPutReplicationHeader(t *testing.T) {
1062 KeepVM = MakeTestVolumeManager(2)
1063 defer KeepVM.Close()
1065 resp := IssueRequest(&RequestTester{
1067 uri: "/" + TestHash,
1068 requestBody: TestBlock,
1070 if r := resp.Header().Get("X-Keep-Replicas-Stored"); r != "1" {
1071 t.Errorf("Got X-Keep-Replicas-Stored: %q, expected %q", r, "1")
1075 func TestUntrashHandler(t *testing.T) {
1078 // Set up Keep volumes
1079 KeepVM = MakeTestVolumeManager(2)
1080 defer KeepVM.Close()
1081 vols := KeepVM.AllWritable()
1082 vols[0].Put(context.Background(), TestHash, TestBlock)
1084 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
1086 // unauthenticatedReq => UnauthorizedError
1087 unauthenticatedReq := &RequestTester{
1089 uri: "/untrash/" + TestHash,
1091 response := IssueRequest(unauthenticatedReq)
1093 "Unauthenticated request",
1094 UnauthorizedError.HTTPCode,
1097 // notDataManagerReq => UnauthorizedError
1098 notDataManagerReq := &RequestTester{
1100 uri: "/untrash/" + TestHash,
1101 apiToken: knownToken,
1104 response = IssueRequest(notDataManagerReq)
1106 "Non-datamanager token",
1107 UnauthorizedError.HTTPCode,
1110 // datamanagerWithBadHashReq => StatusBadRequest
1111 datamanagerWithBadHashReq := &RequestTester{
1113 uri: "/untrash/thisisnotalocator",
1114 apiToken: theConfig.systemAuthToken,
1116 response = IssueRequest(datamanagerWithBadHashReq)
1118 "Bad locator in untrash request",
1119 http.StatusBadRequest,
1122 // datamanagerWrongMethodReq => StatusBadRequest
1123 datamanagerWrongMethodReq := &RequestTester{
1125 uri: "/untrash/" + TestHash,
1126 apiToken: theConfig.systemAuthToken,
1128 response = IssueRequest(datamanagerWrongMethodReq)
1130 "Only PUT method is supported for untrash",
1131 http.StatusMethodNotAllowed,
1134 // datamanagerReq => StatusOK
1135 datamanagerReq := &RequestTester{
1137 uri: "/untrash/" + TestHash,
1138 apiToken: theConfig.systemAuthToken,
1140 response = IssueRequest(datamanagerReq)
1145 expected := "Successfully untrashed on: [MockVolume],[MockVolume]"
1146 if response.Body.String() != expected {
1148 "Untrash response mismatched: expected %s, got:\n%s",
1149 expected, response.Body.String())
1153 func TestUntrashHandlerWithNoWritableVolumes(t *testing.T) {
1156 // Set up readonly Keep volumes
1157 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
1158 vols[0].Readonly = true
1159 vols[1].Readonly = true
1160 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
1161 defer KeepVM.Close()
1163 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
1165 // datamanagerReq => StatusOK
1166 datamanagerReq := &RequestTester{
1168 uri: "/untrash/" + TestHash,
1169 apiToken: theConfig.systemAuthToken,
1171 response := IssueRequest(datamanagerReq)
1173 "No writable volumes",
1174 http.StatusNotFound,
1178 func TestHealthCheckPing(t *testing.T) {
1179 theConfig.ManagementToken = arvadostest.ManagementToken
1180 pingReq := &RequestTester{
1182 uri: "/_health/ping",
1183 apiToken: arvadostest.ManagementToken,
1185 response := IssueHealthCheckRequest(pingReq)
1190 want := `{"health":"OK"}`
1191 if !strings.Contains(response.Body.String(), want) {
1192 t.Errorf("expected response to include %s: got %s", want, response.Body.String())