17187: Merge branch 'master' into 17187-costanalyzer-updates
[arvados.git] / services / keep-web / s3.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         "crypto/hmac"
9         "crypto/sha256"
10         "encoding/xml"
11         "errors"
12         "fmt"
13         "hash"
14         "io"
15         "net/http"
16         "net/url"
17         "os"
18         "path/filepath"
19         "regexp"
20         "sort"
21         "strconv"
22         "strings"
23         "time"
24
25         "git.arvados.org/arvados.git/sdk/go/arvados"
26         "git.arvados.org/arvados.git/sdk/go/ctxlog"
27         "github.com/AdRoll/goamz/s3"
28 )
29
30 const (
31         s3MaxKeys       = 1000
32         s3SignAlgorithm = "AWS4-HMAC-SHA256"
33         s3MaxClockSkew  = 5 * time.Minute
34 )
35
36 func hmacstring(msg string, key []byte) []byte {
37         h := hmac.New(sha256.New, key)
38         io.WriteString(h, msg)
39         return h.Sum(nil)
40 }
41
42 func hashdigest(h hash.Hash, payload string) string {
43         io.WriteString(h, payload)
44         return fmt.Sprintf("%x", h.Sum(nil))
45 }
46
47 // Signing key for given secret key and request attrs.
48 func s3signatureKey(key, datestamp, regionName, serviceName string) []byte {
49         return hmacstring("aws4_request",
50                 hmacstring(serviceName,
51                         hmacstring(regionName,
52                                 hmacstring(datestamp, []byte("AWS4"+key)))))
53 }
54
55 // Canonical query string for S3 V4 signature: sorted keys, spaces
56 // escaped as %20 instead of +, keyvalues joined with &.
57 func s3querystring(u *url.URL) string {
58         keys := make([]string, 0, len(u.Query()))
59         values := make(map[string]string, len(u.Query()))
60         for k, vs := range u.Query() {
61                 k = strings.Replace(url.QueryEscape(k), "+", "%20", -1)
62                 keys = append(keys, k)
63                 for _, v := range vs {
64                         v = strings.Replace(url.QueryEscape(v), "+", "%20", -1)
65                         if values[k] != "" {
66                                 values[k] += "&"
67                         }
68                         values[k] += k + "=" + v
69                 }
70         }
71         sort.Strings(keys)
72         for i, k := range keys {
73                 keys[i] = values[k]
74         }
75         return strings.Join(keys, "&")
76 }
77
78 func s3stringToSign(alg, scope, signedHeaders string, r *http.Request) (string, error) {
79         timefmt, timestr := "20060102T150405Z", r.Header.Get("X-Amz-Date")
80         if timestr == "" {
81                 timefmt, timestr = time.RFC1123, r.Header.Get("Date")
82         }
83         t, err := time.Parse(timefmt, timestr)
84         if err != nil {
85                 return "", fmt.Errorf("invalid timestamp %q: %s", timestr, err)
86         }
87         if skew := time.Now().Sub(t); skew < -s3MaxClockSkew || skew > s3MaxClockSkew {
88                 return "", errors.New("exceeded max clock skew")
89         }
90
91         var canonicalHeaders string
92         for _, h := range strings.Split(signedHeaders, ";") {
93                 if h == "host" {
94                         canonicalHeaders += h + ":" + r.Host + "\n"
95                 } else {
96                         canonicalHeaders += h + ":" + r.Header.Get(h) + "\n"
97                 }
98         }
99
100         canonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s", r.Method, r.URL.EscapedPath(), s3querystring(r.URL), canonicalHeaders, signedHeaders, r.Header.Get("X-Amz-Content-Sha256"))
101         ctxlog.FromContext(r.Context()).Debugf("s3stringToSign: canonicalRequest %s", canonicalRequest)
102         return fmt.Sprintf("%s\n%s\n%s\n%s", alg, r.Header.Get("X-Amz-Date"), scope, hashdigest(sha256.New(), canonicalRequest)), nil
103 }
104
105 func s3signature(secretKey, scope, signedHeaders, stringToSign string) (string, error) {
106         // scope is {datestamp}/{region}/{service}/aws4_request
107         drs := strings.Split(scope, "/")
108         if len(drs) != 4 {
109                 return "", fmt.Errorf("invalid scope %q", scope)
110         }
111         key := s3signatureKey(secretKey, drs[0], drs[1], drs[2])
112         return hashdigest(hmac.New(sha256.New, key), stringToSign), nil
113 }
114
115 var v2tokenUnderscore = regexp.MustCompile(`^v2_[a-z0-9]{5}-gj3su-[a-z0-9]{15}_`)
116
117 func unescapeKey(key string) string {
118         if v2tokenUnderscore.MatchString(key) {
119                 // Entire Arvados token, with "/" replaced by "_" to
120                 // avoid colliding with the Authorization header
121                 // format.
122                 return strings.Replace(key, "_", "/", -1)
123         } else if s, err := url.PathUnescape(key); err == nil {
124                 return s
125         } else {
126                 return key
127         }
128 }
129
130 // checks3signature verifies the given S3 V4 signature and returns the
131 // Arvados token that corresponds to the given accessKey. An error is
132 // returned if accessKey is not a valid token UUID or the signature
133 // does not match.
134 func (h *handler) checks3signature(r *http.Request) (string, error) {
135         var key, scope, signedHeaders, signature string
136         authstring := strings.TrimPrefix(r.Header.Get("Authorization"), s3SignAlgorithm+" ")
137         for _, cmpt := range strings.Split(authstring, ",") {
138                 cmpt = strings.TrimSpace(cmpt)
139                 split := strings.SplitN(cmpt, "=", 2)
140                 switch {
141                 case len(split) != 2:
142                         // (?) ignore
143                 case split[0] == "Credential":
144                         keyandscope := strings.SplitN(split[1], "/", 2)
145                         if len(keyandscope) == 2 {
146                                 key, scope = keyandscope[0], keyandscope[1]
147                         }
148                 case split[0] == "SignedHeaders":
149                         signedHeaders = split[1]
150                 case split[0] == "Signature":
151                         signature = split[1]
152                 }
153         }
154
155         client := (&arvados.Client{
156                 APIHost:  h.Config.cluster.Services.Controller.ExternalURL.Host,
157                 Insecure: h.Config.cluster.TLS.Insecure,
158         }).WithRequestID(r.Header.Get("X-Request-Id"))
159         var aca arvados.APIClientAuthorization
160         var secret string
161         var err error
162         if len(key) == 27 && key[5:12] == "-gj3su-" {
163                 // Access key is the UUID of an Arvados token, secret
164                 // key is the secret part.
165                 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+h.Config.cluster.SystemRootToken)
166                 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/"+key, nil, nil)
167                 secret = aca.APIToken
168         } else {
169                 // Access key and secret key are both an entire
170                 // Arvados token or OIDC access token.
171                 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+unescapeKey(key))
172                 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/current", nil, nil)
173                 secret = key
174         }
175         if err != nil {
176                 ctxlog.FromContext(r.Context()).WithError(err).WithField("UUID", key).Info("token lookup failed")
177                 return "", errors.New("invalid access key")
178         }
179         stringToSign, err := s3stringToSign(s3SignAlgorithm, scope, signedHeaders, r)
180         if err != nil {
181                 return "", err
182         }
183         expect, err := s3signature(secret, scope, signedHeaders, stringToSign)
184         if err != nil {
185                 return "", err
186         } else if expect != signature {
187                 return "", fmt.Errorf("signature does not match (scope %q signedHeaders %q stringToSign %q)", scope, signedHeaders, stringToSign)
188         }
189         return aca.TokenV2(), nil
190 }
191
192 func s3ErrorResponse(w http.ResponseWriter, s3code string, message string, resource string, code int) {
193         w.Header().Set("Content-Type", "application/xml")
194         w.Header().Set("X-Content-Type-Options", "nosniff")
195         w.WriteHeader(code)
196         var errstruct struct {
197                 Code      string
198                 Message   string
199                 Resource  string
200                 RequestId string
201         }
202         errstruct.Code = s3code
203         errstruct.Message = message
204         errstruct.Resource = resource
205         errstruct.RequestId = ""
206         enc := xml.NewEncoder(w)
207         fmt.Fprint(w, xml.Header)
208         enc.EncodeElement(errstruct, xml.StartElement{Name: xml.Name{Local: "Error"}})
209 }
210
211 var NoSuchKey = "NoSuchKey"
212 var NoSuchBucket = "NoSuchBucket"
213 var InvalidArgument = "InvalidArgument"
214 var InternalError = "InternalError"
215 var UnauthorizedAccess = "UnauthorizedAccess"
216 var InvalidRequest = "InvalidRequest"
217 var SignatureDoesNotMatch = "SignatureDoesNotMatch"
218
219 // serveS3 handles r and returns true if r is a request from an S3
220 // client, otherwise it returns false.
221 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
222         var token string
223         if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
224                 split := strings.SplitN(auth[4:], ":", 2)
225                 if len(split) < 2 {
226                         s3ErrorResponse(w, InvalidRequest, "malformed Authorization header", r.URL.Path, http.StatusUnauthorized)
227                         return true
228                 }
229                 token = unescapeKey(split[0])
230         } else if strings.HasPrefix(auth, s3SignAlgorithm+" ") {
231                 t, err := h.checks3signature(r)
232                 if err != nil {
233                         s3ErrorResponse(w, SignatureDoesNotMatch, "signature verification failed: "+err.Error(), r.URL.Path, http.StatusForbidden)
234                         return true
235                 }
236                 token = t
237         } else {
238                 return false
239         }
240
241         _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
242         if err != nil {
243                 s3ErrorResponse(w, InternalError, "Pool failed: "+h.clientPool.Err().Error(), r.URL.Path, http.StatusInternalServerError)
244                 return true
245         }
246         defer release()
247
248         fs := client.SiteFileSystem(kc)
249         fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
250
251         var objectNameGiven bool
252         var bucketName string
253         fspath := "/by_id"
254         if id := parseCollectionIDFromDNSName(r.Host); id != "" {
255                 fspath += "/" + id
256                 bucketName = id
257                 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 0
258         } else {
259                 bucketName = strings.SplitN(strings.TrimPrefix(r.URL.Path, "/"), "/", 2)[0]
260                 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
261         }
262         fspath += r.URL.Path
263
264         switch {
265         case r.Method == http.MethodGet && !objectNameGiven:
266                 // Path is "/{uuid}" or "/{uuid}/", has no object name
267                 if _, ok := r.URL.Query()["versioning"]; ok {
268                         // GetBucketVersioning
269                         w.Header().Set("Content-Type", "application/xml")
270                         io.WriteString(w, xml.Header)
271                         fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
272                 } else {
273                         // ListObjects
274                         h.s3list(bucketName, w, r, fs)
275                 }
276                 return true
277         case r.Method == http.MethodGet || r.Method == http.MethodHead:
278                 fi, err := fs.Stat(fspath)
279                 if r.Method == "HEAD" && !objectNameGiven {
280                         // HeadBucket
281                         if err == nil && fi.IsDir() {
282                                 w.WriteHeader(http.StatusOK)
283                         } else if os.IsNotExist(err) {
284                                 s3ErrorResponse(w, NoSuchBucket, "The specified bucket does not exist.", r.URL.Path, http.StatusNotFound)
285                         } else {
286                                 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
287                         }
288                         return true
289                 }
290                 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Config.cluster.Collections.S3FolderObjects {
291                         w.Header().Set("Content-Type", "application/x-directory")
292                         w.WriteHeader(http.StatusOK)
293                         return true
294                 }
295                 if os.IsNotExist(err) ||
296                         (err != nil && err.Error() == "not a directory") ||
297                         (fi != nil && fi.IsDir()) {
298                         s3ErrorResponse(w, NoSuchKey, "The specified key does not exist.", r.URL.Path, http.StatusNotFound)
299                         return true
300                 }
301                 // shallow copy r, and change URL path
302                 r := *r
303                 r.URL.Path = fspath
304                 http.FileServer(fs).ServeHTTP(w, &r)
305                 return true
306         case r.Method == http.MethodPut:
307                 if !objectNameGiven {
308                         s3ErrorResponse(w, InvalidArgument, "Missing object name in PUT request.", r.URL.Path, http.StatusBadRequest)
309                         return true
310                 }
311                 var objectIsDir bool
312                 if strings.HasSuffix(fspath, "/") {
313                         if !h.Config.cluster.Collections.S3FolderObjects {
314                                 s3ErrorResponse(w, InvalidArgument, "invalid object name: trailing slash", r.URL.Path, http.StatusBadRequest)
315                                 return true
316                         }
317                         n, err := r.Body.Read(make([]byte, 1))
318                         if err != nil && err != io.EOF {
319                                 s3ErrorResponse(w, InternalError, fmt.Sprintf("error reading request body: %s", err), r.URL.Path, http.StatusInternalServerError)
320                                 return true
321                         } else if n > 0 {
322                                 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless content is empty", r.URL.Path, http.StatusBadRequest)
323                                 return true
324                         } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
325                                 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", r.URL.Path, http.StatusBadRequest)
326                                 return true
327                         }
328                         // Given PUT "foo/bar/", we'll use "foo/bar/."
329                         // in the "ensure parents exist" block below,
330                         // and then we'll be done.
331                         fspath += "."
332                         objectIsDir = true
333                 }
334                 fi, err := fs.Stat(fspath)
335                 if err != nil && err.Error() == "not a directory" {
336                         // requested foo/bar, but foo is a file
337                         s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
338                         return true
339                 }
340                 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
341                         // requested foo/bar/, but foo/bar is a file
342                         s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
343                         return true
344                 }
345                 // create missing parent/intermediate directories, if any
346                 for i, c := range fspath {
347                         if i > 0 && c == '/' {
348                                 dir := fspath[:i]
349                                 if strings.HasSuffix(dir, "/") {
350                                         err = errors.New("invalid object name (consecutive '/' chars)")
351                                         s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
352                                         return true
353                                 }
354                                 err = fs.Mkdir(dir, 0755)
355                                 if err == arvados.ErrInvalidArgument {
356                                         // Cannot create a directory
357                                         // here.
358                                         err = fmt.Errorf("mkdir %q failed: %w", dir, err)
359                                         s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
360                                         return true
361                                 } else if err != nil && !os.IsExist(err) {
362                                         err = fmt.Errorf("mkdir %q failed: %w", dir, err)
363                                         s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
364                                         return true
365                                 }
366                         }
367                 }
368                 if !objectIsDir {
369                         f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
370                         if os.IsNotExist(err) {
371                                 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
372                         }
373                         if err != nil {
374                                 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
375                                 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
376                                 return true
377                         }
378                         defer f.Close()
379                         _, err = io.Copy(f, r.Body)
380                         if err != nil {
381                                 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
382                                 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
383                                 return true
384                         }
385                         err = f.Close()
386                         if err != nil {
387                                 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
388                                 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
389                                 return true
390                         }
391                 }
392                 err = fs.Sync()
393                 if err != nil {
394                         err = fmt.Errorf("sync failed: %w", err)
395                         s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
396                         return true
397                 }
398                 w.WriteHeader(http.StatusOK)
399                 return true
400         case r.Method == http.MethodDelete:
401                 if !objectNameGiven || r.URL.Path == "/" {
402                         s3ErrorResponse(w, InvalidArgument, "missing object name in DELETE request", r.URL.Path, http.StatusBadRequest)
403                         return true
404                 }
405                 if strings.HasSuffix(fspath, "/") {
406                         fspath = strings.TrimSuffix(fspath, "/")
407                         fi, err := fs.Stat(fspath)
408                         if os.IsNotExist(err) {
409                                 w.WriteHeader(http.StatusNoContent)
410                                 return true
411                         } else if err != nil {
412                                 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
413                                 return true
414                         } else if !fi.IsDir() {
415                                 // if "foo" exists and is a file, then
416                                 // "foo/" doesn't exist, so we say
417                                 // delete was successful.
418                                 w.WriteHeader(http.StatusNoContent)
419                                 return true
420                         }
421                 } else if fi, err := fs.Stat(fspath); err == nil && fi.IsDir() {
422                         // if "foo" is a dir, it is visible via S3
423                         // only as "foo/", not "foo" -- so we leave
424                         // the dir alone and return 204 to indicate
425                         // that "foo" does not exist.
426                         w.WriteHeader(http.StatusNoContent)
427                         return true
428                 }
429                 err = fs.Remove(fspath)
430                 if os.IsNotExist(err) {
431                         w.WriteHeader(http.StatusNoContent)
432                         return true
433                 }
434                 if err != nil {
435                         err = fmt.Errorf("rm failed: %w", err)
436                         s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
437                         return true
438                 }
439                 err = fs.Sync()
440                 if err != nil {
441                         err = fmt.Errorf("sync failed: %w", err)
442                         s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
443                         return true
444                 }
445                 w.WriteHeader(http.StatusNoContent)
446                 return true
447         default:
448                 s3ErrorResponse(w, InvalidRequest, "method not allowed", r.URL.Path, http.StatusMethodNotAllowed)
449
450                 return true
451         }
452 }
453
454 // Call fn on the given path (directory) and its contents, in
455 // lexicographic order.
456 //
457 // If isRoot==true and path is not a directory, return nil.
458 //
459 // If fn returns filepath.SkipDir when called on a directory, don't
460 // descend into that directory.
461 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
462         if isRoot {
463                 fi, err := fs.Stat(path)
464                 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
465                         return nil
466                 } else if err != nil {
467                         return err
468                 }
469                 err = fn(path, fi)
470                 if err == filepath.SkipDir {
471                         return nil
472                 } else if err != nil {
473                         return err
474                 }
475         }
476         f, err := fs.Open(path)
477         if os.IsNotExist(err) && isRoot {
478                 return nil
479         } else if err != nil {
480                 return fmt.Errorf("open %q: %w", path, err)
481         }
482         defer f.Close()
483         if path == "/" {
484                 path = ""
485         }
486         fis, err := f.Readdir(-1)
487         if err != nil {
488                 return err
489         }
490         sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
491         for _, fi := range fis {
492                 err = fn(path+"/"+fi.Name(), fi)
493                 if err == filepath.SkipDir {
494                         continue
495                 } else if err != nil {
496                         return err
497                 }
498                 if fi.IsDir() {
499                         err = walkFS(fs, path+"/"+fi.Name(), false, fn)
500                         if err != nil {
501                                 return err
502                         }
503                 }
504         }
505         return nil
506 }
507
508 var errDone = errors.New("done")
509
510 func (h *handler) s3list(bucket string, w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
511         var params struct {
512                 delimiter string
513                 marker    string
514                 maxKeys   int
515                 prefix    string
516         }
517         params.delimiter = r.FormValue("delimiter")
518         params.marker = r.FormValue("marker")
519         if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
520                 params.maxKeys = int(mk)
521         } else {
522                 params.maxKeys = s3MaxKeys
523         }
524         params.prefix = r.FormValue("prefix")
525
526         bucketdir := "by_id/" + bucket
527         // walkpath is the directory (relative to bucketdir) we need
528         // to walk: the innermost directory that is guaranteed to
529         // contain all paths that have the requested prefix. Examples:
530         // prefix "foo/bar"  => walkpath "foo"
531         // prefix "foo/bar/" => walkpath "foo/bar"
532         // prefix "foo"      => walkpath ""
533         // prefix ""         => walkpath ""
534         walkpath := params.prefix
535         if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
536                 walkpath = walkpath[:cut]
537         } else {
538                 walkpath = ""
539         }
540
541         type commonPrefix struct {
542                 Prefix string
543         }
544         type listResp struct {
545                 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
546                 s3.ListResp
547                 // s3.ListResp marshals an empty tag when
548                 // CommonPrefixes is nil, which confuses some clients.
549                 // Fix by using this nested struct instead.
550                 CommonPrefixes []commonPrefix
551                 // Similarly, we need omitempty here, because an empty
552                 // tag confuses some clients (e.g.,
553                 // github.com/aws/aws-sdk-net never terminates its
554                 // paging loop).
555                 NextMarker string `xml:"NextMarker,omitempty"`
556                 // ListObjectsV2 has a KeyCount response field.
557                 KeyCount int
558         }
559         resp := listResp{
560                 ListResp: s3.ListResp{
561                         Name:      bucket,
562                         Prefix:    params.prefix,
563                         Delimiter: params.delimiter,
564                         Marker:    params.marker,
565                         MaxKeys:   params.maxKeys,
566                 },
567         }
568         commonPrefixes := map[string]bool{}
569         err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
570                 if path == bucketdir {
571                         return nil
572                 }
573                 path = path[len(bucketdir)+1:]
574                 filesize := fi.Size()
575                 if fi.IsDir() {
576                         path += "/"
577                         filesize = 0
578                 }
579                 if len(path) <= len(params.prefix) {
580                         if path > params.prefix[:len(path)] {
581                                 // with prefix "foobar", walking "fooz" means we're done
582                                 return errDone
583                         }
584                         if path < params.prefix[:len(path)] {
585                                 // with prefix "foobar", walking "foobag" is pointless
586                                 return filepath.SkipDir
587                         }
588                         if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
589                                 // with prefix "foo/bar", walking "fo"
590                                 // is pointless (but walking "foo" or
591                                 // "foo/bar" is necessary)
592                                 return filepath.SkipDir
593                         }
594                         if len(path) < len(params.prefix) {
595                                 // can't skip anything, and this entry
596                                 // isn't in the results, so just
597                                 // continue descent
598                                 return nil
599                         }
600                 } else {
601                         if path[:len(params.prefix)] > params.prefix {
602                                 // with prefix "foobar", nothing we
603                                 // see after "foozzz" is relevant
604                                 return errDone
605                         }
606                 }
607                 if path < params.marker || path < params.prefix {
608                         return nil
609                 }
610                 if fi.IsDir() && !h.Config.cluster.Collections.S3FolderObjects {
611                         // Note we don't add anything to
612                         // commonPrefixes here even if delimiter is
613                         // "/". We descend into the directory, and
614                         // return a commonPrefix only if we end up
615                         // finding a regular file inside it.
616                         return nil
617                 }
618                 if params.delimiter != "" {
619                         idx := strings.Index(path[len(params.prefix):], params.delimiter)
620                         if idx >= 0 {
621                                 // with prefix "foobar" and delimiter
622                                 // "z", when we hit "foobar/baz", we
623                                 // add "/baz" to commonPrefixes and
624                                 // stop descending.
625                                 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
626                                 return filepath.SkipDir
627                         }
628                 }
629                 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
630                         resp.IsTruncated = true
631                         if params.delimiter != "" {
632                                 resp.NextMarker = path
633                         }
634                         return errDone
635                 }
636                 resp.Contents = append(resp.Contents, s3.Key{
637                         Key:          path,
638                         LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
639                         Size:         filesize,
640                 })
641                 return nil
642         })
643         if err != nil && err != errDone {
644                 http.Error(w, err.Error(), http.StatusInternalServerError)
645                 return
646         }
647         if params.delimiter != "" {
648                 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
649                 for prefix := range commonPrefixes {
650                         resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
651                 }
652                 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
653         }
654         resp.KeyCount = len(resp.Contents)
655         w.Header().Set("Content-Type", "application/xml")
656         io.WriteString(w, xml.Header)
657         if err := xml.NewEncoder(w).Encode(resp); err != nil {
658                 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")
659         }
660 }