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