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