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