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 _, err := vols[0].Get(TestHash)
565 var blockDeleted = os.IsNotExist(err)
567 t.Error("superuserExistingBlockReq: block not deleted")
570 // A DELETE request on a block newer than blobSignatureTTL
571 // should return success but leave the block on the volume.
572 vols[0].Put(TestHash, TestBlock)
573 blobSignatureTTL = time.Hour
575 response = IssueRequest(superuserExistingBlockReq)
577 "data manager request, existing block",
580 // Expect response {"copies_deleted":1,"copies_failed":0}
581 expectedDc = deletecounter{1, 0}
582 json.NewDecoder(response.Body).Decode(&responseDc)
583 if responseDc != expectedDc {
584 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
585 expectedDc, responseDc)
587 // Confirm the block has NOT been deleted.
588 _, err = vols[0].Get(TestHash)
590 t.Errorf("testing delete on new block: %s\n", err)
596 // Test handling of the PUT /pull statement.
598 // Cases tested: syntactically valid and invalid pull lists, from the
599 // data manager and from unprivileged users:
601 // 1. Valid pull list from an ordinary user
602 // (expected result: 401 Unauthorized)
604 // 2. Invalid pull request from an ordinary user
605 // (expected result: 401 Unauthorized)
607 // 3. Valid pull request from the data manager
608 // (expected result: 200 OK with request body "Received 3 pull
611 // 4. Invalid pull request from the data manager
612 // (expected result: 400 Bad Request)
614 // Test that in the end, the pull manager received a good pull list with
615 // the expected number of requests.
617 // TODO(twp): test concurrency: launch 100 goroutines to update the
618 // pull list simultaneously. Make sure that none of them return 400
619 // Bad Request and that pullq.GetList() returns a valid list.
621 func TestPullHandler(t *testing.T) {
624 var userToken = "USER TOKEN"
625 dataManagerToken = "DATA MANAGER TOKEN"
627 pullq = NewWorkQueue()
629 goodJSON := []byte(`[
631 "locator":"locator_with_two_servers",
638 "locator":"locator_with_no_servers",
643 "servers":["empty_locator"]
647 badJSON := []byte(`{ "key":"I'm a little teapot" }`)
649 type pullTest struct {
655 var testcases = []pullTest{
657 "Valid pull list from an ordinary user",
658 RequestTester{"/pull", userToken, "PUT", goodJSON},
659 http.StatusUnauthorized,
663 "Invalid pull request from an ordinary user",
664 RequestTester{"/pull", userToken, "PUT", badJSON},
665 http.StatusUnauthorized,
669 "Valid pull request from the data manager",
670 RequestTester{"/pull", dataManagerToken, "PUT", goodJSON},
672 "Received 3 pull requests\n",
675 "Invalid pull request from the data manager",
676 RequestTester{"/pull", dataManagerToken, "PUT", badJSON},
677 http.StatusBadRequest,
682 for _, tst := range testcases {
683 response := IssueRequest(&tst.req)
684 ExpectStatusCode(t, tst.name, tst.responseCode, response)
685 ExpectBody(t, tst.name, tst.responseBody, response)
688 // The Keep pull manager should have received one good list with 3
690 for i := 0; i < 3; i++ {
691 item := <-pullq.NextItem
692 if _, ok := item.(PullRequest); !ok {
693 t.Errorf("item %v could not be parsed as a PullRequest", item)
697 expectChannelEmpty(t, pullq.NextItem)
704 // Cases tested: syntactically valid and invalid trash lists, from the
705 // data manager and from unprivileged users:
707 // 1. Valid trash list from an ordinary user
708 // (expected result: 401 Unauthorized)
710 // 2. Invalid trash list from an ordinary user
711 // (expected result: 401 Unauthorized)
713 // 3. Valid trash list from the data manager
714 // (expected result: 200 OK with request body "Received 3 trash
717 // 4. Invalid trash list from the data manager
718 // (expected result: 400 Bad Request)
720 // Test that in the end, the trash collector received a good list
721 // trash list with the expected number of requests.
723 // TODO(twp): test concurrency: launch 100 goroutines to update the
724 // pull list simultaneously. Make sure that none of them return 400
725 // Bad Request and that replica.Dump() returns a valid list.
727 func TestTrashHandler(t *testing.T) {
730 var userToken = "USER TOKEN"
731 dataManagerToken = "DATA MANAGER TOKEN"
733 trashq = NewWorkQueue()
735 goodJSON := []byte(`[
738 "block_mtime":1409082153
742 "block_mtime":1409082153
746 "block_mtime":1409082153
750 badJSON := []byte(`I am not a valid JSON string`)
752 type trashTest struct {
759 var testcases = []trashTest{
761 "Valid trash list from an ordinary user",
762 RequestTester{"/trash", userToken, "PUT", goodJSON},
763 http.StatusUnauthorized,
767 "Invalid trash list from an ordinary user",
768 RequestTester{"/trash", userToken, "PUT", badJSON},
769 http.StatusUnauthorized,
773 "Valid trash list from the data manager",
774 RequestTester{"/trash", dataManagerToken, "PUT", goodJSON},
776 "Received 3 trash requests\n",
779 "Invalid trash list from the data manager",
780 RequestTester{"/trash", dataManagerToken, "PUT", badJSON},
781 http.StatusBadRequest,
786 for _, tst := range testcases {
787 response := IssueRequest(&tst.req)
788 ExpectStatusCode(t, tst.name, tst.responseCode, response)
789 ExpectBody(t, tst.name, tst.responseBody, response)
792 // The trash collector should have received one good list with 3
794 for i := 0; i < 3; i++ {
795 item := <-trashq.NextItem
796 if _, ok := item.(TrashRequest); !ok {
797 t.Errorf("item %v could not be parsed as a TrashRequest", item)
801 expectChannelEmpty(t, trashq.NextItem)
804 // ====================
806 // ====================
808 // IssueTestRequest executes an HTTP request described by rt, to a
809 // REST router. It returns the HTTP response to the request.
810 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
811 response := httptest.NewRecorder()
812 body := bytes.NewReader(rt.requestBody)
813 req, _ := http.NewRequest(rt.method, rt.uri, body)
814 if rt.apiToken != "" {
815 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
817 loggingRouter := MakeLoggingRESTRouter()
818 loggingRouter.ServeHTTP(response, req)
822 // ExpectStatusCode checks whether a response has the specified status code,
823 // and reports a test failure if not.
824 func ExpectStatusCode(
828 response *httptest.ResponseRecorder) {
829 if response.Code != expectedStatus {
830 t.Errorf("%s: expected status %d, got %+v",
831 testname, expectedStatus, response)
839 response *httptest.ResponseRecorder) {
840 if expectedBody != "" && response.Body.String() != expectedBody {
841 t.Errorf("%s: expected response body '%s', got %+v",
842 testname, expectedBody, response)
847 func TestPutNeedsOnlyOneBuffer(t *testing.T) {
849 KeepVM = MakeTestVolumeManager(1)
852 defer func(orig *bufferPool) {
855 bufs = newBufferPool(1, BlockSize)
857 ok := make(chan struct{})
859 for i := 0; i < 2; i++ {
860 response := IssueRequest(
864 requestBody: TestBlock,
867 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
874 case <-time.After(time.Second):
875 t.Fatal("PUT deadlocks with maxBuffers==1")
879 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
881 func TestPutHandlerNoBufferleak(t *testing.T) {
884 // Prepare two test Keep volumes.
885 KeepVM = MakeTestVolumeManager(2)
888 ok := make(chan bool)
890 for i := 0; i < maxBuffers+1; i++ {
891 // Unauthenticated request, no server key
892 // => OK (unsigned response)
893 unsignedLocator := "/" + TestHash
894 response := IssueRequest(
897 uri: unsignedLocator,
898 requestBody: TestBlock,
901 "TestPutHandlerBufferleak", http.StatusOK, response)
903 "TestPutHandlerBufferleak",
904 TestHashPutResp, response)
909 case <-time.After(20 * time.Second):
910 // If the buffer pool leaks, the test goroutine hangs.
911 t.Fatal("test did not finish, assuming pool leaked")
916 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
918 func TestGetHandlerNoBufferleak(t *testing.T) {
921 // Prepare two test Keep volumes. Our block is stored on the second volume.
922 KeepVM = MakeTestVolumeManager(2)
925 vols := KeepVM.AllWritable()
926 if err := vols[0].Put(TestHash, TestBlock); err != nil {
930 ok := make(chan bool)
932 for i := 0; i < maxBuffers+1; i++ {
933 // Unauthenticated request, unsigned locator
935 unsignedLocator := "/" + TestHash
936 response := IssueRequest(
939 uri: unsignedLocator,
942 "Unauthenticated request, unsigned locator", http.StatusOK, response)
944 "Unauthenticated request, unsigned locator",
951 case <-time.After(20 * time.Second):
952 // If the buffer pool leaks, the test goroutine hangs.
953 t.Fatal("test did not finish, assuming pool leaked")
958 func TestPutReplicationHeader(t *testing.T) {
961 KeepVM = MakeTestVolumeManager(2)
964 resp := IssueRequest(&RequestTester{
967 requestBody: TestBlock,
969 if r := resp.Header().Get("X-Keep-Replicas-Stored"); r != "1" {
970 t.Errorf("Got X-Keep-Replicas-Stored: %q, expected %q", r, "1")