7492: better error reporting of upstream errors in keepproxy.
[arvados.git] / services / keepproxy / keepproxy_test.go
1 package main
2
3 import (
4         "crypto/md5"
5         "crypto/tls"
6         "fmt"
7         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
8         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
9         "git.curoverse.com/arvados.git/sdk/go/keepclient"
10         . "gopkg.in/check.v1"
11         "io"
12         "io/ioutil"
13         "log"
14         "net/http"
15         "net/url"
16         "os"
17         "strings"
18         "testing"
19         "time"
20 )
21
22 // Gocheck boilerplate
23 func Test(t *testing.T) {
24         TestingT(t)
25 }
26
27 // Gocheck boilerplate
28 var _ = Suite(&ServerRequiredSuite{})
29
30 // Tests that require the Keep server running
31 type ServerRequiredSuite struct{}
32
33 // Wait (up to 1 second) for keepproxy to listen on a port. This
34 // avoids a race condition where we hit a "connection refused" error
35 // because we start testing the proxy too soon.
36 func waitForListener() {
37         const (
38                 ms = 5
39         )
40         for i := 0; listener == nil && i < 1000; i += ms {
41                 time.Sleep(ms * time.Millisecond)
42         }
43         if listener == nil {
44                 log.Fatalf("Timed out waiting for listener to start")
45         }
46 }
47
48 func closeListener() {
49         if listener != nil {
50                 listener.Close()
51         }
52 }
53
54 func (s *ServerRequiredSuite) SetUpSuite(c *C) {
55         arvadostest.StartAPI()
56         arvadostest.StartKeep(2, false)
57 }
58
59 func (s *ServerRequiredSuite) SetUpTest(c *C) {
60         arvadostest.ResetEnv()
61 }
62
63 func (s *ServerRequiredSuite) TearDownSuite(c *C) {
64         arvadostest.StopKeep(2)
65         arvadostest.StopAPI()
66 }
67
68 func setupProxyService() {
69
70         client := &http.Client{Transport: &http.Transport{
71                 TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}}
72
73         var req *http.Request
74         var err error
75         if req, err = http.NewRequest("POST", fmt.Sprintf("https://%s/arvados/v1/keep_services", os.Getenv("ARVADOS_API_HOST")), nil); err != nil {
76                 panic(err.Error())
77         }
78         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", os.Getenv("ARVADOS_API_TOKEN")))
79
80         reader, writer := io.Pipe()
81
82         req.Body = reader
83
84         go func() {
85                 data := url.Values{}
86                 data.Set("keep_service", `{
87   "service_host": "localhost",
88   "service_port": 29950,
89   "service_ssl_flag": false,
90   "service_type": "proxy"
91 }`)
92
93                 writer.Write([]byte(data.Encode()))
94                 writer.Close()
95         }()
96
97         var resp *http.Response
98         if resp, err = client.Do(req); err != nil {
99                 panic(err.Error())
100         }
101         if resp.StatusCode != 200 {
102                 panic(resp.Status)
103         }
104 }
105
106 func runProxy(c *C, args []string, port int, bogusClientToken bool) keepclient.KeepClient {
107         if bogusClientToken {
108                 os.Setenv("ARVADOS_API_TOKEN", "bogus-token")
109         }
110         arv, err := arvadosclient.MakeArvadosClient()
111         c.Assert(err, Equals, nil)
112         kc := keepclient.KeepClient{
113                 Arvados:       &arv,
114                 Want_replicas: 2,
115                 Using_proxy:   true,
116                 Client:        &http.Client{},
117         }
118         locals := map[string]string{
119                 "proxy": fmt.Sprintf("http://localhost:%v", port),
120         }
121         writableLocals := map[string]string{
122                 "proxy": fmt.Sprintf("http://localhost:%v", port),
123         }
124         kc.SetServiceRoots(locals, writableLocals, nil)
125         c.Check(kc.Using_proxy, Equals, true)
126         c.Check(len(kc.LocalRoots()), Equals, 1)
127         for _, root := range kc.LocalRoots() {
128                 c.Check(root, Equals, fmt.Sprintf("http://localhost:%v", port))
129         }
130         log.Print("keepclient created")
131         if bogusClientToken {
132                 arvadostest.ResetEnv()
133         }
134
135         {
136                 os.Args = append(args, fmt.Sprintf("-listen=:%v", port))
137                 listener = nil
138                 go main()
139         }
140
141         return kc
142 }
143
144 func (s *ServerRequiredSuite) TestPutAskGet(c *C) {
145         log.Print("TestPutAndGet start")
146
147         os.Args = []string{"keepproxy", "-listen=:29950"}
148         listener = nil
149         go main()
150         time.Sleep(100 * time.Millisecond)
151
152         setupProxyService()
153
154         os.Setenv("ARVADOS_EXTERNAL_CLIENT", "true")
155         arv, err := arvadosclient.MakeArvadosClient()
156         c.Assert(err, Equals, nil)
157         kc, err := keepclient.MakeKeepClient(&arv)
158         c.Assert(err, Equals, nil)
159         c.Check(kc.Arvados.External, Equals, true)
160         c.Check(kc.Using_proxy, Equals, true)
161         c.Check(len(kc.LocalRoots()), Equals, 1)
162         for _, root := range kc.LocalRoots() {
163                 c.Check(root, Equals, "http://localhost:29950")
164         }
165         os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
166
167         waitForListener()
168         defer closeListener()
169
170         hash := fmt.Sprintf("%x", md5.Sum([]byte("foo")))
171         var hash2 string
172
173         {
174                 _, _, err := kc.Ask(hash)
175                 errNotFound, _ := err.(keepclient.ErrNotFound)
176                 c.Check(errNotFound, NotNil)
177                 c.Check(strings.Contains(err.Error(), "Block not found"), Equals, true)
178                 log.Print("Finished Ask (expected BlockNotFound)")
179         }
180
181         {
182                 reader, _, _, err := kc.Get(hash)
183                 c.Check(reader, Equals, nil)
184                 errNotFound, _ := err.(keepclient.ErrNotFound)
185                 c.Check(errNotFound, NotNil)
186                 c.Check(strings.Contains(err.Error(), "Block not found"), Equals, true)
187                 log.Print("Finished Get (expected BlockNotFound)")
188         }
189
190         // Note in bug #5309 among other errors keepproxy would set
191         // Content-Length incorrectly on the 404 BlockNotFound response, this
192         // would result in a protocol violation that would prevent reuse of the
193         // connection, which would manifest by the next attempt to use the
194         // connection (in this case the PutB below) failing.  So to test for
195         // that bug it's necessary to trigger an error response (such as
196         // BlockNotFound) and then do something else with the same httpClient
197         // connection.
198
199         {
200                 var rep int
201                 var err error
202                 hash2, rep, err = kc.PutB([]byte("foo"))
203                 c.Check(hash2, Matches, fmt.Sprintf(`^%s\+3(\+.+)?$`, hash))
204                 c.Check(rep, Equals, 2)
205                 c.Check(err, Equals, nil)
206                 log.Print("Finished PutB (expected success)")
207         }
208
209         {
210                 blocklen, _, err := kc.Ask(hash2)
211                 c.Assert(err, Equals, nil)
212                 c.Check(blocklen, Equals, int64(3))
213                 log.Print("Finished Ask (expected success)")
214         }
215
216         {
217                 reader, blocklen, _, err := kc.Get(hash2)
218                 c.Assert(err, Equals, nil)
219                 all, err := ioutil.ReadAll(reader)
220                 c.Check(all, DeepEquals, []byte("foo"))
221                 c.Check(blocklen, Equals, int64(3))
222                 log.Print("Finished Get (expected success)")
223         }
224
225         {
226                 var rep int
227                 var err error
228                 hash2, rep, err = kc.PutB([]byte(""))
229                 c.Check(hash2, Matches, `^d41d8cd98f00b204e9800998ecf8427e\+0(\+.+)?$`)
230                 c.Check(rep, Equals, 2)
231                 c.Check(err, Equals, nil)
232                 log.Print("Finished PutB zero block")
233         }
234
235         {
236                 reader, blocklen, _, err := kc.Get("d41d8cd98f00b204e9800998ecf8427e")
237                 c.Assert(err, Equals, nil)
238                 all, err := ioutil.ReadAll(reader)
239                 c.Check(all, DeepEquals, []byte(""))
240                 c.Check(blocklen, Equals, int64(0))
241                 log.Print("Finished Get zero block")
242         }
243
244         log.Print("TestPutAndGet done")
245 }
246
247 func (s *ServerRequiredSuite) TestPutAskGetForbidden(c *C) {
248         log.Print("TestPutAskGetForbidden start")
249
250         kc := runProxy(c, []string{"keepproxy"}, 29951, true)
251         waitForListener()
252         defer closeListener()
253
254         hash := fmt.Sprintf("%x", md5.Sum([]byte("bar")))
255
256         {
257                 _, _, err := kc.Ask(hash)
258                 errNotFound, _ := err.(keepclient.ErrNotFound)
259                 c.Check(errNotFound, NotNil)
260                 c.Assert(strings.Contains(err.Error(), "HTTP 403"), Equals, true)
261                 log.Print("Ask 1")
262         }
263
264         {
265                 hash2, rep, err := kc.PutB([]byte("bar"))
266                 c.Check(hash2, Equals, "")
267                 c.Check(rep, Equals, 0)
268                 c.Check(err, Equals, keepclient.InsufficientReplicasError)
269                 log.Print("PutB")
270         }
271
272         {
273                 blocklen, _, err := kc.Ask(hash)
274                 errNotFound, _ := err.(keepclient.ErrNotFound)
275                 c.Check(errNotFound, NotNil)
276                 c.Assert(strings.Contains(err.Error(), "HTTP 403"), Equals, true)
277                 c.Check(blocklen, Equals, int64(0))
278                 log.Print("Ask 2")
279         }
280
281         {
282                 _, blocklen, _, err := kc.Get(hash)
283                 errNotFound, _ := err.(keepclient.ErrNotFound)
284                 c.Check(errNotFound, NotNil)
285                 c.Assert(strings.Contains(err.Error(), "HTTP 403"), Equals, true)
286                 c.Check(blocklen, Equals, int64(0))
287                 log.Print("Get")
288         }
289
290         log.Print("TestPutAskGetForbidden done")
291 }
292
293 func (s *ServerRequiredSuite) TestGetDisabled(c *C) {
294         log.Print("TestGetDisabled start")
295
296         kc := runProxy(c, []string{"keepproxy", "-no-get"}, 29952, false)
297         waitForListener()
298         defer closeListener()
299
300         hash := fmt.Sprintf("%x", md5.Sum([]byte("baz")))
301
302         {
303                 _, _, err := kc.Ask(hash)
304                 errNotFound, _ := err.(keepclient.ErrNotFound)
305                 c.Check(errNotFound, NotNil)
306                 c.Assert(strings.Contains(err.Error(), "HTTP 400"), Equals, true)
307                 log.Print("Ask 1")
308         }
309
310         {
311                 hash2, rep, err := kc.PutB([]byte("baz"))
312                 c.Check(hash2, Matches, fmt.Sprintf(`^%s\+3(\+.+)?$`, hash))
313                 c.Check(rep, Equals, 2)
314                 c.Check(err, Equals, nil)
315                 log.Print("PutB")
316         }
317
318         {
319                 blocklen, _, err := kc.Ask(hash)
320                 errNotFound, _ := err.(keepclient.ErrNotFound)
321                 c.Check(errNotFound, NotNil)
322                 c.Assert(strings.Contains(err.Error(), "HTTP 400"), Equals, true)
323                 c.Check(blocklen, Equals, int64(0))
324                 log.Print("Ask 2")
325         }
326
327         {
328                 _, blocklen, _, err := kc.Get(hash)
329                 errNotFound, _ := err.(keepclient.ErrNotFound)
330                 c.Check(errNotFound, NotNil)
331                 c.Assert(strings.Contains(err.Error(), "HTTP 400"), Equals, true)
332                 c.Check(blocklen, Equals, int64(0))
333                 log.Print("Get")
334         }
335
336         log.Print("TestGetDisabled done")
337 }
338
339 func (s *ServerRequiredSuite) TestPutDisabled(c *C) {
340         log.Print("TestPutDisabled start")
341
342         kc := runProxy(c, []string{"keepproxy", "-no-put"}, 29953, false)
343         waitForListener()
344         defer closeListener()
345
346         {
347                 hash2, rep, err := kc.PutB([]byte("quux"))
348                 c.Check(hash2, Equals, "")
349                 c.Check(rep, Equals, 0)
350                 c.Check(err, Equals, keepclient.InsufficientReplicasError)
351                 log.Print("PutB")
352         }
353
354         log.Print("TestPutDisabled done")
355 }
356
357 func (s *ServerRequiredSuite) TestCorsHeaders(c *C) {
358         runProxy(c, []string{"keepproxy"}, 29954, false)
359         waitForListener()
360         defer closeListener()
361
362         {
363                 client := http.Client{}
364                 req, err := http.NewRequest("OPTIONS",
365                         fmt.Sprintf("http://localhost:29954/%x+3",
366                                 md5.Sum([]byte("foo"))),
367                         nil)
368                 req.Header.Add("Access-Control-Request-Method", "PUT")
369                 req.Header.Add("Access-Control-Request-Headers", "Authorization, X-Keep-Desired-Replicas")
370                 resp, err := client.Do(req)
371                 c.Check(err, Equals, nil)
372                 c.Check(resp.StatusCode, Equals, 200)
373                 body, err := ioutil.ReadAll(resp.Body)
374                 c.Check(string(body), Equals, "")
375                 c.Check(resp.Header.Get("Access-Control-Allow-Methods"), Equals, "GET, HEAD, POST, PUT, OPTIONS")
376                 c.Check(resp.Header.Get("Access-Control-Allow-Origin"), Equals, "*")
377         }
378
379         {
380                 resp, err := http.Get(
381                         fmt.Sprintf("http://localhost:29954/%x+3",
382                                 md5.Sum([]byte("foo"))))
383                 c.Check(err, Equals, nil)
384                 c.Check(resp.Header.Get("Access-Control-Allow-Headers"), Equals, "Authorization, Content-Length, Content-Type, X-Keep-Desired-Replicas")
385                 c.Check(resp.Header.Get("Access-Control-Allow-Origin"), Equals, "*")
386         }
387 }
388
389 func (s *ServerRequiredSuite) TestPostWithoutHash(c *C) {
390         runProxy(c, []string{"keepproxy"}, 29955, false)
391         waitForListener()
392         defer closeListener()
393
394         {
395                 client := http.Client{}
396                 req, err := http.NewRequest("POST",
397                         "http://localhost:29955/",
398                         strings.NewReader("qux"))
399                 req.Header.Add("Authorization", "OAuth2 4axaw8zxe0qm22wa6urpp5nskcne8z88cvbupv653y1njyi05h")
400                 req.Header.Add("Content-Type", "application/octet-stream")
401                 resp, err := client.Do(req)
402                 c.Check(err, Equals, nil)
403                 body, err := ioutil.ReadAll(resp.Body)
404                 c.Check(err, Equals, nil)
405                 c.Check(string(body), Matches,
406                         fmt.Sprintf(`^%x\+3(\+.+)?$`, md5.Sum([]byte("qux"))))
407         }
408 }
409
410 func (s *ServerRequiredSuite) TestStripHint(c *C) {
411         c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73+K@zzzzz", "$1"),
412                 Equals,
413                 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73")
414         c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+K@zzzzz+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73", "$1"),
415                 Equals,
416                 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73")
417         c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz", "$1"),
418                 Equals,
419                 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz")
420         c.Check(removeHint.ReplaceAllString("http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73", "$1"),
421                 Equals,
422                 "http://keep.zzzzz.arvadosapi.com:25107/2228819a18d3727630fa30c81853d23f+67108864+K@zzzzz-zzzzz-zzzzzzzzzzzzzzz+A37b6ab198qqqq28d903b975266b23ee711e1852c@55635f73")
423
424 }
425
426 // Test GetIndex
427 //   Put one block, with 2 replicas
428 //   With no prefix (expect the block locator, twice)
429 //   With an existing prefix (expect the block locator, twice)
430 //   With a valid but non-existing prefix (expect "\n")
431 //   With an invalid prefix (expect error)
432 func (s *ServerRequiredSuite) TestGetIndex(c *C) {
433         kc := runProxy(c, []string{"keepproxy"}, 28852, false)
434         waitForListener()
435         defer closeListener()
436
437         // Put "index-data" blocks
438         data := []byte("index-data")
439         hash := fmt.Sprintf("%x", md5.Sum(data))
440
441         hash2, rep, err := kc.PutB(data)
442         c.Check(hash2, Matches, fmt.Sprintf(`^%s\+10(\+.+)?$`, hash))
443         c.Check(rep, Equals, 2)
444         c.Check(err, Equals, nil)
445
446         reader, blocklen, _, err := kc.Get(hash)
447         c.Assert(err, Equals, nil)
448         c.Check(blocklen, Equals, int64(10))
449         all, err := ioutil.ReadAll(reader)
450         c.Check(all, DeepEquals, data)
451
452         // Put some more blocks
453         _, rep, err = kc.PutB([]byte("some-more-index-data"))
454         c.Check(err, Equals, nil)
455
456         // Invoke GetIndex
457         for _, spec := range []struct {
458                 prefix         string
459                 expectTestHash bool
460                 expectOther    bool
461         }{
462                 {"", true, true},         // with no prefix
463                 {hash[:3], true, false},  // with matching prefix
464                 {"abcdef", false, false}, // with no such prefix
465         } {
466                 indexReader, err := kc.GetIndex("proxy", spec.prefix)
467                 c.Assert(err, Equals, nil)
468                 indexResp, err := ioutil.ReadAll(indexReader)
469                 c.Assert(err, Equals, nil)
470                 locators := strings.Split(string(indexResp), "\n")
471                 gotTestHash := 0
472                 gotOther := 0
473                 for _, locator := range locators {
474                         if locator == "" {
475                                 continue
476                         }
477                         c.Check(locator[:len(spec.prefix)], Equals, spec.prefix)
478                         if locator[:32] == hash {
479                                 gotTestHash++
480                         } else {
481                                 gotOther++
482                         }
483                 }
484                 c.Check(gotTestHash == 2, Equals, spec.expectTestHash)
485                 c.Check(gotOther > 0, Equals, spec.expectOther)
486         }
487
488         // GetIndex with invalid prefix
489         _, err = kc.GetIndex("proxy", "xyz")
490         c.Assert((err != nil), Equals, true)
491 }