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 func s3stringToSign(alg, scope, signedHeaders string, r *http.Request) (string, error) {
79 timefmt, timestr := "20060102T150405Z", r.Header.Get("X-Amz-Date")
81 timefmt, timestr = time.RFC1123, r.Header.Get("Date")
83 t, err := time.Parse(timefmt, timestr)
85 return "", fmt.Errorf("invalid timestamp %q: %s", timestr, err)
87 if skew := time.Now().Sub(t); skew < -s3MaxClockSkew || skew > s3MaxClockSkew {
88 return "", errors.New("exceeded max clock skew")
91 var canonicalHeaders string
92 for _, h := range strings.Split(signedHeaders, ";") {
94 canonicalHeaders += h + ":" + r.Host + "\n"
96 canonicalHeaders += h + ":" + r.Header.Get(h) + "\n"
100 canonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s", r.Method, r.URL.EscapedPath(), s3querystring(r.URL), canonicalHeaders, signedHeaders, r.Header.Get("X-Amz-Content-Sha256"))
101 ctxlog.FromContext(r.Context()).Debugf("s3stringToSign: canonicalRequest %s", canonicalRequest)
102 return fmt.Sprintf("%s\n%s\n%s\n%s", alg, r.Header.Get("X-Amz-Date"), scope, hashdigest(sha256.New(), canonicalRequest)), nil
105 func s3signature(secretKey, scope, signedHeaders, stringToSign string) (string, error) {
106 // scope is {datestamp}/{region}/{service}/aws4_request
107 drs := strings.Split(scope, "/")
109 return "", fmt.Errorf("invalid scope %q", scope)
111 key := s3signatureKey(secretKey, drs[0], drs[1], drs[2])
112 return hashdigest(hmac.New(sha256.New, key), stringToSign), nil
115 var v2tokenUnderscore = regexp.MustCompile(`^v2_[a-z0-9]{5}-gj3su-[a-z0-9]{15}_`)
117 func unescapeKey(key string) string {
118 if v2tokenUnderscore.MatchString(key) {
119 // Entire Arvados token, with "/" replaced by "_" to
120 // avoid colliding with the Authorization header
122 return strings.Replace(key, "_", "/", -1)
123 } else if s, err := url.QueryUnescape(key); err == nil {
130 // checks3signature verifies the given S3 V4 signature and returns the
131 // Arvados token that corresponds to the given accessKey. An error is
132 // returned if accessKey is not a valid token UUID or the signature
134 func (h *handler) checks3signature(r *http.Request) (string, error) {
135 var key, scope, signedHeaders, signature string
136 authstring := strings.TrimPrefix(r.Header.Get("Authorization"), s3SignAlgorithm+" ")
137 for _, cmpt := range strings.Split(authstring, ",") {
138 cmpt = strings.TrimSpace(cmpt)
139 split := strings.SplitN(cmpt, "=", 2)
141 case len(split) != 2:
143 case split[0] == "Credential":
144 keyandscope := strings.SplitN(split[1], "/", 2)
145 if len(keyandscope) == 2 {
146 key, scope = keyandscope[0], keyandscope[1]
148 case split[0] == "SignedHeaders":
149 signedHeaders = split[1]
150 case split[0] == "Signature":
155 client := (&arvados.Client{
156 APIHost: h.Config.cluster.Services.Controller.ExternalURL.Host,
157 Insecure: h.Config.cluster.TLS.Insecure,
158 }).WithRequestID(r.Header.Get("X-Request-Id"))
159 var aca arvados.APIClientAuthorization
162 if len(key) == 27 && key[5:12] == "-gj3su-" {
163 // Access key is the UUID of an Arvados token, secret
164 // key is the secret part.
165 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+h.Config.cluster.SystemRootToken)
166 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/"+key, nil, nil)
167 secret = aca.APIToken
169 // Access key and secret key are both an entire
170 // Arvados token or OIDC access token.
171 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+unescapeKey(key))
172 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/current", nil, nil)
176 ctxlog.FromContext(r.Context()).WithError(err).WithField("UUID", key).Info("token lookup failed")
177 return "", errors.New("invalid access key")
179 stringToSign, err := s3stringToSign(s3SignAlgorithm, scope, signedHeaders, r)
183 expect, err := s3signature(secret, scope, signedHeaders, stringToSign)
186 } else if expect != signature {
187 return "", fmt.Errorf("signature does not match (scope %q signedHeaders %q stringToSign %q)", scope, signedHeaders, stringToSign)
189 return aca.TokenV2(), nil
192 // serveS3 handles r and returns true if r is a request from an S3
193 // client, otherwise it returns false.
194 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
196 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
197 split := strings.SplitN(auth[4:], ":", 2)
199 http.Error(w, "malformed Authorization header", http.StatusUnauthorized)
202 token = unescapeKey(split[0])
203 } else if strings.HasPrefix(auth, s3SignAlgorithm+" ") {
204 t, err := h.checks3signature(r)
206 http.Error(w, "signature verification failed: "+err.Error(), http.StatusForbidden)
214 _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
216 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
221 fs := client.SiteFileSystem(kc)
222 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
224 objectNameGiven := strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
227 case r.Method == http.MethodGet && !objectNameGiven:
228 // Path is "/{uuid}" or "/{uuid}/", has no object name
229 if _, ok := r.URL.Query()["versioning"]; ok {
230 // GetBucketVersioning
231 w.Header().Set("Content-Type", "application/xml")
232 io.WriteString(w, xml.Header)
233 fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
239 case r.Method == http.MethodGet || r.Method == http.MethodHead:
240 fspath := "/by_id" + r.URL.Path
241 fi, err := fs.Stat(fspath)
242 if r.Method == "HEAD" && !objectNameGiven {
244 if err == nil && fi.IsDir() {
245 w.WriteHeader(http.StatusOK)
246 } else if os.IsNotExist(err) {
247 w.WriteHeader(http.StatusNotFound)
249 http.Error(w, err.Error(), http.StatusBadGateway)
253 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Config.cluster.Collections.S3FolderObjects {
254 w.Header().Set("Content-Type", "application/x-directory")
255 w.WriteHeader(http.StatusOK)
258 if os.IsNotExist(err) ||
259 (err != nil && err.Error() == "not a directory") ||
260 (fi != nil && fi.IsDir()) {
261 http.Error(w, "not found", http.StatusNotFound)
264 // shallow copy r, and change URL path
267 http.FileServer(fs).ServeHTTP(w, &r)
269 case r.Method == http.MethodPut:
270 if !objectNameGiven {
271 http.Error(w, "missing object name in PUT request", http.StatusBadRequest)
274 fspath := "by_id" + r.URL.Path
276 if strings.HasSuffix(fspath, "/") {
277 if !h.Config.cluster.Collections.S3FolderObjects {
278 http.Error(w, "invalid object name: trailing slash", http.StatusBadRequest)
281 n, err := r.Body.Read(make([]byte, 1))
282 if err != nil && err != io.EOF {
283 http.Error(w, fmt.Sprintf("error reading request body: %s", err), http.StatusInternalServerError)
286 http.Error(w, "cannot create object with trailing '/' char unless content is empty", http.StatusBadRequest)
288 } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
289 http.Error(w, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", http.StatusBadRequest)
292 // Given PUT "foo/bar/", we'll use "foo/bar/."
293 // in the "ensure parents exist" block below,
294 // and then we'll be done.
298 fi, err := fs.Stat(fspath)
299 if err != nil && err.Error() == "not a directory" {
300 // requested foo/bar, but foo is a file
301 http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
304 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
305 // requested foo/bar/, but foo/bar is a file
306 http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
309 // create missing parent/intermediate directories, if any
310 for i, c := range fspath {
311 if i > 0 && c == '/' {
313 if strings.HasSuffix(dir, "/") {
314 err = errors.New("invalid object name (consecutive '/' chars)")
315 http.Error(w, err.Error(), http.StatusBadRequest)
318 err = fs.Mkdir(dir, 0755)
319 if err == arvados.ErrInvalidArgument {
320 // Cannot create a directory
322 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
323 http.Error(w, err.Error(), http.StatusBadRequest)
325 } else if err != nil && !os.IsExist(err) {
326 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
327 http.Error(w, err.Error(), http.StatusInternalServerError)
333 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
334 if os.IsNotExist(err) {
335 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
338 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
339 http.Error(w, err.Error(), http.StatusBadRequest)
343 _, err = io.Copy(f, r.Body)
345 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
346 http.Error(w, err.Error(), http.StatusBadGateway)
351 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
352 http.Error(w, err.Error(), http.StatusBadGateway)
358 err = fmt.Errorf("sync failed: %w", err)
359 http.Error(w, err.Error(), http.StatusInternalServerError)
362 w.WriteHeader(http.StatusOK)
364 case r.Method == http.MethodDelete:
365 if !objectNameGiven || r.URL.Path == "/" {
366 http.Error(w, "missing object name in DELETE request", http.StatusBadRequest)
369 fspath := "by_id" + r.URL.Path
370 if strings.HasSuffix(fspath, "/") {
371 fspath = strings.TrimSuffix(fspath, "/")
372 fi, err := fs.Stat(fspath)
373 if os.IsNotExist(err) {
374 w.WriteHeader(http.StatusNoContent)
376 } else if err != nil {
377 http.Error(w, err.Error(), http.StatusInternalServerError)
379 } else if !fi.IsDir() {
380 // if "foo" exists and is a file, then
381 // "foo/" doesn't exist, so we say
382 // delete was successful.
383 w.WriteHeader(http.StatusNoContent)
386 } else if fi, err := fs.Stat(fspath); err == nil && fi.IsDir() {
387 // if "foo" is a dir, it is visible via S3
388 // only as "foo/", not "foo" -- so we leave
389 // the dir alone and return 204 to indicate
390 // that "foo" does not exist.
391 w.WriteHeader(http.StatusNoContent)
394 err = fs.Remove(fspath)
395 if os.IsNotExist(err) {
396 w.WriteHeader(http.StatusNoContent)
400 err = fmt.Errorf("rm failed: %w", err)
401 http.Error(w, err.Error(), http.StatusBadRequest)
406 err = fmt.Errorf("sync failed: %w", err)
407 http.Error(w, err.Error(), http.StatusInternalServerError)
410 w.WriteHeader(http.StatusNoContent)
413 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
418 // Call fn on the given path (directory) and its contents, in
419 // lexicographic order.
421 // If isRoot==true and path is not a directory, return nil.
423 // If fn returns filepath.SkipDir when called on a directory, don't
424 // descend into that directory.
425 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
427 fi, err := fs.Stat(path)
428 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
430 } else if err != nil {
434 if err == filepath.SkipDir {
436 } else if err != nil {
440 f, err := fs.Open(path)
441 if os.IsNotExist(err) && isRoot {
443 } else if err != nil {
444 return fmt.Errorf("open %q: %w", path, err)
450 fis, err := f.Readdir(-1)
454 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
455 for _, fi := range fis {
456 err = fn(path+"/"+fi.Name(), fi)
457 if err == filepath.SkipDir {
459 } else if err != nil {
463 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
472 var errDone = errors.New("done")
474 func (h *handler) s3list(w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
482 params.bucket = strings.SplitN(r.URL.Path[1:], "/", 2)[0]
483 params.delimiter = r.FormValue("delimiter")
484 params.marker = r.FormValue("marker")
485 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
486 params.maxKeys = int(mk)
488 params.maxKeys = s3MaxKeys
490 params.prefix = r.FormValue("prefix")
492 bucketdir := "by_id/" + params.bucket
493 // walkpath is the directory (relative to bucketdir) we need
494 // to walk: the innermost directory that is guaranteed to
495 // contain all paths that have the requested prefix. Examples:
496 // prefix "foo/bar" => walkpath "foo"
497 // prefix "foo/bar/" => walkpath "foo/bar"
498 // prefix "foo" => walkpath ""
499 // prefix "" => walkpath ""
500 walkpath := params.prefix
501 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
502 walkpath = walkpath[:cut]
507 type commonPrefix struct {
510 type listResp struct {
511 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
513 // s3.ListResp marshals an empty tag when
514 // CommonPrefixes is nil, which confuses some clients.
515 // Fix by using this nested struct instead.
516 CommonPrefixes []commonPrefix
517 // Similarly, we need omitempty here, because an empty
518 // tag confuses some clients (e.g.,
519 // github.com/aws/aws-sdk-net never terminates its
521 NextMarker string `xml:"NextMarker,omitempty"`
522 // ListObjectsV2 has a KeyCount response field.
526 ListResp: s3.ListResp{
527 Name: strings.SplitN(r.URL.Path[1:], "/", 2)[0],
528 Prefix: params.prefix,
529 Delimiter: params.delimiter,
530 Marker: params.marker,
531 MaxKeys: params.maxKeys,
534 commonPrefixes := map[string]bool{}
535 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
536 if path == bucketdir {
539 path = path[len(bucketdir)+1:]
540 filesize := fi.Size()
545 if len(path) <= len(params.prefix) {
546 if path > params.prefix[:len(path)] {
547 // with prefix "foobar", walking "fooz" means we're done
550 if path < params.prefix[:len(path)] {
551 // with prefix "foobar", walking "foobag" is pointless
552 return filepath.SkipDir
554 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
555 // with prefix "foo/bar", walking "fo"
556 // is pointless (but walking "foo" or
557 // "foo/bar" is necessary)
558 return filepath.SkipDir
560 if len(path) < len(params.prefix) {
561 // can't skip anything, and this entry
562 // isn't in the results, so just
567 if path[:len(params.prefix)] > params.prefix {
568 // with prefix "foobar", nothing we
569 // see after "foozzz" is relevant
573 if path < params.marker || path < params.prefix {
576 if fi.IsDir() && !h.Config.cluster.Collections.S3FolderObjects {
577 // Note we don't add anything to
578 // commonPrefixes here even if delimiter is
579 // "/". We descend into the directory, and
580 // return a commonPrefix only if we end up
581 // finding a regular file inside it.
584 if params.delimiter != "" {
585 idx := strings.Index(path[len(params.prefix):], params.delimiter)
587 // with prefix "foobar" and delimiter
588 // "z", when we hit "foobar/baz", we
589 // add "/baz" to commonPrefixes and
591 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
592 return filepath.SkipDir
595 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
596 resp.IsTruncated = true
597 if params.delimiter != "" {
598 resp.NextMarker = path
602 resp.Contents = append(resp.Contents, s3.Key{
604 LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
609 if err != nil && err != errDone {
610 http.Error(w, err.Error(), http.StatusInternalServerError)
613 if params.delimiter != "" {
614 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
615 for prefix := range commonPrefixes {
616 resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
618 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
620 resp.KeyCount = len(resp.Contents)
621 w.Header().Set("Content-Type", "application/xml")
622 io.WriteString(w, xml.Header)
623 if err := xml.NewEncoder(w).Encode(resp); err != nil {
624 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")