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.
16 "github.com/gorilla/mux"
24 "git.curoverse.com/arvados.git/services/keep"
27 // A RequestTester represents the parameters for an HTTP request to
28 // be issued on behalf of a unit test.
29 type RequestTester struct {
36 // Test GetBlockHandler on the following situations:
37 // - permissions off, unauthenticated request, unsigned locator
38 // - permissions on, authenticated request, signed locator
39 // - permissions on, authenticated request, unsigned locator
40 // - permissions on, unauthenticated request, signed locator
41 // - permissions on, authenticated request, expired locator
43 func TestGetHandler(t *testing.T) {
46 // Prepare two test Keep volumes. Our block is stored on the second volume.
47 KeepVM = MakeTestVolumeManager(2)
50 vols := KeepVM.Volumes()
51 if err := vols[0].Put(TEST_HASH, TEST_BLOCK); err != nil {
55 // Set up a REST router for testing the handlers.
56 rest := MakeRESTRouter()
58 // Create locators for testing.
59 // Turn on permission settings so we can generate signed locators.
60 enforce_permissions = true
61 PermissionSecret = []byte(known_key)
62 permission_ttl = time.Duration(300) * time.Second
65 unsigned_locator = "/" + TEST_HASH
66 valid_timestamp = time.Now().Add(permission_ttl)
67 expired_timestamp = time.Now().Add(-time.Hour)
68 signed_locator = "/" + SignLocator(TEST_HASH, known_token, valid_timestamp)
69 expired_locator = "/" + SignLocator(TEST_HASH, known_token, expired_timestamp)
73 // Test unauthenticated request with permissions off.
74 enforce_permissions = false
76 // Unauthenticated request, unsigned locator
78 response := IssueRequest(rest,
81 uri: unsigned_locator,
84 "Unauthenticated request, unsigned locator", http.StatusOK, response)
86 "Unauthenticated request, unsigned locator",
89 received_xbs := response.Header().Get("X-Block-Size")
90 expected_xbs := fmt.Sprintf("%d", len(TEST_BLOCK))
91 if received_xbs != expected_xbs {
92 t.Errorf("expected X-Block-Size %s, got %s", expected_xbs, received_xbs)
97 enforce_permissions = true
99 // Authenticated request, signed locator
101 response = IssueRequest(rest, &RequestTester{
104 api_token: known_token,
107 "Authenticated request, signed locator", http.StatusOK, response)
109 "Authenticated request, signed locator", string(TEST_BLOCK), response)
110 received_xbs = response.Header().Get("X-Block-Size")
111 expected_xbs = fmt.Sprintf("%d", len(TEST_BLOCK))
112 if received_xbs != expected_xbs {
113 t.Errorf("expected X-Block-Size %s, got %s", expected_xbs, received_xbs)
116 // Authenticated request, unsigned locator
117 // => PermissionError
118 response = IssueRequest(rest, &RequestTester{
120 uri: unsigned_locator,
121 api_token: known_token,
123 ExpectStatusCode(t, "unsigned locator", PermissionError.HTTPCode, response)
125 // Unauthenticated request, signed locator
126 // => PermissionError
127 response = IssueRequest(rest, &RequestTester{
132 "Unauthenticated request, signed locator",
133 PermissionError.HTTPCode, response)
135 // Authenticated request, expired locator
137 response = IssueRequest(rest, &RequestTester{
139 uri: expired_locator,
140 api_token: known_token,
143 "Authenticated request, expired locator",
144 ExpiredError.HTTPCode, response)
147 // Test PutBlockHandler on the following situations:
149 // - with server key, authenticated request, unsigned locator
150 // - with server key, unauthenticated request, unsigned locator
152 func TestPutHandler(t *testing.T) {
155 // Prepare two test Keep volumes.
156 KeepVM = MakeTestVolumeManager(2)
159 // Set up a REST router for testing the handlers.
160 rest := MakeRESTRouter()
165 // Unauthenticated request, no server key
166 // => OK (unsigned response)
167 unsigned_locator := "/" + TEST_HASH
168 response := IssueRequest(rest,
171 uri: unsigned_locator,
172 request_body: TEST_BLOCK,
176 "Unauthenticated request, no server key", http.StatusOK, response)
178 "Unauthenticated request, no server key",
179 TEST_HASH_PUT_RESPONSE, response)
181 // ------------------
182 // With a server key.
184 PermissionSecret = []byte(known_key)
185 permission_ttl = time.Duration(300) * time.Second
187 // When a permission key is available, the locator returned
188 // from an authenticated PUT request will be signed.
190 // Authenticated PUT, signed locator
191 // => OK (signed response)
192 response = IssueRequest(rest,
195 uri: unsigned_locator,
196 request_body: TEST_BLOCK,
197 api_token: known_token,
201 "Authenticated PUT, signed locator, with server key",
202 http.StatusOK, response)
203 response_locator := strings.TrimSpace(response.Body.String())
204 if !VerifySignature(response_locator, known_token) {
205 t.Errorf("Authenticated PUT, signed locator, with server key:\n"+
206 "response '%s' does not contain a valid signature",
210 // Unauthenticated PUT, unsigned locator
212 response = IssueRequest(rest,
215 uri: unsigned_locator,
216 request_body: TEST_BLOCK,
220 "Unauthenticated PUT, unsigned locator, with server key",
221 http.StatusOK, response)
223 "Unauthenticated PUT, unsigned locator, with server key",
224 TEST_HASH_PUT_RESPONSE, response)
227 // Test /index requests:
228 // - unauthenticated /index request
229 // - unauthenticated /index/prefix request
230 // - authenticated /index request | non-superuser
231 // - authenticated /index/prefix request | non-superuser
232 // - authenticated /index request | superuser
233 // - authenticated /index/prefix request | superuser
235 // The only /index requests that should succeed are those issued by the
236 // superuser. They should pass regardless of the value of enforce_permissions.
238 func TestIndexHandler(t *testing.T) {
241 // Set up Keep volumes and populate them.
242 // Include multiple blocks on different volumes, and
243 // some metadata files (which should be omitted from index listings)
244 KeepVM = MakeTestVolumeManager(2)
247 vols := KeepVM.Volumes()
248 vols[0].Put(TEST_HASH, TEST_BLOCK)
249 vols[1].Put(TEST_HASH_2, TEST_BLOCK_2)
250 vols[0].Put(TEST_HASH+".meta", []byte("metadata"))
251 vols[1].Put(TEST_HASH_2+".meta", []byte("metadata"))
253 // Set up a REST router for testing the handlers.
254 rest := MakeRESTRouter()
256 data_manager_token = "DATA MANAGER TOKEN"
258 unauthenticated_req := &RequestTester{
262 authenticated_req := &RequestTester{
265 api_token: known_token,
267 superuser_req := &RequestTester{
270 api_token: data_manager_token,
272 unauth_prefix_req := &RequestTester{
274 uri: "/index/" + TEST_HASH[0:3],
276 auth_prefix_req := &RequestTester{
278 uri: "/index/" + TEST_HASH[0:3],
279 api_token: known_token,
281 superuser_prefix_req := &RequestTester{
283 uri: "/index/" + TEST_HASH[0:3],
284 api_token: data_manager_token,
287 // -------------------------------------------------------------
288 // Only the superuser should be allowed to issue /index requests.
290 // ---------------------------
291 // enforce_permissions enabled
292 // This setting should not affect tests passing.
293 enforce_permissions = true
295 // unauthenticated /index request
296 // => UnauthorizedError
297 response := IssueRequest(rest, unauthenticated_req)
299 "enforce_permissions on, unauthenticated request",
300 UnauthorizedError.HTTPCode,
303 // unauthenticated /index/prefix request
304 // => UnauthorizedError
305 response = IssueRequest(rest, unauth_prefix_req)
307 "permissions on, unauthenticated /index/prefix request",
308 UnauthorizedError.HTTPCode,
311 // authenticated /index request, non-superuser
312 // => UnauthorizedError
313 response = IssueRequest(rest, authenticated_req)
315 "permissions on, authenticated request, non-superuser",
316 UnauthorizedError.HTTPCode,
319 // authenticated /index/prefix request, non-superuser
320 // => UnauthorizedError
321 response = IssueRequest(rest, auth_prefix_req)
323 "permissions on, authenticated /index/prefix request, non-superuser",
324 UnauthorizedError.HTTPCode,
327 // superuser /index request
329 response = IssueRequest(rest, superuser_req)
331 "permissions on, superuser request",
335 // ----------------------------
336 // enforce_permissions disabled
337 // Valid Request should still pass.
338 enforce_permissions = false
340 // superuser /index request
342 response = IssueRequest(rest, superuser_req)
344 "permissions on, superuser request",
350 expected := `^` + TEST_HASH + `\+\d+ \d+\n` +
351 TEST_HASH_2 + `\+\d+ \d+\n$`
352 match, _ := regexp.MatchString(expected, response.Body.String())
355 "permissions on, superuser request: expected %s, got:\n%s",
356 expected, response.Body.String())
359 // superuser /index/prefix request
361 response = IssueRequest(rest, superuser_prefix_req)
363 "permissions on, superuser request",
367 expected = `^` + TEST_HASH + `\+\d+ \d+\n$`
368 match, _ = regexp.MatchString(expected, response.Body.String())
371 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
372 expected, response.Body.String())
380 // With no token and with a non-data-manager token:
381 // * Delete existing block
382 // (test for 403 Forbidden, confirm block not deleted)
384 // With data manager token:
386 // * Delete existing block
387 // (test for 200 OK, response counts, confirm block deleted)
389 // * Delete nonexistent block
390 // (test for 200 OK, response counts)
394 // * Delete block on read-only and read-write volume
395 // (test for 200 OK, response with copies_deleted=1,
396 // copies_failed=1, confirm block deleted only on r/w volume)
398 // * Delete block on read-only volume only
399 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
400 // confirm block not deleted)
402 func TestDeleteHandler(t *testing.T) {
405 // Set up Keep volumes and populate them.
406 // Include multiple blocks on different volumes, and
407 // some metadata files (which should be omitted from index listings)
408 KeepVM = MakeTestVolumeManager(2)
411 vols := KeepVM.Volumes()
412 vols[0].Put(TEST_HASH, TEST_BLOCK)
414 // Explicitly set the permission_ttl to 0 for these
415 // tests, to ensure the MockVolume deletes the blocks
416 // even though they have just been created.
417 permission_ttl = time.Duration(0)
419 // Set up a REST router for testing the handlers.
420 rest := MakeRESTRouter()
422 var user_token = "NOT DATA MANAGER TOKEN"
423 data_manager_token = "DATA MANAGER TOKEN"
425 unauth_req := &RequestTester{
427 uri: "/" + TEST_HASH,
430 user_req := &RequestTester{
432 uri: "/" + TEST_HASH,
433 api_token: user_token,
436 superuser_existing_block_req := &RequestTester{
438 uri: "/" + TEST_HASH,
439 api_token: data_manager_token,
442 superuser_nonexistent_block_req := &RequestTester{
444 uri: "/" + TEST_HASH_2,
445 api_token: data_manager_token,
448 // Unauthenticated request returns PermissionError.
449 var response *httptest.ResponseRecorder
450 response = IssueRequest(rest, unauth_req)
452 "unauthenticated request",
453 PermissionError.HTTPCode,
456 // Authenticated non-admin request returns PermissionError.
457 response = IssueRequest(rest, user_req)
459 "authenticated non-admin request",
460 PermissionError.HTTPCode,
463 // Authenticated admin request for nonexistent block.
464 type deletecounter struct {
465 Deleted int `json:"copies_deleted"`
466 Failed int `json:"copies_failed"`
468 var response_dc, expected_dc deletecounter
470 response = IssueRequest(rest, superuser_nonexistent_block_req)
472 "data manager request, nonexistent block",
476 // Authenticated admin request for existing block while never_delete is set.
478 response = IssueRequest(rest, superuser_existing_block_req)
480 "authenticated request, existing block, method disabled",
481 MethodDisabledError.HTTPCode,
485 // Authenticated admin request for existing block.
486 response = IssueRequest(rest, superuser_existing_block_req)
488 "data manager request, existing block",
491 // Expect response {"copies_deleted":1,"copies_failed":0}
492 expected_dc = deletecounter{1, 0}
493 json.NewDecoder(response.Body).Decode(&response_dc)
494 if response_dc != expected_dc {
495 t.Errorf("superuser_existing_block_req\nexpected: %+v\nreceived: %+v",
496 expected_dc, response_dc)
498 // Confirm the block has been deleted
499 _, err := vols[0].Get(TEST_HASH)
500 var block_deleted = os.IsNotExist(err)
502 t.Error("superuser_existing_block_req: block not deleted")
505 // A DELETE request on a block newer than permission_ttl should return
506 // success but leave the block on the volume.
507 vols[0].Put(TEST_HASH, TEST_BLOCK)
508 permission_ttl = time.Duration(1) * time.Hour
510 response = IssueRequest(rest, superuser_existing_block_req)
512 "data manager request, existing block",
515 // Expect response {"copies_deleted":1,"copies_failed":0}
516 expected_dc = deletecounter{1, 0}
517 json.NewDecoder(response.Body).Decode(&response_dc)
518 if response_dc != expected_dc {
519 t.Errorf("superuser_existing_block_req\nexpected: %+v\nreceived: %+v",
520 expected_dc, response_dc)
522 // Confirm the block has NOT been deleted.
523 _, err = vols[0].Get(TEST_HASH)
525 t.Errorf("testing delete on new block: %s\n", err)
531 // Test handling of the PUT /pull statement.
533 // Cases tested: syntactically valid and invalid pull lists, from the
534 // data manager and from unprivileged users:
536 // 1. Valid pull list from an ordinary user
537 // (expected result: 401 Unauthorized)
539 // 2. Invalid pull request from an ordinary user
540 // (expected result: 401 Unauthorized)
542 // 3. Valid pull request from the data manager
543 // (expected result: 200 OK with request body "Received 3 pull
546 // 4. Invalid pull request from the data manager
547 // (expected result: 400 Bad Request)
549 // Test that in the end, the pull manager received a good pull list with
550 // the expected number of requests.
552 // TODO(twp): test concurrency: launch 100 goroutines to update the
553 // pull list simultaneously. Make sure that none of them return 400
554 // Bad Request and that pullq.GetList() returns a valid list.
556 func TestPullHandler(t *testing.T) {
559 // Set up a REST router for testing the handlers.
560 rest := MakeRESTRouter()
562 var user_token = "USER TOKEN"
563 data_manager_token = "DATA MANAGER TOKEN"
565 good_json := []byte(`[
567 "locator":"locator_with_two_servers",
574 "locator":"locator_with_no_servers",
579 "servers":["empty_locator"]
583 bad_json := []byte(`{ "key":"I'm a little teapot" }`)
585 type pullTest struct {
591 var testcases = []pullTest{
593 "Valid pull list from an ordinary user",
594 RequestTester{"/pull", user_token, "PUT", good_json},
595 http.StatusUnauthorized,
599 "Invalid pull request from an ordinary user",
600 RequestTester{"/pull", user_token, "PUT", bad_json},
601 http.StatusUnauthorized,
605 "Valid pull request from the data manager",
606 RequestTester{"/pull", data_manager_token, "PUT", good_json},
608 "Received 3 pull requests\n",
611 "Invalid pull request from the data manager",
612 RequestTester{"/pull", data_manager_token, "PUT", bad_json},
613 http.StatusBadRequest,
618 for _, tst := range testcases {
619 response := IssueRequest(rest, &tst.req)
620 ExpectStatusCode(t, tst.name, tst.response_code, response)
621 ExpectBody(t, tst.name, tst.response_body, response)
624 // The Keep pull manager should have received one good list with 3
626 for i := 0; i < 3; i++ {
627 item := <-pullq.NextItem
628 if _, ok := item.(PullRequest); !ok {
629 t.Errorf("item %v could not be parsed as a PullRequest", item)
633 expectChannelEmpty(t, pullq.NextItem)
640 // Cases tested: syntactically valid and invalid trash lists, from the
641 // data manager and from unprivileged users:
643 // 1. Valid trash list from an ordinary user
644 // (expected result: 401 Unauthorized)
646 // 2. Invalid trash list from an ordinary user
647 // (expected result: 401 Unauthorized)
649 // 3. Valid trash list from the data manager
650 // (expected result: 200 OK with request body "Received 3 trash
653 // 4. Invalid trash list from the data manager
654 // (expected result: 400 Bad Request)
656 // Test that in the end, the trash collector received a good list
657 // trash list with the expected number of requests.
659 // TODO(twp): test concurrency: launch 100 goroutines to update the
660 // pull list simultaneously. Make sure that none of them return 400
661 // Bad Request and that replica.Dump() returns a valid list.
663 func TestTrashHandler(t *testing.T) {
666 // Set up a REST router for testing the handlers.
667 rest := MakeRESTRouter()
669 var user_token = "USER TOKEN"
670 data_manager_token = "DATA MANAGER TOKEN"
672 good_json := []byte(`[
675 "block_mtime":1409082153
679 "block_mtime":1409082153
683 "block_mtime":1409082153
687 bad_json := []byte(`I am not a valid JSON string`)
689 type trashTest struct {
696 var testcases = []trashTest{
698 "Valid trash list from an ordinary user",
699 RequestTester{"/trash", user_token, "PUT", good_json},
700 http.StatusUnauthorized,
704 "Invalid trash list from an ordinary user",
705 RequestTester{"/trash", user_token, "PUT", bad_json},
706 http.StatusUnauthorized,
710 "Valid trash list from the data manager",
711 RequestTester{"/trash", data_manager_token, "PUT", good_json},
713 "Received 3 trash requests\n",
716 "Invalid trash list from the data manager",
717 RequestTester{"/trash", data_manager_token, "PUT", bad_json},
718 http.StatusBadRequest,
723 for _, tst := range testcases {
724 response := IssueRequest(rest, &tst.req)
725 ExpectStatusCode(t, tst.name, tst.response_code, response)
726 ExpectBody(t, tst.name, tst.response_body, response)
729 // The trash collector should have received one good list with 3
731 for i := 0; i < 3; i++ {
732 item := <-trashq.NextItem
733 if _, ok := item.(TrashRequest); !ok {
734 t.Errorf("item %v could not be parsed as a TrashRequest", item)
738 expectChannelEmpty(t, trashq.NextItem)
741 // ====================
743 // ====================
745 // IssueTestRequest executes an HTTP request described by rt, to a
746 // specified REST router. It returns the HTTP response to the request.
747 func IssueRequest(router *mux.Router, rt *RequestTester) *httptest.ResponseRecorder {
748 response := httptest.NewRecorder()
749 body := bytes.NewReader(rt.request_body)
750 req, _ := http.NewRequest(rt.method, rt.uri, body)
751 if rt.api_token != "" {
752 req.Header.Set("Authorization", "OAuth2 "+rt.api_token)
754 routerWrapper := keep_utils.MakeRESTRouterWrapper(router)
755 routerWrapper.ServeHTTP(response, req)
759 // ExpectStatusCode checks whether a response has the specified status code,
760 // and reports a test failure if not.
761 func ExpectStatusCode(
765 response *httptest.ResponseRecorder) {
766 if response.Code != expected_status {
767 t.Errorf("%s: expected status %s, got %+v",
768 testname, expected_status, response)
775 expected_body string,
776 response *httptest.ResponseRecorder) {
777 if response.Body.String() != expected_body {
778 t.Errorf("%s: expected response body '%s', got %+v",
779 testname, expected_body, response)