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
52 // - permissions on, authenticated request, signed locator, transient error from backend
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)
156 // Authenticated request, signed locator
157 // => 503 Server busy (transient error)
159 // Set up the block owning volume to respond with errors
160 vols[0].(*MockVolume).Bad = true
161 vols[0].(*MockVolume).BadVolumeError = VolumeBusyError
162 response = IssueRequest(&RequestTester{
165 apiToken: knownToken,
167 // A transient error from one volume while the other doesn't find the block
168 // should make the service return a 503 so that clients can retry.
170 "Volume backend busy",
174 // Test PutBlockHandler on the following situations:
176 // - with server key, authenticated request, unsigned locator
177 // - with server key, unauthenticated request, unsigned locator
179 func TestPutHandler(t *testing.T) {
182 // Prepare two test Keep volumes.
183 KeepVM = MakeTestVolumeManager(2)
189 // Unauthenticated request, no server key
190 // => OK (unsigned response)
191 unsignedLocator := "/" + TestHash
192 response := IssueRequest(
195 uri: unsignedLocator,
196 requestBody: TestBlock,
200 "Unauthenticated request, no server key", http.StatusOK, response)
202 "Unauthenticated request, no server key",
203 TestHashPutResp, response)
205 // ------------------
206 // With a server key.
208 theConfig.blobSigningKey = []byte(knownKey)
209 theConfig.BlobSignatureTTL.Set("5m")
211 // When a permission key is available, the locator returned
212 // from an authenticated PUT request will be signed.
214 // Authenticated PUT, signed locator
215 // => OK (signed response)
216 response = IssueRequest(
219 uri: unsignedLocator,
220 requestBody: TestBlock,
221 apiToken: knownToken,
225 "Authenticated PUT, signed locator, with server key",
226 http.StatusOK, response)
227 responseLocator := strings.TrimSpace(response.Body.String())
228 if VerifySignature(responseLocator, knownToken) != nil {
229 t.Errorf("Authenticated PUT, signed locator, with server key:\n"+
230 "response '%s' does not contain a valid signature",
234 // Unauthenticated PUT, unsigned locator
236 response = IssueRequest(
239 uri: unsignedLocator,
240 requestBody: TestBlock,
244 "Unauthenticated PUT, unsigned locator, with server key",
245 http.StatusOK, response)
247 "Unauthenticated PUT, unsigned locator, with server key",
248 TestHashPutResp, response)
251 func TestPutAndDeleteSkipReadonlyVolumes(t *testing.T) {
253 theConfig.systemAuthToken = "fake-data-manager-token"
254 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
255 vols[0].Readonly = true
256 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
262 requestBody: TestBlock,
264 defer func(orig bool) {
265 theConfig.EnableDelete = orig
266 }(theConfig.EnableDelete)
267 theConfig.EnableDelete = true
272 requestBody: TestBlock,
273 apiToken: theConfig.systemAuthToken,
280 for _, e := range []expect{
292 if calls := vols[e.volnum].CallCount(e.method); calls != e.callcount {
293 t.Errorf("Got %d %s() on vol %d, expect %d", calls, e.method, e.volnum, e.callcount)
298 // Test /index requests:
299 // - unauthenticated /index request
300 // - unauthenticated /index/prefix request
301 // - authenticated /index request | non-superuser
302 // - authenticated /index/prefix request | non-superuser
303 // - authenticated /index request | superuser
304 // - authenticated /index/prefix request | superuser
306 // The only /index requests that should succeed are those issued by the
307 // superuser. They should pass regardless of the value of RequireSignatures.
309 func TestIndexHandler(t *testing.T) {
312 // Set up Keep volumes and populate them.
313 // Include multiple blocks on different volumes, and
314 // some metadata files (which should be omitted from index listings)
315 KeepVM = MakeTestVolumeManager(2)
318 vols := KeepVM.AllWritable()
319 vols[0].Put(context.Background(), TestHash, TestBlock)
320 vols[1].Put(context.Background(), TestHash2, TestBlock2)
321 vols[0].Put(context.Background(), TestHash+".meta", []byte("metadata"))
322 vols[1].Put(context.Background(), TestHash2+".meta", []byte("metadata"))
324 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
326 unauthenticatedReq := &RequestTester{
330 authenticatedReq := &RequestTester{
333 apiToken: knownToken,
335 superuserReq := &RequestTester{
338 apiToken: theConfig.systemAuthToken,
340 unauthPrefixReq := &RequestTester{
342 uri: "/index/" + TestHash[0:3],
344 authPrefixReq := &RequestTester{
346 uri: "/index/" + TestHash[0:3],
347 apiToken: knownToken,
349 superuserPrefixReq := &RequestTester{
351 uri: "/index/" + TestHash[0:3],
352 apiToken: theConfig.systemAuthToken,
354 superuserNoSuchPrefixReq := &RequestTester{
357 apiToken: theConfig.systemAuthToken,
359 superuserInvalidPrefixReq := &RequestTester{
362 apiToken: theConfig.systemAuthToken,
365 // -------------------------------------------------------------
366 // Only the superuser should be allowed to issue /index requests.
368 // ---------------------------
369 // RequireSignatures enabled
370 // This setting should not affect tests passing.
371 theConfig.RequireSignatures = true
373 // unauthenticated /index request
374 // => UnauthorizedError
375 response := IssueRequest(unauthenticatedReq)
377 "RequireSignatures on, unauthenticated request",
378 UnauthorizedError.HTTPCode,
381 // unauthenticated /index/prefix request
382 // => UnauthorizedError
383 response = IssueRequest(unauthPrefixReq)
385 "permissions on, unauthenticated /index/prefix request",
386 UnauthorizedError.HTTPCode,
389 // authenticated /index request, non-superuser
390 // => UnauthorizedError
391 response = IssueRequest(authenticatedReq)
393 "permissions on, authenticated request, non-superuser",
394 UnauthorizedError.HTTPCode,
397 // authenticated /index/prefix request, non-superuser
398 // => UnauthorizedError
399 response = IssueRequest(authPrefixReq)
401 "permissions on, authenticated /index/prefix request, non-superuser",
402 UnauthorizedError.HTTPCode,
405 // superuser /index request
407 response = IssueRequest(superuserReq)
409 "permissions on, superuser request",
413 // ----------------------------
414 // RequireSignatures disabled
415 // Valid Request should still pass.
416 theConfig.RequireSignatures = false
418 // superuser /index request
420 response = IssueRequest(superuserReq)
422 "permissions on, superuser request",
426 expected := `^` + TestHash + `\+\d+ \d+\n` +
427 TestHash2 + `\+\d+ \d+\n\n$`
428 match, _ := regexp.MatchString(expected, response.Body.String())
431 "permissions on, superuser request: expected %s, got:\n%s",
432 expected, response.Body.String())
435 // superuser /index/prefix request
437 response = IssueRequest(superuserPrefixReq)
439 "permissions on, superuser request",
443 expected = `^` + TestHash + `\+\d+ \d+\n\n$`
444 match, _ = regexp.MatchString(expected, response.Body.String())
447 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
448 expected, response.Body.String())
451 // superuser /index/{no-such-prefix} request
453 response = IssueRequest(superuserNoSuchPrefixReq)
455 "permissions on, superuser request",
459 if "\n" != response.Body.String() {
460 t.Errorf("Expected empty response for %s. Found %s", superuserNoSuchPrefixReq.uri, response.Body.String())
463 // superuser /index/{invalid-prefix} request
464 // => StatusBadRequest
465 response = IssueRequest(superuserInvalidPrefixReq)
467 "permissions on, superuser request",
468 http.StatusBadRequest,
476 // With no token and with a non-data-manager token:
477 // * Delete existing block
478 // (test for 403 Forbidden, confirm block not deleted)
480 // With data manager token:
482 // * Delete existing block
483 // (test for 200 OK, response counts, confirm block deleted)
485 // * Delete nonexistent block
486 // (test for 200 OK, response counts)
490 // * Delete block on read-only and read-write volume
491 // (test for 200 OK, response with copies_deleted=1,
492 // copies_failed=1, confirm block deleted only on r/w volume)
494 // * Delete block on read-only volume only
495 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
496 // confirm block not deleted)
498 func TestDeleteHandler(t *testing.T) {
501 // Set up Keep volumes and populate them.
502 // Include multiple blocks on different volumes, and
503 // some metadata files (which should be omitted from index listings)
504 KeepVM = MakeTestVolumeManager(2)
507 vols := KeepVM.AllWritable()
508 vols[0].Put(context.Background(), TestHash, TestBlock)
510 // Explicitly set the BlobSignatureTTL to 0 for these
511 // tests, to ensure the MockVolume deletes the blocks
512 // even though they have just been created.
513 theConfig.BlobSignatureTTL = arvados.Duration(0)
515 var userToken = "NOT DATA MANAGER TOKEN"
516 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
518 theConfig.EnableDelete = true
520 unauthReq := &RequestTester{
525 userReq := &RequestTester{
531 superuserExistingBlockReq := &RequestTester{
534 apiToken: theConfig.systemAuthToken,
537 superuserNonexistentBlockReq := &RequestTester{
539 uri: "/" + TestHash2,
540 apiToken: theConfig.systemAuthToken,
543 // Unauthenticated request returns PermissionError.
544 var response *httptest.ResponseRecorder
545 response = IssueRequest(unauthReq)
547 "unauthenticated request",
548 PermissionError.HTTPCode,
551 // Authenticated non-admin request returns PermissionError.
552 response = IssueRequest(userReq)
554 "authenticated non-admin request",
555 PermissionError.HTTPCode,
558 // Authenticated admin request for nonexistent block.
559 type deletecounter struct {
560 Deleted int `json:"copies_deleted"`
561 Failed int `json:"copies_failed"`
563 var responseDc, expectedDc deletecounter
565 response = IssueRequest(superuserNonexistentBlockReq)
567 "data manager request, nonexistent block",
571 // Authenticated admin request for existing block while EnableDelete is false.
572 theConfig.EnableDelete = false
573 response = IssueRequest(superuserExistingBlockReq)
575 "authenticated request, existing block, method disabled",
576 MethodDisabledError.HTTPCode,
578 theConfig.EnableDelete = true
580 // Authenticated admin request for existing block.
581 response = IssueRequest(superuserExistingBlockReq)
583 "data manager request, existing block",
586 // Expect response {"copies_deleted":1,"copies_failed":0}
587 expectedDc = deletecounter{1, 0}
588 json.NewDecoder(response.Body).Decode(&responseDc)
589 if responseDc != expectedDc {
590 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
591 expectedDc, responseDc)
593 // Confirm the block has been deleted
594 buf := make([]byte, BlockSize)
595 _, err := vols[0].Get(context.Background(), TestHash, buf)
596 var blockDeleted = os.IsNotExist(err)
598 t.Error("superuserExistingBlockReq: block not deleted")
601 // A DELETE request on a block newer than BlobSignatureTTL
602 // should return success but leave the block on the volume.
603 vols[0].Put(context.Background(), TestHash, TestBlock)
604 theConfig.BlobSignatureTTL = arvados.Duration(time.Hour)
606 response = IssueRequest(superuserExistingBlockReq)
608 "data manager request, existing block",
611 // Expect response {"copies_deleted":1,"copies_failed":0}
612 expectedDc = deletecounter{1, 0}
613 json.NewDecoder(response.Body).Decode(&responseDc)
614 if responseDc != expectedDc {
615 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
616 expectedDc, responseDc)
618 // Confirm the block has NOT been deleted.
619 _, err = vols[0].Get(context.Background(), TestHash, buf)
621 t.Errorf("testing delete on new block: %s\n", err)
627 // Test handling of the PUT /pull statement.
629 // Cases tested: syntactically valid and invalid pull lists, from the
630 // data manager and from unprivileged users:
632 // 1. Valid pull list from an ordinary user
633 // (expected result: 401 Unauthorized)
635 // 2. Invalid pull request from an ordinary user
636 // (expected result: 401 Unauthorized)
638 // 3. Valid pull request from the data manager
639 // (expected result: 200 OK with request body "Received 3 pull
642 // 4. Invalid pull request from the data manager
643 // (expected result: 400 Bad Request)
645 // Test that in the end, the pull manager received a good pull list with
646 // the expected number of requests.
648 // TODO(twp): test concurrency: launch 100 goroutines to update the
649 // pull list simultaneously. Make sure that none of them return 400
650 // Bad Request and that pullq.GetList() returns a valid list.
652 func TestPullHandler(t *testing.T) {
655 var userToken = "USER TOKEN"
656 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
658 pullq = NewWorkQueue()
660 goodJSON := []byte(`[
662 "locator":"locator_with_two_servers",
669 "locator":"locator_with_no_servers",
674 "servers":["empty_locator"]
678 badJSON := []byte(`{ "key":"I'm a little teapot" }`)
680 type pullTest struct {
686 var testcases = []pullTest{
688 "Valid pull list from an ordinary user",
689 RequestTester{"/pull", userToken, "PUT", goodJSON},
690 http.StatusUnauthorized,
694 "Invalid pull request from an ordinary user",
695 RequestTester{"/pull", userToken, "PUT", badJSON},
696 http.StatusUnauthorized,
700 "Valid pull request from the data manager",
701 RequestTester{"/pull", theConfig.systemAuthToken, "PUT", goodJSON},
703 "Received 3 pull requests\n",
706 "Invalid pull request from the data manager",
707 RequestTester{"/pull", theConfig.systemAuthToken, "PUT", badJSON},
708 http.StatusBadRequest,
713 for _, tst := range testcases {
714 response := IssueRequest(&tst.req)
715 ExpectStatusCode(t, tst.name, tst.responseCode, response)
716 ExpectBody(t, tst.name, tst.responseBody, response)
719 // The Keep pull manager should have received one good list with 3
721 for i := 0; i < 3; i++ {
722 item := <-pullq.NextItem
723 if _, ok := item.(PullRequest); !ok {
724 t.Errorf("item %v could not be parsed as a PullRequest", item)
728 expectChannelEmpty(t, pullq.NextItem)
735 // Cases tested: syntactically valid and invalid trash lists, from the
736 // data manager and from unprivileged users:
738 // 1. Valid trash list from an ordinary user
739 // (expected result: 401 Unauthorized)
741 // 2. Invalid trash list from an ordinary user
742 // (expected result: 401 Unauthorized)
744 // 3. Valid trash list from the data manager
745 // (expected result: 200 OK with request body "Received 3 trash
748 // 4. Invalid trash list from the data manager
749 // (expected result: 400 Bad Request)
751 // Test that in the end, the trash collector received a good list
752 // trash list with the expected number of requests.
754 // TODO(twp): test concurrency: launch 100 goroutines to update the
755 // pull list simultaneously. Make sure that none of them return 400
756 // Bad Request and that replica.Dump() returns a valid list.
758 func TestTrashHandler(t *testing.T) {
761 var userToken = "USER TOKEN"
762 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
764 trashq = NewWorkQueue()
766 goodJSON := []byte(`[
769 "block_mtime":1409082153
773 "block_mtime":1409082153
777 "block_mtime":1409082153
781 badJSON := []byte(`I am not a valid JSON string`)
783 type trashTest struct {
790 var testcases = []trashTest{
792 "Valid trash list from an ordinary user",
793 RequestTester{"/trash", userToken, "PUT", goodJSON},
794 http.StatusUnauthorized,
798 "Invalid trash list from an ordinary user",
799 RequestTester{"/trash", userToken, "PUT", badJSON},
800 http.StatusUnauthorized,
804 "Valid trash list from the data manager",
805 RequestTester{"/trash", theConfig.systemAuthToken, "PUT", goodJSON},
807 "Received 3 trash requests\n",
810 "Invalid trash list from the data manager",
811 RequestTester{"/trash", theConfig.systemAuthToken, "PUT", badJSON},
812 http.StatusBadRequest,
817 for _, tst := range testcases {
818 response := IssueRequest(&tst.req)
819 ExpectStatusCode(t, tst.name, tst.responseCode, response)
820 ExpectBody(t, tst.name, tst.responseBody, response)
823 // The trash collector should have received one good list with 3
825 for i := 0; i < 3; i++ {
826 item := <-trashq.NextItem
827 if _, ok := item.(TrashRequest); !ok {
828 t.Errorf("item %v could not be parsed as a TrashRequest", item)
832 expectChannelEmpty(t, trashq.NextItem)
835 // ====================
837 // ====================
839 // IssueTestRequest executes an HTTP request described by rt, to a
840 // REST router. It returns the HTTP response to the request.
841 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
842 response := httptest.NewRecorder()
843 body := bytes.NewReader(rt.requestBody)
844 req, _ := http.NewRequest(rt.method, rt.uri, body)
845 if rt.apiToken != "" {
846 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
848 loggingRouter := MakeRESTRouter(testCluster)
849 loggingRouter.ServeHTTP(response, req)
853 func IssueHealthCheckRequest(rt *RequestTester) *httptest.ResponseRecorder {
854 response := httptest.NewRecorder()
855 body := bytes.NewReader(rt.requestBody)
856 req, _ := http.NewRequest(rt.method, rt.uri, body)
857 if rt.apiToken != "" {
858 req.Header.Set("Authorization", "Bearer "+rt.apiToken)
860 loggingRouter := MakeRESTRouter(testCluster)
861 loggingRouter.ServeHTTP(response, req)
865 // ExpectStatusCode checks whether a response has the specified status code,
866 // and reports a test failure if not.
867 func ExpectStatusCode(
871 response *httptest.ResponseRecorder) {
872 if response.Code != expectedStatus {
873 t.Errorf("%s: expected status %d, got %+v",
874 testname, expectedStatus, response)
882 response *httptest.ResponseRecorder) {
883 if expectedBody != "" && response.Body.String() != expectedBody {
884 t.Errorf("%s: expected response body '%s', got %+v",
885 testname, expectedBody, response)
890 func TestPutNeedsOnlyOneBuffer(t *testing.T) {
892 KeepVM = MakeTestVolumeManager(1)
895 defer func(orig *bufferPool) {
898 bufs = newBufferPool(1, BlockSize)
900 ok := make(chan struct{})
902 for i := 0; i < 2; i++ {
903 response := IssueRequest(
907 requestBody: TestBlock,
910 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
917 case <-time.After(time.Second):
918 t.Fatal("PUT deadlocks with MaxBuffers==1")
922 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
924 func TestPutHandlerNoBufferleak(t *testing.T) {
927 // Prepare two test Keep volumes.
928 KeepVM = MakeTestVolumeManager(2)
931 ok := make(chan bool)
933 for i := 0; i < theConfig.MaxBuffers+1; i++ {
934 // Unauthenticated request, no server key
935 // => OK (unsigned response)
936 unsignedLocator := "/" + TestHash
937 response := IssueRequest(
940 uri: unsignedLocator,
941 requestBody: TestBlock,
944 "TestPutHandlerBufferleak", http.StatusOK, response)
946 "TestPutHandlerBufferleak",
947 TestHashPutResp, response)
952 case <-time.After(20 * time.Second):
953 // If the buffer pool leaks, the test goroutine hangs.
954 t.Fatal("test did not finish, assuming pool leaked")
959 type notifyingResponseRecorder struct {
960 *httptest.ResponseRecorder
964 func (r *notifyingResponseRecorder) CloseNotify() <-chan bool {
968 func TestGetHandlerClientDisconnect(t *testing.T) {
969 defer func(was bool) {
970 theConfig.RequireSignatures = was
971 }(theConfig.RequireSignatures)
972 theConfig.RequireSignatures = false
974 defer func(orig *bufferPool) {
977 bufs = newBufferPool(1, BlockSize)
978 defer bufs.Put(bufs.Get(BlockSize))
980 KeepVM = MakeTestVolumeManager(2)
983 if err := KeepVM.AllWritable()[0].Put(context.Background(), TestHash, TestBlock); err != nil {
987 resp := ¬ifyingResponseRecorder{
988 ResponseRecorder: httptest.NewRecorder(),
989 closer: make(chan bool, 1),
991 if _, ok := http.ResponseWriter(resp).(http.CloseNotifier); !ok {
992 t.Fatal("notifyingResponseRecorder is broken")
994 // If anyone asks, the client has disconnected.
997 ok := make(chan struct{})
999 req, _ := http.NewRequest("GET", fmt.Sprintf("/%s+%d", TestHash, len(TestBlock)), nil)
1000 MakeRESTRouter(testCluster).ServeHTTP(resp, req)
1005 case <-time.After(20 * time.Second):
1006 t.Fatal("request took >20s, close notifier must be broken")
1010 ExpectStatusCode(t, "client disconnect", http.StatusServiceUnavailable, resp.ResponseRecorder)
1011 for i, v := range KeepVM.AllWritable() {
1012 if calls := v.(*MockVolume).called["GET"]; calls != 0 {
1013 t.Errorf("volume %d got %d calls, expected 0", i, calls)
1018 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
1020 func TestGetHandlerNoBufferLeak(t *testing.T) {
1023 // Prepare two test Keep volumes. Our block is stored on the second volume.
1024 KeepVM = MakeTestVolumeManager(2)
1025 defer KeepVM.Close()
1027 vols := KeepVM.AllWritable()
1028 if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
1032 ok := make(chan bool)
1034 for i := 0; i < theConfig.MaxBuffers+1; i++ {
1035 // Unauthenticated request, unsigned locator
1037 unsignedLocator := "/" + TestHash
1038 response := IssueRequest(
1041 uri: unsignedLocator,
1044 "Unauthenticated request, unsigned locator", http.StatusOK, response)
1046 "Unauthenticated request, unsigned locator",
1053 case <-time.After(20 * time.Second):
1054 // If the buffer pool leaks, the test goroutine hangs.
1055 t.Fatal("test did not finish, assuming pool leaked")
1060 func TestPutReplicationHeader(t *testing.T) {
1063 KeepVM = MakeTestVolumeManager(2)
1064 defer KeepVM.Close()
1066 resp := IssueRequest(&RequestTester{
1068 uri: "/" + TestHash,
1069 requestBody: TestBlock,
1071 if r := resp.Header().Get("X-Keep-Replicas-Stored"); r != "1" {
1072 t.Errorf("Got X-Keep-Replicas-Stored: %q, expected %q", r, "1")
1076 func TestUntrashHandler(t *testing.T) {
1079 // Set up Keep volumes
1080 KeepVM = MakeTestVolumeManager(2)
1081 defer KeepVM.Close()
1082 vols := KeepVM.AllWritable()
1083 vols[0].Put(context.Background(), TestHash, TestBlock)
1085 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
1087 // unauthenticatedReq => UnauthorizedError
1088 unauthenticatedReq := &RequestTester{
1090 uri: "/untrash/" + TestHash,
1092 response := IssueRequest(unauthenticatedReq)
1094 "Unauthenticated request",
1095 UnauthorizedError.HTTPCode,
1098 // notDataManagerReq => UnauthorizedError
1099 notDataManagerReq := &RequestTester{
1101 uri: "/untrash/" + TestHash,
1102 apiToken: knownToken,
1105 response = IssueRequest(notDataManagerReq)
1107 "Non-datamanager token",
1108 UnauthorizedError.HTTPCode,
1111 // datamanagerWithBadHashReq => StatusBadRequest
1112 datamanagerWithBadHashReq := &RequestTester{
1114 uri: "/untrash/thisisnotalocator",
1115 apiToken: theConfig.systemAuthToken,
1117 response = IssueRequest(datamanagerWithBadHashReq)
1119 "Bad locator in untrash request",
1120 http.StatusBadRequest,
1123 // datamanagerWrongMethodReq => StatusBadRequest
1124 datamanagerWrongMethodReq := &RequestTester{
1126 uri: "/untrash/" + TestHash,
1127 apiToken: theConfig.systemAuthToken,
1129 response = IssueRequest(datamanagerWrongMethodReq)
1131 "Only PUT method is supported for untrash",
1132 http.StatusMethodNotAllowed,
1135 // datamanagerReq => StatusOK
1136 datamanagerReq := &RequestTester{
1138 uri: "/untrash/" + TestHash,
1139 apiToken: theConfig.systemAuthToken,
1141 response = IssueRequest(datamanagerReq)
1146 expected := "Successfully untrashed on: [MockVolume],[MockVolume]"
1147 if response.Body.String() != expected {
1149 "Untrash response mismatched: expected %s, got:\n%s",
1150 expected, response.Body.String())
1154 func TestUntrashHandlerWithNoWritableVolumes(t *testing.T) {
1157 // Set up readonly Keep volumes
1158 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
1159 vols[0].Readonly = true
1160 vols[1].Readonly = true
1161 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
1162 defer KeepVM.Close()
1164 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
1166 // datamanagerReq => StatusOK
1167 datamanagerReq := &RequestTester{
1169 uri: "/untrash/" + TestHash,
1170 apiToken: theConfig.systemAuthToken,
1172 response := IssueRequest(datamanagerReq)
1174 "No writable volumes",
1175 http.StatusNotFound,
1179 func TestHealthCheckPing(t *testing.T) {
1180 theConfig.ManagementToken = arvadostest.ManagementToken
1181 pingReq := &RequestTester{
1183 uri: "/_health/ping",
1184 apiToken: arvadostest.ManagementToken,
1186 response := IssueHealthCheckRequest(pingReq)
1191 want := `{"health":"OK"}`
1192 if !strings.Contains(response.Body.String(), want) {
1193 t.Errorf("expected response to include %s: got %s", want, response.Body.String())