33d585ae1e69f18868f7eb57278637c7f855761b
[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(TestHash, TestBlock); 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(knownKey)
57         blobSignatureTTL = 300 * time.Second
58
59         var (
60                 unsignedLocator  = "/" + TestHash
61                 validTimestamp   = time.Now().Add(blobSignatureTTL)
62                 expiredTimestamp = time.Now().Add(-time.Hour)
63                 signedLocator    = "/" + SignLocator(TestHash, knownToken, validTimestamp)
64                 expiredLocator   = "/" + SignLocator(TestHash, knownToken, 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(TestBlock),
83                 response)
84
85         receivedLen := response.Header().Get("Content-Length")
86         expectedLen := fmt.Sprintf("%d", len(TestBlock))
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: knownToken,
101         })
102         ExpectStatusCode(t,
103                 "Authenticated request, signed locator", http.StatusOK, response)
104         ExpectBody(t,
105                 "Authenticated request, signed locator", string(TestBlock), response)
106
107         receivedLen = response.Header().Get("Content-Length")
108         expectedLen = fmt.Sprintf("%d", len(TestBlock))
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: knownToken,
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: knownToken,
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 := "/" + TestHash
162         response := IssueRequest(
163                 &RequestTester{
164                         method:      "PUT",
165                         uri:         unsignedLocator,
166                         requestBody: TestBlock,
167                 })
168
169         ExpectStatusCode(t,
170                 "Unauthenticated request, no server key", http.StatusOK, response)
171         ExpectBody(t,
172                 "Unauthenticated request, no server key",
173                 TestHashPutResp, response)
174
175         // ------------------
176         // With a server key.
177
178         PermissionSecret = []byte(knownKey)
179         blobSignatureTTL = 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: TestBlock,
191                         apiToken:    knownToken,
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, knownToken) != 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: TestBlock,
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                 TestHashPutResp, response)
219 }
220
221 func TestPutAndDeleteSkipReadonlyVolumes(t *testing.T) {
222         defer teardown()
223         dataManagerToken = "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:         "/" + TestHash,
232                         requestBody: TestBlock,
233                 })
234         defer func(orig bool) {
235                 neverDelete = orig
236         }(neverDelete)
237         neverDelete = false
238         IssueRequest(
239                 &RequestTester{
240                         method:      "DELETE",
241                         uri:         "/" + TestHash,
242                         requestBody: TestBlock,
243                         apiToken:    dataManagerToken,
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(TestHash, TestBlock)
290         vols[1].Put(TestHash2, TestBlock2)
291         vols[0].Put(TestHash+".meta", []byte("metadata"))
292         vols[1].Put(TestHash2+".meta", []byte("metadata"))
293
294         dataManagerToken = "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: knownToken,
304         }
305         superuserReq := &RequestTester{
306                 method:   "GET",
307                 uri:      "/index",
308                 apiToken: dataManagerToken,
309         }
310         unauthPrefixReq := &RequestTester{
311                 method: "GET",
312                 uri:    "/index/" + TestHash[0:3],
313         }
314         authPrefixReq := &RequestTester{
315                 method:   "GET",
316                 uri:      "/index/" + TestHash[0:3],
317                 apiToken: knownToken,
318         }
319         superuserPrefixReq := &RequestTester{
320                 method:   "GET",
321                 uri:      "/index/" + TestHash[0:3],
322                 apiToken: dataManagerToken,
323         }
324         superuserNoSuchPrefixReq := &RequestTester{
325                 method:   "GET",
326                 uri:      "/index/abcd",
327                 apiToken: dataManagerToken,
328         }
329         superuserInvalidPrefixReq := &RequestTester{
330                 method:   "GET",
331                 uri:      "/index/xyz",
332                 apiToken: dataManagerToken,
333         }
334
335         // -------------------------------------------------------------
336         // Only the superuser should be allowed to issue /index requests.
337
338         // ---------------------------
339         // enforcePermissions enabled
340         // This setting should not affect tests passing.
341         enforcePermissions = true
342
343         // unauthenticated /index request
344         // => UnauthorizedError
345         response := IssueRequest(unauthenticatedReq)
346         ExpectStatusCode(t,
347                 "enforcePermissions on, unauthenticated request",
348                 UnauthorizedError.HTTPCode,
349                 response)
350
351         // unauthenticated /index/prefix request
352         // => UnauthorizedError
353         response = IssueRequest(unauthPrefixReq)
354         ExpectStatusCode(t,
355                 "permissions on, unauthenticated /index/prefix request",
356                 UnauthorizedError.HTTPCode,
357                 response)
358
359         // authenticated /index request, non-superuser
360         // => UnauthorizedError
361         response = IssueRequest(authenticatedReq)
362         ExpectStatusCode(t,
363                 "permissions on, authenticated request, non-superuser",
364                 UnauthorizedError.HTTPCode,
365                 response)
366
367         // authenticated /index/prefix request, non-superuser
368         // => UnauthorizedError
369         response = IssueRequest(authPrefixReq)
370         ExpectStatusCode(t,
371                 "permissions on, authenticated /index/prefix request, non-superuser",
372                 UnauthorizedError.HTTPCode,
373                 response)
374
375         // superuser /index request
376         // => OK
377         response = IssueRequest(superuserReq)
378         ExpectStatusCode(t,
379                 "permissions on, superuser request",
380                 http.StatusOK,
381                 response)
382
383         // ----------------------------
384         // enforcePermissions disabled
385         // Valid Request should still pass.
386         enforcePermissions = false
387
388         // superuser /index request
389         // => OK
390         response = IssueRequest(superuserReq)
391         ExpectStatusCode(t,
392                 "permissions on, superuser request",
393                 http.StatusOK,
394                 response)
395
396         expected := `^` + TestHash + `\+\d+ \d+\n` +
397                 TestHash2 + `\+\d+ \d+\n\n$`
398         match, _ := regexp.MatchString(expected, response.Body.String())
399         if !match {
400                 t.Errorf(
401                         "permissions on, superuser request: expected %s, got:\n%s",
402                         expected, response.Body.String())
403         }
404
405         // superuser /index/prefix request
406         // => OK
407         response = IssueRequest(superuserPrefixReq)
408         ExpectStatusCode(t,
409                 "permissions on, superuser request",
410                 http.StatusOK,
411                 response)
412
413         expected = `^` + TestHash + `\+\d+ \d+\n\n$`
414         match, _ = regexp.MatchString(expected, response.Body.String())
415         if !match {
416                 t.Errorf(
417                         "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
418                         expected, response.Body.String())
419         }
420
421         // superuser /index/{no-such-prefix} request
422         // => OK
423         response = IssueRequest(superuserNoSuchPrefixReq)
424         ExpectStatusCode(t,
425                 "permissions on, superuser request",
426                 http.StatusOK,
427                 response)
428
429         if "\n" != response.Body.String() {
430                 t.Errorf("Expected empty response for %s. Found %s", superuserNoSuchPrefixReq.uri, response.Body.String())
431         }
432
433         // superuser /index/{invalid-prefix} request
434         // => StatusBadRequest
435         response = IssueRequest(superuserInvalidPrefixReq)
436         ExpectStatusCode(t,
437                 "permissions on, superuser request",
438                 http.StatusBadRequest,
439                 response)
440 }
441
442 // TestDeleteHandler
443 //
444 // Cases tested:
445 //
446 //   With no token and with a non-data-manager token:
447 //   * Delete existing block
448 //     (test for 403 Forbidden, confirm block not deleted)
449 //
450 //   With data manager token:
451 //
452 //   * Delete existing block
453 //     (test for 200 OK, response counts, confirm block deleted)
454 //
455 //   * Delete nonexistent block
456 //     (test for 200 OK, response counts)
457 //
458 //   TODO(twp):
459 //
460 //   * Delete block on read-only and read-write volume
461 //     (test for 200 OK, response with copies_deleted=1,
462 //     copies_failed=1, confirm block deleted only on r/w volume)
463 //
464 //   * Delete block on read-only volume only
465 //     (test for 200 OK, response with copies_deleted=0, copies_failed=1,
466 //     confirm block not deleted)
467 //
468 func TestDeleteHandler(t *testing.T) {
469         defer teardown()
470
471         // Set up Keep volumes and populate them.
472         // Include multiple blocks on different volumes, and
473         // some metadata files (which should be omitted from index listings)
474         KeepVM = MakeTestVolumeManager(2)
475         defer KeepVM.Close()
476
477         vols := KeepVM.AllWritable()
478         vols[0].Put(TestHash, TestBlock)
479
480         // Explicitly set the blobSignatureTTL to 0 for these
481         // tests, to ensure the MockVolume deletes the blocks
482         // even though they have just been created.
483         blobSignatureTTL = time.Duration(0)
484
485         var userToken = "NOT DATA MANAGER TOKEN"
486         dataManagerToken = "DATA MANAGER TOKEN"
487
488         neverDelete = false
489
490         unauthReq := &RequestTester{
491                 method: "DELETE",
492                 uri:    "/" + TestHash,
493         }
494
495         userReq := &RequestTester{
496                 method:   "DELETE",
497                 uri:      "/" + TestHash,
498                 apiToken: userToken,
499         }
500
501         superuserExistingBlockReq := &RequestTester{
502                 method:   "DELETE",
503                 uri:      "/" + TestHash,
504                 apiToken: dataManagerToken,
505         }
506
507         superuserNonexistentBlockReq := &RequestTester{
508                 method:   "DELETE",
509                 uri:      "/" + TestHash2,
510                 apiToken: dataManagerToken,
511         }
512
513         // Unauthenticated request returns PermissionError.
514         var response *httptest.ResponseRecorder
515         response = IssueRequest(unauthReq)
516         ExpectStatusCode(t,
517                 "unauthenticated request",
518                 PermissionError.HTTPCode,
519                 response)
520
521         // Authenticated non-admin request returns PermissionError.
522         response = IssueRequest(userReq)
523         ExpectStatusCode(t,
524                 "authenticated non-admin request",
525                 PermissionError.HTTPCode,
526                 response)
527
528         // Authenticated admin request for nonexistent block.
529         type deletecounter struct {
530                 Deleted int `json:"copies_deleted"`
531                 Failed  int `json:"copies_failed"`
532         }
533         var responseDc, expectedDc deletecounter
534
535         response = IssueRequest(superuserNonexistentBlockReq)
536         ExpectStatusCode(t,
537                 "data manager request, nonexistent block",
538                 http.StatusNotFound,
539                 response)
540
541         // Authenticated admin request for existing block while neverDelete is set.
542         neverDelete = true
543         response = IssueRequest(superuserExistingBlockReq)
544         ExpectStatusCode(t,
545                 "authenticated request, existing block, method disabled",
546                 MethodDisabledError.HTTPCode,
547                 response)
548         neverDelete = false
549
550         // Authenticated admin request for existing block.
551         response = IssueRequest(superuserExistingBlockReq)
552         ExpectStatusCode(t,
553                 "data manager request, existing block",
554                 http.StatusOK,
555                 response)
556         // Expect response {"copies_deleted":1,"copies_failed":0}
557         expectedDc = deletecounter{1, 0}
558         json.NewDecoder(response.Body).Decode(&responseDc)
559         if responseDc != expectedDc {
560                 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
561                         expectedDc, responseDc)
562         }
563         // Confirm the block has been deleted
564         _, err := vols[0].Get(TestHash)
565         var blockDeleted = os.IsNotExist(err)
566         if !blockDeleted {
567                 t.Error("superuserExistingBlockReq: block not deleted")
568         }
569
570         // A DELETE request on a block newer than blobSignatureTTL
571         // should return success but leave the block on the volume.
572         vols[0].Put(TestHash, TestBlock)
573         blobSignatureTTL = time.Hour
574
575         response = IssueRequest(superuserExistingBlockReq)
576         ExpectStatusCode(t,
577                 "data manager request, existing block",
578                 http.StatusOK,
579                 response)
580         // Expect response {"copies_deleted":1,"copies_failed":0}
581         expectedDc = deletecounter{1, 0}
582         json.NewDecoder(response.Body).Decode(&responseDc)
583         if responseDc != expectedDc {
584                 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
585                         expectedDc, responseDc)
586         }
587         // Confirm the block has NOT been deleted.
588         _, err = vols[0].Get(TestHash)
589         if err != nil {
590                 t.Errorf("testing delete on new block: %s\n", err)
591         }
592 }
593
594 // TestPullHandler
595 //
596 // Test handling of the PUT /pull statement.
597 //
598 // Cases tested: syntactically valid and invalid pull lists, from the
599 // data manager and from unprivileged users:
600 //
601 //   1. Valid pull list from an ordinary user
602 //      (expected result: 401 Unauthorized)
603 //
604 //   2. Invalid pull request from an ordinary user
605 //      (expected result: 401 Unauthorized)
606 //
607 //   3. Valid pull request from the data manager
608 //      (expected result: 200 OK with request body "Received 3 pull
609 //      requests"
610 //
611 //   4. Invalid pull request from the data manager
612 //      (expected result: 400 Bad Request)
613 //
614 // Test that in the end, the pull manager received a good pull list with
615 // the expected number of requests.
616 //
617 // TODO(twp): test concurrency: launch 100 goroutines to update the
618 // pull list simultaneously.  Make sure that none of them return 400
619 // Bad Request and that pullq.GetList() returns a valid list.
620 //
621 func TestPullHandler(t *testing.T) {
622         defer teardown()
623
624         var userToken = "USER TOKEN"
625         dataManagerToken = "DATA MANAGER TOKEN"
626
627         pullq = NewWorkQueue()
628
629         goodJSON := []byte(`[
630                 {
631                         "locator":"locator_with_two_servers",
632                         "servers":[
633                                 "server1",
634                                 "server2"
635                         ]
636                 },
637                 {
638                         "locator":"locator_with_no_servers",
639                         "servers":[]
640                 },
641                 {
642                         "locator":"",
643                         "servers":["empty_locator"]
644                 }
645         ]`)
646
647         badJSON := []byte(`{ "key":"I'm a little teapot" }`)
648
649         type pullTest struct {
650                 name         string
651                 req          RequestTester
652                 responseCode int
653                 responseBody string
654         }
655         var testcases = []pullTest{
656                 {
657                         "Valid pull list from an ordinary user",
658                         RequestTester{"/pull", userToken, "PUT", goodJSON},
659                         http.StatusUnauthorized,
660                         "Unauthorized\n",
661                 },
662                 {
663                         "Invalid pull request from an ordinary user",
664                         RequestTester{"/pull", userToken, "PUT", badJSON},
665                         http.StatusUnauthorized,
666                         "Unauthorized\n",
667                 },
668                 {
669                         "Valid pull request from the data manager",
670                         RequestTester{"/pull", dataManagerToken, "PUT", goodJSON},
671                         http.StatusOK,
672                         "Received 3 pull requests\n",
673                 },
674                 {
675                         "Invalid pull request from the data manager",
676                         RequestTester{"/pull", dataManagerToken, "PUT", badJSON},
677                         http.StatusBadRequest,
678                         "",
679                 },
680         }
681
682         for _, tst := range testcases {
683                 response := IssueRequest(&tst.req)
684                 ExpectStatusCode(t, tst.name, tst.responseCode, response)
685                 ExpectBody(t, tst.name, tst.responseBody, response)
686         }
687
688         // The Keep pull manager should have received one good list with 3
689         // requests on it.
690         for i := 0; i < 3; i++ {
691                 item := <-pullq.NextItem
692                 if _, ok := item.(PullRequest); !ok {
693                         t.Errorf("item %v could not be parsed as a PullRequest", item)
694                 }
695         }
696
697         expectChannelEmpty(t, pullq.NextItem)
698 }
699
700 // TestTrashHandler
701 //
702 // Test cases:
703 //
704 // Cases tested: syntactically valid and invalid trash lists, from the
705 // data manager and from unprivileged users:
706 //
707 //   1. Valid trash list from an ordinary user
708 //      (expected result: 401 Unauthorized)
709 //
710 //   2. Invalid trash list from an ordinary user
711 //      (expected result: 401 Unauthorized)
712 //
713 //   3. Valid trash list from the data manager
714 //      (expected result: 200 OK with request body "Received 3 trash
715 //      requests"
716 //
717 //   4. Invalid trash list from the data manager
718 //      (expected result: 400 Bad Request)
719 //
720 // Test that in the end, the trash collector received a good list
721 // trash list with the expected number of requests.
722 //
723 // TODO(twp): test concurrency: launch 100 goroutines to update the
724 // pull list simultaneously.  Make sure that none of them return 400
725 // Bad Request and that replica.Dump() returns a valid list.
726 //
727 func TestTrashHandler(t *testing.T) {
728         defer teardown()
729
730         var userToken = "USER TOKEN"
731         dataManagerToken = "DATA MANAGER TOKEN"
732
733         trashq = NewWorkQueue()
734
735         goodJSON := []byte(`[
736                 {
737                         "locator":"block1",
738                         "block_mtime":1409082153
739                 },
740                 {
741                         "locator":"block2",
742                         "block_mtime":1409082153
743                 },
744                 {
745                         "locator":"block3",
746                         "block_mtime":1409082153
747                 }
748         ]`)
749
750         badJSON := []byte(`I am not a valid JSON string`)
751
752         type trashTest struct {
753                 name         string
754                 req          RequestTester
755                 responseCode int
756                 responseBody string
757         }
758
759         var testcases = []trashTest{
760                 {
761                         "Valid trash list from an ordinary user",
762                         RequestTester{"/trash", userToken, "PUT", goodJSON},
763                         http.StatusUnauthorized,
764                         "Unauthorized\n",
765                 },
766                 {
767                         "Invalid trash list from an ordinary user",
768                         RequestTester{"/trash", userToken, "PUT", badJSON},
769                         http.StatusUnauthorized,
770                         "Unauthorized\n",
771                 },
772                 {
773                         "Valid trash list from the data manager",
774                         RequestTester{"/trash", dataManagerToken, "PUT", goodJSON},
775                         http.StatusOK,
776                         "Received 3 trash requests\n",
777                 },
778                 {
779                         "Invalid trash list from the data manager",
780                         RequestTester{"/trash", dataManagerToken, "PUT", badJSON},
781                         http.StatusBadRequest,
782                         "",
783                 },
784         }
785
786         for _, tst := range testcases {
787                 response := IssueRequest(&tst.req)
788                 ExpectStatusCode(t, tst.name, tst.responseCode, response)
789                 ExpectBody(t, tst.name, tst.responseBody, response)
790         }
791
792         // The trash collector should have received one good list with 3
793         // requests on it.
794         for i := 0; i < 3; i++ {
795                 item := <-trashq.NextItem
796                 if _, ok := item.(TrashRequest); !ok {
797                         t.Errorf("item %v could not be parsed as a TrashRequest", item)
798                 }
799         }
800
801         expectChannelEmpty(t, trashq.NextItem)
802 }
803
804 // ====================
805 // Helper functions
806 // ====================
807
808 // IssueTestRequest executes an HTTP request described by rt, to a
809 // REST router.  It returns the HTTP response to the request.
810 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
811         response := httptest.NewRecorder()
812         body := bytes.NewReader(rt.requestBody)
813         req, _ := http.NewRequest(rt.method, rt.uri, body)
814         if rt.apiToken != "" {
815                 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
816         }
817         loggingRouter := MakeRESTRouter()
818         loggingRouter.ServeHTTP(response, req)
819         return response
820 }
821
822 // ExpectStatusCode checks whether a response has the specified status code,
823 // and reports a test failure if not.
824 func ExpectStatusCode(
825         t *testing.T,
826         testname string,
827         expectedStatus int,
828         response *httptest.ResponseRecorder) {
829         if response.Code != expectedStatus {
830                 t.Errorf("%s: expected status %d, got %+v",
831                         testname, expectedStatus, response)
832         }
833 }
834
835 func ExpectBody(
836         t *testing.T,
837         testname string,
838         expectedBody string,
839         response *httptest.ResponseRecorder) {
840         if expectedBody != "" && response.Body.String() != expectedBody {
841                 t.Errorf("%s: expected response body '%s', got %+v",
842                         testname, expectedBody, response)
843         }
844 }
845
846 // See #7121
847 func TestPutNeedsOnlyOneBuffer(t *testing.T) {
848         defer teardown()
849         KeepVM = MakeTestVolumeManager(1)
850         defer KeepVM.Close()
851
852         defer func(orig *bufferPool) {
853                 bufs = orig
854         }(bufs)
855         bufs = newBufferPool(1, BlockSize)
856
857         ok := make(chan struct{})
858         go func() {
859                 for i := 0; i < 2; i++ {
860                         response := IssueRequest(
861                                 &RequestTester{
862                                         method:      "PUT",
863                                         uri:         "/" + TestHash,
864                                         requestBody: TestBlock,
865                                 })
866                         ExpectStatusCode(t,
867                                 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
868                 }
869                 ok <- struct{}{}
870         }()
871
872         select {
873         case <-ok:
874         case <-time.After(time.Second):
875                 t.Fatal("PUT deadlocks with maxBuffers==1")
876         }
877 }
878
879 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
880 // leak.
881 func TestPutHandlerNoBufferleak(t *testing.T) {
882         defer teardown()
883
884         // Prepare two test Keep volumes.
885         KeepVM = MakeTestVolumeManager(2)
886         defer KeepVM.Close()
887
888         ok := make(chan bool)
889         go func() {
890                 for i := 0; i < maxBuffers+1; i++ {
891                         // Unauthenticated request, no server key
892                         // => OK (unsigned response)
893                         unsignedLocator := "/" + TestHash
894                         response := IssueRequest(
895                                 &RequestTester{
896                                         method:      "PUT",
897                                         uri:         unsignedLocator,
898                                         requestBody: TestBlock,
899                                 })
900                         ExpectStatusCode(t,
901                                 "TestPutHandlerBufferleak", http.StatusOK, response)
902                         ExpectBody(t,
903                                 "TestPutHandlerBufferleak",
904                                 TestHashPutResp, response)
905                 }
906                 ok <- true
907         }()
908         select {
909         case <-time.After(20 * time.Second):
910                 // If the buffer pool leaks, the test goroutine hangs.
911                 t.Fatal("test did not finish, assuming pool leaked")
912         case <-ok:
913         }
914 }
915
916 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
917 // leak.
918 func TestGetHandlerNoBufferleak(t *testing.T) {
919         defer teardown()
920
921         // Prepare two test Keep volumes. Our block is stored on the second volume.
922         KeepVM = MakeTestVolumeManager(2)
923         defer KeepVM.Close()
924
925         vols := KeepVM.AllWritable()
926         if err := vols[0].Put(TestHash, TestBlock); err != nil {
927                 t.Error(err)
928         }
929
930         ok := make(chan bool)
931         go func() {
932                 for i := 0; i < maxBuffers+1; i++ {
933                         // Unauthenticated request, unsigned locator
934                         // => OK
935                         unsignedLocator := "/" + TestHash
936                         response := IssueRequest(
937                                 &RequestTester{
938                                         method: "GET",
939                                         uri:    unsignedLocator,
940                                 })
941                         ExpectStatusCode(t,
942                                 "Unauthenticated request, unsigned locator", http.StatusOK, response)
943                         ExpectBody(t,
944                                 "Unauthenticated request, unsigned locator",
945                                 string(TestBlock),
946                                 response)
947                 }
948                 ok <- true
949         }()
950         select {
951         case <-time.After(20 * time.Second):
952                 // If the buffer pool leaks, the test goroutine hangs.
953                 t.Fatal("test did not finish, assuming pool leaked")
954         case <-ok:
955         }
956 }
957
958 func TestPutReplicationHeader(t *testing.T) {
959         defer teardown()
960
961         KeepVM = MakeTestVolumeManager(2)
962         defer KeepVM.Close()
963
964         resp := IssueRequest(&RequestTester{
965                 method:      "PUT",
966                 uri:         "/" + TestHash,
967                 requestBody: TestBlock,
968         })
969         if r := resp.Header().Get("X-Keep-Replicas-Stored"); r != "1" {
970                 t.Errorf("Got X-Keep-Replicas-Stored: %q, expected %q", r, "1")
971         }
972 }
973
974 func TestUntrashHandler(t *testing.T) {
975         defer teardown()
976
977         // Set up Keep volumes
978         KeepVM = MakeTestVolumeManager(2)
979         defer KeepVM.Close()
980         vols := KeepVM.AllWritable()
981         vols[0].Put(TestHash, TestBlock)
982
983         dataManagerToken = "DATA MANAGER TOKEN"
984
985         // unauthenticatedReq => UnauthorizedError
986         unauthenticatedReq := &RequestTester{
987                 method: "PUT",
988                 uri:    "/untrash/" + TestHash,
989         }
990         response := IssueRequest(unauthenticatedReq)
991         ExpectStatusCode(t,
992                 "Unauthenticated request",
993                 UnauthorizedError.HTTPCode,
994                 response)
995
996         // notDataManagerReq => UnauthorizedError
997         notDataManagerReq := &RequestTester{
998                 method:   "PUT",
999                 uri:      "/untrash/" + TestHash,
1000                 apiToken: knownToken,
1001         }
1002
1003         response = IssueRequest(notDataManagerReq)
1004         ExpectStatusCode(t,
1005                 "Non-datamanager token",
1006                 UnauthorizedError.HTTPCode,
1007                 response)
1008
1009         // datamanagerWithBadHashReq => StatusBadRequest
1010         datamanagerWithBadHashReq := &RequestTester{
1011                 method:   "PUT",
1012                 uri:      "/untrash/thisisnotalocator",
1013                 apiToken: dataManagerToken,
1014         }
1015         response = IssueRequest(datamanagerWithBadHashReq)
1016         ExpectStatusCode(t,
1017                 "Bad locator in untrash request",
1018                 http.StatusBadRequest,
1019                 response)
1020
1021         // datamanagerWrongMethodReq => StatusBadRequest
1022         datamanagerWrongMethodReq := &RequestTester{
1023                 method:   "GET",
1024                 uri:      "/untrash/" + TestHash,
1025                 apiToken: dataManagerToken,
1026         }
1027         response = IssueRequest(datamanagerWrongMethodReq)
1028         ExpectStatusCode(t,
1029                 "Only PUT method is supported for untrash",
1030                 http.StatusBadRequest,
1031                 response)
1032
1033         // datamanagerReq => StatusOK
1034         datamanagerReq := &RequestTester{
1035                 method:   "PUT",
1036                 uri:      "/untrash/" + TestHash,
1037                 apiToken: dataManagerToken,
1038         }
1039         response = IssueRequest(datamanagerReq)
1040         ExpectStatusCode(t,
1041                 "",
1042                 http.StatusOK,
1043                 response)
1044         expected := "Successfully untrashed on: [MockVolume],[MockVolume]"
1045         if response.Body.String() != expected {
1046                 t.Errorf(
1047                         "Untrash response mismatched: expected %s, got:\n%s",
1048                         expected, response.Body.String())
1049         }
1050 }
1051
1052 func TestUntrashHandlerWithNoWritableVolumes(t *testing.T) {
1053         defer teardown()
1054
1055         // Set up readonly Keep volumes
1056         vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
1057         vols[0].Readonly = true
1058         vols[1].Readonly = true
1059         KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
1060         defer KeepVM.Close()
1061
1062         dataManagerToken = "DATA MANAGER TOKEN"
1063
1064         // datamanagerReq => StatusOK
1065         datamanagerReq := &RequestTester{
1066                 method:   "PUT",
1067                 uri:      "/untrash/" + TestHash,
1068                 apiToken: dataManagerToken,
1069         }
1070         response := IssueRequest(datamanagerReq)
1071         ExpectStatusCode(t,
1072                 "No writable volumes",
1073                 http.StatusNotFound,
1074                 response)
1075 }