1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
38 ac *arvadosclient.ArvadosClient
39 kc *keepclient.KeepClient
42 coll arvados.Collection
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",
56 "ensure_unique_name": true,
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",
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)
76 c.Assert(err, check.IsNil)
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)
82 auth := aws.NewAuth(arvadostest.ActiveTokenUUID, arvadostest.ActiveToken, "", time.Now().Add(time.Hour))
85 S3Endpoint: "http://" + s.testServer.Addr,
87 client := s3.New(*auth, region)
88 client.Signature = aws.V4Signature
94 projbucket: &s3.Bucket{
99 collbucket: &s3.Bucket{
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)
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)
117 func (s *IntegrationSuite) TestS3Signatures(c *check.C) {
118 stage := s.s3setup(c)
119 defer stage.teardown(c)
121 bucket := stage.collbucket
122 for _, trial := range []struct {
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},
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"},
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")
148 c.Check(err, check.IsNil)
150 c.Check(err, check.NotNil)
155 func (s *IntegrationSuite) TestS3HeadBucket(c *check.C) {
156 stage := s.s3setup(c)
157 defer stage.teardown(c)
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)
167 func (s *IntegrationSuite) TestS3CollectionGetObject(c *check.C) {
168 stage := s.s3setup(c)
169 defer stage.teardown(c)
170 s.testS3GetObject(c, stage.collbucket, "")
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+"/")
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)
184 c.Check(err, check.IsNil)
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.`)
193 exists, err := bucket.Exists(prefix + "missingfile")
194 c.Check(err, check.IsNil)
195 c.Check(exists, check.Equals, false)
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"))
204 c.Check(err, check.IsNil)
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))
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)
218 func (s *IntegrationSuite) TestS3CollectionPutObjectSuccess(c *check.C) {
219 stage := s.s3setup(c)
220 defer stage.teardown(c)
221 s.testS3PutObjectSuccess(c, stage.collbucket, "")
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+"/")
228 func (s *IntegrationSuite) testS3PutObjectSuccess(c *check.C, bucket *s3.Bucket, prefix string) {
229 for _, trial := range []struct {
237 contentType: "application/octet-stream",
239 path: "newdir/newfile",
241 contentType: "application/octet-stream",
245 contentType: "application/octet-stream",
249 contentType: "application/octet-stream",
253 contentType: "application/x-directory",
255 path: "newdir1/newdir2/newfile",
257 contentType: "application/octet-stream",
259 path: "newdir1/newdir2/newdir3/",
261 contentType: "application/x-directory",
264 c.Logf("=== %v", trial)
266 objname := prefix + trial.path
268 _, err := bucket.GetReader(objname)
269 if !c.Check(err, check.NotNil) {
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.`) {
278 buf := make([]byte, trial.size)
281 err = bucket.PutReader(objname, bytes.NewReader(buf), int64(len(buf)), trial.contentType, s3.Private, s3.Options{})
282 c.Check(err, check.IsNil)
284 rdr, err := bucket.GetReader(objname)
285 if strings.HasSuffix(trial.path, "/") && !s.testServer.Config.cluster.Collections.S3FolderObjects {
286 c.Check(err, check.NotNil)
288 } else if !c.Check(err, check.IsNil) {
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)
298 func (s *IntegrationSuite) TestS3ProjectPutObjectNotSupported(c *check.C) {
299 stage := s.s3setup(c)
300 defer stage.teardown(c)
301 bucket := stage.projbucket
303 for _, trial := range []struct {
311 contentType: "application/octet-stream",
313 path: "newdir/newfile",
315 contentType: "application/octet-stream",
319 contentType: "application/x-directory",
322 c.Logf("=== %v", trial)
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.`)
329 buf := make([]byte, trial.size)
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`)
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.`)
344 func (s *IntegrationSuite) TestS3CollectionDeleteObject(c *check.C) {
345 stage := s.s3setup(c)
346 defer stage.teardown(c)
347 s.testS3DeleteObject(c, stage.collbucket, "")
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+"/")
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 {
367 objname := prefix + trial.path
368 comment := check.Commentf("objname %q", objname)
370 err := bucket.Del(objname)
371 if trial.path == "/" {
372 c.Check(err, check.NotNil)
375 c.Check(err, check.IsNil, comment)
376 _, err = bucket.GetReader(objname)
377 c.Check(err, check.NotNil, comment)
381 func (s *IntegrationSuite) TestS3CollectionPutObjectFailure(c *check.C) {
382 stage := s.s3setup(c)
383 defer stage.teardown(c)
384 s.testS3PutObjectFailure(c, stage.collbucket, "")
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+"/")
391 func (s *IntegrationSuite) testS3PutObjectFailure(c *check.C, bucket *s3.Bucket, prefix string) {
392 s.testServer.Config.cluster.Collections.S3FolderObjects = false
394 var wg sync.WaitGroup
395 for _, trial := range []struct {
399 path: "emptyfile/newname", // emptyfile exists, see s3setup()
401 path: "emptyfile/", // emptyfile exists, see s3setup()
403 path: "emptydir", // dir already exists, see s3setup()
424 c.Logf("=== %v", trial)
426 objname := prefix + trial.path
428 buf := make([]byte, 1234)
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)) {
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))
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)
459 c.Assert(fs.Sync(), check.IsNil)
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)
473 func (s *IntegrationSuite) TestS3VirtualHostStyleRequests(c *check.C) {
474 stage := s.s3setup(c)
475 defer stage.teardown(c)
476 for _, trial := range []struct {
481 responseRegexp []string
484 url: "https://" + stage.collbucket.Name + ".example.com/",
486 responseCode: http.StatusOK,
487 responseRegexp: []string{`(?ms).*sailboat\.txt.*`},
490 url: "https://" + strings.Replace(stage.coll.PortableDataHash, "+", "-", -1) + ".example.com/",
492 responseCode: http.StatusOK,
493 responseRegexp: []string{`(?ms).*sailboat\.txt.*`},
496 url: "https://" + stage.projbucket.Name + ".example.com/?prefix=" + stage.coll.Name + "/&delimiter=/",
498 responseCode: http.StatusOK,
499 responseRegexp: []string{`(?ms).*sailboat\.txt.*`},
502 url: "https://" + stage.projbucket.Name + ".example.com/" + stage.coll.Name + "/sailboat.txt",
504 responseCode: http.StatusOK,
505 responseRegexp: []string{`⛵\n`},
508 url: "https://" + stage.projbucket.Name + ".example.com/" + stage.coll.Name + "/beep",
511 responseCode: http.StatusOK,
514 url: "https://" + stage.projbucket.Name + ".example.com/" + stage.coll.Name + "/beep",
516 responseCode: http.StatusOK,
517 responseRegexp: []string{`boop`},
520 url: "https://" + stage.projbucket.Name + ".example.com/" + stage.coll.Name + "//boop",
522 responseCode: http.StatusNotFound,
525 url: "https://" + stage.projbucket.Name + ".example.com/" + stage.coll.Name + "//boop",
528 responseCode: http.StatusOK,
531 url: "https://" + stage.projbucket.Name + ".example.com/" + stage.coll.Name + "//boop",
533 responseCode: http.StatusOK,
534 responseRegexp: []string{`boop`},
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)
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)
554 func (s *IntegrationSuite) TestS3NormalizeURIForSignature(c *check.C) {
555 stage := s.s3setup(c)
556 defer stage.teardown(c)
557 for _, trial := range []struct {
559 normalizedPath string
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
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)
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)
579 obtained, err := s3stringToSign(s3SignAlgorithm, scope, "host", req)
580 if !c.Check(err, check.IsNil) {
583 c.Check(obtained, check.Equals, expect)
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")
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")
621 func (s *IntegrationSuite) TestS3UnsupportedAPIs(c *check.C) {
622 stage := s.s3setup(c)
623 defer stage.teardown(c)
624 for _, trial := range []struct {
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
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.*")
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)
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.*`)
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
672 func (s *IntegrationSuite) TestS3ListNoNextMarker(c *check.C) {
673 stage := s.s3setup(c)
674 defer stage.teardown(c)
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.*`)
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)
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>.*`)
705 func (s *IntegrationSuite) TestS3CollectionList(c *check.C) {
706 stage := s.s3setup(c)
707 defer stage.teardown(c)
710 for markers, s.testServer.Config.cluster.Collections.S3FolderObjects = range []bool{false, true} {
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)
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
730 gotKeys := map[string]s3.Key{}
734 resp, err := bucket.List(prefix, "", nextMarker, pageSize)
735 if !c.Check(err, check.IsNil) {
738 c.Check(len(resp.Contents) <= expectPageSize, check.Equals, true)
739 if pages++; !c.Check(pages <= (expectFiles/expectPageSize)+1, check.Equals, true) {
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))
748 if !resp.IsTruncated {
749 c.Check(resp.NextMarker, check.Equals, "")
752 if !c.Check(resp.NextMarker, check.Not(check.Equals), "") {
755 nextMarker = resp.NextMarker
757 c.Check(len(gotKeys), check.Equals, expectFiles)
760 func (s *IntegrationSuite) TestS3CollectionListRollup(c *check.C) {
761 for _, s.testServer.Config.cluster.Collections.S3FolderObjects = range []bool{false, true} {
762 s.testS3CollectionListRollup(c)
766 func (s *IntegrationSuite) testS3CollectionListRollup(c *check.C) {
767 stage := s.s3setup(c)
768 defer stage.teardown(c)
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)
784 marker = resp.NextMarker
790 if s.testServer.Config.cluster.Collections.S3FolderObjects {
793 c.Check(allfiles, check.HasLen, dirs*(filesPerDir+markers)+3+markers)
795 gotDirMarker := map[string]bool{}
796 for _, name := range allfiles {
797 isDirMarker := strings.HasSuffix(name, "/")
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
808 for _, trial := range []struct {
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
833 c.Logf("\n\n=== trial %+v markers=%d", trial, markers)
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.
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 {
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
861 expectNextMarker = key
862 expectTruncated = true
864 expectPrefixes = append(expectPrefixes, prefix)
867 if trial.delimiter != "" {
868 expectNextMarker = key
870 expectTruncated = true
873 expectKeys = append(expectKeys, key)
878 for _, key := range resp.Contents {
879 gotKeys = append(gotKeys, key.Key)
881 var gotPrefixes []string
882 for _, prefix := range resp.CommonPrefixes {
883 gotPrefixes = append(gotPrefixes, prefix)
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)
894 func (s *IntegrationSuite) TestS3ListObjectsV2(c *check.C) {
895 stage := s.s3setup(c)
896 defer stage.teardown(c)
899 stage.writeBigDirs(c, dirs, filesPerDir)
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),
908 stringOrNil := func(s string) *string {
916 client := aws_s3.New(sess)
917 ctx := context.Background()
919 for _, trial := range []struct {
925 expectCommonPrefixes map[string]bool
928 // Expect {filesPerDir plus the dir itself}
929 // for each dir, plus emptydir, emptyfile, and
931 expectKeys: (filesPerDir+1)*dirs + 3,
935 expectKeys: (filesPerDir+1)*dirs + 3,
938 startAfter: "dir0/z",
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,
948 expectKeys: 2, // emptyfile, sailboat.txt
949 expectCommonPrefixes: map[string]bool{"dir0/": true, "dir1/": true, "emptydir/": true},
952 startAfter: "dir0/z",
955 expectKeys: 2, // emptyfile, sailboat.txt
956 expectCommonPrefixes: map[string]bool{"dir1/": true, "emptydir/": true},
959 startAfter: "dir0/file10.txt",
963 expectCommonPrefixes: map[string]bool{"dir0/": true, "dir1/": true, "emptydir/": true},
966 startAfter: "dir0/file10.txt",
971 expectCommonPrefixes: map[string]bool{"dir0/": true, "dir1/": true},
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)),
982 keySeen := map[string]bool{}
983 prefixSeen := map[string]bool{}
985 result, err := client.ListObjectsV2WithContext(ctx, ¶ms)
986 if !c.Check(err, check.IsNil) {
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)
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)
1003 c.Check(result.MaxKeys, check.DeepEquals, aws_aws.Int64(int64(s3MaxKeys)))
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
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) {
1017 // startAfter=dir0/file10.txt,
1018 // we expect dir0/ to be
1019 // returned as a common prefix
1021 c.Check(*ent.Prefix > trial.startAfter, check.Equals, true)
1023 c.Check(prefixSeen[*ent.Prefix], check.Equals, false, check.Commentf("dup common prefix %q", *ent.Prefix))
1024 prefixSeen[*ent.Prefix] = true
1026 if *result.IsTruncated && c.Check(result.NextContinuationToken, check.Not(check.Equals), "") {
1027 params.ContinuationToken = aws_aws.String(*result.NextContinuationToken)
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)
1040 func (s *IntegrationSuite) TestS3ListObjectsV2EncodingTypeURL(c *check.C) {
1041 stage := s.s3setup(c)
1042 defer stage.teardown(c)
1045 stage.writeBigDirs(c, dirs, filesPerDir)
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),
1054 client := aws_s3.New(sess)
1055 ctx := context.Background()
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"),
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.*")
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"),
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")
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")
1094 stage := s.s3setup(c)
1095 defer stage.teardown(c)
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`)
1103 func (s *IntegrationSuite) TestS3BucketInHost(c *check.C) {
1104 stage := s.s3setup(c)
1105 defer stage.teardown(c)
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")