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