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",
84 received_xbs := response.Header().Get("X-Block-Size")
85 expected_xbs := fmt.Sprintf("%d", len(TEST_BLOCK))
86 if received_xbs != expected_xbs {
87 t.Errorf("expected X-Block-Size %s, got %s", expected_xbs, received_xbs)
92 enforce_permissions = true
94 // Authenticated request, signed locator
96 response = IssueRequest(&RequestTester{
99 api_token: known_token,
102 "Authenticated request, signed locator", http.StatusOK, response)
104 "Authenticated request, signed locator", string(TEST_BLOCK), response)
105 received_xbs = response.Header().Get("X-Block-Size")
106 expected_xbs = fmt.Sprintf("%d", len(TEST_BLOCK))
107 if received_xbs != expected_xbs {
108 t.Errorf("expected X-Block-Size %s, got %s", expected_xbs, received_xbs)
111 // Authenticated request, unsigned locator
112 // => PermissionError
113 response = IssueRequest(&RequestTester{
115 uri: unsigned_locator,
116 api_token: known_token,
118 ExpectStatusCode(t, "unsigned locator", PermissionError.HTTPCode, response)
120 // Unauthenticated request, signed locator
121 // => PermissionError
122 response = IssueRequest(&RequestTester{
127 "Unauthenticated request, signed locator",
128 PermissionError.HTTPCode, response)
130 // Authenticated request, expired locator
132 response = IssueRequest(&RequestTester{
134 uri: expired_locator,
135 api_token: known_token,
138 "Authenticated request, expired locator",
139 ExpiredError.HTTPCode, response)
142 // Test PutBlockHandler on the following situations:
144 // - with server key, authenticated request, unsigned locator
145 // - with server key, unauthenticated request, unsigned locator
147 func TestPutHandler(t *testing.T) {
150 // Prepare two test Keep volumes.
151 KeepVM = MakeTestVolumeManager(2)
157 // Unauthenticated request, no server key
158 // => OK (unsigned response)
159 unsigned_locator := "/" + TEST_HASH
160 response := IssueRequest(
163 uri: unsigned_locator,
164 request_body: TEST_BLOCK,
168 "Unauthenticated request, no server key", http.StatusOK, response)
170 "Unauthenticated request, no server key",
171 TEST_HASH_PUT_RESPONSE, response)
173 // ------------------
174 // With a server key.
176 PermissionSecret = []byte(known_key)
177 permission_ttl = time.Duration(300) * time.Second
179 // When a permission key is available, the locator returned
180 // from an authenticated PUT request will be signed.
182 // Authenticated PUT, signed locator
183 // => OK (signed response)
184 response = IssueRequest(
187 uri: unsigned_locator,
188 request_body: TEST_BLOCK,
189 api_token: known_token,
193 "Authenticated PUT, signed locator, with server key",
194 http.StatusOK, response)
195 response_locator := strings.TrimSpace(response.Body.String())
196 if !VerifySignature(response_locator, known_token) {
197 t.Errorf("Authenticated PUT, signed locator, with server key:\n"+
198 "response '%s' does not contain a valid signature",
202 // Unauthenticated PUT, unsigned locator
204 response = IssueRequest(
207 uri: unsigned_locator,
208 request_body: TEST_BLOCK,
212 "Unauthenticated PUT, unsigned locator, with server key",
213 http.StatusOK, response)
215 "Unauthenticated PUT, unsigned locator, with server key",
216 TEST_HASH_PUT_RESPONSE, response)
219 // Test /index requests:
220 // - unauthenticated /index request
221 // - unauthenticated /index/prefix request
222 // - authenticated /index request | non-superuser
223 // - authenticated /index/prefix request | non-superuser
224 // - authenticated /index request | superuser
225 // - authenticated /index/prefix request | superuser
227 // The only /index requests that should succeed are those issued by the
228 // superuser. They should pass regardless of the value of enforce_permissions.
230 func TestIndexHandler(t *testing.T) {
233 // Set up Keep volumes and populate them.
234 // Include multiple blocks on different volumes, and
235 // some metadata files (which should be omitted from index listings)
236 KeepVM = MakeTestVolumeManager(2)
239 vols := KeepVM.Volumes()
240 vols[0].Put(TEST_HASH, TEST_BLOCK)
241 vols[1].Put(TEST_HASH_2, TEST_BLOCK_2)
242 vols[0].Put(TEST_HASH+".meta", []byte("metadata"))
243 vols[1].Put(TEST_HASH_2+".meta", []byte("metadata"))
245 data_manager_token = "DATA MANAGER TOKEN"
247 unauthenticated_req := &RequestTester{
251 authenticated_req := &RequestTester{
254 api_token: known_token,
256 superuser_req := &RequestTester{
259 api_token: data_manager_token,
261 unauth_prefix_req := &RequestTester{
263 uri: "/index/" + TEST_HASH[0:3],
265 auth_prefix_req := &RequestTester{
267 uri: "/index/" + TEST_HASH[0:3],
268 api_token: known_token,
270 superuser_prefix_req := &RequestTester{
272 uri: "/index/" + TEST_HASH[0:3],
273 api_token: data_manager_token,
276 // -------------------------------------------------------------
277 // Only the superuser should be allowed to issue /index requests.
279 // ---------------------------
280 // enforce_permissions enabled
281 // This setting should not affect tests passing.
282 enforce_permissions = true
284 // unauthenticated /index request
285 // => UnauthorizedError
286 response := IssueRequest(unauthenticated_req)
288 "enforce_permissions on, unauthenticated request",
289 UnauthorizedError.HTTPCode,
292 // unauthenticated /index/prefix request
293 // => UnauthorizedError
294 response = IssueRequest(unauth_prefix_req)
296 "permissions on, unauthenticated /index/prefix request",
297 UnauthorizedError.HTTPCode,
300 // authenticated /index request, non-superuser
301 // => UnauthorizedError
302 response = IssueRequest(authenticated_req)
304 "permissions on, authenticated request, non-superuser",
305 UnauthorizedError.HTTPCode,
308 // authenticated /index/prefix request, non-superuser
309 // => UnauthorizedError
310 response = IssueRequest(auth_prefix_req)
312 "permissions on, authenticated /index/prefix request, non-superuser",
313 UnauthorizedError.HTTPCode,
316 // superuser /index request
318 response = IssueRequest(superuser_req)
320 "permissions on, superuser request",
324 // ----------------------------
325 // enforce_permissions disabled
326 // Valid Request should still pass.
327 enforce_permissions = false
329 // superuser /index request
331 response = IssueRequest(superuser_req)
333 "permissions on, superuser request",
337 expected := `^` + TEST_HASH + `\+\d+ \d+\n` +
338 TEST_HASH_2 + `\+\d+ \d+\n$`
339 match, _ := regexp.MatchString(expected, response.Body.String())
342 "permissions on, superuser request: expected %s, got:\n%s",
343 expected, response.Body.String())
346 // superuser /index/prefix request
348 response = IssueRequest(superuser_prefix_req)
350 "permissions on, superuser request",
354 expected = `^` + TEST_HASH + `\+\d+ \d+\n$`
355 match, _ = regexp.MatchString(expected, response.Body.String())
358 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
359 expected, response.Body.String())
367 // With no token and with a non-data-manager token:
368 // * Delete existing block
369 // (test for 403 Forbidden, confirm block not deleted)
371 // With data manager token:
373 // * Delete existing block
374 // (test for 200 OK, response counts, confirm block deleted)
376 // * Delete nonexistent block
377 // (test for 200 OK, response counts)
381 // * Delete block on read-only and read-write volume
382 // (test for 200 OK, response with copies_deleted=1,
383 // copies_failed=1, confirm block deleted only on r/w volume)
385 // * Delete block on read-only volume only
386 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
387 // confirm block not deleted)
389 func TestDeleteHandler(t *testing.T) {
392 // Set up Keep volumes and populate them.
393 // Include multiple blocks on different volumes, and
394 // some metadata files (which should be omitted from index listings)
395 KeepVM = MakeTestVolumeManager(2)
398 vols := KeepVM.Volumes()
399 vols[0].Put(TEST_HASH, TEST_BLOCK)
401 // Explicitly set the permission_ttl to 0 for these
402 // tests, to ensure the MockVolume deletes the blocks
403 // even though they have just been created.
404 permission_ttl = time.Duration(0)
406 var user_token = "NOT DATA MANAGER TOKEN"
407 data_manager_token = "DATA MANAGER TOKEN"
409 unauth_req := &RequestTester{
411 uri: "/" + TEST_HASH,
414 user_req := &RequestTester{
416 uri: "/" + TEST_HASH,
417 api_token: user_token,
420 superuser_existing_block_req := &RequestTester{
422 uri: "/" + TEST_HASH,
423 api_token: data_manager_token,
426 superuser_nonexistent_block_req := &RequestTester{
428 uri: "/" + TEST_HASH_2,
429 api_token: data_manager_token,
432 // Unauthenticated request returns PermissionError.
433 var response *httptest.ResponseRecorder
434 response = IssueRequest(unauth_req)
436 "unauthenticated request",
437 PermissionError.HTTPCode,
440 // Authenticated non-admin request returns PermissionError.
441 response = IssueRequest(user_req)
443 "authenticated non-admin request",
444 PermissionError.HTTPCode,
447 // Authenticated admin request for nonexistent block.
448 type deletecounter struct {
449 Deleted int `json:"copies_deleted"`
450 Failed int `json:"copies_failed"`
452 var response_dc, expected_dc deletecounter
454 response = IssueRequest(superuser_nonexistent_block_req)
456 "data manager request, nonexistent block",
460 // Authenticated admin request for existing block while never_delete is set.
462 response = IssueRequest(superuser_existing_block_req)
464 "authenticated request, existing block, method disabled",
465 MethodDisabledError.HTTPCode,
469 // Authenticated admin request for existing block.
470 response = IssueRequest(superuser_existing_block_req)
472 "data manager request, existing block",
475 // Expect response {"copies_deleted":1,"copies_failed":0}
476 expected_dc = deletecounter{1, 0}
477 json.NewDecoder(response.Body).Decode(&response_dc)
478 if response_dc != expected_dc {
479 t.Errorf("superuser_existing_block_req\nexpected: %+v\nreceived: %+v",
480 expected_dc, response_dc)
482 // Confirm the block has been deleted
483 _, err := vols[0].Get(TEST_HASH)
484 var block_deleted = os.IsNotExist(err)
486 t.Error("superuser_existing_block_req: block not deleted")
489 // A DELETE request on a block newer than permission_ttl should return
490 // success but leave the block on the volume.
491 vols[0].Put(TEST_HASH, TEST_BLOCK)
492 permission_ttl = time.Duration(1) * time.Hour
494 response = IssueRequest(superuser_existing_block_req)
496 "data manager request, existing block",
499 // Expect response {"copies_deleted":1,"copies_failed":0}
500 expected_dc = deletecounter{1, 0}
501 json.NewDecoder(response.Body).Decode(&response_dc)
502 if response_dc != expected_dc {
503 t.Errorf("superuser_existing_block_req\nexpected: %+v\nreceived: %+v",
504 expected_dc, response_dc)
506 // Confirm the block has NOT been deleted.
507 _, err = vols[0].Get(TEST_HASH)
509 t.Errorf("testing delete on new block: %s\n", err)
515 // Test handling of the PUT /pull statement.
517 // Cases tested: syntactically valid and invalid pull lists, from the
518 // data manager and from unprivileged users:
520 // 1. Valid pull list from an ordinary user
521 // (expected result: 401 Unauthorized)
523 // 2. Invalid pull request from an ordinary user
524 // (expected result: 401 Unauthorized)
526 // 3. Valid pull request from the data manager
527 // (expected result: 200 OK with request body "Received 3 pull
530 // 4. Invalid pull request from the data manager
531 // (expected result: 400 Bad Request)
533 // Test that in the end, the pull manager received a good pull list with
534 // the expected number of requests.
536 // TODO(twp): test concurrency: launch 100 goroutines to update the
537 // pull list simultaneously. Make sure that none of them return 400
538 // Bad Request and that pullq.GetList() returns a valid list.
540 func TestPullHandler(t *testing.T) {
543 var user_token = "USER TOKEN"
544 data_manager_token = "DATA MANAGER TOKEN"
546 good_json := []byte(`[
548 "locator":"locator_with_two_servers",
555 "locator":"locator_with_no_servers",
560 "servers":["empty_locator"]
564 bad_json := []byte(`{ "key":"I'm a little teapot" }`)
566 type pullTest struct {
572 var testcases = []pullTest{
574 "Valid pull list from an ordinary user",
575 RequestTester{"/pull", user_token, "PUT", good_json},
576 http.StatusUnauthorized,
580 "Invalid pull request from an ordinary user",
581 RequestTester{"/pull", user_token, "PUT", bad_json},
582 http.StatusUnauthorized,
586 "Valid pull request from the data manager",
587 RequestTester{"/pull", data_manager_token, "PUT", good_json},
589 "Received 3 pull requests\n",
592 "Invalid pull request from the data manager",
593 RequestTester{"/pull", data_manager_token, "PUT", bad_json},
594 http.StatusBadRequest,
599 for _, tst := range testcases {
600 response := IssueRequest(&tst.req)
601 ExpectStatusCode(t, tst.name, tst.response_code, response)
602 ExpectBody(t, tst.name, tst.response_body, response)
605 // The Keep pull manager should have received one good list with 3
607 for i := 0; i < 3; i++ {
608 item := <-pullq.NextItem
609 if _, ok := item.(PullRequest); !ok {
610 t.Errorf("item %v could not be parsed as a PullRequest", item)
614 expectChannelEmpty(t, pullq.NextItem)
621 // Cases tested: syntactically valid and invalid trash lists, from the
622 // data manager and from unprivileged users:
624 // 1. Valid trash list from an ordinary user
625 // (expected result: 401 Unauthorized)
627 // 2. Invalid trash list from an ordinary user
628 // (expected result: 401 Unauthorized)
630 // 3. Valid trash list from the data manager
631 // (expected result: 200 OK with request body "Received 3 trash
634 // 4. Invalid trash list from the data manager
635 // (expected result: 400 Bad Request)
637 // Test that in the end, the trash collector received a good list
638 // trash list with the expected number of requests.
640 // TODO(twp): test concurrency: launch 100 goroutines to update the
641 // pull list simultaneously. Make sure that none of them return 400
642 // Bad Request and that replica.Dump() returns a valid list.
644 func TestTrashHandler(t *testing.T) {
647 var user_token = "USER TOKEN"
648 data_manager_token = "DATA MANAGER TOKEN"
650 good_json := []byte(`[
653 "block_mtime":1409082153
657 "block_mtime":1409082153
661 "block_mtime":1409082153
665 bad_json := []byte(`I am not a valid JSON string`)
667 type trashTest struct {
674 var testcases = []trashTest{
676 "Valid trash list from an ordinary user",
677 RequestTester{"/trash", user_token, "PUT", good_json},
678 http.StatusUnauthorized,
682 "Invalid trash list from an ordinary user",
683 RequestTester{"/trash", user_token, "PUT", bad_json},
684 http.StatusUnauthorized,
688 "Valid trash list from the data manager",
689 RequestTester{"/trash", data_manager_token, "PUT", good_json},
691 "Received 3 trash requests\n",
694 "Invalid trash list from the data manager",
695 RequestTester{"/trash", data_manager_token, "PUT", bad_json},
696 http.StatusBadRequest,
701 for _, tst := range testcases {
702 response := IssueRequest(&tst.req)
703 ExpectStatusCode(t, tst.name, tst.response_code, response)
704 ExpectBody(t, tst.name, tst.response_body, response)
707 // The trash collector should have received one good list with 3
709 for i := 0; i < 3; i++ {
710 item := <-trashq.NextItem
711 if _, ok := item.(TrashRequest); !ok {
712 t.Errorf("item %v could not be parsed as a TrashRequest", item)
716 expectChannelEmpty(t, trashq.NextItem)
719 // ====================
721 // ====================
723 // IssueTestRequest executes an HTTP request described by rt, to a
724 // REST router. It returns the HTTP response to the request.
725 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
726 response := httptest.NewRecorder()
727 body := bytes.NewReader(rt.request_body)
728 req, _ := http.NewRequest(rt.method, rt.uri, body)
729 if rt.api_token != "" {
730 req.Header.Set("Authorization", "OAuth2 "+rt.api_token)
732 loggingRouter := MakeLoggingRESTRouter()
733 loggingRouter.ServeHTTP(response, req)
737 // ExpectStatusCode checks whether a response has the specified status code,
738 // and reports a test failure if not.
739 func ExpectStatusCode(
743 response *httptest.ResponseRecorder) {
744 if response.Code != expected_status {
745 t.Errorf("%s: expected status %s, got %+v",
746 testname, expected_status, response)
753 expected_body string,
754 response *httptest.ResponseRecorder) {
755 if response.Body.String() != expected_body {
756 t.Errorf("%s: expected response body '%s', got %+v",
757 testname, expected_body, response)