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