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