1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 "git.arvados.org/arvados.git/sdk/go/ctxlog"
26 "github.com/AdRoll/goamz/s3"
31 s3SignAlgorithm = "AWS4-HMAC-SHA256"
32 s3MaxClockSkew = 5 * time.Minute
35 func hmacstring(msg string, key []byte) []byte {
36 h := hmac.New(sha256.New, key)
37 io.WriteString(h, msg)
41 func hashdigest(h hash.Hash, payload string) string {
42 io.WriteString(h, payload)
43 return fmt.Sprintf("%x", h.Sum(nil))
46 // Signing key for given secret key and request attrs.
47 func s3signatureKey(key, datestamp, regionName, serviceName string) []byte {
48 return hmacstring("aws4_request",
49 hmacstring(serviceName,
50 hmacstring(regionName,
51 hmacstring(datestamp, []byte("AWS4"+key)))))
54 // Canonical query string for S3 V4 signature: sorted keys, spaces
55 // escaped as %20 instead of +, keyvalues joined with &.
56 func s3querystring(u *url.URL) string {
57 keys := make([]string, 0, len(u.Query()))
58 values := make(map[string]string, len(u.Query()))
59 for k, vs := range u.Query() {
60 k = strings.Replace(url.QueryEscape(k), "+", "%20", -1)
61 keys = append(keys, k)
62 for _, v := range vs {
63 v = strings.Replace(url.QueryEscape(v), "+", "%20", -1)
67 values[k] += k + "=" + v
71 for i, k := range keys {
74 return strings.Join(keys, "&")
77 func s3stringToSign(alg, scope, signedHeaders string, r *http.Request) (string, error) {
78 timefmt, timestr := "20060102T150405Z", r.Header.Get("X-Amz-Date")
80 timefmt, timestr = time.RFC1123, r.Header.Get("Date")
82 t, err := time.Parse(timefmt, timestr)
84 return "", fmt.Errorf("invalid timestamp %q: %s", timestr, err)
86 if skew := time.Now().Sub(t); skew < -s3MaxClockSkew || skew > s3MaxClockSkew {
87 return "", errors.New("exceeded max clock skew")
90 var canonicalHeaders string
91 for _, h := range strings.Split(signedHeaders, ";") {
93 canonicalHeaders += h + ":" + r.Host + "\n"
95 canonicalHeaders += h + ":" + r.Header.Get(h) + "\n"
99 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"))
100 ctxlog.FromContext(r.Context()).Debugf("s3stringToSign: canonicalRequest %s", canonicalRequest)
101 return fmt.Sprintf("%s\n%s\n%s\n%s", alg, r.Header.Get("X-Amz-Date"), scope, hashdigest(sha256.New(), canonicalRequest)), nil
104 func s3signature(secretKey, scope, signedHeaders, stringToSign string) (string, error) {
105 // scope is {datestamp}/{region}/{service}/aws4_request
106 drs := strings.Split(scope, "/")
108 return "", fmt.Errorf("invalid scope %q", scope)
110 key := s3signatureKey(secretKey, drs[0], drs[1], drs[2])
111 return hashdigest(hmac.New(sha256.New, key), stringToSign), nil
114 // checks3signature verifies the given S3 V4 signature and returns the
115 // Arvados token that corresponds to the given accessKey. An error is
116 // returned if accessKey is not a valid token UUID or the signature
118 func (h *handler) checks3signature(r *http.Request) (string, error) {
119 var key, scope, signedHeaders, signature string
120 authstring := strings.TrimPrefix(r.Header.Get("Authorization"), s3SignAlgorithm+" ")
121 for _, cmpt := range strings.Split(authstring, ",") {
122 cmpt = strings.TrimSpace(cmpt)
123 split := strings.SplitN(cmpt, "=", 2)
125 case len(split) != 2:
127 case split[0] == "Credential":
128 keyandscope := strings.SplitN(split[1], "/", 2)
129 if len(keyandscope) == 2 {
130 key, scope = keyandscope[0], keyandscope[1]
132 case split[0] == "SignedHeaders":
133 signedHeaders = split[1]
134 case split[0] == "Signature":
139 client := (&arvados.Client{
140 APIHost: h.Config.cluster.Services.Controller.ExternalURL.Host,
141 Insecure: h.Config.cluster.TLS.Insecure,
142 }).WithRequestID(r.Header.Get("X-Request-Id"))
143 var aca arvados.APIClientAuthorization
146 if len(key) == 27 && key[5:12] == "-gj3su-" {
147 // Access key is the UUID of an Arvados token, secret
148 // key is the secret part.
149 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+h.Config.cluster.SystemRootToken)
150 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/"+key, nil, nil)
151 secret = aca.APIToken
153 // Access key and secret key are both an entire
154 // Arvados token or OIDC access token.
156 if strings.HasPrefix(key, "v2_") {
157 // Entire Arvados token, with "/" replaced by
158 // "_" to avoid colliding with the
159 // Authorization header format.
160 mungedKey = strings.Replace(key, "_", "/", -1)
162 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+mungedKey)
163 err = client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/current", nil, nil)
167 ctxlog.FromContext(r.Context()).WithError(err).WithField("UUID", key).Info("token lookup failed")
168 return "", errors.New("invalid access key")
170 stringToSign, err := s3stringToSign(s3SignAlgorithm, scope, signedHeaders, r)
174 expect, err := s3signature(secret, scope, signedHeaders, stringToSign)
177 } else if expect != signature {
178 return "", fmt.Errorf("signature does not match (scope %q signedHeaders %q stringToSign %q)", scope, signedHeaders, stringToSign)
180 return aca.TokenV2(), nil
183 // serveS3 handles r and returns true if r is a request from an S3
184 // client, otherwise it returns false.
185 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
187 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
188 split := strings.SplitN(auth[4:], ":", 2)
190 http.Error(w, "malformed Authorization header", http.StatusUnauthorized)
194 } else if strings.HasPrefix(auth, s3SignAlgorithm+" ") {
195 t, err := h.checks3signature(r)
197 http.Error(w, "signature verification failed: "+err.Error(), http.StatusForbidden)
205 _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
207 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
212 fs := client.SiteFileSystem(kc)
213 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
215 objectNameGiven := strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
218 case r.Method == http.MethodGet && !objectNameGiven:
219 // Path is "/{uuid}" or "/{uuid}/", has no object name
220 if _, ok := r.URL.Query()["versioning"]; ok {
221 // GetBucketVersioning
222 w.Header().Set("Content-Type", "application/xml")
223 io.WriteString(w, xml.Header)
224 fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
230 case r.Method == http.MethodGet || r.Method == http.MethodHead:
231 fspath := "/by_id" + r.URL.Path
232 fi, err := fs.Stat(fspath)
233 if r.Method == "HEAD" && !objectNameGiven {
235 if err == nil && fi.IsDir() {
236 w.WriteHeader(http.StatusOK)
237 } else if os.IsNotExist(err) {
238 w.WriteHeader(http.StatusNotFound)
240 http.Error(w, err.Error(), http.StatusBadGateway)
244 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Config.cluster.Collections.S3FolderObjects {
245 w.Header().Set("Content-Type", "application/x-directory")
246 w.WriteHeader(http.StatusOK)
249 if os.IsNotExist(err) ||
250 (err != nil && err.Error() == "not a directory") ||
251 (fi != nil && fi.IsDir()) {
252 http.Error(w, "not found", http.StatusNotFound)
255 // shallow copy r, and change URL path
258 http.FileServer(fs).ServeHTTP(w, &r)
260 case r.Method == http.MethodPut:
261 if !objectNameGiven {
262 http.Error(w, "missing object name in PUT request", http.StatusBadRequest)
265 fspath := "by_id" + r.URL.Path
267 if strings.HasSuffix(fspath, "/") {
268 if !h.Config.cluster.Collections.S3FolderObjects {
269 http.Error(w, "invalid object name: trailing slash", http.StatusBadRequest)
272 n, err := r.Body.Read(make([]byte, 1))
273 if err != nil && err != io.EOF {
274 http.Error(w, fmt.Sprintf("error reading request body: %s", err), http.StatusInternalServerError)
277 http.Error(w, "cannot create object with trailing '/' char unless content is empty", http.StatusBadRequest)
279 } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
280 http.Error(w, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", http.StatusBadRequest)
283 // Given PUT "foo/bar/", we'll use "foo/bar/."
284 // in the "ensure parents exist" block below,
285 // and then we'll be done.
289 fi, err := fs.Stat(fspath)
290 if err != nil && err.Error() == "not a directory" {
291 // requested foo/bar, but foo is a file
292 http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
295 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
296 // requested foo/bar/, but foo/bar is a file
297 http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
300 // create missing parent/intermediate directories, if any
301 for i, c := range fspath {
302 if i > 0 && c == '/' {
304 if strings.HasSuffix(dir, "/") {
305 err = errors.New("invalid object name (consecutive '/' chars)")
306 http.Error(w, err.Error(), http.StatusBadRequest)
309 err = fs.Mkdir(dir, 0755)
310 if err == arvados.ErrInvalidArgument {
311 // Cannot create a directory
313 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
314 http.Error(w, err.Error(), http.StatusBadRequest)
316 } else if err != nil && !os.IsExist(err) {
317 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
318 http.Error(w, err.Error(), http.StatusInternalServerError)
324 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
325 if os.IsNotExist(err) {
326 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
329 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
330 http.Error(w, err.Error(), http.StatusBadRequest)
334 _, err = io.Copy(f, r.Body)
336 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
337 http.Error(w, err.Error(), http.StatusBadGateway)
342 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
343 http.Error(w, err.Error(), http.StatusBadGateway)
349 err = fmt.Errorf("sync failed: %w", err)
350 http.Error(w, err.Error(), http.StatusInternalServerError)
353 w.WriteHeader(http.StatusOK)
355 case r.Method == http.MethodDelete:
356 if !objectNameGiven || r.URL.Path == "/" {
357 http.Error(w, "missing object name in DELETE request", http.StatusBadRequest)
360 fspath := "by_id" + r.URL.Path
361 if strings.HasSuffix(fspath, "/") {
362 fspath = strings.TrimSuffix(fspath, "/")
363 fi, err := fs.Stat(fspath)
364 if os.IsNotExist(err) {
365 w.WriteHeader(http.StatusNoContent)
367 } else if err != nil {
368 http.Error(w, err.Error(), http.StatusInternalServerError)
370 } else if !fi.IsDir() {
371 // if "foo" exists and is a file, then
372 // "foo/" doesn't exist, so we say
373 // delete was successful.
374 w.WriteHeader(http.StatusNoContent)
377 } else if fi, err := fs.Stat(fspath); err == nil && fi.IsDir() {
378 // if "foo" is a dir, it is visible via S3
379 // only as "foo/", not "foo" -- so we leave
380 // the dir alone and return 204 to indicate
381 // that "foo" does not exist.
382 w.WriteHeader(http.StatusNoContent)
385 err = fs.Remove(fspath)
386 if os.IsNotExist(err) {
387 w.WriteHeader(http.StatusNoContent)
391 err = fmt.Errorf("rm failed: %w", err)
392 http.Error(w, err.Error(), http.StatusBadRequest)
397 err = fmt.Errorf("sync failed: %w", err)
398 http.Error(w, err.Error(), http.StatusInternalServerError)
401 w.WriteHeader(http.StatusNoContent)
404 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
409 // Call fn on the given path (directory) and its contents, in
410 // lexicographic order.
412 // If isRoot==true and path is not a directory, return nil.
414 // If fn returns filepath.SkipDir when called on a directory, don't
415 // descend into that directory.
416 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
418 fi, err := fs.Stat(path)
419 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
421 } else if err != nil {
425 if err == filepath.SkipDir {
427 } else if err != nil {
431 f, err := fs.Open(path)
432 if os.IsNotExist(err) && isRoot {
434 } else if err != nil {
435 return fmt.Errorf("open %q: %w", path, err)
441 fis, err := f.Readdir(-1)
445 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
446 for _, fi := range fis {
447 err = fn(path+"/"+fi.Name(), fi)
448 if err == filepath.SkipDir {
450 } else if err != nil {
454 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
463 var errDone = errors.New("done")
465 func (h *handler) s3list(w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
473 params.bucket = strings.SplitN(r.URL.Path[1:], "/", 2)[0]
474 params.delimiter = r.FormValue("delimiter")
475 params.marker = r.FormValue("marker")
476 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
477 params.maxKeys = int(mk)
479 params.maxKeys = s3MaxKeys
481 params.prefix = r.FormValue("prefix")
483 bucketdir := "by_id/" + params.bucket
484 // walkpath is the directory (relative to bucketdir) we need
485 // to walk: the innermost directory that is guaranteed to
486 // contain all paths that have the requested prefix. Examples:
487 // prefix "foo/bar" => walkpath "foo"
488 // prefix "foo/bar/" => walkpath "foo/bar"
489 // prefix "foo" => walkpath ""
490 // prefix "" => walkpath ""
491 walkpath := params.prefix
492 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
493 walkpath = walkpath[:cut]
498 type commonPrefix struct {
501 type listResp struct {
502 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
504 // s3.ListResp marshals an empty tag when
505 // CommonPrefixes is nil, which confuses some clients.
506 // Fix by using this nested struct instead.
507 CommonPrefixes []commonPrefix
508 // Similarly, we need omitempty here, because an empty
509 // tag confuses some clients (e.g.,
510 // github.com/aws/aws-sdk-net never terminates its
512 NextMarker string `xml:"NextMarker,omitempty"`
513 // ListObjectsV2 has a KeyCount response field.
517 ListResp: s3.ListResp{
518 Name: strings.SplitN(r.URL.Path[1:], "/", 2)[0],
519 Prefix: params.prefix,
520 Delimiter: params.delimiter,
521 Marker: params.marker,
522 MaxKeys: params.maxKeys,
525 commonPrefixes := map[string]bool{}
526 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
527 if path == bucketdir {
530 path = path[len(bucketdir)+1:]
531 filesize := fi.Size()
536 if len(path) <= len(params.prefix) {
537 if path > params.prefix[:len(path)] {
538 // with prefix "foobar", walking "fooz" means we're done
541 if path < params.prefix[:len(path)] {
542 // with prefix "foobar", walking "foobag" is pointless
543 return filepath.SkipDir
545 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
546 // with prefix "foo/bar", walking "fo"
547 // is pointless (but walking "foo" or
548 // "foo/bar" is necessary)
549 return filepath.SkipDir
551 if len(path) < len(params.prefix) {
552 // can't skip anything, and this entry
553 // isn't in the results, so just
558 if path[:len(params.prefix)] > params.prefix {
559 // with prefix "foobar", nothing we
560 // see after "foozzz" is relevant
564 if path < params.marker || path < params.prefix {
567 if fi.IsDir() && !h.Config.cluster.Collections.S3FolderObjects {
568 // Note we don't add anything to
569 // commonPrefixes here even if delimiter is
570 // "/". We descend into the directory, and
571 // return a commonPrefix only if we end up
572 // finding a regular file inside it.
575 if params.delimiter != "" {
576 idx := strings.Index(path[len(params.prefix):], params.delimiter)
578 // with prefix "foobar" and delimiter
579 // "z", when we hit "foobar/baz", we
580 // add "/baz" to commonPrefixes and
582 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
583 return filepath.SkipDir
586 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
587 resp.IsTruncated = true
588 if params.delimiter != "" {
589 resp.NextMarker = path
593 resp.Contents = append(resp.Contents, s3.Key{
595 LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
600 if err != nil && err != errDone {
601 http.Error(w, err.Error(), http.StatusInternalServerError)
604 if params.delimiter != "" {
605 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
606 for prefix := range commonPrefixes {
607 resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
609 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
611 resp.KeyCount = len(resp.Contents)
612 w.Header().Set("Content-Type", "application/xml")
613 io.WriteString(w, xml.Header)
614 if err := xml.NewEncoder(w).Encode(resp); err != nil {
615 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")