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