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 func s3ErrorResponse(w http.ResponseWriter, s3code string, message string, resource string, code int) {
193 w.Header().Set("Content-Type", "application/xml")
194 w.Header().Set("X-Content-Type-Options", "nosniff")
196 var errstruct struct {
202 errstruct.Code = s3code
203 errstruct.Message = message
204 errstruct.Resource = resource
205 errstruct.RequestId = ""
206 enc := xml.NewEncoder(w)
207 fmt.Fprint(w, xml.Header)
208 enc.EncodeElement(errstruct, xml.StartElement{Name: xml.Name{Local: "Error"}})
211 var NoSuchKey = "NoSuchKey"
212 var NoSuchBucket = "NoSuchBucket"
213 var InvalidArgument = "InvalidArgument"
214 var InternalError = "InternalError"
215 var UnauthorizedAccess = "UnauthorizedAccess"
216 var InvalidRequest = "InvalidRequest"
217 var SignatureDoesNotMatch = "SignatureDoesNotMatch"
219 // serveS3 handles r and returns true if r is a request from an S3
220 // client, otherwise it returns false.
221 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
223 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
224 split := strings.SplitN(auth[4:], ":", 2)
226 s3ErrorResponse(w, InvalidRequest, "malformed Authorization header", r.URL.Path, http.StatusUnauthorized)
229 token = unescapeKey(split[0])
230 } else if strings.HasPrefix(auth, s3SignAlgorithm+" ") {
231 t, err := h.checks3signature(r)
233 s3ErrorResponse(w, SignatureDoesNotMatch, "signature verification failed: "+err.Error(), r.URL.Path, http.StatusForbidden)
241 _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
243 s3ErrorResponse(w, InternalError, "Pool failed: "+h.clientPool.Err().Error(), r.URL.Path, http.StatusInternalServerError)
248 fs := client.SiteFileSystem(kc)
249 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
251 var objectNameGiven bool
253 if id := parseCollectionIDFromDNSName(r.Host); id != "" {
255 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 0
257 objectNameGiven = strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
262 case r.Method == http.MethodGet && !objectNameGiven:
263 // Path is "/{uuid}" or "/{uuid}/", has no object name
264 if _, ok := r.URL.Query()["versioning"]; ok {
265 // GetBucketVersioning
266 w.Header().Set("Content-Type", "application/xml")
267 io.WriteString(w, xml.Header)
268 fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
274 case r.Method == http.MethodGet || r.Method == http.MethodHead:
275 fi, err := fs.Stat(fspath)
276 if r.Method == "HEAD" && !objectNameGiven {
278 if err == nil && fi.IsDir() {
279 w.WriteHeader(http.StatusOK)
280 } else if os.IsNotExist(err) {
281 s3ErrorResponse(w, NoSuchBucket, "The specified bucket does not exist.", r.URL.Path, http.StatusNotFound)
283 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
287 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Config.cluster.Collections.S3FolderObjects {
288 w.Header().Set("Content-Type", "application/x-directory")
289 w.WriteHeader(http.StatusOK)
292 if os.IsNotExist(err) ||
293 (err != nil && err.Error() == "not a directory") ||
294 (fi != nil && fi.IsDir()) {
295 s3ErrorResponse(w, NoSuchKey, "The specified key does not exist.", r.URL.Path, http.StatusNotFound)
298 // shallow copy r, and change URL path
301 http.FileServer(fs).ServeHTTP(w, &r)
303 case r.Method == http.MethodPut:
304 if !objectNameGiven {
305 s3ErrorResponse(w, InvalidArgument, "Missing object name in PUT request.", r.URL.Path, http.StatusBadRequest)
309 if strings.HasSuffix(fspath, "/") {
310 if !h.Config.cluster.Collections.S3FolderObjects {
311 s3ErrorResponse(w, InvalidArgument, "invalid object name: trailing slash", r.URL.Path, http.StatusBadRequest)
314 n, err := r.Body.Read(make([]byte, 1))
315 if err != nil && err != io.EOF {
316 s3ErrorResponse(w, InternalError, fmt.Sprintf("error reading request body: %s", err), r.URL.Path, http.StatusInternalServerError)
319 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless content is empty", r.URL.Path, http.StatusBadRequest)
321 } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
322 s3ErrorResponse(w, InvalidArgument, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", r.URL.Path, http.StatusBadRequest)
325 // Given PUT "foo/bar/", we'll use "foo/bar/."
326 // in the "ensure parents exist" block below,
327 // and then we'll be done.
331 fi, err := fs.Stat(fspath)
332 if err != nil && err.Error() == "not a directory" {
333 // requested foo/bar, but foo is a file
334 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
337 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
338 // requested foo/bar/, but foo/bar is a file
339 s3ErrorResponse(w, InvalidArgument, "object name conflicts with existing object", r.URL.Path, http.StatusBadRequest)
342 // create missing parent/intermediate directories, if any
343 for i, c := range fspath {
344 if i > 0 && c == '/' {
346 if strings.HasSuffix(dir, "/") {
347 err = errors.New("invalid object name (consecutive '/' chars)")
348 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
351 err = fs.Mkdir(dir, 0755)
352 if err == arvados.ErrInvalidArgument {
353 // Cannot create a directory
355 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
356 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
358 } else if err != nil && !os.IsExist(err) {
359 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
360 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
366 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
367 if os.IsNotExist(err) {
368 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
371 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
372 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
376 _, err = io.Copy(f, r.Body)
378 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
379 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
384 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
385 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusBadGateway)
391 err = fmt.Errorf("sync failed: %w", err)
392 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
395 w.WriteHeader(http.StatusOK)
397 case r.Method == http.MethodDelete:
398 if !objectNameGiven || r.URL.Path == "/" {
399 s3ErrorResponse(w, InvalidArgument, "missing object name in DELETE request", r.URL.Path, http.StatusBadRequest)
402 if strings.HasSuffix(fspath, "/") {
403 fspath = strings.TrimSuffix(fspath, "/")
404 fi, err := fs.Stat(fspath)
405 if os.IsNotExist(err) {
406 w.WriteHeader(http.StatusNoContent)
408 } else if err != nil {
409 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
411 } else if !fi.IsDir() {
412 // if "foo" exists and is a file, then
413 // "foo/" doesn't exist, so we say
414 // delete was successful.
415 w.WriteHeader(http.StatusNoContent)
418 } else if fi, err := fs.Stat(fspath); err == nil && fi.IsDir() {
419 // if "foo" is a dir, it is visible via S3
420 // only as "foo/", not "foo" -- so we leave
421 // the dir alone and return 204 to indicate
422 // that "foo" does not exist.
423 w.WriteHeader(http.StatusNoContent)
426 err = fs.Remove(fspath)
427 if os.IsNotExist(err) {
428 w.WriteHeader(http.StatusNoContent)
432 err = fmt.Errorf("rm failed: %w", err)
433 s3ErrorResponse(w, InvalidArgument, err.Error(), r.URL.Path, http.StatusBadRequest)
438 err = fmt.Errorf("sync failed: %w", err)
439 s3ErrorResponse(w, InternalError, err.Error(), r.URL.Path, http.StatusInternalServerError)
442 w.WriteHeader(http.StatusNoContent)
445 s3ErrorResponse(w, InvalidRequest, "method not allowed", r.URL.Path, http.StatusMethodNotAllowed)
451 // Call fn on the given path (directory) and its contents, in
452 // lexicographic order.
454 // If isRoot==true and path is not a directory, return nil.
456 // If fn returns filepath.SkipDir when called on a directory, don't
457 // descend into that directory.
458 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
460 fi, err := fs.Stat(path)
461 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
463 } else if err != nil {
467 if err == filepath.SkipDir {
469 } else if err != nil {
473 f, err := fs.Open(path)
474 if os.IsNotExist(err) && isRoot {
476 } else if err != nil {
477 return fmt.Errorf("open %q: %w", path, err)
483 fis, err := f.Readdir(-1)
487 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
488 for _, fi := range fis {
489 err = fn(path+"/"+fi.Name(), fi)
490 if err == filepath.SkipDir {
492 } else if err != nil {
496 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
505 var errDone = errors.New("done")
507 func (h *handler) s3list(w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
515 params.bucket = strings.SplitN(r.URL.Path[1:], "/", 2)[0]
516 params.delimiter = r.FormValue("delimiter")
517 params.marker = r.FormValue("marker")
518 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
519 params.maxKeys = int(mk)
521 params.maxKeys = s3MaxKeys
523 params.prefix = r.FormValue("prefix")
525 bucketdir := "by_id/" + params.bucket
526 // walkpath is the directory (relative to bucketdir) we need
527 // to walk: the innermost directory that is guaranteed to
528 // contain all paths that have the requested prefix. Examples:
529 // prefix "foo/bar" => walkpath "foo"
530 // prefix "foo/bar/" => walkpath "foo/bar"
531 // prefix "foo" => walkpath ""
532 // prefix "" => walkpath ""
533 walkpath := params.prefix
534 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
535 walkpath = walkpath[:cut]
540 type commonPrefix struct {
543 type listResp struct {
544 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
546 // s3.ListResp marshals an empty tag when
547 // CommonPrefixes is nil, which confuses some clients.
548 // Fix by using this nested struct instead.
549 CommonPrefixes []commonPrefix
550 // Similarly, we need omitempty here, because an empty
551 // tag confuses some clients (e.g.,
552 // github.com/aws/aws-sdk-net never terminates its
554 NextMarker string `xml:"NextMarker,omitempty"`
555 // ListObjectsV2 has a KeyCount response field.
559 ListResp: s3.ListResp{
560 Name: strings.SplitN(r.URL.Path[1:], "/", 2)[0],
561 Prefix: params.prefix,
562 Delimiter: params.delimiter,
563 Marker: params.marker,
564 MaxKeys: params.maxKeys,
567 commonPrefixes := map[string]bool{}
568 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
569 if path == bucketdir {
572 path = path[len(bucketdir)+1:]
573 filesize := fi.Size()
578 if len(path) <= len(params.prefix) {
579 if path > params.prefix[:len(path)] {
580 // with prefix "foobar", walking "fooz" means we're done
583 if path < params.prefix[:len(path)] {
584 // with prefix "foobar", walking "foobag" is pointless
585 return filepath.SkipDir
587 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
588 // with prefix "foo/bar", walking "fo"
589 // is pointless (but walking "foo" or
590 // "foo/bar" is necessary)
591 return filepath.SkipDir
593 if len(path) < len(params.prefix) {
594 // can't skip anything, and this entry
595 // isn't in the results, so just
600 if path[:len(params.prefix)] > params.prefix {
601 // with prefix "foobar", nothing we
602 // see after "foozzz" is relevant
606 if path < params.marker || path < params.prefix {
609 if fi.IsDir() && !h.Config.cluster.Collections.S3FolderObjects {
610 // Note we don't add anything to
611 // commonPrefixes here even if delimiter is
612 // "/". We descend into the directory, and
613 // return a commonPrefix only if we end up
614 // finding a regular file inside it.
617 if params.delimiter != "" {
618 idx := strings.Index(path[len(params.prefix):], params.delimiter)
620 // with prefix "foobar" and delimiter
621 // "z", when we hit "foobar/baz", we
622 // add "/baz" to commonPrefixes and
624 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
625 return filepath.SkipDir
628 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
629 resp.IsTruncated = true
630 if params.delimiter != "" {
631 resp.NextMarker = path
635 resp.Contents = append(resp.Contents, s3.Key{
637 LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
642 if err != nil && err != errDone {
643 http.Error(w, err.Error(), http.StatusInternalServerError)
646 if params.delimiter != "" {
647 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
648 for prefix := range commonPrefixes {
649 resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
651 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
653 resp.KeyCount = len(resp.Contents)
654 w.Header().Set("Content-Type", "application/xml")
655 io.WriteString(w, xml.Header)
656 if err := xml.NewEncoder(w).Encode(resp); err != nil {
657 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")