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
53 // - permissions on, authenticated request, signed locator, transient error from backend
55 func TestGetHandler(t *testing.T) {
58 // Prepare two test Keep volumes. Our block is stored on the second volume.
59 KeepVM = MakeTestVolumeManager(2)
62 vols := KeepVM.AllWritable()
63 if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
67 // Create locators for testing.
68 // Turn on permission settings so we can generate signed locators.
69 theConfig.RequireSignatures = true
70 theConfig.blobSigningKey = []byte(knownKey)
71 theConfig.BlobSignatureTTL.Set("5m")
74 unsignedLocator = "/" + TestHash
75 validTimestamp = time.Now().Add(theConfig.BlobSignatureTTL.Duration())
76 expiredTimestamp = time.Now().Add(-time.Hour)
77 signedLocator = "/" + SignLocator(TestHash, knownToken, validTimestamp)
78 expiredLocator = "/" + SignLocator(TestHash, knownToken, expiredTimestamp)
82 // Test unauthenticated request with permissions off.
83 theConfig.RequireSignatures = false
85 // Unauthenticated request, unsigned locator
87 response := IssueRequest(
93 "Unauthenticated request, unsigned locator", http.StatusOK, response)
95 "Unauthenticated request, unsigned locator",
99 receivedLen := response.Header().Get("Content-Length")
100 expectedLen := fmt.Sprintf("%d", len(TestBlock))
101 if receivedLen != expectedLen {
102 t.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
107 theConfig.RequireSignatures = true
109 // Authenticated request, signed locator
111 response = IssueRequest(&RequestTester{
114 apiToken: knownToken,
117 "Authenticated request, signed locator", http.StatusOK, response)
119 "Authenticated request, signed locator", string(TestBlock), response)
121 receivedLen = response.Header().Get("Content-Length")
122 expectedLen = fmt.Sprintf("%d", len(TestBlock))
123 if receivedLen != expectedLen {
124 t.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
127 // Authenticated request, unsigned locator
128 // => PermissionError
129 response = IssueRequest(&RequestTester{
131 uri: unsignedLocator,
132 apiToken: knownToken,
134 ExpectStatusCode(t, "unsigned locator", PermissionError.HTTPCode, response)
136 // Unauthenticated request, signed locator
137 // => PermissionError
138 response = IssueRequest(&RequestTester{
143 "Unauthenticated request, signed locator",
144 PermissionError.HTTPCode, response)
146 // Authenticated request, expired locator
148 response = IssueRequest(&RequestTester{
151 apiToken: knownToken,
154 "Authenticated request, expired locator",
155 ExpiredError.HTTPCode, response)
157 // Authenticated request, signed locator
158 // => 503 Server busy (transient error)
160 // Set up the block owning volume to respond with errors
161 vols[0].(*MockVolume).Bad = true
162 vols[0].(*MockVolume).BadVolumeError = VolumeBusyError
163 response = IssueRequest(&RequestTester{
166 apiToken: knownToken,
168 // A transient error from one volume while the other doesn't find the block
169 // should make the service return a 503 so that clients can retry.
171 "Volume backend busy",
175 // Test PutBlockHandler on the following situations:
177 // - with server key, authenticated request, unsigned locator
178 // - with server key, unauthenticated request, unsigned locator
180 func TestPutHandler(t *testing.T) {
183 // Prepare two test Keep volumes.
184 KeepVM = MakeTestVolumeManager(2)
190 // Unauthenticated request, no server key
191 // => OK (unsigned response)
192 unsignedLocator := "/" + TestHash
193 response := IssueRequest(
196 uri: unsignedLocator,
197 requestBody: TestBlock,
201 "Unauthenticated request, no server key", http.StatusOK, response)
203 "Unauthenticated request, no server key",
204 TestHashPutResp, response)
206 // ------------------
207 // With a server key.
209 theConfig.blobSigningKey = []byte(knownKey)
210 theConfig.BlobSignatureTTL.Set("5m")
212 // When a permission key is available, the locator returned
213 // from an authenticated PUT request will be signed.
215 // Authenticated PUT, signed locator
216 // => OK (signed response)
217 response = IssueRequest(
220 uri: unsignedLocator,
221 requestBody: TestBlock,
222 apiToken: knownToken,
226 "Authenticated PUT, signed locator, with server key",
227 http.StatusOK, response)
228 responseLocator := strings.TrimSpace(response.Body.String())
229 if VerifySignature(responseLocator, knownToken) != nil {
230 t.Errorf("Authenticated PUT, signed locator, with server key:\n"+
231 "response '%s' does not contain a valid signature",
235 // Unauthenticated PUT, unsigned locator
237 response = IssueRequest(
240 uri: unsignedLocator,
241 requestBody: TestBlock,
245 "Unauthenticated PUT, unsigned locator, with server key",
246 http.StatusOK, response)
248 "Unauthenticated PUT, unsigned locator, with server key",
249 TestHashPutResp, response)
252 func TestPutAndDeleteSkipReadonlyVolumes(t *testing.T) {
254 theConfig.systemAuthToken = "fake-data-manager-token"
255 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
256 vols[0].Readonly = true
257 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
263 requestBody: TestBlock,
265 defer func(orig bool) {
266 theConfig.EnableDelete = orig
267 }(theConfig.EnableDelete)
268 theConfig.EnableDelete = true
273 requestBody: TestBlock,
274 apiToken: theConfig.systemAuthToken,
281 for _, e := range []expect{
293 if calls := vols[e.volnum].CallCount(e.method); calls != e.callcount {
294 t.Errorf("Got %d %s() on vol %d, expect %d", calls, e.method, e.volnum, e.callcount)
299 // Test /index requests:
300 // - unauthenticated /index request
301 // - unauthenticated /index/prefix request
302 // - authenticated /index request | non-superuser
303 // - authenticated /index/prefix request | non-superuser
304 // - authenticated /index request | superuser
305 // - authenticated /index/prefix request | superuser
307 // The only /index requests that should succeed are those issued by the
308 // superuser. They should pass regardless of the value of RequireSignatures.
310 func TestIndexHandler(t *testing.T) {
313 // Set up Keep volumes and populate them.
314 // Include multiple blocks on different volumes, and
315 // some metadata files (which should be omitted from index listings)
316 KeepVM = MakeTestVolumeManager(2)
319 vols := KeepVM.AllWritable()
320 vols[0].Put(context.Background(), TestHash, TestBlock)
321 vols[1].Put(context.Background(), TestHash2, TestBlock2)
322 vols[0].Put(context.Background(), TestHash+".meta", []byte("metadata"))
323 vols[1].Put(context.Background(), TestHash2+".meta", []byte("metadata"))
325 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
327 unauthenticatedReq := &RequestTester{
331 authenticatedReq := &RequestTester{
334 apiToken: knownToken,
336 superuserReq := &RequestTester{
339 apiToken: theConfig.systemAuthToken,
341 unauthPrefixReq := &RequestTester{
343 uri: "/index/" + TestHash[0:3],
345 authPrefixReq := &RequestTester{
347 uri: "/index/" + TestHash[0:3],
348 apiToken: knownToken,
350 superuserPrefixReq := &RequestTester{
352 uri: "/index/" + TestHash[0:3],
353 apiToken: theConfig.systemAuthToken,
355 superuserNoSuchPrefixReq := &RequestTester{
358 apiToken: theConfig.systemAuthToken,
360 superuserInvalidPrefixReq := &RequestTester{
363 apiToken: theConfig.systemAuthToken,
366 // -------------------------------------------------------------
367 // Only the superuser should be allowed to issue /index requests.
369 // ---------------------------
370 // RequireSignatures enabled
371 // This setting should not affect tests passing.
372 theConfig.RequireSignatures = true
374 // unauthenticated /index request
375 // => UnauthorizedError
376 response := IssueRequest(unauthenticatedReq)
378 "RequireSignatures on, unauthenticated request",
379 UnauthorizedError.HTTPCode,
382 // unauthenticated /index/prefix request
383 // => UnauthorizedError
384 response = IssueRequest(unauthPrefixReq)
386 "permissions on, unauthenticated /index/prefix request",
387 UnauthorizedError.HTTPCode,
390 // authenticated /index request, non-superuser
391 // => UnauthorizedError
392 response = IssueRequest(authenticatedReq)
394 "permissions on, authenticated request, non-superuser",
395 UnauthorizedError.HTTPCode,
398 // authenticated /index/prefix request, non-superuser
399 // => UnauthorizedError
400 response = IssueRequest(authPrefixReq)
402 "permissions on, authenticated /index/prefix request, non-superuser",
403 UnauthorizedError.HTTPCode,
406 // superuser /index request
408 response = IssueRequest(superuserReq)
410 "permissions on, superuser request",
414 // ----------------------------
415 // RequireSignatures disabled
416 // Valid Request should still pass.
417 theConfig.RequireSignatures = false
419 // superuser /index request
421 response = IssueRequest(superuserReq)
423 "permissions on, superuser request",
427 expected := `^` + TestHash + `\+\d+ \d+\n` +
428 TestHash2 + `\+\d+ \d+\n\n$`
429 match, _ := regexp.MatchString(expected, response.Body.String())
432 "permissions on, superuser request: expected %s, got:\n%s",
433 expected, response.Body.String())
436 // superuser /index/prefix request
438 response = IssueRequest(superuserPrefixReq)
440 "permissions on, superuser request",
444 expected = `^` + TestHash + `\+\d+ \d+\n\n$`
445 match, _ = regexp.MatchString(expected, response.Body.String())
448 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
449 expected, response.Body.String())
452 // superuser /index/{no-such-prefix} request
454 response = IssueRequest(superuserNoSuchPrefixReq)
456 "permissions on, superuser request",
460 if "\n" != response.Body.String() {
461 t.Errorf("Expected empty response for %s. Found %s", superuserNoSuchPrefixReq.uri, response.Body.String())
464 // superuser /index/{invalid-prefix} request
465 // => StatusBadRequest
466 response = IssueRequest(superuserInvalidPrefixReq)
468 "permissions on, superuser request",
469 http.StatusBadRequest,
477 // With no token and with a non-data-manager token:
478 // * Delete existing block
479 // (test for 403 Forbidden, confirm block not deleted)
481 // With data manager token:
483 // * Delete existing block
484 // (test for 200 OK, response counts, confirm block deleted)
486 // * Delete nonexistent block
487 // (test for 200 OK, response counts)
491 // * Delete block on read-only and read-write volume
492 // (test for 200 OK, response with copies_deleted=1,
493 // copies_failed=1, confirm block deleted only on r/w volume)
495 // * Delete block on read-only volume only
496 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
497 // confirm block not deleted)
499 func TestDeleteHandler(t *testing.T) {
502 // Set up Keep volumes and populate them.
503 // Include multiple blocks on different volumes, and
504 // some metadata files (which should be omitted from index listings)
505 KeepVM = MakeTestVolumeManager(2)
508 vols := KeepVM.AllWritable()
509 vols[0].Put(context.Background(), TestHash, TestBlock)
511 // Explicitly set the BlobSignatureTTL to 0 for these
512 // tests, to ensure the MockVolume deletes the blocks
513 // even though they have just been created.
514 theConfig.BlobSignatureTTL = arvados.Duration(0)
516 var userToken = "NOT DATA MANAGER TOKEN"
517 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
519 theConfig.EnableDelete = true
521 unauthReq := &RequestTester{
526 userReq := &RequestTester{
532 superuserExistingBlockReq := &RequestTester{
535 apiToken: theConfig.systemAuthToken,
538 superuserNonexistentBlockReq := &RequestTester{
540 uri: "/" + TestHash2,
541 apiToken: theConfig.systemAuthToken,
544 // Unauthenticated request returns PermissionError.
545 var response *httptest.ResponseRecorder
546 response = IssueRequest(unauthReq)
548 "unauthenticated request",
549 PermissionError.HTTPCode,
552 // Authenticated non-admin request returns PermissionError.
553 response = IssueRequest(userReq)
555 "authenticated non-admin request",
556 PermissionError.HTTPCode,
559 // Authenticated admin request for nonexistent block.
560 type deletecounter struct {
561 Deleted int `json:"copies_deleted"`
562 Failed int `json:"copies_failed"`
564 var responseDc, expectedDc deletecounter
566 response = IssueRequest(superuserNonexistentBlockReq)
568 "data manager request, nonexistent block",
572 // Authenticated admin request for existing block while EnableDelete is false.
573 theConfig.EnableDelete = false
574 response = IssueRequest(superuserExistingBlockReq)
576 "authenticated request, existing block, method disabled",
577 MethodDisabledError.HTTPCode,
579 theConfig.EnableDelete = true
581 // Authenticated admin request for existing block.
582 response = IssueRequest(superuserExistingBlockReq)
584 "data manager request, existing block",
587 // Expect response {"copies_deleted":1,"copies_failed":0}
588 expectedDc = deletecounter{1, 0}
589 json.NewDecoder(response.Body).Decode(&responseDc)
590 if responseDc != expectedDc {
591 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
592 expectedDc, responseDc)
594 // Confirm the block has been deleted
595 buf := make([]byte, BlockSize)
596 _, err := vols[0].Get(context.Background(), TestHash, buf)
597 var blockDeleted = os.IsNotExist(err)
599 t.Error("superuserExistingBlockReq: block not deleted")
602 // A DELETE request on a block newer than BlobSignatureTTL
603 // should return success but leave the block on the volume.
604 vols[0].Put(context.Background(), TestHash, TestBlock)
605 theConfig.BlobSignatureTTL = arvados.Duration(time.Hour)
607 response = IssueRequest(superuserExistingBlockReq)
609 "data manager request, existing block",
612 // Expect response {"copies_deleted":1,"copies_failed":0}
613 expectedDc = deletecounter{1, 0}
614 json.NewDecoder(response.Body).Decode(&responseDc)
615 if responseDc != expectedDc {
616 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
617 expectedDc, responseDc)
619 // Confirm the block has NOT been deleted.
620 _, err = vols[0].Get(context.Background(), TestHash, buf)
622 t.Errorf("testing delete on new block: %s\n", err)
628 // Test handling of the PUT /pull statement.
630 // Cases tested: syntactically valid and invalid pull lists, from the
631 // data manager and from unprivileged users:
633 // 1. Valid pull list from an ordinary user
634 // (expected result: 401 Unauthorized)
636 // 2. Invalid pull request from an ordinary user
637 // (expected result: 401 Unauthorized)
639 // 3. Valid pull request from the data manager
640 // (expected result: 200 OK with request body "Received 3 pull
643 // 4. Invalid pull request from the data manager
644 // (expected result: 400 Bad Request)
646 // Test that in the end, the pull manager received a good pull list with
647 // the expected number of requests.
649 // TODO(twp): test concurrency: launch 100 goroutines to update the
650 // pull list simultaneously. Make sure that none of them return 400
651 // Bad Request and that pullq.GetList() returns a valid list.
653 func TestPullHandler(t *testing.T) {
656 var userToken = "USER TOKEN"
657 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
659 pullq = NewWorkQueue()
661 goodJSON := []byte(`[
663 "locator":"locator_with_two_servers",
670 "locator":"locator_with_no_servers",
675 "servers":["empty_locator"]
679 badJSON := []byte(`{ "key":"I'm a little teapot" }`)
681 type pullTest struct {
687 var testcases = []pullTest{
689 "Valid pull list from an ordinary user",
690 RequestTester{"/pull", userToken, "PUT", goodJSON},
691 http.StatusUnauthorized,
695 "Invalid pull request from an ordinary user",
696 RequestTester{"/pull", userToken, "PUT", badJSON},
697 http.StatusUnauthorized,
701 "Valid pull request from the data manager",
702 RequestTester{"/pull", theConfig.systemAuthToken, "PUT", goodJSON},
704 "Received 3 pull requests\n",
707 "Invalid pull request from the data manager",
708 RequestTester{"/pull", theConfig.systemAuthToken, "PUT", badJSON},
709 http.StatusBadRequest,
714 for _, tst := range testcases {
715 response := IssueRequest(&tst.req)
716 ExpectStatusCode(t, tst.name, tst.responseCode, response)
717 ExpectBody(t, tst.name, tst.responseBody, response)
720 // The Keep pull manager should have received one good list with 3
722 for i := 0; i < 3; i++ {
723 item := <-pullq.NextItem
724 if _, ok := item.(PullRequest); !ok {
725 t.Errorf("item %v could not be parsed as a PullRequest", item)
729 expectChannelEmpty(t, pullq.NextItem)
736 // Cases tested: syntactically valid and invalid trash lists, from the
737 // data manager and from unprivileged users:
739 // 1. Valid trash list from an ordinary user
740 // (expected result: 401 Unauthorized)
742 // 2. Invalid trash list from an ordinary user
743 // (expected result: 401 Unauthorized)
745 // 3. Valid trash list from the data manager
746 // (expected result: 200 OK with request body "Received 3 trash
749 // 4. Invalid trash list from the data manager
750 // (expected result: 400 Bad Request)
752 // Test that in the end, the trash collector received a good list
753 // trash list with the expected number of requests.
755 // TODO(twp): test concurrency: launch 100 goroutines to update the
756 // pull list simultaneously. Make sure that none of them return 400
757 // Bad Request and that replica.Dump() returns a valid list.
759 func TestTrashHandler(t *testing.T) {
762 var userToken = "USER TOKEN"
763 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
765 trashq = NewWorkQueue()
767 goodJSON := []byte(`[
770 "block_mtime":1409082153
774 "block_mtime":1409082153
778 "block_mtime":1409082153
782 badJSON := []byte(`I am not a valid JSON string`)
784 type trashTest struct {
791 var testcases = []trashTest{
793 "Valid trash list from an ordinary user",
794 RequestTester{"/trash", userToken, "PUT", goodJSON},
795 http.StatusUnauthorized,
799 "Invalid trash list from an ordinary user",
800 RequestTester{"/trash", userToken, "PUT", badJSON},
801 http.StatusUnauthorized,
805 "Valid trash list from the data manager",
806 RequestTester{"/trash", theConfig.systemAuthToken, "PUT", goodJSON},
808 "Received 3 trash requests\n",
811 "Invalid trash list from the data manager",
812 RequestTester{"/trash", theConfig.systemAuthToken, "PUT", badJSON},
813 http.StatusBadRequest,
818 for _, tst := range testcases {
819 response := IssueRequest(&tst.req)
820 ExpectStatusCode(t, tst.name, tst.responseCode, response)
821 ExpectBody(t, tst.name, tst.responseBody, response)
824 // The trash collector should have received one good list with 3
826 for i := 0; i < 3; i++ {
827 item := <-trashq.NextItem
828 if _, ok := item.(TrashRequest); !ok {
829 t.Errorf("item %v could not be parsed as a TrashRequest", item)
833 expectChannelEmpty(t, trashq.NextItem)
836 // ====================
838 // ====================
840 // IssueTestRequest executes an HTTP request described by rt, to a
841 // REST router. It returns the HTTP response to the request.
842 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
843 response := httptest.NewRecorder()
844 body := bytes.NewReader(rt.requestBody)
845 req, _ := http.NewRequest(rt.method, rt.uri, body)
846 if rt.apiToken != "" {
847 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
849 loggingRouter := MakeRESTRouter(testCluster, prometheus.NewRegistry())
850 loggingRouter.ServeHTTP(response, req)
854 func IssueHealthCheckRequest(rt *RequestTester) *httptest.ResponseRecorder {
855 response := httptest.NewRecorder()
856 body := bytes.NewReader(rt.requestBody)
857 req, _ := http.NewRequest(rt.method, rt.uri, body)
858 if rt.apiToken != "" {
859 req.Header.Set("Authorization", "Bearer "+rt.apiToken)
861 loggingRouter := MakeRESTRouter(testCluster, prometheus.NewRegistry())
862 loggingRouter.ServeHTTP(response, req)
866 // ExpectStatusCode checks whether a response has the specified status code,
867 // and reports a test failure if not.
868 func ExpectStatusCode(
872 response *httptest.ResponseRecorder) {
873 if response.Code != expectedStatus {
874 t.Errorf("%s: expected status %d, got %+v",
875 testname, expectedStatus, response)
883 response *httptest.ResponseRecorder) {
884 if expectedBody != "" && response.Body.String() != expectedBody {
885 t.Errorf("%s: expected response body '%s', got %+v",
886 testname, expectedBody, response)
891 func TestPutNeedsOnlyOneBuffer(t *testing.T) {
893 KeepVM = MakeTestVolumeManager(1)
896 defer func(orig *bufferPool) {
899 bufs = newBufferPool(1, BlockSize)
901 ok := make(chan struct{})
903 for i := 0; i < 2; i++ {
904 response := IssueRequest(
908 requestBody: TestBlock,
911 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
918 case <-time.After(time.Second):
919 t.Fatal("PUT deadlocks with MaxBuffers==1")
923 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
925 func TestPutHandlerNoBufferleak(t *testing.T) {
928 // Prepare two test Keep volumes.
929 KeepVM = MakeTestVolumeManager(2)
932 ok := make(chan bool)
934 for i := 0; i < theConfig.MaxBuffers+1; i++ {
935 // Unauthenticated request, no server key
936 // => OK (unsigned response)
937 unsignedLocator := "/" + TestHash
938 response := IssueRequest(
941 uri: unsignedLocator,
942 requestBody: TestBlock,
945 "TestPutHandlerBufferleak", http.StatusOK, response)
947 "TestPutHandlerBufferleak",
948 TestHashPutResp, response)
953 case <-time.After(20 * time.Second):
954 // If the buffer pool leaks, the test goroutine hangs.
955 t.Fatal("test did not finish, assuming pool leaked")
960 type notifyingResponseRecorder struct {
961 *httptest.ResponseRecorder
965 func (r *notifyingResponseRecorder) CloseNotify() <-chan bool {
969 func TestGetHandlerClientDisconnect(t *testing.T) {
970 defer func(was bool) {
971 theConfig.RequireSignatures = was
972 }(theConfig.RequireSignatures)
973 theConfig.RequireSignatures = false
975 defer func(orig *bufferPool) {
978 bufs = newBufferPool(1, BlockSize)
979 defer bufs.Put(bufs.Get(BlockSize))
981 KeepVM = MakeTestVolumeManager(2)
984 if err := KeepVM.AllWritable()[0].Put(context.Background(), TestHash, TestBlock); err != nil {
988 resp := ¬ifyingResponseRecorder{
989 ResponseRecorder: httptest.NewRecorder(),
990 closer: make(chan bool, 1),
992 if _, ok := http.ResponseWriter(resp).(http.CloseNotifier); !ok {
993 t.Fatal("notifyingResponseRecorder is broken")
995 // If anyone asks, the client has disconnected.
998 ok := make(chan struct{})
1000 req, _ := http.NewRequest("GET", fmt.Sprintf("/%s+%d", TestHash, len(TestBlock)), nil)
1001 MakeRESTRouter(testCluster, prometheus.NewRegistry()).ServeHTTP(resp, req)
1006 case <-time.After(20 * time.Second):
1007 t.Fatal("request took >20s, close notifier must be broken")
1011 ExpectStatusCode(t, "client disconnect", http.StatusServiceUnavailable, resp.ResponseRecorder)
1012 for i, v := range KeepVM.AllWritable() {
1013 if calls := v.(*MockVolume).called["GET"]; calls != 0 {
1014 t.Errorf("volume %d got %d calls, expected 0", i, calls)
1019 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
1021 func TestGetHandlerNoBufferLeak(t *testing.T) {
1024 // Prepare two test Keep volumes. Our block is stored on the second volume.
1025 KeepVM = MakeTestVolumeManager(2)
1026 defer KeepVM.Close()
1028 vols := KeepVM.AllWritable()
1029 if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
1033 ok := make(chan bool)
1035 for i := 0; i < theConfig.MaxBuffers+1; i++ {
1036 // Unauthenticated request, unsigned locator
1038 unsignedLocator := "/" + TestHash
1039 response := IssueRequest(
1042 uri: unsignedLocator,
1045 "Unauthenticated request, unsigned locator", http.StatusOK, response)
1047 "Unauthenticated request, unsigned locator",
1054 case <-time.After(20 * time.Second):
1055 // If the buffer pool leaks, the test goroutine hangs.
1056 t.Fatal("test did not finish, assuming pool leaked")
1061 func TestPutReplicationHeader(t *testing.T) {
1064 KeepVM = MakeTestVolumeManager(2)
1065 defer KeepVM.Close()
1067 resp := IssueRequest(&RequestTester{
1069 uri: "/" + TestHash,
1070 requestBody: TestBlock,
1072 if r := resp.Header().Get("X-Keep-Replicas-Stored"); r != "1" {
1073 t.Errorf("Got X-Keep-Replicas-Stored: %q, expected %q", r, "1")
1077 func TestUntrashHandler(t *testing.T) {
1080 // Set up Keep volumes
1081 KeepVM = MakeTestVolumeManager(2)
1082 defer KeepVM.Close()
1083 vols := KeepVM.AllWritable()
1084 vols[0].Put(context.Background(), TestHash, TestBlock)
1086 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
1088 // unauthenticatedReq => UnauthorizedError
1089 unauthenticatedReq := &RequestTester{
1091 uri: "/untrash/" + TestHash,
1093 response := IssueRequest(unauthenticatedReq)
1095 "Unauthenticated request",
1096 UnauthorizedError.HTTPCode,
1099 // notDataManagerReq => UnauthorizedError
1100 notDataManagerReq := &RequestTester{
1102 uri: "/untrash/" + TestHash,
1103 apiToken: knownToken,
1106 response = IssueRequest(notDataManagerReq)
1108 "Non-datamanager token",
1109 UnauthorizedError.HTTPCode,
1112 // datamanagerWithBadHashReq => StatusBadRequest
1113 datamanagerWithBadHashReq := &RequestTester{
1115 uri: "/untrash/thisisnotalocator",
1116 apiToken: theConfig.systemAuthToken,
1118 response = IssueRequest(datamanagerWithBadHashReq)
1120 "Bad locator in untrash request",
1121 http.StatusBadRequest,
1124 // datamanagerWrongMethodReq => StatusBadRequest
1125 datamanagerWrongMethodReq := &RequestTester{
1127 uri: "/untrash/" + TestHash,
1128 apiToken: theConfig.systemAuthToken,
1130 response = IssueRequest(datamanagerWrongMethodReq)
1132 "Only PUT method is supported for untrash",
1133 http.StatusMethodNotAllowed,
1136 // datamanagerReq => StatusOK
1137 datamanagerReq := &RequestTester{
1139 uri: "/untrash/" + TestHash,
1140 apiToken: theConfig.systemAuthToken,
1142 response = IssueRequest(datamanagerReq)
1147 expected := "Successfully untrashed on: [MockVolume],[MockVolume]"
1148 if response.Body.String() != expected {
1150 "Untrash response mismatched: expected %s, got:\n%s",
1151 expected, response.Body.String())
1155 func TestUntrashHandlerWithNoWritableVolumes(t *testing.T) {
1158 // Set up readonly Keep volumes
1159 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
1160 vols[0].Readonly = true
1161 vols[1].Readonly = true
1162 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
1163 defer KeepVM.Close()
1165 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
1167 // datamanagerReq => StatusOK
1168 datamanagerReq := &RequestTester{
1170 uri: "/untrash/" + TestHash,
1171 apiToken: theConfig.systemAuthToken,
1173 response := IssueRequest(datamanagerReq)
1175 "No writable volumes",
1176 http.StatusNotFound,
1180 func TestHealthCheckPing(t *testing.T) {
1181 theConfig.ManagementToken = arvadostest.ManagementToken
1182 pingReq := &RequestTester{
1184 uri: "/_health/ping",
1185 apiToken: arvadostest.ManagementToken,
1187 response := IssueHealthCheckRequest(pingReq)
1192 want := `{"health":"OK"}`
1193 if !strings.Contains(response.Body.String(), want) {
1194 t.Errorf("expected response to include %s: got %s", want, response.Body.String())