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)
156 // Test PutBlockHandler on the following situations:
158 // - with server key, authenticated request, unsigned locator
159 // - with server key, unauthenticated request, unsigned locator
161 func TestPutHandler(t *testing.T) {
164 // Prepare two test Keep volumes.
165 KeepVM = MakeTestVolumeManager(2)
171 // Unauthenticated request, no server key
172 // => OK (unsigned response)
173 unsignedLocator := "/" + TestHash
174 response := IssueRequest(
177 uri: unsignedLocator,
178 requestBody: TestBlock,
182 "Unauthenticated request, no server key", http.StatusOK, response)
184 "Unauthenticated request, no server key",
185 TestHashPutResp, response)
187 // ------------------
188 // With a server key.
190 theConfig.blobSigningKey = []byte(knownKey)
191 theConfig.BlobSignatureTTL.Set("5m")
193 // When a permission key is available, the locator returned
194 // from an authenticated PUT request will be signed.
196 // Authenticated PUT, signed locator
197 // => OK (signed response)
198 response = IssueRequest(
201 uri: unsignedLocator,
202 requestBody: TestBlock,
203 apiToken: knownToken,
207 "Authenticated PUT, signed locator, with server key",
208 http.StatusOK, response)
209 responseLocator := strings.TrimSpace(response.Body.String())
210 if VerifySignature(responseLocator, knownToken) != nil {
211 t.Errorf("Authenticated PUT, signed locator, with server key:\n"+
212 "response '%s' does not contain a valid signature",
216 // Unauthenticated PUT, unsigned locator
218 response = IssueRequest(
221 uri: unsignedLocator,
222 requestBody: TestBlock,
226 "Unauthenticated PUT, unsigned locator, with server key",
227 http.StatusOK, response)
229 "Unauthenticated PUT, unsigned locator, with server key",
230 TestHashPutResp, response)
233 func TestPutAndDeleteSkipReadonlyVolumes(t *testing.T) {
235 theConfig.systemAuthToken = "fake-data-manager-token"
236 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
237 vols[0].Readonly = true
238 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
244 requestBody: TestBlock,
246 defer func(orig bool) {
247 theConfig.EnableDelete = orig
248 }(theConfig.EnableDelete)
249 theConfig.EnableDelete = true
254 requestBody: TestBlock,
255 apiToken: theConfig.systemAuthToken,
262 for _, e := range []expect{
274 if calls := vols[e.volnum].CallCount(e.method); calls != e.callcount {
275 t.Errorf("Got %d %s() on vol %d, expect %d", calls, e.method, e.volnum, e.callcount)
280 // Test /index requests:
281 // - unauthenticated /index request
282 // - unauthenticated /index/prefix request
283 // - authenticated /index request | non-superuser
284 // - authenticated /index/prefix request | non-superuser
285 // - authenticated /index request | superuser
286 // - authenticated /index/prefix request | superuser
288 // The only /index requests that should succeed are those issued by the
289 // superuser. They should pass regardless of the value of RequireSignatures.
291 func TestIndexHandler(t *testing.T) {
294 // Set up Keep volumes and populate them.
295 // Include multiple blocks on different volumes, and
296 // some metadata files (which should be omitted from index listings)
297 KeepVM = MakeTestVolumeManager(2)
300 vols := KeepVM.AllWritable()
301 vols[0].Put(context.Background(), TestHash, TestBlock)
302 vols[1].Put(context.Background(), TestHash2, TestBlock2)
303 vols[0].Put(context.Background(), TestHash+".meta", []byte("metadata"))
304 vols[1].Put(context.Background(), TestHash2+".meta", []byte("metadata"))
306 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
308 unauthenticatedReq := &RequestTester{
312 authenticatedReq := &RequestTester{
315 apiToken: knownToken,
317 superuserReq := &RequestTester{
320 apiToken: theConfig.systemAuthToken,
322 unauthPrefixReq := &RequestTester{
324 uri: "/index/" + TestHash[0:3],
326 authPrefixReq := &RequestTester{
328 uri: "/index/" + TestHash[0:3],
329 apiToken: knownToken,
331 superuserPrefixReq := &RequestTester{
333 uri: "/index/" + TestHash[0:3],
334 apiToken: theConfig.systemAuthToken,
336 superuserNoSuchPrefixReq := &RequestTester{
339 apiToken: theConfig.systemAuthToken,
341 superuserInvalidPrefixReq := &RequestTester{
344 apiToken: theConfig.systemAuthToken,
347 // -------------------------------------------------------------
348 // Only the superuser should be allowed to issue /index requests.
350 // ---------------------------
351 // RequireSignatures enabled
352 // This setting should not affect tests passing.
353 theConfig.RequireSignatures = true
355 // unauthenticated /index request
356 // => UnauthorizedError
357 response := IssueRequest(unauthenticatedReq)
359 "RequireSignatures on, unauthenticated request",
360 UnauthorizedError.HTTPCode,
363 // unauthenticated /index/prefix request
364 // => UnauthorizedError
365 response = IssueRequest(unauthPrefixReq)
367 "permissions on, unauthenticated /index/prefix request",
368 UnauthorizedError.HTTPCode,
371 // authenticated /index request, non-superuser
372 // => UnauthorizedError
373 response = IssueRequest(authenticatedReq)
375 "permissions on, authenticated request, non-superuser",
376 UnauthorizedError.HTTPCode,
379 // authenticated /index/prefix request, non-superuser
380 // => UnauthorizedError
381 response = IssueRequest(authPrefixReq)
383 "permissions on, authenticated /index/prefix request, non-superuser",
384 UnauthorizedError.HTTPCode,
387 // superuser /index request
389 response = IssueRequest(superuserReq)
391 "permissions on, superuser request",
395 // ----------------------------
396 // RequireSignatures disabled
397 // Valid Request should still pass.
398 theConfig.RequireSignatures = false
400 // superuser /index request
402 response = IssueRequest(superuserReq)
404 "permissions on, superuser request",
408 expected := `^` + TestHash + `\+\d+ \d+\n` +
409 TestHash2 + `\+\d+ \d+\n\n$`
410 match, _ := regexp.MatchString(expected, response.Body.String())
413 "permissions on, superuser request: expected %s, got:\n%s",
414 expected, response.Body.String())
417 // superuser /index/prefix request
419 response = IssueRequest(superuserPrefixReq)
421 "permissions on, superuser request",
425 expected = `^` + TestHash + `\+\d+ \d+\n\n$`
426 match, _ = regexp.MatchString(expected, response.Body.String())
429 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
430 expected, response.Body.String())
433 // superuser /index/{no-such-prefix} request
435 response = IssueRequest(superuserNoSuchPrefixReq)
437 "permissions on, superuser request",
441 if "\n" != response.Body.String() {
442 t.Errorf("Expected empty response for %s. Found %s", superuserNoSuchPrefixReq.uri, response.Body.String())
445 // superuser /index/{invalid-prefix} request
446 // => StatusBadRequest
447 response = IssueRequest(superuserInvalidPrefixReq)
449 "permissions on, superuser request",
450 http.StatusBadRequest,
458 // With no token and with a non-data-manager token:
459 // * Delete existing block
460 // (test for 403 Forbidden, confirm block not deleted)
462 // With data manager token:
464 // * Delete existing block
465 // (test for 200 OK, response counts, confirm block deleted)
467 // * Delete nonexistent block
468 // (test for 200 OK, response counts)
472 // * Delete block on read-only and read-write volume
473 // (test for 200 OK, response with copies_deleted=1,
474 // copies_failed=1, confirm block deleted only on r/w volume)
476 // * Delete block on read-only volume only
477 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
478 // confirm block not deleted)
480 func TestDeleteHandler(t *testing.T) {
483 // Set up Keep volumes and populate them.
484 // Include multiple blocks on different volumes, and
485 // some metadata files (which should be omitted from index listings)
486 KeepVM = MakeTestVolumeManager(2)
489 vols := KeepVM.AllWritable()
490 vols[0].Put(context.Background(), TestHash, TestBlock)
492 // Explicitly set the BlobSignatureTTL to 0 for these
493 // tests, to ensure the MockVolume deletes the blocks
494 // even though they have just been created.
495 theConfig.BlobSignatureTTL = arvados.Duration(0)
497 var userToken = "NOT DATA MANAGER TOKEN"
498 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
500 theConfig.EnableDelete = true
502 unauthReq := &RequestTester{
507 userReq := &RequestTester{
513 superuserExistingBlockReq := &RequestTester{
516 apiToken: theConfig.systemAuthToken,
519 superuserNonexistentBlockReq := &RequestTester{
521 uri: "/" + TestHash2,
522 apiToken: theConfig.systemAuthToken,
525 // Unauthenticated request returns PermissionError.
526 var response *httptest.ResponseRecorder
527 response = IssueRequest(unauthReq)
529 "unauthenticated request",
530 PermissionError.HTTPCode,
533 // Authenticated non-admin request returns PermissionError.
534 response = IssueRequest(userReq)
536 "authenticated non-admin request",
537 PermissionError.HTTPCode,
540 // Authenticated admin request for nonexistent block.
541 type deletecounter struct {
542 Deleted int `json:"copies_deleted"`
543 Failed int `json:"copies_failed"`
545 var responseDc, expectedDc deletecounter
547 response = IssueRequest(superuserNonexistentBlockReq)
549 "data manager request, nonexistent block",
553 // Authenticated admin request for existing block while EnableDelete is false.
554 theConfig.EnableDelete = false
555 response = IssueRequest(superuserExistingBlockReq)
557 "authenticated request, existing block, method disabled",
558 MethodDisabledError.HTTPCode,
560 theConfig.EnableDelete = true
562 // Authenticated admin request for existing block.
563 response = IssueRequest(superuserExistingBlockReq)
565 "data manager request, existing block",
568 // Expect response {"copies_deleted":1,"copies_failed":0}
569 expectedDc = deletecounter{1, 0}
570 json.NewDecoder(response.Body).Decode(&responseDc)
571 if responseDc != expectedDc {
572 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
573 expectedDc, responseDc)
575 // Confirm the block has been deleted
576 buf := make([]byte, BlockSize)
577 _, err := vols[0].Get(context.Background(), TestHash, buf)
578 var blockDeleted = os.IsNotExist(err)
580 t.Error("superuserExistingBlockReq: block not deleted")
583 // A DELETE request on a block newer than BlobSignatureTTL
584 // should return success but leave the block on the volume.
585 vols[0].Put(context.Background(), TestHash, TestBlock)
586 theConfig.BlobSignatureTTL = arvados.Duration(time.Hour)
588 response = IssueRequest(superuserExistingBlockReq)
590 "data manager request, existing block",
593 // Expect response {"copies_deleted":1,"copies_failed":0}
594 expectedDc = deletecounter{1, 0}
595 json.NewDecoder(response.Body).Decode(&responseDc)
596 if responseDc != expectedDc {
597 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
598 expectedDc, responseDc)
600 // Confirm the block has NOT been deleted.
601 _, err = vols[0].Get(context.Background(), TestHash, buf)
603 t.Errorf("testing delete on new block: %s\n", err)
609 // Test handling of the PUT /pull statement.
611 // Cases tested: syntactically valid and invalid pull lists, from the
612 // data manager and from unprivileged users:
614 // 1. Valid pull list from an ordinary user
615 // (expected result: 401 Unauthorized)
617 // 2. Invalid pull request from an ordinary user
618 // (expected result: 401 Unauthorized)
620 // 3. Valid pull request from the data manager
621 // (expected result: 200 OK with request body "Received 3 pull
624 // 4. Invalid pull request from the data manager
625 // (expected result: 400 Bad Request)
627 // Test that in the end, the pull manager received a good pull list with
628 // the expected number of requests.
630 // TODO(twp): test concurrency: launch 100 goroutines to update the
631 // pull list simultaneously. Make sure that none of them return 400
632 // Bad Request and that pullq.GetList() returns a valid list.
634 func TestPullHandler(t *testing.T) {
637 var userToken = "USER TOKEN"
638 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
640 pullq = NewWorkQueue()
642 goodJSON := []byte(`[
644 "locator":"locator_with_two_servers",
651 "locator":"locator_with_no_servers",
656 "servers":["empty_locator"]
660 badJSON := []byte(`{ "key":"I'm a little teapot" }`)
662 type pullTest struct {
668 var testcases = []pullTest{
670 "Valid pull list from an ordinary user",
671 RequestTester{"/pull", userToken, "PUT", goodJSON},
672 http.StatusUnauthorized,
676 "Invalid pull request from an ordinary user",
677 RequestTester{"/pull", userToken, "PUT", badJSON},
678 http.StatusUnauthorized,
682 "Valid pull request from the data manager",
683 RequestTester{"/pull", theConfig.systemAuthToken, "PUT", goodJSON},
685 "Received 3 pull requests\n",
688 "Invalid pull request from the data manager",
689 RequestTester{"/pull", theConfig.systemAuthToken, "PUT", badJSON},
690 http.StatusBadRequest,
695 for _, tst := range testcases {
696 response := IssueRequest(&tst.req)
697 ExpectStatusCode(t, tst.name, tst.responseCode, response)
698 ExpectBody(t, tst.name, tst.responseBody, response)
701 // The Keep pull manager should have received one good list with 3
703 for i := 0; i < 3; i++ {
704 item := <-pullq.NextItem
705 if _, ok := item.(PullRequest); !ok {
706 t.Errorf("item %v could not be parsed as a PullRequest", item)
710 expectChannelEmpty(t, pullq.NextItem)
717 // Cases tested: syntactically valid and invalid trash lists, from the
718 // data manager and from unprivileged users:
720 // 1. Valid trash list from an ordinary user
721 // (expected result: 401 Unauthorized)
723 // 2. Invalid trash list from an ordinary user
724 // (expected result: 401 Unauthorized)
726 // 3. Valid trash list from the data manager
727 // (expected result: 200 OK with request body "Received 3 trash
730 // 4. Invalid trash list from the data manager
731 // (expected result: 400 Bad Request)
733 // Test that in the end, the trash collector received a good list
734 // trash list with the expected number of requests.
736 // TODO(twp): test concurrency: launch 100 goroutines to update the
737 // pull list simultaneously. Make sure that none of them return 400
738 // Bad Request and that replica.Dump() returns a valid list.
740 func TestTrashHandler(t *testing.T) {
743 var userToken = "USER TOKEN"
744 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
746 trashq = NewWorkQueue()
748 goodJSON := []byte(`[
751 "block_mtime":1409082153
755 "block_mtime":1409082153
759 "block_mtime":1409082153
763 badJSON := []byte(`I am not a valid JSON string`)
765 type trashTest struct {
772 var testcases = []trashTest{
774 "Valid trash list from an ordinary user",
775 RequestTester{"/trash", userToken, "PUT", goodJSON},
776 http.StatusUnauthorized,
780 "Invalid trash list from an ordinary user",
781 RequestTester{"/trash", userToken, "PUT", badJSON},
782 http.StatusUnauthorized,
786 "Valid trash list from the data manager",
787 RequestTester{"/trash", theConfig.systemAuthToken, "PUT", goodJSON},
789 "Received 3 trash requests\n",
792 "Invalid trash list from the data manager",
793 RequestTester{"/trash", theConfig.systemAuthToken, "PUT", badJSON},
794 http.StatusBadRequest,
799 for _, tst := range testcases {
800 response := IssueRequest(&tst.req)
801 ExpectStatusCode(t, tst.name, tst.responseCode, response)
802 ExpectBody(t, tst.name, tst.responseBody, response)
805 // The trash collector should have received one good list with 3
807 for i := 0; i < 3; i++ {
808 item := <-trashq.NextItem
809 if _, ok := item.(TrashRequest); !ok {
810 t.Errorf("item %v could not be parsed as a TrashRequest", item)
814 expectChannelEmpty(t, trashq.NextItem)
817 // ====================
819 // ====================
821 // IssueTestRequest executes an HTTP request described by rt, to a
822 // REST router. It returns the HTTP response to the request.
823 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
824 response := httptest.NewRecorder()
825 body := bytes.NewReader(rt.requestBody)
826 req, _ := http.NewRequest(rt.method, rt.uri, body)
827 if rt.apiToken != "" {
828 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
830 loggingRouter := MakeRESTRouter(testCluster)
831 loggingRouter.ServeHTTP(response, req)
835 func IssueHealthCheckRequest(rt *RequestTester) *httptest.ResponseRecorder {
836 response := httptest.NewRecorder()
837 body := bytes.NewReader(rt.requestBody)
838 req, _ := http.NewRequest(rt.method, rt.uri, body)
839 if rt.apiToken != "" {
840 req.Header.Set("Authorization", "Bearer "+rt.apiToken)
842 loggingRouter := MakeRESTRouter(testCluster)
843 loggingRouter.ServeHTTP(response, req)
847 // ExpectStatusCode checks whether a response has the specified status code,
848 // and reports a test failure if not.
849 func ExpectStatusCode(
853 response *httptest.ResponseRecorder) {
854 if response.Code != expectedStatus {
855 t.Errorf("%s: expected status %d, got %+v",
856 testname, expectedStatus, response)
864 response *httptest.ResponseRecorder) {
865 if expectedBody != "" && response.Body.String() != expectedBody {
866 t.Errorf("%s: expected response body '%s', got %+v",
867 testname, expectedBody, response)
872 func TestPutNeedsOnlyOneBuffer(t *testing.T) {
874 KeepVM = MakeTestVolumeManager(1)
877 defer func(orig *bufferPool) {
880 bufs = newBufferPool(1, BlockSize)
882 ok := make(chan struct{})
884 for i := 0; i < 2; i++ {
885 response := IssueRequest(
889 requestBody: TestBlock,
892 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
899 case <-time.After(time.Second):
900 t.Fatal("PUT deadlocks with MaxBuffers==1")
904 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
906 func TestPutHandlerNoBufferleak(t *testing.T) {
909 // Prepare two test Keep volumes.
910 KeepVM = MakeTestVolumeManager(2)
913 ok := make(chan bool)
915 for i := 0; i < theConfig.MaxBuffers+1; i++ {
916 // Unauthenticated request, no server key
917 // => OK (unsigned response)
918 unsignedLocator := "/" + TestHash
919 response := IssueRequest(
922 uri: unsignedLocator,
923 requestBody: TestBlock,
926 "TestPutHandlerBufferleak", http.StatusOK, response)
928 "TestPutHandlerBufferleak",
929 TestHashPutResp, response)
934 case <-time.After(20 * time.Second):
935 // If the buffer pool leaks, the test goroutine hangs.
936 t.Fatal("test did not finish, assuming pool leaked")
941 type notifyingResponseRecorder struct {
942 *httptest.ResponseRecorder
946 func (r *notifyingResponseRecorder) CloseNotify() <-chan bool {
950 func TestGetHandlerClientDisconnect(t *testing.T) {
951 defer func(was bool) {
952 theConfig.RequireSignatures = was
953 }(theConfig.RequireSignatures)
954 theConfig.RequireSignatures = false
956 defer func(orig *bufferPool) {
959 bufs = newBufferPool(1, BlockSize)
960 defer bufs.Put(bufs.Get(BlockSize))
962 KeepVM = MakeTestVolumeManager(2)
965 if err := KeepVM.AllWritable()[0].Put(context.Background(), TestHash, TestBlock); err != nil {
969 resp := ¬ifyingResponseRecorder{
970 ResponseRecorder: httptest.NewRecorder(),
971 closer: make(chan bool, 1),
973 if _, ok := http.ResponseWriter(resp).(http.CloseNotifier); !ok {
974 t.Fatal("notifyingResponseRecorder is broken")
976 // If anyone asks, the client has disconnected.
979 ok := make(chan struct{})
981 req, _ := http.NewRequest("GET", fmt.Sprintf("/%s+%d", TestHash, len(TestBlock)), nil)
982 MakeRESTRouter(testCluster).ServeHTTP(resp, req)
987 case <-time.After(20 * time.Second):
988 t.Fatal("request took >20s, close notifier must be broken")
992 ExpectStatusCode(t, "client disconnect", http.StatusServiceUnavailable, resp.ResponseRecorder)
993 for i, v := range KeepVM.AllWritable() {
994 if calls := v.(*MockVolume).called["GET"]; calls != 0 {
995 t.Errorf("volume %d got %d calls, expected 0", i, calls)
1000 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
1002 func TestGetHandlerNoBufferLeak(t *testing.T) {
1005 // Prepare two test Keep volumes. Our block is stored on the second volume.
1006 KeepVM = MakeTestVolumeManager(2)
1007 defer KeepVM.Close()
1009 vols := KeepVM.AllWritable()
1010 if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
1014 ok := make(chan bool)
1016 for i := 0; i < theConfig.MaxBuffers+1; i++ {
1017 // Unauthenticated request, unsigned locator
1019 unsignedLocator := "/" + TestHash
1020 response := IssueRequest(
1023 uri: unsignedLocator,
1026 "Unauthenticated request, unsigned locator", http.StatusOK, response)
1028 "Unauthenticated request, unsigned locator",
1035 case <-time.After(20 * time.Second):
1036 // If the buffer pool leaks, the test goroutine hangs.
1037 t.Fatal("test did not finish, assuming pool leaked")
1042 func TestPutReplicationHeader(t *testing.T) {
1045 KeepVM = MakeTestVolumeManager(2)
1046 defer KeepVM.Close()
1048 resp := IssueRequest(&RequestTester{
1050 uri: "/" + TestHash,
1051 requestBody: TestBlock,
1053 if r := resp.Header().Get("X-Keep-Replicas-Stored"); r != "1" {
1054 t.Errorf("Got X-Keep-Replicas-Stored: %q, expected %q", r, "1")
1058 func TestUntrashHandler(t *testing.T) {
1061 // Set up Keep volumes
1062 KeepVM = MakeTestVolumeManager(2)
1063 defer KeepVM.Close()
1064 vols := KeepVM.AllWritable()
1065 vols[0].Put(context.Background(), TestHash, TestBlock)
1067 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
1069 // unauthenticatedReq => UnauthorizedError
1070 unauthenticatedReq := &RequestTester{
1072 uri: "/untrash/" + TestHash,
1074 response := IssueRequest(unauthenticatedReq)
1076 "Unauthenticated request",
1077 UnauthorizedError.HTTPCode,
1080 // notDataManagerReq => UnauthorizedError
1081 notDataManagerReq := &RequestTester{
1083 uri: "/untrash/" + TestHash,
1084 apiToken: knownToken,
1087 response = IssueRequest(notDataManagerReq)
1089 "Non-datamanager token",
1090 UnauthorizedError.HTTPCode,
1093 // datamanagerWithBadHashReq => StatusBadRequest
1094 datamanagerWithBadHashReq := &RequestTester{
1096 uri: "/untrash/thisisnotalocator",
1097 apiToken: theConfig.systemAuthToken,
1099 response = IssueRequest(datamanagerWithBadHashReq)
1101 "Bad locator in untrash request",
1102 http.StatusBadRequest,
1105 // datamanagerWrongMethodReq => StatusBadRequest
1106 datamanagerWrongMethodReq := &RequestTester{
1108 uri: "/untrash/" + TestHash,
1109 apiToken: theConfig.systemAuthToken,
1111 response = IssueRequest(datamanagerWrongMethodReq)
1113 "Only PUT method is supported for untrash",
1114 http.StatusMethodNotAllowed,
1117 // datamanagerReq => StatusOK
1118 datamanagerReq := &RequestTester{
1120 uri: "/untrash/" + TestHash,
1121 apiToken: theConfig.systemAuthToken,
1123 response = IssueRequest(datamanagerReq)
1128 expected := "Successfully untrashed on: [MockVolume],[MockVolume]"
1129 if response.Body.String() != expected {
1131 "Untrash response mismatched: expected %s, got:\n%s",
1132 expected, response.Body.String())
1136 func TestUntrashHandlerWithNoWritableVolumes(t *testing.T) {
1139 // Set up readonly Keep volumes
1140 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
1141 vols[0].Readonly = true
1142 vols[1].Readonly = true
1143 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
1144 defer KeepVM.Close()
1146 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
1148 // datamanagerReq => StatusOK
1149 datamanagerReq := &RequestTester{
1151 uri: "/untrash/" + TestHash,
1152 apiToken: theConfig.systemAuthToken,
1154 response := IssueRequest(datamanagerReq)
1156 "No writable volumes",
1157 http.StatusNotFound,
1161 func TestHealthCheckPing(t *testing.T) {
1162 theConfig.ManagementToken = arvadostest.ManagementToken
1163 pingReq := &RequestTester{
1165 uri: "/_health/ping",
1166 apiToken: arvadostest.ManagementToken,
1168 response := IssueHealthCheckRequest(pingReq)
1173 want := `{"health":"OK"}`
1174 if !strings.Contains(response.Body.String(), want) {
1175 t.Errorf("expected response to include %s: got %s", want, response.Body.String())