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