1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
37 s3SignAlgorithm = "AWS4-HMAC-SHA256"
38 s3MaxClockSkew = 5 * time.Minute
41 type commonPrefix struct {
45 type listV1Resp struct {
46 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
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
56 NextMarker string `xml:"NextMarker,omitempty"`
57 // ListObjectsV2 has a KeyCount response field.
61 type listV2Resp struct {
62 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
69 CommonPrefixes []commonPrefix
70 EncodingType string `xml:",omitempty"`
72 ContinuationToken string `xml:",omitempty"`
73 NextContinuationToken string `xml:",omitempty"`
74 StartAfter string `xml:",omitempty"`
77 func hmacstring(msg string, key []byte) []byte {
78 h := hmac.New(sha256.New, key)
79 io.WriteString(h, msg)
83 func hashdigest(h hash.Hash, payload string) string {
84 io.WriteString(h, payload)
85 return fmt.Sprintf("%x", h.Sum(nil))
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)))))
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)
109 values[k] += k + "=" + v
113 for i, k := range keys {
116 return strings.Join(keys, "&")
119 var reMultipleSlashChars = regexp.MustCompile(`//+`)
121 func s3stringToSign(alg, scope, signedHeaders string, r *http.Request) (string, error) {
122 timefmt, timestr := "20060102T150405Z", r.Header.Get("X-Amz-Date")
124 timefmt, timestr = time.RFC1123, r.Header.Get("Date")
126 t, err := time.Parse(timefmt, timestr)
128 return "", fmt.Errorf("invalid timestamp %q: %s", timestr, err)
130 if skew := time.Now().Sub(t); skew < -s3MaxClockSkew || skew > s3MaxClockSkew {
131 return "", errors.New("exceeded max clock skew")
134 var canonicalHeaders string
135 for _, h := range strings.Split(signedHeaders, ";") {
137 canonicalHeaders += h + ":" + r.Host + "\n"
139 canonicalHeaders += h + ":" + r.Header.Get(h) + "\n"
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
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.
159 for _, c := range []byte(reMultipleSlashChars.ReplaceAllString(s, "/")) {
160 if (c >= 'a' && c <= 'z') ||
161 (c >= 'A' && c <= 'Z') ||
162 (c >= '0' && c <= '9') ||
170 out += fmt.Sprintf("%%%02X", c)
176 func s3signature(secretKey, scope, signedHeaders, stringToSign string) (string, error) {
177 // scope is {datestamp}/{region}/{service}/aws4_request
178 drs := strings.Split(scope, "/")
180 return "", fmt.Errorf("invalid scope %q", scope)
182 key := s3signatureKey(secretKey, drs[0], drs[1], drs[2])
183 return hashdigest(hmac.New(sha256.New, key), stringToSign), nil
186 var v2tokenUnderscore = regexp.MustCompile(`^v2_[a-z0-9]{5}-gj3su-[a-z0-9]{15}_`)
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
193 return strings.Replace(key, "_", "/", -1)
194 } else if s, err := url.PathUnescape(key); err == nil {
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
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)
212 case len(split) != 2:
214 case split[0] == "Credential":
215 keyandscope := strings.SplitN(split[1], "/", 2)
216 if len(keyandscope) == 2 {
217 key, scope = keyandscope[0], keyandscope[1]
219 case split[0] == "SignedHeaders":
220 signedHeaders = split[1]
221 case split[0] == "Signature":
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
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
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)
247 ctxlog.FromContext(r.Context()).WithError(err).WithField("UUID", key).Info("token lookup failed")
248 return "", errors.New("invalid access key")
250 stringToSign, err := s3stringToSign(s3SignAlgorithm, scope, signedHeaders, r)
254 expect, err := s3signature(secret, scope, signedHeaders, stringToSign)
257 } else if expect != signature {
258 return "", fmt.Errorf("signature does not match (scope %q signedHeaders %q stringToSign %q)", scope, signedHeaders, stringToSign)
260 return aca.TokenV2(), nil
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")
267 var errstruct struct {
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"}})
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"
290 var reRawQueryIndicatesAPI = regexp.MustCompile(`^[a-z]+(&|$)`)
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 {
296 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
297 split := strings.SplitN(auth[4:], ":", 2)
299 s3ErrorResponse(w, InvalidRequest, "malformed Authorization header", r.URL.Path, http.StatusUnauthorized)
302 token = unescapeKey(split[0])
303 } else if strings.HasPrefix(auth, s3SignAlgorithm+" ") {
304 t, err := h.checks3signature(r)
306 s3ErrorResponse(w, SignatureDoesNotMatch, "signature verification failed: "+err.Error(), r.URL.Path, http.StatusForbidden)
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)
323 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
326 arvclient = sess.arvadosclient
328 // Create a FileSystem for this request, to avoid
329 // exposing incomplete write operations to concurrent
331 var kc *keepclient.KeepClient
333 var client *arvados.Client
334 arvclient, kc, client, release, err = h.getClients(r.Header.Get("X-Request-Id"), token)
336 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
340 fs = client.SiteFileSystem(kc)
341 fs.ForwardSlashNameSubstitution(h.Cluster.Collections.ForwardSlashNameSubstitution)
344 var objectNameGiven bool
345 var bucketName string
347 if id := arvados.CollectionIDFromDNSName(r.Host); id != "" {
350 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 0
352 bucketName = strings.SplitN(strings.TrimPrefix(r.URL.Path, "/"), "/", 2)[0]
353 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
355 fspath += reMultipleSlashChars.ReplaceAllString(r.URL.Path, "/")
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 {
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/">`+
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)
377 h.s3list(bucketName, w, r, fs)
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)
386 fi, err := fs.Stat(fspath)
387 if r.Method == "HEAD" && !objectNameGiven {
389 if err == nil && fi.IsDir() {
390 setFileInfoHeaders(w.Header(), fs, fspath)
391 w.WriteHeader(http.StatusOK)
392 } else if os.IsNotExist(err) {
393 s3ErrorResponse(w, NoSuchBucket, "The specified bucket does not exist.", r.URL.Path, http.StatusNotFound)
395 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
399 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Cluster.Collections.S3FolderObjects {
400 setFileInfoHeaders(w.Header(), fs, fspath)
401 w.Header().Set("Content-Type", "application/x-directory")
402 w.WriteHeader(http.StatusOK)
405 if os.IsNotExist(err) ||
406 (err != nil && err.Error() == "not a directory") ||
407 (fi != nil && fi.IsDir()) {
408 s3ErrorResponse(w, NoSuchKey, "The specified key does not exist.", r.URL.Path, http.StatusNotFound)
412 tokenUser, err := h.Cache.GetTokenUser(token)
413 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
414 http.Error(w, "Not permitted", http.StatusForbidden)
417 h.logUploadOrDownload(r, arvclient, fs, fspath, nil, tokenUser)
419 // shallow copy r, and change URL path
422 setFileInfoHeaders(w.Header(), fs, fspath)
423 http.FileServer(fs).ServeHTTP(w, &r)
425 case r.Method == http.MethodPut:
426 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
427 // PutObjectAcl ("PUT /bucketid/objectid?acl&versionID=..."), etc.
428 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
431 if !objectNameGiven {
432 s3ErrorResponse(w, InvalidArgument, "Missing object name in PUT request.", r.URL.Path, http.StatusBadRequest)
436 if strings.HasSuffix(fspath, "/") {
437 if !h.Cluster.Collections.S3FolderObjects {
438 s3ErrorResponse(w, InvalidArgument, "invalid object name: trailing slash", r.URL.Path, http.StatusBadRequest)
441 n, err := r.Body.Read(make([]byte, 1))
442 if err != nil && err != io.EOF {
443 s3ErrorResponse(w, InternalError, fmt.Sprintf("error reading request body: %s", err), r.URL.Path, http.StatusInternalServerError)
446 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless content is empty", r.URL.Path, http.StatusBadRequest)
448 } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
449 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", r.URL.Path, http.StatusBadRequest)
452 // Given PUT "foo/bar/", we'll use "foo/bar/."
453 // in the "ensure parents exist" block below,
454 // and then we'll be done.
458 fi, err := fs.Stat(fspath)
459 if err != nil && err.Error() == "not a directory" {
460 // requested foo/bar, but foo is a file
461 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
464 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
465 // requested foo/bar/, but foo/bar is a file
466 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
469 // create missing parent/intermediate directories, if any
470 for i, c := range fspath {
471 if i > 0 && c == '/' {
473 if strings.HasSuffix(dir, "/") {
474 err = errors.New("invalid object name (consecutive '/' chars)")
475 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
478 err = fs.Mkdir(dir, 0755)
479 if errors.Is(err, arvados.ErrInvalidArgument) || errors.Is(err, arvados.ErrInvalidOperation) {
480 // Cannot create a directory
482 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
483 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
485 } else if err != nil && !os.IsExist(err) {
486 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
487 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
493 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
494 if os.IsNotExist(err) {
495 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
498 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
499 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
504 tokenUser, err := h.Cache.GetTokenUser(token)
505 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
506 http.Error(w, "Not permitted", http.StatusForbidden)
509 h.logUploadOrDownload(r, arvclient, fs, fspath, nil, tokenUser)
511 _, err = io.Copy(f, r.Body)
513 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
514 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
519 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
520 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
526 err = fmt.Errorf("sync failed: %w", err)
527 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
530 // Ensure a subsequent read operation will see the changes.
531 h.Cache.ResetSession(token)
532 w.WriteHeader(http.StatusOK)
534 case r.Method == http.MethodDelete:
535 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
536 // DeleteObjectTagging ("DELETE /bucketid/objectid?tagging&versionID=..."), etc.
537 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
540 if !objectNameGiven || r.URL.Path == "/" {
541 s3ErrorResponse(w, InvalidArgument, "missing object name in DELETE request", r.URL.Path, http.StatusBadRequest)
544 if strings.HasSuffix(fspath, "/") {
545 fspath = strings.TrimSuffix(fspath, "/")
546 fi, err := fs.Stat(fspath)
547 if os.IsNotExist(err) {
548 w.WriteHeader(http.StatusNoContent)
550 } else if err != nil {
551 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
553 } else if !fi.IsDir() {
554 // if "foo" exists and is a file, then
555 // "foo/" doesn't exist, so we say
556 // delete was successful.
557 w.WriteHeader(http.StatusNoContent)
560 } else if fi, err := fs.Stat(fspath); err == nil && fi.IsDir() {
561 // if "foo" is a dir, it is visible via S3
562 // only as "foo/", not "foo" -- so we leave
563 // the dir alone and return 204 to indicate
564 // that "foo" does not exist.
565 w.WriteHeader(http.StatusNoContent)
568 err = fs.Remove(fspath)
569 if os.IsNotExist(err) {
570 w.WriteHeader(http.StatusNoContent)
574 err = fmt.Errorf("rm failed: %w", err)
575 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
580 err = fmt.Errorf("sync failed: %w", err)
581 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
584 // Ensure a subsequent read operation will see the changes.
585 h.Cache.ResetSession(token)
586 w.WriteHeader(http.StatusNoContent)
589 s3ErrorResponse(w, InvalidRequest, "method not allowed", r.URL.Path, http.StatusMethodNotAllowed)
594 func setFileInfoHeaders(header http.Header, fs arvados.CustomFileSystem, path string) {
595 path = strings.TrimSuffix(path, "/")
596 var props map[string]interface{}
598 fi, err := fs.Stat(path)
602 switch src := fi.Sys().(type) {
603 case *arvados.Collection:
604 props = src.Properties
606 props = src.Properties
609 cut := strings.LastIndexByte(path, '/')
618 for k, v := range props {
619 if !validMIMEHeaderKey(k) {
622 k = "x-amz-meta-" + k
623 if s, ok := v.(string); ok {
625 } else if j, err := json.Marshal(v); err == nil {
626 header.Set(k, string(j))
631 func validMIMEHeaderKey(k string) bool {
633 return check != textproto.CanonicalMIMEHeaderKey(check)
636 // Call fn on the given path (directory) and its contents, in
637 // lexicographic order.
639 // If isRoot==true and path is not a directory, return nil.
641 // If fn returns filepath.SkipDir when called on a directory, don't
642 // descend into that directory.
643 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
645 fi, err := fs.Stat(path)
646 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
648 } else if err != nil {
652 if err == filepath.SkipDir {
654 } else if err != nil {
658 f, err := fs.Open(path)
659 if os.IsNotExist(err) && isRoot {
661 } else if err != nil {
662 return fmt.Errorf("open %q: %w", path, err)
668 fis, err := f.Readdir(-1)
672 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
673 for _, fi := range fis {
674 err = fn(path+"/"+fi.Name(), fi)
675 if err == filepath.SkipDir {
677 } else if err != nil {
681 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
690 var errDone = errors.New("done")
692 func (h *handler) s3list(bucket string, w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
698 marker string // decoded continuationToken (v2) or provided by client (v1)
699 startAfter string // v2
700 continuationToken string // v2
701 encodingTypeURL bool // v2
703 params.delimiter = r.FormValue("delimiter")
704 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
705 params.maxKeys = int(mk)
707 params.maxKeys = s3MaxKeys
709 params.prefix = r.FormValue("prefix")
710 switch r.FormValue("list-type") {
715 http.Error(w, "invalid list-type parameter", http.StatusBadRequest)
719 params.continuationToken = r.FormValue("continuation-token")
720 marker, err := base64.StdEncoding.DecodeString(params.continuationToken)
722 http.Error(w, "invalid continuation token", http.StatusBadRequest)
725 params.marker = string(marker)
726 params.startAfter = r.FormValue("start-after")
727 switch r.FormValue("encoding-type") {
730 params.encodingTypeURL = true
732 http.Error(w, "invalid encoding-type parameter", http.StatusBadRequest)
736 params.marker = r.FormValue("marker")
739 bucketdir := "by_id/" + bucket
740 // walkpath is the directory (relative to bucketdir) we need
741 // to walk: the innermost directory that is guaranteed to
742 // contain all paths that have the requested prefix. Examples:
743 // prefix "foo/bar" => walkpath "foo"
744 // prefix "foo/bar/" => walkpath "foo/bar"
745 // prefix "foo" => walkpath ""
746 // prefix "" => walkpath ""
747 walkpath := params.prefix
748 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
749 walkpath = walkpath[:cut]
756 Prefix: params.prefix,
757 Delimiter: params.delimiter,
758 MaxKeys: params.maxKeys,
759 ContinuationToken: r.FormValue("continuation-token"),
760 StartAfter: params.startAfter,
764 commonPrefixes := map[string]bool{}
765 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
766 if path == bucketdir {
769 path = path[len(bucketdir)+1:]
770 filesize := fi.Size()
775 if len(path) <= len(params.prefix) {
776 if path > params.prefix[:len(path)] {
777 // with prefix "foobar", walking "fooz" means we're done
780 if path < params.prefix[:len(path)] {
781 // with prefix "foobar", walking "foobag" is pointless
782 return filepath.SkipDir
784 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
785 // with prefix "foo/bar", walking "fo"
786 // is pointless (but walking "foo" or
787 // "foo/bar" is necessary)
788 return filepath.SkipDir
790 if len(path) < len(params.prefix) {
791 // can't skip anything, and this entry
792 // isn't in the results, so just
797 if path[:len(params.prefix)] > params.prefix {
798 // with prefix "foobar", nothing we
799 // see after "foozzz" is relevant
803 if path < params.marker || path < params.prefix || path <= params.startAfter {
806 if fi.IsDir() && !h.Cluster.Collections.S3FolderObjects {
807 // Note we don't add anything to
808 // commonPrefixes here even if delimiter is
809 // "/". We descend into the directory, and
810 // return a commonPrefix only if we end up
811 // finding a regular file inside it.
814 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
815 resp.IsTruncated = true
816 if params.delimiter != "" || params.v2 {
821 if params.delimiter != "" {
822 idx := strings.Index(path[len(params.prefix):], params.delimiter)
824 // with prefix "foobar" and delimiter
825 // "z", when we hit "foobar/baz", we
826 // add "/baz" to commonPrefixes and
828 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
829 return filepath.SkipDir
832 resp.Contents = append(resp.Contents, s3.Key{
834 LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
839 if err != nil && err != errDone {
840 http.Error(w, err.Error(), http.StatusInternalServerError)
843 if params.delimiter != "" {
844 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
845 for prefix := range commonPrefixes {
846 resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
848 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
850 resp.KeyCount = len(resp.Contents)
851 var respV1orV2 interface{}
853 if params.encodingTypeURL {
854 // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
855 // "If you specify the encoding-type request
856 // parameter, Amazon S3 includes this element in the
857 // response, and returns encoded key name values in
858 // the following response elements:
860 // Delimiter, Prefix, Key, and StartAfter.
864 // Valid Values: url"
866 // This is somewhat vague but in practice it appears
867 // to mean x-www-form-urlencoded as in RFC1866 8.2.1
868 // para 1 (encode space as "+") rather than straight
869 // percent-encoding as in RFC1738 2.2. Presumably,
870 // the intent is to allow the client to decode XML and
871 // then paste the strings directly into another URI
872 // query or POST form like "https://host/path?foo=" +
873 // foo + "&bar=" + bar.
874 resp.EncodingType = "url"
875 resp.Delimiter = url.QueryEscape(resp.Delimiter)
876 resp.Prefix = url.QueryEscape(resp.Prefix)
877 resp.StartAfter = url.QueryEscape(resp.StartAfter)
878 for i, ent := range resp.Contents {
879 ent.Key = url.QueryEscape(ent.Key)
880 resp.Contents[i] = ent
882 for i, ent := range resp.CommonPrefixes {
883 ent.Prefix = url.QueryEscape(ent.Prefix)
884 resp.CommonPrefixes[i] = ent
889 resp.NextContinuationToken = base64.StdEncoding.EncodeToString([]byte(nextMarker))
892 respV1orV2 = listV1Resp{
893 CommonPrefixes: resp.CommonPrefixes,
894 NextMarker: nextMarker,
895 KeyCount: resp.KeyCount,
896 ListResp: s3.ListResp{
897 IsTruncated: resp.IsTruncated,
899 Prefix: params.prefix,
900 Delimiter: params.delimiter,
901 Marker: params.marker,
902 MaxKeys: params.maxKeys,
903 Contents: resp.Contents,
908 w.Header().Set("Content-Type", "application/xml")
909 io.WriteString(w, xml.Header)
910 if err := xml.NewEncoder(w).Encode(respV1orV2); err != nil {
911 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")