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