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 normalizedPath := normalizePath(r.URL.Path)
140 ctxlog.FromContext(r.Context()).Debugf("normalizedPath %q", normalizedPath)
141 canonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s", r.Method, normalizedPath, s3querystring(r.URL), canonicalHeaders, signedHeaders, r.Header.Get("X-Amz-Content-Sha256"))
142 ctxlog.FromContext(r.Context()).Debugf("s3stringToSign: canonicalRequest %s", canonicalRequest)
143 return fmt.Sprintf("%s\n%s\n%s\n%s", alg, r.Header.Get("X-Amz-Date"), scope, hashdigest(sha256.New(), canonicalRequest)), nil
146 func normalizePath(s string) string {
147 // (url.URL).EscapedPath() would be incorrect here. AWS
148 // documentation specifies the URL path should be normalized
149 // according to RFC 3986, i.e., unescaping ALPHA / DIGIT / "-"
150 // / "." / "_" / "~". The implication is that everything other
151 // than those chars (and "/") _must_ be percent-encoded --
152 // even chars like ";" and "," that are not normally
153 // percent-encoded in paths.
155 for _, c := range []byte(reMultipleSlashChars.ReplaceAllString(s, "/")) {
156 if (c >= 'a' && c <= 'z') ||
157 (c >= 'A' && c <= 'Z') ||
158 (c >= '0' && c <= '9') ||
166 out += fmt.Sprintf("%%%02X", c)
172 func s3signature(secretKey, scope, signedHeaders, stringToSign string) (string, error) {
173 // scope is {datestamp}/{region}/{service}/aws4_request
174 drs := strings.Split(scope, "/")
176 return "", fmt.Errorf("invalid scope %q", scope)
178 key := s3signatureKey(secretKey, drs[0], drs[1], drs[2])
179 return hashdigest(hmac.New(sha256.New, key), stringToSign), nil
182 var v2tokenUnderscore = regexp.MustCompile(`^v2_[a-z0-9]{5}-gj3su-[a-z0-9]{15}_`)
184 func unescapeKey(key string) string {
185 if v2tokenUnderscore.MatchString(key) {
186 // Entire Arvados token, with "/" replaced by "_" to
187 // avoid colliding with the Authorization header
189 return strings.Replace(key, "_", "/", -1)
190 } else if s, err := url.PathUnescape(key); err == nil {
197 // checks3signature verifies the given S3 V4 signature and returns the
198 // Arvados token that corresponds to the given accessKey. An error is
199 // returned if accessKey is not a valid token UUID or the signature
201 func (h *handler) checks3signature(r *http.Request) (string, error) {
202 var key, scope, signedHeaders, signature string
203 authstring := strings.TrimPrefix(r.Header.Get("Authorization"), s3SignAlgorithm+" ")
204 for _, cmpt := range strings.Split(authstring, ",") {
205 cmpt = strings.TrimSpace(cmpt)
206 split := strings.SplitN(cmpt, "=", 2)
208 case len(split) != 2:
210 case split[0] == "Credential":
211 keyandscope := strings.SplitN(split[1], "/", 2)
212 if len(keyandscope) == 2 {
213 key, scope = keyandscope[0], keyandscope[1]
215 case split[0] == "SignedHeaders":
216 signedHeaders = split[1]
217 case split[0] == "Signature":
222 client := (&arvados.Client{
223 APIHost: h.Config.cluster.Services.Controller.ExternalURL.Host,
224 Insecure: h.Config.cluster.TLS.Insecure,
225 }).WithRequestID(r.Header.Get("X-Request-Id"))
226 var aca arvados.APIClientAuthorization
229 if len(key) == 27 && key[5:12] == "-gj3su-" {
230 // Access key is the UUID of an Arvados token, secret
231 // key is the secret part.
232 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+h.Config.cluster.SystemRootToken)
233 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/"+key, nil, nil)
234 secret = aca.APIToken
236 // Access key and secret key are both an entire
237 // Arvados token or OIDC access token.
238 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+unescapeKey(key))
239 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/current", nil, nil)
243 ctxlog.FromContext(r.Context()).WithError(err).WithField("UUID", key).Info("token lookup failed")
244 return "", errors.New("invalid access key")
246 stringToSign, err := s3stringToSign(s3SignAlgorithm, scope, signedHeaders, r)
250 expect, err := s3signature(secret, scope, signedHeaders, stringToSign)
253 } else if expect != signature {
254 return "", fmt.Errorf("signature does not match (scope %q signedHeaders %q stringToSign %q)", scope, signedHeaders, stringToSign)
256 return aca.TokenV2(), nil
259 func s3ErrorResponse(w http.ResponseWriter, s3code string, message string, resource string, code int) {
260 w.Header().Set("Content-Type", "application/xml")
261 w.Header().Set("X-Content-Type-Options", "nosniff")
263 var errstruct struct {
269 errstruct.Code = s3code
270 errstruct.Message = message
271 errstruct.Resource = resource
272 errstruct.RequestId = ""
273 enc := xml.NewEncoder(w)
274 fmt.Fprint(w, xml.Header)
275 enc.EncodeElement(errstruct, xml.StartElement{Name: xml.Name{Local: "Error"}})
278 var NoSuchKey = "NoSuchKey"
279 var NoSuchBucket = "NoSuchBucket"
280 var InvalidArgument = "InvalidArgument"
281 var InternalError = "InternalError"
282 var UnauthorizedAccess = "UnauthorizedAccess"
283 var InvalidRequest = "InvalidRequest"
284 var SignatureDoesNotMatch = "SignatureDoesNotMatch"
286 var reRawQueryIndicatesAPI = regexp.MustCompile(`^[a-z]+(&|$)`)
288 // serveS3 handles r and returns true if r is a request from an S3
289 // client, otherwise it returns false.
290 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
292 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
293 split := strings.SplitN(auth[4:], ":", 2)
295 s3ErrorResponse(w, InvalidRequest, "malformed Authorization header", r.URL.Path, http.StatusUnauthorized)
298 token = unescapeKey(split[0])
299 } else if strings.HasPrefix(auth, s3SignAlgorithm+" ") {
300 t, err := h.checks3signature(r)
302 s3ErrorResponse(w, SignatureDoesNotMatch, "signature verification failed: "+err.Error(), r.URL.Path, http.StatusForbidden)
311 var fs arvados.CustomFileSystem
312 if r.Method == http.MethodGet || r.Method == http.MethodHead {
313 // Use a single session (cached FileSystem) across
314 // multiple read requests.
315 fs, err = h.Config.Cache.GetSession(token)
317 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
321 // Create a FileSystem for this request, to avoid
322 // exposing incomplete write operations to concurrent
324 _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
326 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
330 fs = client.SiteFileSystem(kc)
331 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
334 var objectNameGiven bool
335 var bucketName string
337 if id := parseCollectionIDFromDNSName(r.Host); id != "" {
340 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 0
342 bucketName = strings.SplitN(strings.TrimPrefix(r.URL.Path, "/"), "/", 2)[0]
343 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
345 fspath += reMultipleSlashChars.ReplaceAllString(r.URL.Path, "/")
348 case r.Method == http.MethodGet && !objectNameGiven:
349 // Path is "/{uuid}" or "/{uuid}/", has no object name
350 if _, ok := r.URL.Query()["versioning"]; ok {
351 // GetBucketVersioning
352 w.Header().Set("Content-Type", "application/xml")
353 io.WriteString(w, xml.Header)
354 fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
355 } else if _, ok = r.URL.Query()["location"]; ok {
357 w.Header().Set("Content-Type", "application/xml")
358 io.WriteString(w, xml.Header)
359 fmt.Fprintln(w, `<LocationConstraint><LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/">`+
360 h.Config.cluster.ClusterID+
361 `</LocationConstraint></LocationConstraint>`)
362 } else if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
363 // GetBucketWebsite ("GET /bucketid/?website"), GetBucketTagging, etc.
364 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
367 h.s3list(bucketName, w, r, fs)
370 case r.Method == http.MethodGet || r.Method == http.MethodHead:
371 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
372 // GetObjectRetention ("GET /bucketid/objectid?retention&versionID=..."), etc.
373 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
376 fi, err := fs.Stat(fspath)
377 if r.Method == "HEAD" && !objectNameGiven {
379 if err == nil && fi.IsDir() {
380 w.WriteHeader(http.StatusOK)
381 } else if os.IsNotExist(err) {
382 s3ErrorResponse(w, NoSuchBucket, "The specified bucket does not exist.", r.URL.Path, http.StatusNotFound)
384 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
388 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Config.cluster.Collections.S3FolderObjects {
389 w.Header().Set("Content-Type", "application/x-directory")
390 w.WriteHeader(http.StatusOK)
393 if os.IsNotExist(err) ||
394 (err != nil && err.Error() == "not a directory") ||
395 (fi != nil && fi.IsDir()) {
396 s3ErrorResponse(w, NoSuchKey, "The specified key does not exist.", r.URL.Path, http.StatusNotFound)
399 // shallow copy r, and change URL path
402 http.FileServer(fs).ServeHTTP(w, &r)
404 case r.Method == http.MethodPut:
405 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
406 // PutObjectAcl ("PUT /bucketid/objectid?acl&versionID=..."), etc.
407 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
410 if !objectNameGiven {
411 s3ErrorResponse(w, InvalidArgument, "Missing object name in PUT request.", r.URL.Path, http.StatusBadRequest)
415 if strings.HasSuffix(fspath, "/") {
416 if !h.Config.cluster.Collections.S3FolderObjects {
417 s3ErrorResponse(w, InvalidArgument, "invalid object name: trailing slash", r.URL.Path, http.StatusBadRequest)
420 n, err := r.Body.Read(make([]byte, 1))
421 if err != nil && err != io.EOF {
422 s3ErrorResponse(w, InternalError, fmt.Sprintf("error reading request body: %s", err), r.URL.Path, http.StatusInternalServerError)
425 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless content is empty", r.URL.Path, http.StatusBadRequest)
427 } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
428 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", r.URL.Path, http.StatusBadRequest)
431 // Given PUT "foo/bar/", we'll use "foo/bar/."
432 // in the "ensure parents exist" block below,
433 // and then we'll be done.
437 fi, err := fs.Stat(fspath)
438 if err != nil && err.Error() == "not a directory" {
439 // requested foo/bar, but foo is a file
440 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
443 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
444 // requested foo/bar/, but foo/bar is a file
445 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
448 // create missing parent/intermediate directories, if any
449 for i, c := range fspath {
450 if i > 0 && c == '/' {
452 if strings.HasSuffix(dir, "/") {
453 err = errors.New("invalid object name (consecutive '/' chars)")
454 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
457 err = fs.Mkdir(dir, 0755)
458 if err == arvados.ErrInvalidArgument {
459 // Cannot create a directory
461 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
462 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
464 } else if err != nil && !os.IsExist(err) {
465 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
466 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
472 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
473 if os.IsNotExist(err) {
474 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
477 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
478 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
482 _, err = io.Copy(f, r.Body)
484 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
485 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
490 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
491 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
497 err = fmt.Errorf("sync failed: %w", err)
498 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
501 // Ensure a subsequent read operation will see the changes.
502 h.Config.Cache.ResetSession(token)
503 w.WriteHeader(http.StatusOK)
505 case r.Method == http.MethodDelete:
506 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
507 // DeleteObjectTagging ("DELETE /bucketid/objectid?tagging&versionID=..."), etc.
508 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
511 if !objectNameGiven || r.URL.Path == "/" {
512 s3ErrorResponse(w, InvalidArgument, "missing object name in DELETE request", r.URL.Path, http.StatusBadRequest)
515 if strings.HasSuffix(fspath, "/") {
516 fspath = strings.TrimSuffix(fspath, "/")
517 fi, err := fs.Stat(fspath)
518 if os.IsNotExist(err) {
519 w.WriteHeader(http.StatusNoContent)
521 } else if err != nil {
522 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
524 } else if !fi.IsDir() {
525 // if "foo" exists and is a file, then
526 // "foo/" doesn't exist, so we say
527 // delete was successful.
528 w.WriteHeader(http.StatusNoContent)
531 } else if fi, err := fs.Stat(fspath); err == nil && fi.IsDir() {
532 // if "foo" is a dir, it is visible via S3
533 // only as "foo/", not "foo" -- so we leave
534 // the dir alone and return 204 to indicate
535 // that "foo" does not exist.
536 w.WriteHeader(http.StatusNoContent)
539 err = fs.Remove(fspath)
540 if os.IsNotExist(err) {
541 w.WriteHeader(http.StatusNoContent)
545 err = fmt.Errorf("rm failed: %w", err)
546 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
551 err = fmt.Errorf("sync failed: %w", err)
552 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
555 // Ensure a subsequent read operation will see the changes.
556 h.Config.Cache.ResetSession(token)
557 w.WriteHeader(http.StatusNoContent)
560 s3ErrorResponse(w, InvalidRequest, "method not allowed", r.URL.Path, http.StatusMethodNotAllowed)
565 // Call fn on the given path (directory) and its contents, in
566 // lexicographic order.
568 // If isRoot==true and path is not a directory, return nil.
570 // If fn returns filepath.SkipDir when called on a directory, don't
571 // descend into that directory.
572 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
574 fi, err := fs.Stat(path)
575 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
577 } else if err != nil {
581 if err == filepath.SkipDir {
583 } else if err != nil {
587 f, err := fs.Open(path)
588 if os.IsNotExist(err) && isRoot {
590 } else if err != nil {
591 return fmt.Errorf("open %q: %w", path, err)
597 fis, err := f.Readdir(-1)
601 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
602 for _, fi := range fis {
603 err = fn(path+"/"+fi.Name(), fi)
604 if err == filepath.SkipDir {
606 } else if err != nil {
610 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
619 var errDone = errors.New("done")
621 func (h *handler) s3list(bucket string, w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
627 marker string // decoded continuationToken (v2) or provided by client (v1)
628 startAfter string // v2
629 continuationToken string // v2
630 encodingTypeURL bool // v2
632 params.delimiter = r.FormValue("delimiter")
633 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
634 params.maxKeys = int(mk)
636 params.maxKeys = s3MaxKeys
638 params.prefix = r.FormValue("prefix")
639 switch r.FormValue("list-type") {
644 http.Error(w, "invalid list-type parameter", http.StatusBadRequest)
648 params.continuationToken = r.FormValue("continuation-token")
649 marker, err := base64.StdEncoding.DecodeString(params.continuationToken)
651 http.Error(w, "invalid continuation token", http.StatusBadRequest)
654 params.marker = string(marker)
655 params.startAfter = r.FormValue("start-after")
656 switch r.FormValue("encoding-type") {
659 params.encodingTypeURL = true
661 http.Error(w, "invalid encoding-type parameter", http.StatusBadRequest)
665 params.marker = r.FormValue("marker")
668 bucketdir := "by_id/" + bucket
669 // walkpath is the directory (relative to bucketdir) we need
670 // to walk: the innermost directory that is guaranteed to
671 // contain all paths that have the requested prefix. Examples:
672 // prefix "foo/bar" => walkpath "foo"
673 // prefix "foo/bar/" => walkpath "foo/bar"
674 // prefix "foo" => walkpath ""
675 // prefix "" => walkpath ""
676 walkpath := params.prefix
677 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
678 walkpath = walkpath[:cut]
685 Prefix: params.prefix,
686 Delimiter: params.delimiter,
687 MaxKeys: params.maxKeys,
688 ContinuationToken: r.FormValue("continuation-token"),
689 StartAfter: params.startAfter,
693 commonPrefixes := map[string]bool{}
694 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
695 if path == bucketdir {
698 path = path[len(bucketdir)+1:]
699 filesize := fi.Size()
704 if len(path) <= len(params.prefix) {
705 if path > params.prefix[:len(path)] {
706 // with prefix "foobar", walking "fooz" means we're done
709 if path < params.prefix[:len(path)] {
710 // with prefix "foobar", walking "foobag" is pointless
711 return filepath.SkipDir
713 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
714 // with prefix "foo/bar", walking "fo"
715 // is pointless (but walking "foo" or
716 // "foo/bar" is necessary)
717 return filepath.SkipDir
719 if len(path) < len(params.prefix) {
720 // can't skip anything, and this entry
721 // isn't in the results, so just
726 if path[:len(params.prefix)] > params.prefix {
727 // with prefix "foobar", nothing we
728 // see after "foozzz" is relevant
732 if path < params.marker || path < params.prefix || path <= params.startAfter {
735 if fi.IsDir() && !h.Config.cluster.Collections.S3FolderObjects {
736 // Note we don't add anything to
737 // commonPrefixes here even if delimiter is
738 // "/". We descend into the directory, and
739 // return a commonPrefix only if we end up
740 // finding a regular file inside it.
743 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
744 resp.IsTruncated = true
745 if params.delimiter != "" || params.v2 {
750 if params.delimiter != "" {
751 idx := strings.Index(path[len(params.prefix):], params.delimiter)
753 // with prefix "foobar" and delimiter
754 // "z", when we hit "foobar/baz", we
755 // add "/baz" to commonPrefixes and
757 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
758 return filepath.SkipDir
761 resp.Contents = append(resp.Contents, s3.Key{
763 LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
768 if err != nil && err != errDone {
769 http.Error(w, err.Error(), http.StatusInternalServerError)
772 if params.delimiter != "" {
773 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
774 for prefix := range commonPrefixes {
775 resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
777 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
779 resp.KeyCount = len(resp.Contents)
780 var respV1orV2 interface{}
782 if params.encodingTypeURL {
783 // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
784 // "If you specify the encoding-type request
785 // parameter, Amazon S3 includes this element in the
786 // response, and returns encoded key name values in
787 // the following response elements:
789 // Delimiter, Prefix, Key, and StartAfter.
793 // Valid Values: url"
795 // This is somewhat vague but in practice it appears
796 // to mean x-www-form-urlencoded as in RFC1866 8.2.1
797 // para 1 (encode space as "+") rather than straight
798 // percent-encoding as in RFC1738 2.2. Presumably,
799 // the intent is to allow the client to decode XML and
800 // then paste the strings directly into another URI
801 // query or POST form like "https://host/path?foo=" +
802 // foo + "&bar=" + bar.
803 resp.EncodingType = "url"
804 resp.Delimiter = url.QueryEscape(resp.Delimiter)
805 resp.Prefix = url.QueryEscape(resp.Prefix)
806 resp.StartAfter = url.QueryEscape(resp.StartAfter)
807 for i, ent := range resp.Contents {
808 ent.Key = url.QueryEscape(ent.Key)
809 resp.Contents[i] = ent
811 for i, ent := range resp.CommonPrefixes {
812 ent.Prefix = url.QueryEscape(ent.Prefix)
813 resp.CommonPrefixes[i] = ent
818 resp.NextContinuationToken = base64.StdEncoding.EncodeToString([]byte(nextMarker))
821 respV1orV2 = listV1Resp{
822 CommonPrefixes: resp.CommonPrefixes,
823 NextMarker: nextMarker,
824 KeyCount: resp.KeyCount,
825 ListResp: s3.ListResp{
826 IsTruncated: resp.IsTruncated,
828 Prefix: params.prefix,
829 Delimiter: params.delimiter,
830 Marker: params.marker,
831 MaxKeys: params.maxKeys,
832 Contents: resp.Contents,
837 w.Header().Set("Content-Type", "application/xml")
838 io.WriteString(w, xml.Header)
839 if err := xml.NewEncoder(w).Encode(respV1orV2); err != nil {
840 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")