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