14804: Exposes the bug with a test.
[arvados.git] / services / keepstore / handler_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 // Tests for Keep HTTP handlers:
6 //
7 //     GetBlockHandler
8 //     PutBlockHandler
9 //     IndexHandler
10 //
11 // The HTTP handlers are responsible for enforcing permission policy,
12 // so these tests must exercise all possible permission permutations.
13
14 package main
15
16 import (
17         "bytes"
18         "context"
19         "encoding/json"
20         "fmt"
21         "net/http"
22         "net/http/httptest"
23         "os"
24         "regexp"
25         "strings"
26         "testing"
27         "time"
28
29         "git.curoverse.com/arvados.git/sdk/go/arvados"
30         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
31 )
32
33 var testCluster = &arvados.Cluster{
34         ClusterID: "zzzzz",
35 }
36
37 // A RequestTester represents the parameters for an HTTP request to
38 // be issued on behalf of a unit test.
39 type RequestTester struct {
40         uri         string
41         apiToken    string
42         method      string
43         requestBody []byte
44 }
45
46 // Test GetBlockHandler on the following situations:
47 //   - permissions off, unauthenticated request, unsigned locator
48 //   - permissions on, authenticated request, signed locator
49 //   - permissions on, authenticated request, unsigned locator
50 //   - permissions on, unauthenticated request, signed locator
51 //   - permissions on, authenticated request, expired locator
52 //
53 func TestGetHandler(t *testing.T) {
54         defer teardown()
55
56         // Prepare two test Keep volumes. Our block is stored on the second volume.
57         KeepVM = MakeTestVolumeManager(2)
58         defer KeepVM.Close()
59
60         vols := KeepVM.AllWritable()
61         if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
62                 t.Error(err)
63         }
64
65         // Create locators for testing.
66         // Turn on permission settings so we can generate signed locators.
67         theConfig.RequireSignatures = true
68         theConfig.blobSigningKey = []byte(knownKey)
69         theConfig.BlobSignatureTTL.Set("5m")
70
71         var (
72                 unsignedLocator  = "/" + TestHash
73                 validTimestamp   = time.Now().Add(theConfig.BlobSignatureTTL.Duration())
74                 expiredTimestamp = time.Now().Add(-time.Hour)
75                 signedLocator    = "/" + SignLocator(TestHash, knownToken, validTimestamp)
76                 expiredLocator   = "/" + SignLocator(TestHash, knownToken, expiredTimestamp)
77         )
78
79         // -----------------
80         // Test unauthenticated request with permissions off.
81         theConfig.RequireSignatures = false
82
83         // Unauthenticated request, unsigned locator
84         // => OK
85         response := IssueRequest(
86                 &RequestTester{
87                         method: "GET",
88                         uri:    unsignedLocator,
89                 })
90         ExpectStatusCode(t,
91                 "Unauthenticated request, unsigned locator", http.StatusOK, response)
92         ExpectBody(t,
93                 "Unauthenticated request, unsigned locator",
94                 string(TestBlock),
95                 response)
96
97         receivedLen := response.Header().Get("Content-Length")
98         expectedLen := fmt.Sprintf("%d", len(TestBlock))
99         if receivedLen != expectedLen {
100                 t.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
101         }
102
103         // ----------------
104         // Permissions: on.
105         theConfig.RequireSignatures = true
106
107         // Authenticated request, signed locator
108         // => OK
109         response = IssueRequest(&RequestTester{
110                 method:   "GET",
111                 uri:      signedLocator,
112                 apiToken: knownToken,
113         })
114         ExpectStatusCode(t,
115                 "Authenticated request, signed locator", http.StatusOK, response)
116         ExpectBody(t,
117                 "Authenticated request, signed locator", string(TestBlock), response)
118
119         receivedLen = response.Header().Get("Content-Length")
120         expectedLen = fmt.Sprintf("%d", len(TestBlock))
121         if receivedLen != expectedLen {
122                 t.Errorf("expected Content-Length %s, got %s", expectedLen, receivedLen)
123         }
124
125         // Authenticated request, unsigned locator
126         // => PermissionError
127         response = IssueRequest(&RequestTester{
128                 method:   "GET",
129                 uri:      unsignedLocator,
130                 apiToken: knownToken,
131         })
132         ExpectStatusCode(t, "unsigned locator", PermissionError.HTTPCode, response)
133
134         // Unauthenticated request, signed locator
135         // => PermissionError
136         response = IssueRequest(&RequestTester{
137                 method: "GET",
138                 uri:    signedLocator,
139         })
140         ExpectStatusCode(t,
141                 "Unauthenticated request, signed locator",
142                 PermissionError.HTTPCode, response)
143
144         // Authenticated request, expired locator
145         // => ExpiredError
146         response = IssueRequest(&RequestTester{
147                 method:   "GET",
148                 uri:      expiredLocator,
149                 apiToken: knownToken,
150         })
151         ExpectStatusCode(t,
152                 "Authenticated request, expired locator",
153                 ExpiredError.HTTPCode, response)
154
155         // Authenticated request, signed locator
156         // => 503 Server busy (transient error)
157
158         // Set up the block owning volume to respond with errors
159         vols[0].(*MockVolume).Bad = true
160         vols[0].(*MockVolume).BadVolumeError = VolumeBusyError
161         response = IssueRequest(&RequestTester{
162                 method:   "GET",
163                 uri:      signedLocator,
164                 apiToken: knownToken,
165         })
166         // A transient error from one volume while the other doesn't find the block
167         // should make the service return a 503 so that clients can retry.
168         ExpectStatusCode(t,
169                 "Volume backend busy",
170                 503, response)
171 }
172
173 // Test PutBlockHandler on the following situations:
174 //   - no server key
175 //   - with server key, authenticated request, unsigned locator
176 //   - with server key, unauthenticated request, unsigned locator
177 //
178 func TestPutHandler(t *testing.T) {
179         defer teardown()
180
181         // Prepare two test Keep volumes.
182         KeepVM = MakeTestVolumeManager(2)
183         defer KeepVM.Close()
184
185         // --------------
186         // No server key.
187
188         // Unauthenticated request, no server key
189         // => OK (unsigned response)
190         unsignedLocator := "/" + TestHash
191         response := IssueRequest(
192                 &RequestTester{
193                         method:      "PUT",
194                         uri:         unsignedLocator,
195                         requestBody: TestBlock,
196                 })
197
198         ExpectStatusCode(t,
199                 "Unauthenticated request, no server key", http.StatusOK, response)
200         ExpectBody(t,
201                 "Unauthenticated request, no server key",
202                 TestHashPutResp, response)
203
204         // ------------------
205         // With a server key.
206
207         theConfig.blobSigningKey = []byte(knownKey)
208         theConfig.BlobSignatureTTL.Set("5m")
209
210         // When a permission key is available, the locator returned
211         // from an authenticated PUT request will be signed.
212
213         // Authenticated PUT, signed locator
214         // => OK (signed response)
215         response = IssueRequest(
216                 &RequestTester{
217                         method:      "PUT",
218                         uri:         unsignedLocator,
219                         requestBody: TestBlock,
220                         apiToken:    knownToken,
221                 })
222
223         ExpectStatusCode(t,
224                 "Authenticated PUT, signed locator, with server key",
225                 http.StatusOK, response)
226         responseLocator := strings.TrimSpace(response.Body.String())
227         if VerifySignature(responseLocator, knownToken) != nil {
228                 t.Errorf("Authenticated PUT, signed locator, with server key:\n"+
229                         "response '%s' does not contain a valid signature",
230                         responseLocator)
231         }
232
233         // Unauthenticated PUT, unsigned locator
234         // => OK
235         response = IssueRequest(
236                 &RequestTester{
237                         method:      "PUT",
238                         uri:         unsignedLocator,
239                         requestBody: TestBlock,
240                 })
241
242         ExpectStatusCode(t,
243                 "Unauthenticated PUT, unsigned locator, with server key",
244                 http.StatusOK, response)
245         ExpectBody(t,
246                 "Unauthenticated PUT, unsigned locator, with server key",
247                 TestHashPutResp, response)
248 }
249
250 func TestPutAndDeleteSkipReadonlyVolumes(t *testing.T) {
251         defer teardown()
252         theConfig.systemAuthToken = "fake-data-manager-token"
253         vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
254         vols[0].Readonly = true
255         KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
256         defer KeepVM.Close()
257         IssueRequest(
258                 &RequestTester{
259                         method:      "PUT",
260                         uri:         "/" + TestHash,
261                         requestBody: TestBlock,
262                 })
263         defer func(orig bool) {
264                 theConfig.EnableDelete = orig
265         }(theConfig.EnableDelete)
266         theConfig.EnableDelete = true
267         IssueRequest(
268                 &RequestTester{
269                         method:      "DELETE",
270                         uri:         "/" + TestHash,
271                         requestBody: TestBlock,
272                         apiToken:    theConfig.systemAuthToken,
273                 })
274         type expect struct {
275                 volnum    int
276                 method    string
277                 callcount int
278         }
279         for _, e := range []expect{
280                 {0, "Get", 0},
281                 {0, "Compare", 0},
282                 {0, "Touch", 0},
283                 {0, "Put", 0},
284                 {0, "Delete", 0},
285                 {1, "Get", 0},
286                 {1, "Compare", 1},
287                 {1, "Touch", 1},
288                 {1, "Put", 1},
289                 {1, "Delete", 1},
290         } {
291                 if calls := vols[e.volnum].CallCount(e.method); calls != e.callcount {
292                         t.Errorf("Got %d %s() on vol %d, expect %d", calls, e.method, e.volnum, e.callcount)
293                 }
294         }
295 }
296
297 // Test /index requests:
298 //   - unauthenticated /index request
299 //   - unauthenticated /index/prefix request
300 //   - authenticated   /index request        | non-superuser
301 //   - authenticated   /index/prefix request | non-superuser
302 //   - authenticated   /index request        | superuser
303 //   - authenticated   /index/prefix request | superuser
304 //
305 // The only /index requests that should succeed are those issued by the
306 // superuser. They should pass regardless of the value of RequireSignatures.
307 //
308 func TestIndexHandler(t *testing.T) {
309         defer teardown()
310
311         // Set up Keep volumes and populate them.
312         // Include multiple blocks on different volumes, and
313         // some metadata files (which should be omitted from index listings)
314         KeepVM = MakeTestVolumeManager(2)
315         defer KeepVM.Close()
316
317         vols := KeepVM.AllWritable()
318         vols[0].Put(context.Background(), TestHash, TestBlock)
319         vols[1].Put(context.Background(), TestHash2, TestBlock2)
320         vols[0].Put(context.Background(), TestHash+".meta", []byte("metadata"))
321         vols[1].Put(context.Background(), TestHash2+".meta", []byte("metadata"))
322
323         theConfig.systemAuthToken = "DATA MANAGER TOKEN"
324
325         unauthenticatedReq := &RequestTester{
326                 method: "GET",
327                 uri:    "/index",
328         }
329         authenticatedReq := &RequestTester{
330                 method:   "GET",
331                 uri:      "/index",
332                 apiToken: knownToken,
333         }
334         superuserReq := &RequestTester{
335                 method:   "GET",
336                 uri:      "/index",
337                 apiToken: theConfig.systemAuthToken,
338         }
339         unauthPrefixReq := &RequestTester{
340                 method: "GET",
341                 uri:    "/index/" + TestHash[0:3],
342         }
343         authPrefixReq := &RequestTester{
344                 method:   "GET",
345                 uri:      "/index/" + TestHash[0:3],
346                 apiToken: knownToken,
347         }
348         superuserPrefixReq := &RequestTester{
349                 method:   "GET",
350                 uri:      "/index/" + TestHash[0:3],
351                 apiToken: theConfig.systemAuthToken,
352         }
353         superuserNoSuchPrefixReq := &RequestTester{
354                 method:   "GET",
355                 uri:      "/index/abcd",
356                 apiToken: theConfig.systemAuthToken,
357         }
358         superuserInvalidPrefixReq := &RequestTester{
359                 method:   "GET",
360                 uri:      "/index/xyz",
361                 apiToken: theConfig.systemAuthToken,
362         }
363
364         // -------------------------------------------------------------
365         // Only the superuser should be allowed to issue /index requests.
366
367         // ---------------------------
368         // RequireSignatures enabled
369         // This setting should not affect tests passing.
370         theConfig.RequireSignatures = true
371
372         // unauthenticated /index request
373         // => UnauthorizedError
374         response := IssueRequest(unauthenticatedReq)
375         ExpectStatusCode(t,
376                 "RequireSignatures on, unauthenticated request",
377                 UnauthorizedError.HTTPCode,
378                 response)
379
380         // unauthenticated /index/prefix request
381         // => UnauthorizedError
382         response = IssueRequest(unauthPrefixReq)
383         ExpectStatusCode(t,
384                 "permissions on, unauthenticated /index/prefix request",
385                 UnauthorizedError.HTTPCode,
386                 response)
387
388         // authenticated /index request, non-superuser
389         // => UnauthorizedError
390         response = IssueRequest(authenticatedReq)
391         ExpectStatusCode(t,
392                 "permissions on, authenticated request, non-superuser",
393                 UnauthorizedError.HTTPCode,
394                 response)
395
396         // authenticated /index/prefix request, non-superuser
397         // => UnauthorizedError
398         response = IssueRequest(authPrefixReq)
399         ExpectStatusCode(t,
400                 "permissions on, authenticated /index/prefix request, non-superuser",
401                 UnauthorizedError.HTTPCode,
402                 response)
403
404         // superuser /index request
405         // => OK
406         response = IssueRequest(superuserReq)
407         ExpectStatusCode(t,
408                 "permissions on, superuser request",
409                 http.StatusOK,
410                 response)
411
412         // ----------------------------
413         // RequireSignatures disabled
414         // Valid Request should still pass.
415         theConfig.RequireSignatures = false
416
417         // superuser /index request
418         // => OK
419         response = IssueRequest(superuserReq)
420         ExpectStatusCode(t,
421                 "permissions on, superuser request",
422                 http.StatusOK,
423                 response)
424
425         expected := `^` + TestHash + `\+\d+ \d+\n` +
426                 TestHash2 + `\+\d+ \d+\n\n$`
427         match, _ := regexp.MatchString(expected, response.Body.String())
428         if !match {
429                 t.Errorf(
430                         "permissions on, superuser request: expected %s, got:\n%s",
431                         expected, response.Body.String())
432         }
433
434         // superuser /index/prefix request
435         // => OK
436         response = IssueRequest(superuserPrefixReq)
437         ExpectStatusCode(t,
438                 "permissions on, superuser request",
439                 http.StatusOK,
440                 response)
441
442         expected = `^` + TestHash + `\+\d+ \d+\n\n$`
443         match, _ = regexp.MatchString(expected, response.Body.String())
444         if !match {
445                 t.Errorf(
446                         "permissions on, superuser /index/prefix request: expected %s, got:\n%s",
447                         expected, response.Body.String())
448         }
449
450         // superuser /index/{no-such-prefix} request
451         // => OK
452         response = IssueRequest(superuserNoSuchPrefixReq)
453         ExpectStatusCode(t,
454                 "permissions on, superuser request",
455                 http.StatusOK,
456                 response)
457
458         if "\n" != response.Body.String() {
459                 t.Errorf("Expected empty response for %s. Found %s", superuserNoSuchPrefixReq.uri, response.Body.String())
460         }
461
462         // superuser /index/{invalid-prefix} request
463         // => StatusBadRequest
464         response = IssueRequest(superuserInvalidPrefixReq)
465         ExpectStatusCode(t,
466                 "permissions on, superuser request",
467                 http.StatusBadRequest,
468                 response)
469 }
470
471 // TestDeleteHandler
472 //
473 // Cases tested:
474 //
475 //   With no token and with a non-data-manager token:
476 //   * Delete existing block
477 //     (test for 403 Forbidden, confirm block not deleted)
478 //
479 //   With data manager token:
480 //
481 //   * Delete existing block
482 //     (test for 200 OK, response counts, confirm block deleted)
483 //
484 //   * Delete nonexistent block
485 //     (test for 200 OK, response counts)
486 //
487 //   TODO(twp):
488 //
489 //   * Delete block on read-only and read-write volume
490 //     (test for 200 OK, response with copies_deleted=1,
491 //     copies_failed=1, confirm block deleted only on r/w volume)
492 //
493 //   * Delete block on read-only volume only
494 //     (test for 200 OK, response with copies_deleted=0, copies_failed=1,
495 //     confirm block not deleted)
496 //
497 func TestDeleteHandler(t *testing.T) {
498         defer teardown()
499
500         // Set up Keep volumes and populate them.
501         // Include multiple blocks on different volumes, and
502         // some metadata files (which should be omitted from index listings)
503         KeepVM = MakeTestVolumeManager(2)
504         defer KeepVM.Close()
505
506         vols := KeepVM.AllWritable()
507         vols[0].Put(context.Background(), TestHash, TestBlock)
508
509         // Explicitly set the BlobSignatureTTL to 0 for these
510         // tests, to ensure the MockVolume deletes the blocks
511         // even though they have just been created.
512         theConfig.BlobSignatureTTL = arvados.Duration(0)
513
514         var userToken = "NOT DATA MANAGER TOKEN"
515         theConfig.systemAuthToken = "DATA MANAGER TOKEN"
516
517         theConfig.EnableDelete = true
518
519         unauthReq := &RequestTester{
520                 method: "DELETE",
521                 uri:    "/" + TestHash,
522         }
523
524         userReq := &RequestTester{
525                 method:   "DELETE",
526                 uri:      "/" + TestHash,
527                 apiToken: userToken,
528         }
529
530         superuserExistingBlockReq := &RequestTester{
531                 method:   "DELETE",
532                 uri:      "/" + TestHash,
533                 apiToken: theConfig.systemAuthToken,
534         }
535
536         superuserNonexistentBlockReq := &RequestTester{
537                 method:   "DELETE",
538                 uri:      "/" + TestHash2,
539                 apiToken: theConfig.systemAuthToken,
540         }
541
542         // Unauthenticated request returns PermissionError.
543         var response *httptest.ResponseRecorder
544         response = IssueRequest(unauthReq)
545         ExpectStatusCode(t,
546                 "unauthenticated request",
547                 PermissionError.HTTPCode,
548                 response)
549
550         // Authenticated non-admin request returns PermissionError.
551         response = IssueRequest(userReq)
552         ExpectStatusCode(t,
553                 "authenticated non-admin request",
554                 PermissionError.HTTPCode,
555                 response)
556
557         // Authenticated admin request for nonexistent block.
558         type deletecounter struct {
559                 Deleted int `json:"copies_deleted"`
560                 Failed  int `json:"copies_failed"`
561         }
562         var responseDc, expectedDc deletecounter
563
564         response = IssueRequest(superuserNonexistentBlockReq)
565         ExpectStatusCode(t,
566                 "data manager request, nonexistent block",
567                 http.StatusNotFound,
568                 response)
569
570         // Authenticated admin request for existing block while EnableDelete is false.
571         theConfig.EnableDelete = false
572         response = IssueRequest(superuserExistingBlockReq)
573         ExpectStatusCode(t,
574                 "authenticated request, existing block, method disabled",
575                 MethodDisabledError.HTTPCode,
576                 response)
577         theConfig.EnableDelete = true
578
579         // Authenticated admin request for existing block.
580         response = IssueRequest(superuserExistingBlockReq)
581         ExpectStatusCode(t,
582                 "data manager request, existing block",
583                 http.StatusOK,
584                 response)
585         // Expect response {"copies_deleted":1,"copies_failed":0}
586         expectedDc = deletecounter{1, 0}
587         json.NewDecoder(response.Body).Decode(&responseDc)
588         if responseDc != expectedDc {
589                 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
590                         expectedDc, responseDc)
591         }
592         // Confirm the block has been deleted
593         buf := make([]byte, BlockSize)
594         _, err := vols[0].Get(context.Background(), TestHash, buf)
595         var blockDeleted = os.IsNotExist(err)
596         if !blockDeleted {
597                 t.Error("superuserExistingBlockReq: block not deleted")
598         }
599
600         // A DELETE request on a block newer than BlobSignatureTTL
601         // should return success but leave the block on the volume.
602         vols[0].Put(context.Background(), TestHash, TestBlock)
603         theConfig.BlobSignatureTTL = arvados.Duration(time.Hour)
604
605         response = IssueRequest(superuserExistingBlockReq)
606         ExpectStatusCode(t,
607                 "data manager request, existing block",
608                 http.StatusOK,
609                 response)
610         // Expect response {"copies_deleted":1,"copies_failed":0}
611         expectedDc = deletecounter{1, 0}
612         json.NewDecoder(response.Body).Decode(&responseDc)
613         if responseDc != expectedDc {
614                 t.Errorf("superuserExistingBlockReq\nexpected: %+v\nreceived: %+v",
615                         expectedDc, responseDc)
616         }
617         // Confirm the block has NOT been deleted.
618         _, err = vols[0].Get(context.Background(), TestHash, buf)
619         if err != nil {
620                 t.Errorf("testing delete on new block: %s\n", err)
621         }
622 }
623
624 // TestPullHandler
625 //
626 // Test handling of the PUT /pull statement.
627 //
628 // Cases tested: syntactically valid and invalid pull lists, from the
629 // data manager and from unprivileged users:
630 //
631 //   1. Valid pull list from an ordinary user
632 //      (expected result: 401 Unauthorized)
633 //
634 //   2. Invalid pull request from an ordinary user
635 //      (expected result: 401 Unauthorized)
636 //
637 //   3. Valid pull request from the data manager
638 //      (expected result: 200 OK with request body "Received 3 pull
639 //      requests"
640 //
641 //   4. Invalid pull request from the data manager
642 //      (expected result: 400 Bad Request)
643 //
644 // Test that in the end, the pull manager received a good pull list with
645 // the expected number of requests.
646 //
647 // TODO(twp): test concurrency: launch 100 goroutines to update the
648 // pull list simultaneously.  Make sure that none of them return 400
649 // Bad Request and that pullq.GetList() returns a valid list.
650 //
651 func TestPullHandler(t *testing.T) {
652         defer teardown()
653
654         var userToken = "USER TOKEN"
655         theConfig.systemAuthToken = "DATA MANAGER TOKEN"
656
657         pullq = NewWorkQueue()
658
659         goodJSON := []byte(`[
660                 {
661                         "locator":"locator_with_two_servers",
662                         "servers":[
663                                 "server1",
664                                 "server2"
665                         ]
666                 },
667                 {
668                         "locator":"locator_with_no_servers",
669                         "servers":[]
670                 },
671                 {
672                         "locator":"",
673                         "servers":["empty_locator"]
674                 }
675         ]`)
676
677         badJSON := []byte(`{ "key":"I'm a little teapot" }`)
678
679         type pullTest struct {
680                 name         string
681                 req          RequestTester
682                 responseCode int
683                 responseBody string
684         }
685         var testcases = []pullTest{
686                 {
687                         "Valid pull list from an ordinary user",
688                         RequestTester{"/pull", userToken, "PUT", goodJSON},
689                         http.StatusUnauthorized,
690                         "Unauthorized\n",
691                 },
692                 {
693                         "Invalid pull request from an ordinary user",
694                         RequestTester{"/pull", userToken, "PUT", badJSON},
695                         http.StatusUnauthorized,
696                         "Unauthorized\n",
697                 },
698                 {
699                         "Valid pull request from the data manager",
700                         RequestTester{"/pull", theConfig.systemAuthToken, "PUT", goodJSON},
701                         http.StatusOK,
702                         "Received 3 pull requests\n",
703                 },
704                 {
705                         "Invalid pull request from the data manager",
706                         RequestTester{"/pull", theConfig.systemAuthToken, "PUT", badJSON},
707                         http.StatusBadRequest,
708                         "",
709                 },
710         }
711
712         for _, tst := range testcases {
713                 response := IssueRequest(&tst.req)
714                 ExpectStatusCode(t, tst.name, tst.responseCode, response)
715                 ExpectBody(t, tst.name, tst.responseBody, response)
716         }
717
718         // The Keep pull manager should have received one good list with 3
719         // requests on it.
720         for i := 0; i < 3; i++ {
721                 item := <-pullq.NextItem
722                 if _, ok := item.(PullRequest); !ok {
723                         t.Errorf("item %v could not be parsed as a PullRequest", item)
724                 }
725         }
726
727         expectChannelEmpty(t, pullq.NextItem)
728 }
729
730 // TestTrashHandler
731 //
732 // Test cases:
733 //
734 // Cases tested: syntactically valid and invalid trash lists, from the
735 // data manager and from unprivileged users:
736 //
737 //   1. Valid trash list from an ordinary user
738 //      (expected result: 401 Unauthorized)
739 //
740 //   2. Invalid trash list from an ordinary user
741 //      (expected result: 401 Unauthorized)
742 //
743 //   3. Valid trash list from the data manager
744 //      (expected result: 200 OK with request body "Received 3 trash
745 //      requests"
746 //
747 //   4. Invalid trash list from the data manager
748 //      (expected result: 400 Bad Request)
749 //
750 // Test that in the end, the trash collector received a good list
751 // trash list with the expected number of requests.
752 //
753 // TODO(twp): test concurrency: launch 100 goroutines to update the
754 // pull list simultaneously.  Make sure that none of them return 400
755 // Bad Request and that replica.Dump() returns a valid list.
756 //
757 func TestTrashHandler(t *testing.T) {
758         defer teardown()
759
760         var userToken = "USER TOKEN"
761         theConfig.systemAuthToken = "DATA MANAGER TOKEN"
762
763         trashq = NewWorkQueue()
764
765         goodJSON := []byte(`[
766                 {
767                         "locator":"block1",
768                         "block_mtime":1409082153
769                 },
770                 {
771                         "locator":"block2",
772                         "block_mtime":1409082153
773                 },
774                 {
775                         "locator":"block3",
776                         "block_mtime":1409082153
777                 }
778         ]`)
779
780         badJSON := []byte(`I am not a valid JSON string`)
781
782         type trashTest struct {
783                 name         string
784                 req          RequestTester
785                 responseCode int
786                 responseBody string
787         }
788
789         var testcases = []trashTest{
790                 {
791                         "Valid trash list from an ordinary user",
792                         RequestTester{"/trash", userToken, "PUT", goodJSON},
793                         http.StatusUnauthorized,
794                         "Unauthorized\n",
795                 },
796                 {
797                         "Invalid trash list from an ordinary user",
798                         RequestTester{"/trash", userToken, "PUT", badJSON},
799                         http.StatusUnauthorized,
800                         "Unauthorized\n",
801                 },
802                 {
803                         "Valid trash list from the data manager",
804                         RequestTester{"/trash", theConfig.systemAuthToken, "PUT", goodJSON},
805                         http.StatusOK,
806                         "Received 3 trash requests\n",
807                 },
808                 {
809                         "Invalid trash list from the data manager",
810                         RequestTester{"/trash", theConfig.systemAuthToken, "PUT", badJSON},
811                         http.StatusBadRequest,
812                         "",
813                 },
814         }
815
816         for _, tst := range testcases {
817                 response := IssueRequest(&tst.req)
818                 ExpectStatusCode(t, tst.name, tst.responseCode, response)
819                 ExpectBody(t, tst.name, tst.responseBody, response)
820         }
821
822         // The trash collector should have received one good list with 3
823         // requests on it.
824         for i := 0; i < 3; i++ {
825                 item := <-trashq.NextItem
826                 if _, ok := item.(TrashRequest); !ok {
827                         t.Errorf("item %v could not be parsed as a TrashRequest", item)
828                 }
829         }
830
831         expectChannelEmpty(t, trashq.NextItem)
832 }
833
834 // ====================
835 // Helper functions
836 // ====================
837
838 // IssueTestRequest executes an HTTP request described by rt, to a
839 // REST router.  It returns the HTTP response to the request.
840 func IssueRequest(rt *RequestTester) *httptest.ResponseRecorder {
841         response := httptest.NewRecorder()
842         body := bytes.NewReader(rt.requestBody)
843         req, _ := http.NewRequest(rt.method, rt.uri, body)
844         if rt.apiToken != "" {
845                 req.Header.Set("Authorization", "OAuth2 "+rt.apiToken)
846         }
847         loggingRouter := MakeRESTRouter(testCluster)
848         loggingRouter.ServeHTTP(response, req)
849         return response
850 }
851
852 func IssueHealthCheckRequest(rt *RequestTester) *httptest.ResponseRecorder {
853         response := httptest.NewRecorder()
854         body := bytes.NewReader(rt.requestBody)
855         req, _ := http.NewRequest(rt.method, rt.uri, body)
856         if rt.apiToken != "" {
857                 req.Header.Set("Authorization", "Bearer "+rt.apiToken)
858         }
859         loggingRouter := MakeRESTRouter(testCluster)
860         loggingRouter.ServeHTTP(response, req)
861         return response
862 }
863
864 // ExpectStatusCode checks whether a response has the specified status code,
865 // and reports a test failure if not.
866 func ExpectStatusCode(
867         t *testing.T,
868         testname string,
869         expectedStatus int,
870         response *httptest.ResponseRecorder) {
871         if response.Code != expectedStatus {
872                 t.Errorf("%s: expected status %d, got %+v",
873                         testname, expectedStatus, response)
874         }
875 }
876
877 func ExpectBody(
878         t *testing.T,
879         testname string,
880         expectedBody string,
881         response *httptest.ResponseRecorder) {
882         if expectedBody != "" && response.Body.String() != expectedBody {
883                 t.Errorf("%s: expected response body '%s', got %+v",
884                         testname, expectedBody, response)
885         }
886 }
887
888 // See #7121
889 func TestPutNeedsOnlyOneBuffer(t *testing.T) {
890         defer teardown()
891         KeepVM = MakeTestVolumeManager(1)
892         defer KeepVM.Close()
893
894         defer func(orig *bufferPool) {
895                 bufs = orig
896         }(bufs)
897         bufs = newBufferPool(1, BlockSize)
898
899         ok := make(chan struct{})
900         go func() {
901                 for i := 0; i < 2; i++ {
902                         response := IssueRequest(
903                                 &RequestTester{
904                                         method:      "PUT",
905                                         uri:         "/" + TestHash,
906                                         requestBody: TestBlock,
907                                 })
908                         ExpectStatusCode(t,
909                                 "TestPutNeedsOnlyOneBuffer", http.StatusOK, response)
910                 }
911                 ok <- struct{}{}
912         }()
913
914         select {
915         case <-ok:
916         case <-time.After(time.Second):
917                 t.Fatal("PUT deadlocks with MaxBuffers==1")
918         }
919 }
920
921 // Invoke the PutBlockHandler a bunch of times to test for bufferpool resource
922 // leak.
923 func TestPutHandlerNoBufferleak(t *testing.T) {
924         defer teardown()
925
926         // Prepare two test Keep volumes.
927         KeepVM = MakeTestVolumeManager(2)
928         defer KeepVM.Close()
929
930         ok := make(chan bool)
931         go func() {
932                 for i := 0; i < theConfig.MaxBuffers+1; i++ {
933                         // Unauthenticated request, no server key
934                         // => OK (unsigned response)
935                         unsignedLocator := "/" + TestHash
936                         response := IssueRequest(
937                                 &RequestTester{
938                                         method:      "PUT",
939                                         uri:         unsignedLocator,
940                                         requestBody: TestBlock,
941                                 })
942                         ExpectStatusCode(t,
943                                 "TestPutHandlerBufferleak", http.StatusOK, response)
944                         ExpectBody(t,
945                                 "TestPutHandlerBufferleak",
946                                 TestHashPutResp, 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 type notifyingResponseRecorder struct {
959         *httptest.ResponseRecorder
960         closer chan bool
961 }
962
963 func (r *notifyingResponseRecorder) CloseNotify() <-chan bool {
964         return r.closer
965 }
966
967 func TestGetHandlerClientDisconnect(t *testing.T) {
968         defer func(was bool) {
969                 theConfig.RequireSignatures = was
970         }(theConfig.RequireSignatures)
971         theConfig.RequireSignatures = false
972
973         defer func(orig *bufferPool) {
974                 bufs = orig
975         }(bufs)
976         bufs = newBufferPool(1, BlockSize)
977         defer bufs.Put(bufs.Get(BlockSize))
978
979         KeepVM = MakeTestVolumeManager(2)
980         defer KeepVM.Close()
981
982         if err := KeepVM.AllWritable()[0].Put(context.Background(), TestHash, TestBlock); err != nil {
983                 t.Error(err)
984         }
985
986         resp := &notifyingResponseRecorder{
987                 ResponseRecorder: httptest.NewRecorder(),
988                 closer:           make(chan bool, 1),
989         }
990         if _, ok := http.ResponseWriter(resp).(http.CloseNotifier); !ok {
991                 t.Fatal("notifyingResponseRecorder is broken")
992         }
993         // If anyone asks, the client has disconnected.
994         resp.closer <- true
995
996         ok := make(chan struct{})
997         go func() {
998                 req, _ := http.NewRequest("GET", fmt.Sprintf("/%s+%d", TestHash, len(TestBlock)), nil)
999                 MakeRESTRouter(testCluster).ServeHTTP(resp, req)
1000                 ok <- struct{}{}
1001         }()
1002
1003         select {
1004         case <-time.After(20 * time.Second):
1005                 t.Fatal("request took >20s, close notifier must be broken")
1006         case <-ok:
1007         }
1008
1009         ExpectStatusCode(t, "client disconnect", http.StatusServiceUnavailable, resp.ResponseRecorder)
1010         for i, v := range KeepVM.AllWritable() {
1011                 if calls := v.(*MockVolume).called["GET"]; calls != 0 {
1012                         t.Errorf("volume %d got %d calls, expected 0", i, calls)
1013                 }
1014         }
1015 }
1016
1017 // Invoke the GetBlockHandler a bunch of times to test for bufferpool resource
1018 // leak.
1019 func TestGetHandlerNoBufferLeak(t *testing.T) {
1020         defer teardown()
1021
1022         // Prepare two test Keep volumes. Our block is stored on the second volume.
1023         KeepVM = MakeTestVolumeManager(2)
1024         defer KeepVM.Close()
1025
1026         vols := KeepVM.AllWritable()
1027         if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
1028                 t.Error(err)
1029         }
1030
1031         ok := make(chan bool)
1032         go func() {
1033                 for i := 0; i < theConfig.MaxBuffers+1; i++ {
1034                         // Unauthenticated request, unsigned locator
1035                         // => OK
1036                         unsignedLocator := "/" + TestHash
1037                         response := IssueRequest(
1038                                 &RequestTester{
1039                                         method: "GET",
1040                                         uri:    unsignedLocator,
1041                                 })
1042                         ExpectStatusCode(t,
1043                                 "Unauthenticated request, unsigned locator", http.StatusOK, response)
1044                         ExpectBody(t,
1045                                 "Unauthenticated request, unsigned locator",
1046                                 string(TestBlock),
1047                                 response)
1048                 }
1049                 ok <- true
1050         }()
1051         select {
1052         case <-time.After(20 * time.Second):
1053                 // If the buffer pool leaks, the test goroutine hangs.
1054                 t.Fatal("test did not finish, assuming pool leaked")
1055         case <-ok:
1056         }
1057 }
1058
1059 func TestPutReplicationHeader(t *testing.T) {
1060         defer teardown()
1061
1062         KeepVM = MakeTestVolumeManager(2)
1063         defer KeepVM.Close()
1064
1065         resp := IssueRequest(&RequestTester{
1066                 method:      "PUT",
1067                 uri:         "/" + TestHash,
1068                 requestBody: TestBlock,
1069         })
1070         if r := resp.Header().Get("X-Keep-Replicas-Stored"); r != "1" {
1071                 t.Errorf("Got X-Keep-Replicas-Stored: %q, expected %q", r, "1")
1072         }
1073 }
1074
1075 func TestUntrashHandler(t *testing.T) {
1076         defer teardown()
1077
1078         // Set up Keep volumes
1079         KeepVM = MakeTestVolumeManager(2)
1080         defer KeepVM.Close()
1081         vols := KeepVM.AllWritable()
1082         vols[0].Put(context.Background(), TestHash, TestBlock)
1083
1084         theConfig.systemAuthToken = "DATA MANAGER TOKEN"
1085
1086         // unauthenticatedReq => UnauthorizedError
1087         unauthenticatedReq := &RequestTester{
1088                 method: "PUT",
1089                 uri:    "/untrash/" + TestHash,
1090         }
1091         response := IssueRequest(unauthenticatedReq)
1092         ExpectStatusCode(t,
1093                 "Unauthenticated request",
1094                 UnauthorizedError.HTTPCode,
1095                 response)
1096
1097         // notDataManagerReq => UnauthorizedError
1098         notDataManagerReq := &RequestTester{
1099                 method:   "PUT",
1100                 uri:      "/untrash/" + TestHash,
1101                 apiToken: knownToken,
1102         }
1103
1104         response = IssueRequest(notDataManagerReq)
1105         ExpectStatusCode(t,
1106                 "Non-datamanager token",
1107                 UnauthorizedError.HTTPCode,
1108                 response)
1109
1110         // datamanagerWithBadHashReq => StatusBadRequest
1111         datamanagerWithBadHashReq := &RequestTester{
1112                 method:   "PUT",
1113                 uri:      "/untrash/thisisnotalocator",
1114                 apiToken: theConfig.systemAuthToken,
1115         }
1116         response = IssueRequest(datamanagerWithBadHashReq)
1117         ExpectStatusCode(t,
1118                 "Bad locator in untrash request",
1119                 http.StatusBadRequest,
1120                 response)
1121
1122         // datamanagerWrongMethodReq => StatusBadRequest
1123         datamanagerWrongMethodReq := &RequestTester{
1124                 method:   "GET",
1125                 uri:      "/untrash/" + TestHash,
1126                 apiToken: theConfig.systemAuthToken,
1127         }
1128         response = IssueRequest(datamanagerWrongMethodReq)
1129         ExpectStatusCode(t,
1130                 "Only PUT method is supported for untrash",
1131                 http.StatusMethodNotAllowed,
1132                 response)
1133
1134         // datamanagerReq => StatusOK
1135         datamanagerReq := &RequestTester{
1136                 method:   "PUT",
1137                 uri:      "/untrash/" + TestHash,
1138                 apiToken: theConfig.systemAuthToken,
1139         }
1140         response = IssueRequest(datamanagerReq)
1141         ExpectStatusCode(t,
1142                 "",
1143                 http.StatusOK,
1144                 response)
1145         expected := "Successfully untrashed on: [MockVolume],[MockVolume]"
1146         if response.Body.String() != expected {
1147                 t.Errorf(
1148                         "Untrash response mismatched: expected %s, got:\n%s",
1149                         expected, response.Body.String())
1150         }
1151 }
1152
1153 func TestUntrashHandlerWithNoWritableVolumes(t *testing.T) {
1154         defer teardown()
1155
1156         // Set up readonly Keep volumes
1157         vols := []*MockVolume{CreateMockVolume(), CreateMockVolume()}
1158         vols[0].Readonly = true
1159         vols[1].Readonly = true
1160         KeepVM = MakeRRVolumeManager([]Volume{vols[0], vols[1]})
1161         defer KeepVM.Close()
1162
1163         theConfig.systemAuthToken = "DATA MANAGER TOKEN"
1164
1165         // datamanagerReq => StatusOK
1166         datamanagerReq := &RequestTester{
1167                 method:   "PUT",
1168                 uri:      "/untrash/" + TestHash,
1169                 apiToken: theConfig.systemAuthToken,
1170         }
1171         response := IssueRequest(datamanagerReq)
1172         ExpectStatusCode(t,
1173                 "No writable volumes",
1174                 http.StatusNotFound,
1175                 response)
1176 }
1177
1178 func TestHealthCheckPing(t *testing.T) {
1179         theConfig.ManagementToken = arvadostest.ManagementToken
1180         pingReq := &RequestTester{
1181                 method:   "GET",
1182                 uri:      "/_health/ping",
1183                 apiToken: arvadostest.ManagementToken,
1184         }
1185         response := IssueHealthCheckRequest(pingReq)
1186         ExpectStatusCode(t,
1187                 "",
1188                 http.StatusOK,
1189                 response)
1190         want := `{"health":"OK"}`
1191         if !strings.Contains(response.Body.String(), want) {
1192                 t.Errorf("expected response to include %s: got %s", want, response.Body.String())
1193         }
1194 }