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