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.
25 // A RequestTester represents the parameters for an HTTP request to
26 // be issued on behalf of a unit test.
27 type RequestTester struct {
34 // Test GetBlockHandler on the following situations:
35 // - permissions off, unauthenticated request, unsigned locator
36 // - permissions on, authenticated request, signed locator
37 // - permissions on, authenticated request, unsigned locator
38 // - permissions on, unauthenticated request, signed locator
39 // - permissions on, authenticated request, expired locator
41 func TestGetHandler(t *testing.T) {
44 // Prepare two test Keep volumes. Our block is stored on the second volume.
45 KeepVM = MakeTestVolumeManager(2)
48 vols := KeepVM.AllWritable()
49 if err := vols[0].Put(TestHash, TestBlock); err != nil {
53 // Create locators for testing.
54 // Turn on permission settings so we can generate signed locators.
55 enforcePermissions = true
56 PermissionSecret = []byte(knownKey)
57 blobSignatureTTL = 300 * time.Second
60 unsignedLocator = "/" + TestHash
61 validTimestamp = time.Now().Add(blobSignatureTTL)
62 expiredTimestamp = time.Now().Add(-time.Hour)
63 signedLocator = "/" + SignLocator(TestHash, knownToken, validTimestamp)
64 expiredLocator = "/" + SignLocator(TestHash, knownToken, expiredTimestamp)
68 // Test unauthenticated request with permissions off.
69 enforcePermissions = false
71 // Unauthenticated request, unsigned locator
73 response := IssueRequest(
79 "Unauthenticated request, unsigned locator", http.StatusOK, response)
81 "Unauthenticated request, unsigned locator",
85 receivedLen := response.Header().Get("Content-Length")
86 expectedLen := fmt.Sprintf("%d", len(TestBlock))
87 if receivedLen != expectedLen {
88 t.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
93 enforcePermissions = true
95 // Authenticated request, signed locator
97 response = IssueRequest(&RequestTester{
100 apiToken: knownToken,
103 "Authenticated request, signed locator", http.StatusOK, response)
105 "Authenticated request, signed locator", string(TestBlock), response)
107 receivedLen = response.Header().Get("Content-Length")
108 expectedLen = fmt.Sprintf("%d", len(TestBlock))
109 if receivedLen != expectedLen {
110 t.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
113 // Authenticated request, unsigned locator
114 // => PermissionError
115 response = IssueRequest(&RequestTester{
117 uri: unsignedLocator,
118 apiToken: knownToken,
120 ExpectStatusCode(t, "unsigned locator", PermissionError.HTTPCode, response)
122 // Unauthenticated request, signed locator
123 // => PermissionError
124 response = IssueRequest(&RequestTester{
129 "Unauthenticated request, signed locator",
130 PermissionError.HTTPCode, response)
132 // Authenticated request, expired locator
134 response = IssueRequest(&RequestTester{
137 apiToken: knownToken,
140 "Authenticated request, expired locator",
141 ExpiredError.HTTPCode, response)
144 // Test PutBlockHandler on the following situations:
146 // - with server key, authenticated request, unsigned locator
147 // - with server key, unauthenticated request, unsigned locator
149 func TestPutHandler(t *testing.T) {
152 // Prepare two test Keep volumes.
153 KeepVM = MakeTestVolumeManager(2)
159 // Unauthenticated request, no server key
160 // => OK (unsigned response)
161 unsignedLocator := "/" + TestHash
162 response := IssueRequest(
165 uri: unsignedLocator,
166 requestBody: TestBlock,
170 "Unauthenticated request, no server key", http.StatusOK, response)
172 "Unauthenticated request, no server key",
173 TestHashPutResp, response)
175 // ------------------
176 // With a server key.
178 PermissionSecret = []byte(knownKey)
179 blobSignatureTTL = 300 * time.Second
181 // When a permission key is available, the locator returned
182 // from an authenticated PUT request will be signed.
184 // Authenticated PUT, signed locator
185 // => OK (signed response)
186 response = IssueRequest(
189 uri: unsignedLocator,
190 requestBody: TestBlock,
191 apiToken: knownToken,
195 "Authenticated PUT, signed locator, with server key",
196 http.StatusOK, response)
197 responseLocator := strings.TrimSpace(response.Body.String())
198 if VerifySignature(responseLocator, knownToken) != nil {
199 t.Errorf("Authenticated PUT, signed locator, with server key:\n"+
200 "response '%s' does not contain a valid signature",
204 // Unauthenticated PUT, unsigned locator
206 response = IssueRequest(
209 uri: unsignedLocator,
210 requestBody: TestBlock,
214 "Unauthenticated PUT, unsigned locator, with server key",
215 http.StatusOK, response)
217 "Unauthenticated PUT, unsigned locator, with server key",
218 TestHashPutResp, response)
221 func TestPutAndDeleteSkipReadonlyVolumes(t *testing.T) {
223 dataManagerToken = "fake-data-manager-token"
224 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
225 vols[0].Readonly = true
226 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
232 requestBody: TestBlock,
234 defer func(orig bool) {
242 requestBody: TestBlock,
243 apiToken: dataManagerToken,
250 for _, e := range []expect{
262 if calls := vols[e.volnum].CallCount(e.method); calls != e.callcount {
263 t.Errorf("Got %d %s() on vol %d, expect %d", calls, e.method, e.volnum, e.callcount)
268 // Test /index requests:
269 // - unauthenticated /index request
270 // - unauthenticated /index/prefix request
271 // - authenticated /index request | non-superuser
272 // - authenticated /index/prefix request | non-superuser
273 // - authenticated /index request | superuser
274 // - authenticated /index/prefix request | superuser
276 // The only /index requests that should succeed are those issued by the
277 // superuser. They should pass regardless of the value of enforcePermissions.
279 func TestIndexHandler(t *testing.T) {
282 // Set up Keep volumes and populate them.
283 // Include multiple blocks on different volumes, and
284 // some metadata files (which should be omitted from index listings)
285 KeepVM = MakeTestVolumeManager(2)
288 vols := KeepVM.AllWritable()
289 vols[0].Put(TestHash, TestBlock)
290 vols[1].Put(TestHash2, TestBlock2)
291 vols[0].Put(TestHash+".meta", []byte("metadata"))
292 vols[1].Put(TestHash2+".meta", []byte("metadata"))
294 dataManagerToken = "DATA MANAGER TOKEN"
296 unauthenticatedReq := &RequestTester{
300 authenticatedReq := &RequestTester{
303 apiToken: knownToken,
305 superuserReq := &RequestTester{
308 apiToken: dataManagerToken,
310 unauthPrefixReq := &RequestTester{
312 uri: "/index/" + TestHash[0:3],
314 authPrefixReq := &RequestTester{
316 uri: "/index/" + TestHash[0:3],
317 apiToken: knownToken,
319 superuserPrefixReq := &RequestTester{
321 uri: "/index/" + TestHash[0:3],
322 apiToken: dataManagerToken,
324 superuserNoSuchPrefixReq := &RequestTester{
327 apiToken: dataManagerToken,
329 superuserInvalidPrefixReq := &RequestTester{
332 apiToken: dataManagerToken,
335 // -------------------------------------------------------------
336 // Only the superuser should be allowed to issue /index requests.
338 // ---------------------------
339 // enforcePermissions enabled
340 // This setting should not affect tests passing.
341 enforcePermissions = true
343 // unauthenticated /index request
344 // => UnauthorizedError
345 response := IssueRequest(unauthenticatedReq)
347 "enforcePermissions on, unauthenticated request",
348 UnauthorizedError.HTTPCode,
351 // unauthenticated /index/prefix request
352 // => UnauthorizedError
353 response = IssueRequest(unauthPrefixReq)
355 "permissions on, unauthenticated /index/prefix request",
356 UnauthorizedError.HTTPCode,
359 // authenticated /index request, non-superuser
360 // => UnauthorizedError
361 response = IssueRequest(authenticatedReq)
363 "permissions on, authenticated request, non-superuser",
364 UnauthorizedError.HTTPCode,
367 // authenticated /index/prefix request, non-superuser
368 // => UnauthorizedError
369 response = IssueRequest(authPrefixReq)
371 "permissions on, authenticated /index/prefix request, non-superuser",
372 UnauthorizedError.HTTPCode,
375 // superuser /index request
377 response = IssueRequest(superuserReq)
379 "permissions on, superuser request",
383 // ----------------------------
384 // enforcePermissions disabled
385 // Valid Request should still pass.
386 enforcePermissions = false
388 // superuser /index request
390 response = IssueRequest(superuserReq)
392 "permissions on, superuser request",
396 expected := `^` + TestHash + `\+\d+ \d+\n` +
397 TestHash2 + `\+\d+ \d+\n\n$`
398 match, _ := regexp.MatchString(expected, response.Body.String())
401 "permissions on, superuser request: expected %s, got:\n%s",
402 expected, response.Body.String())
405 // superuser /index/prefix request
407 response = IssueRequest(superuserPrefixReq)
409 "permissions on, superuser request",
413 expected = `^` + TestHash + `\+\d+ \d+\n\n$`
414 match, _ = regexp.MatchString(expected, response.Body.String())
417 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
418 expected, response.Body.String())
421 // superuser /index/{no-such-prefix} request
423 response = IssueRequest(superuserNoSuchPrefixReq)
425 "permissions on, superuser request",
429 if "\n" != response.Body.String() {
430 t.Errorf("Expected empty response for %s. Found %s", superuserNoSuchPrefixReq.uri, response.Body.String())
433 // superuser /index/{invalid-prefix} request
434 // => StatusBadRequest
435 response = IssueRequest(superuserInvalidPrefixReq)
437 "permissions on, superuser request",
438 http.StatusBadRequest,
446 // With no token and with a non-data-manager token:
447 // * Delete existing block
448 // (test for 403 Forbidden, confirm block not deleted)
450 // With data manager token:
452 // * Delete existing block
453 // (test for 200 OK, response counts, confirm block deleted)
455 // * Delete nonexistent block
456 // (test for 200 OK, response counts)
460 // * Delete block on read-only and read-write volume
461 // (test for 200 OK, response with copies_deleted=1,
462 // copies_failed=1, confirm block deleted only on r/w volume)
464 // * Delete block on read-only volume only
465 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
466 // confirm block not deleted)
468 func TestDeleteHandler(t *testing.T) {
471 // Set up Keep volumes and populate them.
472 // Include multiple blocks on different volumes, and
473 // some metadata files (which should be omitted from index listings)
474 KeepVM = MakeTestVolumeManager(2)
477 vols := KeepVM.AllWritable()
478 vols[0].Put(TestHash, TestBlock)
480 // Explicitly set the blobSignatureTTL to 0 for these
481 // tests, to ensure the MockVolume deletes the blocks
482 // even though they have just been created.
483 blobSignatureTTL = time.Duration(0)
485 var userToken = "NOT DATA MANAGER TOKEN"
486 dataManagerToken = "DATA MANAGER TOKEN"
490 unauthReq := &RequestTester{
495 userReq := &RequestTester{
501 superuserExistingBlockReq := &RequestTester{
504 apiToken: dataManagerToken,
507 superuserNonexistentBlockReq := &RequestTester{
509 uri: "/" + TestHash2,
510 apiToken: dataManagerToken,
513 // Unauthenticated request returns PermissionError.
514 var response *httptest.ResponseRecorder
515 response = IssueRequest(unauthReq)
517 "unauthenticated request",
518 PermissionError.HTTPCode,
521 // Authenticated non-admin request returns PermissionError.
522 response = IssueRequest(userReq)
524 "authenticated non-admin request",
525 PermissionError.HTTPCode,
528 // Authenticated admin request for nonexistent block.
529 type deletecounter struct {
530 Deleted int `json:"copies_deleted"`
531 Failed int `json:"copies_failed"`
533 var responseDc, expectedDc deletecounter
535 response = IssueRequest(superuserNonexistentBlockReq)
537 "data manager request, nonexistent block",
541 // Authenticated admin request for existing block while neverDelete is set.
543 response = IssueRequest(superuserExistingBlockReq)
545 "authenticated request, existing block, method disabled",
546 MethodDisabledError.HTTPCode,
550 // Authenticated admin request for existing block.
551 response = IssueRequest(superuserExistingBlockReq)
553 "data manager request, existing block",
556 // Expect response {"copies_deleted":1,"copies_failed":0}
557 expectedDc = deletecounter{1, 0}
558 json.NewDecoder(response.Body).Decode(&responseDc)
559 if responseDc != expectedDc {
560 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
561 expectedDc, responseDc)
563 // Confirm the block has been deleted
564 buf := make([]byte, BlockSize)
565 _, err := vols[0].Get(TestHash, buf)
566 var blockDeleted = os.IsNotExist(err)
568 t.Error("superuserExistingBlockReq: block not deleted")
571 // A DELETE request on a block newer than blobSignatureTTL
572 // should return success but leave the block on the volume.
573 vols[0].Put(TestHash, TestBlock)
574 blobSignatureTTL = time.Hour
576 response = IssueRequest(superuserExistingBlockReq)
578 "data manager request, existing block",
581 // Expect response {"copies_deleted":1,"copies_failed":0}
582 expectedDc = deletecounter{1, 0}
583 json.NewDecoder(response.Body).Decode(&responseDc)
584 if responseDc != expectedDc {
585 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
586 expectedDc, responseDc)
588 // Confirm the block has NOT been deleted.
589 _, err = vols[0].Get(TestHash, buf)
591 t.Errorf("testing delete on new block: %s\n", err)
597 // Test handling of the PUT /pull statement.
599 // Cases tested: syntactically valid and invalid pull lists, from the
600 // data manager and from unprivileged users:
602 // 1. Valid pull list from an ordinary user
603 // (expected result: 401 Unauthorized)
605 // 2. Invalid pull request from an ordinary user
606 // (expected result: 401 Unauthorized)
608 // 3. Valid pull request from the data manager
609 // (expected result: 200 OK with request body "Received 3 pull
612 // 4. Invalid pull request from the data manager
613 // (expected result: 400 Bad Request)
615 // Test that in the end, the pull manager received a good pull list with
616 // the expected number of requests.
618 // TODO(twp): test concurrency: launch 100 goroutines to update the
619 // pull list simultaneously. Make sure that none of them return 400
620 // Bad Request and that pullq.GetList() returns a valid list.
622 func TestPullHandler(t *testing.T) {
625 var userToken = "USER TOKEN"
626 dataManagerToken = "DATA MANAGER TOKEN"
628 pullq = NewWorkQueue()
630 goodJSON := []byte(`[
632 "locator":"locator_with_two_servers",
639 "locator":"locator_with_no_servers",
644 "servers":["empty_locator"]
648 badJSON := []byte(`{ "key":"I'm a little teapot" }`)
650 type pullTest struct {
656 var testcases = []pullTest{
658 "Valid pull list from an ordinary user",
659 RequestTester{"/pull", userToken, "PUT", goodJSON},
660 http.StatusUnauthorized,
664 "Invalid pull request from an ordinary user",
665 RequestTester{"/pull", userToken, "PUT", badJSON},
666 http.StatusUnauthorized,
670 "Valid pull request from the data manager",
671 RequestTester{"/pull", dataManagerToken, "PUT", goodJSON},
673 "Received 3 pull requests\n",
676 "Invalid pull request from the data manager",
677 RequestTester{"/pull", dataManagerToken, "PUT", badJSON},
678 http.StatusBadRequest,
683 for _, tst := range testcases {
684 response := IssueRequest(&tst.req)
685 ExpectStatusCode(t, tst.name, tst.responseCode, response)
686 ExpectBody(t, tst.name, tst.responseBody, response)
689 // The Keep pull manager should have received one good list with 3
691 for i := 0; i < 3; i++ {
692 item := <-pullq.NextItem
693 if _, ok := item.(PullRequest); !ok {
694 t.Errorf("item %v could not be parsed as a PullRequest", item)
698 expectChannelEmpty(t, pullq.NextItem)
705 // Cases tested: syntactically valid and invalid trash lists, from the
706 // data manager and from unprivileged users:
708 // 1. Valid trash list from an ordinary user
709 // (expected result: 401 Unauthorized)
711 // 2. Invalid trash list from an ordinary user
712 // (expected result: 401 Unauthorized)
714 // 3. Valid trash list from the data manager
715 // (expected result: 200 OK with request body "Received 3 trash
718 // 4. Invalid trash list from the data manager
719 // (expected result: 400 Bad Request)
721 // Test that in the end, the trash collector received a good list
722 // trash list with the expected number of requests.
724 // TODO(twp): test concurrency: launch 100 goroutines to update the
725 // pull list simultaneously. Make sure that none of them return 400
726 // Bad Request and that replica.Dump() returns a valid list.
728 func TestTrashHandler(t *testing.T) {
731 var userToken = "USER TOKEN"
732 dataManagerToken = "DATA MANAGER TOKEN"
734 trashq = NewWorkQueue()
736 goodJSON := []byte(`[
739 "block_mtime":1409082153
743 "block_mtime":1409082153
747 "block_mtime":1409082153
751 badJSON := []byte(`I am not a valid JSON string`)
753 type trashTest struct {
760 var testcases = []trashTest{
762 "Valid trash list from an ordinary user",
763 RequestTester{"/trash", userToken, "PUT", goodJSON},
764 http.StatusUnauthorized,
768 "Invalid trash list from an ordinary user",
769 RequestTester{"/trash", userToken, "PUT", badJSON},
770 http.StatusUnauthorized,
774 "Valid trash list from the data manager",
775 RequestTester{"/trash", dataManagerToken, "PUT", goodJSON},
777 "Received 3 trash requests\n",
780 "Invalid trash list from the data manager",
781 RequestTester{"/trash", dataManagerToken, "PUT", badJSON},
782 http.StatusBadRequest,
787 for _, tst := range testcases {
788 response := IssueRequest(&tst.req)
789 ExpectStatusCode(t, tst.name, tst.responseCode, response)
790 ExpectBody(t, tst.name, tst.responseBody, response)
793 // The trash collector should have received one good list with 3
795 for i := 0; i < 3; i++ {
796 item := <-trashq.NextItem
797 if _, ok := item.(TrashRequest); !ok {
798 t.Errorf("item %v could not be parsed as a TrashRequest", item)
802 expectChannelEmpty(t, trashq.NextItem)
805 // ====================
807 // ====================
809 // IssueTestRequest executes an HTTP request described by rt, to a
810 // REST router. It returns the HTTP response to the request.
811 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
812 response := httptest.NewRecorder()
813 body := bytes.NewReader(rt.requestBody)
814 req, _ := http.NewRequest(rt.method, rt.uri, body)
815 if rt.apiToken != "" {
816 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
818 loggingRouter := MakeRESTRouter()
819 loggingRouter.ServeHTTP(response, req)
823 // ExpectStatusCode checks whether a response has the specified status code,
824 // and reports a test failure if not.
825 func ExpectStatusCode(
829 response *httptest.ResponseRecorder) {
830 if response.Code != expectedStatus {
831 t.Errorf("%s: expected status %d, got %+v",
832 testname, expectedStatus, response)
840 response *httptest.ResponseRecorder) {
841 if expectedBody != "" && response.Body.String() != expectedBody {
842 t.Errorf("%s: expected response body '%s', got %+v",
843 testname, expectedBody, response)
848 func TestPutNeedsOnlyOneBuffer(t *testing.T) {
850 KeepVM = MakeTestVolumeManager(1)
853 defer func(orig *bufferPool) {
856 bufs = newBufferPool(1, BlockSize)
858 ok := make(chan struct{})
860 for i := 0; i < 2; i++ {
861 response := IssueRequest(
865 requestBody: TestBlock,
868 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
875 case <-time.After(time.Second):
876 t.Fatal("PUT deadlocks with maxBuffers==1")
880 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
882 func TestPutHandlerNoBufferleak(t *testing.T) {
885 // Prepare two test Keep volumes.
886 KeepVM = MakeTestVolumeManager(2)
889 ok := make(chan bool)
891 for i := 0; i < maxBuffers+1; i++ {
892 // Unauthenticated request, no server key
893 // => OK (unsigned response)
894 unsignedLocator := "/" + TestHash
895 response := IssueRequest(
898 uri: unsignedLocator,
899 requestBody: TestBlock,
902 "TestPutHandlerBufferleak", http.StatusOK, response)
904 "TestPutHandlerBufferleak",
905 TestHashPutResp, response)
910 case <-time.After(20 * time.Second):
911 // If the buffer pool leaks, the test goroutine hangs.
912 t.Fatal("test did not finish, assuming pool leaked")
917 type notifyingResponseRecorder struct {
918 *httptest.ResponseRecorder
922 func (r *notifyingResponseRecorder) CloseNotify() <-chan bool {
926 func TestGetHandlerClientDisconnect(t *testing.T) {
927 defer func(was bool) {
928 enforcePermissions = was
929 }(enforcePermissions)
930 enforcePermissions = false
932 defer func(orig *bufferPool) {
935 bufs = newBufferPool(1, BlockSize)
936 defer bufs.Put(bufs.Get(BlockSize))
938 KeepVM = MakeTestVolumeManager(2)
941 if err := KeepVM.AllWritable()[0].Put(TestHash, TestBlock); err != nil {
945 resp := ¬ifyingResponseRecorder{
946 ResponseRecorder: httptest.NewRecorder(),
947 closer: make(chan bool, 1),
949 if _, ok := http.ResponseWriter(resp).(http.CloseNotifier); !ok {
950 t.Fatal("notifyingResponseRecorder is broken")
952 // If anyone asks, the client has disconnected.
955 ok := make(chan struct{})
957 req, _ := http.NewRequest("GET", fmt.Sprintf("/%s+%d", TestHash, len(TestBlock)), nil)
958 (&LoggingRESTRouter{MakeRESTRouter()}).ServeHTTP(resp, req)
963 case <-time.After(20 * time.Second):
964 t.Fatal("request took >20s, close notifier must be broken")
968 ExpectStatusCode(t, "client disconnect", http.StatusServiceUnavailable, resp.ResponseRecorder)
969 for i, v := range KeepVM.AllWritable() {
970 if calls := v.(*MockVolume).called["GET"]; calls != 0 {
971 t.Errorf("volume %d got %d calls, expected 0", i, calls)
976 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
978 func TestGetHandlerNoBufferleak(t *testing.T) {
981 // Prepare two test Keep volumes. Our block is stored on the second volume.
982 KeepVM = MakeTestVolumeManager(2)
985 vols := KeepVM.AllWritable()
986 if err := vols[0].Put(TestHash, TestBlock); err != nil {
990 ok := make(chan bool)
992 for i := 0; i < maxBuffers+1; i++ {
993 // Unauthenticated request, unsigned locator
995 unsignedLocator := "/" + TestHash
996 response := IssueRequest(
999 uri: unsignedLocator,
1002 "Unauthenticated request, unsigned locator", http.StatusOK, response)
1004 "Unauthenticated request, unsigned locator",
1011 case <-time.After(20 * time.Second):
1012 // If the buffer pool leaks, the test goroutine hangs.
1013 t.Fatal("test did not finish, assuming pool leaked")
1018 func TestPutReplicationHeader(t *testing.T) {
1021 KeepVM = MakeTestVolumeManager(2)
1022 defer KeepVM.Close()
1024 resp := IssueRequest(&RequestTester{
1026 uri: "/" + TestHash,
1027 requestBody: TestBlock,
1029 if r := resp.Header().Get("X-Keep-Replicas-Stored"); r != "1" {
1030 t.Errorf("Got X-Keep-Replicas-Stored: %q, expected %q", r, "1")
1034 func TestUntrashHandler(t *testing.T) {
1037 // Set up Keep volumes
1038 KeepVM = MakeTestVolumeManager(2)
1039 defer KeepVM.Close()
1040 vols := KeepVM.AllWritable()
1041 vols[0].Put(TestHash, TestBlock)
1043 dataManagerToken = "DATA MANAGER TOKEN"
1045 // unauthenticatedReq => UnauthorizedError
1046 unauthenticatedReq := &RequestTester{
1048 uri: "/untrash/" + TestHash,
1050 response := IssueRequest(unauthenticatedReq)
1052 "Unauthenticated request",
1053 UnauthorizedError.HTTPCode,
1056 // notDataManagerReq => UnauthorizedError
1057 notDataManagerReq := &RequestTester{
1059 uri: "/untrash/" + TestHash,
1060 apiToken: knownToken,
1063 response = IssueRequest(notDataManagerReq)
1065 "Non-datamanager token",
1066 UnauthorizedError.HTTPCode,
1069 // datamanagerWithBadHashReq => StatusBadRequest
1070 datamanagerWithBadHashReq := &RequestTester{
1072 uri: "/untrash/thisisnotalocator",
1073 apiToken: dataManagerToken,
1075 response = IssueRequest(datamanagerWithBadHashReq)
1077 "Bad locator in untrash request",
1078 http.StatusBadRequest,
1081 // datamanagerWrongMethodReq => StatusBadRequest
1082 datamanagerWrongMethodReq := &RequestTester{
1084 uri: "/untrash/" + TestHash,
1085 apiToken: dataManagerToken,
1087 response = IssueRequest(datamanagerWrongMethodReq)
1089 "Only PUT method is supported for untrash",
1090 http.StatusBadRequest,
1093 // datamanagerReq => StatusOK
1094 datamanagerReq := &RequestTester{
1096 uri: "/untrash/" + TestHash,
1097 apiToken: dataManagerToken,
1099 response = IssueRequest(datamanagerReq)
1104 expected := "Successfully untrashed on: [MockVolume],[MockVolume]"
1105 if response.Body.String() != expected {
1107 "Untrash response mismatched: expected %s, got:\n%s",
1108 expected, response.Body.String())
1112 func TestUntrashHandlerWithNoWritableVolumes(t *testing.T) {
1115 // Set up readonly Keep volumes
1116 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
1117 vols[0].Readonly = true
1118 vols[1].Readonly = true
1119 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
1120 defer KeepVM.Close()
1122 dataManagerToken = "DATA MANAGER TOKEN"
1124 // datamanagerReq => StatusOK
1125 datamanagerReq := &RequestTester{
1127 uri: "/untrash/" + TestHash,
1128 apiToken: dataManagerToken,
1130 response := IssueRequest(datamanagerReq)
1132 "No writable volumes",
1133 http.StatusNotFound,