1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
26 "git.arvados.org/arvados.git/sdk/go/arvados"
27 "git.arvados.org/arvados.git/sdk/go/ctxlog"
28 "github.com/AdRoll/goamz/s3"
33 s3SignAlgorithm = "AWS4-HMAC-SHA256"
34 s3MaxClockSkew = 5 * time.Minute
37 type commonPrefix struct {
41 type listV1Resp struct {
42 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
44 // s3.ListResp marshals an empty tag when
45 // CommonPrefixes is nil, which confuses some clients.
46 // Fix by using this nested struct instead.
47 CommonPrefixes []commonPrefix
48 // Similarly, we need omitempty here, because an empty
49 // tag confuses some clients (e.g.,
50 // github.com/aws/aws-sdk-net never terminates its
52 NextMarker string `xml:"NextMarker,omitempty"`
53 // ListObjectsV2 has a KeyCount response field.
57 type listV2Resp struct {
58 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
65 CommonPrefixes []commonPrefix
66 EncodingType string `xml:",omitempty"`
68 ContinuationToken string `xml:",omitempty"`
69 NextContinuationToken string `xml:",omitempty"`
70 StartAfter string `xml:",omitempty"`
73 func hmacstring(msg string, key []byte) []byte {
74 h := hmac.New(sha256.New, key)
75 io.WriteString(h, msg)
79 func hashdigest(h hash.Hash, payload string) string {
80 io.WriteString(h, payload)
81 return fmt.Sprintf("%x", h.Sum(nil))
84 // Signing key for given secret key and request attrs.
85 func s3signatureKey(key, datestamp, regionName, serviceName string) []byte {
86 return hmacstring("aws4_request",
87 hmacstring(serviceName,
88 hmacstring(regionName,
89 hmacstring(datestamp, []byte("AWS4"+key)))))
92 // Canonical query string for S3 V4 signature: sorted keys, spaces
93 // escaped as %20 instead of +, keyvalues joined with &.
94 func s3querystring(u *url.URL) string {
95 keys := make([]string, 0, len(u.Query()))
96 values := make(map[string]string, len(u.Query()))
97 for k, vs := range u.Query() {
98 k = strings.Replace(url.QueryEscape(k), "+", "%20", -1)
99 keys = append(keys, k)
100 for _, v := range vs {
101 v = strings.Replace(url.QueryEscape(v), "+", "%20", -1)
105 values[k] += k + "=" + v
109 for i, k := range keys {
112 return strings.Join(keys, "&")
115 var reMultipleSlashChars = regexp.MustCompile(`//+`)
117 func s3stringToSign(alg, scope, signedHeaders string, r *http.Request) (string, error) {
118 timefmt, timestr := "20060102T150405Z", r.Header.Get("X-Amz-Date")
120 timefmt, timestr = time.RFC1123, r.Header.Get("Date")
122 t, err := time.Parse(timefmt, timestr)
124 return "", fmt.Errorf("invalid timestamp %q: %s", timestr, err)
126 if skew := time.Now().Sub(t); skew < -s3MaxClockSkew || skew > s3MaxClockSkew {
127 return "", errors.New("exceeded max clock skew")
130 var canonicalHeaders string
131 for _, h := range strings.Split(signedHeaders, ";") {
133 canonicalHeaders += h + ":" + r.Host + "\n"
135 canonicalHeaders += h + ":" + r.Header.Get(h) + "\n"
139 normalizedURL := *r.URL
140 normalizedURL.RawPath = ""
141 normalizedURL.Path = reMultipleSlashChars.ReplaceAllString(normalizedURL.Path, "/")
142 ctxlog.FromContext(r.Context()).Infof("escapedPath %s", normalizedURL.EscapedPath())
143 canonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s", r.Method, normalizedURL.EscapedPath(), s3querystring(r.URL), canonicalHeaders, signedHeaders, r.Header.Get("X-Amz-Content-Sha256"))
144 ctxlog.FromContext(r.Context()).Debugf("s3stringToSign: canonicalRequest %s", canonicalRequest)
145 return fmt.Sprintf("%s\n%s\n%s\n%s", alg, r.Header.Get("X-Amz-Date"), scope, hashdigest(sha256.New(), canonicalRequest)), nil
148 func s3signature(secretKey, scope, signedHeaders, stringToSign string) (string, error) {
149 // scope is {datestamp}/{region}/{service}/aws4_request
150 drs := strings.Split(scope, "/")
152 return "", fmt.Errorf("invalid scope %q", scope)
154 key := s3signatureKey(secretKey, drs[0], drs[1], drs[2])
155 return hashdigest(hmac.New(sha256.New, key), stringToSign), nil
158 var v2tokenUnderscore = regexp.MustCompile(`^v2_[a-z0-9]{5}-gj3su-[a-z0-9]{15}_`)
160 func unescapeKey(key string) string {
161 if v2tokenUnderscore.MatchString(key) {
162 // Entire Arvados token, with "/" replaced by "_" to
163 // avoid colliding with the Authorization header
165 return strings.Replace(key, "_", "/", -1)
166 } else if s, err := url.PathUnescape(key); err == nil {
173 // checks3signature verifies the given S3 V4 signature and returns the
174 // Arvados token that corresponds to the given accessKey. An error is
175 // returned if accessKey is not a valid token UUID or the signature
177 func (h *handler) checks3signature(r *http.Request) (string, error) {
178 var key, scope, signedHeaders, signature string
179 authstring := strings.TrimPrefix(r.Header.Get("Authorization"), s3SignAlgorithm+" ")
180 for _, cmpt := range strings.Split(authstring, ",") {
181 cmpt = strings.TrimSpace(cmpt)
182 split := strings.SplitN(cmpt, "=", 2)
184 case len(split) != 2:
186 case split[0] == "Credential":
187 keyandscope := strings.SplitN(split[1], "/", 2)
188 if len(keyandscope) == 2 {
189 key, scope = keyandscope[0], keyandscope[1]
191 case split[0] == "SignedHeaders":
192 signedHeaders = split[1]
193 case split[0] == "Signature":
198 client := (&arvados.Client{
199 APIHost: h.Config.cluster.Services.Controller.ExternalURL.Host,
200 Insecure: h.Config.cluster.TLS.Insecure,
201 }).WithRequestID(r.Header.Get("X-Request-Id"))
202 var aca arvados.APIClientAuthorization
205 if len(key) == 27 && key[5:12] == "-gj3su-" {
206 // Access key is the UUID of an Arvados token, secret
207 // key is the secret part.
208 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+h.Config.cluster.SystemRootToken)
209 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/"+key, nil, nil)
210 secret = aca.APIToken
212 // Access key and secret key are both an entire
213 // Arvados token or OIDC access token.
214 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+unescapeKey(key))
215 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/current", nil, nil)
219 ctxlog.FromContext(r.Context()).WithError(err).WithField("UUID", key).Info("token lookup failed")
220 return "", errors.New("invalid access key")
222 stringToSign, err := s3stringToSign(s3SignAlgorithm, scope, signedHeaders, r)
226 expect, err := s3signature(secret, scope, signedHeaders, stringToSign)
229 } else if expect != signature {
230 return "", fmt.Errorf("signature does not match (scope %q signedHeaders %q stringToSign %q)", scope, signedHeaders, stringToSign)
232 return aca.TokenV2(), nil
235 func s3ErrorResponse(w http.ResponseWriter, s3code string, message string, resource string, code int) {
236 w.Header().Set("Content-Type", "application/xml")
237 w.Header().Set("X-Content-Type-Options", "nosniff")
239 var errstruct struct {
245 errstruct.Code = s3code
246 errstruct.Message = message
247 errstruct.Resource = resource
248 errstruct.RequestId = ""
249 enc := xml.NewEncoder(w)
250 fmt.Fprint(w, xml.Header)
251 enc.EncodeElement(errstruct, xml.StartElement{Name: xml.Name{Local: "Error"}})
254 var NoSuchKey = "NoSuchKey"
255 var NoSuchBucket = "NoSuchBucket"
256 var InvalidArgument = "InvalidArgument"
257 var InternalError = "InternalError"
258 var UnauthorizedAccess = "UnauthorizedAccess"
259 var InvalidRequest = "InvalidRequest"
260 var SignatureDoesNotMatch = "SignatureDoesNotMatch"
262 var reRawQueryIndicatesAPI = regexp.MustCompile(`^[a-z]+(&|$)`)
264 // serveS3 handles r and returns true if r is a request from an S3
265 // client, otherwise it returns false.
266 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
268 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
269 split := strings.SplitN(auth[4:], ":", 2)
271 s3ErrorResponse(w, InvalidRequest, "malformed Authorization header", r.URL.Path, http.StatusUnauthorized)
274 token = unescapeKey(split[0])
275 } else if strings.HasPrefix(auth, s3SignAlgorithm+" ") {
276 t, err := h.checks3signature(r)
278 s3ErrorResponse(w, SignatureDoesNotMatch, "signature verification failed: "+err.Error(), r.URL.Path, http.StatusForbidden)
287 var fs arvados.CustomFileSystem
288 if r.Method == http.MethodGet || r.Method == http.MethodHead {
289 // Use a single session (cached FileSystem) across
290 // multiple read requests.
291 fs, err = h.Config.Cache.GetSession(token)
293 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
297 // Create a FileSystem for this request, to avoid
298 // exposing incomplete write operations to concurrent
300 _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
302 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
306 fs = client.SiteFileSystem(kc)
307 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
310 var objectNameGiven bool
311 var bucketName string
313 if id := parseCollectionIDFromDNSName(r.Host); id != "" {
316 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 0
318 bucketName = strings.SplitN(strings.TrimPrefix(r.URL.Path, "/"), "/", 2)[0]
319 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
321 fspath += reMultipleSlashChars.ReplaceAllString(r.URL.Path, "/")
324 case r.Method == http.MethodGet && !objectNameGiven:
325 // Path is "/{uuid}" or "/{uuid}/", has no object name
326 if _, ok := r.URL.Query()["versioning"]; ok {
327 // GetBucketVersioning
328 w.Header().Set("Content-Type", "application/xml")
329 io.WriteString(w, xml.Header)
330 fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
331 } else if _, ok = r.URL.Query()["location"]; ok {
333 w.Header().Set("Content-Type", "application/xml")
334 io.WriteString(w, xml.Header)
335 fmt.Fprintln(w, `<LocationConstraint><LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/">`+
336 h.Config.cluster.ClusterID+
337 `</LocationConstraint></LocationConstraint>`)
338 } else if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
339 // GetBucketWebsite ("GET /bucketid/?website"), GetBucketTagging, etc.
340 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
343 h.s3list(bucketName, w, r, fs)
346 case r.Method == http.MethodGet || r.Method == http.MethodHead:
347 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
348 // GetObjectRetention ("GET /bucketid/objectid?retention&versionID=..."), etc.
349 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
352 fi, err := fs.Stat(fspath)
353 if r.Method == "HEAD" && !objectNameGiven {
355 if err == nil && fi.IsDir() {
356 w.WriteHeader(http.StatusOK)
357 } else if os.IsNotExist(err) {
358 s3ErrorResponse(w, NoSuchBucket, "The specified bucket does not exist.", r.URL.Path, http.StatusNotFound)
360 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
364 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Config.cluster.Collections.S3FolderObjects {
365 w.Header().Set("Content-Type", "application/x-directory")
366 w.WriteHeader(http.StatusOK)
369 if os.IsNotExist(err) ||
370 (err != nil && err.Error() == "not a directory") ||
371 (fi != nil && fi.IsDir()) {
372 s3ErrorResponse(w, NoSuchKey, "The specified key does not exist.", r.URL.Path, http.StatusNotFound)
375 // shallow copy r, and change URL path
378 http.FileServer(fs).ServeHTTP(w, &r)
380 case r.Method == http.MethodPut:
381 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
382 // PutObjectAcl ("PUT /bucketid/objectid?acl&versionID=..."), etc.
383 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
386 if !objectNameGiven {
387 s3ErrorResponse(w, InvalidArgument, "Missing object name in PUT request.", r.URL.Path, http.StatusBadRequest)
391 if strings.HasSuffix(fspath, "/") {
392 if !h.Config.cluster.Collections.S3FolderObjects {
393 s3ErrorResponse(w, InvalidArgument, "invalid object name: trailing slash", r.URL.Path, http.StatusBadRequest)
396 n, err := r.Body.Read(make([]byte, 1))
397 if err != nil && err != io.EOF {
398 s3ErrorResponse(w, InternalError, fmt.Sprintf("error reading request body: %s", err), r.URL.Path, http.StatusInternalServerError)
401 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless content is empty", r.URL.Path, http.StatusBadRequest)
403 } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
404 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", r.URL.Path, http.StatusBadRequest)
407 // Given PUT "foo/bar/", we'll use "foo/bar/."
408 // in the "ensure parents exist" block below,
409 // and then we'll be done.
413 fi, err := fs.Stat(fspath)
414 if err != nil && err.Error() == "not a directory" {
415 // requested foo/bar, but foo is a file
416 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
419 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
420 // requested foo/bar/, but foo/bar is a file
421 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
424 // create missing parent/intermediate directories, if any
425 for i, c := range fspath {
426 if i > 0 && c == '/' {
428 if strings.HasSuffix(dir, "/") {
429 err = errors.New("invalid object name (consecutive '/' chars)")
430 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
433 err = fs.Mkdir(dir, 0755)
434 if err == arvados.ErrInvalidArgument {
435 // Cannot create a directory
437 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
438 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
440 } else if err != nil && !os.IsExist(err) {
441 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
442 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
448 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
449 if os.IsNotExist(err) {
450 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
453 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
454 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
458 _, err = io.Copy(f, r.Body)
460 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
461 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
466 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
467 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
473 err = fmt.Errorf("sync failed: %w", err)
474 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
477 // Ensure a subsequent read operation will see the changes.
478 h.Config.Cache.ResetSession(token)
479 w.WriteHeader(http.StatusOK)
481 case r.Method == http.MethodDelete:
482 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
483 // DeleteObjectTagging ("DELETE /bucketid/objectid?tagging&versionID=..."), etc.
484 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
487 if !objectNameGiven || r.URL.Path == "/" {
488 s3ErrorResponse(w, InvalidArgument, "missing object name in DELETE request", r.URL.Path, http.StatusBadRequest)
491 if strings.HasSuffix(fspath, "/") {
492 fspath = strings.TrimSuffix(fspath, "/")
493 fi, err := fs.Stat(fspath)
494 if os.IsNotExist(err) {
495 w.WriteHeader(http.StatusNoContent)
497 } else if err != nil {
498 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
500 } else if !fi.IsDir() {
501 // if "foo" exists and is a file, then
502 // "foo/" doesn't exist, so we say
503 // delete was successful.
504 w.WriteHeader(http.StatusNoContent)
507 } else if fi, err := fs.Stat(fspath); err == nil && fi.IsDir() {
508 // if "foo" is a dir, it is visible via S3
509 // only as "foo/", not "foo" -- so we leave
510 // the dir alone and return 204 to indicate
511 // that "foo" does not exist.
512 w.WriteHeader(http.StatusNoContent)
515 err = fs.Remove(fspath)
516 if os.IsNotExist(err) {
517 w.WriteHeader(http.StatusNoContent)
521 err = fmt.Errorf("rm failed: %w", err)
522 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
527 err = fmt.Errorf("sync failed: %w", err)
528 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
531 // Ensure a subsequent read operation will see the changes.
532 h.Config.Cache.ResetSession(token)
533 w.WriteHeader(http.StatusNoContent)
536 s3ErrorResponse(w, InvalidRequest, "method not allowed", r.URL.Path, http.StatusMethodNotAllowed)
541 // Call fn on the given path (directory) and its contents, in
542 // lexicographic order.
544 // If isRoot==true and path is not a directory, return nil.
546 // If fn returns filepath.SkipDir when called on a directory, don't
547 // descend into that directory.
548 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
550 fi, err := fs.Stat(path)
551 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
553 } else if err != nil {
557 if err == filepath.SkipDir {
559 } else if err != nil {
563 f, err := fs.Open(path)
564 if os.IsNotExist(err) && isRoot {
566 } else if err != nil {
567 return fmt.Errorf("open %q: %w", path, err)
573 fis, err := f.Readdir(-1)
577 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
578 for _, fi := range fis {
579 err = fn(path+"/"+fi.Name(), fi)
580 if err == filepath.SkipDir {
582 } else if err != nil {
586 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
595 var errDone = errors.New("done")
597 func (h *handler) s3list(bucket string, w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
603 marker string // decoded continuationToken (v2) or provided by client (v1)
604 startAfter string // v2
605 continuationToken string // v2
606 encodingTypeURL bool // v2
608 params.delimiter = r.FormValue("delimiter")
609 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
610 params.maxKeys = int(mk)
612 params.maxKeys = s3MaxKeys
614 params.prefix = r.FormValue("prefix")
615 switch r.FormValue("list-type") {
620 http.Error(w, "invalid list-type parameter", http.StatusBadRequest)
624 params.continuationToken = r.FormValue("continuation-token")
625 marker, err := base64.StdEncoding.DecodeString(params.continuationToken)
627 http.Error(w, "invalid continuation token", http.StatusBadRequest)
630 params.marker = string(marker)
631 params.startAfter = r.FormValue("start-after")
632 switch r.FormValue("encoding-type") {
635 params.encodingTypeURL = true
637 http.Error(w, "invalid encoding-type parameter", http.StatusBadRequest)
641 params.marker = r.FormValue("marker")
644 bucketdir := "by_id/" + bucket
645 // walkpath is the directory (relative to bucketdir) we need
646 // to walk: the innermost directory that is guaranteed to
647 // contain all paths that have the requested prefix. Examples:
648 // prefix "foo/bar" => walkpath "foo"
649 // prefix "foo/bar/" => walkpath "foo/bar"
650 // prefix "foo" => walkpath ""
651 // prefix "" => walkpath ""
652 walkpath := params.prefix
653 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
654 walkpath = walkpath[:cut]
661 Prefix: params.prefix,
662 Delimiter: params.delimiter,
663 MaxKeys: params.maxKeys,
664 ContinuationToken: r.FormValue("continuation-token"),
665 StartAfter: params.startAfter,
669 commonPrefixes := map[string]bool{}
670 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
671 if path == bucketdir {
674 path = path[len(bucketdir)+1:]
675 filesize := fi.Size()
680 if len(path) <= len(params.prefix) {
681 if path > params.prefix[:len(path)] {
682 // with prefix "foobar", walking "fooz" means we're done
685 if path < params.prefix[:len(path)] {
686 // with prefix "foobar", walking "foobag" is pointless
687 return filepath.SkipDir
689 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
690 // with prefix "foo/bar", walking "fo"
691 // is pointless (but walking "foo" or
692 // "foo/bar" is necessary)
693 return filepath.SkipDir
695 if len(path) < len(params.prefix) {
696 // can't skip anything, and this entry
697 // isn't in the results, so just
702 if path[:len(params.prefix)] > params.prefix {
703 // with prefix "foobar", nothing we
704 // see after "foozzz" is relevant
708 if path < params.marker || path < params.prefix || path <= params.startAfter {
711 if fi.IsDir() && !h.Config.cluster.Collections.S3FolderObjects {
712 // Note we don't add anything to
713 // commonPrefixes here even if delimiter is
714 // "/". We descend into the directory, and
715 // return a commonPrefix only if we end up
716 // finding a regular file inside it.
719 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
720 resp.IsTruncated = true
721 if params.delimiter != "" || params.v2 {
726 if params.delimiter != "" {
727 idx := strings.Index(path[len(params.prefix):], params.delimiter)
729 // with prefix "foobar" and delimiter
730 // "z", when we hit "foobar/baz", we
731 // add "/baz" to commonPrefixes and
733 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
734 return filepath.SkipDir
737 resp.Contents = append(resp.Contents, s3.Key{
739 LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
744 if err != nil && err != errDone {
745 http.Error(w, err.Error(), http.StatusInternalServerError)
748 if params.delimiter != "" {
749 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
750 for prefix := range commonPrefixes {
751 resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
753 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
755 resp.KeyCount = len(resp.Contents)
756 var respV1orV2 interface{}
758 if params.encodingTypeURL {
759 // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
760 // "If you specify the encoding-type request
761 // parameter, Amazon S3 includes this element in the
762 // response, and returns encoded key name values in
763 // the following response elements:
765 // Delimiter, Prefix, Key, and StartAfter.
769 // Valid Values: url"
771 // This is somewhat vague but in practice it appears
772 // to mean x-www-form-urlencoded as in RFC1866 8.2.1
773 // para 1 (encode space as "+") rather than straight
774 // percent-encoding as in RFC1738 2.2. Presumably,
775 // the intent is to allow the client to decode XML and
776 // then paste the strings directly into another URI
777 // query or POST form like "https://host/path?foo=" +
778 // foo + "&bar=" + bar.
779 resp.EncodingType = "url"
780 resp.Delimiter = url.QueryEscape(resp.Delimiter)
781 resp.Prefix = url.QueryEscape(resp.Prefix)
782 resp.StartAfter = url.QueryEscape(resp.StartAfter)
783 for i, ent := range resp.Contents {
784 ent.Key = url.QueryEscape(ent.Key)
785 resp.Contents[i] = ent
787 for i, ent := range resp.CommonPrefixes {
788 ent.Prefix = url.QueryEscape(ent.Prefix)
789 resp.CommonPrefixes[i] = ent
794 resp.NextContinuationToken = base64.StdEncoding.EncodeToString([]byte(nextMarker))
797 respV1orV2 = listV1Resp{
798 CommonPrefixes: resp.CommonPrefixes,
799 NextMarker: nextMarker,
800 KeyCount: resp.KeyCount,
801 ListResp: s3.ListResp{
802 IsTruncated: resp.IsTruncated,
804 Prefix: params.prefix,
805 Delimiter: params.delimiter,
806 Marker: params.marker,
807 MaxKeys: params.maxKeys,
808 Contents: resp.Contents,
813 w.Header().Set("Content-Type", "application/xml")
814 io.WriteString(w, xml.Header)
815 if err := xml.NewEncoder(w).Encode(respV1orV2); err != nil {
816 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")