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