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