1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
25 "git.arvados.org/arvados.git/sdk/go/arvados"
26 "git.arvados.org/arvados.git/sdk/go/ctxlog"
27 "github.com/AdRoll/goamz/s3"
32 s3SignAlgorithm = "AWS4-HMAC-SHA256"
33 s3MaxClockSkew = 5 * time.Minute
36 func hmacstring(msg string, key []byte) []byte {
37 h := hmac.New(sha256.New, key)
38 io.WriteString(h, msg)
42 func hashdigest(h hash.Hash, payload string) string {
43 io.WriteString(h, payload)
44 return fmt.Sprintf("%x", h.Sum(nil))
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)))))
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)
68 values[k] += k + "=" + v
72 for i, k := range keys {
75 return strings.Join(keys, "&")
78 var reMultipleSlashChars = regexp.MustCompile(`//+`)
80 func s3stringToSign(alg, scope, signedHeaders string, r *http.Request) (string, error) {
81 timefmt, timestr := "20060102T150405Z", r.Header.Get("X-Amz-Date")
83 timefmt, timestr = time.RFC1123, r.Header.Get("Date")
85 t, err := time.Parse(timefmt, timestr)
87 return "", fmt.Errorf("invalid timestamp %q: %s", timestr, err)
89 if skew := time.Now().Sub(t); skew < -s3MaxClockSkew || skew > s3MaxClockSkew {
90 return "", errors.New("exceeded max clock skew")
93 var canonicalHeaders string
94 for _, h := range strings.Split(signedHeaders, ";") {
96 canonicalHeaders += h + ":" + r.Host + "\n"
98 canonicalHeaders += h + ":" + r.Header.Get(h) + "\n"
102 normalizedURL := *r.URL
103 normalizedURL.RawPath = ""
104 normalizedURL.Path = reMultipleSlashChars.ReplaceAllString(normalizedURL.Path, "/")
105 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"))
106 ctxlog.FromContext(r.Context()).Debugf("s3stringToSign: canonicalRequest %s", canonicalRequest)
107 return fmt.Sprintf("%s\n%s\n%s\n%s", alg, r.Header.Get("X-Amz-Date"), scope, hashdigest(sha256.New(), canonicalRequest)), nil
110 func s3signature(secretKey, scope, signedHeaders, stringToSign string) (string, error) {
111 // scope is {datestamp}/{region}/{service}/aws4_request
112 drs := strings.Split(scope, "/")
114 return "", fmt.Errorf("invalid scope %q", scope)
116 key := s3signatureKey(secretKey, drs[0], drs[1], drs[2])
117 return hashdigest(hmac.New(sha256.New, key), stringToSign), nil
120 var v2tokenUnderscore = regexp.MustCompile(`^v2_[a-z0-9]{5}-gj3su-[a-z0-9]{15}_`)
122 func unescapeKey(key string) string {
123 if v2tokenUnderscore.MatchString(key) {
124 // Entire Arvados token, with "/" replaced by "_" to
125 // avoid colliding with the Authorization header
127 return strings.Replace(key, "_", "/", -1)
128 } else if s, err := url.PathUnescape(key); err == nil {
135 // checks3signature verifies the given S3 V4 signature and returns the
136 // Arvados token that corresponds to the given accessKey. An error is
137 // returned if accessKey is not a valid token UUID or the signature
139 func (h *handler) checks3signature(r *http.Request) (string, error) {
140 var key, scope, signedHeaders, signature string
141 authstring := strings.TrimPrefix(r.Header.Get("Authorization"), s3SignAlgorithm+" ")
142 for _, cmpt := range strings.Split(authstring, ",") {
143 cmpt = strings.TrimSpace(cmpt)
144 split := strings.SplitN(cmpt, "=", 2)
146 case len(split) != 2:
148 case split[0] == "Credential":
149 keyandscope := strings.SplitN(split[1], "/", 2)
150 if len(keyandscope) == 2 {
151 key, scope = keyandscope[0], keyandscope[1]
153 case split[0] == "SignedHeaders":
154 signedHeaders = split[1]
155 case split[0] == "Signature":
160 client := (&arvados.Client{
161 APIHost: h.Config.cluster.Services.Controller.ExternalURL.Host,
162 Insecure: h.Config.cluster.TLS.Insecure,
163 }).WithRequestID(r.Header.Get("X-Request-Id"))
164 var aca arvados.APIClientAuthorization
167 if len(key) == 27 && key[5:12] == "-gj3su-" {
168 // Access key is the UUID of an Arvados token, secret
169 // key is the secret part.
170 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+h.Config.cluster.SystemRootToken)
171 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/"+key, nil, nil)
172 secret = aca.APIToken
174 // Access key and secret key are both an entire
175 // Arvados token or OIDC access token.
176 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+unescapeKey(key))
177 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/current", nil, nil)
181 ctxlog.FromContext(r.Context()).WithError(err).WithField("UUID", key).Info("token lookup failed")
182 return "", errors.New("invalid access key")
184 stringToSign, err := s3stringToSign(s3SignAlgorithm, scope, signedHeaders, r)
188 expect, err := s3signature(secret, scope, signedHeaders, stringToSign)
191 } else if expect != signature {
192 return "", fmt.Errorf("signature does not match (scope %q signedHeaders %q stringToSign %q)", scope, signedHeaders, stringToSign)
194 return aca.TokenV2(), nil
197 func s3ErrorResponse(w http.ResponseWriter, s3code string, message string, resource string, code int) {
198 w.Header().Set("Content-Type", "application/xml")
199 w.Header().Set("X-Content-Type-Options", "nosniff")
201 var errstruct struct {
207 errstruct.Code = s3code
208 errstruct.Message = message
209 errstruct.Resource = resource
210 errstruct.RequestId = ""
211 enc := xml.NewEncoder(w)
212 fmt.Fprint(w, xml.Header)
213 enc.EncodeElement(errstruct, xml.StartElement{Name: xml.Name{Local: "Error"}})
216 var NoSuchKey = "NoSuchKey"
217 var NoSuchBucket = "NoSuchBucket"
218 var InvalidArgument = "InvalidArgument"
219 var InternalError = "InternalError"
220 var UnauthorizedAccess = "UnauthorizedAccess"
221 var InvalidRequest = "InvalidRequest"
222 var SignatureDoesNotMatch = "SignatureDoesNotMatch"
224 // serveS3 handles r and returns true if r is a request from an S3
225 // client, otherwise it returns false.
226 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
228 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
229 split := strings.SplitN(auth[4:], ":", 2)
231 s3ErrorResponse(w, InvalidRequest, "malformed Authorization header", r.URL.Path, http.StatusUnauthorized)
234 token = unescapeKey(split[0])
235 } else if strings.HasPrefix(auth, s3SignAlgorithm+" ") {
236 t, err := h.checks3signature(r)
238 s3ErrorResponse(w, SignatureDoesNotMatch, "signature verification failed: "+err.Error(), r.URL.Path, http.StatusForbidden)
247 var fs arvados.CustomFileSystem
248 if r.Method == http.MethodGet || r.Method == http.MethodHead {
249 // Use a single session (cached FileSystem) across
250 // multiple read requests.
251 fs, err = h.Config.Cache.GetSession(token)
253 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
257 // Create a FileSystem for this request, to avoid
258 // exposing incomplete write operations to concurrent
260 _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
262 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
266 fs = client.SiteFileSystem(kc)
267 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
270 var objectNameGiven bool
271 var bucketName string
273 if id := parseCollectionIDFromDNSName(r.Host); id != "" {
276 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 0
278 bucketName = strings.SplitN(strings.TrimPrefix(r.URL.Path, "/"), "/", 2)[0]
279 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
281 fspath += reMultipleSlashChars.ReplaceAllString(r.URL.Path, "/")
284 case r.Method == http.MethodGet && !objectNameGiven:
285 // Path is "/{uuid}" or "/{uuid}/", has no object name
286 if _, ok := r.URL.Query()["versioning"]; ok {
287 // GetBucketVersioning
288 w.Header().Set("Content-Type", "application/xml")
289 io.WriteString(w, xml.Header)
290 fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
293 h.s3list(bucketName, w, r, fs)
296 case r.Method == http.MethodGet || r.Method == http.MethodHead:
297 fi, err := fs.Stat(fspath)
298 if r.Method == "HEAD" && !objectNameGiven {
300 if err == nil && fi.IsDir() {
301 w.WriteHeader(http.StatusOK)
302 } else if os.IsNotExist(err) {
303 s3ErrorResponse(w, NoSuchBucket, "The specified bucket does not exist.", r.URL.Path, http.StatusNotFound)
305 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
309 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Config.cluster.Collections.S3FolderObjects {
310 w.Header().Set("Content-Type", "application/x-directory")
311 w.WriteHeader(http.StatusOK)
314 if os.IsNotExist(err) ||
315 (err != nil && err.Error() == "not a directory") ||
316 (fi != nil && fi.IsDir()) {
317 s3ErrorResponse(w, NoSuchKey, "The specified key does not exist.", r.URL.Path, http.StatusNotFound)
320 // shallow copy r, and change URL path
323 http.FileServer(fs).ServeHTTP(w, &r)
325 case r.Method == http.MethodPut:
326 if !objectNameGiven {
327 s3ErrorResponse(w, InvalidArgument, "Missing object name in PUT request.", r.URL.Path, http.StatusBadRequest)
331 if strings.HasSuffix(fspath, "/") {
332 if !h.Config.cluster.Collections.S3FolderObjects {
333 s3ErrorResponse(w, InvalidArgument, "invalid object name: trailing slash", r.URL.Path, http.StatusBadRequest)
336 n, err := r.Body.Read(make([]byte, 1))
337 if err != nil && err != io.EOF {
338 s3ErrorResponse(w, InternalError, fmt.Sprintf("error reading request body: %s", err), r.URL.Path, http.StatusInternalServerError)
341 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless content is empty", r.URL.Path, http.StatusBadRequest)
343 } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
344 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", r.URL.Path, http.StatusBadRequest)
347 // Given PUT "foo/bar/", we'll use "foo/bar/."
348 // in the "ensure parents exist" block below,
349 // and then we'll be done.
353 fi, err := fs.Stat(fspath)
354 if err != nil && err.Error() == "not a directory" {
355 // requested foo/bar, but foo is a file
356 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
359 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
360 // requested foo/bar/, but foo/bar is a file
361 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
364 // create missing parent/intermediate directories, if any
365 for i, c := range fspath {
366 if i > 0 && c == '/' {
368 if strings.HasSuffix(dir, "/") {
369 err = errors.New("invalid object name (consecutive '/' chars)")
370 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
373 err = fs.Mkdir(dir, 0755)
374 if err == arvados.ErrInvalidArgument {
375 // Cannot create a directory
377 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
378 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
380 } else if err != nil && !os.IsExist(err) {
381 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
382 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
388 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
389 if os.IsNotExist(err) {
390 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
393 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
394 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
398 _, err = io.Copy(f, r.Body)
400 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
401 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
406 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
407 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
413 err = fmt.Errorf("sync failed: %w", err)
414 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
417 // Ensure a subsequent read operation will see the changes.
418 h.Config.Cache.ResetSession(token)
419 w.WriteHeader(http.StatusOK)
421 case r.Method == http.MethodDelete:
422 if !objectNameGiven || r.URL.Path == "/" {
423 s3ErrorResponse(w, InvalidArgument, "missing object name in DELETE request", r.URL.Path, http.StatusBadRequest)
426 if strings.HasSuffix(fspath, "/") {
427 fspath = strings.TrimSuffix(fspath, "/")
428 fi, err := fs.Stat(fspath)
429 if os.IsNotExist(err) {
430 w.WriteHeader(http.StatusNoContent)
432 } else if err != nil {
433 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
435 } else if !fi.IsDir() {
436 // if "foo" exists and is a file, then
437 // "foo/" doesn't exist, so we say
438 // delete was successful.
439 w.WriteHeader(http.StatusNoContent)
442 } else if fi, err := fs.Stat(fspath); err == nil && fi.IsDir() {
443 // if "foo" is a dir, it is visible via S3
444 // only as "foo/", not "foo" -- so we leave
445 // the dir alone and return 204 to indicate
446 // that "foo" does not exist.
447 w.WriteHeader(http.StatusNoContent)
450 err = fs.Remove(fspath)
451 if os.IsNotExist(err) {
452 w.WriteHeader(http.StatusNoContent)
456 err = fmt.Errorf("rm failed: %w", err)
457 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
462 err = fmt.Errorf("sync failed: %w", err)
463 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
466 // Ensure a subsequent read operation will see the changes.
467 h.Config.Cache.ResetSession(token)
468 w.WriteHeader(http.StatusNoContent)
471 s3ErrorResponse(w, InvalidRequest, "method not allowed", r.URL.Path, http.StatusMethodNotAllowed)
476 // Call fn on the given path (directory) and its contents, in
477 // lexicographic order.
479 // If isRoot==true and path is not a directory, return nil.
481 // If fn returns filepath.SkipDir when called on a directory, don't
482 // descend into that directory.
483 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
485 fi, err := fs.Stat(path)
486 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
488 } else if err != nil {
492 if err == filepath.SkipDir {
494 } else if err != nil {
498 f, err := fs.Open(path)
499 if os.IsNotExist(err) && isRoot {
501 } else if err != nil {
502 return fmt.Errorf("open %q: %w", path, err)
508 fis, err := f.Readdir(-1)
512 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
513 for _, fi := range fis {
514 err = fn(path+"/"+fi.Name(), fi)
515 if err == filepath.SkipDir {
517 } else if err != nil {
521 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
530 var errDone = errors.New("done")
532 func (h *handler) s3list(bucket string, w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
539 params.delimiter = r.FormValue("delimiter")
540 params.marker = r.FormValue("marker")
541 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
542 params.maxKeys = int(mk)
544 params.maxKeys = s3MaxKeys
546 params.prefix = r.FormValue("prefix")
548 bucketdir := "by_id/" + bucket
549 // walkpath is the directory (relative to bucketdir) we need
550 // to walk: the innermost directory that is guaranteed to
551 // contain all paths that have the requested prefix. Examples:
552 // prefix "foo/bar" => walkpath "foo"
553 // prefix "foo/bar/" => walkpath "foo/bar"
554 // prefix "foo" => walkpath ""
555 // prefix "" => walkpath ""
556 walkpath := params.prefix
557 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
558 walkpath = walkpath[:cut]
563 type commonPrefix struct {
566 type listResp struct {
567 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
569 // s3.ListResp marshals an empty tag when
570 // CommonPrefixes is nil, which confuses some clients.
571 // Fix by using this nested struct instead.
572 CommonPrefixes []commonPrefix
573 // Similarly, we need omitempty here, because an empty
574 // tag confuses some clients (e.g.,
575 // github.com/aws/aws-sdk-net never terminates its
577 NextMarker string `xml:"NextMarker,omitempty"`
578 // ListObjectsV2 has a KeyCount response field.
582 ListResp: s3.ListResp{
584 Prefix: params.prefix,
585 Delimiter: params.delimiter,
586 Marker: params.marker,
587 MaxKeys: params.maxKeys,
590 commonPrefixes := map[string]bool{}
591 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
592 if path == bucketdir {
595 path = path[len(bucketdir)+1:]
596 filesize := fi.Size()
601 if len(path) <= len(params.prefix) {
602 if path > params.prefix[:len(path)] {
603 // with prefix "foobar", walking "fooz" means we're done
606 if path < params.prefix[:len(path)] {
607 // with prefix "foobar", walking "foobag" is pointless
608 return filepath.SkipDir
610 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
611 // with prefix "foo/bar", walking "fo"
612 // is pointless (but walking "foo" or
613 // "foo/bar" is necessary)
614 return filepath.SkipDir
616 if len(path) < len(params.prefix) {
617 // can't skip anything, and this entry
618 // isn't in the results, so just
623 if path[:len(params.prefix)] > params.prefix {
624 // with prefix "foobar", nothing we
625 // see after "foozzz" is relevant
629 if path < params.marker || path < params.prefix {
632 if fi.IsDir() && !h.Config.cluster.Collections.S3FolderObjects {
633 // Note we don't add anything to
634 // commonPrefixes here even if delimiter is
635 // "/". We descend into the directory, and
636 // return a commonPrefix only if we end up
637 // finding a regular file inside it.
640 if params.delimiter != "" {
641 idx := strings.Index(path[len(params.prefix):], params.delimiter)
643 // with prefix "foobar" and delimiter
644 // "z", when we hit "foobar/baz", we
645 // add "/baz" to commonPrefixes and
647 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
648 return filepath.SkipDir
651 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
652 resp.IsTruncated = true
653 if params.delimiter != "" {
654 resp.NextMarker = path
658 resp.Contents = append(resp.Contents, s3.Key{
660 LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
665 if err != nil && err != errDone {
666 http.Error(w, err.Error(), http.StatusInternalServerError)
669 if params.delimiter != "" {
670 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
671 for prefix := range commonPrefixes {
672 resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
674 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
676 resp.KeyCount = len(resp.Contents)
677 w.Header().Set("Content-Type", "application/xml")
678 io.WriteString(w, xml.Header)
679 if err := xml.NewEncoder(w).Encode(resp); err != nil {
680 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")