Merge branch '17465-pysdk-storage-classes-support'
[arvados.git] / services / keep-web / s3_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "bytes"
9         "context"
10         "crypto/rand"
11         "crypto/sha256"
12         "fmt"
13         "io/ioutil"
14         "net/http"
15         "net/http/httptest"
16         "net/url"
17         "os"
18         "os/exec"
19         "strings"
20         "sync"
21         "time"
22
23         "git.arvados.org/arvados.git/sdk/go/arvados"
24         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
25         "git.arvados.org/arvados.git/sdk/go/arvadostest"
26         "git.arvados.org/arvados.git/sdk/go/keepclient"
27         "github.com/AdRoll/goamz/aws"
28         "github.com/AdRoll/goamz/s3"
29         aws_aws "github.com/aws/aws-sdk-go/aws"
30         aws_credentials "github.com/aws/aws-sdk-go/aws/credentials"
31         aws_session "github.com/aws/aws-sdk-go/aws/session"
32         aws_s3 "github.com/aws/aws-sdk-go/service/s3"
33         check "gopkg.in/check.v1"
34 )
35
36 type s3stage struct {
37         arv        *arvados.Client
38         ac         *arvadosclient.ArvadosClient
39         kc         *keepclient.KeepClient
40         proj       arvados.Group
41         projbucket *s3.Bucket
42         coll       arvados.Collection
43         collbucket *s3.Bucket
44 }
45
46 func (s *IntegrationSuite) s3setup(c *check.C) s3stage {
47         var proj arvados.Group
48         var coll arvados.Collection
49         arv := arvados.NewClientFromEnv()
50         arv.AuthToken = arvadostest.ActiveToken
51         err := arv.RequestAndDecode(&proj, "POST", "arvados/v1/groups", nil, map[string]interface{}{
52                 "group": map[string]interface{}{
53                         "group_class": "project",
54                         "name":        "keep-web s3 test",
55                 },
56                 "ensure_unique_name": true,
57         })
58         c.Assert(err, check.IsNil)
59         err = arv.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{"collection": map[string]interface{}{
60                 "owner_uuid":    proj.UUID,
61                 "name":          "keep-web s3 test collection",
62                 "manifest_text": ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:emptyfile\n./emptydir d41d8cd98f00b204e9800998ecf8427e+0 0:0:.\n",
63         }})
64         c.Assert(err, check.IsNil)
65         ac, err := arvadosclient.New(arv)
66         c.Assert(err, check.IsNil)
67         kc, err := keepclient.MakeKeepClient(ac)
68         c.Assert(err, check.IsNil)
69         fs, err := coll.FileSystem(arv, kc)
70         c.Assert(err, check.IsNil)
71         f, err := fs.OpenFile("sailboat.txt", os.O_CREATE|os.O_WRONLY, 0644)
72         c.Assert(err, check.IsNil)
73         _, err = f.Write([]byte("⛵\n"))
74         c.Assert(err, check.IsNil)
75         err = f.Close()
76         c.Assert(err, check.IsNil)
77         err = fs.Sync()
78         c.Assert(err, check.IsNil)
79         err = arv.RequestAndDecode(&coll, "GET", "arvados/v1/collections/"+coll.UUID, nil, nil)
80         c.Assert(err, check.IsNil)
81
82         auth := aws.NewAuth(arvadostest.ActiveTokenUUID, arvadostest.ActiveToken, "", time.Now().Add(time.Hour))
83         region := aws.Region{
84                 Name:       "zzzzz",
85                 S3Endpoint: "http://" + s.testServer.Addr,
86         }
87         client := s3.New(*auth, region)
88         client.Signature = aws.V4Signature
89         return s3stage{
90                 arv:  arv,
91                 ac:   ac,
92                 kc:   kc,
93                 proj: proj,
94                 projbucket: &s3.Bucket{
95                         S3:   client,
96                         Name: proj.UUID,
97                 },
98                 coll: coll,
99                 collbucket: &s3.Bucket{
100                         S3:   client,
101                         Name: coll.UUID,
102                 },
103         }
104 }
105
106 func (stage s3stage) teardown(c *check.C) {
107         if stage.coll.UUID != "" {
108                 err := stage.arv.RequestAndDecode(&stage.coll, "DELETE", "arvados/v1/collections/"+stage.coll.UUID, nil, nil)
109                 c.Check(err, check.IsNil)
110         }
111         if stage.proj.UUID != "" {
112                 err := stage.arv.RequestAndDecode(&stage.proj, "DELETE", "arvados/v1/groups/"+stage.proj.UUID, nil, nil)
113                 c.Check(err, check.IsNil)
114         }
115 }
116
117 func (s *IntegrationSuite) TestS3Signatures(c *check.C) {
118         stage := s.s3setup(c)
119         defer stage.teardown(c)
120
121         bucket := stage.collbucket
122         for _, trial := range []struct {
123                 success   bool
124                 signature int
125                 accesskey string
126                 secretkey string
127         }{
128                 {true, aws.V2Signature, arvadostest.ActiveToken, "none"},
129                 {true, aws.V2Signature, url.QueryEscape(arvadostest.ActiveTokenV2), "none"},
130                 {true, aws.V2Signature, strings.Replace(arvadostest.ActiveTokenV2, "/", "_", -1), "none"},
131                 {false, aws.V2Signature, "none", "none"},
132                 {false, aws.V2Signature, "none", arvadostest.ActiveToken},
133
134                 {true, aws.V4Signature, arvadostest.ActiveTokenUUID, arvadostest.ActiveToken},
135                 {true, aws.V4Signature, arvadostest.ActiveToken, arvadostest.ActiveToken},
136                 {true, aws.V4Signature, url.QueryEscape(arvadostest.ActiveTokenV2), url.QueryEscape(arvadostest.ActiveTokenV2)},
137                 {true, aws.V4Signature, strings.Replace(arvadostest.ActiveTokenV2, "/", "_", -1), strings.Replace(arvadostest.ActiveTokenV2, "/", "_", -1)},
138                 {false, aws.V4Signature, arvadostest.ActiveToken, ""},
139                 {false, aws.V4Signature, arvadostest.ActiveToken, "none"},
140                 {false, aws.V4Signature, "none", arvadostest.ActiveToken},
141                 {false, aws.V4Signature, "none", "none"},
142         } {
143                 c.Logf("%#v", trial)
144                 bucket.S3.Auth = *(aws.NewAuth(trial.accesskey, trial.secretkey, "", time.Now().Add(time.Hour)))
145                 bucket.S3.Signature = trial.signature
146                 _, err := bucket.GetReader("emptyfile")
147                 if trial.success {
148                         c.Check(err, check.IsNil)
149                 } else {
150                         c.Check(err, check.NotNil)
151                 }
152         }
153 }
154
155 func (s *IntegrationSuite) TestS3HeadBucket(c *check.C) {
156         stage := s.s3setup(c)
157         defer stage.teardown(c)
158
159         for _, bucket := range []*s3.Bucket{stage.collbucket, stage.projbucket} {
160                 c.Logf("bucket %s", bucket.Name)
161                 exists, err := bucket.Exists("")
162                 c.Check(err, check.IsNil)
163                 c.Check(exists, check.Equals, true)
164         }
165 }
166
167 func (s *IntegrationSuite) TestS3CollectionGetObject(c *check.C) {
168         stage := s.s3setup(c)
169         defer stage.teardown(c)
170         s.testS3GetObject(c, stage.collbucket, "")
171 }
172 func (s *IntegrationSuite) TestS3ProjectGetObject(c *check.C) {
173         stage := s.s3setup(c)
174         defer stage.teardown(c)
175         s.testS3GetObject(c, stage.projbucket, stage.coll.Name+"/")
176 }
177 func (s *IntegrationSuite) testS3GetObject(c *check.C, bucket *s3.Bucket, prefix string) {
178         rdr, err := bucket.GetReader(prefix + "emptyfile")
179         c.Assert(err, check.IsNil)
180         buf, err := ioutil.ReadAll(rdr)
181         c.Check(err, check.IsNil)
182         c.Check(len(buf), check.Equals, 0)
183         err = rdr.Close()
184         c.Check(err, check.IsNil)
185
186         // GetObject
187         rdr, err = bucket.GetReader(prefix + "missingfile")
188         c.Check(err.(*s3.Error).StatusCode, check.Equals, 404)
189         c.Check(err.(*s3.Error).Code, check.Equals, `NoSuchKey`)
190         c.Check(err, check.ErrorMatches, `The specified key does not exist.`)
191
192         // HeadObject
193         exists, err := bucket.Exists(prefix + "missingfile")
194         c.Check(err, check.IsNil)
195         c.Check(exists, check.Equals, false)
196
197         // GetObject
198         rdr, err = bucket.GetReader(prefix + "sailboat.txt")
199         c.Assert(err, check.IsNil)
200         buf, err = ioutil.ReadAll(rdr)
201         c.Check(err, check.IsNil)
202         c.Check(buf, check.DeepEquals, []byte("⛵\n"))
203         err = rdr.Close()
204         c.Check(err, check.IsNil)
205
206         // HeadObject
207         resp, err := bucket.Head(prefix+"sailboat.txt", nil)
208         c.Check(err, check.IsNil)
209         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
210         c.Check(resp.ContentLength, check.Equals, int64(4))
211
212         // HeadObject with superfluous leading slashes
213         exists, err = bucket.Exists(prefix + "//sailboat.txt")
214         c.Check(err, check.IsNil)
215         c.Check(exists, check.Equals, true)
216 }
217
218 func (s *IntegrationSuite) TestS3CollectionPutObjectSuccess(c *check.C) {
219         stage := s.s3setup(c)
220         defer stage.teardown(c)
221         s.testS3PutObjectSuccess(c, stage.collbucket, "")
222 }
223 func (s *IntegrationSuite) TestS3ProjectPutObjectSuccess(c *check.C) {
224         stage := s.s3setup(c)
225         defer stage.teardown(c)
226         s.testS3PutObjectSuccess(c, stage.projbucket, stage.coll.Name+"/")
227 }
228 func (s *IntegrationSuite) testS3PutObjectSuccess(c *check.C, bucket *s3.Bucket, prefix string) {
229         for _, trial := range []struct {
230                 path        string
231                 size        int
232                 contentType string
233         }{
234                 {
235                         path:        "newfile",
236                         size:        128000000,
237                         contentType: "application/octet-stream",
238                 }, {
239                         path:        "newdir/newfile",
240                         size:        1 << 26,
241                         contentType: "application/octet-stream",
242                 }, {
243                         path:        "/aaa",
244                         size:        2,
245                         contentType: "application/octet-stream",
246                 }, {
247                         path:        "//bbb",
248                         size:        2,
249                         contentType: "application/octet-stream",
250                 }, {
251                         path:        "ccc//",
252                         size:        0,
253                         contentType: "application/x-directory",
254                 }, {
255                         path:        "newdir1/newdir2/newfile",
256                         size:        0,
257                         contentType: "application/octet-stream",
258                 }, {
259                         path:        "newdir1/newdir2/newdir3/",
260                         size:        0,
261                         contentType: "application/x-directory",
262                 },
263         } {
264                 c.Logf("=== %v", trial)
265
266                 objname := prefix + trial.path
267
268                 _, err := bucket.GetReader(objname)
269                 if !c.Check(err, check.NotNil) {
270                         continue
271                 }
272                 c.Check(err.(*s3.Error).StatusCode, check.Equals, 404)
273                 c.Check(err.(*s3.Error).Code, check.Equals, `NoSuchKey`)
274                 if !c.Check(err, check.ErrorMatches, `The specified key does not exist.`) {
275                         continue
276                 }
277
278                 buf := make([]byte, trial.size)
279                 rand.Read(buf)
280
281                 err = bucket.PutReader(objname, bytes.NewReader(buf), int64(len(buf)), trial.contentType, s3.Private, s3.Options{})
282                 c.Check(err, check.IsNil)
283
284                 rdr, err := bucket.GetReader(objname)
285                 if strings.HasSuffix(trial.path, "/") && !s.testServer.Config.cluster.Collections.S3FolderObjects {
286                         c.Check(err, check.NotNil)
287                         continue
288                 } else if !c.Check(err, check.IsNil) {
289                         continue
290                 }
291                 buf2, err := ioutil.ReadAll(rdr)
292                 c.Check(err, check.IsNil)
293                 c.Check(buf2, check.HasLen, len(buf))
294                 c.Check(bytes.Equal(buf, buf2), check.Equals, true)
295         }
296 }
297
298 func (s *IntegrationSuite) TestS3ProjectPutObjectNotSupported(c *check.C) {
299         stage := s.s3setup(c)
300         defer stage.teardown(c)
301         bucket := stage.projbucket
302
303         for _, trial := range []struct {
304                 path        string
305                 size        int
306                 contentType string
307         }{
308                 {
309                         path:        "newfile",
310                         size:        1234,
311                         contentType: "application/octet-stream",
312                 }, {
313                         path:        "newdir/newfile",
314                         size:        1234,
315                         contentType: "application/octet-stream",
316                 }, {
317                         path:        "newdir2/",
318                         size:        0,
319                         contentType: "application/x-directory",
320                 },
321         } {
322                 c.Logf("=== %v", trial)
323
324                 _, err := bucket.GetReader(trial.path)
325                 c.Check(err.(*s3.Error).StatusCode, check.Equals, 404)
326                 c.Check(err.(*s3.Error).Code, check.Equals, `NoSuchKey`)
327                 c.Assert(err, check.ErrorMatches, `The specified key does not exist.`)
328
329                 buf := make([]byte, trial.size)
330                 rand.Read(buf)
331
332                 err = bucket.PutReader(trial.path, bytes.NewReader(buf), int64(len(buf)), trial.contentType, s3.Private, s3.Options{})
333                 c.Check(err.(*s3.Error).StatusCode, check.Equals, 400)
334                 c.Check(err.(*s3.Error).Code, check.Equals, `InvalidArgument`)
335                 c.Check(err, check.ErrorMatches, `(mkdir "/by_id/zzzzz-j7d0g-[a-z0-9]{15}/newdir2?"|open "/zzzzz-j7d0g-[a-z0-9]{15}/newfile") failed: invalid argument`)
336
337                 _, err = bucket.GetReader(trial.path)
338                 c.Check(err.(*s3.Error).StatusCode, check.Equals, 404)
339                 c.Check(err.(*s3.Error).Code, check.Equals, `NoSuchKey`)
340                 c.Assert(err, check.ErrorMatches, `The specified key does not exist.`)
341         }
342 }
343
344 func (s *IntegrationSuite) TestS3CollectionDeleteObject(c *check.C) {
345         stage := s.s3setup(c)
346         defer stage.teardown(c)
347         s.testS3DeleteObject(c, stage.collbucket, "")
348 }
349 func (s *IntegrationSuite) TestS3ProjectDeleteObject(c *check.C) {
350         stage := s.s3setup(c)
351         defer stage.teardown(c)
352         s.testS3DeleteObject(c, stage.projbucket, stage.coll.Name+"/")
353 }
354 func (s *IntegrationSuite) testS3DeleteObject(c *check.C, bucket *s3.Bucket, prefix string) {
355         s.testServer.Config.cluster.Collections.S3FolderObjects = true
356         for _, trial := range []struct {
357                 path string
358         }{
359                 {"/"},
360                 {"nonexistentfile"},
361                 {"emptyfile"},
362                 {"sailboat.txt"},
363                 {"sailboat.txt/"},
364                 {"emptydir"},
365                 {"emptydir/"},
366         } {
367                 objname := prefix + trial.path
368                 comment := check.Commentf("objname %q", objname)
369
370                 err := bucket.Del(objname)
371                 if trial.path == "/" {
372                         c.Check(err, check.NotNil)
373                         continue
374                 }
375                 c.Check(err, check.IsNil, comment)
376                 _, err = bucket.GetReader(objname)
377                 c.Check(err, check.NotNil, comment)
378         }
379 }
380
381 func (s *IntegrationSuite) TestS3CollectionPutObjectFailure(c *check.C) {
382         stage := s.s3setup(c)
383         defer stage.teardown(c)
384         s.testS3PutObjectFailure(c, stage.collbucket, "")
385 }
386 func (s *IntegrationSuite) TestS3ProjectPutObjectFailure(c *check.C) {
387         stage := s.s3setup(c)
388         defer stage.teardown(c)
389         s.testS3PutObjectFailure(c, stage.projbucket, stage.coll.Name+"/")
390 }
391 func (s *IntegrationSuite) testS3PutObjectFailure(c *check.C, bucket *s3.Bucket, prefix string) {
392         s.testServer.Config.cluster.Collections.S3FolderObjects = false
393
394         var wg sync.WaitGroup
395         for _, trial := range []struct {
396                 path string
397         }{
398                 {
399                         path: "emptyfile/newname", // emptyfile exists, see s3setup()
400                 }, {
401                         path: "emptyfile/", // emptyfile exists, see s3setup()
402                 }, {
403                         path: "emptydir", // dir already exists, see s3setup()
404                 }, {
405                         path: "emptydir/",
406                 }, {
407                         path: "emptydir//",
408                 }, {
409                         path: "newdir/",
410                 }, {
411                         path: "newdir//",
412                 }, {
413                         path: "/",
414                 }, {
415                         path: "//",
416                 }, {
417                         path: "",
418                 },
419         } {
420                 trial := trial
421                 wg.Add(1)
422                 go func() {
423                         defer wg.Done()
424                         c.Logf("=== %v", trial)
425
426                         objname := prefix + trial.path
427
428                         buf := make([]byte, 1234)
429                         rand.Read(buf)
430
431                         err := bucket.PutReader(objname, bytes.NewReader(buf), int64(len(buf)), "application/octet-stream", s3.Private, s3.Options{})
432                         if !c.Check(err, check.ErrorMatches, `(invalid object name.*|open ".*" failed.*|object name conflicts with existing object|Missing object name in PUT request.)`, check.Commentf("PUT %q should fail", objname)) {
433                                 return
434                         }
435
436                         if objname != "" && objname != "/" {
437                                 _, err = bucket.GetReader(objname)
438                                 c.Check(err.(*s3.Error).StatusCode, check.Equals, 404)
439                                 c.Check(err.(*s3.Error).Code, check.Equals, `NoSuchKey`)
440                                 c.Check(err, check.ErrorMatches, `The specified key does not exist.`, check.Commentf("GET %q should return 404", objname))
441                         }
442                 }()
443         }
444         wg.Wait()
445 }
446
447 func (stage *s3stage) writeBigDirs(c *check.C, dirs int, filesPerDir int) {
448         fs, err := stage.coll.FileSystem(stage.arv, stage.kc)
449         c.Assert(err, check.IsNil)
450         for d := 0; d < dirs; d++ {
451                 dir := fmt.Sprintf("dir%d", d)
452                 c.Assert(fs.Mkdir(dir, 0755), check.IsNil)
453                 for i := 0; i < filesPerDir; i++ {
454                         f, err := fs.OpenFile(fmt.Sprintf("%s/file%d.txt", dir, i), os.O_CREATE|os.O_WRONLY, 0644)
455                         c.Assert(err, check.IsNil)
456                         c.Assert(f.Close(), check.IsNil)
457                 }
458         }
459         c.Assert(fs.Sync(), check.IsNil)
460 }
461
462 func (s *IntegrationSuite) sign(c *check.C, req *http.Request, key, secret string) {
463         scope := "20200202/zzzzz/service/aws4_request"
464         signedHeaders := "date"
465         req.Header.Set("Date", time.Now().UTC().Format(time.RFC1123))
466         stringToSign, err := s3stringToSign(s3SignAlgorithm, scope, signedHeaders, req)
467         c.Assert(err, check.IsNil)
468         sig, err := s3signature(secret, scope, signedHeaders, stringToSign)
469         c.Assert(err, check.IsNil)
470         req.Header.Set("Authorization", s3SignAlgorithm+" Credential="+key+"/"+scope+", SignedHeaders="+signedHeaders+", Signature="+sig)
471 }
472
473 func (s *IntegrationSuite) TestS3VirtualHostStyleRequests(c *check.C) {
474         stage := s.s3setup(c)
475         defer stage.teardown(c)
476         for _, trial := range []struct {
477                 url            string
478                 method         string
479                 body           string
480                 responseCode   int
481                 responseRegexp []string
482         }{
483                 {
484                         url:            "https://" + stage.collbucket.Name + ".example.com/",
485                         method:         "GET",
486                         responseCode:   http.StatusOK,
487                         responseRegexp: []string{`(?ms).*sailboat\.txt.*`},
488                 },
489                 {
490                         url:            "https://" + strings.Replace(stage.coll.PortableDataHash, "+", "-", -1) + ".example.com/",
491                         method:         "GET",
492                         responseCode:   http.StatusOK,
493                         responseRegexp: []string{`(?ms).*sailboat\.txt.*`},
494                 },
495                 {
496                         url:            "https://" + stage.projbucket.Name + ".example.com/?prefix=" + stage.coll.Name + "/&delimiter=/",
497                         method:         "GET",
498                         responseCode:   http.StatusOK,
499                         responseRegexp: []string{`(?ms).*sailboat\.txt.*`},
500                 },
501                 {
502                         url:            "https://" + stage.projbucket.Name + ".example.com/" + stage.coll.Name + "/sailboat.txt",
503                         method:         "GET",
504                         responseCode:   http.StatusOK,
505                         responseRegexp: []string{`⛵\n`},
506                 },
507                 {
508                         url:          "https://" + stage.projbucket.Name + ".example.com/" + stage.coll.Name + "/beep",
509                         method:       "PUT",
510                         body:         "boop",
511                         responseCode: http.StatusOK,
512                 },
513                 {
514                         url:            "https://" + stage.projbucket.Name + ".example.com/" + stage.coll.Name + "/beep",
515                         method:         "GET",
516                         responseCode:   http.StatusOK,
517                         responseRegexp: []string{`boop`},
518                 },
519                 {
520                         url:          "https://" + stage.projbucket.Name + ".example.com/" + stage.coll.Name + "//boop",
521                         method:       "GET",
522                         responseCode: http.StatusNotFound,
523                 },
524                 {
525                         url:          "https://" + stage.projbucket.Name + ".example.com/" + stage.coll.Name + "//boop",
526                         method:       "PUT",
527                         body:         "boop",
528                         responseCode: http.StatusOK,
529                 },
530                 {
531                         url:            "https://" + stage.projbucket.Name + ".example.com/" + stage.coll.Name + "//boop",
532                         method:         "GET",
533                         responseCode:   http.StatusOK,
534                         responseRegexp: []string{`boop`},
535                 },
536         } {
537                 url, err := url.Parse(trial.url)
538                 c.Assert(err, check.IsNil)
539                 req, err := http.NewRequest(trial.method, url.String(), bytes.NewReader([]byte(trial.body)))
540                 c.Assert(err, check.IsNil)
541                 s.sign(c, req, arvadostest.ActiveTokenUUID, arvadostest.ActiveToken)
542                 rr := httptest.NewRecorder()
543                 s.testServer.Server.Handler.ServeHTTP(rr, req)
544                 resp := rr.Result()
545                 c.Check(resp.StatusCode, check.Equals, trial.responseCode)
546                 body, err := ioutil.ReadAll(resp.Body)
547                 c.Assert(err, check.IsNil)
548                 for _, re := range trial.responseRegexp {
549                         c.Check(string(body), check.Matches, re)
550                 }
551         }
552 }
553
554 func (s *IntegrationSuite) TestS3NormalizeURIForSignature(c *check.C) {
555         stage := s.s3setup(c)
556         defer stage.teardown(c)
557         for _, trial := range []struct {
558                 rawPath        string
559                 normalizedPath string
560         }{
561                 {"/foo", "/foo"},             // boring case
562                 {"/foo%5fbar", "/foo_bar"},   // _ must not be escaped
563                 {"/foo%2fbar", "/foo/bar"},   // / must not be escaped
564                 {"/(foo)", "/%28foo%29"},     // () must be escaped
565                 {"/foo%5bbar", "/foo%5Bbar"}, // %XX must be uppercase
566         } {
567                 date := time.Now().UTC().Format("20060102T150405Z")
568                 scope := "20200202/zzzzz/S3/aws4_request"
569                 canonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s", "GET", trial.normalizedPath, "", "host:host.example.com\n", "host", "")
570                 c.Logf("canonicalRequest %q", canonicalRequest)
571                 expect := fmt.Sprintf("%s\n%s\n%s\n%s", s3SignAlgorithm, date, scope, hashdigest(sha256.New(), canonicalRequest))
572                 c.Logf("expected stringToSign %q", expect)
573
574                 req, err := http.NewRequest("GET", "https://host.example.com"+trial.rawPath, nil)
575                 req.Header.Set("X-Amz-Date", date)
576                 req.Host = "host.example.com"
577                 c.Assert(err, check.IsNil)
578
579                 obtained, err := s3stringToSign(s3SignAlgorithm, scope, "host", req)
580                 if !c.Check(err, check.IsNil) {
581                         continue
582                 }
583                 c.Check(obtained, check.Equals, expect)
584         }
585 }
586
587 func (s *IntegrationSuite) TestS3GetBucketLocation(c *check.C) {
588         stage := s.s3setup(c)
589         defer stage.teardown(c)
590         for _, bucket := range []*s3.Bucket{stage.collbucket, stage.projbucket} {
591                 req, err := http.NewRequest("GET", bucket.URL("/"), nil)
592                 c.Check(err, check.IsNil)
593                 req.Header.Set("Authorization", "AWS "+arvadostest.ActiveTokenV2+":none")
594                 req.URL.RawQuery = "location"
595                 resp, err := http.DefaultClient.Do(req)
596                 c.Assert(err, check.IsNil)
597                 c.Check(resp.Header.Get("Content-Type"), check.Equals, "application/xml")
598                 buf, err := ioutil.ReadAll(resp.Body)
599                 c.Assert(err, check.IsNil)
600                 c.Check(string(buf), check.Equals, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<LocationConstraint><LocationConstraint xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">zzzzz</LocationConstraint></LocationConstraint>\n")
601         }
602 }
603
604 func (s *IntegrationSuite) TestS3GetBucketVersioning(c *check.C) {
605         stage := s.s3setup(c)
606         defer stage.teardown(c)
607         for _, bucket := range []*s3.Bucket{stage.collbucket, stage.projbucket} {
608                 req, err := http.NewRequest("GET", bucket.URL("/"), nil)
609                 c.Check(err, check.IsNil)
610                 req.Header.Set("Authorization", "AWS "+arvadostest.ActiveTokenV2+":none")
611                 req.URL.RawQuery = "versioning"
612                 resp, err := http.DefaultClient.Do(req)
613                 c.Assert(err, check.IsNil)
614                 c.Check(resp.Header.Get("Content-Type"), check.Equals, "application/xml")
615                 buf, err := ioutil.ReadAll(resp.Body)
616                 c.Assert(err, check.IsNil)
617                 c.Check(string(buf), check.Equals, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<VersioningConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"/>\n")
618         }
619 }
620
621 func (s *IntegrationSuite) TestS3UnsupportedAPIs(c *check.C) {
622         stage := s.s3setup(c)
623         defer stage.teardown(c)
624         for _, trial := range []struct {
625                 method   string
626                 path     string
627                 rawquery string
628         }{
629                 {"GET", "/", "acl&versionId=1234"},    // GetBucketAcl
630                 {"GET", "/foo", "acl&versionId=1234"}, // GetObjectAcl
631                 {"PUT", "/", "acl"},                   // PutBucketAcl
632                 {"PUT", "/foo", "acl"},                // PutObjectAcl
633                 {"DELETE", "/", "tagging"},            // DeleteBucketTagging
634                 {"DELETE", "/foo", "tagging"},         // DeleteObjectTagging
635         } {
636                 for _, bucket := range []*s3.Bucket{stage.collbucket, stage.projbucket} {
637                         c.Logf("trial %v bucket %v", trial, bucket)
638                         req, err := http.NewRequest(trial.method, bucket.URL(trial.path), nil)
639                         c.Check(err, check.IsNil)
640                         req.Header.Set("Authorization", "AWS "+arvadostest.ActiveTokenV2+":none")
641                         req.URL.RawQuery = trial.rawquery
642                         resp, err := http.DefaultClient.Do(req)
643                         c.Assert(err, check.IsNil)
644                         c.Check(resp.Header.Get("Content-Type"), check.Equals, "application/xml")
645                         buf, err := ioutil.ReadAll(resp.Body)
646                         c.Assert(err, check.IsNil)
647                         c.Check(string(buf), check.Matches, "(?ms).*InvalidRequest.*API not supported.*")
648                 }
649         }
650 }
651
652 // If there are no CommonPrefixes entries, the CommonPrefixes XML tag
653 // should not appear at all.
654 func (s *IntegrationSuite) TestS3ListNoCommonPrefixes(c *check.C) {
655         stage := s.s3setup(c)
656         defer stage.teardown(c)
657
658         req, err := http.NewRequest("GET", stage.collbucket.URL("/"), nil)
659         c.Assert(err, check.IsNil)
660         req.Header.Set("Authorization", "AWS "+arvadostest.ActiveTokenV2+":none")
661         req.URL.RawQuery = "prefix=asdfasdfasdf&delimiter=/"
662         resp, err := http.DefaultClient.Do(req)
663         c.Assert(err, check.IsNil)
664         buf, err := ioutil.ReadAll(resp.Body)
665         c.Assert(err, check.IsNil)
666         c.Check(string(buf), check.Not(check.Matches), `(?ms).*CommonPrefixes.*`)
667 }
668
669 // If there is no delimiter in the request, or the results are not
670 // truncated, the NextMarker XML tag should not appear in the response
671 // body.
672 func (s *IntegrationSuite) TestS3ListNoNextMarker(c *check.C) {
673         stage := s.s3setup(c)
674         defer stage.teardown(c)
675
676         for _, query := range []string{"prefix=e&delimiter=/", ""} {
677                 req, err := http.NewRequest("GET", stage.collbucket.URL("/"), nil)
678                 c.Assert(err, check.IsNil)
679                 req.Header.Set("Authorization", "AWS "+arvadostest.ActiveTokenV2+":none")
680                 req.URL.RawQuery = query
681                 resp, err := http.DefaultClient.Do(req)
682                 c.Assert(err, check.IsNil)
683                 buf, err := ioutil.ReadAll(resp.Body)
684                 c.Assert(err, check.IsNil)
685                 c.Check(string(buf), check.Not(check.Matches), `(?ms).*NextMarker.*`)
686         }
687 }
688
689 // List response should include KeyCount field.
690 func (s *IntegrationSuite) TestS3ListKeyCount(c *check.C) {
691         stage := s.s3setup(c)
692         defer stage.teardown(c)
693
694         req, err := http.NewRequest("GET", stage.collbucket.URL("/"), nil)
695         c.Assert(err, check.IsNil)
696         req.Header.Set("Authorization", "AWS "+arvadostest.ActiveTokenV2+":none")
697         req.URL.RawQuery = "prefix=&delimiter=/"
698         resp, err := http.DefaultClient.Do(req)
699         c.Assert(err, check.IsNil)
700         buf, err := ioutil.ReadAll(resp.Body)
701         c.Assert(err, check.IsNil)
702         c.Check(string(buf), check.Matches, `(?ms).*<KeyCount>2</KeyCount>.*`)
703 }
704
705 func (s *IntegrationSuite) TestS3CollectionList(c *check.C) {
706         stage := s.s3setup(c)
707         defer stage.teardown(c)
708
709         var markers int
710         for markers, s.testServer.Config.cluster.Collections.S3FolderObjects = range []bool{false, true} {
711                 dirs := 2
712                 filesPerDir := 1001
713                 stage.writeBigDirs(c, dirs, filesPerDir)
714                 // Total # objects is:
715                 //                 2 file entries from s3setup (emptyfile and sailboat.txt)
716                 //                +1 fake "directory" marker from s3setup (emptydir) (if enabled)
717                 //             +dirs fake "directory" marker from writeBigDirs (dir0/, dir1/) (if enabled)
718                 // +filesPerDir*dirs file entries from writeBigDirs (dir0/file0.txt, etc.)
719                 s.testS3List(c, stage.collbucket, "", 4000, markers+2+(filesPerDir+markers)*dirs)
720                 s.testS3List(c, stage.collbucket, "", 131, markers+2+(filesPerDir+markers)*dirs)
721                 s.testS3List(c, stage.collbucket, "dir0/", 71, filesPerDir+markers)
722         }
723 }
724 func (s *IntegrationSuite) testS3List(c *check.C, bucket *s3.Bucket, prefix string, pageSize, expectFiles int) {
725         c.Logf("testS3List: prefix=%q pageSize=%d S3FolderObjects=%v", prefix, pageSize, s.testServer.Config.cluster.Collections.S3FolderObjects)
726         expectPageSize := pageSize
727         if expectPageSize > 1000 {
728                 expectPageSize = 1000
729         }
730         gotKeys := map[string]s3.Key{}
731         nextMarker := ""
732         pages := 0
733         for {
734                 resp, err := bucket.List(prefix, "", nextMarker, pageSize)
735                 if !c.Check(err, check.IsNil) {
736                         break
737                 }
738                 c.Check(len(resp.Contents) <= expectPageSize, check.Equals, true)
739                 if pages++; !c.Check(pages <= (expectFiles/expectPageSize)+1, check.Equals, true) {
740                         break
741                 }
742                 for _, key := range resp.Contents {
743                         gotKeys[key.Key] = key
744                         if strings.Contains(key.Key, "sailboat.txt") {
745                                 c.Check(key.Size, check.Equals, int64(4))
746                         }
747                 }
748                 if !resp.IsTruncated {
749                         c.Check(resp.NextMarker, check.Equals, "")
750                         break
751                 }
752                 if !c.Check(resp.NextMarker, check.Not(check.Equals), "") {
753                         break
754                 }
755                 nextMarker = resp.NextMarker
756         }
757         c.Check(len(gotKeys), check.Equals, expectFiles)
758 }
759
760 func (s *IntegrationSuite) TestS3CollectionListRollup(c *check.C) {
761         for _, s.testServer.Config.cluster.Collections.S3FolderObjects = range []bool{false, true} {
762                 s.testS3CollectionListRollup(c)
763         }
764 }
765
766 func (s *IntegrationSuite) testS3CollectionListRollup(c *check.C) {
767         stage := s.s3setup(c)
768         defer stage.teardown(c)
769
770         dirs := 2
771         filesPerDir := 500
772         stage.writeBigDirs(c, dirs, filesPerDir)
773         err := stage.collbucket.PutReader("dingbats", &bytes.Buffer{}, 0, "application/octet-stream", s3.Private, s3.Options{})
774         c.Assert(err, check.IsNil)
775         var allfiles []string
776         for marker := ""; ; {
777                 resp, err := stage.collbucket.List("", "", marker, 20000)
778                 c.Check(err, check.IsNil)
779                 for _, key := range resp.Contents {
780                         if len(allfiles) == 0 || allfiles[len(allfiles)-1] != key.Key {
781                                 allfiles = append(allfiles, key.Key)
782                         }
783                 }
784                 marker = resp.NextMarker
785                 if marker == "" {
786                         break
787                 }
788         }
789         markers := 0
790         if s.testServer.Config.cluster.Collections.S3FolderObjects {
791                 markers = 1
792         }
793         c.Check(allfiles, check.HasLen, dirs*(filesPerDir+markers)+3+markers)
794
795         gotDirMarker := map[string]bool{}
796         for _, name := range allfiles {
797                 isDirMarker := strings.HasSuffix(name, "/")
798                 if markers == 0 {
799                         c.Check(isDirMarker, check.Equals, false, check.Commentf("name %q", name))
800                 } else if isDirMarker {
801                         gotDirMarker[name] = true
802                 } else if i := strings.LastIndex(name, "/"); i >= 0 {
803                         c.Check(gotDirMarker[name[:i+1]], check.Equals, true, check.Commentf("name %q", name))
804                         gotDirMarker[name[:i+1]] = true // skip redundant complaints about this dir marker
805                 }
806         }
807
808         for _, trial := range []struct {
809                 prefix    string
810                 delimiter string
811                 marker    string
812         }{
813                 {"", "", ""},
814                 {"di", "/", ""},
815                 {"di", "r", ""},
816                 {"di", "n", ""},
817                 {"dir0", "/", ""},
818                 {"dir0/", "/", ""},
819                 {"dir0/f", "/", ""},
820                 {"dir0", "", ""},
821                 {"dir0/", "", ""},
822                 {"dir0/f", "", ""},
823                 {"dir0", "/", "dir0/file14.txt"},       // no commonprefixes
824                 {"", "", "dir0/file14.txt"},            // middle page, skip walking dir1
825                 {"", "", "dir1/file14.txt"},            // middle page, skip walking dir0
826                 {"", "", "dir1/file498.txt"},           // last page of results
827                 {"dir1/file", "", "dir1/file498.txt"},  // last page of results, with prefix
828                 {"dir1/file", "/", "dir1/file498.txt"}, // last page of results, with prefix + delimiter
829                 {"dir1", "Z", "dir1/file498.txt"},      // delimiter "Z" never appears
830                 {"dir2", "/", ""},                      // prefix "dir2" does not exist
831                 {"", "/", ""},
832         } {
833                 c.Logf("\n\n=== trial %+v markers=%d", trial, markers)
834
835                 maxKeys := 20
836                 resp, err := stage.collbucket.List(trial.prefix, trial.delimiter, trial.marker, maxKeys)
837                 c.Check(err, check.IsNil)
838                 if resp.IsTruncated && trial.delimiter == "" {
839                         // goamz List method fills in the missing
840                         // NextMarker field if resp.IsTruncated, so
841                         // now we can't really tell whether it was
842                         // sent by the server or by goamz. In cases
843                         // where it should be empty but isn't, assume
844                         // it's goamz's fault.
845                         resp.NextMarker = ""
846                 }
847
848                 var expectKeys []string
849                 var expectPrefixes []string
850                 var expectNextMarker string
851                 var expectTruncated bool
852                 for _, key := range allfiles {
853                         full := len(expectKeys)+len(expectPrefixes) >= maxKeys
854                         if !strings.HasPrefix(key, trial.prefix) || key < trial.marker {
855                                 continue
856                         } else if idx := strings.Index(key[len(trial.prefix):], trial.delimiter); trial.delimiter != "" && idx >= 0 {
857                                 prefix := key[:len(trial.prefix)+idx+1]
858                                 if len(expectPrefixes) > 0 && expectPrefixes[len(expectPrefixes)-1] == prefix {
859                                         // same prefix as previous key
860                                 } else if full {
861                                         expectNextMarker = key
862                                         expectTruncated = true
863                                 } else {
864                                         expectPrefixes = append(expectPrefixes, prefix)
865                                 }
866                         } else if full {
867                                 if trial.delimiter != "" {
868                                         expectNextMarker = key
869                                 }
870                                 expectTruncated = true
871                                 break
872                         } else {
873                                 expectKeys = append(expectKeys, key)
874                         }
875                 }
876
877                 var gotKeys []string
878                 for _, key := range resp.Contents {
879                         gotKeys = append(gotKeys, key.Key)
880                 }
881                 var gotPrefixes []string
882                 for _, prefix := range resp.CommonPrefixes {
883                         gotPrefixes = append(gotPrefixes, prefix)
884                 }
885                 commentf := check.Commentf("trial %+v markers=%d", trial, markers)
886                 c.Check(gotKeys, check.DeepEquals, expectKeys, commentf)
887                 c.Check(gotPrefixes, check.DeepEquals, expectPrefixes, commentf)
888                 c.Check(resp.NextMarker, check.Equals, expectNextMarker, commentf)
889                 c.Check(resp.IsTruncated, check.Equals, expectTruncated, commentf)
890                 c.Logf("=== trial %+v keys %q prefixes %q nextMarker %q", trial, gotKeys, gotPrefixes, resp.NextMarker)
891         }
892 }
893
894 func (s *IntegrationSuite) TestS3ListObjectsV2(c *check.C) {
895         stage := s.s3setup(c)
896         defer stage.teardown(c)
897         dirs := 2
898         filesPerDir := 40
899         stage.writeBigDirs(c, dirs, filesPerDir)
900
901         sess := aws_session.Must(aws_session.NewSession(&aws_aws.Config{
902                 Region:           aws_aws.String("auto"),
903                 Endpoint:         aws_aws.String("http://" + s.testServer.Addr),
904                 Credentials:      aws_credentials.NewStaticCredentials(url.QueryEscape(arvadostest.ActiveTokenV2), url.QueryEscape(arvadostest.ActiveTokenV2), ""),
905                 S3ForcePathStyle: aws_aws.Bool(true),
906         }))
907
908         stringOrNil := func(s string) *string {
909                 if s == "" {
910                         return nil
911                 } else {
912                         return &s
913                 }
914         }
915
916         client := aws_s3.New(sess)
917         ctx := context.Background()
918
919         for _, trial := range []struct {
920                 prefix               string
921                 delimiter            string
922                 startAfter           string
923                 maxKeys              int
924                 expectKeys           int
925                 expectCommonPrefixes map[string]bool
926         }{
927                 {
928                         // Expect {filesPerDir plus the dir itself}
929                         // for each dir, plus emptydir, emptyfile, and
930                         // sailboat.txt.
931                         expectKeys: (filesPerDir+1)*dirs + 3,
932                 },
933                 {
934                         maxKeys:    15,
935                         expectKeys: (filesPerDir+1)*dirs + 3,
936                 },
937                 {
938                         startAfter: "dir0/z",
939                         maxKeys:    15,
940                         // Expect {filesPerDir plus the dir itself}
941                         // for each dir except dir0, plus emptydir,
942                         // emptyfile, and sailboat.txt.
943                         expectKeys: (filesPerDir+1)*(dirs-1) + 3,
944                 },
945                 {
946                         maxKeys:              1,
947                         delimiter:            "/",
948                         expectKeys:           2, // emptyfile, sailboat.txt
949                         expectCommonPrefixes: map[string]bool{"dir0/": true, "dir1/": true, "emptydir/": true},
950                 },
951                 {
952                         startAfter:           "dir0/z",
953                         maxKeys:              15,
954                         delimiter:            "/",
955                         expectKeys:           2, // emptyfile, sailboat.txt
956                         expectCommonPrefixes: map[string]bool{"dir1/": true, "emptydir/": true},
957                 },
958                 {
959                         startAfter:           "dir0/file10.txt",
960                         maxKeys:              15,
961                         delimiter:            "/",
962                         expectKeys:           2,
963                         expectCommonPrefixes: map[string]bool{"dir0/": true, "dir1/": true, "emptydir/": true},
964                 },
965                 {
966                         startAfter:           "dir0/file10.txt",
967                         maxKeys:              15,
968                         prefix:               "d",
969                         delimiter:            "/",
970                         expectKeys:           0,
971                         expectCommonPrefixes: map[string]bool{"dir0/": true, "dir1/": true},
972                 },
973         } {
974                 c.Logf("[trial %+v]", trial)
975                 params := aws_s3.ListObjectsV2Input{
976                         Bucket:     aws_aws.String(stage.collbucket.Name),
977                         Prefix:     stringOrNil(trial.prefix),
978                         Delimiter:  stringOrNil(trial.delimiter),
979                         StartAfter: stringOrNil(trial.startAfter),
980                         MaxKeys:    aws_aws.Int64(int64(trial.maxKeys)),
981                 }
982                 keySeen := map[string]bool{}
983                 prefixSeen := map[string]bool{}
984                 for {
985                         result, err := client.ListObjectsV2WithContext(ctx, &params)
986                         if !c.Check(err, check.IsNil) {
987                                 break
988                         }
989                         c.Check(result.Name, check.DeepEquals, aws_aws.String(stage.collbucket.Name))
990                         c.Check(result.Prefix, check.DeepEquals, aws_aws.String(trial.prefix))
991                         c.Check(result.Delimiter, check.DeepEquals, aws_aws.String(trial.delimiter))
992                         // The following two fields are expected to be
993                         // nil (i.e., no tag in XML response) rather
994                         // than "" when the corresponding request
995                         // field was empty or nil.
996                         c.Check(result.StartAfter, check.DeepEquals, stringOrNil(trial.startAfter))
997                         c.Check(result.ContinuationToken, check.DeepEquals, params.ContinuationToken)
998
999                         if trial.maxKeys > 0 {
1000                                 c.Check(result.MaxKeys, check.DeepEquals, aws_aws.Int64(int64(trial.maxKeys)))
1001                                 c.Check(len(result.Contents)+len(result.CommonPrefixes) <= trial.maxKeys, check.Equals, true)
1002                         } else {
1003                                 c.Check(result.MaxKeys, check.DeepEquals, aws_aws.Int64(int64(s3MaxKeys)))
1004                         }
1005
1006                         for _, ent := range result.Contents {
1007                                 c.Assert(ent.Key, check.NotNil)
1008                                 c.Check(*ent.Key > trial.startAfter, check.Equals, true)
1009                                 c.Check(keySeen[*ent.Key], check.Equals, false, check.Commentf("dup key %q", *ent.Key))
1010                                 keySeen[*ent.Key] = true
1011                         }
1012                         for _, ent := range result.CommonPrefixes {
1013                                 c.Assert(ent.Prefix, check.NotNil)
1014                                 c.Check(strings.HasSuffix(*ent.Prefix, trial.delimiter), check.Equals, true, check.Commentf("bad CommonPrefix %q", *ent.Prefix))
1015                                 if strings.HasPrefix(trial.startAfter, *ent.Prefix) {
1016                                         // If we asked for
1017                                         // startAfter=dir0/file10.txt,
1018                                         // we expect dir0/ to be
1019                                         // returned as a common prefix
1020                                 } else {
1021                                         c.Check(*ent.Prefix > trial.startAfter, check.Equals, true)
1022                                 }
1023                                 c.Check(prefixSeen[*ent.Prefix], check.Equals, false, check.Commentf("dup common prefix %q", *ent.Prefix))
1024                                 prefixSeen[*ent.Prefix] = true
1025                         }
1026                         if *result.IsTruncated && c.Check(result.NextContinuationToken, check.Not(check.Equals), "") {
1027                                 params.ContinuationToken = aws_aws.String(*result.NextContinuationToken)
1028                         } else {
1029                                 break
1030                         }
1031                 }
1032                 c.Check(keySeen, check.HasLen, trial.expectKeys)
1033                 c.Check(prefixSeen, check.HasLen, len(trial.expectCommonPrefixes))
1034                 if len(trial.expectCommonPrefixes) > 0 {
1035                         c.Check(prefixSeen, check.DeepEquals, trial.expectCommonPrefixes)
1036                 }
1037         }
1038 }
1039
1040 func (s *IntegrationSuite) TestS3ListObjectsV2EncodingTypeURL(c *check.C) {
1041         stage := s.s3setup(c)
1042         defer stage.teardown(c)
1043         dirs := 2
1044         filesPerDir := 40
1045         stage.writeBigDirs(c, dirs, filesPerDir)
1046
1047         sess := aws_session.Must(aws_session.NewSession(&aws_aws.Config{
1048                 Region:           aws_aws.String("auto"),
1049                 Endpoint:         aws_aws.String("http://" + s.testServer.Addr),
1050                 Credentials:      aws_credentials.NewStaticCredentials(url.QueryEscape(arvadostest.ActiveTokenV2), url.QueryEscape(arvadostest.ActiveTokenV2), ""),
1051                 S3ForcePathStyle: aws_aws.Bool(true),
1052         }))
1053
1054         client := aws_s3.New(sess)
1055         ctx := context.Background()
1056
1057         result, err := client.ListObjectsV2WithContext(ctx, &aws_s3.ListObjectsV2Input{
1058                 Bucket:       aws_aws.String(stage.collbucket.Name),
1059                 Prefix:       aws_aws.String("dir0/"),
1060                 Delimiter:    aws_aws.String("/"),
1061                 StartAfter:   aws_aws.String("dir0/"),
1062                 EncodingType: aws_aws.String("url"),
1063         })
1064         c.Assert(err, check.IsNil)
1065         c.Check(*result.Prefix, check.Equals, "dir0%2F")
1066         c.Check(*result.Delimiter, check.Equals, "%2F")
1067         c.Check(*result.StartAfter, check.Equals, "dir0%2F")
1068         for _, ent := range result.Contents {
1069                 c.Check(*ent.Key, check.Matches, "dir0%2F.*")
1070         }
1071         result, err = client.ListObjectsV2WithContext(ctx, &aws_s3.ListObjectsV2Input{
1072                 Bucket:       aws_aws.String(stage.collbucket.Name),
1073                 Delimiter:    aws_aws.String("/"),
1074                 EncodingType: aws_aws.String("url"),
1075         })
1076         c.Assert(err, check.IsNil)
1077         c.Check(*result.Delimiter, check.Equals, "%2F")
1078         c.Check(result.CommonPrefixes, check.HasLen, dirs+1)
1079         for _, ent := range result.CommonPrefixes {
1080                 c.Check(*ent.Prefix, check.Matches, ".*%2F")
1081         }
1082 }
1083
1084 // TestS3cmd checks compatibility with the s3cmd command line tool, if
1085 // it's installed. As of Debian buster, s3cmd is only in backports, so
1086 // `arvados-server install` don't install it, and this test skips if
1087 // it's not installed.
1088 func (s *IntegrationSuite) TestS3cmd(c *check.C) {
1089         if _, err := exec.LookPath("s3cmd"); err != nil {
1090                 c.Skip("s3cmd not found")
1091                 return
1092         }
1093
1094         stage := s.s3setup(c)
1095         defer stage.teardown(c)
1096
1097         cmd := exec.Command("s3cmd", "--no-ssl", "--host="+s.testServer.Addr, "--host-bucket="+s.testServer.Addr, "--access_key="+arvadostest.ActiveTokenUUID, "--secret_key="+arvadostest.ActiveToken, "ls", "s3://"+arvadostest.FooCollection)
1098         buf, err := cmd.CombinedOutput()
1099         c.Check(err, check.IsNil)
1100         c.Check(string(buf), check.Matches, `.* 3 +s3://`+arvadostest.FooCollection+`/foo\n`)
1101 }
1102
1103 func (s *IntegrationSuite) TestS3BucketInHost(c *check.C) {
1104         stage := s.s3setup(c)
1105         defer stage.teardown(c)
1106
1107         hdr, body, _ := s.runCurl(c, "AWS "+arvadostest.ActiveTokenV2+":none", stage.coll.UUID+".collections.example.com", "/sailboat.txt")
1108         c.Check(hdr, check.Matches, `(?s)HTTP/1.1 200 OK\r\n.*`)
1109         c.Check(body, check.Equals, "⛵\n")
1110 }