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