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