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