1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
21 "git.arvados.org/arvados.git/sdk/go/arvados"
22 "git.arvados.org/arvados.git/sdk/go/arvadostest"
23 "git.arvados.org/arvados.git/sdk/go/httpserver"
24 "github.com/prometheus/client_golang/prometheus"
28 // routerSuite tests that the router correctly translates HTTP
29 // requests to the appropriate keepstore functionality, and translates
30 // the results to HTTP responses.
31 type routerSuite struct {
32 cluster *arvados.Cluster
35 var _ = Suite(&routerSuite{})
37 func testRouter(t TB, cluster *arvados.Cluster, reg *prometheus.Registry) (*router, context.CancelFunc) {
39 reg = prometheus.NewRegistry()
41 ctx, cancel := context.WithCancel(context.Background())
42 ks, kcancel := testKeepstore(t, cluster, reg)
47 puller := newPuller(ctx, ks, reg)
48 trasher := newTrasher(ctx, ks, reg)
49 return newRouter(ks, puller, trasher).(*router), cancel
52 func (s *routerSuite) SetUpTest(c *C) {
53 s.cluster = testCluster(c)
54 s.cluster.Volumes = map[string]arvados.Volume{
55 "zzzzz-nyw5e-000000000000000": {Replication: 1, Driver: "stub", StorageClasses: map[string]bool{"testclass1": true}},
56 "zzzzz-nyw5e-111111111111111": {Replication: 1, Driver: "stub", StorageClasses: map[string]bool{"testclass2": true}},
58 s.cluster.StorageClasses = map[string]arvados.StorageClassConfig{
59 "testclass1": arvados.StorageClassConfig{
62 "testclass2": arvados.StorageClassConfig{
68 func (s *routerSuite) TestBlockRead_Token(c *C) {
69 router, cancel := testRouter(c, s.cluster, nil)
72 err := router.keepstore.mountsW[0].BlockWrite(context.Background(), fooHash, []byte("foo"))
74 locSigned := router.keepstore.signLocator(arvadostest.ActiveTokenV2, fooHash+"+3")
75 c.Assert(locSigned, Not(Equals), fooHash+"+3")
78 resp := call(router, "GET", "http://example/"+locSigned, "", nil, nil)
79 c.Check(resp.Code, Equals, http.StatusUnauthorized)
80 c.Check(resp.Body.String(), Matches, "no token provided in Authorization header\n")
81 checkCORSHeaders(c, resp.Header())
83 // Different token => invalid signature
84 resp = call(router, "GET", "http://example/"+locSigned, "badtoken", nil, nil)
85 c.Check(resp.Code, Equals, http.StatusBadRequest)
86 c.Check(resp.Body.String(), Equals, "invalid signature\n")
87 checkCORSHeaders(c, resp.Header())
90 resp = call(router, "GET", "http://example/"+locSigned, arvadostest.ActiveTokenV2, nil, nil)
91 c.Check(resp.Code, Equals, http.StatusOK)
92 c.Check(resp.Body.String(), Equals, "foo")
93 checkCORSHeaders(c, resp.Header())
96 resp = call(router, "HEAD", "http://example/"+locSigned, arvadostest.ActiveTokenV2, nil, nil)
97 c.Check(resp.Code, Equals, http.StatusOK)
98 c.Check(resp.Result().ContentLength, Equals, int64(3))
99 c.Check(resp.Body.String(), Equals, "")
100 checkCORSHeaders(c, resp.Header())
103 // As a special case we allow HEAD requests that only provide a hash
104 // without a size hint. This accommodates uses of keep-block-check
105 // where it's inconvenient to attach size hints to known hashes.
107 // GET requests must provide a size hint -- otherwise we can't
108 // propagate a checksum mismatch error.
109 func (s *routerSuite) TestBlockRead_NoSizeHint(c *C) {
110 s.cluster.Collections.BlobSigning = true
111 router, cancel := testRouter(c, s.cluster, nil)
113 err := router.keepstore.mountsW[0].BlockWrite(context.Background(), fooHash, []byte("foo"))
117 hashSigned := router.keepstore.signLocator(arvadostest.ActiveTokenV2, fooHash)
118 resp := call(router, "GET", "http://example/"+hashSigned, arvadostest.ActiveTokenV2, nil, nil)
119 c.Check(resp.Code, Equals, http.StatusMethodNotAllowed)
121 resp = call(router, "HEAD", "http://example/"+fooHash, "", nil, nil)
122 c.Check(resp.Code, Equals, http.StatusUnauthorized)
123 resp = call(router, "HEAD", "http://example/"+fooHash+"+3", "", nil, nil)
124 c.Check(resp.Code, Equals, http.StatusUnauthorized)
126 s.cluster.Collections.BlobSigning = false
127 router, cancel = testRouter(c, s.cluster, nil)
129 err = router.keepstore.mountsW[0].BlockWrite(context.Background(), fooHash, []byte("foo"))
132 resp = call(router, "GET", "http://example/"+fooHash, "", nil, nil)
133 c.Check(resp.Code, Equals, http.StatusMethodNotAllowed)
135 resp = call(router, "HEAD", "http://example/"+fooHash, "", nil, nil)
136 c.Check(resp.Code, Equals, http.StatusOK)
137 c.Check(resp.Body.String(), Equals, "")
138 c.Check(resp.Result().ContentLength, Equals, int64(3))
139 c.Check(resp.Header().Get("Content-Length"), Equals, "3")
142 // By the time we discover the checksum mismatch, it's too late to
143 // change the response code, but the expected block size is given in
144 // the Content-Length response header, so a generic http client can
145 // detect the problem.
146 func (s *routerSuite) TestBlockRead_ChecksumMismatch(c *C) {
147 router, cancel := testRouter(c, s.cluster, nil)
150 gooddata := make([]byte, 10_000_000)
152 hash := fmt.Sprintf("%x", md5.Sum(gooddata))
153 locSigned := router.keepstore.signLocator(arvadostest.ActiveTokenV2, fmt.Sprintf("%s+%d", hash, len(gooddata)))
155 for _, baddata := range [][]byte{
157 make([]byte, len(gooddata)),
158 make([]byte, len(gooddata)-1),
159 make([]byte, len(gooddata)+1),
160 make([]byte, len(gooddata)*2),
162 c.Logf("=== baddata len %d", len(baddata))
163 err := router.keepstore.mountsW[0].BlockWrite(context.Background(), hash, baddata)
166 resp := call(router, "GET", "http://example/"+locSigned, arvadostest.ActiveTokenV2, nil, nil)
167 if !c.Check(resp.Code, Equals, http.StatusOK) {
168 c.Logf("resp.Body: %s", resp.Body.String())
170 c.Check(resp.Body.Len(), Not(Equals), len(gooddata))
171 c.Check(resp.Result().ContentLength, Equals, int64(len(gooddata)))
172 checkCORSHeaders(c, resp.Header())
174 resp = call(router, "HEAD", "http://example/"+locSigned, arvadostest.ActiveTokenV2, nil, nil)
175 c.Check(resp.Code, Equals, http.StatusBadGateway)
176 checkCORSHeaders(c, resp.Header())
178 hashSigned := router.keepstore.signLocator(arvadostest.ActiveTokenV2, hash)
179 resp = call(router, "HEAD", "http://example/"+hashSigned, arvadostest.ActiveTokenV2, nil, nil)
180 c.Check(resp.Code, Equals, http.StatusBadGateway)
181 checkCORSHeaders(c, resp.Header())
185 func (s *routerSuite) TestBlockWrite(c *C) {
186 router, cancel := testRouter(c, s.cluster, nil)
189 resp := call(router, "PUT", "http://example/"+fooHash, arvadostest.ActiveTokenV2, []byte("foo"), nil)
190 c.Check(resp.Code, Equals, http.StatusOK)
191 checkCORSHeaders(c, resp.Header())
192 locator := strings.TrimSpace(resp.Body.String())
194 resp = call(router, "GET", "http://example/"+locator, arvadostest.ActiveTokenV2, nil, nil)
195 c.Check(resp.Code, Equals, http.StatusOK)
196 c.Check(resp.Body.String(), Equals, "foo")
199 func (s *routerSuite) TestBlockWrite_Headers(c *C) {
200 router, cancel := testRouter(c, s.cluster, nil)
203 resp := call(router, "PUT", "http://example/"+fooHash, arvadostest.ActiveTokenV2, []byte("foo"), http.Header{"X-Keep-Desired-Replicas": []string{"2"}})
204 c.Check(resp.Code, Equals, http.StatusOK)
205 c.Check(resp.Header().Get("X-Keep-Replicas-Stored"), Equals, "1")
206 c.Check(sortCommaSeparated(resp.Header().Get("X-Keep-Storage-Classes-Confirmed")), Equals, "testclass1=1")
208 resp = call(router, "PUT", "http://example/"+fooHash, arvadostest.ActiveTokenV2, []byte("foo"), http.Header{"X-Keep-Storage-Classes": []string{"testclass1"}})
209 c.Check(resp.Code, Equals, http.StatusOK)
210 c.Check(resp.Header().Get("X-Keep-Replicas-Stored"), Equals, "1")
211 c.Check(resp.Header().Get("X-Keep-Storage-Classes-Confirmed"), Equals, "testclass1=1")
213 resp = call(router, "PUT", "http://example/"+fooHash, arvadostest.ActiveTokenV2, []byte("foo"), http.Header{"X-Keep-Storage-Classes": []string{" , testclass2 , "}})
214 c.Check(resp.Code, Equals, http.StatusOK)
215 c.Check(resp.Header().Get("X-Keep-Replicas-Stored"), Equals, "1")
216 c.Check(resp.Header().Get("X-Keep-Storage-Classes-Confirmed"), Equals, "testclass2=1")
219 func sortCommaSeparated(s string) string {
220 slice := strings.Split(s, ", ")
222 return strings.Join(slice, ", ")
225 func (s *routerSuite) TestBlockTouch(c *C) {
226 router, cancel := testRouter(c, s.cluster, nil)
229 resp := call(router, "TOUCH", "http://example/"+fooHash+"+3", s.cluster.SystemRootToken, nil, nil)
230 c.Check(resp.Code, Equals, http.StatusNotFound)
232 vol0 := router.keepstore.mountsW[0].volume.(*stubVolume)
233 err := vol0.BlockWrite(context.Background(), fooHash, []byte("foo"))
235 vol1 := router.keepstore.mountsW[1].volume.(*stubVolume)
236 err = vol1.BlockWrite(context.Background(), fooHash, []byte("foo"))
240 resp = call(router, "TOUCH", "http://example/"+fooHash+"+3", s.cluster.SystemRootToken, nil, nil)
241 c.Check(resp.Code, Equals, http.StatusOK)
244 // Unauthorized request is a no-op
245 resp = call(router, "TOUCH", "http://example/"+fooHash+"+3", arvadostest.ActiveTokenV2, nil, nil)
246 c.Check(resp.Code, Equals, http.StatusForbidden)
248 // Volume 0 mtime should be updated
249 t, err := vol0.Mtime(fooHash)
251 c.Check(t.After(t1), Equals, true)
252 c.Check(t.Before(t2), Equals, true)
254 // Volume 1 mtime should not be updated
255 t, err = vol1.Mtime(fooHash)
257 c.Check(t.Before(t1), Equals, true)
259 err = vol0.BlockTrash(fooHash)
261 err = vol1.BlockTrash(fooHash)
263 resp = call(router, "TOUCH", "http://example/"+fooHash+"+3", s.cluster.SystemRootToken, nil, nil)
264 c.Check(resp.Code, Equals, http.StatusNotFound)
267 func (s *routerSuite) TestBlockTrash(c *C) {
268 router, cancel := testRouter(c, s.cluster, nil)
271 vol0 := router.keepstore.mountsW[0].volume.(*stubVolume)
272 err := vol0.BlockWrite(context.Background(), fooHash, []byte("foo"))
274 err = vol0.blockTouchWithTime(fooHash, time.Now().Add(-s.cluster.Collections.BlobSigningTTL.Duration()))
276 resp := call(router, "DELETE", "http://example/"+fooHash+"+3", s.cluster.SystemRootToken, nil, nil)
277 c.Check(resp.Code, Equals, http.StatusOK)
278 c.Check(vol0.stubLog.String(), Matches, `(?ms).* trash .*`)
279 err = vol0.BlockRead(context.Background(), fooHash, brdiscard)
280 c.Assert(err, Equals, os.ErrNotExist)
283 func (s *routerSuite) TestBlockUntrash(c *C) {
284 router, cancel := testRouter(c, s.cluster, nil)
287 vol0 := router.keepstore.mountsW[0].volume.(*stubVolume)
288 err := vol0.BlockWrite(context.Background(), fooHash, []byte("foo"))
290 err = vol0.BlockTrash(fooHash)
292 err = vol0.BlockRead(context.Background(), fooHash, brdiscard)
293 c.Assert(err, Equals, os.ErrNotExist)
294 resp := call(router, "PUT", "http://example/untrash/"+fooHash+"+3", s.cluster.SystemRootToken, nil, nil)
295 c.Check(resp.Code, Equals, http.StatusOK)
296 c.Check(vol0.stubLog.String(), Matches, `(?ms).* untrash .*`)
297 err = vol0.BlockRead(context.Background(), fooHash, brdiscard)
301 func (s *routerSuite) TestBadRequest(c *C) {
302 router, cancel := testRouter(c, s.cluster, nil)
305 for _, trial := range []string{
308 "GET /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcdefg",
310 "GET /mounts/blocks/123",
313 "GET /debug.json", // old endpoint, no longer exists
314 "GET /status.json", // old endpoint, no longer exists
316 "POST /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
321 c.Logf("=== %s", trial)
322 methodpath := strings.Split(trial, " ")
323 req := httptest.NewRequest(methodpath[0], "http://example"+methodpath[1], nil)
324 resp := httptest.NewRecorder()
325 router.ServeHTTP(resp, req)
326 c.Check(resp.Code, Equals, http.StatusBadRequest)
330 func (s *routerSuite) TestRequireAdminMgtToken(c *C) {
331 router, cancel := testRouter(c, s.cluster, nil)
334 for _, token := range []string{"badtoken", ""} {
335 for _, trial := range []string{
341 "PUT /untrash/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
343 c.Logf("=== %s", trial)
344 methodpath := strings.Split(trial, " ")
345 req := httptest.NewRequest(methodpath[0], "http://example"+methodpath[1], nil)
347 req.Header.Set("Authorization", "Bearer "+token)
349 resp := httptest.NewRecorder()
350 router.ServeHTTP(resp, req)
352 c.Check(resp.Code, Equals, http.StatusUnauthorized)
354 c.Check(resp.Code, Equals, http.StatusForbidden)
358 req := httptest.NewRequest("TOUCH", "http://example/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", nil)
359 resp := httptest.NewRecorder()
360 router.ServeHTTP(resp, req)
361 c.Check(resp.Code, Equals, http.StatusUnauthorized)
364 func (s *routerSuite) TestVolumeErrorStatusCode(c *C) {
365 router, cancel := testRouter(c, s.cluster, nil)
367 router.keepstore.mountsW[0].volume.(*stubVolume).blockRead = func(_ context.Context, hash string, w io.WriterAt) error {
368 return httpserver.ErrorWithStatus(errors.New("test error"), http.StatusBadGateway)
371 // To test whether we fall back to volume 1 after volume 0
372 // returns an error, we need to use a block whose rendezvous
373 // order has volume 0 first. Luckily "bar" is such a block.
374 c.Assert(router.keepstore.rendezvous(barHash, router.keepstore.mountsR)[0].UUID, DeepEquals, router.keepstore.mountsR[0].UUID)
376 locSigned := router.keepstore.signLocator(arvadostest.ActiveTokenV2, barHash+"+3")
378 // Volume 0 fails with an error that specifies an HTTP status
379 // code, so that code should be propagated to caller.
380 resp := call(router, "GET", "http://example/"+locSigned, arvadostest.ActiveTokenV2, nil, nil)
381 c.Check(resp.Code, Equals, http.StatusBadGateway)
382 c.Check(resp.Body.String(), Equals, "test error\n")
384 router.keepstore.mountsW[0].volume.(*stubVolume).blockRead = func(_ context.Context, hash string, w io.WriterAt) error {
385 return errors.New("no http status provided")
387 resp = call(router, "GET", "http://example/"+locSigned, arvadostest.ActiveTokenV2, nil, nil)
388 c.Check(resp.Code, Equals, http.StatusInternalServerError)
389 c.Check(resp.Body.String(), Equals, "no http status provided\n")
391 c.Assert(router.keepstore.mountsW[1].volume.BlockWrite(context.Background(), barHash, []byte("bar")), IsNil)
393 // If the requested block is available on the second volume,
394 // it doesn't matter that the first volume failed.
395 resp = call(router, "GET", "http://example/"+locSigned, arvadostest.ActiveTokenV2, nil, nil)
396 c.Check(resp.Code, Equals, http.StatusOK)
397 c.Check(resp.Body.String(), Equals, "bar")
400 func (s *routerSuite) TestIndex(c *C) {
401 router, cancel := testRouter(c, s.cluster, nil)
404 resp := call(router, "GET", "http://example/index", s.cluster.SystemRootToken, nil, nil)
405 c.Check(resp.Code, Equals, http.StatusOK)
406 c.Check(resp.Body.String(), Equals, "\n")
408 resp = call(router, "GET", "http://example/index?prefix=fff", s.cluster.SystemRootToken, nil, nil)
409 c.Check(resp.Code, Equals, http.StatusOK)
410 c.Check(resp.Body.String(), Equals, "\n")
412 t0 := time.Now().Add(-time.Hour)
413 vol0 := router.keepstore.mounts["zzzzz-nyw5e-000000000000000"].volume.(*stubVolume)
414 err := vol0.BlockWrite(context.Background(), fooHash, []byte("foo"))
416 err = vol0.blockTouchWithTime(fooHash, t0)
418 err = vol0.BlockWrite(context.Background(), barHash, []byte("bar"))
420 err = vol0.blockTouchWithTime(barHash, t0)
422 t1 := time.Now().Add(-time.Minute)
423 vol1 := router.keepstore.mounts["zzzzz-nyw5e-111111111111111"].volume.(*stubVolume)
424 err = vol1.BlockWrite(context.Background(), barHash, []byte("bar"))
426 err = vol1.blockTouchWithTime(barHash, t1)
429 for _, path := range []string{
432 "/index/?prefix=acb",
433 "/mounts/zzzzz-nyw5e-000000000000000/blocks?prefix=acb",
434 "/mounts/zzzzz-nyw5e-000000000000000/blocks/?prefix=acb",
435 "/mounts/zzzzz-nyw5e-000000000000000/blocks/acb",
437 c.Logf("=== %s", path)
438 resp = call(router, "GET", "http://example"+path, s.cluster.SystemRootToken, nil, nil)
439 c.Check(resp.Code, Equals, http.StatusOK)
440 c.Check(resp.Body.String(), Equals, fooHash+"+3 "+fmt.Sprintf("%d", t0.UnixNano())+"\n\n")
443 for _, path := range []string{
448 c.Logf("=== %s", path)
449 resp = call(router, "GET", "http://example"+path, s.cluster.SystemRootToken, nil, nil)
450 c.Check(resp.Code, Equals, http.StatusOK)
451 c.Check(resp.Body.String(), Equals, ""+
452 barHash+"+3 "+fmt.Sprintf("%d", t0.UnixNano())+"\n"+
453 barHash+"+3 "+fmt.Sprintf("%d", t1.UnixNano())+"\n\n")
456 for _, path := range []string{
457 "/mounts/zzzzz-nyw5e-111111111111111/blocks",
458 "/mounts/zzzzz-nyw5e-111111111111111/blocks/",
459 "/mounts/zzzzz-nyw5e-111111111111111/blocks?prefix=37",
460 "/mounts/zzzzz-nyw5e-111111111111111/blocks/?prefix=37",
461 "/mounts/zzzzz-nyw5e-111111111111111/blocks/37",
463 c.Logf("=== %s", path)
464 resp = call(router, "GET", "http://example"+path, s.cluster.SystemRootToken, nil, nil)
465 c.Check(resp.Code, Equals, http.StatusOK)
466 c.Check(resp.Body.String(), Equals, barHash+"+3 "+fmt.Sprintf("%d", t1.UnixNano())+"\n\n")
469 for _, path := range []string{
475 c.Logf("=== %s", path)
476 resp = call(router, "GET", "http://example"+path, s.cluster.SystemRootToken, nil, nil)
477 c.Check(resp.Code, Equals, http.StatusOK)
478 c.Check(strings.Split(resp.Body.String(), "\n"), HasLen, 5)
482 // Check that the context passed to a volume method gets cancelled
483 // when the http client hangs up.
484 func (s *routerSuite) TestCancelOnDisconnect(c *C) {
485 router, cancel := testRouter(c, s.cluster, nil)
488 unblock := make(chan struct{})
489 router.keepstore.mountsW[0].volume.(*stubVolume).blockRead = func(ctx context.Context, hash string, w io.WriterAt) error {
491 c.Check(ctx.Err(), NotNil)
495 time.Sleep(time.Second / 10)
499 locSigned := router.keepstore.signLocator(arvadostest.ActiveTokenV2, fooHash+"+3")
500 ctx, cancel := context.WithCancel(context.Background())
502 req, err := http.NewRequestWithContext(ctx, "GET", "http://example/"+locSigned, nil)
504 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveTokenV2)
505 resp := httptest.NewRecorder()
506 router.ServeHTTP(resp, req)
507 c.Check(resp.Code, Equals, 499)
510 func (s *routerSuite) TestCORSPreflight(c *C) {
511 router, cancel := testRouter(c, s.cluster, nil)
514 for _, path := range []string{"/", "/whatever", "/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+123"} {
515 c.Logf("=== %s", path)
516 resp := call(router, http.MethodOptions, "http://example"+path, arvadostest.ActiveTokenV2, nil, nil)
517 c.Check(resp.Code, Equals, http.StatusOK)
518 c.Check(resp.Body.String(), Equals, "")
519 checkCORSHeaders(c, resp.Header())
523 func call(handler http.Handler, method, path, tok string, body []byte, hdr http.Header) *httptest.ResponseRecorder {
524 resp := httptest.NewRecorder()
525 req, err := http.NewRequest(method, path, bytes.NewReader(body))
530 req.Header.Set(k, hdr.Get(k))
533 req.Header.Set("Authorization", "Bearer "+tok)
535 handler.ServeHTTP(resp, req)
539 func checkCORSHeaders(c *C, h http.Header) {
540 c.Check(h.Get("Access-Control-Allow-Methods"), Equals, "GET, HEAD, PUT, OPTIONS")
541 c.Check(h.Get("Access-Control-Allow-Origin"), Equals, "*")
542 c.Check(h.Get("Access-Control-Allow-Headers"), Equals, "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas, X-Keep-Signature, X-Keep-Storage-Classes")
543 c.Check(h.Get("Access-Control-Expose-Headers"), Equals, "X-Keep-Locator, X-Keep-Replicas-Stored, X-Keep-Storage-Classes-Confirmed")