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