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