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(TEST_HASH, TEST_BLOCK); err != nil {
53 // Create locators for testing.
54 // Turn on permission settings so we can generate signed locators.
55 enforce_permissions = true
56 PermissionSecret = []byte(known_key)
57 blob_signature_ttl = 300 * time.Second
60 unsigned_locator = "/" + TEST_HASH
61 valid_timestamp = time.Now().Add(blob_signature_ttl)
62 expired_timestamp = time.Now().Add(-time.Hour)
63 signed_locator = "/" + SignLocator(TEST_HASH, known_token, valid_timestamp)
64 expired_locator = "/" + SignLocator(TEST_HASH, known_token, expired_timestamp)
68 // Test unauthenticated request with permissions off.
69 enforce_permissions = false
71 // Unauthenticated request, unsigned locator
73 response := IssueRequest(
76 uri: unsigned_locator,
79 "Unauthenticated request, unsigned locator", http.StatusOK, response)
81 "Unauthenticated request, unsigned locator",
85 received_cl := response.Header().Get("Content-Length")
86 expected_cl := fmt.Sprintf("%d", len(TEST_BLOCK))
87 if received_cl != expected_cl {
88 t.Errorf("expected Content-Length %s, got %s", expected_cl, received_cl)
93 enforce_permissions = true
95 // Authenticated request, signed locator
97 response = IssueRequest(&RequestTester{
100 api_token: known_token,
103 "Authenticated request, signed locator", http.StatusOK, response)
105 "Authenticated request, signed locator", string(TEST_BLOCK), response)
107 received_cl = response.Header().Get("Content-Length")
108 expected_cl = fmt.Sprintf("%d", len(TEST_BLOCK))
109 if received_cl != expected_cl {
110 t.Errorf("expected Content-Length %s, got %s", expected_cl, received_cl)
113 // Authenticated request, unsigned locator
114 // => PermissionError
115 response = IssueRequest(&RequestTester{
117 uri: unsigned_locator,
118 api_token: known_token,
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{
136 uri: expired_locator,
137 api_token: known_token,
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 unsigned_locator := "/" + TEST_HASH
162 response := IssueRequest(
165 uri: unsigned_locator,
166 request_body: TEST_BLOCK,
170 "Unauthenticated request, no server key", http.StatusOK, response)
172 "Unauthenticated request, no server key",
173 TEST_HASH_PUT_RESPONSE, response)
175 // ------------------
176 // With a server key.
178 PermissionSecret = []byte(known_key)
179 blob_signature_ttl = 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: unsigned_locator,
190 request_body: TEST_BLOCK,
191 api_token: known_token,
195 "Authenticated PUT, signed locator, with server key",
196 http.StatusOK, response)
197 response_locator := strings.TrimSpace(response.Body.String())
198 if VerifySignature(response_locator, known_token) != 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: unsigned_locator,
210 request_body: TEST_BLOCK,
214 "Unauthenticated PUT, unsigned locator, with server key",
215 http.StatusOK, response)
217 "Unauthenticated PUT, unsigned locator, with server key",
218 TEST_HASH_PUT_RESPONSE, response)
221 func TestPutAndDeleteSkipReadonlyVolumes(t *testing.T) {
223 data_manager_token = "fake-data-manager-token"
224 vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
225 vols[0].Readonly = true
226 KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
231 uri: "/" + TEST_HASH,
232 request_body: TEST_BLOCK,
238 uri: "/" + TEST_HASH,
239 request_body: TEST_BLOCK,
240 api_token: data_manager_token,
247 for _, e := range []expect{
256 if calls := vols[e.volnum].CallCount(e.method); calls != e.callcount {
257 t.Errorf("Got %d %s() on vol %d, expect %d", calls, e.method, e.volnum, e.callcount)
262 // Test /index requests:
263 // - unauthenticated /index request
264 // - unauthenticated /index/prefix request
265 // - authenticated /index request | non-superuser
266 // - authenticated /index/prefix request | non-superuser
267 // - authenticated /index request | superuser
268 // - authenticated /index/prefix request | superuser
270 // The only /index requests that should succeed are those issued by the
271 // superuser. They should pass regardless of the value of enforce_permissions.
273 func TestIndexHandler(t *testing.T) {
276 // Set up Keep volumes and populate them.
277 // Include multiple blocks on different volumes, and
278 // some metadata files (which should be omitted from index listings)
279 KeepVM = MakeTestVolumeManager(2)
282 vols := KeepVM.AllWritable()
283 vols[0].Put(TEST_HASH, TEST_BLOCK)
284 vols[1].Put(TEST_HASH_2, TEST_BLOCK_2)
285 vols[0].Put(TEST_HASH+".meta", []byte("metadata"))
286 vols[1].Put(TEST_HASH_2+".meta", []byte("metadata"))
288 data_manager_token = "DATA MANAGER TOKEN"
290 unauthenticated_req := &RequestTester{
294 authenticated_req := &RequestTester{
297 api_token: known_token,
299 superuser_req := &RequestTester{
302 api_token: data_manager_token,
304 unauth_prefix_req := &RequestTester{
306 uri: "/index/" + TEST_HASH[0:3],
308 auth_prefix_req := &RequestTester{
310 uri: "/index/" + TEST_HASH[0:3],
311 api_token: known_token,
313 superuser_prefix_req := &RequestTester{
315 uri: "/index/" + TEST_HASH[0:3],
316 api_token: data_manager_token,
319 // -------------------------------------------------------------
320 // Only the superuser should be allowed to issue /index requests.
322 // ---------------------------
323 // enforce_permissions enabled
324 // This setting should not affect tests passing.
325 enforce_permissions = true
327 // unauthenticated /index request
328 // => UnauthorizedError
329 response := IssueRequest(unauthenticated_req)
331 "enforce_permissions on, unauthenticated request",
332 UnauthorizedError.HTTPCode,
335 // unauthenticated /index/prefix request
336 // => UnauthorizedError
337 response = IssueRequest(unauth_prefix_req)
339 "permissions on, unauthenticated /index/prefix request",
340 UnauthorizedError.HTTPCode,
343 // authenticated /index request, non-superuser
344 // => UnauthorizedError
345 response = IssueRequest(authenticated_req)
347 "permissions on, authenticated request, non-superuser",
348 UnauthorizedError.HTTPCode,
351 // authenticated /index/prefix request, non-superuser
352 // => UnauthorizedError
353 response = IssueRequest(auth_prefix_req)
355 "permissions on, authenticated /index/prefix request, non-superuser",
356 UnauthorizedError.HTTPCode,
359 // superuser /index request
361 response = IssueRequest(superuser_req)
363 "permissions on, superuser request",
367 // ----------------------------
368 // enforce_permissions disabled
369 // Valid Request should still pass.
370 enforce_permissions = false
372 // superuser /index request
374 response = IssueRequest(superuser_req)
376 "permissions on, superuser request",
380 expected := `^` + TEST_HASH + `\+\d+ \d+\n` +
381 TEST_HASH_2 + `\+\d+ \d+\n\n$`
382 match, _ := regexp.MatchString(expected, response.Body.String())
385 "permissions on, superuser request: expected %s, got:\n%s",
386 expected, response.Body.String())
389 // superuser /index/prefix request
391 response = IssueRequest(superuser_prefix_req)
393 "permissions on, superuser request",
397 expected = `^` + TEST_HASH + `\+\d+ \d+\n\n$`
398 match, _ = regexp.MatchString(expected, response.Body.String())
401 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
402 expected, response.Body.String())
410 // With no token and with a non-data-manager token:
411 // * Delete existing block
412 // (test for 403 Forbidden, confirm block not deleted)
414 // With data manager token:
416 // * Delete existing block
417 // (test for 200 OK, response counts, confirm block deleted)
419 // * Delete nonexistent block
420 // (test for 200 OK, response counts)
424 // * Delete block on read-only and read-write volume
425 // (test for 200 OK, response with copies_deleted=1,
426 // copies_failed=1, confirm block deleted only on r/w volume)
428 // * Delete block on read-only volume only
429 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
430 // confirm block not deleted)
432 func TestDeleteHandler(t *testing.T) {
435 // Set up Keep volumes and populate them.
436 // Include multiple blocks on different volumes, and
437 // some metadata files (which should be omitted from index listings)
438 KeepVM = MakeTestVolumeManager(2)
441 vols := KeepVM.AllWritable()
442 vols[0].Put(TEST_HASH, TEST_BLOCK)
444 // Explicitly set the blob_signature_ttl to 0 for these
445 // tests, to ensure the MockVolume deletes the blocks
446 // even though they have just been created.
447 blob_signature_ttl = time.Duration(0)
449 var user_token = "NOT DATA MANAGER TOKEN"
450 data_manager_token = "DATA MANAGER TOKEN"
454 unauth_req := &RequestTester{
456 uri: "/" + TEST_HASH,
459 user_req := &RequestTester{
461 uri: "/" + TEST_HASH,
462 api_token: user_token,
465 superuser_existing_block_req := &RequestTester{
467 uri: "/" + TEST_HASH,
468 api_token: data_manager_token,
471 superuser_nonexistent_block_req := &RequestTester{
473 uri: "/" + TEST_HASH_2,
474 api_token: data_manager_token,
477 // Unauthenticated request returns PermissionError.
478 var response *httptest.ResponseRecorder
479 response = IssueRequest(unauth_req)
481 "unauthenticated request",
482 PermissionError.HTTPCode,
485 // Authenticated non-admin request returns PermissionError.
486 response = IssueRequest(user_req)
488 "authenticated non-admin request",
489 PermissionError.HTTPCode,
492 // Authenticated admin request for nonexistent block.
493 type deletecounter struct {
494 Deleted int `json:"copies_deleted"`
495 Failed int `json:"copies_failed"`
497 var response_dc, expected_dc deletecounter
499 response = IssueRequest(superuser_nonexistent_block_req)
501 "data manager request, nonexistent block",
505 // Authenticated admin request for existing block while never_delete is set.
507 response = IssueRequest(superuser_existing_block_req)
509 "authenticated request, existing block, method disabled",
510 MethodDisabledError.HTTPCode,
514 // Authenticated admin request for existing block.
515 response = IssueRequest(superuser_existing_block_req)
517 "data manager request, existing block",
520 // Expect response {"copies_deleted":1,"copies_failed":0}
521 expected_dc = deletecounter{1, 0}
522 json.NewDecoder(response.Body).Decode(&response_dc)
523 if response_dc != expected_dc {
524 t.Errorf("superuser_existing_block_req\nexpected: %+v\nreceived: %+v",
525 expected_dc, response_dc)
527 // Confirm the block has been deleted
528 _, err := vols[0].Get(TEST_HASH)
529 var block_deleted = os.IsNotExist(err)
531 t.Error("superuser_existing_block_req: block not deleted")
534 // A DELETE request on a block newer than blob_signature_ttl
535 // should return success but leave the block on the volume.
536 vols[0].Put(TEST_HASH, TEST_BLOCK)
537 blob_signature_ttl = time.Hour
539 response = IssueRequest(superuser_existing_block_req)
541 "data manager request, existing block",
544 // Expect response {"copies_deleted":1,"copies_failed":0}
545 expected_dc = deletecounter{1, 0}
546 json.NewDecoder(response.Body).Decode(&response_dc)
547 if response_dc != expected_dc {
548 t.Errorf("superuser_existing_block_req\nexpected: %+v\nreceived: %+v",
549 expected_dc, response_dc)
551 // Confirm the block has NOT been deleted.
552 _, err = vols[0].Get(TEST_HASH)
554 t.Errorf("testing delete on new block: %s\n", err)
560 // Test handling of the PUT /pull statement.
562 // Cases tested: syntactically valid and invalid pull lists, from the
563 // data manager and from unprivileged users:
565 // 1. Valid pull list from an ordinary user
566 // (expected result: 401 Unauthorized)
568 // 2. Invalid pull request from an ordinary user
569 // (expected result: 401 Unauthorized)
571 // 3. Valid pull request from the data manager
572 // (expected result: 200 OK with request body "Received 3 pull
575 // 4. Invalid pull request from the data manager
576 // (expected result: 400 Bad Request)
578 // Test that in the end, the pull manager received a good pull list with
579 // the expected number of requests.
581 // TODO(twp): test concurrency: launch 100 goroutines to update the
582 // pull list simultaneously. Make sure that none of them return 400
583 // Bad Request and that pullq.GetList() returns a valid list.
585 func TestPullHandler(t *testing.T) {
588 var user_token = "USER TOKEN"
589 data_manager_token = "DATA MANAGER TOKEN"
591 pullq = NewWorkQueue()
593 good_json := []byte(`[
595 "locator":"locator_with_two_servers",
602 "locator":"locator_with_no_servers",
607 "servers":["empty_locator"]
611 bad_json := []byte(`{ "key":"I'm a little teapot" }`)
613 type pullTest struct {
619 var testcases = []pullTest{
621 "Valid pull list from an ordinary user",
622 RequestTester{"/pull", user_token, "PUT", good_json},
623 http.StatusUnauthorized,
627 "Invalid pull request from an ordinary user",
628 RequestTester{"/pull", user_token, "PUT", bad_json},
629 http.StatusUnauthorized,
633 "Valid pull request from the data manager",
634 RequestTester{"/pull", data_manager_token, "PUT", good_json},
636 "Received 3 pull requests\n",
639 "Invalid pull request from the data manager",
640 RequestTester{"/pull", data_manager_token, "PUT", bad_json},
641 http.StatusBadRequest,
646 for _, tst := range testcases {
647 response := IssueRequest(&tst.req)
648 ExpectStatusCode(t, tst.name, tst.response_code, response)
649 ExpectBody(t, tst.name, tst.response_body, response)
652 // The Keep pull manager should have received one good list with 3
654 for i := 0; i < 3; i++ {
655 item := <-pullq.NextItem
656 if _, ok := item.(PullRequest); !ok {
657 t.Errorf("item %v could not be parsed as a PullRequest", item)
661 expectChannelEmpty(t, pullq.NextItem)
668 // Cases tested: syntactically valid and invalid trash lists, from the
669 // data manager and from unprivileged users:
671 // 1. Valid trash list from an ordinary user
672 // (expected result: 401 Unauthorized)
674 // 2. Invalid trash list from an ordinary user
675 // (expected result: 401 Unauthorized)
677 // 3. Valid trash list from the data manager
678 // (expected result: 200 OK with request body "Received 3 trash
681 // 4. Invalid trash list from the data manager
682 // (expected result: 400 Bad Request)
684 // Test that in the end, the trash collector received a good list
685 // trash list with the expected number of requests.
687 // TODO(twp): test concurrency: launch 100 goroutines to update the
688 // pull list simultaneously. Make sure that none of them return 400
689 // Bad Request and that replica.Dump() returns a valid list.
691 func TestTrashHandler(t *testing.T) {
694 var user_token = "USER TOKEN"
695 data_manager_token = "DATA MANAGER TOKEN"
697 trashq = NewWorkQueue()
699 good_json := []byte(`[
702 "block_mtime":1409082153
706 "block_mtime":1409082153
710 "block_mtime":1409082153
714 bad_json := []byte(`I am not a valid JSON string`)
716 type trashTest struct {
723 var testcases = []trashTest{
725 "Valid trash list from an ordinary user",
726 RequestTester{"/trash", user_token, "PUT", good_json},
727 http.StatusUnauthorized,
731 "Invalid trash list from an ordinary user",
732 RequestTester{"/trash", user_token, "PUT", bad_json},
733 http.StatusUnauthorized,
737 "Valid trash list from the data manager",
738 RequestTester{"/trash", data_manager_token, "PUT", good_json},
740 "Received 3 trash requests\n",
743 "Invalid trash list from the data manager",
744 RequestTester{"/trash", data_manager_token, "PUT", bad_json},
745 http.StatusBadRequest,
750 for _, tst := range testcases {
751 response := IssueRequest(&tst.req)
752 ExpectStatusCode(t, tst.name, tst.response_code, response)
753 ExpectBody(t, tst.name, tst.response_body, response)
756 // The trash collector should have received one good list with 3
758 for i := 0; i < 3; i++ {
759 item := <-trashq.NextItem
760 if _, ok := item.(TrashRequest); !ok {
761 t.Errorf("item %v could not be parsed as a TrashRequest", item)
765 expectChannelEmpty(t, trashq.NextItem)
768 // ====================
770 // ====================
772 // IssueTestRequest executes an HTTP request described by rt, to a
773 // REST router. It returns the HTTP response to the request.
774 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
775 response := httptest.NewRecorder()
776 body := bytes.NewReader(rt.request_body)
777 req, _ := http.NewRequest(rt.method, rt.uri, body)
778 if rt.api_token != "" {
779 req.Header.Set("Authorization", "OAuth2 "+rt.api_token)
781 loggingRouter := MakeLoggingRESTRouter()
782 loggingRouter.ServeHTTP(response, req)
786 // ExpectStatusCode checks whether a response has the specified status code,
787 // and reports a test failure if not.
788 func ExpectStatusCode(
792 response *httptest.ResponseRecorder) {
793 if response.Code != expected_status {
794 t.Errorf("%s: expected status %d, got %+v",
795 testname, expected_status, response)
802 expected_body string,
803 response *httptest.ResponseRecorder) {
804 if expected_body != "" && response.Body.String() != expected_body {
805 t.Errorf("%s: expected response body '%s', got %+v",
806 testname, expected_body, response)
810 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
812 func TestPutHandlerNoBufferleak(t *testing.T) {
815 // Prepare two test Keep volumes.
816 KeepVM = MakeTestVolumeManager(2)
819 ok := make(chan bool)
821 for i := 0; i < maxBuffers+1; i += 1 {
822 // Unauthenticated request, no server key
823 // => OK (unsigned response)
824 unsigned_locator := "/" + TEST_HASH
825 response := IssueRequest(
828 uri: unsigned_locator,
829 request_body: TEST_BLOCK,
832 "TestPutHandlerBufferleak", http.StatusOK, response)
834 "TestPutHandlerBufferleak",
835 TEST_HASH_PUT_RESPONSE, response)
840 case <-time.After(20 * time.Second):
841 // If the buffer pool leaks, the test goroutine hangs.
842 t.Fatal("test did not finish, assuming pool leaked")
847 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
849 func TestGetHandlerNoBufferleak(t *testing.T) {
852 // Prepare two test Keep volumes. Our block is stored on the second volume.
853 KeepVM = MakeTestVolumeManager(2)
856 vols := KeepVM.AllWritable()
857 if err := vols[0].Put(TEST_HASH, TEST_BLOCK); err != nil {
861 ok := make(chan bool)
863 for i := 0; i < maxBuffers+1; i += 1 {
864 // Unauthenticated request, unsigned locator
866 unsigned_locator := "/" + TEST_HASH
867 response := IssueRequest(
870 uri: unsigned_locator,
873 "Unauthenticated request, unsigned locator", http.StatusOK, response)
875 "Unauthenticated request, unsigned locator",
882 case <-time.After(20 * time.Second):
883 // If the buffer pool leaks, the test goroutine hangs.
884 t.Fatal("test did not finish, assuming pool leaked")