1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 // Tests for Keep HTTP handlers:
11 // The HTTP handlers are responsible for enforcing permission policy,
12 // so these tests must exercise all possible permission permutations.
29 "git.arvados.org/arvados.git/lib/config"
30 "git.arvados.org/arvados.git/sdk/go/arvados"
31 "git.arvados.org/arvados.git/sdk/go/arvadostest"
32 "git.arvados.org/arvados.git/sdk/go/ctxlog"
33 "github.com/prometheus/client_golang/prometheus"
34 check "gopkg.in/check.v1"
37 var testServiceURL = func() arvados.URL {
38 return arvados.URL{Host: "localhost:12345", Scheme: "http"}
41 func testCluster(t TB) *arvados.Cluster {
42 cfg, err := config.NewLoader(bytes.NewBufferString("Clusters: {zzzzz: {}}"), ctxlog.TestLogger(t)).Load()
46 cluster, err := cfg.GetCluster("")
50 cluster.SystemRootToken = arvadostest.SystemRootToken
51 cluster.ManagementToken = arvadostest.ManagementToken
52 cluster.Collections.BlobSigning = false
56 var _ = check.Suite(&HandlerSuite{})
58 type HandlerSuite struct {
59 cluster *arvados.Cluster
63 func (s *HandlerSuite) SetUpTest(c *check.C) {
64 s.cluster = testCluster(c)
65 s.cluster.Volumes = map[string]arvados.Volume{
66 "zzzzz-nyw5e-000000000000000": {Replication: 1, Driver: "mock"},
67 "zzzzz-nyw5e-111111111111111": {Replication: 1, Driver: "mock"},
69 s.handler = &handler{}
72 // A RequestTester represents the parameters for an HTTP request to
73 // be issued on behalf of a unit test.
74 type RequestTester struct {
82 // Test GetBlockHandler on the following situations:
83 // - permissions off, unauthenticated request, unsigned locator
84 // - permissions on, authenticated request, signed locator
85 // - permissions on, authenticated request, unsigned locator
86 // - permissions on, unauthenticated request, signed locator
87 // - permissions on, authenticated request, expired locator
88 // - permissions on, authenticated request, signed locator, transient error from backend
90 func (s *HandlerSuite) TestGetHandler(c *check.C) {
91 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
93 vols := s.handler.volmgr.AllWritable()
94 err := vols[0].Put(context.Background(), TestHash, TestBlock)
95 c.Check(err, check.IsNil)
97 // Create locators for testing.
98 // Turn on permission settings so we can generate signed locators.
99 s.cluster.Collections.BlobSigning = true
100 s.cluster.Collections.BlobSigningKey = knownKey
101 s.cluster.Collections.BlobSigningTTL.Set("5m")
104 unsignedLocator = "/" + TestHash
105 validTimestamp = time.Now().Add(s.cluster.Collections.BlobSigningTTL.Duration())
106 expiredTimestamp = time.Now().Add(-time.Hour)
107 signedLocator = "/" + SignLocator(s.cluster, TestHash, knownToken, validTimestamp)
108 expiredLocator = "/" + SignLocator(s.cluster, TestHash, knownToken, expiredTimestamp)
112 // Test unauthenticated request with permissions off.
113 s.cluster.Collections.BlobSigning = false
115 // Unauthenticated request, unsigned locator
117 response := IssueRequest(s.handler,
120 uri: unsignedLocator,
123 "Unauthenticated request, unsigned locator", http.StatusOK, response)
125 "Unauthenticated request, unsigned locator",
129 receivedLen := response.Header().Get("Content-Length")
130 expectedLen := fmt.Sprintf("%d", len(TestBlock))
131 if receivedLen != expectedLen {
132 c.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
137 s.cluster.Collections.BlobSigning = true
139 // Authenticated request, signed locator
141 response = IssueRequest(s.handler, &RequestTester{
144 apiToken: knownToken,
147 "Authenticated request, signed locator", http.StatusOK, response)
149 "Authenticated request, signed locator", string(TestBlock), response)
151 receivedLen = response.Header().Get("Content-Length")
152 expectedLen = fmt.Sprintf("%d", len(TestBlock))
153 if receivedLen != expectedLen {
154 c.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
157 // Authenticated request, unsigned locator
158 // => PermissionError
159 response = IssueRequest(s.handler, &RequestTester{
161 uri: unsignedLocator,
162 apiToken: knownToken,
164 ExpectStatusCode(c, "unsigned locator", PermissionError.HTTPCode, response)
166 // Unauthenticated request, signed locator
167 // => PermissionError
168 response = IssueRequest(s.handler, &RequestTester{
173 "Unauthenticated request, signed locator",
174 PermissionError.HTTPCode, response)
176 // Authenticated request, expired locator
178 response = IssueRequest(s.handler, &RequestTester{
181 apiToken: knownToken,
184 "Authenticated request, expired locator",
185 ExpiredError.HTTPCode, response)
187 // Authenticated request, signed locator
188 // => 503 Server busy (transient error)
190 // Set up the block owning volume to respond with errors
191 vols[0].Volume.(*MockVolume).Bad = true
192 vols[0].Volume.(*MockVolume).BadVolumeError = VolumeBusyError
193 response = IssueRequest(s.handler, &RequestTester{
196 apiToken: knownToken,
198 // A transient error from one volume while the other doesn't find the block
199 // should make the service return a 503 so that clients can retry.
201 "Volume backend busy",
205 // Test PutBlockHandler on the following situations:
207 // - with server key, authenticated request, unsigned locator
208 // - with server key, unauthenticated request, unsigned locator
210 func (s *HandlerSuite) TestPutHandler(c *check.C) {
211 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
216 s.cluster.Collections.BlobSigningKey = ""
218 // Unauthenticated request, no server key
219 // => OK (unsigned response)
220 unsignedLocator := "/" + TestHash
221 response := IssueRequest(s.handler,
224 uri: unsignedLocator,
225 requestBody: TestBlock,
229 "Unauthenticated request, no server key", http.StatusOK, response)
231 "Unauthenticated request, no server key",
232 TestHashPutResp, response)
234 // ------------------
235 // With a server key.
237 s.cluster.Collections.BlobSigningKey = knownKey
238 s.cluster.Collections.BlobSigningTTL.Set("5m")
240 // When a permission key is available, the locator returned
241 // from an authenticated PUT request will be signed.
243 // Authenticated PUT, signed locator
244 // => OK (signed response)
245 response = IssueRequest(s.handler,
248 uri: unsignedLocator,
249 requestBody: TestBlock,
250 apiToken: knownToken,
254 "Authenticated PUT, signed locator, with server key",
255 http.StatusOK, response)
256 responseLocator := strings.TrimSpace(response.Body.String())
257 if VerifySignature(s.cluster, responseLocator, knownToken) != nil {
258 c.Errorf("Authenticated PUT, signed locator, with server key:\n"+
259 "response '%s' does not contain a valid signature",
263 // Unauthenticated PUT, unsigned locator
265 response = IssueRequest(s.handler,
268 uri: unsignedLocator,
269 requestBody: TestBlock,
273 "Unauthenticated PUT, unsigned locator, with server key",
274 http.StatusOK, response)
276 "Unauthenticated PUT, unsigned locator, with server key",
277 TestHashPutResp, response)
280 func (s *HandlerSuite) TestPutAndDeleteSkipReadonlyVolumes(c *check.C) {
281 s.cluster.Volumes["zzzzz-nyw5e-000000000000000"] = arvados.Volume{Driver: "mock", ReadOnly: true}
282 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
284 s.cluster.SystemRootToken = "fake-data-manager-token"
285 IssueRequest(s.handler,
289 requestBody: TestBlock,
292 s.cluster.Collections.BlobTrash = true
293 IssueRequest(s.handler,
297 requestBody: TestBlock,
298 apiToken: s.cluster.SystemRootToken,
305 for _, e := range []expect{
306 {"zzzzz-nyw5e-000000000000000", "Get", 0},
307 {"zzzzz-nyw5e-000000000000000", "Compare", 0},
308 {"zzzzz-nyw5e-000000000000000", "Touch", 0},
309 {"zzzzz-nyw5e-000000000000000", "Put", 0},
310 {"zzzzz-nyw5e-000000000000000", "Delete", 0},
311 {"zzzzz-nyw5e-111111111111111", "Get", 0},
312 {"zzzzz-nyw5e-111111111111111", "Compare", 1},
313 {"zzzzz-nyw5e-111111111111111", "Touch", 1},
314 {"zzzzz-nyw5e-111111111111111", "Put", 1},
315 {"zzzzz-nyw5e-111111111111111", "Delete", 1},
317 if calls := s.handler.volmgr.mountMap[e.volid].Volume.(*MockVolume).CallCount(e.method); calls != e.callcount {
318 c.Errorf("Got %d %s() on vol %s, expect %d", calls, e.method, e.volid, e.callcount)
323 func (s *HandlerSuite) TestReadsOrderedByStorageClassPriority(c *check.C) {
324 s.cluster.Volumes = map[string]arvados.Volume{
325 "zzzzz-nyw5e-111111111111111": {
328 StorageClasses: map[string]bool{"class1": true}},
329 "zzzzz-nyw5e-222222222222222": {
332 StorageClasses: map[string]bool{"class2": true, "class3": true}},
335 for _, trial := range []struct {
336 priority1 int // priority of class1, thus vol1
337 priority2 int // priority of class2
338 priority3 int // priority of class3 (vol2 priority will be max(priority2, priority3))
339 get1 int // expected number of "get" ops on vol1
340 get2 int // expected number of "get" ops on vol2
342 {100, 50, 50, 1, 0}, // class1 has higher priority => try vol1 first, no need to try vol2
343 {100, 100, 100, 1, 0}, // same priority, vol1 is first lexicographically => try vol1 first and succeed
344 {66, 99, 33, 1, 1}, // class2 has higher priority => try vol2 first, then try vol1
345 {66, 33, 99, 1, 1}, // class3 has highest priority => vol2 has highest => try vol2 first, then try vol1
348 s.cluster.StorageClasses = map[string]arvados.StorageClassConfig{
349 "class1": {Priority: trial.priority1},
350 "class2": {Priority: trial.priority2},
351 "class3": {Priority: trial.priority3},
353 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
354 IssueRequest(s.handler,
358 requestBody: TestBlock,
359 storageClasses: "class1",
361 IssueRequest(s.handler,
366 c.Check(s.handler.volmgr.mountMap["zzzzz-nyw5e-111111111111111"].Volume.(*MockVolume).CallCount("Get"), check.Equals, trial.get1)
367 c.Check(s.handler.volmgr.mountMap["zzzzz-nyw5e-222222222222222"].Volume.(*MockVolume).CallCount("Get"), check.Equals, trial.get2)
371 // Test TOUCH requests.
372 func (s *HandlerSuite) TestTouchHandler(c *check.C) {
373 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
374 vols := s.handler.volmgr.AllWritable()
375 vols[0].Put(context.Background(), TestHash, TestBlock)
376 vols[0].Volume.(*MockVolume).TouchWithDate(TestHash, time.Now().Add(-time.Hour))
377 afterPut := time.Now()
378 t, err := vols[0].Mtime(TestHash)
379 c.Assert(err, check.IsNil)
380 c.Assert(t.Before(afterPut), check.Equals, true)
383 "touch with no credentials",
384 http.StatusUnauthorized,
385 IssueRequest(s.handler, &RequestTester{
391 "touch with non-root credentials",
392 http.StatusUnauthorized,
393 IssueRequest(s.handler, &RequestTester{
396 apiToken: arvadostest.ActiveTokenV2,
400 "touch non-existent block",
402 IssueRequest(s.handler, &RequestTester{
404 uri: "/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
405 apiToken: s.cluster.SystemRootToken,
408 beforeTouch := time.Now()
412 IssueRequest(s.handler, &RequestTester{
415 apiToken: s.cluster.SystemRootToken,
417 t, err = vols[0].Mtime(TestHash)
418 c.Assert(err, check.IsNil)
419 c.Assert(t.After(beforeTouch), check.Equals, true)
422 // Test /index requests:
423 // - unauthenticated /index request
424 // - unauthenticated /index/prefix request
425 // - authenticated /index request | non-superuser
426 // - authenticated /index/prefix request | non-superuser
427 // - authenticated /index request | superuser
428 // - authenticated /index/prefix request | superuser
430 // The only /index requests that should succeed are those issued by the
431 // superuser. They should pass regardless of the value of BlobSigning.
433 func (s *HandlerSuite) TestIndexHandler(c *check.C) {
434 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
436 // Include multiple blocks on different volumes, and
437 // some metadata files (which should be omitted from index listings)
438 vols := s.handler.volmgr.AllWritable()
439 vols[0].Put(context.Background(), TestHash, TestBlock)
440 vols[1].Put(context.Background(), TestHash2, TestBlock2)
441 vols[0].Put(context.Background(), TestHash+".meta", []byte("metadata"))
442 vols[1].Put(context.Background(), TestHash2+".meta", []byte("metadata"))
444 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
446 unauthenticatedReq := &RequestTester{
450 authenticatedReq := &RequestTester{
453 apiToken: knownToken,
455 superuserReq := &RequestTester{
458 apiToken: s.cluster.SystemRootToken,
460 unauthPrefixReq := &RequestTester{
462 uri: "/index/" + TestHash[0:3],
464 authPrefixReq := &RequestTester{
466 uri: "/index/" + TestHash[0:3],
467 apiToken: knownToken,
469 superuserPrefixReq := &RequestTester{
471 uri: "/index/" + TestHash[0:3],
472 apiToken: s.cluster.SystemRootToken,
474 superuserNoSuchPrefixReq := &RequestTester{
477 apiToken: s.cluster.SystemRootToken,
479 superuserInvalidPrefixReq := &RequestTester{
482 apiToken: s.cluster.SystemRootToken,
485 // -------------------------------------------------------------
486 // Only the superuser should be allowed to issue /index requests.
488 // ---------------------------
489 // BlobSigning enabled
490 // This setting should not affect tests passing.
491 s.cluster.Collections.BlobSigning = true
493 // unauthenticated /index request
494 // => UnauthorizedError
495 response := IssueRequest(s.handler, unauthenticatedReq)
497 "permissions on, unauthenticated request",
498 UnauthorizedError.HTTPCode,
501 // unauthenticated /index/prefix request
502 // => UnauthorizedError
503 response = IssueRequest(s.handler, unauthPrefixReq)
505 "permissions on, unauthenticated /index/prefix request",
506 UnauthorizedError.HTTPCode,
509 // authenticated /index request, non-superuser
510 // => UnauthorizedError
511 response = IssueRequest(s.handler, authenticatedReq)
513 "permissions on, authenticated request, non-superuser",
514 UnauthorizedError.HTTPCode,
517 // authenticated /index/prefix request, non-superuser
518 // => UnauthorizedError
519 response = IssueRequest(s.handler, authPrefixReq)
521 "permissions on, authenticated /index/prefix request, non-superuser",
522 UnauthorizedError.HTTPCode,
525 // superuser /index request
527 response = IssueRequest(s.handler, superuserReq)
529 "permissions on, superuser request",
533 // ----------------------------
534 // BlobSigning disabled
535 // Valid Request should still pass.
536 s.cluster.Collections.BlobSigning = false
538 // superuser /index request
540 response = IssueRequest(s.handler, superuserReq)
542 "permissions on, superuser request",
546 expected := `^` + TestHash + `\+\d+ \d+\n` +
547 TestHash2 + `\+\d+ \d+\n\n$`
548 match, _ := regexp.MatchString(expected, response.Body.String())
551 "permissions on, superuser request: expected %s, got:\n%s",
552 expected, response.Body.String())
555 // superuser /index/prefix request
557 response = IssueRequest(s.handler, superuserPrefixReq)
559 "permissions on, superuser request",
563 expected = `^` + TestHash + `\+\d+ \d+\n\n$`
564 match, _ = regexp.MatchString(expected, response.Body.String())
567 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
568 expected, response.Body.String())
571 // superuser /index/{no-such-prefix} request
573 response = IssueRequest(s.handler, superuserNoSuchPrefixReq)
575 "permissions on, superuser request",
579 if "\n" != response.Body.String() {
580 c.Errorf("Expected empty response for %s. Found %s", superuserNoSuchPrefixReq.uri, response.Body.String())
583 // superuser /index/{invalid-prefix} request
584 // => StatusBadRequest
585 response = IssueRequest(s.handler, superuserInvalidPrefixReq)
587 "permissions on, superuser request",
588 http.StatusBadRequest,
596 // With no token and with a non-data-manager token:
597 // * Delete existing block
598 // (test for 403 Forbidden, confirm block not deleted)
600 // With data manager token:
602 // * Delete existing block
603 // (test for 200 OK, response counts, confirm block deleted)
605 // * Delete nonexistent block
606 // (test for 200 OK, response counts)
610 // * Delete block on read-only and read-write volume
611 // (test for 200 OK, response with copies_deleted=1,
612 // copies_failed=1, confirm block deleted only on r/w volume)
614 // * Delete block on read-only volume only
615 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
616 // confirm block not deleted)
618 func (s *HandlerSuite) TestDeleteHandler(c *check.C) {
619 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
621 vols := s.handler.volmgr.AllWritable()
622 vols[0].Put(context.Background(), TestHash, TestBlock)
624 // Explicitly set the BlobSigningTTL to 0 for these
625 // tests, to ensure the MockVolume deletes the blocks
626 // even though they have just been created.
627 s.cluster.Collections.BlobSigningTTL = arvados.Duration(0)
629 var userToken = "NOT DATA MANAGER TOKEN"
630 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
632 s.cluster.Collections.BlobTrash = true
634 unauthReq := &RequestTester{
639 userReq := &RequestTester{
645 superuserExistingBlockReq := &RequestTester{
648 apiToken: s.cluster.SystemRootToken,
651 superuserNonexistentBlockReq := &RequestTester{
653 uri: "/" + TestHash2,
654 apiToken: s.cluster.SystemRootToken,
657 // Unauthenticated request returns PermissionError.
658 var response *httptest.ResponseRecorder
659 response = IssueRequest(s.handler, unauthReq)
661 "unauthenticated request",
662 PermissionError.HTTPCode,
665 // Authenticated non-admin request returns PermissionError.
666 response = IssueRequest(s.handler, userReq)
668 "authenticated non-admin request",
669 PermissionError.HTTPCode,
672 // Authenticated admin request for nonexistent block.
673 type deletecounter struct {
674 Deleted int `json:"copies_deleted"`
675 Failed int `json:"copies_failed"`
677 var responseDc, expectedDc deletecounter
679 response = IssueRequest(s.handler, superuserNonexistentBlockReq)
681 "data manager request, nonexistent block",
685 // Authenticated admin request for existing block while BlobTrash is false.
686 s.cluster.Collections.BlobTrash = false
687 response = IssueRequest(s.handler, superuserExistingBlockReq)
689 "authenticated request, existing block, method disabled",
690 MethodDisabledError.HTTPCode,
692 s.cluster.Collections.BlobTrash = true
694 // Authenticated admin request for existing block.
695 response = IssueRequest(s.handler, superuserExistingBlockReq)
697 "data manager request, existing block",
700 // Expect response {"copies_deleted":1,"copies_failed":0}
701 expectedDc = deletecounter{1, 0}
702 json.NewDecoder(response.Body).Decode(&responseDc)
703 if responseDc != expectedDc {
704 c.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
705 expectedDc, responseDc)
707 // Confirm the block has been deleted
708 buf := make([]byte, BlockSize)
709 _, err := vols[0].Get(context.Background(), TestHash, buf)
710 var blockDeleted = os.IsNotExist(err)
712 c.Error("superuserExistingBlockReq: block not deleted")
715 // A DELETE request on a block newer than BlobSigningTTL
716 // should return success but leave the block on the volume.
717 vols[0].Put(context.Background(), TestHash, TestBlock)
718 s.cluster.Collections.BlobSigningTTL = arvados.Duration(time.Hour)
720 response = IssueRequest(s.handler, superuserExistingBlockReq)
722 "data manager request, existing block",
725 // Expect response {"copies_deleted":1,"copies_failed":0}
726 expectedDc = deletecounter{1, 0}
727 json.NewDecoder(response.Body).Decode(&responseDc)
728 if responseDc != expectedDc {
729 c.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
730 expectedDc, responseDc)
732 // Confirm the block has NOT been deleted.
733 _, err = vols[0].Get(context.Background(), TestHash, buf)
735 c.Errorf("testing delete on new block: %s\n", err)
741 // Test handling of the PUT /pull statement.
743 // Cases tested: syntactically valid and invalid pull lists, from the
744 // data manager and from unprivileged users:
746 // 1. Valid pull list from an ordinary user
747 // (expected result: 401 Unauthorized)
749 // 2. Invalid pull request from an ordinary user
750 // (expected result: 401 Unauthorized)
752 // 3. Valid pull request from the data manager
753 // (expected result: 200 OK with request body "Received 3 pull
756 // 4. Invalid pull request from the data manager
757 // (expected result: 400 Bad Request)
759 // Test that in the end, the pull manager received a good pull list with
760 // the expected number of requests.
762 // TODO(twp): test concurrency: launch 100 goroutines to update the
763 // pull list simultaneously. Make sure that none of them return 400
764 // Bad Request and that pullq.GetList() returns a valid list.
766 func (s *HandlerSuite) TestPullHandler(c *check.C) {
767 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
769 // Replace the router's pullq -- which the worker goroutines
770 // started by setup() are now receiving from -- with a new
771 // one, so we can see what the handler sends to it.
772 pullq := NewWorkQueue()
773 s.handler.Handler.(*router).pullq = pullq
775 var userToken = "USER TOKEN"
776 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
778 goodJSON := []byte(`[
780 "locator":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+12345",
787 "locator":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb+12345",
791 "locator":"cccccccccccccccccccccccccccccccc+12345",
792 "servers":["http://server1"]
796 badJSON := []byte(`{ "key":"I'm a little teapot" }`)
798 type pullTest struct {
804 var testcases = []pullTest{
806 "Valid pull list from an ordinary user",
807 RequestTester{"/pull", userToken, "PUT", goodJSON, ""},
808 http.StatusUnauthorized,
812 "Invalid pull request from an ordinary user",
813 RequestTester{"/pull", userToken, "PUT", badJSON, ""},
814 http.StatusUnauthorized,
818 "Valid pull request from the data manager",
819 RequestTester{"/pull", s.cluster.SystemRootToken, "PUT", goodJSON, ""},
821 "Received 3 pull requests\n",
824 "Invalid pull request from the data manager",
825 RequestTester{"/pull", s.cluster.SystemRootToken, "PUT", badJSON, ""},
826 http.StatusBadRequest,
831 for _, tst := range testcases {
832 response := IssueRequest(s.handler, &tst.req)
833 ExpectStatusCode(c, tst.name, tst.responseCode, response)
834 ExpectBody(c, tst.name, tst.responseBody, response)
837 // The Keep pull manager should have received one good list with 3
839 for i := 0; i < 3; i++ {
842 case item = <-pullq.NextItem:
843 case <-time.After(time.Second):
846 if _, ok := item.(PullRequest); !ok {
847 c.Errorf("item %v could not be parsed as a PullRequest", item)
851 expectChannelEmpty(c, pullq.NextItem)
858 // Cases tested: syntactically valid and invalid trash lists, from the
859 // data manager and from unprivileged users:
861 // 1. Valid trash list from an ordinary user
862 // (expected result: 401 Unauthorized)
864 // 2. Invalid trash list from an ordinary user
865 // (expected result: 401 Unauthorized)
867 // 3. Valid trash list from the data manager
868 // (expected result: 200 OK with request body "Received 3 trash
871 // 4. Invalid trash list from the data manager
872 // (expected result: 400 Bad Request)
874 // Test that in the end, the trash collector received a good list
875 // trash list with the expected number of requests.
877 // TODO(twp): test concurrency: launch 100 goroutines to update the
878 // pull list simultaneously. Make sure that none of them return 400
879 // Bad Request and that replica.Dump() returns a valid list.
881 func (s *HandlerSuite) TestTrashHandler(c *check.C) {
882 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
883 // Replace the router's trashq -- which the worker goroutines
884 // started by setup() are now receiving from -- with a new
885 // one, so we can see what the handler sends to it.
886 trashq := NewWorkQueue()
887 s.handler.Handler.(*router).trashq = trashq
889 var userToken = "USER TOKEN"
890 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
892 goodJSON := []byte(`[
895 "block_mtime":1409082153
899 "block_mtime":1409082153
903 "block_mtime":1409082153
907 badJSON := []byte(`I am not a valid JSON string`)
909 type trashTest struct {
916 var testcases = []trashTest{
918 "Valid trash list from an ordinary user",
919 RequestTester{"/trash", userToken, "PUT", goodJSON, ""},
920 http.StatusUnauthorized,
924 "Invalid trash list from an ordinary user",
925 RequestTester{"/trash", userToken, "PUT", badJSON, ""},
926 http.StatusUnauthorized,
930 "Valid trash list from the data manager",
931 RequestTester{"/trash", s.cluster.SystemRootToken, "PUT", goodJSON, ""},
933 "Received 3 trash requests\n",
936 "Invalid trash list from the data manager",
937 RequestTester{"/trash", s.cluster.SystemRootToken, "PUT", badJSON, ""},
938 http.StatusBadRequest,
943 for _, tst := range testcases {
944 response := IssueRequest(s.handler, &tst.req)
945 ExpectStatusCode(c, tst.name, tst.responseCode, response)
946 ExpectBody(c, tst.name, tst.responseBody, response)
949 // The trash collector should have received one good list with 3
951 for i := 0; i < 3; i++ {
952 item := <-trashq.NextItem
953 if _, ok := item.(TrashRequest); !ok {
954 c.Errorf("item %v could not be parsed as a TrashRequest", item)
958 expectChannelEmpty(c, trashq.NextItem)
961 // ====================
963 // ====================
965 // IssueTestRequest executes an HTTP request described by rt, to a
966 // REST router. It returns the HTTP response to the request.
967 func IssueRequest(handler http.Handler, rt *RequestTester) *httptest.ResponseRecorder {
968 response := httptest.NewRecorder()
969 body := bytes.NewReader(rt.requestBody)
970 req, _ := http.NewRequest(rt.method, rt.uri, body)
971 if rt.apiToken != "" {
972 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
974 if rt.storageClasses != "" {
975 req.Header.Set("X-Keep-Storage-Classes", rt.storageClasses)
977 handler.ServeHTTP(response, req)
981 func IssueHealthCheckRequest(handler http.Handler, rt *RequestTester) *httptest.ResponseRecorder {
982 response := httptest.NewRecorder()
983 body := bytes.NewReader(rt.requestBody)
984 req, _ := http.NewRequest(rt.method, rt.uri, body)
985 if rt.apiToken != "" {
986 req.Header.Set("Authorization", "Bearer "+rt.apiToken)
988 handler.ServeHTTP(response, req)
992 // ExpectStatusCode checks whether a response has the specified status code,
993 // and reports a test failure if not.
994 func ExpectStatusCode(
998 response *httptest.ResponseRecorder) {
999 c.Check(response.Code, check.Equals, expectedStatus, check.Commentf("%s", testname))
1005 expectedBody string,
1006 response *httptest.ResponseRecorder) {
1007 if expectedBody != "" && response.Body.String() != expectedBody {
1008 c.Errorf("%s: expected response body '%s', got %+v",
1009 testname, expectedBody, response)
1014 func (s *HandlerSuite) TestPutNeedsOnlyOneBuffer(c *check.C) {
1015 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1017 defer func(orig *bufferPool) {
1020 bufs = newBufferPool(ctxlog.TestLogger(c), 1, BlockSize)
1022 ok := make(chan struct{})
1024 for i := 0; i < 2; i++ {
1025 response := IssueRequest(s.handler,
1028 uri: "/" + TestHash,
1029 requestBody: TestBlock,
1032 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
1039 case <-time.After(time.Second):
1040 c.Fatal("PUT deadlocks with MaxKeepBlobBuffers==1")
1044 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
1046 func (s *HandlerSuite) TestPutHandlerNoBufferleak(c *check.C) {
1047 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1049 ok := make(chan bool)
1051 for i := 0; i < s.cluster.API.MaxKeepBlobBuffers+1; i++ {
1052 // Unauthenticated request, no server key
1053 // => OK (unsigned response)
1054 unsignedLocator := "/" + TestHash
1055 response := IssueRequest(s.handler,
1058 uri: unsignedLocator,
1059 requestBody: TestBlock,
1062 "TestPutHandlerBufferleak", http.StatusOK, response)
1064 "TestPutHandlerBufferleak",
1065 TestHashPutResp, response)
1070 case <-time.After(20 * time.Second):
1071 // If the buffer pool leaks, the test goroutine hangs.
1072 c.Fatal("test did not finish, assuming pool leaked")
1077 type notifyingResponseRecorder struct {
1078 *httptest.ResponseRecorder
1082 func (r *notifyingResponseRecorder) CloseNotify() <-chan bool {
1086 func (s *HandlerSuite) TestGetHandlerClientDisconnect(c *check.C) {
1087 s.cluster.Collections.BlobSigning = false
1088 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1090 defer func(orig *bufferPool) {
1093 bufs = newBufferPool(ctxlog.TestLogger(c), 1, BlockSize)
1094 defer bufs.Put(bufs.Get(BlockSize))
1096 if err := s.handler.volmgr.AllWritable()[0].Put(context.Background(), TestHash, TestBlock); err != nil {
1100 resp := ¬ifyingResponseRecorder{
1101 ResponseRecorder: httptest.NewRecorder(),
1102 closer: make(chan bool, 1),
1104 if _, ok := http.ResponseWriter(resp).(http.CloseNotifier); !ok {
1105 c.Fatal("notifyingResponseRecorder is broken")
1107 // If anyone asks, the client has disconnected.
1110 ok := make(chan struct{})
1112 req, _ := http.NewRequest("GET", fmt.Sprintf("/%s+%d", TestHash, len(TestBlock)), nil)
1113 s.handler.ServeHTTP(resp, req)
1118 case <-time.After(20 * time.Second):
1119 c.Fatal("request took >20s, close notifier must be broken")
1123 ExpectStatusCode(c, "client disconnect", http.StatusServiceUnavailable, resp.ResponseRecorder)
1124 for i, v := range s.handler.volmgr.AllWritable() {
1125 if calls := v.Volume.(*MockVolume).called["GET"]; calls != 0 {
1126 c.Errorf("volume %d got %d calls, expected 0", i, calls)
1131 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
1133 func (s *HandlerSuite) TestGetHandlerNoBufferLeak(c *check.C) {
1134 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1136 vols := s.handler.volmgr.AllWritable()
1137 if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
1141 ok := make(chan bool)
1143 for i := 0; i < s.cluster.API.MaxKeepBlobBuffers+1; i++ {
1144 // Unauthenticated request, unsigned locator
1146 unsignedLocator := "/" + TestHash
1147 response := IssueRequest(s.handler,
1150 uri: unsignedLocator,
1153 "Unauthenticated request, unsigned locator", http.StatusOK, response)
1155 "Unauthenticated request, unsigned locator",
1162 case <-time.After(20 * time.Second):
1163 // If the buffer pool leaks, the test goroutine hangs.
1164 c.Fatal("test did not finish, assuming pool leaked")
1169 func (s *HandlerSuite) TestPutStorageClasses(c *check.C) {
1170 s.cluster.Volumes = map[string]arvados.Volume{
1171 "zzzzz-nyw5e-000000000000000": {Replication: 1, Driver: "mock"}, // "default" is implicit
1172 "zzzzz-nyw5e-111111111111111": {Replication: 1, Driver: "mock", StorageClasses: map[string]bool{"special": true, "extra": true}},
1173 "zzzzz-nyw5e-222222222222222": {Replication: 1, Driver: "mock", StorageClasses: map[string]bool{"readonly": true}, ReadOnly: true},
1175 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1176 rt := RequestTester{
1178 uri: "/" + TestHash,
1179 requestBody: TestBlock,
1182 for _, trial := range []struct {
1187 {"default", "default=1"},
1188 {" , default , default , ", "default=1"},
1189 {"special", "extra=1, special=1"},
1190 {"special, readonly", "extra=1, special=1"},
1191 {"special, nonexistent", "extra=1, special=1"},
1192 {"extra, special", "extra=1, special=1"},
1193 {"default, special", "default=1, extra=1, special=1"},
1195 c.Logf("success case %#v", trial)
1196 rt.storageClasses = trial.ask
1197 resp := IssueRequest(s.handler, &rt)
1198 if trial.expect == "" {
1199 // any non-empty value is correct
1200 c.Check(resp.Header().Get("X-Keep-Storage-Classes-Confirmed"), check.Not(check.Equals), "")
1202 c.Check(sortCommaSeparated(resp.Header().Get("X-Keep-Storage-Classes-Confirmed")), check.Equals, trial.expect)
1206 for _, trial := range []struct {
1210 {"doesnotexist, readonly"},
1213 c.Logf("failure case %#v", trial)
1214 rt.storageClasses = trial.ask
1215 resp := IssueRequest(s.handler, &rt)
1216 c.Check(resp.Code, check.Equals, http.StatusServiceUnavailable)
1220 func sortCommaSeparated(s string) string {
1221 slice := strings.Split(s, ", ")
1223 return strings.Join(slice, ", ")
1226 func (s *HandlerSuite) TestPutResponseHeader(c *check.C) {
1227 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1229 resp := IssueRequest(s.handler, &RequestTester{
1231 uri: "/" + TestHash,
1232 requestBody: TestBlock,
1235 c.Check(resp.Header().Get("X-Keep-Replicas-Stored"), check.Equals, "1")
1236 c.Check(resp.Header().Get("X-Keep-Storage-Classes-Confirmed"), check.Equals, "default=1")
1239 func (s *HandlerSuite) TestUntrashHandler(c *check.C) {
1240 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1242 // Set up Keep volumes
1243 vols := s.handler.volmgr.AllWritable()
1244 vols[0].Put(context.Background(), TestHash, TestBlock)
1246 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
1248 // unauthenticatedReq => UnauthorizedError
1249 unauthenticatedReq := &RequestTester{
1251 uri: "/untrash/" + TestHash,
1253 response := IssueRequest(s.handler, unauthenticatedReq)
1255 "Unauthenticated request",
1256 UnauthorizedError.HTTPCode,
1259 // notDataManagerReq => UnauthorizedError
1260 notDataManagerReq := &RequestTester{
1262 uri: "/untrash/" + TestHash,
1263 apiToken: knownToken,
1266 response = IssueRequest(s.handler, notDataManagerReq)
1268 "Non-datamanager token",
1269 UnauthorizedError.HTTPCode,
1272 // datamanagerWithBadHashReq => StatusBadRequest
1273 datamanagerWithBadHashReq := &RequestTester{
1275 uri: "/untrash/thisisnotalocator",
1276 apiToken: s.cluster.SystemRootToken,
1278 response = IssueRequest(s.handler, datamanagerWithBadHashReq)
1280 "Bad locator in untrash request",
1281 http.StatusBadRequest,
1284 // datamanagerWrongMethodReq => StatusBadRequest
1285 datamanagerWrongMethodReq := &RequestTester{
1287 uri: "/untrash/" + TestHash,
1288 apiToken: s.cluster.SystemRootToken,
1290 response = IssueRequest(s.handler, datamanagerWrongMethodReq)
1292 "Only PUT method is supported for untrash",
1293 http.StatusMethodNotAllowed,
1296 // datamanagerReq => StatusOK
1297 datamanagerReq := &RequestTester{
1299 uri: "/untrash/" + TestHash,
1300 apiToken: s.cluster.SystemRootToken,
1302 response = IssueRequest(s.handler, datamanagerReq)
1307 c.Check(response.Body.String(), check.Equals, "Successfully untrashed on: [MockVolume], [MockVolume]\n")
1310 func (s *HandlerSuite) TestUntrashHandlerWithNoWritableVolumes(c *check.C) {
1311 // Change all volumes to read-only
1312 for uuid, v := range s.cluster.Volumes {
1314 s.cluster.Volumes[uuid] = v
1316 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1318 // datamanagerReq => StatusOK
1319 datamanagerReq := &RequestTester{
1321 uri: "/untrash/" + TestHash,
1322 apiToken: s.cluster.SystemRootToken,
1324 response := IssueRequest(s.handler, datamanagerReq)
1326 "No writable volumes",
1327 http.StatusNotFound,
1331 func (s *HandlerSuite) TestHealthCheckPing(c *check.C) {
1332 s.cluster.ManagementToken = arvadostest.ManagementToken
1333 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1334 pingReq := &RequestTester{
1336 uri: "/_health/ping",
1337 apiToken: arvadostest.ManagementToken,
1339 response := IssueHealthCheckRequest(s.handler, pingReq)
1344 want := `{"health":"OK"}`
1345 if !strings.Contains(response.Body.String(), want) {
1346 c.Errorf("expected response to include %s: got %s", want, response.Body.String())