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.
28 "git.curoverse.com/arvados.git/lib/config"
29 "git.curoverse.com/arvados.git/sdk/go/arvados"
30 "git.curoverse.com/arvados.git/sdk/go/arvadostest"
31 "git.curoverse.com/arvados.git/sdk/go/ctxlog"
32 "github.com/prometheus/client_golang/prometheus"
33 check "gopkg.in/check.v1"
36 var testServiceURL = func() arvados.URL {
37 return arvados.URL{Host: "localhost:12345", Scheme: "http"}
40 func testCluster(t TB) *arvados.Cluster {
41 cfg, err := config.NewLoader(bytes.NewBufferString("Clusters: {zzzzz: {}}"), ctxlog.TestLogger(t)).Load()
45 cluster, err := cfg.GetCluster("")
49 cluster.SystemRootToken = arvadostest.DataManagerToken
50 cluster.ManagementToken = arvadostest.ManagementToken
51 cluster.Collections.BlobSigning = false
55 var _ = check.Suite(&HandlerSuite{})
57 type HandlerSuite struct {
58 cluster *arvados.Cluster
62 func (s *HandlerSuite) SetUpTest(c *check.C) {
63 s.cluster = testCluster(c)
64 s.cluster.Volumes = map[string]arvados.Volume{
65 "zzzzz-nyw5e-000000000000000": {Replication: 1, Driver: "mock"},
66 "zzzzz-nyw5e-111111111111111": {Replication: 1, Driver: "mock"},
68 s.handler = &handler{}
71 // A RequestTester represents the parameters for an HTTP request to
72 // be issued on behalf of a unit test.
73 type RequestTester struct {
80 // Test GetBlockHandler on the following situations:
81 // - permissions off, unauthenticated request, unsigned locator
82 // - permissions on, authenticated request, signed locator
83 // - permissions on, authenticated request, unsigned locator
84 // - permissions on, unauthenticated request, signed locator
85 // - permissions on, authenticated request, expired locator
86 // - permissions on, authenticated request, signed locator, transient error from backend
88 func (s *HandlerSuite) TestGetHandler(c *check.C) {
89 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
91 vols := s.handler.volmgr.AllWritable()
92 err := vols[0].Put(context.Background(), TestHash, TestBlock)
93 c.Check(err, check.IsNil)
95 // Create locators for testing.
96 // Turn on permission settings so we can generate signed locators.
97 s.cluster.Collections.BlobSigning = true
98 s.cluster.Collections.BlobSigningKey = knownKey
99 s.cluster.Collections.BlobSigningTTL.Set("5m")
102 unsignedLocator = "/" + TestHash
103 validTimestamp = time.Now().Add(s.cluster.Collections.BlobSigningTTL.Duration())
104 expiredTimestamp = time.Now().Add(-time.Hour)
105 signedLocator = "/" + SignLocator(s.cluster, TestHash, knownToken, validTimestamp)
106 expiredLocator = "/" + SignLocator(s.cluster, TestHash, knownToken, expiredTimestamp)
110 // Test unauthenticated request with permissions off.
111 s.cluster.Collections.BlobSigning = false
113 // Unauthenticated request, unsigned locator
115 response := IssueRequest(s.handler,
118 uri: unsignedLocator,
121 "Unauthenticated request, unsigned locator", http.StatusOK, response)
123 "Unauthenticated request, unsigned locator",
127 receivedLen := response.Header().Get("Content-Length")
128 expectedLen := fmt.Sprintf("%d", len(TestBlock))
129 if receivedLen != expectedLen {
130 c.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
135 s.cluster.Collections.BlobSigning = true
137 // Authenticated request, signed locator
139 response = IssueRequest(s.handler, &RequestTester{
142 apiToken: knownToken,
145 "Authenticated request, signed locator", http.StatusOK, response)
147 "Authenticated request, signed locator", string(TestBlock), response)
149 receivedLen = response.Header().Get("Content-Length")
150 expectedLen = fmt.Sprintf("%d", len(TestBlock))
151 if receivedLen != expectedLen {
152 c.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
155 // Authenticated request, unsigned locator
156 // => PermissionError
157 response = IssueRequest(s.handler, &RequestTester{
159 uri: unsignedLocator,
160 apiToken: knownToken,
162 ExpectStatusCode(c, "unsigned locator", PermissionError.HTTPCode, response)
164 // Unauthenticated request, signed locator
165 // => PermissionError
166 response = IssueRequest(s.handler, &RequestTester{
171 "Unauthenticated request, signed locator",
172 PermissionError.HTTPCode, response)
174 // Authenticated request, expired locator
176 response = IssueRequest(s.handler, &RequestTester{
179 apiToken: knownToken,
182 "Authenticated request, expired locator",
183 ExpiredError.HTTPCode, response)
185 // Authenticated request, signed locator
186 // => 503 Server busy (transient error)
188 // Set up the block owning volume to respond with errors
189 vols[0].Volume.(*MockVolume).Bad = true
190 vols[0].Volume.(*MockVolume).BadVolumeError = VolumeBusyError
191 response = IssueRequest(s.handler, &RequestTester{
194 apiToken: knownToken,
196 // A transient error from one volume while the other doesn't find the block
197 // should make the service return a 503 so that clients can retry.
199 "Volume backend busy",
203 // Test PutBlockHandler on the following situations:
205 // - with server key, authenticated request, unsigned locator
206 // - with server key, unauthenticated request, unsigned locator
208 func (s *HandlerSuite) TestPutHandler(c *check.C) {
209 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
214 s.cluster.Collections.BlobSigningKey = ""
216 // Unauthenticated request, no server key
217 // => OK (unsigned response)
218 unsignedLocator := "/" + TestHash
219 response := IssueRequest(s.handler,
222 uri: unsignedLocator,
223 requestBody: TestBlock,
227 "Unauthenticated request, no server key", http.StatusOK, response)
229 "Unauthenticated request, no server key",
230 TestHashPutResp, response)
232 // ------------------
233 // With a server key.
235 s.cluster.Collections.BlobSigningKey = knownKey
236 s.cluster.Collections.BlobSigningTTL.Set("5m")
238 // When a permission key is available, the locator returned
239 // from an authenticated PUT request will be signed.
241 // Authenticated PUT, signed locator
242 // => OK (signed response)
243 response = IssueRequest(s.handler,
246 uri: unsignedLocator,
247 requestBody: TestBlock,
248 apiToken: knownToken,
252 "Authenticated PUT, signed locator, with server key",
253 http.StatusOK, response)
254 responseLocator := strings.TrimSpace(response.Body.String())
255 if VerifySignature(s.cluster, responseLocator, knownToken) != nil {
256 c.Errorf("Authenticated PUT, signed locator, with server key:\n"+
257 "response '%s' does not contain a valid signature",
261 // Unauthenticated PUT, unsigned locator
263 response = IssueRequest(s.handler,
266 uri: unsignedLocator,
267 requestBody: TestBlock,
271 "Unauthenticated PUT, unsigned locator, with server key",
272 http.StatusOK, response)
274 "Unauthenticated PUT, unsigned locator, with server key",
275 TestHashPutResp, response)
278 func (s *HandlerSuite) TestPutAndDeleteSkipReadonlyVolumes(c *check.C) {
279 s.cluster.Volumes["zzzzz-nyw5e-000000000000000"] = arvados.Volume{Driver: "mock", ReadOnly: true}
280 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
282 s.cluster.SystemRootToken = "fake-data-manager-token"
283 IssueRequest(s.handler,
287 requestBody: TestBlock,
290 s.cluster.Collections.BlobTrash = true
291 IssueRequest(s.handler,
295 requestBody: TestBlock,
296 apiToken: s.cluster.SystemRootToken,
303 for _, e := range []expect{
304 {"zzzzz-nyw5e-000000000000000", "Get", 0},
305 {"zzzzz-nyw5e-000000000000000", "Compare", 0},
306 {"zzzzz-nyw5e-000000000000000", "Touch", 0},
307 {"zzzzz-nyw5e-000000000000000", "Put", 0},
308 {"zzzzz-nyw5e-000000000000000", "Delete", 0},
309 {"zzzzz-nyw5e-111111111111111", "Get", 0},
310 {"zzzzz-nyw5e-111111111111111", "Compare", 1},
311 {"zzzzz-nyw5e-111111111111111", "Touch", 1},
312 {"zzzzz-nyw5e-111111111111111", "Put", 1},
313 {"zzzzz-nyw5e-111111111111111", "Delete", 1},
315 if calls := s.handler.volmgr.mountMap[e.volid].Volume.(*MockVolume).CallCount(e.method); calls != e.callcount {
316 c.Errorf("Got %d %s() on vol %s, expect %d", calls, e.method, e.volid, e.callcount)
321 // Test /index requests:
322 // - unauthenticated /index request
323 // - unauthenticated /index/prefix request
324 // - authenticated /index request | non-superuser
325 // - authenticated /index/prefix request | non-superuser
326 // - authenticated /index request | superuser
327 // - authenticated /index/prefix request | superuser
329 // The only /index requests that should succeed are those issued by the
330 // superuser. They should pass regardless of the value of RequireSignatures.
332 func (s *HandlerSuite) TestIndexHandler(c *check.C) {
333 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
335 // Include multiple blocks on different volumes, and
336 // some metadata files (which should be omitted from index listings)
337 vols := s.handler.volmgr.AllWritable()
338 vols[0].Put(context.Background(), TestHash, TestBlock)
339 vols[1].Put(context.Background(), TestHash2, TestBlock2)
340 vols[0].Put(context.Background(), TestHash+".meta", []byte("metadata"))
341 vols[1].Put(context.Background(), TestHash2+".meta", []byte("metadata"))
343 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
345 unauthenticatedReq := &RequestTester{
349 authenticatedReq := &RequestTester{
352 apiToken: knownToken,
354 superuserReq := &RequestTester{
357 apiToken: s.cluster.SystemRootToken,
359 unauthPrefixReq := &RequestTester{
361 uri: "/index/" + TestHash[0:3],
363 authPrefixReq := &RequestTester{
365 uri: "/index/" + TestHash[0:3],
366 apiToken: knownToken,
368 superuserPrefixReq := &RequestTester{
370 uri: "/index/" + TestHash[0:3],
371 apiToken: s.cluster.SystemRootToken,
373 superuserNoSuchPrefixReq := &RequestTester{
376 apiToken: s.cluster.SystemRootToken,
378 superuserInvalidPrefixReq := &RequestTester{
381 apiToken: s.cluster.SystemRootToken,
384 // -------------------------------------------------------------
385 // Only the superuser should be allowed to issue /index requests.
387 // ---------------------------
388 // BlobSigning enabled
389 // This setting should not affect tests passing.
390 s.cluster.Collections.BlobSigning = true
392 // unauthenticated /index request
393 // => UnauthorizedError
394 response := IssueRequest(s.handler, unauthenticatedReq)
396 "RequireSignatures on, unauthenticated request",
397 UnauthorizedError.HTTPCode,
400 // unauthenticated /index/prefix request
401 // => UnauthorizedError
402 response = IssueRequest(s.handler, unauthPrefixReq)
404 "permissions on, unauthenticated /index/prefix request",
405 UnauthorizedError.HTTPCode,
408 // authenticated /index request, non-superuser
409 // => UnauthorizedError
410 response = IssueRequest(s.handler, authenticatedReq)
412 "permissions on, authenticated request, non-superuser",
413 UnauthorizedError.HTTPCode,
416 // authenticated /index/prefix request, non-superuser
417 // => UnauthorizedError
418 response = IssueRequest(s.handler, authPrefixReq)
420 "permissions on, authenticated /index/prefix request, non-superuser",
421 UnauthorizedError.HTTPCode,
424 // superuser /index request
426 response = IssueRequest(s.handler, superuserReq)
428 "permissions on, superuser request",
432 // ----------------------------
433 // BlobSigning disabled
434 // Valid Request should still pass.
435 s.cluster.Collections.BlobSigning = false
437 // superuser /index request
439 response = IssueRequest(s.handler, superuserReq)
441 "permissions on, superuser request",
445 expected := `^` + TestHash + `\+\d+ \d+\n` +
446 TestHash2 + `\+\d+ \d+\n\n$`
447 match, _ := regexp.MatchString(expected, response.Body.String())
450 "permissions on, superuser request: expected %s, got:\n%s",
451 expected, response.Body.String())
454 // superuser /index/prefix request
456 response = IssueRequest(s.handler, superuserPrefixReq)
458 "permissions on, superuser request",
462 expected = `^` + TestHash + `\+\d+ \d+\n\n$`
463 match, _ = regexp.MatchString(expected, response.Body.String())
466 "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
467 expected, response.Body.String())
470 // superuser /index/{no-such-prefix} request
472 response = IssueRequest(s.handler, superuserNoSuchPrefixReq)
474 "permissions on, superuser request",
478 if "\n" != response.Body.String() {
479 c.Errorf("Expected empty response for %s. Found %s", superuserNoSuchPrefixReq.uri, response.Body.String())
482 // superuser /index/{invalid-prefix} request
483 // => StatusBadRequest
484 response = IssueRequest(s.handler, superuserInvalidPrefixReq)
486 "permissions on, superuser request",
487 http.StatusBadRequest,
495 // With no token and with a non-data-manager token:
496 // * Delete existing block
497 // (test for 403 Forbidden, confirm block not deleted)
499 // With data manager token:
501 // * Delete existing block
502 // (test for 200 OK, response counts, confirm block deleted)
504 // * Delete nonexistent block
505 // (test for 200 OK, response counts)
509 // * Delete block on read-only and read-write volume
510 // (test for 200 OK, response with copies_deleted=1,
511 // copies_failed=1, confirm block deleted only on r/w volume)
513 // * Delete block on read-only volume only
514 // (test for 200 OK, response with copies_deleted=0, copies_failed=1,
515 // confirm block not deleted)
517 func (s *HandlerSuite) TestDeleteHandler(c *check.C) {
518 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
520 vols := s.handler.volmgr.AllWritable()
521 vols[0].Put(context.Background(), TestHash, TestBlock)
523 // Explicitly set the BlobSignatureTTL to 0 for these
524 // tests, to ensure the MockVolume deletes the blocks
525 // even though they have just been created.
526 s.cluster.Collections.BlobSigningTTL = arvados.Duration(0)
528 var userToken = "NOT DATA MANAGER TOKEN"
529 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
531 s.cluster.Collections.BlobTrash = true
533 unauthReq := &RequestTester{
538 userReq := &RequestTester{
544 superuserExistingBlockReq := &RequestTester{
547 apiToken: s.cluster.SystemRootToken,
550 superuserNonexistentBlockReq := &RequestTester{
552 uri: "/" + TestHash2,
553 apiToken: s.cluster.SystemRootToken,
556 // Unauthenticated request returns PermissionError.
557 var response *httptest.ResponseRecorder
558 response = IssueRequest(s.handler, unauthReq)
560 "unauthenticated request",
561 PermissionError.HTTPCode,
564 // Authenticated non-admin request returns PermissionError.
565 response = IssueRequest(s.handler, userReq)
567 "authenticated non-admin request",
568 PermissionError.HTTPCode,
571 // Authenticated admin request for nonexistent block.
572 type deletecounter struct {
573 Deleted int `json:"copies_deleted"`
574 Failed int `json:"copies_failed"`
576 var responseDc, expectedDc deletecounter
578 response = IssueRequest(s.handler, superuserNonexistentBlockReq)
580 "data manager request, nonexistent block",
584 // Authenticated admin request for existing block while BlobTrash is false.
585 s.cluster.Collections.BlobTrash = false
586 response = IssueRequest(s.handler, superuserExistingBlockReq)
588 "authenticated request, existing block, method disabled",
589 MethodDisabledError.HTTPCode,
591 s.cluster.Collections.BlobTrash = true
593 // Authenticated admin request for existing block.
594 response = IssueRequest(s.handler, superuserExistingBlockReq)
596 "data manager request, existing block",
599 // Expect response {"copies_deleted":1,"copies_failed":0}
600 expectedDc = deletecounter{1, 0}
601 json.NewDecoder(response.Body).Decode(&responseDc)
602 if responseDc != expectedDc {
603 c.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
604 expectedDc, responseDc)
606 // Confirm the block has been deleted
607 buf := make([]byte, BlockSize)
608 _, err := vols[0].Get(context.Background(), TestHash, buf)
609 var blockDeleted = os.IsNotExist(err)
611 c.Error("superuserExistingBlockReq: block not deleted")
614 // A DELETE request on a block newer than BlobSignatureTTL
615 // should return success but leave the block on the volume.
616 vols[0].Put(context.Background(), TestHash, TestBlock)
617 s.cluster.Collections.BlobSigningTTL = arvados.Duration(time.Hour)
619 response = IssueRequest(s.handler, superuserExistingBlockReq)
621 "data manager request, existing block",
624 // Expect response {"copies_deleted":1,"copies_failed":0}
625 expectedDc = deletecounter{1, 0}
626 json.NewDecoder(response.Body).Decode(&responseDc)
627 if responseDc != expectedDc {
628 c.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
629 expectedDc, responseDc)
631 // Confirm the block has NOT been deleted.
632 _, err = vols[0].Get(context.Background(), TestHash, buf)
634 c.Errorf("testing delete on new block: %s\n", err)
640 // Test handling of the PUT /pull statement.
642 // Cases tested: syntactically valid and invalid pull lists, from the
643 // data manager and from unprivileged users:
645 // 1. Valid pull list from an ordinary user
646 // (expected result: 401 Unauthorized)
648 // 2. Invalid pull request from an ordinary user
649 // (expected result: 401 Unauthorized)
651 // 3. Valid pull request from the data manager
652 // (expected result: 200 OK with request body "Received 3 pull
655 // 4. Invalid pull request from the data manager
656 // (expected result: 400 Bad Request)
658 // Test that in the end, the pull manager received a good pull list with
659 // the expected number of requests.
661 // TODO(twp): test concurrency: launch 100 goroutines to update the
662 // pull list simultaneously. Make sure that none of them return 400
663 // Bad Request and that pullq.GetList() returns a valid list.
665 func (s *HandlerSuite) TestPullHandler(c *check.C) {
666 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
668 // Replace the router's pullq -- which the worker goroutines
669 // started by setup() are now receiving from -- with a new
670 // one, so we can see what the handler sends to it.
671 pullq := NewWorkQueue()
672 s.handler.Handler.(*router).pullq = pullq
674 var userToken = "USER TOKEN"
675 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
677 goodJSON := []byte(`[
679 "locator":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+12345",
686 "locator":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb+12345",
690 "locator":"cccccccccccccccccccccccccccccccc+12345",
691 "servers":["http://server1"]
695 badJSON := []byte(`{ "key":"I'm a little teapot" }`)
697 type pullTest struct {
703 var testcases = []pullTest{
705 "Valid pull list from an ordinary user",
706 RequestTester{"/pull", userToken, "PUT", goodJSON},
707 http.StatusUnauthorized,
711 "Invalid pull request from an ordinary user",
712 RequestTester{"/pull", userToken, "PUT", badJSON},
713 http.StatusUnauthorized,
717 "Valid pull request from the data manager",
718 RequestTester{"/pull", s.cluster.SystemRootToken, "PUT", goodJSON},
720 "Received 3 pull requests\n",
723 "Invalid pull request from the data manager",
724 RequestTester{"/pull", s.cluster.SystemRootToken, "PUT", badJSON},
725 http.StatusBadRequest,
730 for _, tst := range testcases {
731 response := IssueRequest(s.handler, &tst.req)
732 ExpectStatusCode(c, tst.name, tst.responseCode, response)
733 ExpectBody(c, tst.name, tst.responseBody, response)
736 // The Keep pull manager should have received one good list with 3
738 for i := 0; i < 3; i++ {
741 case item = <-pullq.NextItem:
742 case <-time.After(time.Second):
745 if _, ok := item.(PullRequest); !ok {
746 c.Errorf("item %v could not be parsed as a PullRequest", item)
750 expectChannelEmpty(c, pullq.NextItem)
757 // Cases tested: syntactically valid and invalid trash lists, from the
758 // data manager and from unprivileged users:
760 // 1. Valid trash list from an ordinary user
761 // (expected result: 401 Unauthorized)
763 // 2. Invalid trash list from an ordinary user
764 // (expected result: 401 Unauthorized)
766 // 3. Valid trash list from the data manager
767 // (expected result: 200 OK with request body "Received 3 trash
770 // 4. Invalid trash list from the data manager
771 // (expected result: 400 Bad Request)
773 // Test that in the end, the trash collector received a good list
774 // trash list with the expected number of requests.
776 // TODO(twp): test concurrency: launch 100 goroutines to update the
777 // pull list simultaneously. Make sure that none of them return 400
778 // Bad Request and that replica.Dump() returns a valid list.
780 func (s *HandlerSuite) TestTrashHandler(c *check.C) {
781 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
782 // Replace the router's trashq -- which the worker goroutines
783 // started by setup() are now receiving from -- with a new
784 // one, so we can see what the handler sends to it.
785 trashq := NewWorkQueue()
786 s.handler.Handler.(*router).trashq = trashq
788 var userToken = "USER TOKEN"
789 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
791 goodJSON := []byte(`[
794 "block_mtime":1409082153
798 "block_mtime":1409082153
802 "block_mtime":1409082153
806 badJSON := []byte(`I am not a valid JSON string`)
808 type trashTest struct {
815 var testcases = []trashTest{
817 "Valid trash list from an ordinary user",
818 RequestTester{"/trash", userToken, "PUT", goodJSON},
819 http.StatusUnauthorized,
823 "Invalid trash list from an ordinary user",
824 RequestTester{"/trash", userToken, "PUT", badJSON},
825 http.StatusUnauthorized,
829 "Valid trash list from the data manager",
830 RequestTester{"/trash", s.cluster.SystemRootToken, "PUT", goodJSON},
832 "Received 3 trash requests\n",
835 "Invalid trash list from the data manager",
836 RequestTester{"/trash", s.cluster.SystemRootToken, "PUT", badJSON},
837 http.StatusBadRequest,
842 for _, tst := range testcases {
843 response := IssueRequest(s.handler, &tst.req)
844 ExpectStatusCode(c, tst.name, tst.responseCode, response)
845 ExpectBody(c, tst.name, tst.responseBody, response)
848 // The trash collector should have received one good list with 3
850 for i := 0; i < 3; i++ {
851 item := <-trashq.NextItem
852 if _, ok := item.(TrashRequest); !ok {
853 c.Errorf("item %v could not be parsed as a TrashRequest", item)
857 expectChannelEmpty(c, trashq.NextItem)
860 // ====================
862 // ====================
864 // IssueTestRequest executes an HTTP request described by rt, to a
865 // REST router. It returns the HTTP response to the request.
866 func IssueRequest(handler http.Handler, rt *RequestTester) *httptest.ResponseRecorder {
867 response := httptest.NewRecorder()
868 body := bytes.NewReader(rt.requestBody)
869 req, _ := http.NewRequest(rt.method, rt.uri, body)
870 if rt.apiToken != "" {
871 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
873 handler.ServeHTTP(response, req)
877 func IssueHealthCheckRequest(handler http.Handler, rt *RequestTester) *httptest.ResponseRecorder {
878 response := httptest.NewRecorder()
879 body := bytes.NewReader(rt.requestBody)
880 req, _ := http.NewRequest(rt.method, rt.uri, body)
881 if rt.apiToken != "" {
882 req.Header.Set("Authorization", "Bearer "+rt.apiToken)
884 handler.ServeHTTP(response, req)
888 // ExpectStatusCode checks whether a response has the specified status code,
889 // and reports a test failure if not.
890 func ExpectStatusCode(
894 response *httptest.ResponseRecorder) {
895 if response.Code != expectedStatus {
896 c.Errorf("%s: expected status %d, got %+v",
897 testname, expectedStatus, response)
905 response *httptest.ResponseRecorder) {
906 if expectedBody != "" && response.Body.String() != expectedBody {
907 c.Errorf("%s: expected response body '%s', got %+v",
908 testname, expectedBody, response)
913 func (s *HandlerSuite) TestPutNeedsOnlyOneBuffer(c *check.C) {
914 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
916 defer func(orig *bufferPool) {
919 bufs = newBufferPool(ctxlog.TestLogger(c), 1, BlockSize)
921 ok := make(chan struct{})
923 for i := 0; i < 2; i++ {
924 response := IssueRequest(s.handler,
928 requestBody: TestBlock,
931 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
938 case <-time.After(time.Second):
939 c.Fatal("PUT deadlocks with MaxBuffers==1")
943 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
945 func (s *HandlerSuite) TestPutHandlerNoBufferleak(c *check.C) {
946 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
948 ok := make(chan bool)
950 for i := 0; i < s.cluster.API.MaxKeepBlobBuffers+1; i++ {
951 // Unauthenticated request, no server key
952 // => OK (unsigned response)
953 unsignedLocator := "/" + TestHash
954 response := IssueRequest(s.handler,
957 uri: unsignedLocator,
958 requestBody: TestBlock,
961 "TestPutHandlerBufferleak", http.StatusOK, response)
963 "TestPutHandlerBufferleak",
964 TestHashPutResp, response)
969 case <-time.After(20 * time.Second):
970 // If the buffer pool leaks, the test goroutine hangs.
971 c.Fatal("test did not finish, assuming pool leaked")
976 type notifyingResponseRecorder struct {
977 *httptest.ResponseRecorder
981 func (r *notifyingResponseRecorder) CloseNotify() <-chan bool {
985 func (s *HandlerSuite) TestGetHandlerClientDisconnect(c *check.C) {
986 s.cluster.Collections.BlobSigning = false
987 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
989 defer func(orig *bufferPool) {
992 bufs = newBufferPool(ctxlog.TestLogger(c), 1, BlockSize)
993 defer bufs.Put(bufs.Get(BlockSize))
995 if err := s.handler.volmgr.AllWritable()[0].Put(context.Background(), TestHash, TestBlock); err != nil {
999 resp := ¬ifyingResponseRecorder{
1000 ResponseRecorder: httptest.NewRecorder(),
1001 closer: make(chan bool, 1),
1003 if _, ok := http.ResponseWriter(resp).(http.CloseNotifier); !ok {
1004 c.Fatal("notifyingResponseRecorder is broken")
1006 // If anyone asks, the client has disconnected.
1009 ok := make(chan struct{})
1011 req, _ := http.NewRequest("GET", fmt.Sprintf("/%s+%d", TestHash, len(TestBlock)), nil)
1012 s.handler.ServeHTTP(resp, req)
1017 case <-time.After(20 * time.Second):
1018 c.Fatal("request took >20s, close notifier must be broken")
1022 ExpectStatusCode(c, "client disconnect", http.StatusServiceUnavailable, resp.ResponseRecorder)
1023 for i, v := range s.handler.volmgr.AllWritable() {
1024 if calls := v.Volume.(*MockVolume).called["GET"]; calls != 0 {
1025 c.Errorf("volume %d got %d calls, expected 0", i, calls)
1030 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
1032 func (s *HandlerSuite) TestGetHandlerNoBufferLeak(c *check.C) {
1033 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1035 vols := s.handler.volmgr.AllWritable()
1036 if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
1040 ok := make(chan bool)
1042 for i := 0; i < s.cluster.API.MaxKeepBlobBuffers+1; i++ {
1043 // Unauthenticated request, unsigned locator
1045 unsignedLocator := "/" + TestHash
1046 response := IssueRequest(s.handler,
1049 uri: unsignedLocator,
1052 "Unauthenticated request, unsigned locator", http.StatusOK, response)
1054 "Unauthenticated request, unsigned locator",
1061 case <-time.After(20 * time.Second):
1062 // If the buffer pool leaks, the test goroutine hangs.
1063 c.Fatal("test did not finish, assuming pool leaked")
1068 func (s *HandlerSuite) TestPutReplicationHeader(c *check.C) {
1069 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1071 resp := IssueRequest(s.handler, &RequestTester{
1073 uri: "/" + TestHash,
1074 requestBody: TestBlock,
1076 if r := resp.Header().Get("X-Keep-Replicas-Stored"); r != "1" {
1078 c.Errorf("Got X-Keep-Replicas-Stored: %q, expected %q", r, "1")
1082 func (s *HandlerSuite) TestUntrashHandler(c *check.C) {
1083 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1085 // Set up Keep volumes
1086 vols := s.handler.volmgr.AllWritable()
1087 vols[0].Put(context.Background(), TestHash, TestBlock)
1089 s.cluster.SystemRootToken = "DATA MANAGER TOKEN"
1091 // unauthenticatedReq => UnauthorizedError
1092 unauthenticatedReq := &RequestTester{
1094 uri: "/untrash/" + TestHash,
1096 response := IssueRequest(s.handler, unauthenticatedReq)
1098 "Unauthenticated request",
1099 UnauthorizedError.HTTPCode,
1102 // notDataManagerReq => UnauthorizedError
1103 notDataManagerReq := &RequestTester{
1105 uri: "/untrash/" + TestHash,
1106 apiToken: knownToken,
1109 response = IssueRequest(s.handler, notDataManagerReq)
1111 "Non-datamanager token",
1112 UnauthorizedError.HTTPCode,
1115 // datamanagerWithBadHashReq => StatusBadRequest
1116 datamanagerWithBadHashReq := &RequestTester{
1118 uri: "/untrash/thisisnotalocator",
1119 apiToken: s.cluster.SystemRootToken,
1121 response = IssueRequest(s.handler, datamanagerWithBadHashReq)
1123 "Bad locator in untrash request",
1124 http.StatusBadRequest,
1127 // datamanagerWrongMethodReq => StatusBadRequest
1128 datamanagerWrongMethodReq := &RequestTester{
1130 uri: "/untrash/" + TestHash,
1131 apiToken: s.cluster.SystemRootToken,
1133 response = IssueRequest(s.handler, datamanagerWrongMethodReq)
1135 "Only PUT method is supported for untrash",
1136 http.StatusMethodNotAllowed,
1139 // datamanagerReq => StatusOK
1140 datamanagerReq := &RequestTester{
1142 uri: "/untrash/" + TestHash,
1143 apiToken: s.cluster.SystemRootToken,
1145 response = IssueRequest(s.handler, datamanagerReq)
1150 expected := "Successfully untrashed on: [MockVolume],[MockVolume]"
1151 if response.Body.String() != expected {
1153 "Untrash response mismatched: expected %s, got:\n%s",
1154 expected, response.Body.String())
1158 func (s *HandlerSuite) TestUntrashHandlerWithNoWritableVolumes(c *check.C) {
1159 // Change all volumes to read-only
1160 for uuid, v := range s.cluster.Volumes {
1162 s.cluster.Volumes[uuid] = v
1164 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1166 // datamanagerReq => StatusOK
1167 datamanagerReq := &RequestTester{
1169 uri: "/untrash/" + TestHash,
1170 apiToken: s.cluster.SystemRootToken,
1172 response := IssueRequest(s.handler, datamanagerReq)
1174 "No writable volumes",
1175 http.StatusNotFound,
1179 func (s *HandlerSuite) TestHealthCheckPing(c *check.C) {
1180 s.cluster.ManagementToken = arvadostest.ManagementToken
1181 c.Assert(s.handler.setup(context.Background(), s.cluster, "", prometheus.NewRegistry(), testServiceURL), check.IsNil)
1182 pingReq := &RequestTester{
1184 uri: "/_health/ping",
1185 apiToken: arvadostest.ManagementToken,
1187 response := IssueHealthCheckRequest(s.handler, pingReq)
1192 want := `{"health":"OK"}`
1193 if !strings.Contains(response.Body.String(), want) {
1194 c.Errorf("expected response to include %s: got %s", want, response.Body.String())