1 // Tests for Keep HTTP handlers:
7 // The HTTP handlers are responsible for enforcing permission policy,
8 // so these tests must exercise all possible permission permutations.
24 "git.curoverse.com/arvados.git/sdk/go/arvados"
27 // A RequestTester represents the parameters for an HTTP request to
28 // be issued on behalf of a unit test.
29 type RequestTester struct {
36 // Test GetBlockHandler on the following situations:
37 // - permissions off, unauthenticated request, unsigned locator
38 // - permissions on, authenticated request, signed locator
39 // - permissions on, authenticated request, unsigned locator
40 // - permissions on, unauthenticated request, signed locator
41 // - permissions on, authenticated request, expired locator
43 func TestGetHandler(t *testing.T) {
46 // Prepare two test Keep volumes. Our block is stored on the second volume.
47 KeepVM = MakeTestVolumeManager(2)
50 vols := KeepVM.AllWritable()
51 if err := vols[0].Put(TestHash, TestBlock); err != nil {
55 // Create locators for testing.
56 // Turn on permission settings so we can generate signed locators.
57 theConfig.RequireSignatures = true
58 theConfig.blobSigningKey = []byte(knownKey)
59 theConfig.BlobSignatureTTL.Set("5m")
62 unsignedLocator = "/" + TestHash
63 validTimestamp = time.Now().Add(theConfig.BlobSignatureTTL.Duration())
64 expiredTimestamp = time.Now().Add(-time.Hour)
65 signedLocator = "/" + SignLocator(TestHash, knownToken, validTimestamp)
66 expiredLocator = "/" + SignLocator(TestHash, knownToken, expiredTimestamp)
70 // Test unauthenticated request with permissions off.
71 theConfig.RequireSignatures = false
73 // Unauthenticated request, unsigned locator
75 response := IssueRequest(
81 "Unauthenticated request, unsigned locator", http.StatusOK, response)
83 "Unauthenticated request, unsigned locator",
87 receivedLen := response.Header().Get("Content-Length")
88 expectedLen := fmt.Sprintf("%d", len(TestBlock))
89 if receivedLen != expectedLen {
90 t.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
95 theConfig.RequireSignatures = true
97 // Authenticated request, signed locator
99 response = IssueRequest(&RequestTester{
102 apiToken: knownToken,
105 "Authenticated request, signed locator", http.StatusOK, response)
107 "Authenticated request, signed locator", string(TestBlock), response)
109 receivedLen = response.Header().Get("Content-Length")
110 expectedLen = fmt.Sprintf("%d", len(TestBlock))
111 if receivedLen != expectedLen {
112 t.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
115 // Authenticated request, unsigned locator
116 // => PermissionError
117 response = IssueRequest(&RequestTester{
119 uri: unsignedLocator,
120 apiToken: knownToken,
122 ExpectStatusCode(t, "unsigned locator", PermissionError.HTTPCode, response)
124 // Unauthenticated request, signed locator
125 // => PermissionError
126 response = IssueRequest(&RequestTester{
131 "Unauthenticated request, signed locator",
132 PermissionError.HTTPCode, response)
134 // Authenticated request, expired locator
136 response = IssueRequest(&RequestTester{
139 apiToken: knownToken,
142 "Authenticated request, expired locator",
143 ExpiredError.HTTPCode, response)
146 // Test PutBlockHandler on the following situations:
148 // - with server key, authenticated request, unsigned locator
149 // - with server key, unauthenticated request, unsigned locator
151 func TestPutHandler(t *testing.T) {
154 // Prepare two test Keep volumes.
155 KeepVM = MakeTestVolumeManager(2)
161 // Unauthenticated request, no server key
162 // => OK (unsigned response)
163 unsignedLocator := "/" + TestHash
164 response := IssueRequest(
167 uri: unsignedLocator,
168 requestBody: TestBlock,
172 "Unauthenticated request, no server key", http.StatusOK, response)
174 "Unauthenticated request, no server key",
175 TestHashPutResp, response)
177 // ------------------
178 // With a server key.
180 theConfig.blobSigningKey = []byte(knownKey)
181 theConfig.BlobSignatureTTL.Set("5m")
183 // When a permission key is available, the locator returned
184 // from an authenticated PUT request will be signed.
186 // Authenticated PUT, signed locator
187 // => OK (signed response)
188 response = IssueRequest(
191 uri: unsignedLocator,
192 requestBody: TestBlock,
193 apiToken: knownToken,
197 "Authenticated PUT, signed locator, with server key",
198 http.StatusOK, response)
199 responseLocator := strings.TrimSpace(response.Body.String())
200 if VerifySignature(responseLocator, knownToken) != nil {
201 t.Errorf("Authenticated PUT, signed locator, with server key:\n"+
202 "response '%s' does not contain a valid signature",
206 // Unauthenticated PUT, unsigned locator
208 response = IssueRequest(
211 uri: unsignedLocator,
212 requestBody: TestBlock,
216 "Unauthenticated PUT, unsigned locator, with server key",
217 http.StatusOK, response)
219 "Unauthenticated PUT, unsigned locator, with server key",
220 TestHashPutResp, response)
223 func TestPutAndDeleteSkipReadonlyVolumes(t *testing.T) {
225 theConfig.systemAuthToken = "fake-data-manager-token"
226 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
227 vols[0].Readonly = true
228 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
234 requestBody: TestBlock,
236 defer func(orig bool) {
237 theConfig.EnableDelete = orig
238 }(theConfig.EnableDelete)
239 theConfig.EnableDelete = true
244 requestBody: TestBlock,
245 apiToken: theConfig.systemAuthToken,
252 for _, e := range []expect{
264 if calls := vols[e.volnum].CallCount(e.method); calls != e.callcount {
265 t.Errorf("Got %d %s() on vol %d, expect %d", calls, e.method, e.volnum, e.callcount)
270 // Test /index requests:
271 // - unauthenticated /index request
272 // - unauthenticated /index/prefix request
273 // - authenticated /index request | non-superuser
274 // - authenticated /index/prefix request | non-superuser
275 // - authenticated /index request | superuser
276 // - authenticated /index/prefix request | superuser
278 // The only /index requests that should succeed are those issued by the
279 // superuser. They should pass regardless of the value of RequireSignatures.
281 func TestIndexHandler(t *testing.T) {
284 // Set up Keep volumes and populate them.
285 // Include multiple blocks on different volumes, and
286 // some metadata files (which should be omitted from index listings)
287 KeepVM = MakeTestVolumeManager(2)
290 vols := KeepVM.AllWritable()
291 vols[0].Put(TestHash, TestBlock)
292 vols[1].Put(TestHash2, TestBlock2)
293 vols[0].Put(TestHash+".meta", []byte("metadata"))
294 vols[1].Put(TestHash2+".meta", []byte("metadata"))
296 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
298 unauthenticatedReq := &RequestTester{
302 authenticatedReq := &RequestTester{
305 apiToken: knownToken,
307 superuserReq := &RequestTester{
310 apiToken: theConfig.systemAuthToken,
312 unauthPrefixReq := &RequestTester{
314 uri: "/index/" + TestHash[0:3],
316 authPrefixReq := &RequestTester{
318 uri: "/index/" + TestHash[0:3],
319 apiToken: knownToken,
321 superuserPrefixReq := &RequestTester{
323 uri: "/index/" + TestHash[0:3],
324 apiToken: theConfig.systemAuthToken,
326 superuserNoSuchPrefixReq := &RequestTester{
329 apiToken: theConfig.systemAuthToken,
331 superuserInvalidPrefixReq := &RequestTester{
334 apiToken: theConfig.systemAuthToken,
337 // -------------------------------------------------------------
338 // Only the superuser should be allowed to issue /index requests.
340 // ---------------------------
341 // RequireSignatures enabled
342 // This setting should not affect tests passing.
343 theConfig.RequireSignatures = true
345 // unauthenticated /index request
346 // => UnauthorizedError
347 response := IssueRequest(unauthenticatedReq)
349 "RequireSignatures on, unauthenticated request",
350 UnauthorizedError.HTTPCode,
353 // unauthenticated /index/prefix request
354 // => UnauthorizedError
355 response = IssueRequest(unauthPrefixReq)
357 "permissions on, unauthenticated /index/prefix request",
358 UnauthorizedError.HTTPCode,
361 // authenticated /index request, non-superuser
362 // => UnauthorizedError
363 response = IssueRequest(authenticatedReq)
365 "permissions on, authenticated request, non-superuser",
366 UnauthorizedError.HTTPCode,
369 // authenticated /index/prefix request, non-superuser
370 // => UnauthorizedError
371 response = IssueRequest(authPrefixReq)
373 "permissions on, authenticated /index/prefix request, non-superuser",
374 UnauthorizedError.HTTPCode,
377 // superuser /index request
379 response = IssueRequest(superuserReq)
381 "permissions on, superuser request",
385 // ----------------------------
386 // RequireSignatures disabled
387 // Valid Request should still pass.
388 theConfig.RequireSignatures = false
390 // superuser /index request
392 response = IssueRequest(superuserReq)
394 "permissions on, superuser request",
398 expected := `^` + TestHash + `\+\d+ \d+\n` +
399 TestHash2 + `\+\d+ \d+\n\n$`
400 match, _ := regexp.MatchString(expected, response.Body.String())
403 "permissions on, superuser request: expected %s, got:\n%s",
404 expected, response.Body.String())
407 // superuser /index/prefix request
409 response = IssueRequest(superuserPrefixReq)
411 "permissions on, superuser request",
415 expected = `^` + TestHash + `\+\d+ \d+\n\n$`
416 match, _ = regexp.MatchString(expected, response.Body.String())
419 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
420 expected, response.Body.String())
423 // superuser /index/{no-such-prefix} request
425 response = IssueRequest(superuserNoSuchPrefixReq)
427 "permissions on, superuser request",
431 if "\n" != response.Body.String() {
432 t.Errorf("Expected empty response for %s. Found %s", superuserNoSuchPrefixReq.uri, response.Body.String())
435 // superuser /index/{invalid-prefix} request
436 // => StatusBadRequest
437 response = IssueRequest(superuserInvalidPrefixReq)
439 "permissions on, superuser request",
440 http.StatusBadRequest,
448 // With no token and with a non-data-manager token:
449 // * Delete existing block
450 // (test for 403 Forbidden, confirm block not deleted)
452 // With data manager token:
454 // * Delete existing block
455 // (test for 200 OK, response counts, confirm block deleted)
457 // * Delete nonexistent block
458 // (test for 200 OK, response counts)
462 // * Delete block on read-only and read-write volume
463 // (test for 200 OK, response with copies_deleted=1,
464 // copies_failed=1, confirm block deleted only on r/w volume)
466 // * Delete block on read-only volume only
467 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
468 // confirm block not deleted)
470 func TestDeleteHandler(t *testing.T) {
473 // Set up Keep volumes and populate them.
474 // Include multiple blocks on different volumes, and
475 // some metadata files (which should be omitted from index listings)
476 KeepVM = MakeTestVolumeManager(2)
479 vols := KeepVM.AllWritable()
480 vols[0].Put(TestHash, TestBlock)
482 // Explicitly set the BlobSignatureTTL to 0 for these
483 // tests, to ensure the MockVolume deletes the blocks
484 // even though they have just been created.
485 theConfig.BlobSignatureTTL = arvados.Duration(0)
487 var userToken = "NOT DATA MANAGER TOKEN"
488 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
490 theConfig.EnableDelete = true
492 unauthReq := &RequestTester{
497 userReq := &RequestTester{
503 superuserExistingBlockReq := &RequestTester{
506 apiToken: theConfig.systemAuthToken,
509 superuserNonexistentBlockReq := &RequestTester{
511 uri: "/" + TestHash2,
512 apiToken: theConfig.systemAuthToken,
515 // Unauthenticated request returns PermissionError.
516 var response *httptest.ResponseRecorder
517 response = IssueRequest(unauthReq)
519 "unauthenticated request",
520 PermissionError.HTTPCode,
523 // Authenticated non-admin request returns PermissionError.
524 response = IssueRequest(userReq)
526 "authenticated non-admin request",
527 PermissionError.HTTPCode,
530 // Authenticated admin request for nonexistent block.
531 type deletecounter struct {
532 Deleted int `json:"copies_deleted"`
533 Failed int `json:"copies_failed"`
535 var responseDc, expectedDc deletecounter
537 response = IssueRequest(superuserNonexistentBlockReq)
539 "data manager request, nonexistent block",
543 // Authenticated admin request for existing block while EnableDelete is false.
544 theConfig.EnableDelete = false
545 response = IssueRequest(superuserExistingBlockReq)
547 "authenticated request, existing block, method disabled",
548 MethodDisabledError.HTTPCode,
550 theConfig.EnableDelete = true
552 // Authenticated admin request for existing block.
553 response = IssueRequest(superuserExistingBlockReq)
555 "data manager request, existing block",
558 // Expect response {"copies_deleted":1,"copies_failed":0}
559 expectedDc = deletecounter{1, 0}
560 json.NewDecoder(response.Body).Decode(&responseDc)
561 if responseDc != expectedDc {
562 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
563 expectedDc, responseDc)
565 // Confirm the block has been deleted
566 buf := make([]byte, BlockSize)
567 _, err := vols[0].Get(TestHash, buf)
568 var blockDeleted = os.IsNotExist(err)
570 t.Error("superuserExistingBlockReq: block not deleted")
573 // A DELETE request on a block newer than BlobSignatureTTL
574 // should return success but leave the block on the volume.
575 vols[0].Put(TestHash, TestBlock)
576 theConfig.BlobSignatureTTL = arvados.Duration(time.Hour)
578 response = IssueRequest(superuserExistingBlockReq)
580 "data manager request, existing block",
583 // Expect response {"copies_deleted":1,"copies_failed":0}
584 expectedDc = deletecounter{1, 0}
585 json.NewDecoder(response.Body).Decode(&responseDc)
586 if responseDc != expectedDc {
587 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
588 expectedDc, responseDc)
590 // Confirm the block has NOT been deleted.
591 _, err = vols[0].Get(TestHash, buf)
593 t.Errorf("testing delete on new block: %s\n", err)
599 // Test handling of the PUT /pull statement.
601 // Cases tested: syntactically valid and invalid pull lists, from the
602 // data manager and from unprivileged users:
604 // 1. Valid pull list from an ordinary user
605 // (expected result: 401 Unauthorized)
607 // 2. Invalid pull request from an ordinary user
608 // (expected result: 401 Unauthorized)
610 // 3. Valid pull request from the data manager
611 // (expected result: 200 OK with request body "Received 3 pull
614 // 4. Invalid pull request from the data manager
615 // (expected result: 400 Bad Request)
617 // Test that in the end, the pull manager received a good pull list with
618 // the expected number of requests.
620 // TODO(twp): test concurrency: launch 100 goroutines to update the
621 // pull list simultaneously. Make sure that none of them return 400
622 // Bad Request and that pullq.GetList() returns a valid list.
624 func TestPullHandler(t *testing.T) {
627 var userToken = "USER TOKEN"
628 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
630 pullq = NewWorkQueue()
632 goodJSON := []byte(`[
634 "locator":"locator_with_two_servers",
641 "locator":"locator_with_no_servers",
646 "servers":["empty_locator"]
650 badJSON := []byte(`{ "key":"I'm a little teapot" }`)
652 type pullTest struct {
658 var testcases = []pullTest{
660 "Valid pull list from an ordinary user",
661 RequestTester{"/pull", userToken, "PUT", goodJSON},
662 http.StatusUnauthorized,
666 "Invalid pull request from an ordinary user",
667 RequestTester{"/pull", userToken, "PUT", badJSON},
668 http.StatusUnauthorized,
672 "Valid pull request from the data manager",
673 RequestTester{"/pull", theConfig.systemAuthToken, "PUT", goodJSON},
675 "Received 3 pull requests\n",
678 "Invalid pull request from the data manager",
679 RequestTester{"/pull", theConfig.systemAuthToken, "PUT", badJSON},
680 http.StatusBadRequest,
685 for _, tst := range testcases {
686 response := IssueRequest(&tst.req)
687 ExpectStatusCode(t, tst.name, tst.responseCode, response)
688 ExpectBody(t, tst.name, tst.responseBody, response)
691 // The Keep pull manager should have received one good list with 3
693 for i := 0; i < 3; i++ {
694 item := <-pullq.NextItem
695 if _, ok := item.(PullRequest); !ok {
696 t.Errorf("item %v could not be parsed as a PullRequest", item)
700 expectChannelEmpty(t, pullq.NextItem)
707 // Cases tested: syntactically valid and invalid trash lists, from the
708 // data manager and from unprivileged users:
710 // 1. Valid trash list from an ordinary user
711 // (expected result: 401 Unauthorized)
713 // 2. Invalid trash list from an ordinary user
714 // (expected result: 401 Unauthorized)
716 // 3. Valid trash list from the data manager
717 // (expected result: 200 OK with request body "Received 3 trash
720 // 4. Invalid trash list from the data manager
721 // (expected result: 400 Bad Request)
723 // Test that in the end, the trash collector received a good list
724 // trash list with the expected number of requests.
726 // TODO(twp): test concurrency: launch 100 goroutines to update the
727 // pull list simultaneously. Make sure that none of them return 400
728 // Bad Request and that replica.Dump() returns a valid list.
730 func TestTrashHandler(t *testing.T) {
733 var userToken = "USER TOKEN"
734 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
736 trashq = NewWorkQueue()
738 goodJSON := []byte(`[
741 "block_mtime":1409082153
745 "block_mtime":1409082153
749 "block_mtime":1409082153
753 badJSON := []byte(`I am not a valid JSON string`)
755 type trashTest struct {
762 var testcases = []trashTest{
764 "Valid trash list from an ordinary user",
765 RequestTester{"/trash", userToken, "PUT", goodJSON},
766 http.StatusUnauthorized,
770 "Invalid trash list from an ordinary user",
771 RequestTester{"/trash", userToken, "PUT", badJSON},
772 http.StatusUnauthorized,
776 "Valid trash list from the data manager",
777 RequestTester{"/trash", theConfig.systemAuthToken, "PUT", goodJSON},
779 "Received 3 trash requests\n",
782 "Invalid trash list from the data manager",
783 RequestTester{"/trash", theConfig.systemAuthToken, "PUT", badJSON},
784 http.StatusBadRequest,
789 for _, tst := range testcases {
790 response := IssueRequest(&tst.req)
791 ExpectStatusCode(t, tst.name, tst.responseCode, response)
792 ExpectBody(t, tst.name, tst.responseBody, response)
795 // The trash collector should have received one good list with 3
797 for i := 0; i < 3; i++ {
798 item := <-trashq.NextItem
799 if _, ok := item.(TrashRequest); !ok {
800 t.Errorf("item %v could not be parsed as a TrashRequest", item)
804 expectChannelEmpty(t, trashq.NextItem)
807 // ====================
809 // ====================
811 // IssueTestRequest executes an HTTP request described by rt, to a
812 // REST router. It returns the HTTP response to the request.
813 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
814 response := httptest.NewRecorder()
815 body := bytes.NewReader(rt.requestBody)
816 req, _ := http.NewRequest(rt.method, rt.uri, body)
817 if rt.apiToken != "" {
818 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
820 loggingRouter := MakeRESTRouter()
821 loggingRouter.ServeHTTP(response, req)
825 // ExpectStatusCode checks whether a response has the specified status code,
826 // and reports a test failure if not.
827 func ExpectStatusCode(
831 response *httptest.ResponseRecorder) {
832 if response.Code != expectedStatus {
833 t.Errorf("%s: expected status %d, got %+v",
834 testname, expectedStatus, response)
842 response *httptest.ResponseRecorder) {
843 if expectedBody != "" && response.Body.String() != expectedBody {
844 t.Errorf("%s: expected response body '%s', got %+v",
845 testname, expectedBody, response)
850 func TestPutNeedsOnlyOneBuffer(t *testing.T) {
852 KeepVM = MakeTestVolumeManager(1)
855 defer func(orig *bufferPool) {
858 bufs = newBufferPool(1, BlockSize)
860 ok := make(chan struct{})
862 for i := 0; i < 2; i++ {
863 response := IssueRequest(
867 requestBody: TestBlock,
870 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
877 case <-time.After(time.Second):
878 t.Fatal("PUT deadlocks with MaxBuffers==1")
882 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
884 func TestPutHandlerNoBufferleak(t *testing.T) {
887 // Prepare two test Keep volumes.
888 KeepVM = MakeTestVolumeManager(2)
891 ok := make(chan bool)
893 for i := 0; i < theConfig.MaxBuffers+1; i++ {
894 // Unauthenticated request, no server key
895 // => OK (unsigned response)
896 unsignedLocator := "/" + TestHash
897 response := IssueRequest(
900 uri: unsignedLocator,
901 requestBody: TestBlock,
904 "TestPutHandlerBufferleak", http.StatusOK, response)
906 "TestPutHandlerBufferleak",
907 TestHashPutResp, response)
912 case <-time.After(20 * time.Second):
913 // If the buffer pool leaks, the test goroutine hangs.
914 t.Fatal("test did not finish, assuming pool leaked")
919 type notifyingResponseRecorder struct {
920 *httptest.ResponseRecorder
924 func (r *notifyingResponseRecorder) CloseNotify() <-chan bool {
928 func TestGetHandlerClientDisconnect(t *testing.T) {
929 defer func(was bool) {
930 theConfig.RequireSignatures = was
931 }(theConfig.RequireSignatures)
932 theConfig.RequireSignatures = false
934 defer func(orig *bufferPool) {
937 bufs = newBufferPool(1, BlockSize)
938 defer bufs.Put(bufs.Get(BlockSize))
940 KeepVM = MakeTestVolumeManager(2)
943 if err := KeepVM.AllWritable()[0].Put(TestHash, TestBlock); err != nil {
947 resp := ¬ifyingResponseRecorder{
948 ResponseRecorder: httptest.NewRecorder(),
949 closer: make(chan bool, 1),
951 if _, ok := http.ResponseWriter(resp).(http.CloseNotifier); !ok {
952 t.Fatal("notifyingResponseRecorder is broken")
954 // If anyone asks, the client has disconnected.
957 ok := make(chan struct{})
959 req, _ := http.NewRequest("GET", fmt.Sprintf("/%s+%d", TestHash, len(TestBlock)), nil)
960 (&LoggingRESTRouter{MakeRESTRouter()}).ServeHTTP(resp, req)
965 case <-time.After(20 * time.Second):
966 t.Fatal("request took >20s, close notifier must be broken")
970 ExpectStatusCode(t, "client disconnect", http.StatusServiceUnavailable, resp.ResponseRecorder)
971 for i, v := range KeepVM.AllWritable() {
972 if calls := v.(*MockVolume).called["GET"]; calls != 0 {
973 t.Errorf("volume %d got %d calls, expected 0", i, calls)
978 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
980 func TestGetHandlerNoBufferLeak(t *testing.T) {
983 // Prepare two test Keep volumes. Our block is stored on the second volume.
984 KeepVM = MakeTestVolumeManager(2)
987 vols := KeepVM.AllWritable()
988 if err := vols[0].Put(TestHash, TestBlock); err != nil {
992 ok := make(chan bool)
994 for i := 0; i < theConfig.MaxBuffers+1; i++ {
995 // Unauthenticated request, unsigned locator
997 unsignedLocator := "/" + TestHash
998 response := IssueRequest(
1001 uri: unsignedLocator,
1004 "Unauthenticated request, unsigned locator", http.StatusOK, response)
1006 "Unauthenticated request, unsigned locator",
1013 case <-time.After(20 * time.Second):
1014 // If the buffer pool leaks, the test goroutine hangs.
1015 t.Fatal("test did not finish, assuming pool leaked")
1020 func TestPutReplicationHeader(t *testing.T) {
1023 KeepVM = MakeTestVolumeManager(2)
1024 defer KeepVM.Close()
1026 resp := IssueRequest(&RequestTester{
1028 uri: "/" + TestHash,
1029 requestBody: TestBlock,
1031 if r := resp.Header().Get("X-Keep-Replicas-Stored"); r != "1" {
1032 t.Errorf("Got X-Keep-Replicas-Stored: %q, expected %q", r, "1")
1036 func TestUntrashHandler(t *testing.T) {
1039 // Set up Keep volumes
1040 KeepVM = MakeTestVolumeManager(2)
1041 defer KeepVM.Close()
1042 vols := KeepVM.AllWritable()
1043 vols[0].Put(TestHash, TestBlock)
1045 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
1047 // unauthenticatedReq => UnauthorizedError
1048 unauthenticatedReq := &RequestTester{
1050 uri: "/untrash/" + TestHash,
1052 response := IssueRequest(unauthenticatedReq)
1054 "Unauthenticated request",
1055 UnauthorizedError.HTTPCode,
1058 // notDataManagerReq => UnauthorizedError
1059 notDataManagerReq := &RequestTester{
1061 uri: "/untrash/" + TestHash,
1062 apiToken: knownToken,
1065 response = IssueRequest(notDataManagerReq)
1067 "Non-datamanager token",
1068 UnauthorizedError.HTTPCode,
1071 // datamanagerWithBadHashReq => StatusBadRequest
1072 datamanagerWithBadHashReq := &RequestTester{
1074 uri: "/untrash/thisisnotalocator",
1075 apiToken: theConfig.systemAuthToken,
1077 response = IssueRequest(datamanagerWithBadHashReq)
1079 "Bad locator in untrash request",
1080 http.StatusBadRequest,
1083 // datamanagerWrongMethodReq => StatusBadRequest
1084 datamanagerWrongMethodReq := &RequestTester{
1086 uri: "/untrash/" + TestHash,
1087 apiToken: theConfig.systemAuthToken,
1089 response = IssueRequest(datamanagerWrongMethodReq)
1091 "Only PUT method is supported for untrash",
1092 http.StatusBadRequest,
1095 // datamanagerReq => StatusOK
1096 datamanagerReq := &RequestTester{
1098 uri: "/untrash/" + TestHash,
1099 apiToken: theConfig.systemAuthToken,
1101 response = IssueRequest(datamanagerReq)
1106 expected := "Successfully untrashed on: [MockVolume],[MockVolume]"
1107 if response.Body.String() != expected {
1109 "Untrash response mismatched: expected %s, got:\n%s",
1110 expected, response.Body.String())
1114 func TestUntrashHandlerWithNoWritableVolumes(t *testing.T) {
1117 // Set up readonly Keep volumes
1118 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
1119 vols[0].Readonly = true
1120 vols[1].Readonly = true
1121 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
1122 defer KeepVM.Close()
1124 theConfig.systemAuthToken = "DATA MANAGER TOKEN"
1126 // datamanagerReq => StatusOK
1127 datamanagerReq := &RequestTester{
1129 uri: "/untrash/" + TestHash,
1130 apiToken: theConfig.systemAuthToken,
1132 response := IssueRequest(datamanagerReq)
1134 "No writable volumes",
1135 http.StatusNotFound,