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