1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
29 "git.arvados.org/arvados.git/sdk/go/arvados"
30 "git.arvados.org/arvados.git/sdk/go/ctxlog"
35 s3SignAlgorithm = "AWS4-HMAC-SHA256"
36 s3MaxClockSkew = 5 * time.Minute
39 type commonPrefix struct {
43 type listV1Resp struct {
44 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
52 // If we use a []string here, xml marshals an empty tag when
53 // CommonPrefixes is nil, which confuses some clients. Fix by
54 // using this nested struct instead.
55 CommonPrefixes []commonPrefix
56 // Similarly, we need omitempty here, because an empty
57 // tag confuses some clients (e.g.,
58 // github.com/aws/aws-sdk-net never terminates its
60 NextMarker string `xml:"NextMarker,omitempty"`
61 // ListObjectsV2 has a KeyCount response field.
65 type listV2Resp struct {
66 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
73 CommonPrefixes []commonPrefix
74 EncodingType string `xml:",omitempty"`
76 ContinuationToken string `xml:",omitempty"`
77 NextContinuationToken string `xml:",omitempty"`
78 StartAfter string `xml:",omitempty"`
85 // The following fields are not populated, but are here in
86 // case clients rely on the keys being present in xml
96 func hmacstring(msg string, key []byte) []byte {
97 h := hmac.New(sha256.New, key)
98 io.WriteString(h, msg)
102 func hashdigest(h hash.Hash, payload string) string {
103 io.WriteString(h, payload)
104 return fmt.Sprintf("%x", h.Sum(nil))
107 // Signing key for given secret key and request attrs.
108 func s3signatureKey(key, datestamp, regionName, serviceName string) []byte {
109 return hmacstring("aws4_request",
110 hmacstring(serviceName,
111 hmacstring(regionName,
112 hmacstring(datestamp, []byte("AWS4"+key)))))
115 // Canonical query string for S3 V4 signature: sorted keys, spaces
116 // escaped as %20 instead of +, keyvalues joined with &.
117 func s3querystring(u *url.URL) string {
118 keys := make([]string, 0, len(u.Query()))
119 values := make(map[string]string, len(u.Query()))
120 for k, vs := range u.Query() {
121 k = strings.Replace(url.QueryEscape(k), "+", "%20", -1)
122 keys = append(keys, k)
123 for _, v := range vs {
124 v = strings.Replace(url.QueryEscape(v), "+", "%20", -1)
128 values[k] += k + "=" + v
132 for i, k := range keys {
135 return strings.Join(keys, "&")
138 var reMultipleSlashChars = regexp.MustCompile(`//+`)
140 func s3stringToSign(alg, scope, signedHeaders string, r *http.Request) (string, error) {
141 timefmt, timestr := "20060102T150405Z", r.Header.Get("X-Amz-Date")
143 timefmt, timestr = time.RFC1123, r.Header.Get("Date")
145 t, err := time.Parse(timefmt, timestr)
147 return "", fmt.Errorf("invalid timestamp %q: %s", timestr, err)
149 if skew := time.Now().Sub(t); skew < -s3MaxClockSkew || skew > s3MaxClockSkew {
150 return "", errors.New("exceeded max clock skew")
153 var canonicalHeaders string
154 for _, h := range strings.Split(signedHeaders, ";") {
156 canonicalHeaders += h + ":" + r.Host + "\n"
158 canonicalHeaders += h + ":" + r.Header.Get(h) + "\n"
162 normalizedPath := normalizePath(r.URL.Path)
163 ctxlog.FromContext(r.Context()).Debugf("normalizedPath %q", normalizedPath)
164 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"))
165 ctxlog.FromContext(r.Context()).Debugf("s3stringToSign: canonicalRequest %s", canonicalRequest)
166 return fmt.Sprintf("%s\n%s\n%s\n%s", alg, r.Header.Get("X-Amz-Date"), scope, hashdigest(sha256.New(), canonicalRequest)), nil
169 func normalizePath(s string) string {
170 // (url.URL).EscapedPath() would be incorrect here. AWS
171 // documentation specifies the URL path should be normalized
172 // according to RFC 3986, i.e., unescaping ALPHA / DIGIT / "-"
173 // / "." / "_" / "~". The implication is that everything other
174 // than those chars (and "/") _must_ be percent-encoded --
175 // even chars like ";" and "," that are not normally
176 // percent-encoded in paths.
178 for _, c := range []byte(reMultipleSlashChars.ReplaceAllString(s, "/")) {
179 if (c >= 'a' && c <= 'z') ||
180 (c >= 'A' && c <= 'Z') ||
181 (c >= '0' && c <= '9') ||
189 out += fmt.Sprintf("%%%02X", c)
195 func s3signature(secretKey, scope, signedHeaders, stringToSign string) (string, error) {
196 // scope is {datestamp}/{region}/{service}/aws4_request
197 drs := strings.Split(scope, "/")
199 return "", fmt.Errorf("invalid scope %q", scope)
201 key := s3signatureKey(secretKey, drs[0], drs[1], drs[2])
202 return hashdigest(hmac.New(sha256.New, key), stringToSign), nil
205 var v2tokenUnderscore = regexp.MustCompile(`^v2_[a-z0-9]{5}-gj3su-[a-z0-9]{15}_`)
207 func unescapeKey(key string) string {
208 if v2tokenUnderscore.MatchString(key) {
209 // Entire Arvados token, with "/" replaced by "_" to
210 // avoid colliding with the Authorization header
212 return strings.Replace(key, "_", "/", -1)
213 } else if s, err := url.PathUnescape(key); err == nil {
220 // checks3signature verifies the given S3 V4 signature and returns the
221 // Arvados token that corresponds to the given accessKey. An error is
222 // returned if accessKey is not a valid token UUID or the signature
224 func (h *handler) checks3signature(r *http.Request) (string, error) {
225 var key, scope, signedHeaders, signature string
226 authstring := strings.TrimPrefix(r.Header.Get("Authorization"), s3SignAlgorithm+" ")
227 for _, cmpt := range strings.Split(authstring, ",") {
228 cmpt = strings.TrimSpace(cmpt)
229 split := strings.SplitN(cmpt, "=", 2)
231 case len(split) != 2:
233 case split[0] == "Credential":
234 keyandscope := strings.SplitN(split[1], "/", 2)
235 if len(keyandscope) == 2 {
236 key, scope = keyandscope[0], keyandscope[1]
238 case split[0] == "SignedHeaders":
239 signedHeaders = split[1]
240 case split[0] == "Signature":
245 client := (&arvados.Client{
246 APIHost: h.Cluster.Services.Controller.ExternalURL.Host,
247 Insecure: h.Cluster.TLS.Insecure,
248 }).WithRequestID(r.Header.Get("X-Request-Id"))
249 var aca arvados.APIClientAuthorization
252 if len(key) == 27 && key[5:12] == "-gj3su-" {
253 // Access key is the UUID of an Arvados token, secret
254 // key is the secret part.
255 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+h.Cluster.SystemRootToken)
256 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/"+key, nil, nil)
257 secret = aca.APIToken
259 // Access key and secret key are both an entire
260 // Arvados token or OIDC access token.
261 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+unescapeKey(key))
262 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/current", nil, nil)
266 ctxlog.FromContext(r.Context()).WithError(err).WithField("UUID", key).Info("token lookup failed")
267 return "", errors.New("invalid access key")
269 stringToSign, err := s3stringToSign(s3SignAlgorithm, scope, signedHeaders, r)
273 expect, err := s3signature(secret, scope, signedHeaders, stringToSign)
276 } else if expect != signature {
277 return "", fmt.Errorf("signature does not match (scope %q signedHeaders %q stringToSign %q)", scope, signedHeaders, stringToSign)
279 return aca.TokenV2(), nil
282 func s3ErrorResponse(w http.ResponseWriter, s3code string, message string, resource string, code int) {
283 w.Header().Set("Content-Type", "application/xml")
284 w.Header().Set("X-Content-Type-Options", "nosniff")
286 var errstruct struct {
292 errstruct.Code = s3code
293 errstruct.Message = message
294 errstruct.Resource = resource
295 errstruct.RequestId = ""
296 enc := xml.NewEncoder(w)
297 fmt.Fprint(w, xml.Header)
298 enc.EncodeElement(errstruct, xml.StartElement{Name: xml.Name{Local: "Error"}})
301 var NoSuchKey = "NoSuchKey"
302 var NoSuchBucket = "NoSuchBucket"
303 var InvalidArgument = "InvalidArgument"
304 var InternalError = "InternalError"
305 var UnauthorizedAccess = "UnauthorizedAccess"
306 var InvalidRequest = "InvalidRequest"
307 var SignatureDoesNotMatch = "SignatureDoesNotMatch"
309 var reRawQueryIndicatesAPI = regexp.MustCompile(`^[a-z]+(&|$)`)
311 // serveS3 handles r and returns true if r is a request from an S3
312 // client, otherwise it returns false.
313 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
315 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
316 split := strings.SplitN(auth[4:], ":", 2)
318 s3ErrorResponse(w, InvalidRequest, "malformed Authorization header", r.URL.Path, http.StatusUnauthorized)
321 token = unescapeKey(split[0])
322 } else if strings.HasPrefix(auth, s3SignAlgorithm+" ") {
323 t, err := h.checks3signature(r)
325 s3ErrorResponse(w, SignatureDoesNotMatch, "signature verification failed: "+err.Error(), r.URL.Path, http.StatusForbidden)
333 fs, sess, tokenUser, err := h.Cache.GetSession(token)
335 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
339 if writeMethod[r.Method] {
340 // Create a FileSystem for this request, to avoid
341 // exposing incomplete write operations to concurrent
343 client := sess.client.WithRequestID(r.Header.Get("X-Request-Id"))
344 fs = client.SiteFileSystem(sess.keepclient)
345 fs.ForwardSlashNameSubstitution(h.Cluster.Collections.ForwardSlashNameSubstitution)
348 var objectNameGiven bool
349 var bucketName string
351 if id := arvados.CollectionIDFromDNSName(r.Host); id != "" {
354 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 0
356 bucketName = strings.SplitN(strings.TrimPrefix(r.URL.Path, "/"), "/", 2)[0]
357 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
359 fspath += reMultipleSlashChars.ReplaceAllString(r.URL.Path, "/")
362 case r.Method == http.MethodGet && !objectNameGiven:
363 // Path is "/{uuid}" or "/{uuid}/", has no object name
364 if _, ok := r.URL.Query()["versioning"]; ok {
365 // GetBucketVersioning
366 w.Header().Set("Content-Type", "application/xml")
367 io.WriteString(w, xml.Header)
368 fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
369 } else if _, ok = r.URL.Query()["location"]; ok {
371 w.Header().Set("Content-Type", "application/xml")
372 io.WriteString(w, xml.Header)
373 fmt.Fprintln(w, `<LocationConstraint><LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/">`+
375 `</LocationConstraint></LocationConstraint>`)
376 } else if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
377 // GetBucketWebsite ("GET /bucketid/?website"), GetBucketTagging, etc.
378 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
381 h.s3list(bucketName, w, r, fs)
384 case r.Method == http.MethodGet || r.Method == http.MethodHead:
385 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
386 // GetObjectRetention ("GET /bucketid/objectid?retention&versionID=..."), etc.
387 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
390 fi, err := fs.Stat(fspath)
391 if r.Method == "HEAD" && !objectNameGiven {
393 if err == nil && fi.IsDir() {
394 err = setFileInfoHeaders(w.Header(), fs, fspath)
396 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
399 w.WriteHeader(http.StatusOK)
400 } else if os.IsNotExist(err) {
401 s3ErrorResponse(w, NoSuchBucket, "The specified bucket does not exist.", r.URL.Path, http.StatusNotFound)
403 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
407 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Cluster.Collections.S3FolderObjects {
408 err = setFileInfoHeaders(w.Header(), fs, fspath)
410 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
413 w.Header().Set("Content-Type", "application/x-directory")
414 w.WriteHeader(http.StatusOK)
417 if os.IsNotExist(err) ||
418 (err != nil && err.Error() == "not a directory") ||
419 (fi != nil && fi.IsDir()) {
420 s3ErrorResponse(w, NoSuchKey, "The specified key does not exist.", r.URL.Path, http.StatusNotFound)
424 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
425 http.Error(w, "Not permitted", http.StatusForbidden)
428 h.logUploadOrDownload(r, sess.arvadosclient, fs, fspath, nil, tokenUser)
430 // shallow copy r, and change URL path
433 err = setFileInfoHeaders(w.Header(), fs, fspath)
435 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
438 http.FileServer(fs).ServeHTTP(w, &r)
440 case r.Method == http.MethodPut:
441 if reRawQueryIndicatesAPI.MatchString(r.URL.RawQuery) {
442 // PutObjectAcl ("PUT /bucketid/objectid?acl&versionID=..."), etc.
443 s3ErrorResponse(w, InvalidRequest, "API not supported", r.URL.Path+"?"+r.URL.RawQuery, http.StatusBadRequest)
446 if !objectNameGiven {
447 s3ErrorResponse(w, InvalidArgument, "Missing object name in PUT request.", r.URL.Path, http.StatusBadRequest)
451 if strings.HasSuffix(fspath, "/") {
452 if !h.Cluster.Collections.S3FolderObjects {
453 s3ErrorResponse(w, InvalidArgument, "invalid object name: trailing slash", r.URL.Path, http.StatusBadRequest)
456 n, err := r.Body.Read(make([]byte, 1))
457 if err != nil && err != io.EOF {
458 s3ErrorResponse(w, InternalError, fmt.Sprintf("error reading request body: %s", err), r.URL.Path, http.StatusInternalServerError)
461 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless content is empty", r.URL.Path, http.StatusBadRequest)
463 } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
464 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", r.URL.Path, http.StatusBadRequest)
467 // Given PUT "foo/bar/", we'll use "foo/bar/."
468 // in the "ensure parents exist" block below,
469 // and then we'll be done.
473 fi, err := fs.Stat(fspath)
474 if err != nil && err.Error() == "not a directory" {
475 // requested foo/bar, but foo is a file
476 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
479 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
480 // requested foo/bar/, but foo/bar is a file
481 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
484 // create missing parent/intermediate directories, if any
485 for i, c := range fspath {
486 if i > 0 && c == '/' {
488 if strings.HasSuffix(dir, "/") {
489 err = errors.New("invalid object name (consecutive '/' chars)")
490 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
493 err = fs.Mkdir(dir, 0755)
494 if errors.Is(err, arvados.ErrInvalidArgument) || errors.Is(err, arvados.ErrInvalidOperation) {
495 // Cannot create a directory
497 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
498 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
500 } else if err != nil && !os.IsExist(err) {
501 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
502 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
508 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
509 if os.IsNotExist(err) {
510 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
513 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
514 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
519 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
520 http.Error(w, "Not permitted", http.StatusForbidden)
523 h.logUploadOrDownload(r, sess.arvadosclient, fs, fspath, nil, tokenUser)
525 _, err = io.Copy(f, r.Body)
527 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
528 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
533 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
534 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
538 err = h.syncCollection(fs, readfs, fspath)
540 err = fmt.Errorf("sync failed: %w", err)
541 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
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)
590 err = h.syncCollection(fs, readfs, fspath)
592 err = fmt.Errorf("sync failed: %w", err)
593 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
596 w.WriteHeader(http.StatusNoContent)
599 s3ErrorResponse(w, InvalidRequest, "method not allowed", r.URL.Path, http.StatusMethodNotAllowed)
604 // Save modifications to the indicated collection in srcfs, then (if
605 // successful) ensure they are also reflected in dstfs.
606 func (h *handler) syncCollection(srcfs, dstfs arvados.CustomFileSystem, path string) error {
607 coll, _ := h.determineCollection(srcfs, path)
608 if coll == nil || coll.UUID == "" {
609 return errors.New("could not determine collection to sync")
611 d, err := srcfs.OpenFile("by_id/"+coll.UUID, os.O_RDWR, 0777)
620 snap, err := d.Snapshot()
624 dstd, err := dstfs.OpenFile("by_id/"+coll.UUID, os.O_RDWR, 0777)
629 return dstd.Splice(snap)
632 func setFileInfoHeaders(header http.Header, fs arvados.CustomFileSystem, path string) error {
633 maybeEncode := func(s string) string {
634 for _, c := range s {
635 if c > '\u007f' || c < ' ' {
636 return mime.BEncoding.Encode("UTF-8", s)
641 path = strings.TrimSuffix(path, "/")
642 var props map[string]interface{}
644 fi, err := fs.Stat(path)
648 switch src := fi.Sys().(type) {
649 case *arvados.Collection:
650 props = src.Properties
652 props = src.Properties
654 if err, ok := src.(error); ok {
658 cut := strings.LastIndexByte(path, '/')
667 for k, v := range props {
668 if !validMIMEHeaderKey(k) {
671 k = "x-amz-meta-" + k
672 if s, ok := v.(string); ok {
673 header.Set(k, maybeEncode(s))
674 } else if j, err := json.Marshal(v); err == nil {
675 header.Set(k, maybeEncode(string(j)))
681 func validMIMEHeaderKey(k string) bool {
683 return check != textproto.CanonicalMIMEHeaderKey(check)
686 // Call fn on the given path (directory) and its contents, in
687 // lexicographic order.
689 // If isRoot==true and path is not a directory, return nil.
691 // If fn returns filepath.SkipDir when called on a directory, don't
692 // descend into that directory.
693 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
695 fi, err := fs.Stat(path)
696 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
698 } else if err != nil {
702 if err == filepath.SkipDir {
704 } else if err != nil {
708 f, err := fs.Open(path)
709 if os.IsNotExist(err) && isRoot {
711 } else if err != nil {
712 return fmt.Errorf("open %q: %w", path, err)
718 fis, err := f.Readdir(-1)
722 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
723 for _, fi := range fis {
724 err = fn(path+"/"+fi.Name(), fi)
725 if err == filepath.SkipDir {
727 } else if err != nil {
731 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
740 var errDone = errors.New("done")
742 func (h *handler) s3list(bucket string, w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
748 marker string // decoded continuationToken (v2) or provided by client (v1)
749 startAfter string // v2
750 continuationToken string // v2
751 encodingTypeURL bool // v2
753 params.delimiter = r.FormValue("delimiter")
754 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
755 params.maxKeys = int(mk)
757 params.maxKeys = s3MaxKeys
759 params.prefix = r.FormValue("prefix")
760 switch r.FormValue("list-type") {
765 http.Error(w, "invalid list-type parameter", http.StatusBadRequest)
769 params.continuationToken = r.FormValue("continuation-token")
770 marker, err := base64.StdEncoding.DecodeString(params.continuationToken)
772 http.Error(w, "invalid continuation token", http.StatusBadRequest)
775 params.marker = string(marker)
776 params.startAfter = r.FormValue("start-after")
777 switch r.FormValue("encoding-type") {
780 params.encodingTypeURL = true
782 http.Error(w, "invalid encoding-type parameter", http.StatusBadRequest)
786 params.marker = r.FormValue("marker")
789 bucketdir := "by_id/" + bucket
790 // walkpath is the directory (relative to bucketdir) we need
791 // to walk: the innermost directory that is guaranteed to
792 // contain all paths that have the requested prefix. Examples:
793 // prefix "foo/bar" => walkpath "foo"
794 // prefix "foo/bar/" => walkpath "foo/bar"
795 // prefix "foo" => walkpath ""
796 // prefix "" => walkpath ""
797 walkpath := params.prefix
798 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
799 walkpath = walkpath[:cut]
806 Prefix: params.prefix,
807 Delimiter: params.delimiter,
808 MaxKeys: params.maxKeys,
809 ContinuationToken: r.FormValue("continuation-token"),
810 StartAfter: params.startAfter,
814 commonPrefixes := map[string]bool{}
815 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
816 if path == bucketdir {
819 path = path[len(bucketdir)+1:]
820 filesize := fi.Size()
825 if len(path) <= len(params.prefix) {
826 if path > params.prefix[:len(path)] {
827 // with prefix "foobar", walking "fooz" means we're done
830 if path < params.prefix[:len(path)] {
831 // with prefix "foobar", walking "foobag" is pointless
832 return filepath.SkipDir
834 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
835 // with prefix "foo/bar", walking "fo"
836 // is pointless (but walking "foo" or
837 // "foo/bar" is necessary)
838 return filepath.SkipDir
840 if len(path) < len(params.prefix) {
841 // can't skip anything, and this entry
842 // isn't in the results, so just
847 if path[:len(params.prefix)] > params.prefix {
848 // with prefix "foobar", nothing we
849 // see after "foozzz" is relevant
853 if path < params.marker || path < params.prefix || path <= params.startAfter {
856 if fi.IsDir() && !h.Cluster.Collections.S3FolderObjects {
857 // Note we don't add anything to
858 // commonPrefixes here even if delimiter is
859 // "/". We descend into the directory, and
860 // return a commonPrefix only if we end up
861 // finding a regular file inside it.
864 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
865 resp.IsTruncated = true
866 if params.delimiter != "" || params.v2 {
871 if params.delimiter != "" {
872 idx := strings.Index(path[len(params.prefix):], params.delimiter)
874 // with prefix "foobar" and delimiter
875 // "z", when we hit "foobar/baz", we
876 // add "/baz" to commonPrefixes and
878 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
879 return filepath.SkipDir
882 resp.Contents = append(resp.Contents, s3Key{
884 LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
889 if err != nil && err != errDone {
890 http.Error(w, err.Error(), http.StatusInternalServerError)
893 if params.delimiter != "" {
894 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
895 for prefix := range commonPrefixes {
896 resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
898 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
900 resp.KeyCount = len(resp.Contents)
901 var respV1orV2 interface{}
903 if params.encodingTypeURL {
904 // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
905 // "If you specify the encoding-type request
906 // parameter, Amazon S3 includes this element in the
907 // response, and returns encoded key name values in
908 // the following response elements:
910 // Delimiter, Prefix, Key, and StartAfter.
914 // Valid Values: url"
916 // This is somewhat vague but in practice it appears
917 // to mean x-www-form-urlencoded as in RFC1866 8.2.1
918 // para 1 (encode space as "+") rather than straight
919 // percent-encoding as in RFC1738 2.2. Presumably,
920 // the intent is to allow the client to decode XML and
921 // then paste the strings directly into another URI
922 // query or POST form like "https://host/path?foo=" +
923 // foo + "&bar=" + bar.
924 resp.EncodingType = "url"
925 resp.Delimiter = url.QueryEscape(resp.Delimiter)
926 resp.Prefix = url.QueryEscape(resp.Prefix)
927 resp.StartAfter = url.QueryEscape(resp.StartAfter)
928 for i, ent := range resp.Contents {
929 ent.Key = url.QueryEscape(ent.Key)
930 resp.Contents[i] = ent
932 for i, ent := range resp.CommonPrefixes {
933 ent.Prefix = url.QueryEscape(ent.Prefix)
934 resp.CommonPrefixes[i] = ent
939 resp.NextContinuationToken = base64.StdEncoding.EncodeToString([]byte(nextMarker))
942 respV1orV2 = listV1Resp{
943 CommonPrefixes: resp.CommonPrefixes,
944 NextMarker: nextMarker,
945 KeyCount: resp.KeyCount,
946 IsTruncated: resp.IsTruncated,
948 Prefix: params.prefix,
949 Delimiter: params.delimiter,
950 Marker: params.marker,
951 MaxKeys: params.maxKeys,
952 Contents: resp.Contents,
956 w.Header().Set("Content-Type", "application/xml")
957 io.WriteString(w, xml.Header)
958 if err := xml.NewEncoder(w).Encode(respV1orV2); err != nil {
959 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")