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.PathUnescape(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 var objectNameGiven bool
226 if id := parseCollectionIDFromDNSName(r.Host); id != "" {
228 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 0
230 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
235 case r.Method == http.MethodGet && !objectNameGiven:
236 // Path is "/{uuid}" or "/{uuid}/", has no object name
237 if _, ok := r.URL.Query()["versioning"]; ok {
238 // GetBucketVersioning
239 w.Header().Set("Content-Type", "application/xml")
240 io.WriteString(w, xml.Header)
241 fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
247 case r.Method == http.MethodGet || r.Method == http.MethodHead:
248 fi, err := fs.Stat(fspath)
249 if r.Method == "HEAD" && !objectNameGiven {
251 if err == nil && fi.IsDir() {
252 w.WriteHeader(http.StatusOK)
253 } else if os.IsNotExist(err) {
254 w.WriteHeader(http.StatusNotFound)
256 http.Error(w, err.Error(), http.StatusBadGateway)
260 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Config.cluster.Collections.S3FolderObjects {
261 w.Header().Set("Content-Type", "application/x-directory")
262 w.WriteHeader(http.StatusOK)
265 if os.IsNotExist(err) ||
266 (err != nil && err.Error() == "not a directory") ||
267 (fi != nil && fi.IsDir()) {
268 http.Error(w, "not found", http.StatusNotFound)
271 // shallow copy r, and change URL path
274 http.FileServer(fs).ServeHTTP(w, &r)
276 case r.Method == http.MethodPut:
277 if !objectNameGiven {
278 http.Error(w, "missing object name in PUT request", http.StatusBadRequest)
282 if strings.HasSuffix(fspath, "/") {
283 if !h.Config.cluster.Collections.S3FolderObjects {
284 http.Error(w, "invalid object name: trailing slash", http.StatusBadRequest)
287 n, err := r.Body.Read(make([]byte, 1))
288 if err != nil && err != io.EOF {
289 http.Error(w, fmt.Sprintf("error reading request body: %s", err), http.StatusInternalServerError)
292 http.Error(w, "cannot create object with trailing '/' char unless content is empty", http.StatusBadRequest)
294 } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
295 http.Error(w, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", http.StatusBadRequest)
298 // Given PUT "foo/bar/", we'll use "foo/bar/."
299 // in the "ensure parents exist" block below,
300 // and then we'll be done.
304 fi, err := fs.Stat(fspath)
305 if err != nil && err.Error() == "not a directory" {
306 // requested foo/bar, but foo is a file
307 http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
310 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
311 // requested foo/bar/, but foo/bar is a file
312 http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
315 // create missing parent/intermediate directories, if any
316 for i, c := range fspath {
317 if i > 0 && c == '/' {
319 if strings.HasSuffix(dir, "/") {
320 err = errors.New("invalid object name (consecutive '/' chars)")
321 http.Error(w, err.Error(), http.StatusBadRequest)
324 err = fs.Mkdir(dir, 0755)
325 if err == arvados.ErrInvalidArgument {
326 // Cannot create a directory
328 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
329 http.Error(w, err.Error(), http.StatusBadRequest)
331 } else if err != nil && !os.IsExist(err) {
332 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
333 http.Error(w, err.Error(), http.StatusInternalServerError)
339 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
340 if os.IsNotExist(err) {
341 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
344 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
345 http.Error(w, err.Error(), http.StatusBadRequest)
349 _, err = io.Copy(f, r.Body)
351 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
352 http.Error(w, err.Error(), http.StatusBadGateway)
357 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
358 http.Error(w, err.Error(), http.StatusBadGateway)
364 err = fmt.Errorf("sync failed: %w", err)
365 http.Error(w, err.Error(), http.StatusInternalServerError)
368 w.WriteHeader(http.StatusOK)
370 case r.Method == http.MethodDelete:
371 if !objectNameGiven || r.URL.Path == "/" {
372 http.Error(w, "missing object name in DELETE request", http.StatusBadRequest)
375 if strings.HasSuffix(fspath, "/") {
376 fspath = strings.TrimSuffix(fspath, "/")
377 fi, err := fs.Stat(fspath)
378 if os.IsNotExist(err) {
379 w.WriteHeader(http.StatusNoContent)
381 } else if err != nil {
382 http.Error(w, err.Error(), http.StatusInternalServerError)
384 } else if !fi.IsDir() {
385 // if "foo" exists and is a file, then
386 // "foo/" doesn't exist, so we say
387 // delete was successful.
388 w.WriteHeader(http.StatusNoContent)
391 } else if fi, err := fs.Stat(fspath); err == nil && fi.IsDir() {
392 // if "foo" is a dir, it is visible via S3
393 // only as "foo/", not "foo" -- so we leave
394 // the dir alone and return 204 to indicate
395 // that "foo" does not exist.
396 w.WriteHeader(http.StatusNoContent)
399 err = fs.Remove(fspath)
400 if os.IsNotExist(err) {
401 w.WriteHeader(http.StatusNoContent)
405 err = fmt.Errorf("rm failed: %w", err)
406 http.Error(w, err.Error(), http.StatusBadRequest)
411 err = fmt.Errorf("sync failed: %w", err)
412 http.Error(w, err.Error(), http.StatusInternalServerError)
415 w.WriteHeader(http.StatusNoContent)
418 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
423 // Call fn on the given path (directory) and its contents, in
424 // lexicographic order.
426 // If isRoot==true and path is not a directory, return nil.
428 // If fn returns filepath.SkipDir when called on a directory, don't
429 // descend into that directory.
430 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
432 fi, err := fs.Stat(path)
433 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
435 } else if err != nil {
439 if err == filepath.SkipDir {
441 } else if err != nil {
445 f, err := fs.Open(path)
446 if os.IsNotExist(err) && isRoot {
448 } else if err != nil {
449 return fmt.Errorf("open %q: %w", path, err)
455 fis, err := f.Readdir(-1)
459 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
460 for _, fi := range fis {
461 err = fn(path+"/"+fi.Name(), fi)
462 if err == filepath.SkipDir {
464 } else if err != nil {
468 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
477 var errDone = errors.New("done")
479 func (h *handler) s3list(w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
487 params.bucket = strings.SplitN(r.URL.Path[1:], "/", 2)[0]
488 params.delimiter = r.FormValue("delimiter")
489 params.marker = r.FormValue("marker")
490 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
491 params.maxKeys = int(mk)
493 params.maxKeys = s3MaxKeys
495 params.prefix = r.FormValue("prefix")
497 bucketdir := "by_id/" + params.bucket
498 // walkpath is the directory (relative to bucketdir) we need
499 // to walk: the innermost directory that is guaranteed to
500 // contain all paths that have the requested prefix. Examples:
501 // prefix "foo/bar" => walkpath "foo"
502 // prefix "foo/bar/" => walkpath "foo/bar"
503 // prefix "foo" => walkpath ""
504 // prefix "" => walkpath ""
505 walkpath := params.prefix
506 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
507 walkpath = walkpath[:cut]
512 type commonPrefix struct {
515 type listResp struct {
516 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
518 // s3.ListResp marshals an empty tag when
519 // CommonPrefixes is nil, which confuses some clients.
520 // Fix by using this nested struct instead.
521 CommonPrefixes []commonPrefix
522 // Similarly, we need omitempty here, because an empty
523 // tag confuses some clients (e.g.,
524 // github.com/aws/aws-sdk-net never terminates its
526 NextMarker string `xml:"NextMarker,omitempty"`
527 // ListObjectsV2 has a KeyCount response field.
531 ListResp: s3.ListResp{
532 Name: strings.SplitN(r.URL.Path[1:], "/", 2)[0],
533 Prefix: params.prefix,
534 Delimiter: params.delimiter,
535 Marker: params.marker,
536 MaxKeys: params.maxKeys,
539 commonPrefixes := map[string]bool{}
540 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
541 if path == bucketdir {
544 path = path[len(bucketdir)+1:]
545 filesize := fi.Size()
550 if len(path) <= len(params.prefix) {
551 if path > params.prefix[:len(path)] {
552 // with prefix "foobar", walking "fooz" means we're done
555 if path < params.prefix[:len(path)] {
556 // with prefix "foobar", walking "foobag" is pointless
557 return filepath.SkipDir
559 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
560 // with prefix "foo/bar", walking "fo"
561 // is pointless (but walking "foo" or
562 // "foo/bar" is necessary)
563 return filepath.SkipDir
565 if len(path) < len(params.prefix) {
566 // can't skip anything, and this entry
567 // isn't in the results, so just
572 if path[:len(params.prefix)] > params.prefix {
573 // with prefix "foobar", nothing we
574 // see after "foozzz" is relevant
578 if path < params.marker || path < params.prefix {
581 if fi.IsDir() && !h.Config.cluster.Collections.S3FolderObjects {
582 // Note we don't add anything to
583 // commonPrefixes here even if delimiter is
584 // "/". We descend into the directory, and
585 // return a commonPrefix only if we end up
586 // finding a regular file inside it.
589 if params.delimiter != "" {
590 idx := strings.Index(path[len(params.prefix):], params.delimiter)
592 // with prefix "foobar" and delimiter
593 // "z", when we hit "foobar/baz", we
594 // add "/baz" to commonPrefixes and
596 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
597 return filepath.SkipDir
600 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
601 resp.IsTruncated = true
602 if params.delimiter != "" {
603 resp.NextMarker = path
607 resp.Contents = append(resp.Contents, s3.Key{
609 LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
614 if err != nil && err != errDone {
615 http.Error(w, err.Error(), http.StatusInternalServerError)
618 if params.delimiter != "" {
619 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
620 for prefix := range commonPrefixes {
621 resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
623 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
625 resp.KeyCount = len(resp.Contents)
626 w.Header().Set("Content-Type", "application/xml")
627 io.WriteString(w, xml.Header)
628 if err := xml.NewEncoder(w).Encode(resp); err != nil {
629 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")