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.Volumes()
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 permission_ttl = time.Duration(300) * time.Second
60 unsigned_locator = "/" + TEST_HASH
61 valid_timestamp = time.Now().Add(permission_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)
91 received_xbs := response.Header().Get("X-Block-Size")
92 expected_xbs := fmt.Sprintf("%d", len(TEST_BLOCK))
93 if received_xbs != expected_xbs {
94 t.Errorf("expected X-Block-Size %s, got %s", expected_xbs, received_xbs)
99 enforce_permissions = true
101 // Authenticated request, signed locator
103 response = IssueRequest(&RequestTester{
106 api_token: known_token,
109 "Authenticated request, signed locator", http.StatusOK, response)
111 "Authenticated request, signed locator", string(TEST_BLOCK), response)
113 received_xbs = response.Header().Get("X-Block-Size")
114 expected_xbs = fmt.Sprintf("%d", len(TEST_BLOCK))
115 if received_xbs != expected_xbs {
116 t.Errorf("expected X-Block-Size %s, got %s", expected_xbs, received_xbs)
119 received_cl = response.Header().Get("Content-Length")
120 expected_cl = fmt.Sprintf("%d", len(TEST_BLOCK))
121 if received_cl != expected_cl {
122 t.Errorf("expected Content-Length %s, got %s", expected_cl, received_cl)
125 // Authenticated request, unsigned locator
126 // => PermissionError
127 response = IssueRequest(&RequestTester{
129 uri: unsigned_locator,
130 api_token: known_token,
132 ExpectStatusCode(t, "unsigned locator", PermissionError.HTTPCode, response)
134 // Unauthenticated request, signed locator
135 // => PermissionError
136 response = IssueRequest(&RequestTester{
141 "Unauthenticated request, signed locator",
142 PermissionError.HTTPCode, response)
144 // Authenticated request, expired locator
146 response = IssueRequest(&RequestTester{
148 uri: expired_locator,
149 api_token: known_token,
152 "Authenticated request, expired locator",
153 ExpiredError.HTTPCode, response)
156 // Test PutBlockHandler on the following situations:
158 // - with server key, authenticated request, unsigned locator
159 // - with server key, unauthenticated request, unsigned locator
161 func TestPutHandler(t *testing.T) {
164 // Prepare two test Keep volumes.
165 KeepVM = MakeTestVolumeManager(2)
171 // Unauthenticated request, no server key
172 // => OK (unsigned response)
173 unsigned_locator := "/" + TEST_HASH
174 response := IssueRequest(
177 uri: unsigned_locator,
178 request_body: TEST_BLOCK,
182 "Unauthenticated request, no server key", http.StatusOK, response)
184 "Unauthenticated request, no server key",
185 TEST_HASH_PUT_RESPONSE, response)
187 // ------------------
188 // With a server key.
190 PermissionSecret = []byte(known_key)
191 permission_ttl = time.Duration(300) * time.Second
193 // When a permission key is available, the locator returned
194 // from an authenticated PUT request will be signed.
196 // Authenticated PUT, signed locator
197 // => OK (signed response)
198 response = IssueRequest(
201 uri: unsigned_locator,
202 request_body: TEST_BLOCK,
203 api_token: known_token,
207 "Authenticated PUT, signed locator, with server key",
208 http.StatusOK, response)
209 response_locator := strings.TrimSpace(response.Body.String())
210 if !VerifySignature(response_locator, known_token) {
211 t.Errorf("Authenticated PUT, signed locator, with server key:\n"+
212 "response '%s' does not contain a valid signature",
216 // Unauthenticated PUT, unsigned locator
218 response = IssueRequest(
221 uri: unsigned_locator,
222 request_body: TEST_BLOCK,
226 "Unauthenticated PUT, unsigned locator, with server key",
227 http.StatusOK, response)
229 "Unauthenticated PUT, unsigned locator, with server key",
230 TEST_HASH_PUT_RESPONSE, response)
233 // Test /index requests:
234 // - unauthenticated /index request
235 // - unauthenticated /index/prefix request
236 // - authenticated /index request | non-superuser
237 // - authenticated /index/prefix request | non-superuser
238 // - authenticated /index request | superuser
239 // - authenticated /index/prefix request | superuser
241 // The only /index requests that should succeed are those issued by the
242 // superuser. They should pass regardless of the value of enforce_permissions.
244 func TestIndexHandler(t *testing.T) {
247 // Set up Keep volumes and populate them.
248 // Include multiple blocks on different volumes, and
249 // some metadata files (which should be omitted from index listings)
250 KeepVM = MakeTestVolumeManager(2)
253 vols := KeepVM.Volumes()
254 vols[0].Put(TEST_HASH, TEST_BLOCK)
255 vols[1].Put(TEST_HASH_2, TEST_BLOCK_2)
256 vols[0].Put(TEST_HASH+".meta", []byte("metadata"))
257 vols[1].Put(TEST_HASH_2+".meta", []byte("metadata"))
259 data_manager_token = "DATA MANAGER TOKEN"
261 unauthenticated_req := &RequestTester{
265 authenticated_req := &RequestTester{
268 api_token: known_token,
270 superuser_req := &RequestTester{
273 api_token: data_manager_token,
275 unauth_prefix_req := &RequestTester{
277 uri: "/index/" + TEST_HASH[0:3],
279 auth_prefix_req := &RequestTester{
281 uri: "/index/" + TEST_HASH[0:3],
282 api_token: known_token,
284 superuser_prefix_req := &RequestTester{
286 uri: "/index/" + TEST_HASH[0:3],
287 api_token: data_manager_token,
290 // -------------------------------------------------------------
291 // Only the superuser should be allowed to issue /index requests.
293 // ---------------------------
294 // enforce_permissions enabled
295 // This setting should not affect tests passing.
296 enforce_permissions = true
298 // unauthenticated /index request
299 // => UnauthorizedError
300 response := IssueRequest(unauthenticated_req)
302 "enforce_permissions on, unauthenticated request",
303 UnauthorizedError.HTTPCode,
306 // unauthenticated /index/prefix request
307 // => UnauthorizedError
308 response = IssueRequest(unauth_prefix_req)
310 "permissions on, unauthenticated /index/prefix request",
311 UnauthorizedError.HTTPCode,
314 // authenticated /index request, non-superuser
315 // => UnauthorizedError
316 response = IssueRequest(authenticated_req)
318 "permissions on, authenticated request, non-superuser",
319 UnauthorizedError.HTTPCode,
322 // authenticated /index/prefix request, non-superuser
323 // => UnauthorizedError
324 response = IssueRequest(auth_prefix_req)
326 "permissions on, authenticated /index/prefix request, non-superuser",
327 UnauthorizedError.HTTPCode,
330 // superuser /index request
332 response = IssueRequest(superuser_req)
334 "permissions on, superuser request",
338 // ----------------------------
339 // enforce_permissions disabled
340 // Valid Request should still pass.
341 enforce_permissions = false
343 // superuser /index request
345 response = IssueRequest(superuser_req)
347 "permissions on, superuser request",
351 expected := `^` + TEST_HASH + `\+\d+ \d+\n` +
352 TEST_HASH_2 + `\+\d+ \d+\n$`
353 match, _ := regexp.MatchString(expected, response.Body.String())
356 "permissions on, superuser request: expected %s, got:\n%s",
357 expected, response.Body.String())
360 // superuser /index/prefix request
362 response = IssueRequest(superuser_prefix_req)
364 "permissions on, superuser request",
368 expected = `^` + TEST_HASH + `\+\d+ \d+\n$`
369 match, _ = regexp.MatchString(expected, response.Body.String())
372 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
373 expected, response.Body.String())
381 // With no token and with a non-data-manager token:
382 // * Delete existing block
383 // (test for 403 Forbidden, confirm block not deleted)
385 // With data manager token:
387 // * Delete existing block
388 // (test for 200 OK, response counts, confirm block deleted)
390 // * Delete nonexistent block
391 // (test for 200 OK, response counts)
395 // * Delete block on read-only and read-write volume
396 // (test for 200 OK, response with copies_deleted=1,
397 // copies_failed=1, confirm block deleted only on r/w volume)
399 // * Delete block on read-only volume only
400 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
401 // confirm block not deleted)
403 func TestDeleteHandler(t *testing.T) {
406 // Set up Keep volumes and populate them.
407 // Include multiple blocks on different volumes, and
408 // some metadata files (which should be omitted from index listings)
409 KeepVM = MakeTestVolumeManager(2)
412 vols := KeepVM.Volumes()
413 vols[0].Put(TEST_HASH, TEST_BLOCK)
415 // Explicitly set the permission_ttl to 0 for these
416 // tests, to ensure the MockVolume deletes the blocks
417 // even though they have just been created.
418 permission_ttl = time.Duration(0)
420 var user_token = "NOT DATA MANAGER TOKEN"
421 data_manager_token = "DATA MANAGER TOKEN"
423 unauth_req := &RequestTester{
425 uri: "/" + TEST_HASH,
428 user_req := &RequestTester{
430 uri: "/" + TEST_HASH,
431 api_token: user_token,
434 superuser_existing_block_req := &RequestTester{
436 uri: "/" + TEST_HASH,
437 api_token: data_manager_token,
440 superuser_nonexistent_block_req := &RequestTester{
442 uri: "/" + TEST_HASH_2,
443 api_token: data_manager_token,
446 // Unauthenticated request returns PermissionError.
447 var response *httptest.ResponseRecorder
448 response = IssueRequest(unauth_req)
450 "unauthenticated request",
451 PermissionError.HTTPCode,
454 // Authenticated non-admin request returns PermissionError.
455 response = IssueRequest(user_req)
457 "authenticated non-admin request",
458 PermissionError.HTTPCode,
461 // Authenticated admin request for nonexistent block.
462 type deletecounter struct {
463 Deleted int `json:"copies_deleted"`
464 Failed int `json:"copies_failed"`
466 var response_dc, expected_dc deletecounter
468 response = IssueRequest(superuser_nonexistent_block_req)
470 "data manager request, nonexistent block",
474 // Authenticated admin request for existing block while never_delete is set.
476 response = IssueRequest(superuser_existing_block_req)
478 "authenticated request, existing block, method disabled",
479 MethodDisabledError.HTTPCode,
483 // Authenticated admin request for existing block.
484 response = IssueRequest(superuser_existing_block_req)
486 "data manager request, existing block",
489 // Expect response {"copies_deleted":1,"copies_failed":0}
490 expected_dc = deletecounter{1, 0}
491 json.NewDecoder(response.Body).Decode(&response_dc)
492 if response_dc != expected_dc {
493 t.Errorf("superuser_existing_block_req\nexpected: %+v\nreceived: %+v",
494 expected_dc, response_dc)
496 // Confirm the block has been deleted
497 _, err := vols[0].Get(TEST_HASH)
498 var block_deleted = os.IsNotExist(err)
500 t.Error("superuser_existing_block_req: block not deleted")
503 // A DELETE request on a block newer than permission_ttl should return
504 // success but leave the block on the volume.
505 vols[0].Put(TEST_HASH, TEST_BLOCK)
506 permission_ttl = time.Duration(1) * time.Hour
508 response = IssueRequest(superuser_existing_block_req)
510 "data manager request, existing block",
513 // Expect response {"copies_deleted":1,"copies_failed":0}
514 expected_dc = deletecounter{1, 0}
515 json.NewDecoder(response.Body).Decode(&response_dc)
516 if response_dc != expected_dc {
517 t.Errorf("superuser_existing_block_req\nexpected: %+v\nreceived: %+v",
518 expected_dc, response_dc)
520 // Confirm the block has NOT been deleted.
521 _, err = vols[0].Get(TEST_HASH)
523 t.Errorf("testing delete on new block: %s\n", err)
529 // Test handling of the PUT /pull statement.
531 // Cases tested: syntactically valid and invalid pull lists, from the
532 // data manager and from unprivileged users:
534 // 1. Valid pull list from an ordinary user
535 // (expected result: 401 Unauthorized)
537 // 2. Invalid pull request from an ordinary user
538 // (expected result: 401 Unauthorized)
540 // 3. Valid pull request from the data manager
541 // (expected result: 200 OK with request body "Received 3 pull
544 // 4. Invalid pull request from the data manager
545 // (expected result: 400 Bad Request)
547 // Test that in the end, the pull manager received a good pull list with
548 // the expected number of requests.
550 // TODO(twp): test concurrency: launch 100 goroutines to update the
551 // pull list simultaneously. Make sure that none of them return 400
552 // Bad Request and that pullq.GetList() returns a valid list.
554 func TestPullHandler(t *testing.T) {
557 var user_token = "USER TOKEN"
558 data_manager_token = "DATA MANAGER TOKEN"
560 good_json := []byte(`[
562 "locator":"locator_with_two_servers",
569 "locator":"locator_with_no_servers",
574 "servers":["empty_locator"]
578 bad_json := []byte(`{ "key":"I'm a little teapot" }`)
580 type pullTest struct {
586 var testcases = []pullTest{
588 "Valid pull list from an ordinary user",
589 RequestTester{"/pull", user_token, "PUT", good_json},
590 http.StatusUnauthorized,
594 "Invalid pull request from an ordinary user",
595 RequestTester{"/pull", user_token, "PUT", bad_json},
596 http.StatusUnauthorized,
600 "Valid pull request from the data manager",
601 RequestTester{"/pull", data_manager_token, "PUT", good_json},
603 "Received 3 pull requests\n",
606 "Invalid pull request from the data manager",
607 RequestTester{"/pull", data_manager_token, "PUT", bad_json},
608 http.StatusBadRequest,
613 for _, tst := range testcases {
614 response := IssueRequest(&tst.req)
615 ExpectStatusCode(t, tst.name, tst.response_code, response)
616 ExpectBody(t, tst.name, tst.response_body, response)
619 // The Keep pull manager should have received one good list with 3
621 for i := 0; i < 3; i++ {
622 item := <-pullq.NextItem
623 if _, ok := item.(PullRequest); !ok {
624 t.Errorf("item %v could not be parsed as a PullRequest", item)
628 expectChannelEmpty(t, pullq.NextItem)
635 // Cases tested: syntactically valid and invalid trash lists, from the
636 // data manager and from unprivileged users:
638 // 1. Valid trash list from an ordinary user
639 // (expected result: 401 Unauthorized)
641 // 2. Invalid trash list from an ordinary user
642 // (expected result: 401 Unauthorized)
644 // 3. Valid trash list from the data manager
645 // (expected result: 200 OK with request body "Received 3 trash
648 // 4. Invalid trash list from the data manager
649 // (expected result: 400 Bad Request)
651 // Test that in the end, the trash collector received a good list
652 // trash list with the expected number of requests.
654 // TODO(twp): test concurrency: launch 100 goroutines to update the
655 // pull list simultaneously. Make sure that none of them return 400
656 // Bad Request and that replica.Dump() returns a valid list.
658 func TestTrashHandler(t *testing.T) {
661 var user_token = "USER TOKEN"
662 data_manager_token = "DATA MANAGER TOKEN"
664 good_json := []byte(`[
667 "block_mtime":1409082153
671 "block_mtime":1409082153
675 "block_mtime":1409082153
679 bad_json := []byte(`I am not a valid JSON string`)
681 type trashTest struct {
688 var testcases = []trashTest{
690 "Valid trash list from an ordinary user",
691 RequestTester{"/trash", user_token, "PUT", good_json},
692 http.StatusUnauthorized,
696 "Invalid trash list from an ordinary user",
697 RequestTester{"/trash", user_token, "PUT", bad_json},
698 http.StatusUnauthorized,
702 "Valid trash list from the data manager",
703 RequestTester{"/trash", data_manager_token, "PUT", good_json},
705 "Received 3 trash requests\n",
708 "Invalid trash list from the data manager",
709 RequestTester{"/trash", data_manager_token, "PUT", bad_json},
710 http.StatusBadRequest,
715 for _, tst := range testcases {
716 response := IssueRequest(&tst.req)
717 ExpectStatusCode(t, tst.name, tst.response_code, response)
718 ExpectBody(t, tst.name, tst.response_body, response)
721 // The trash collector should have received one good list with 3
723 for i := 0; i < 3; i++ {
724 item := <-trashq.NextItem
725 if _, ok := item.(TrashRequest); !ok {
726 t.Errorf("item %v could not be parsed as a TrashRequest", item)
730 expectChannelEmpty(t, trashq.NextItem)
733 // ====================
735 // ====================
737 // IssueTestRequest executes an HTTP request described by rt, to a
738 // REST router. It returns the HTTP response to the request.
739 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
740 response := httptest.NewRecorder()
741 body := bytes.NewReader(rt.request_body)
742 req, _ := http.NewRequest(rt.method, rt.uri, body)
743 if rt.api_token != "" {
744 req.Header.Set("Authorization", "OAuth2 "+rt.api_token)
746 loggingRouter := MakeLoggingRESTRouter()
747 loggingRouter.ServeHTTP(response, req)
751 // ExpectStatusCode checks whether a response has the specified status code,
752 // and reports a test failure if not.
753 func ExpectStatusCode(
757 response *httptest.ResponseRecorder) {
758 if response.Code != expected_status {
759 t.Errorf("%s: expected status %s, got %+v",
760 testname, expected_status, response)
767 expected_body string,
768 response *httptest.ResponseRecorder) {
769 if response.Body.String() != expected_body {
770 t.Errorf("%s: expected response body '%s', got %+v",
771 testname, expected_body, response)