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