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