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