Merge branch 'master' into 8017-slurm-runtime-constraints
[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         buf := make([]byte, BlockSize)
565         _, err := vols[0].Get(TestHash, buf)
566         var blockDeleted = os.IsNotExist(err)
567         if !blockDeleted {
568                 t.Error("superuserExistingBlockReq: block not deleted")
569         }
570
571         // A DELETE request on a block newer than blobSignatureTTL
572         // should return success but leave the block on the volume.
573         vols[0].Put(TestHash, TestBlock)
574         blobSignatureTTL = time.Hour
575
576         response = IssueRequest(superuserExistingBlockReq)
577         ExpectStatusCode(t,
578                 "data manager request, existing block",
579                 http.StatusOK,
580                 response)
581         // Expect response {"copies_deleted":1,"copies_failed":0}
582         expectedDc = deletecounter{1, 0}
583         json.NewDecoder(response.Body).Decode(&responseDc)
584         if responseDc != expectedDc {
585                 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
586                         expectedDc, responseDc)
587         }
588         // Confirm the block has NOT been deleted.
589         _, err = vols[0].Get(TestHash, buf)
590         if err != nil {
591                 t.Errorf("testing delete on new block: %s\n", err)
592         }
593 }
594
595 // TestPullHandler
596 //
597 // Test handling of the PUT /pull statement.
598 //
599 // Cases tested: syntactically valid and invalid pull lists, from the
600 // data manager and from unprivileged users:
601 //
602 //   1. Valid pull list from an ordinary user
603 //      (expected result: 401 Unauthorized)
604 //
605 //   2. Invalid pull request from an ordinary user
606 //      (expected result: 401 Unauthorized)
607 //
608 //   3. Valid pull request from the data manager
609 //      (expected result: 200 OK with request body "Received 3 pull
610 //      requests"
611 //
612 //   4. Invalid pull request from the data manager
613 //      (expected result: 400 Bad Request)
614 //
615 // Test that in the end, the pull manager received a good pull list with
616 // the expected number of requests.
617 //
618 // TODO(twp): test concurrency: launch 100 goroutines to update the
619 // pull list simultaneously.  Make sure that none of them return 400
620 // Bad Request and that pullq.GetList() returns a valid list.
621 //
622 func TestPullHandler(t *testing.T) {
623         defer teardown()
624
625         var userToken = "USER TOKEN"
626         dataManagerToken = "DATA MANAGER TOKEN"
627
628         pullq = NewWorkQueue()
629
630         goodJSON := []byte(`[
631                 {
632                         "locator":"locator_with_two_servers",
633                         "servers":[
634                                 "server1",
635                                 "server2"
636                         ]
637                 },
638                 {
639                         "locator":"locator_with_no_servers",
640                         "servers":[]
641                 },
642                 {
643                         "locator":"",
644                         "servers":["empty_locator"]
645                 }
646         ]`)
647
648         badJSON := []byte(`{ "key":"I'm a little teapot" }`)
649
650         type pullTest struct {
651                 name         string
652                 req          RequestTester
653                 responseCode int
654                 responseBody string
655         }
656         var testcases = []pullTest{
657                 {
658                         "Valid pull list from an ordinary user",
659                         RequestTester{"/pull", userToken, "PUT", goodJSON},
660                         http.StatusUnauthorized,
661                         "Unauthorized\n",
662                 },
663                 {
664                         "Invalid pull request from an ordinary user",
665                         RequestTester{"/pull", userToken, "PUT", badJSON},
666                         http.StatusUnauthorized,
667                         "Unauthorized\n",
668                 },
669                 {
670                         "Valid pull request from the data manager",
671                         RequestTester{"/pull", dataManagerToken, "PUT", goodJSON},
672                         http.StatusOK,
673                         "Received 3 pull requests\n",
674                 },
675                 {
676                         "Invalid pull request from the data manager",
677                         RequestTester{"/pull", dataManagerToken, "PUT", badJSON},
678                         http.StatusBadRequest,
679                         "",
680                 },
681         }
682
683         for _, tst := range testcases {
684                 response := IssueRequest(&tst.req)
685                 ExpectStatusCode(t, tst.name, tst.responseCode, response)
686                 ExpectBody(t, tst.name, tst.responseBody, response)
687         }
688
689         // The Keep pull manager should have received one good list with 3
690         // requests on it.
691         for i := 0; i < 3; i++ {
692                 item := <-pullq.NextItem
693                 if _, ok := item.(PullRequest); !ok {
694                         t.Errorf("item %v could not be parsed as a PullRequest", item)
695                 }
696         }
697
698         expectChannelEmpty(t, pullq.NextItem)
699 }
700
701 // TestTrashHandler
702 //
703 // Test cases:
704 //
705 // Cases tested: syntactically valid and invalid trash lists, from the
706 // data manager and from unprivileged users:
707 //
708 //   1. Valid trash list from an ordinary user
709 //      (expected result: 401 Unauthorized)
710 //
711 //   2. Invalid trash list from an ordinary user
712 //      (expected result: 401 Unauthorized)
713 //
714 //   3. Valid trash list from the data manager
715 //      (expected result: 200 OK with request body "Received 3 trash
716 //      requests"
717 //
718 //   4. Invalid trash list from the data manager
719 //      (expected result: 400 Bad Request)
720 //
721 // Test that in the end, the trash collector received a good list
722 // trash list with the expected number of requests.
723 //
724 // TODO(twp): test concurrency: launch 100 goroutines to update the
725 // pull list simultaneously.  Make sure that none of them return 400
726 // Bad Request and that replica.Dump() returns a valid list.
727 //
728 func TestTrashHandler(t *testing.T) {
729         defer teardown()
730
731         var userToken = "USER TOKEN"
732         dataManagerToken = "DATA MANAGER TOKEN"
733
734         trashq = NewWorkQueue()
735
736         goodJSON := []byte(`[
737                 {
738                         "locator":"block1",
739                         "block_mtime":1409082153
740                 },
741                 {
742                         "locator":"block2",
743                         "block_mtime":1409082153
744                 },
745                 {
746                         "locator":"block3",
747                         "block_mtime":1409082153
748                 }
749         ]`)
750
751         badJSON := []byte(`I am not a valid JSON string`)
752
753         type trashTest struct {
754                 name         string
755                 req          RequestTester
756                 responseCode int
757                 responseBody string
758         }
759
760         var testcases = []trashTest{
761                 {
762                         "Valid trash list from an ordinary user",
763                         RequestTester{"/trash", userToken, "PUT", goodJSON},
764                         http.StatusUnauthorized,
765                         "Unauthorized\n",
766                 },
767                 {
768                         "Invalid trash list from an ordinary user",
769                         RequestTester{"/trash", userToken, "PUT", badJSON},
770                         http.StatusUnauthorized,
771                         "Unauthorized\n",
772                 },
773                 {
774                         "Valid trash list from the data manager",
775                         RequestTester{"/trash", dataManagerToken, "PUT", goodJSON},
776                         http.StatusOK,
777                         "Received 3 trash requests\n",
778                 },
779                 {
780                         "Invalid trash list from the data manager",
781                         RequestTester{"/trash", dataManagerToken, "PUT", badJSON},
782                         http.StatusBadRequest,
783                         "",
784                 },
785         }
786
787         for _, tst := range testcases {
788                 response := IssueRequest(&tst.req)
789                 ExpectStatusCode(t, tst.name, tst.responseCode, response)
790                 ExpectBody(t, tst.name, tst.responseBody, response)
791         }
792
793         // The trash collector should have received one good list with 3
794         // requests on it.
795         for i := 0; i < 3; i++ {
796                 item := <-trashq.NextItem
797                 if _, ok := item.(TrashRequest); !ok {
798                         t.Errorf("item %v could not be parsed as a TrashRequest", item)
799                 }
800         }
801
802         expectChannelEmpty(t, trashq.NextItem)
803 }
804
805 // ====================
806 // Helper functions
807 // ====================
808
809 // IssueTestRequest executes an HTTP request described by rt, to a
810 // REST router.  It returns the HTTP response to the request.
811 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
812         response := httptest.NewRecorder()
813         body := bytes.NewReader(rt.requestBody)
814         req, _ := http.NewRequest(rt.method, rt.uri, body)
815         if rt.apiToken != "" {
816                 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
817         }
818         loggingRouter := MakeRESTRouter()
819         loggingRouter.ServeHTTP(response, req)
820         return response
821 }
822
823 // ExpectStatusCode checks whether a response has the specified status code,
824 // and reports a test failure if not.
825 func ExpectStatusCode(
826         t *testing.T,
827         testname string,
828         expectedStatus int,
829         response *httptest.ResponseRecorder) {
830         if response.Code != expectedStatus {
831                 t.Errorf("%s: expected status %d, got %+v",
832                         testname, expectedStatus, response)
833         }
834 }
835
836 func ExpectBody(
837         t *testing.T,
838         testname string,
839         expectedBody string,
840         response *httptest.ResponseRecorder) {
841         if expectedBody != "" && response.Body.String() != expectedBody {
842                 t.Errorf("%s: expected response body '%s', got %+v",
843                         testname, expectedBody, response)
844         }
845 }
846
847 // See #7121
848 func TestPutNeedsOnlyOneBuffer(t *testing.T) {
849         defer teardown()
850         KeepVM = MakeTestVolumeManager(1)
851         defer KeepVM.Close()
852
853         defer func(orig *bufferPool) {
854                 bufs = orig
855         }(bufs)
856         bufs = newBufferPool(1, BlockSize)
857
858         ok := make(chan struct{})
859         go func() {
860                 for i := 0; i < 2; i++ {
861                         response := IssueRequest(
862                                 &RequestTester{
863                                         method:      "PUT",
864                                         uri:         "/" + TestHash,
865                                         requestBody: TestBlock,
866                                 })
867                         ExpectStatusCode(t,
868                                 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
869                 }
870                 ok <- struct{}{}
871         }()
872
873         select {
874         case <-ok:
875         case <-time.After(time.Second):
876                 t.Fatal("PUT deadlocks with maxBuffers==1")
877         }
878 }
879
880 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
881 // leak.
882 func TestPutHandlerNoBufferleak(t *testing.T) {
883         defer teardown()
884
885         // Prepare two test Keep volumes.
886         KeepVM = MakeTestVolumeManager(2)
887         defer KeepVM.Close()
888
889         ok := make(chan bool)
890         go func() {
891                 for i := 0; i < maxBuffers+1; i++ {
892                         // Unauthenticated request, no server key
893                         // => OK (unsigned response)
894                         unsignedLocator := "/" + TestHash
895                         response := IssueRequest(
896                                 &RequestTester{
897                                         method:      "PUT",
898                                         uri:         unsignedLocator,
899                                         requestBody: TestBlock,
900                                 })
901                         ExpectStatusCode(t,
902                                 "TestPutHandlerBufferleak", http.StatusOK, response)
903                         ExpectBody(t,
904                                 "TestPutHandlerBufferleak",
905                                 TestHashPutResp, response)
906                 }
907                 ok <- true
908         }()
909         select {
910         case <-time.After(20 * time.Second):
911                 // If the buffer pool leaks, the test goroutine hangs.
912                 t.Fatal("test did not finish, assuming pool leaked")
913         case <-ok:
914         }
915 }
916
917 type notifyingResponseRecorder struct {
918         *httptest.ResponseRecorder
919         closer chan bool
920 }
921
922 func (r *notifyingResponseRecorder) CloseNotify() <-chan bool {
923         return r.closer
924 }
925
926 func TestGetHandlerClientDisconnect(t *testing.T) {
927         defer func(was bool) {
928                 enforcePermissions = was
929         }(enforcePermissions)
930         enforcePermissions = false
931
932         defer func(orig *bufferPool) {
933                 bufs = orig
934         }(bufs)
935         bufs = newBufferPool(1, BlockSize)
936         defer bufs.Put(bufs.Get(BlockSize))
937
938         KeepVM = MakeTestVolumeManager(2)
939         defer KeepVM.Close()
940
941         if err := KeepVM.AllWritable()[0].Put(TestHash, TestBlock); err != nil {
942                 t.Error(err)
943         }
944
945         resp := &notifyingResponseRecorder{
946                 ResponseRecorder: httptest.NewRecorder(),
947                 closer:           make(chan bool, 1),
948         }
949         if _, ok := http.ResponseWriter(resp).(http.CloseNotifier); !ok {
950                 t.Fatal("notifyingResponseRecorder is broken")
951         }
952         // If anyone asks, the client has disconnected.
953         resp.closer <- true
954
955         ok := make(chan struct{})
956         go func() {
957                 req, _ := http.NewRequest("GET", fmt.Sprintf("/%s+%d", TestHash, len(TestBlock)), nil)
958                 (&LoggingRESTRouter{MakeRESTRouter()}).ServeHTTP(resp, req)
959                 ok <- struct{}{}
960         }()
961
962         select {
963         case <-time.After(20 * time.Second):
964                 t.Fatal("request took >20s, close notifier must be broken")
965         case <-ok:
966         }
967
968         ExpectStatusCode(t, "client disconnect", http.StatusServiceUnavailable, resp.ResponseRecorder)
969         for i, v := range KeepVM.AllWritable() {
970                 if calls := v.(*MockVolume).called["GET"]; calls != 0 {
971                         t.Errorf("volume %d got %d calls, expected 0", i, calls)
972                 }
973         }
974 }
975
976 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
977 // leak.
978 func TestGetHandlerNoBufferleak(t *testing.T) {
979         defer teardown()
980
981         // Prepare two test Keep volumes. Our block is stored on the second volume.
982         KeepVM = MakeTestVolumeManager(2)
983         defer KeepVM.Close()
984
985         vols := KeepVM.AllWritable()
986         if err := vols[0].Put(TestHash, TestBlock); err != nil {
987                 t.Error(err)
988         }
989
990         ok := make(chan bool)
991         go func() {
992                 for i := 0; i < maxBuffers+1; i++ {
993                         // Unauthenticated request, unsigned locator
994                         // => OK
995                         unsignedLocator := "/" + TestHash
996                         response := IssueRequest(
997                                 &RequestTester{
998                                         method: "GET",
999                                         uri:    unsignedLocator,
1000                                 })
1001                         ExpectStatusCode(t,
1002                                 "Unauthenticated request, unsigned locator", http.StatusOK, response)
1003                         ExpectBody(t,
1004                                 "Unauthenticated request, unsigned locator",
1005                                 string(TestBlock),
1006                                 response)
1007                 }
1008                 ok <- true
1009         }()
1010         select {
1011         case <-time.After(20 * time.Second):
1012                 // If the buffer pool leaks, the test goroutine hangs.
1013                 t.Fatal("test did not finish, assuming pool leaked")
1014         case <-ok:
1015         }
1016 }
1017
1018 func TestPutReplicationHeader(t *testing.T) {
1019         defer teardown()
1020
1021         KeepVM = MakeTestVolumeManager(2)
1022         defer KeepVM.Close()
1023
1024         resp := IssueRequest(&RequestTester{
1025                 method:      "PUT",
1026                 uri:         "/" + TestHash,
1027                 requestBody: TestBlock,
1028         })
1029         if r := resp.Header().Get("X-Keep-Replicas-Stored"); r != "1" {
1030                 t.Errorf("Got X-Keep-Replicas-Stored: %q, expected %q", r, "1")
1031         }
1032 }
1033
1034 func TestUntrashHandler(t *testing.T) {
1035         defer teardown()
1036
1037         // Set up Keep volumes
1038         KeepVM = MakeTestVolumeManager(2)
1039         defer KeepVM.Close()
1040         vols := KeepVM.AllWritable()
1041         vols[0].Put(TestHash, TestBlock)
1042
1043         dataManagerToken = "DATA MANAGER TOKEN"
1044
1045         // unauthenticatedReq => UnauthorizedError
1046         unauthenticatedReq := &RequestTester{
1047                 method: "PUT",
1048                 uri:    "/untrash/" + TestHash,
1049         }
1050         response := IssueRequest(unauthenticatedReq)
1051         ExpectStatusCode(t,
1052                 "Unauthenticated request",
1053                 UnauthorizedError.HTTPCode,
1054                 response)
1055
1056         // notDataManagerReq => UnauthorizedError
1057         notDataManagerReq := &RequestTester{
1058                 method:   "PUT",
1059                 uri:      "/untrash/" + TestHash,
1060                 apiToken: knownToken,
1061         }
1062
1063         response = IssueRequest(notDataManagerReq)
1064         ExpectStatusCode(t,
1065                 "Non-datamanager token",
1066                 UnauthorizedError.HTTPCode,
1067                 response)
1068
1069         // datamanagerWithBadHashReq => StatusBadRequest
1070         datamanagerWithBadHashReq := &RequestTester{
1071                 method:   "PUT",
1072                 uri:      "/untrash/thisisnotalocator",
1073                 apiToken: dataManagerToken,
1074         }
1075         response = IssueRequest(datamanagerWithBadHashReq)
1076         ExpectStatusCode(t,
1077                 "Bad locator in untrash request",
1078                 http.StatusBadRequest,
1079                 response)
1080
1081         // datamanagerWrongMethodReq => StatusBadRequest
1082         datamanagerWrongMethodReq := &RequestTester{
1083                 method:   "GET",
1084                 uri:      "/untrash/" + TestHash,
1085                 apiToken: dataManagerToken,
1086         }
1087         response = IssueRequest(datamanagerWrongMethodReq)
1088         ExpectStatusCode(t,
1089                 "Only PUT method is supported for untrash",
1090                 http.StatusBadRequest,
1091                 response)
1092
1093         // datamanagerReq => StatusOK
1094         datamanagerReq := &RequestTester{
1095                 method:   "PUT",
1096                 uri:      "/untrash/" + TestHash,
1097                 apiToken: dataManagerToken,
1098         }
1099         response = IssueRequest(datamanagerReq)
1100         ExpectStatusCode(t,
1101                 "",
1102                 http.StatusOK,
1103                 response)
1104         expected := "Successfully untrashed on: [MockVolume],[MockVolume]"
1105         if response.Body.String() != expected {
1106                 t.Errorf(
1107                         "Untrash response mismatched: expected %s, got:\n%s",
1108                         expected, response.Body.String())
1109         }
1110 }
1111
1112 func TestUntrashHandlerWithNoWritableVolumes(t *testing.T) {
1113         defer teardown()
1114
1115         // Set up readonly Keep volumes
1116         vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
1117         vols[0].Readonly = true
1118         vols[1].Readonly = true
1119         KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
1120         defer KeepVM.Close()
1121
1122         dataManagerToken = "DATA MANAGER TOKEN"
1123
1124         // datamanagerReq => StatusOK
1125         datamanagerReq := &RequestTester{
1126                 method:   "PUT",
1127                 uri:      "/untrash/" + TestHash,
1128                 apiToken: dataManagerToken,
1129         }
1130         response := IssueRequest(datamanagerReq)
1131         ExpectStatusCode(t,
1132                 "No writable volumes",
1133                 http.StatusNotFound,
1134                 response)
1135 }