8191466af634da400e94cf35b25ac6363311a196
[arvados.git] / services / keepstore / handler_test.go
1 // Tests for Keep HTTP handlers:
2 //
3 //     GetBlockHandler
4 //     PutBlockHandler
5 //     IndexHandler
6 //
7 // The HTTP handlers are responsible for enforcing permission policy,
8 // so these tests must exercise all possible permission permutations.
9
10 package main
11
12 import (
13         "bytes"
14         "encoding/json"
15         "fmt"
16         "net/http"
17         "net/http/httptest"
18         "os"
19         "regexp"
20         "strings"
21         "testing"
22         "time"
23 )
24
25 // A RequestTester represents the parameters for an HTTP request to
26 // be issued on behalf of a unit test.
27 type RequestTester struct {
28         uri         string
29         apiToken    string
30         method      string
31         requestBody []byte
32 }
33
34 // Test GetBlockHandler on the following situations:
35 //   - permissions off, unauthenticated request, unsigned locator
36 //   - permissions on, authenticated request, signed locator
37 //   - permissions on, authenticated request, unsigned locator
38 //   - permissions on, unauthenticated request, signed locator
39 //   - permissions on, authenticated request, expired locator
40 //
41 func TestGetHandler(t *testing.T) {
42         defer teardown()
43
44         // Prepare two test Keep volumes. Our block is stored on the second volume.
45         KeepVM = MakeTestVolumeManager(2)
46         defer KeepVM.Close()
47
48         vols := KeepVM.AllWritable()
49         if err := vols[0].Put(TEST_HASH, TEST_BLOCK); err != nil {
50                 t.Error(err)
51         }
52
53         // Create locators for testing.
54         // Turn on permission settings so we can generate signed locators.
55         enforcePermissions = true
56         PermissionSecret = []byte(known_key)
57         blob_signature_ttl = 300 * time.Second
58
59         var (
60                 unsignedLocator  = "/" + TEST_HASH
61                 validTimestamp   = time.Now().Add(blob_signature_ttl)
62                 expiredTimestamp = time.Now().Add(-time.Hour)
63                 signedLocator    = "/" + SignLocator(TEST_HASH, known_token, validTimestamp)
64                 expiredLocator   = "/" + SignLocator(TEST_HASH, known_token, expiredTimestamp)
65         )
66
67         // -----------------
68         // Test unauthenticated request with permissions off.
69         enforcePermissions = false
70
71         // Unauthenticated request, unsigned locator
72         // => OK
73         response := IssueRequest(
74                 &RequestTester{
75                         method: "GET",
76                         uri:    unsignedLocator,
77                 })
78         ExpectStatusCode(t,
79                 "Unauthenticated request, unsigned locator", http.StatusOK, response)
80         ExpectBody(t,
81                 "Unauthenticated request, unsigned locator",
82                 string(TEST_BLOCK),
83                 response)
84
85         receivedLen := response.Header().Get("Content-Length")
86         expectedLen := fmt.Sprintf("%d", len(TEST_BLOCK))
87         if receivedLen != expectedLen {
88                 t.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
89         }
90
91         // ----------------
92         // Permissions: on.
93         enforcePermissions = true
94
95         // Authenticated request, signed locator
96         // => OK
97         response = IssueRequest(&RequestTester{
98                 method:   "GET",
99                 uri:      signedLocator,
100                 apiToken: known_token,
101         })
102         ExpectStatusCode(t,
103                 "Authenticated request, signed locator", http.StatusOK, response)
104         ExpectBody(t,
105                 "Authenticated request, signed locator", string(TEST_BLOCK), response)
106
107         receivedLen = response.Header().Get("Content-Length")
108         expectedLen = fmt.Sprintf("%d", len(TEST_BLOCK))
109         if receivedLen != expectedLen {
110                 t.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
111         }
112
113         // Authenticated request, unsigned locator
114         // => PermissionError
115         response = IssueRequest(&RequestTester{
116                 method:   "GET",
117                 uri:      unsignedLocator,
118                 apiToken: known_token,
119         })
120         ExpectStatusCode(t, "unsigned locator", PermissionError.HTTPCode, response)
121
122         // Unauthenticated request, signed locator
123         // => PermissionError
124         response = IssueRequest(&RequestTester{
125                 method: "GET",
126                 uri:    signedLocator,
127         })
128         ExpectStatusCode(t,
129                 "Unauthenticated request, signed locator",
130                 PermissionError.HTTPCode, response)
131
132         // Authenticated request, expired locator
133         // => ExpiredError
134         response = IssueRequest(&RequestTester{
135                 method:   "GET",
136                 uri:      expiredLocator,
137                 apiToken: known_token,
138         })
139         ExpectStatusCode(t,
140                 "Authenticated request, expired locator",
141                 ExpiredError.HTTPCode, response)
142 }
143
144 // Test PutBlockHandler on the following situations:
145 //   - no server key
146 //   - with server key, authenticated request, unsigned locator
147 //   - with server key, unauthenticated request, unsigned locator
148 //
149 func TestPutHandler(t *testing.T) {
150         defer teardown()
151
152         // Prepare two test Keep volumes.
153         KeepVM = MakeTestVolumeManager(2)
154         defer KeepVM.Close()
155
156         // --------------
157         // No server key.
158
159         // Unauthenticated request, no server key
160         // => OK (unsigned response)
161         unsignedLocator := "/" + TEST_HASH
162         response := IssueRequest(
163                 &RequestTester{
164                         method:      "PUT",
165                         uri:         unsignedLocator,
166                         requestBody: TEST_BLOCK,
167                 })
168
169         ExpectStatusCode(t,
170                 "Unauthenticated request, no server key", http.StatusOK, response)
171         ExpectBody(t,
172                 "Unauthenticated request, no server key",
173                 TEST_HASH_PUT_RESPONSE, response)
174
175         // ------------------
176         // With a server key.
177
178         PermissionSecret = []byte(known_key)
179         blob_signature_ttl = 300 * time.Second
180
181         // When a permission key is available, the locator returned
182         // from an authenticated PUT request will be signed.
183
184         // Authenticated PUT, signed locator
185         // => OK (signed response)
186         response = IssueRequest(
187                 &RequestTester{
188                         method:      "PUT",
189                         uri:         unsignedLocator,
190                         requestBody: TEST_BLOCK,
191                         apiToken:    known_token,
192                 })
193
194         ExpectStatusCode(t,
195                 "Authenticated PUT, signed locator, with server key",
196                 http.StatusOK, response)
197         responseLocator := strings.TrimSpace(response.Body.String())
198         if VerifySignature(responseLocator, known_token) != nil {
199                 t.Errorf("Authenticated PUT, signed locator, with server key:\n"+
200                         "response '%s' does not contain a valid signature",
201                         responseLocator)
202         }
203
204         // Unauthenticated PUT, unsigned locator
205         // => OK
206         response = IssueRequest(
207                 &RequestTester{
208                         method:      "PUT",
209                         uri:         unsignedLocator,
210                         requestBody: TEST_BLOCK,
211                 })
212
213         ExpectStatusCode(t,
214                 "Unauthenticated PUT, unsigned locator, with server key",
215                 http.StatusOK, response)
216         ExpectBody(t,
217                 "Unauthenticated PUT, unsigned locator, with server key",
218                 TEST_HASH_PUT_RESPONSE, response)
219 }
220
221 func TestPutAndDeleteSkipReadonlyVolumes(t *testing.T) {
222         defer teardown()
223         data_manager_token = "fake-data-manager-token"
224         vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
225         vols[0].Readonly = true
226         KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
227         defer KeepVM.Close()
228         IssueRequest(
229                 &RequestTester{
230                         method:      "PUT",
231                         uri:         "/" + TEST_HASH,
232                         requestBody: TEST_BLOCK,
233                 })
234         defer func(orig bool) {
235                 never_delete = orig
236         }(never_delete)
237         never_delete = false
238         IssueRequest(
239                 &RequestTester{
240                         method:      "DELETE",
241                         uri:         "/" + TEST_HASH,
242                         requestBody: TEST_BLOCK,
243                         apiToken:    data_manager_token,
244                 })
245         type expect struct {
246                 volnum    int
247                 method    string
248                 callcount int
249         }
250         for _, e := range []expect{
251                 {0, "Get", 0},
252                 {0, "Compare", 0},
253                 {0, "Touch", 0},
254                 {0, "Put", 0},
255                 {0, "Delete", 0},
256                 {1, "Get", 0},
257                 {1, "Compare", 1},
258                 {1, "Touch", 1},
259                 {1, "Put", 1},
260                 {1, "Delete", 1},
261         } {
262                 if calls := vols[e.volnum].CallCount(e.method); calls != e.callcount {
263                         t.Errorf("Got %d %s() on vol %d, expect %d", calls, e.method, e.volnum, e.callcount)
264                 }
265         }
266 }
267
268 // Test /index requests:
269 //   - unauthenticated /index request
270 //   - unauthenticated /index/prefix request
271 //   - authenticated   /index request        | non-superuser
272 //   - authenticated   /index/prefix request | non-superuser
273 //   - authenticated   /index request        | superuser
274 //   - authenticated   /index/prefix request | superuser
275 //
276 // The only /index requests that should succeed are those issued by the
277 // superuser. They should pass regardless of the value of enforcePermissions.
278 //
279 func TestIndexHandler(t *testing.T) {
280         defer teardown()
281
282         // Set up Keep volumes and populate them.
283         // Include multiple blocks on different volumes, and
284         // some metadata files (which should be omitted from index listings)
285         KeepVM = MakeTestVolumeManager(2)
286         defer KeepVM.Close()
287
288         vols := KeepVM.AllWritable()
289         vols[0].Put(TEST_HASH, TEST_BLOCK)
290         vols[1].Put(TEST_HASH_2, TEST_BLOCK_2)
291         vols[0].Put(TEST_HASH+".meta", []byte("metadata"))
292         vols[1].Put(TEST_HASH_2+".meta", []byte("metadata"))
293
294         data_manager_token = "DATA MANAGER TOKEN"
295
296         unauthenticatedReq := &RequestTester{
297                 method: "GET",
298                 uri:    "/index",
299         }
300         authenticatedReq := &RequestTester{
301                 method:   "GET",
302                 uri:      "/index",
303                 apiToken: known_token,
304         }
305         superuserReq := &RequestTester{
306                 method:   "GET",
307                 uri:      "/index",
308                 apiToken: data_manager_token,
309         }
310         unauthPrefixReq := &RequestTester{
311                 method: "GET",
312                 uri:    "/index/" + TEST_HASH[0:3],
313         }
314         authPrefixReq := &RequestTester{
315                 method:   "GET",
316                 uri:      "/index/" + TEST_HASH[0:3],
317                 apiToken: known_token,
318         }
319         superuserPrefixReq := &RequestTester{
320                 method:   "GET",
321                 uri:      "/index/" + TEST_HASH[0:3],
322                 apiToken: data_manager_token,
323         }
324
325         // -------------------------------------------------------------
326         // Only the superuser should be allowed to issue /index requests.
327
328         // ---------------------------
329         // enforcePermissions enabled
330         // This setting should not affect tests passing.
331         enforcePermissions = true
332
333         // unauthenticated /index request
334         // => UnauthorizedError
335         response := IssueRequest(unauthenticatedReq)
336         ExpectStatusCode(t,
337                 "enforcePermissions on, unauthenticated request",
338                 UnauthorizedError.HTTPCode,
339                 response)
340
341         // unauthenticated /index/prefix request
342         // => UnauthorizedError
343         response = IssueRequest(unauthPrefixReq)
344         ExpectStatusCode(t,
345                 "permissions on, unauthenticated /index/prefix request",
346                 UnauthorizedError.HTTPCode,
347                 response)
348
349         // authenticated /index request, non-superuser
350         // => UnauthorizedError
351         response = IssueRequest(authenticatedReq)
352         ExpectStatusCode(t,
353                 "permissions on, authenticated request, non-superuser",
354                 UnauthorizedError.HTTPCode,
355                 response)
356
357         // authenticated /index/prefix request, non-superuser
358         // => UnauthorizedError
359         response = IssueRequest(authPrefixReq)
360         ExpectStatusCode(t,
361                 "permissions on, authenticated /index/prefix request, non-superuser",
362                 UnauthorizedError.HTTPCode,
363                 response)
364
365         // superuser /index request
366         // => OK
367         response = IssueRequest(superuserReq)
368         ExpectStatusCode(t,
369                 "permissions on, superuser request",
370                 http.StatusOK,
371                 response)
372
373         // ----------------------------
374         // enforcePermissions disabled
375         // Valid Request should still pass.
376         enforcePermissions = false
377
378         // superuser /index request
379         // => OK
380         response = IssueRequest(superuserReq)
381         ExpectStatusCode(t,
382                 "permissions on, superuser request",
383                 http.StatusOK,
384                 response)
385
386         expected := `^` + TEST_HASH + `\+\d+ \d+\n` +
387                 TEST_HASH_2 + `\+\d+ \d+\n\n$`
388         match, _ := regexp.MatchString(expected, response.Body.String())
389         if !match {
390                 t.Errorf(
391                         "permissions on, superuser request: expected %s, got:\n%s",
392                         expected, response.Body.String())
393         }
394
395         // superuser /index/prefix request
396         // => OK
397         response = IssueRequest(superuserPrefixReq)
398         ExpectStatusCode(t,
399                 "permissions on, superuser request",
400                 http.StatusOK,
401                 response)
402
403         expected = `^` + TEST_HASH + `\+\d+ \d+\n\n$`
404         match, _ = regexp.MatchString(expected, response.Body.String())
405         if !match {
406                 t.Errorf(
407                         "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
408                         expected, response.Body.String())
409         }
410 }
411
412 // TestDeleteHandler
413 //
414 // Cases tested:
415 //
416 //   With no token and with a non-data-manager token:
417 //   * Delete existing block
418 //     (test for 403 Forbidden, confirm block not deleted)
419 //
420 //   With data manager token:
421 //
422 //   * Delete existing block
423 //     (test for 200 OK, response counts, confirm block deleted)
424 //
425 //   * Delete nonexistent block
426 //     (test for 200 OK, response counts)
427 //
428 //   TODO(twp):
429 //
430 //   * Delete block on read-only and read-write volume
431 //     (test for 200 OK, response with copies_deleted=1,
432 //     copies_failed=1, confirm block deleted only on r/w volume)
433 //
434 //   * Delete block on read-only volume only
435 //     (test for 200 OK, response with copies_deleted=0, copies_failed=1,
436 //     confirm block not deleted)
437 //
438 func TestDeleteHandler(t *testing.T) {
439         defer teardown()
440
441         // Set up Keep volumes and populate them.
442         // Include multiple blocks on different volumes, and
443         // some metadata files (which should be omitted from index listings)
444         KeepVM = MakeTestVolumeManager(2)
445         defer KeepVM.Close()
446
447         vols := KeepVM.AllWritable()
448         vols[0].Put(TEST_HASH, TEST_BLOCK)
449
450         // Explicitly set the blob_signature_ttl to 0 for these
451         // tests, to ensure the MockVolume deletes the blocks
452         // even though they have just been created.
453         blob_signature_ttl = time.Duration(0)
454
455         var userToken = "NOT DATA MANAGER TOKEN"
456         data_manager_token = "DATA MANAGER TOKEN"
457
458         never_delete = false
459
460         unauthReq := &RequestTester{
461                 method: "DELETE",
462                 uri:    "/" + TEST_HASH,
463         }
464
465         userReq := &RequestTester{
466                 method:   "DELETE",
467                 uri:      "/" + TEST_HASH,
468                 apiToken: userToken,
469         }
470
471         superuserExistingBlockReq := &RequestTester{
472                 method:   "DELETE",
473                 uri:      "/" + TEST_HASH,
474                 apiToken: data_manager_token,
475         }
476
477         superuserNonexistentBlockReq := &RequestTester{
478                 method:   "DELETE",
479                 uri:      "/" + TEST_HASH_2,
480                 apiToken: data_manager_token,
481         }
482
483         // Unauthenticated request returns PermissionError.
484         var response *httptest.ResponseRecorder
485         response = IssueRequest(unauthReq)
486         ExpectStatusCode(t,
487                 "unauthenticated request",
488                 PermissionError.HTTPCode,
489                 response)
490
491         // Authenticated non-admin request returns PermissionError.
492         response = IssueRequest(userReq)
493         ExpectStatusCode(t,
494                 "authenticated non-admin request",
495                 PermissionError.HTTPCode,
496                 response)
497
498         // Authenticated admin request for nonexistent block.
499         type deletecounter struct {
500                 Deleted int `json:"copies_deleted"`
501                 Failed  int `json:"copies_failed"`
502         }
503         var responseDc, expectedDc deletecounter
504
505         response = IssueRequest(superuserNonexistentBlockReq)
506         ExpectStatusCode(t,
507                 "data manager request, nonexistent block",
508                 http.StatusNotFound,
509                 response)
510
511         // Authenticated admin request for existing block while never_delete is set.
512         never_delete = true
513         response = IssueRequest(superuserExistingBlockReq)
514         ExpectStatusCode(t,
515                 "authenticated request, existing block, method disabled",
516                 MethodDisabledError.HTTPCode,
517                 response)
518         never_delete = false
519
520         // Authenticated admin request for existing block.
521         response = IssueRequest(superuserExistingBlockReq)
522         ExpectStatusCode(t,
523                 "data manager request, existing block",
524                 http.StatusOK,
525                 response)
526         // Expect response {"copies_deleted":1,"copies_failed":0}
527         expectedDc = deletecounter{1, 0}
528         json.NewDecoder(response.Body).Decode(&responseDc)
529         if responseDc != expectedDc {
530                 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
531                         expectedDc, responseDc)
532         }
533         // Confirm the block has been deleted
534         _, err := vols[0].Get(TEST_HASH)
535         var blockDeleted = os.IsNotExist(err)
536         if !blockDeleted {
537                 t.Error("superuserExistingBlockReq: block not deleted")
538         }
539
540         // A DELETE request on a block newer than blob_signature_ttl
541         // should return success but leave the block on the volume.
542         vols[0].Put(TEST_HASH, TEST_BLOCK)
543         blob_signature_ttl = time.Hour
544
545         response = IssueRequest(superuserExistingBlockReq)
546         ExpectStatusCode(t,
547                 "data manager request, existing block",
548                 http.StatusOK,
549                 response)
550         // Expect response {"copies_deleted":1,"copies_failed":0}
551         expectedDc = deletecounter{1, 0}
552         json.NewDecoder(response.Body).Decode(&responseDc)
553         if responseDc != expectedDc {
554                 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
555                         expectedDc, responseDc)
556         }
557         // Confirm the block has NOT been deleted.
558         _, err = vols[0].Get(TEST_HASH)
559         if err != nil {
560                 t.Errorf("testing delete on new block: %s\n", err)
561         }
562 }
563
564 // TestPullHandler
565 //
566 // Test handling of the PUT /pull statement.
567 //
568 // Cases tested: syntactically valid and invalid pull lists, from the
569 // data manager and from unprivileged users:
570 //
571 //   1. Valid pull list from an ordinary user
572 //      (expected result: 401 Unauthorized)
573 //
574 //   2. Invalid pull request from an ordinary user
575 //      (expected result: 401 Unauthorized)
576 //
577 //   3. Valid pull request from the data manager
578 //      (expected result: 200 OK with request body "Received 3 pull
579 //      requests"
580 //
581 //   4. Invalid pull request from the data manager
582 //      (expected result: 400 Bad Request)
583 //
584 // Test that in the end, the pull manager received a good pull list with
585 // the expected number of requests.
586 //
587 // TODO(twp): test concurrency: launch 100 goroutines to update the
588 // pull list simultaneously.  Make sure that none of them return 400
589 // Bad Request and that pullq.GetList() returns a valid list.
590 //
591 func TestPullHandler(t *testing.T) {
592         defer teardown()
593
594         var userToken = "USER TOKEN"
595         data_manager_token = "DATA MANAGER TOKEN"
596
597         pullq = NewWorkQueue()
598
599         goodJSON := []byte(`[
600                 {
601                         "locator":"locator_with_two_servers",
602                         "servers":[
603                                 "server1",
604                                 "server2"
605                         ]
606                 },
607                 {
608                         "locator":"locator_with_no_servers",
609                         "servers":[]
610                 },
611                 {
612                         "locator":"",
613                         "servers":["empty_locator"]
614                 }
615         ]`)
616
617         badJSON := []byte(`{ "key":"I'm a little teapot" }`)
618
619         type pullTest struct {
620                 name         string
621                 req          RequestTester
622                 responseCode int
623                 responseBody string
624         }
625         var testcases = []pullTest{
626                 {
627                         "Valid pull list from an ordinary user",
628                         RequestTester{"/pull", userToken, "PUT", goodJSON},
629                         http.StatusUnauthorized,
630                         "Unauthorized\n",
631                 },
632                 {
633                         "Invalid pull request from an ordinary user",
634                         RequestTester{"/pull", userToken, "PUT", badJSON},
635                         http.StatusUnauthorized,
636                         "Unauthorized\n",
637                 },
638                 {
639                         "Valid pull request from the data manager",
640                         RequestTester{"/pull", data_manager_token, "PUT", goodJSON},
641                         http.StatusOK,
642                         "Received 3 pull requests\n",
643                 },
644                 {
645                         "Invalid pull request from the data manager",
646                         RequestTester{"/pull", data_manager_token, "PUT", badJSON},
647                         http.StatusBadRequest,
648                         "",
649                 },
650         }
651
652         for _, tst := range testcases {
653                 response := IssueRequest(&tst.req)
654                 ExpectStatusCode(t, tst.name, tst.responseCode, response)
655                 ExpectBody(t, tst.name, tst.responseBody, response)
656         }
657
658         // The Keep pull manager should have received one good list with 3
659         // requests on it.
660         for i := 0; i < 3; i++ {
661                 item := <-pullq.NextItem
662                 if _, ok := item.(PullRequest); !ok {
663                         t.Errorf("item %v could not be parsed as a PullRequest", item)
664                 }
665         }
666
667         expectChannelEmpty(t, pullq.NextItem)
668 }
669
670 // TestTrashHandler
671 //
672 // Test cases:
673 //
674 // Cases tested: syntactically valid and invalid trash lists, from the
675 // data manager and from unprivileged users:
676 //
677 //   1. Valid trash list from an ordinary user
678 //      (expected result: 401 Unauthorized)
679 //
680 //   2. Invalid trash list from an ordinary user
681 //      (expected result: 401 Unauthorized)
682 //
683 //   3. Valid trash list from the data manager
684 //      (expected result: 200 OK with request body "Received 3 trash
685 //      requests"
686 //
687 //   4. Invalid trash list from the data manager
688 //      (expected result: 400 Bad Request)
689 //
690 // Test that in the end, the trash collector received a good list
691 // trash list with the expected number of requests.
692 //
693 // TODO(twp): test concurrency: launch 100 goroutines to update the
694 // pull list simultaneously.  Make sure that none of them return 400
695 // Bad Request and that replica.Dump() returns a valid list.
696 //
697 func TestTrashHandler(t *testing.T) {
698         defer teardown()
699
700         var userToken = "USER TOKEN"
701         data_manager_token = "DATA MANAGER TOKEN"
702
703         trashq = NewWorkQueue()
704
705         goodJSON := []byte(`[
706                 {
707                         "locator":"block1",
708                         "block_mtime":1409082153
709                 },
710                 {
711                         "locator":"block2",
712                         "block_mtime":1409082153
713                 },
714                 {
715                         "locator":"block3",
716                         "block_mtime":1409082153
717                 }
718         ]`)
719
720         badJSON := []byte(`I am not a valid JSON string`)
721
722         type trashTest struct {
723                 name         string
724                 req          RequestTester
725                 responseCode int
726                 responseBody string
727         }
728
729         var testcases = []trashTest{
730                 {
731                         "Valid trash list from an ordinary user",
732                         RequestTester{"/trash", userToken, "PUT", goodJSON},
733                         http.StatusUnauthorized,
734                         "Unauthorized\n",
735                 },
736                 {
737                         "Invalid trash list from an ordinary user",
738                         RequestTester{"/trash", userToken, "PUT", badJSON},
739                         http.StatusUnauthorized,
740                         "Unauthorized\n",
741                 },
742                 {
743                         "Valid trash list from the data manager",
744                         RequestTester{"/trash", data_manager_token, "PUT", goodJSON},
745                         http.StatusOK,
746                         "Received 3 trash requests\n",
747                 },
748                 {
749                         "Invalid trash list from the data manager",
750                         RequestTester{"/trash", data_manager_token, "PUT", badJSON},
751                         http.StatusBadRequest,
752                         "",
753                 },
754         }
755
756         for _, tst := range testcases {
757                 response := IssueRequest(&tst.req)
758                 ExpectStatusCode(t, tst.name, tst.responseCode, response)
759                 ExpectBody(t, tst.name, tst.responseBody, response)
760         }
761
762         // The trash collector should have received one good list with 3
763         // requests on it.
764         for i := 0; i < 3; i++ {
765                 item := <-trashq.NextItem
766                 if _, ok := item.(TrashRequest); !ok {
767                         t.Errorf("item %v could not be parsed as a TrashRequest", item)
768                 }
769         }
770
771         expectChannelEmpty(t, trashq.NextItem)
772 }
773
774 // ====================
775 // Helper functions
776 // ====================
777
778 // IssueTestRequest executes an HTTP request described by rt, to a
779 // REST router.  It returns the HTTP response to the request.
780 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
781         response := httptest.NewRecorder()
782         body := bytes.NewReader(rt.requestBody)
783         req, _ := http.NewRequest(rt.method, rt.uri, body)
784         if rt.apiToken != "" {
785                 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
786         }
787         loggingRouter := MakeLoggingRESTRouter()
788         loggingRouter.ServeHTTP(response, req)
789         return response
790 }
791
792 // ExpectStatusCode checks whether a response has the specified status code,
793 // and reports a test failure if not.
794 func ExpectStatusCode(
795         t *testing.T,
796         testname string,
797         expectedStatus int,
798         response *httptest.ResponseRecorder) {
799         if response.Code != expectedStatus {
800                 t.Errorf("%s: expected status %d, got %+v",
801                         testname, expectedStatus, response)
802         }
803 }
804
805 func ExpectBody(
806         t *testing.T,
807         testname string,
808         expectedBody string,
809         response *httptest.ResponseRecorder) {
810         if expectedBody != "" && response.Body.String() != expectedBody {
811                 t.Errorf("%s: expected response body '%s', got %+v",
812                         testname, expectedBody, response)
813         }
814 }
815
816 // See #7121
817 func TestPutNeedsOnlyOneBuffer(t *testing.T) {
818         defer teardown()
819         KeepVM = MakeTestVolumeManager(1)
820         defer KeepVM.Close()
821
822         defer func(orig *bufferPool) {
823                 bufs = orig
824         }(bufs)
825         bufs = newBufferPool(1, BlockSize)
826
827         ok := make(chan struct{})
828         go func() {
829                 for i := 0; i < 2; i++ {
830                         response := IssueRequest(
831                                 &RequestTester{
832                                         method:      "PUT",
833                                         uri:         "/" + TEST_HASH,
834                                         requestBody: TEST_BLOCK,
835                                 })
836                         ExpectStatusCode(t,
837                                 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
838                 }
839                 ok <- struct{}{}
840         }()
841
842         select {
843         case <-ok:
844         case <-time.After(time.Second):
845                 t.Fatal("PUT deadlocks with maxBuffers==1")
846         }
847 }
848
849 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
850 // leak.
851 func TestPutHandlerNoBufferleak(t *testing.T) {
852         defer teardown()
853
854         // Prepare two test Keep volumes.
855         KeepVM = MakeTestVolumeManager(2)
856         defer KeepVM.Close()
857
858         ok := make(chan bool)
859         go func() {
860                 for i := 0; i < maxBuffers+1; i++ {
861                         // Unauthenticated request, no server key
862                         // => OK (unsigned response)
863                         unsignedLocator := "/" + TEST_HASH
864                         response := IssueRequest(
865                                 &RequestTester{
866                                         method:      "PUT",
867                                         uri:         unsignedLocator,
868                                         requestBody: TEST_BLOCK,
869                                 })
870                         ExpectStatusCode(t,
871                                 "TestPutHandlerBufferleak", http.StatusOK, response)
872                         ExpectBody(t,
873                                 "TestPutHandlerBufferleak",
874                                 TEST_HASH_PUT_RESPONSE, response)
875                 }
876                 ok <- true
877         }()
878         select {
879         case <-time.After(20 * time.Second):
880                 // If the buffer pool leaks, the test goroutine hangs.
881                 t.Fatal("test did not finish, assuming pool leaked")
882         case <-ok:
883         }
884 }
885
886 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
887 // leak.
888 func TestGetHandlerNoBufferleak(t *testing.T) {
889         defer teardown()
890
891         // Prepare two test Keep volumes. Our block is stored on the second volume.
892         KeepVM = MakeTestVolumeManager(2)
893         defer KeepVM.Close()
894
895         vols := KeepVM.AllWritable()
896         if err := vols[0].Put(TEST_HASH, TEST_BLOCK); err != nil {
897                 t.Error(err)
898         }
899
900         ok := make(chan bool)
901         go func() {
902                 for i := 0; i < maxBuffers+1; i++ {
903                         // Unauthenticated request, unsigned locator
904                         // => OK
905                         unsignedLocator := "/" + TEST_HASH
906                         response := IssueRequest(
907                                 &RequestTester{
908                                         method: "GET",
909                                         uri:    unsignedLocator,
910                                 })
911                         ExpectStatusCode(t,
912                                 "Unauthenticated request, unsigned locator", http.StatusOK, response)
913                         ExpectBody(t,
914                                 "Unauthenticated request, unsigned locator",
915                                 string(TEST_BLOCK),
916                                 response)
917                 }
918                 ok <- true
919         }()
920         select {
921         case <-time.After(20 * time.Second):
922                 // If the buffer pool leaks, the test goroutine hangs.
923                 t.Fatal("test did not finish, assuming pool leaked")
924         case <-ok:
925         }
926 }