16774: Keep-web errors include messages
[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         fmt.Fprintf(w, `<?xml version="1.0" encoding="UTF-8"?>
181 <Error>
182   <Code>%v</Code>
183   <Message>%v</Message>
184   <Resource>%v</Resource>
185   <RequestId></RequestId>
186 </Error>`, code, message, resource)
187 }
188
189 var NoSuchKey = "NoSuchKey"
190 var NoSuchBucket = "NoSuchBucket"
191 var InvalidArgument = "InvalidArgument"
192 var InternalError = "InternalError"
193 var UnauthorizedAccess = "UnauthorizedAccess"
194 var InvalidRequest = "InvalidRequest"
195 var SignatureDoesNotMatch = "SignatureDoesNotMatch"
196
197 // serveS3 handles r and returns true if r is a request from an S3
198 // client, otherwise it returns false.
199 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
200         var token string
201         if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
202                 split := strings.SplitN(auth[4:], ":", 2)
203                 if len(split) < 2 {
204                         s3ErrorResponse(w, InvalidRequest, "malformed Authorization header", r.URL.Path, http.StatusUnauthorized)
205                         return true
206                 }
207                 token = split[0]
208         } else if strings.HasPrefix(auth, s3SignAlgorithm+" ") {
209                 t, err := h.checks3signature(r)
210                 if err != nil {
211                         s3ErrorResponse(w, SignatureDoesNotMatch, "signature verification failed: "+err.Error(), r.URL.Path, http.StatusForbidden)
212                         return true
213                 }
214                 token = t
215         } else {
216                 return false
217         }
218
219         _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
220         if err != nil {
221                 s3ErrorResponse(w, InternalError, "Pool failed: "+h.clientPool.Err().Error(), r.URL.Path, http.StatusInternalServerError)
222                 return true
223         }
224         defer release()
225
226         fs := client.SiteFileSystem(kc)
227         fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
228
229         objectNameGiven := strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
230
231         switch {
232         case r.Method == http.MethodGet && !objectNameGiven:
233                 // Path is "/{uuid}" or "/{uuid}/", has no object name
234                 if _, ok := r.URL.Query()["versioning"]; ok {
235                         // GetBucketVersioning
236                         w.Header().Set("Content-Type", "application/xml")
237                         io.WriteString(w, xml.Header)
238                         fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
239                 } else {
240                         // ListObjects
241                         h.s3list(w, r, fs)
242                 }
243                 return true
244         case r.Method == http.MethodGet || r.Method == http.MethodHead:
245                 fspath := "/by_id" + r.URL.Path
246                 fi, err := fs.Stat(fspath)
247                 if r.Method == "HEAD" && !objectNameGiven {
248                         // HeadBucket
249                         if err == nil && fi.IsDir() {
250                                 w.WriteHeader(http.StatusOK)
251                         } else if os.IsNotExist(err) {
252                                 s3ErrorResponse(w, NoSuchBucket, "The specified bucket does not exist.", r.URL.Path, http.StatusNotFound)
253                         } else {
254                                 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
255                         }
256                         return true
257                 }
258                 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Config.cluster.Collections.S3FolderObjects {
259                         w.Header().Set("Content-Type", "application/x-directory")
260                         w.WriteHeader(http.StatusOK)
261                         return true
262                 }
263                 if os.IsNotExist(err) ||
264                         (err != nil && err.Error() == "not a directory") ||
265                         (fi != nil && fi.IsDir()) {
266                         s3ErrorResponse(w, NoSuchKey, "The specified key does not exist.", r.URL.Path, http.StatusNotFound)
267                         return true
268                 }
269                 // shallow copy r, and change URL path
270                 r := *r
271                 r.URL.Path = fspath
272                 http.FileServer(fs).ServeHTTP(w, &r)
273                 return true
274         case r.Method == http.MethodPut:
275                 if !objectNameGiven {
276                         s3ErrorResponse(w, InvalidArgument, "Missing object name in PUT request.", r.URL.Path, http.StatusBadRequest)
277                         return true
278                 }
279                 fspath := "by_id" + r.URL.Path
280                 var objectIsDir bool
281                 if strings.HasSuffix(fspath, "/") {
282                         if !h.Config.cluster.Collections.S3FolderObjects {
283                                 s3ErrorResponse(w, InvalidArgument, "invalid object name: trailing slash", r.URL.Path, http.StatusBadRequest)
284                                 return true
285                         }
286                         n, err := r.Body.Read(make([]byte, 1))
287                         if err != nil && err != io.EOF {
288                                 s3ErrorResponse(w, InternalError, fmt.Sprintf("error reading request body: %s", err), r.URL.Path, http.StatusInternalServerError)
289                                 return true
290                         } else if n > 0 {
291                                 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless content is empty", r.URL.Path, http.StatusBadRequest)
292                                 return true
293                         } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
294                                 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", r.URL.Path, http.StatusBadRequest)
295                                 return true
296                         }
297                         // Given PUT "foo/bar/", we'll use "foo/bar/."
298                         // in the "ensure parents exist" block below,
299                         // and then we'll be done.
300                         fspath += "."
301                         objectIsDir = true
302                 }
303                 fi, err := fs.Stat(fspath)
304                 if err != nil && err.Error() == "not a directory" {
305                         // requested foo/bar, but foo is a file
306                         s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
307                         return true
308                 }
309                 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
310                         // requested foo/bar/, but foo/bar is a file
311                         s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
312                         return true
313                 }
314                 // create missing parent/intermediate directories, if any
315                 for i, c := range fspath {
316                         if i > 0 && c == '/' {
317                                 dir := fspath[:i]
318                                 if strings.HasSuffix(dir, "/") {
319                                         err = errors.New("invalid object name (consecutive '/' chars)")
320                                         s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
321                                         return true
322                                 }
323                                 err = fs.Mkdir(dir, 0755)
324                                 if err == arvados.ErrInvalidArgument {
325                                         // Cannot create a directory
326                                         // here.
327                                         err = fmt.Errorf("mkdir %q failed: %w", dir, err)
328                                         s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
329                                         return true
330                                 } else if err != nil && !os.IsExist(err) {
331                                         err = fmt.Errorf("mkdir %q failed: %w", dir, err)
332                                         s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
333                                         return true
334                                 }
335                         }
336                 }
337                 if !objectIsDir {
338                         f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
339                         if os.IsNotExist(err) {
340                                 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
341                         }
342                         if err != nil {
343                                 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
344                                 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
345                                 return true
346                         }
347                         defer f.Close()
348                         _, err = io.Copy(f, r.Body)
349                         if err != nil {
350                                 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
351                                 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
352                                 return true
353                         }
354                         err = f.Close()
355                         if err != nil {
356                                 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
357                                 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
358                                 return true
359                         }
360                 }
361                 err = fs.Sync()
362                 if err != nil {
363                         err = fmt.Errorf("sync failed: %w", err)
364                         s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
365                         return true
366                 }
367                 w.WriteHeader(http.StatusOK)
368                 return true
369         case r.Method == http.MethodDelete:
370                 if !objectNameGiven || r.URL.Path == "/" {
371                         s3ErrorResponse(w, InvalidArgument, "missing object name in DELETE request", r.URL.Path, http.StatusBadRequest)
372                         return true
373                 }
374                 fspath := "by_id" + r.URL.Path
375                 if strings.HasSuffix(fspath, "/") {
376                         fspath = strings.TrimSuffix(fspath, "/")
377                         fi, err := fs.Stat(fspath)
378                         if os.IsNotExist(err) {
379                                 w.WriteHeader(http.StatusNoContent)
380                                 return true
381                         } else if err != nil {
382                                 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
383                                 return true
384                         } else if !fi.IsDir() {
385                                 // if "foo" exists and is a file, then
386                                 // "foo/" doesn't exist, so we say
387                                 // delete was successful.
388                                 w.WriteHeader(http.StatusNoContent)
389                                 return true
390                         }
391                 } else if fi, err := fs.Stat(fspath); err == nil && fi.IsDir() {
392                         // if "foo" is a dir, it is visible via S3
393                         // only as "foo/", not "foo" -- so we leave
394                         // the dir alone and return 204 to indicate
395                         // that "foo" does not exist.
396                         w.WriteHeader(http.StatusNoContent)
397                         return true
398                 }
399                 err = fs.Remove(fspath)
400                 if os.IsNotExist(err) {
401                         w.WriteHeader(http.StatusNoContent)
402                         return true
403                 }
404                 if err != nil {
405                         err = fmt.Errorf("rm failed: %w", err)
406                         s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
407                         return true
408                 }
409                 err = fs.Sync()
410                 if err != nil {
411                         err = fmt.Errorf("sync failed: %w", err)
412                         s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
413                         return true
414                 }
415                 w.WriteHeader(http.StatusNoContent)
416                 return true
417         default:
418                 s3ErrorResponse(w, InvalidRequest, "method not allowed", r.URL.Path, http.StatusMethodNotAllowed)
419
420                 return true
421         }
422 }
423
424 // Call fn on the given path (directory) and its contents, in
425 // lexicographic order.
426 //
427 // If isRoot==true and path is not a directory, return nil.
428 //
429 // If fn returns filepath.SkipDir when called on a directory, don't
430 // descend into that directory.
431 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
432         if isRoot {
433                 fi, err := fs.Stat(path)
434                 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
435                         return nil
436                 } else if err != nil {
437                         return err
438                 }
439                 err = fn(path, fi)
440                 if err == filepath.SkipDir {
441                         return nil
442                 } else if err != nil {
443                         return err
444                 }
445         }
446         f, err := fs.Open(path)
447         if os.IsNotExist(err) && isRoot {
448                 return nil
449         } else if err != nil {
450                 return fmt.Errorf("open %q: %w", path, err)
451         }
452         defer f.Close()
453         if path == "/" {
454                 path = ""
455         }
456         fis, err := f.Readdir(-1)
457         if err != nil {
458                 return err
459         }
460         sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
461         for _, fi := range fis {
462                 err = fn(path+"/"+fi.Name(), fi)
463                 if err == filepath.SkipDir {
464                         continue
465                 } else if err != nil {
466                         return err
467                 }
468                 if fi.IsDir() {
469                         err = walkFS(fs, path+"/"+fi.Name(), false, fn)
470                         if err != nil {
471                                 return err
472                         }
473                 }
474         }
475         return nil
476 }
477
478 var errDone = errors.New("done")
479
480 func (h *handler) s3list(w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
481         var params struct {
482                 bucket    string
483                 delimiter string
484                 marker    string
485                 maxKeys   int
486                 prefix    string
487         }
488         params.bucket = strings.SplitN(r.URL.Path[1:], "/", 2)[0]
489         params.delimiter = r.FormValue("delimiter")
490         params.marker = r.FormValue("marker")
491         if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
492                 params.maxKeys = int(mk)
493         } else {
494                 params.maxKeys = s3MaxKeys
495         }
496         params.prefix = r.FormValue("prefix")
497
498         bucketdir := "by_id/" + params.bucket
499         // walkpath is the directory (relative to bucketdir) we need
500         // to walk: the innermost directory that is guaranteed to
501         // contain all paths that have the requested prefix. Examples:
502         // prefix "foo/bar"  => walkpath "foo"
503         // prefix "foo/bar/" => walkpath "foo/bar"
504         // prefix "foo"      => walkpath ""
505         // prefix ""         => walkpath ""
506         walkpath := params.prefix
507         if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
508                 walkpath = walkpath[:cut]
509         } else {
510                 walkpath = ""
511         }
512
513         type commonPrefix struct {
514                 Prefix string
515         }
516         type listResp struct {
517                 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
518                 s3.ListResp
519                 // s3.ListResp marshals an empty tag when
520                 // CommonPrefixes is nil, which confuses some clients.
521                 // Fix by using this nested struct instead.
522                 CommonPrefixes []commonPrefix
523                 // Similarly, we need omitempty here, because an empty
524                 // tag confuses some clients (e.g.,
525                 // github.com/aws/aws-sdk-net never terminates its
526                 // paging loop).
527                 NextMarker string `xml:"NextMarker,omitempty"`
528                 // ListObjectsV2 has a KeyCount response field.
529                 KeyCount int
530         }
531         resp := listResp{
532                 ListResp: s3.ListResp{
533                         Name:      strings.SplitN(r.URL.Path[1:], "/", 2)[0],
534                         Prefix:    params.prefix,
535                         Delimiter: params.delimiter,
536                         Marker:    params.marker,
537                         MaxKeys:   params.maxKeys,
538                 },
539         }
540         commonPrefixes := map[string]bool{}
541         err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
542                 if path == bucketdir {
543                         return nil
544                 }
545                 path = path[len(bucketdir)+1:]
546                 filesize := fi.Size()
547                 if fi.IsDir() {
548                         path += "/"
549                         filesize = 0
550                 }
551                 if len(path) <= len(params.prefix) {
552                         if path > params.prefix[:len(path)] {
553                                 // with prefix "foobar", walking "fooz" means we're done
554                                 return errDone
555                         }
556                         if path < params.prefix[:len(path)] {
557                                 // with prefix "foobar", walking "foobag" is pointless
558                                 return filepath.SkipDir
559                         }
560                         if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
561                                 // with prefix "foo/bar", walking "fo"
562                                 // is pointless (but walking "foo" or
563                                 // "foo/bar" is necessary)
564                                 return filepath.SkipDir
565                         }
566                         if len(path) < len(params.prefix) {
567                                 // can't skip anything, and this entry
568                                 // isn't in the results, so just
569                                 // continue descent
570                                 return nil
571                         }
572                 } else {
573                         if path[:len(params.prefix)] > params.prefix {
574                                 // with prefix "foobar", nothing we
575                                 // see after "foozzz" is relevant
576                                 return errDone
577                         }
578                 }
579                 if path < params.marker || path < params.prefix {
580                         return nil
581                 }
582                 if fi.IsDir() && !h.Config.cluster.Collections.S3FolderObjects {
583                         // Note we don't add anything to
584                         // commonPrefixes here even if delimiter is
585                         // "/". We descend into the directory, and
586                         // return a commonPrefix only if we end up
587                         // finding a regular file inside it.
588                         return nil
589                 }
590                 if params.delimiter != "" {
591                         idx := strings.Index(path[len(params.prefix):], params.delimiter)
592                         if idx >= 0 {
593                                 // with prefix "foobar" and delimiter
594                                 // "z", when we hit "foobar/baz", we
595                                 // add "/baz" to commonPrefixes and
596                                 // stop descending.
597                                 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
598                                 return filepath.SkipDir
599                         }
600                 }
601                 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
602                         resp.IsTruncated = true
603                         if params.delimiter != "" {
604                                 resp.NextMarker = path
605                         }
606                         return errDone
607                 }
608                 resp.Contents = append(resp.Contents, s3.Key{
609                         Key:          path,
610                         LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
611                         Size:         filesize,
612                 })
613                 return nil
614         })
615         if err != nil && err != errDone {
616                 http.Error(w, err.Error(), http.StatusInternalServerError)
617                 return
618         }
619         if params.delimiter != "" {
620                 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
621                 for prefix := range commonPrefixes {
622                         resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
623                 }
624                 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
625         }
626         resp.KeyCount = len(resp.Contents)
627         w.Header().Set("Content-Type", "application/xml")
628         io.WriteString(w, xml.Header)
629         if err := xml.NewEncoder(w).Encode(resp); err != nil {
630                 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")
631         }
632 }