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,
325 // -------------------------------------------------------------
326 // Only the superuser should be allowed to issue /index requests.
328 // ---------------------------
329 // enforcePermissions enabled
330 // This setting should not affect tests passing.
331 enforcePermissions = true
333 // unauthenticated /index request
334 // => UnauthorizedError
335 response := IssueRequest(unauthenticatedReq)
337 "enforcePermissions on, unauthenticated request",
338 UnauthorizedError.HTTPCode,
341 // unauthenticated /index/prefix request
342 // => UnauthorizedError
343 response = IssueRequest(unauthPrefixReq)
345 "permissions on, unauthenticated /index/prefix request",
346 UnauthorizedError.HTTPCode,
349 // authenticated /index request, non-superuser
350 // => UnauthorizedError
351 response = IssueRequest(authenticatedReq)
353 "permissions on, authenticated request, non-superuser",
354 UnauthorizedError.HTTPCode,
357 // authenticated /index/prefix request, non-superuser
358 // => UnauthorizedError
359 response = IssueRequest(authPrefixReq)
361 "permissions on, authenticated /index/prefix request, non-superuser",
362 UnauthorizedError.HTTPCode,
365 // superuser /index request
367 response = IssueRequest(superuserReq)
369 "permissions on, superuser request",
373 // ----------------------------
374 // enforcePermissions disabled
375 // Valid Request should still pass.
376 enforcePermissions = false
378 // superuser /index request
380 response = IssueRequest(superuserReq)
382 "permissions on, superuser request",
386 expected := `^` + TestHash + `\+\d+ \d+\n` +
387 TestHash2 + `\+\d+ \d+\n\n$`
388 match, _ := regexp.MatchString(expected, response.Body.String())
391 "permissions on, superuser request: expected %s, got:\n%s",
392 expected, response.Body.String())
395 // superuser /index/prefix request
397 response = IssueRequest(superuserPrefixReq)
399 "permissions on, superuser request",
403 expected = `^` + TestHash + `\+\d+ \d+\n\n$`
404 match, _ = regexp.MatchString(expected, response.Body.String())
407 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
408 expected, response.Body.String())
416 // With no token and with a non-data-manager token:
417 // * Delete existing block
418 // (test for 403 Forbidden, confirm block not deleted)
420 // With data manager token:
422 // * Delete existing block
423 // (test for 200 OK, response counts, confirm block deleted)
425 // * Delete nonexistent block
426 // (test for 200 OK, response counts)
430 // * Delete block on read-only and read-write volume
431 // (test for 200 OK, response with copies_deleted=1,
432 // copies_failed=1, confirm block deleted only on r/w volume)
434 // * Delete block on read-only volume only
435 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
436 // confirm block not deleted)
438 func TestDeleteHandler(t *testing.T) {
441 // Set up Keep volumes and populate them.
442 // Include multiple blocks on different volumes, and
443 // some metadata files (which should be omitted from index listings)
444 KeepVM = MakeTestVolumeManager(2)
447 vols := KeepVM.AllWritable()
448 vols[0].Put(TestHash, TestBlock)
450 // Explicitly set the blobSignatureTTL to 0 for these
451 // tests, to ensure the MockVolume deletes the blocks
452 // even though they have just been created.
453 blobSignatureTTL = time.Duration(0)
455 var userToken = "NOT DATA MANAGER TOKEN"
456 dataManagerToken = "DATA MANAGER TOKEN"
460 unauthReq := &RequestTester{
465 userReq := &RequestTester{
471 superuserExistingBlockReq := &RequestTester{
474 apiToken: dataManagerToken,
477 superuserNonexistentBlockReq := &RequestTester{
479 uri: "/" + TestHash2,
480 apiToken: dataManagerToken,
483 // Unauthenticated request returns PermissionError.
484 var response *httptest.ResponseRecorder
485 response = IssueRequest(unauthReq)
487 "unauthenticated request",
488 PermissionError.HTTPCode,
491 // Authenticated non-admin request returns PermissionError.
492 response = IssueRequest(userReq)
494 "authenticated non-admin request",
495 PermissionError.HTTPCode,
498 // Authenticated admin request for nonexistent block.
499 type deletecounter struct {
500 Deleted int `json:"copies_deleted"`
501 Failed int `json:"copies_failed"`
503 var responseDc, expectedDc deletecounter
505 response = IssueRequest(superuserNonexistentBlockReq)
507 "data manager request, nonexistent block",
511 // Authenticated admin request for existing block while neverDelete is set.
513 response = IssueRequest(superuserExistingBlockReq)
515 "authenticated request, existing block, method disabled",
516 MethodDisabledError.HTTPCode,
520 // Authenticated admin request for existing block.
521 response = IssueRequest(superuserExistingBlockReq)
523 "data manager request, existing block",
526 // Expect response {"copies_deleted":1,"copies_failed":0}
527 expectedDc = deletecounter{1, 0}
528 json.NewDecoder(response.Body).Decode(&responseDc)
529 if responseDc != expectedDc {
530 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
531 expectedDc, responseDc)
533 // Confirm the block has been deleted
534 _, err := vols[0].Get(TestHash)
535 var blockDeleted = os.IsNotExist(err)
537 t.Error("superuserExistingBlockReq: block not deleted")
540 // A DELETE request on a block newer than blobSignatureTTL
541 // should return success but leave the block on the volume.
542 vols[0].Put(TestHash, TestBlock)
543 blobSignatureTTL = time.Hour
545 response = IssueRequest(superuserExistingBlockReq)
547 "data manager request, existing block",
550 // Expect response {"copies_deleted":1,"copies_failed":0}
551 expectedDc = deletecounter{1, 0}
552 json.NewDecoder(response.Body).Decode(&responseDc)
553 if responseDc != expectedDc {
554 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
555 expectedDc, responseDc)
557 // Confirm the block has NOT been deleted.
558 _, err = vols[0].Get(TestHash)
560 t.Errorf("testing delete on new block: %s\n", err)
566 // Test handling of the PUT /pull statement.
568 // Cases tested: syntactically valid and invalid pull lists, from the
569 // data manager and from unprivileged users:
571 // 1. Valid pull list from an ordinary user
572 // (expected result: 401 Unauthorized)
574 // 2. Invalid pull request from an ordinary user
575 // (expected result: 401 Unauthorized)
577 // 3. Valid pull request from the data manager
578 // (expected result: 200 OK with request body "Received 3 pull
581 // 4. Invalid pull request from the data manager
582 // (expected result: 400 Bad Request)
584 // Test that in the end, the pull manager received a good pull list with
585 // the expected number of requests.
587 // TODO(twp): test concurrency: launch 100 goroutines to update the
588 // pull list simultaneously. Make sure that none of them return 400
589 // Bad Request and that pullq.GetList() returns a valid list.
591 func TestPullHandler(t *testing.T) {
594 var userToken = "USER TOKEN"
595 dataManagerToken = "DATA MANAGER TOKEN"
597 pullq = NewWorkQueue()
599 goodJSON := []byte(`[
601 "locator":"locator_with_two_servers",
608 "locator":"locator_with_no_servers",
613 "servers":["empty_locator"]
617 badJSON := []byte(`{ "key":"I'm a little teapot" }`)
619 type pullTest struct {
625 var testcases = []pullTest{
627 "Valid pull list from an ordinary user",
628 RequestTester{"/pull", userToken, "PUT", goodJSON},
629 http.StatusUnauthorized,
633 "Invalid pull request from an ordinary user",
634 RequestTester{"/pull", userToken, "PUT", badJSON},
635 http.StatusUnauthorized,
639 "Valid pull request from the data manager",
640 RequestTester{"/pull", dataManagerToken, "PUT", goodJSON},
642 "Received 3 pull requests\n",
645 "Invalid pull request from the data manager",
646 RequestTester{"/pull", dataManagerToken, "PUT", badJSON},
647 http.StatusBadRequest,
652 for _, tst := range testcases {
653 response := IssueRequest(&tst.req)
654 ExpectStatusCode(t, tst.name, tst.responseCode, response)
655 ExpectBody(t, tst.name, tst.responseBody, response)
658 // The Keep pull manager should have received one good list with 3
660 for i := 0; i < 3; i++ {
661 item := <-pullq.NextItem
662 if _, ok := item.(PullRequest); !ok {
663 t.Errorf("item %v could not be parsed as a PullRequest", item)
667 expectChannelEmpty(t, pullq.NextItem)
674 // Cases tested: syntactically valid and invalid trash lists, from the
675 // data manager and from unprivileged users:
677 // 1. Valid trash list from an ordinary user
678 // (expected result: 401 Unauthorized)
680 // 2. Invalid trash list from an ordinary user
681 // (expected result: 401 Unauthorized)
683 // 3. Valid trash list from the data manager
684 // (expected result: 200 OK with request body "Received 3 trash
687 // 4. Invalid trash list from the data manager
688 // (expected result: 400 Bad Request)
690 // Test that in the end, the trash collector received a good list
691 // trash list with the expected number of requests.
693 // TODO(twp): test concurrency: launch 100 goroutines to update the
694 // pull list simultaneously. Make sure that none of them return 400
695 // Bad Request and that replica.Dump() returns a valid list.
697 func TestTrashHandler(t *testing.T) {
700 var userToken = "USER TOKEN"
701 dataManagerToken = "DATA MANAGER TOKEN"
703 trashq = NewWorkQueue()
705 goodJSON := []byte(`[
708 "block_mtime":1409082153
712 "block_mtime":1409082153
716 "block_mtime":1409082153
720 badJSON := []byte(`I am not a valid JSON string`)
722 type trashTest struct {
729 var testcases = []trashTest{
731 "Valid trash list from an ordinary user",
732 RequestTester{"/trash", userToken, "PUT", goodJSON},
733 http.StatusUnauthorized,
737 "Invalid trash list from an ordinary user",
738 RequestTester{"/trash", userToken, "PUT", badJSON},
739 http.StatusUnauthorized,
743 "Valid trash list from the data manager",
744 RequestTester{"/trash", dataManagerToken, "PUT", goodJSON},
746 "Received 3 trash requests\n",
749 "Invalid trash list from the data manager",
750 RequestTester{"/trash", dataManagerToken, "PUT", badJSON},
751 http.StatusBadRequest,
756 for _, tst := range testcases {
757 response := IssueRequest(&tst.req)
758 ExpectStatusCode(t, tst.name, tst.responseCode, response)
759 ExpectBody(t, tst.name, tst.responseBody, response)
762 // The trash collector should have received one good list with 3
764 for i := 0; i < 3; i++ {
765 item := <-trashq.NextItem
766 if _, ok := item.(TrashRequest); !ok {
767 t.Errorf("item %v could not be parsed as a TrashRequest", item)
771 expectChannelEmpty(t, trashq.NextItem)
774 // ====================
776 // ====================
778 // IssueTestRequest executes an HTTP request described by rt, to a
779 // REST router. It returns the HTTP response to the request.
780 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
781 response := httptest.NewRecorder()
782 body := bytes.NewReader(rt.requestBody)
783 req, _ := http.NewRequest(rt.method, rt.uri, body)
784 if rt.apiToken != "" {
785 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
787 loggingRouter := MakeLoggingRESTRouter()
788 loggingRouter.ServeHTTP(response, req)
792 // ExpectStatusCode checks whether a response has the specified status code,
793 // and reports a test failure if not.
794 func ExpectStatusCode(
798 response *httptest.ResponseRecorder) {
799 if response.Code != expectedStatus {
800 t.Errorf("%s: expected status %d, got %+v",
801 testname, expectedStatus, response)
809 response *httptest.ResponseRecorder) {
810 if expectedBody != "" && response.Body.String() != expectedBody {
811 t.Errorf("%s: expected response body '%s', got %+v",
812 testname, expectedBody, response)
817 func TestPutNeedsOnlyOneBuffer(t *testing.T) {
819 KeepVM = MakeTestVolumeManager(1)
822 defer func(orig *bufferPool) {
825 bufs = newBufferPool(1, BlockSize)
827 ok := make(chan struct{})
829 for i := 0; i < 2; i++ {
830 response := IssueRequest(
834 requestBody: TestBlock,
837 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
844 case <-time.After(time.Second):
845 t.Fatal("PUT deadlocks with maxBuffers==1")
849 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
851 func TestPutHandlerNoBufferleak(t *testing.T) {
854 // Prepare two test Keep volumes.
855 KeepVM = MakeTestVolumeManager(2)
858 ok := make(chan bool)
860 for i := 0; i < maxBuffers+1; i++ {
861 // Unauthenticated request, no server key
862 // => OK (unsigned response)
863 unsignedLocator := "/" + TestHash
864 response := IssueRequest(
867 uri: unsignedLocator,
868 requestBody: TestBlock,
871 "TestPutHandlerBufferleak", http.StatusOK, response)
873 "TestPutHandlerBufferleak",
874 TestHashPutResp, response)
879 case <-time.After(20 * time.Second):
880 // If the buffer pool leaks, the test goroutine hangs.
881 t.Fatal("test did not finish, assuming pool leaked")
886 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
888 func TestGetHandlerNoBufferleak(t *testing.T) {
891 // Prepare two test Keep volumes. Our block is stored on the second volume.
892 KeepVM = MakeTestVolumeManager(2)
895 vols := KeepVM.AllWritable()
896 if err := vols[0].Put(TestHash, TestBlock); err != nil {
900 ok := make(chan bool)
902 for i := 0; i < maxBuffers+1; i++ {
903 // Unauthenticated request, unsigned locator
905 unsignedLocator := "/" + TestHash
906 response := IssueRequest(
909 uri: unsignedLocator,
912 "Unauthenticated request, unsigned locator", http.StatusOK, response)
914 "Unauthenticated request, unsigned locator",
921 case <-time.After(20 * time.Second):
922 // If the buffer pool leaks, the test goroutine hangs.
923 t.Fatal("test did not finish, assuming pool leaked")