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 err = setFileInfoHeaders(w.Header(), fs, fspath)
392 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
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)
399 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
403 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Cluster.Collections.S3FolderObjects {
404 err = setFileInfoHeaders(w.Header(), fs, fspath)
406 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
409 w.Header().Set("Content-Type", "application/x-directory")
410 w.WriteHeader(http.StatusOK)
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)
420 tokenUser, err := h.Cache.GetTokenUser(token)
421 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
422 http.Error(w, "Not permitted", http.StatusForbidden)
425 h.logUploadOrDownload(r, arvclient, fs, fspath, nil, tokenUser)
427 // shallow copy r, and change URL path
430 err = setFileInfoHeaders(w.Header(), fs, fspath)
432 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
435 http.FileServer(fs).ServeHTTP(w, &r)
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)
443 if !objectNameGiven {
444 s3ErrorResponse(w, InvalidArgument, "Missing object name in PUT request.", r.URL.Path, http.StatusBadRequest)
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)
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)
458 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless content is empty", r.URL.Path, http.StatusBadRequest)
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)
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.
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)
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)
481 // create missing parent/intermediate directories, if any
482 for i, c := range fspath {
483 if i > 0 && c == '/' {
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)
490 err = fs.Mkdir(dir, 0755)
491 if errors.Is(err, arvados.ErrInvalidArgument) || errors.Is(err, arvados.ErrInvalidOperation) {
492 // Cannot create a directory
494 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
495 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
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)
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)
510 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
511 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
516 tokenUser, err := h.Cache.GetTokenUser(token)
517 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
518 http.Error(w, "Not permitted", http.StatusForbidden)
521 h.logUploadOrDownload(r, arvclient, fs, fspath, nil, tokenUser)
523 _, err = io.Copy(f, r.Body)
525 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
526 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
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)
538 err = fmt.Errorf("sync failed: %w", err)
539 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
542 // Ensure a subsequent read operation will see the changes.
543 h.Cache.ResetSession(token)
544 w.WriteHeader(http.StatusOK)
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)
552 if !objectNameGiven || r.URL.Path == "/" {
553 s3ErrorResponse(w, InvalidArgument, "missing object name in DELETE request", r.URL.Path, http.StatusBadRequest)
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)
562 } else if err != nil {
563 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
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)
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)
580 err = fs.Remove(fspath)
581 if os.IsNotExist(err) {
582 w.WriteHeader(http.StatusNoContent)
586 err = fmt.Errorf("rm failed: %w", err)
587 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
592 err = fmt.Errorf("sync failed: %w", err)
593 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
596 // Ensure a subsequent read operation will see the changes.
597 h.Cache.ResetSession(token)
598 w.WriteHeader(http.StatusNoContent)
601 s3ErrorResponse(w, InvalidRequest, "method not allowed", r.URL.Path, http.StatusMethodNotAllowed)
606 func setFileInfoHeaders(header http.Header, fs arvados.CustomFileSystem, path string) error {
607 path = strings.TrimSuffix(path, "/")
608 var props map[string]interface{}
610 fi, err := fs.Stat(path)
614 switch src := fi.Sys().(type) {
615 case *arvados.Collection:
616 props = src.Properties
618 props = src.Properties
620 if err, ok := src.(error); ok {
624 cut := strings.LastIndexByte(path, '/')
633 for k, v := range props {
634 if !validMIMEHeaderKey(k) {
637 k = "x-amz-meta-" + k
638 if s, ok := v.(string); ok {
640 } else if j, err := json.Marshal(v); err == nil {
641 header.Set(k, string(j))
647 func validMIMEHeaderKey(k string) bool {
649 return check != textproto.CanonicalMIMEHeaderKey(check)
652 // Call fn on the given path (directory) and its contents, in
653 // lexicographic order.
655 // If isRoot==true and path is not a directory, return nil.
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 {
661 fi, err := fs.Stat(path)
662 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
664 } else if err != nil {
668 if err == filepath.SkipDir {
670 } else if err != nil {
674 f, err := fs.Open(path)
675 if os.IsNotExist(err) && isRoot {
677 } else if err != nil {
678 return fmt.Errorf("open %q: %w", path, err)
684 fis, err := f.Readdir(-1)
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 {
693 } else if err != nil {
697 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
706 var errDone = errors.New("done")
708 func (h *handler) s3list(bucket string, w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
714 marker string // decoded continuationToken (v2) or provided by client (v1)
715 startAfter string // v2
716 continuationToken string // v2
717 encodingTypeURL bool // v2
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)
723 params.maxKeys = s3MaxKeys
725 params.prefix = r.FormValue("prefix")
726 switch r.FormValue("list-type") {
731 http.Error(w, "invalid list-type parameter", http.StatusBadRequest)
735 params.continuationToken = r.FormValue("continuation-token")
736 marker, err := base64.StdEncoding.DecodeString(params.continuationToken)
738 http.Error(w, "invalid continuation token", http.StatusBadRequest)
741 params.marker = string(marker)
742 params.startAfter = r.FormValue("start-after")
743 switch r.FormValue("encoding-type") {
746 params.encodingTypeURL = true
748 http.Error(w, "invalid encoding-type parameter", http.StatusBadRequest)
752 params.marker = r.FormValue("marker")
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]
772 Prefix: params.prefix,
773 Delimiter: params.delimiter,
774 MaxKeys: params.maxKeys,
775 ContinuationToken: r.FormValue("continuation-token"),
776 StartAfter: params.startAfter,
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 {
785 path = path[len(bucketdir)+1:]
786 filesize := fi.Size()
791 if len(path) <= len(params.prefix) {
792 if path > params.prefix[:len(path)] {
793 // with prefix "foobar", walking "fooz" means we're done
796 if path < params.prefix[:len(path)] {
797 // with prefix "foobar", walking "foobag" is pointless
798 return filepath.SkipDir
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
806 if len(path) < len(params.prefix) {
807 // can't skip anything, and this entry
808 // isn't in the results, so just
813 if path[:len(params.prefix)] > params.prefix {
814 // with prefix "foobar", nothing we
815 // see after "foozzz" is relevant
819 if path < params.marker || path < params.prefix || path <= params.startAfter {
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.
830 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
831 resp.IsTruncated = true
832 if params.delimiter != "" || params.v2 {
837 if params.delimiter != "" {
838 idx := strings.Index(path[len(params.prefix):], params.delimiter)
840 // with prefix "foobar" and delimiter
841 // "z", when we hit "foobar/baz", we
842 // add "/baz" to commonPrefixes and
844 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
845 return filepath.SkipDir
848 resp.Contents = append(resp.Contents, s3.Key{
850 LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
855 if err != nil && err != errDone {
856 http.Error(w, err.Error(), http.StatusInternalServerError)
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})
864 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
866 resp.KeyCount = len(resp.Contents)
867 var respV1orV2 interface{}
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:
876 // Delimiter, Prefix, Key, and StartAfter.
880 // Valid Values: url"
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
898 for i, ent := range resp.CommonPrefixes {
899 ent.Prefix = url.QueryEscape(ent.Prefix)
900 resp.CommonPrefixes[i] = ent
905 resp.NextContinuationToken = base64.StdEncoding.EncodeToString([]byte(nextMarker))
908 respV1orV2 = listV1Resp{
909 CommonPrefixes: resp.CommonPrefixes,
910 NextMarker: nextMarker,
911 KeyCount: resp.KeyCount,
912 ListResp: s3.ListResp{
913 IsTruncated: resp.IsTruncated,
915 Prefix: params.prefix,
916 Delimiter: params.delimiter,
917 Marker: params.marker,
918 MaxKeys: params.maxKeys,
919 Contents: resp.Contents,
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")