8936: address review comments
[arvados.git] / tools / keep-block-check / keep-block-check_test.go
1 package main
2
3 import (
4         "bytes"
5         "fmt"
6         "io"
7         "io/ioutil"
8         "log"
9         "os"
10         "regexp"
11         "strings"
12         "testing"
13         "time"
14
15         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
16         "git.curoverse.com/arvados.git/sdk/go/keepclient"
17
18         . "gopkg.in/check.v1"
19 )
20
21 // Gocheck boilerplate
22 func Test(t *testing.T) {
23         TestingT(t)
24 }
25
26 // Gocheck boilerplate
27 var _ = Suite(&ServerRequiredSuite{})
28 var _ = Suite(&DoMainTestSuite{})
29
30 type ServerRequiredSuite struct{}
31 type DoMainTestSuite struct{}
32
33 var kc *keepclient.KeepClient
34 var logBuffer bytes.Buffer
35
36 var TestHash = "aaaa09c290d0fb1ca068ffaddf22cbd0"
37 var TestHash2 = "aaaac516f788aec4f30932ffb6395c39"
38
39 var blobSignatureTTL = time.Duration(2*7*24) * time.Hour
40
41 func (s *ServerRequiredSuite) SetUpSuite(c *C) {
42         arvadostest.StartAPI()
43 }
44
45 func (s *ServerRequiredSuite) TearDownSuite(c *C) {
46         arvadostest.StopAPI()
47         arvadostest.ResetEnv()
48 }
49
50 func (s *ServerRequiredSuite) SetUpTest(c *C) {
51         logOutput := io.MultiWriter(&logBuffer)
52         log.SetOutput(logOutput)
53 }
54
55 func (s *ServerRequiredSuite) TearDownTest(c *C) {
56         arvadostest.StopKeep(2)
57         log.SetOutput(os.Stdout)
58         log.Printf("%v", logBuffer.String())
59 }
60
61 func (s *DoMainTestSuite) SetUpSuite(c *C) {
62 }
63
64 func (s *DoMainTestSuite) SetUpTest(c *C) {
65         logOutput := io.MultiWriter(&logBuffer)
66         log.SetOutput(logOutput)
67 }
68
69 func (s *DoMainTestSuite) TearDownTest(c *C) {
70         log.SetOutput(os.Stdout)
71         log.Printf("%v", logBuffer.String())
72 }
73
74 func setupKeepBlockCheck(c *C, enforcePermissions bool, keepServicesJSON string) {
75         var config apiConfig
76         config.APIHost = os.Getenv("ARVADOS_API_HOST")
77         config.APIToken = arvadostest.DataManagerToken
78         config.APIHostInsecure = matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
79
80         // Start Keep servers
81         arvadostest.StartKeep(2, enforcePermissions)
82
83         // setup keepclients
84         var err error
85         kc, err = setupKeepClient(config, keepServicesJSON, blobSignatureTTL)
86         c.Check(err, IsNil)
87 }
88
89 // Setup test data
90 func setupTestData(c *C) []string {
91         allLocators := []string{}
92
93         // Put a few blocks
94         for i := 0; i < 5; i++ {
95                 hash, _, err := kc.PutB([]byte(fmt.Sprintf("keep-block-check-test-data-%d", i)))
96                 c.Check(err, IsNil)
97                 allLocators = append(allLocators, strings.Split(hash, "+A")[0])
98         }
99
100         return allLocators
101 }
102
103 func setupConfigFile(c *C, fileName string) string {
104         // Setup a config file
105         file, err := ioutil.TempFile(os.TempDir(), fileName)
106         c.Check(err, IsNil)
107
108         // Add config to file. While at it, throw some extra white space
109         fileContent := "ARVADOS_API_HOST=" + os.Getenv("ARVADOS_API_HOST") + "\n"
110         fileContent += "ARVADOS_API_TOKEN=" + arvadostest.DataManagerToken + "\n"
111         fileContent += "\n"
112         fileContent += "ARVADOS_API_HOST_INSECURE=" + os.Getenv("ARVADOS_API_HOST_INSECURE") + "\n"
113         fileContent += " ARVADOS_EXTERNAL_CLIENT = false \n"
114         fileContent += " NotANameValuePairAndShouldGetIgnored \n"
115         fileContent += "ARVADOS_BLOB_SIGNING_KEY=abcdefg\n"
116
117         _, err = file.Write([]byte(fileContent))
118         c.Check(err, IsNil)
119
120         return file.Name()
121 }
122
123 func setupBlockHashFile(c *C, name string, blocks []string) string {
124         // Setup a block hash file
125         file, err := ioutil.TempFile(os.TempDir(), name)
126         c.Check(err, IsNil)
127
128         // Add the hashes to the file. While at it, throw some extra white space
129         fileContent := ""
130         for _, hash := range blocks {
131                 fileContent += fmt.Sprintf(" %s \n", hash)
132         }
133         fileContent += "\n"
134         _, err = file.Write([]byte(fileContent))
135         c.Check(err, IsNil)
136
137         return file.Name()
138 }
139
140 func checkErrorLog(c *C, blocks []string, prefix, suffix string) {
141         for _, hash := range blocks {
142                 expected := prefix + `.*` + hash + `.*` + suffix
143                 match, _ := regexp.MatchString(expected, logBuffer.String())
144                 c.Assert(match, Equals, true)
145         }
146 }
147
148 func checkNoErrorsLogged(c *C, prefix, suffix string) {
149         expected := prefix + `.*` + suffix
150         match, _ := regexp.MatchString(expected, logBuffer.String())
151         c.Assert(match, Equals, false)
152 }
153
154 func (s *ServerRequiredSuite) TestBlockCheck(c *C) {
155         setupKeepBlockCheck(c, false, "")
156         allLocators := setupTestData(c)
157         err := performKeepBlockCheck(kc, blobSignatureTTL, "", allLocators, true)
158         c.Check(err, IsNil)
159         checkNoErrorsLogged(c, "Error verifying block", "Block not found")
160 }
161
162 func (s *ServerRequiredSuite) TestBlockCheckWithBlobSigning(c *C) {
163         setupKeepBlockCheck(c, true, "")
164         allLocators := setupTestData(c)
165         err := performKeepBlockCheck(kc, blobSignatureTTL, arvadostest.BlobSigningKey, allLocators, true)
166         c.Check(err, IsNil)
167         checkNoErrorsLogged(c, "Error verifying block", "Block not found")
168 }
169
170 func (s *ServerRequiredSuite) TestBlockCheck_NoSuchBlock(c *C) {
171         setupKeepBlockCheck(c, false, "")
172         allLocators := setupTestData(c)
173         allLocators = append(allLocators, TestHash)
174         allLocators = append(allLocators, TestHash2)
175         err := performKeepBlockCheck(kc, blobSignatureTTL, "", allLocators, true)
176         c.Check(err, NotNil)
177         c.Assert(err.Error(), Equals, "Block verification failed for 2 out of 7 blocks with matching prefix.")
178         checkErrorLog(c, []string{TestHash, TestHash2}, "Error verifying block", "Block not found")
179 }
180
181 func (s *ServerRequiredSuite) TestBlockCheck_NoSuchBlock_WithMatchingPrefix(c *C) {
182         setupKeepBlockCheck(c, false, "")
183         allLocators := setupTestData(c)
184         allLocators = append(allLocators, TestHash)
185         allLocators = append(allLocators, TestHash2)
186         locatorFile := setupBlockHashFile(c, "block-hash", allLocators)
187         defer os.Remove(locatorFile)
188         locators, err := getBlockLocators(locatorFile, "aaa")
189         c.Check(err, IsNil)
190         err = performKeepBlockCheck(kc, blobSignatureTTL, "", locators, true)
191         c.Check(err, NotNil)
192         // Of the 7 blocks in allLocators, only two match the prefix and hence only those are checked
193         c.Assert(err.Error(), Equals, "Block verification failed for 2 out of 2 blocks with matching prefix.")
194         checkErrorLog(c, []string{TestHash, TestHash2}, "Error verifying block", "Block not found")
195 }
196
197 func (s *ServerRequiredSuite) TestBlockCheck_NoSuchBlock_WithPrefixMismatch(c *C) {
198         setupKeepBlockCheck(c, false, "")
199         allLocators := setupTestData(c)
200         allLocators = append(allLocators, TestHash)
201         allLocators = append(allLocators, TestHash2)
202         locatorFile := setupBlockHashFile(c, "block-hash", allLocators)
203         defer os.Remove(locatorFile)
204         locators, err := getBlockLocators(locatorFile, "999")
205         c.Check(err, IsNil)
206         err = performKeepBlockCheck(kc, blobSignatureTTL, "", locators, true)
207         c.Check(err, IsNil) // there were no matching locators in file and hence nothing was checked
208 }
209
210 func (s *ServerRequiredSuite) TestBlockCheck_BadSignature(c *C) {
211         setupKeepBlockCheck(c, true, "")
212         setupTestData(c)
213         err := performKeepBlockCheck(kc, blobSignatureTTL, "badblobsigningkey", []string{TestHash, TestHash2}, false)
214         c.Assert(err.Error(), Equals, "Block verification failed for 2 out of 2 blocks with matching prefix.")
215         checkErrorLog(c, []string{TestHash, TestHash2}, "Error verifying block", "HTTP 403")
216         // verbose logging not requested
217         c.Assert(strings.Contains(logBuffer.String(), "Verifying block 1 of 2"), Equals, false)
218 }
219
220 var testKeepServicesJSON = `{
221   "kind":"arvados#keepServiceList",
222   "etag":"",
223   "self_link":"",
224   "offset":null, "limit":null,
225   "items":[
226     {"href":"/keep_services/zzzzz-bi6l4-123456789012340",
227      "kind":"arvados#keepService",
228      "uuid":"zzzzz-bi6l4-123456789012340",
229      "service_host":"keep0.zzzzz.arvadosapi.com",
230      "service_port":25107,
231      "service_ssl_flag":false,
232      "service_type":"disk",
233      "read_only":false },
234     {"href":"/keep_services/zzzzz-bi6l4-123456789012341",
235      "kind":"arvados#keepService",
236      "uuid":"zzzzz-bi6l4-123456789012341",
237      "service_host":"keep0.zzzzz.arvadosapi.com",
238      "service_port":25108,
239      "service_ssl_flag":false,
240      "service_type":"disk",
241      "read_only":false }
242     ],
243   "items_available":2 }`
244
245 // Setup block-check using keepServicesJSON with fake keepservers.
246 // Expect error during performKeepBlockCheck due to unreachable keepservers.
247 func (s *ServerRequiredSuite) TestErrorDuringKeepBlockCheck_FakeKeepservers(c *C) {
248         setupKeepBlockCheck(c, false, testKeepServicesJSON)
249         err := performKeepBlockCheck(kc, blobSignatureTTL, "", []string{TestHash, TestHash2}, true)
250         c.Assert(err.Error(), Equals, "Block verification failed for 2 out of 2 blocks with matching prefix.")
251         checkErrorLog(c, []string{TestHash, TestHash2}, "Error verifying block", "")
252 }
253
254 // Test keep-block-check initialization with keepServicesJSON
255 func (s *ServerRequiredSuite) TestKeepBlockCheck_InitializeWithKeepServicesJSON(c *C) {
256         setupKeepBlockCheck(c, false, testKeepServicesJSON)
257         found := 0
258         for k := range kc.LocalRoots() {
259                 if k == "zzzzz-bi6l4-123456789012340" || k == "zzzzz-bi6l4-123456789012341" {
260                         found++
261                 }
262         }
263         c.Check(found, Equals, 2)
264 }
265
266 // Test loadConfig func
267 func (s *ServerRequiredSuite) TestLoadConfig(c *C) {
268         // Setup config file
269         configFile := setupConfigFile(c, "config")
270         defer os.Remove(configFile)
271
272         // load configuration from the file
273         config, blobSigningKey, err := loadConfig(configFile)
274         c.Check(err, IsNil)
275
276         c.Assert(config.APIHost, Equals, os.Getenv("ARVADOS_API_HOST"))
277         c.Assert(config.APIToken, Equals, arvadostest.DataManagerToken)
278         c.Assert(config.APIHostInsecure, Equals, matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE")))
279         c.Assert(config.ExternalClient, Equals, false)
280         c.Assert(blobSigningKey, Equals, "abcdefg")
281 }
282
283 func (s *DoMainTestSuite) Test_doMain_WithNoConfig(c *C) {
284         args := []string{"-prefix", "a"}
285         err := doMain(args)
286         c.Check(err, NotNil)
287         c.Assert(strings.Contains(err.Error(), "config file not specified"), Equals, true)
288 }
289
290 func (s *DoMainTestSuite) Test_doMain_WithNoSuchConfigFile(c *C) {
291         args := []string{"-config", "no-such-file"}
292         err := doMain(args)
293         c.Check(err, NotNil)
294         c.Assert(strings.Contains(err.Error(), "no such file or directory"), Equals, true)
295 }
296
297 func (s *DoMainTestSuite) Test_doMain_WithNoBlockHashFile(c *C) {
298         config := setupConfigFile(c, "config")
299         defer os.Remove(config)
300
301         // Start keepservers.
302         arvadostest.StartKeep(2, false)
303         defer arvadostest.StopKeep(2)
304
305         args := []string{"-config", config}
306         err := doMain(args)
307         c.Assert(strings.Contains(err.Error(), "block-hash-file not specified"), Equals, true)
308 }
309
310 func (s *DoMainTestSuite) Test_doMain_WithNoSuchBlockHashFile(c *C) {
311         config := setupConfigFile(c, "config")
312         defer os.Remove(config)
313
314         arvadostest.StartKeep(2, false)
315         defer arvadostest.StopKeep(2)
316
317         args := []string{"-config", config, "-block-hash-file", "no-such-file"}
318         err := doMain(args)
319         c.Assert(strings.Contains(err.Error(), "no such file or directory"), Equals, true)
320 }
321
322 func (s *DoMainTestSuite) Test_doMain(c *C) {
323         // Start keepservers.
324         arvadostest.StartKeep(2, false)
325         defer arvadostest.StopKeep(2)
326
327         config := setupConfigFile(c, "config")
328         defer os.Remove(config)
329
330         locatorFile := setupBlockHashFile(c, "block-hash", []string{TestHash, TestHash2})
331         defer os.Remove(locatorFile)
332
333         args := []string{"-config", config, "-block-hash-file", locatorFile, "-v"}
334         err := doMain(args)
335         c.Check(err, NotNil)
336         c.Assert(err.Error(), Equals, "Block verification failed for 2 out of 2 blocks with matching prefix.")
337         checkErrorLog(c, []string{TestHash, TestHash2}, "Error verifying block", "Block not found")
338         c.Assert(strings.Contains(logBuffer.String(), "Verifying block 1 of 2"), Equals, true)
339 }