1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
23 "git.arvados.org/arvados.git/sdk/go/arvados"
24 "git.arvados.org/arvados.git/sdk/go/ctxlog"
25 "github.com/AdRoll/goamz/s3"
30 s3SignAlgorithm = "AWS4-HMAC-SHA256"
31 s3MaxClockSkew = 5 * time.Minute
34 func hmacstring(msg string, key []byte) []byte {
35 h := hmac.New(sha256.New, key)
36 io.WriteString(h, msg)
40 // Signing key for given secret key and request attrs.
41 func s3signatureKey(key, datestamp, regionName, serviceName string) []byte {
42 return hmacstring("aws4_request",
43 hmacstring(serviceName,
44 hmacstring(regionName,
45 hmacstring(datestamp, []byte("AWS4"+key)))))
48 // Canonical query string for S3 V4 signature: sorted keys, spaces
49 // escaped as %20 instead of +, keyvalues joined with &.
50 func s3querystring(u *url.URL) string {
51 keys := make([]string, 0, len(u.Query()))
52 values := make(map[string]string, len(u.Query()))
53 for k, vs := range u.Query() {
54 k = strings.Replace(url.QueryEscape(k), "+", "%20", -1)
55 keys = append(keys, k)
56 for _, v := range vs {
57 v = strings.Replace(url.QueryEscape(v), "+", "%20", -1)
61 values[k] += k + "=" + v
65 for i, k := range keys {
68 return strings.Join(keys, "&")
71 func s3signature(alg, secretKey, scope, signedHeaders string, r *http.Request) (string, error) {
72 timefmt, timestr := "20060102T150405Z", r.Header.Get("X-Amz-Date")
74 timefmt, timestr = time.RFC1123, r.Header.Get("Date")
76 t, err := time.Parse(timefmt, timestr)
78 return "", fmt.Errorf("invalid timestamp %q: %s", timestr, err)
80 if skew := time.Now().Sub(t); skew < -s3MaxClockSkew || skew > s3MaxClockSkew {
81 return "", errors.New("exceeded max clock skew")
84 var canonicalHeaders string
85 for _, h := range strings.Split(signedHeaders, ";") {
87 canonicalHeaders += h + ":" + r.URL.Host + "\n"
89 canonicalHeaders += h + ":" + r.Header.Get(h) + "\n"
93 crhash := sha256.New()
94 fmt.Fprintf(crhash, "%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"))
95 crdigest := fmt.Sprintf("%x", crhash.Sum(nil))
97 payload := fmt.Sprintf("%s\n%s\n%s\n%s", alg, r.Header.Get("X-Amz-Date"), scope, crdigest)
99 // scope is {datestamp}/{region}/{service}/aws4_request
100 drs := strings.Split(scope, "/")
102 return "", fmt.Errorf("invalid scope %q", scope)
105 key := s3signatureKey(secretKey, drs[0], drs[1], drs[2])
106 h := hmac.New(sha256.New, key)
107 h.Write([]byte(payload))
108 return fmt.Sprintf("%x", h.Sum(nil)), nil
111 // checks3signature verifies the given S3 V4 signature and returns the
112 // Arvados token that corresponds to the given accessKey. An error is
113 // returned if accessKey is not a valid token UUID or the signature
115 func (h *handler) checks3signature(r *http.Request) (string, error) {
116 var key, scope, signedHeaders, signature string
117 authstring := strings.TrimPrefix(r.Header.Get("Authorization"), s3SignAlgorithm+" ")
118 for _, cmpt := range strings.Split(authstring, ",") {
119 cmpt = strings.TrimSpace(cmpt)
120 split := strings.SplitN(cmpt, "=", 2)
122 case len(split) != 2:
124 case split[0] == "Credential":
125 keyandscope := strings.SplitN(split[1], "/", 2)
126 if len(keyandscope) == 2 {
127 key, scope = keyandscope[0], keyandscope[1]
129 case split[0] == "SignedHeaders":
130 signedHeaders = split[1]
131 case split[0] == "Signature":
136 client := (&arvados.Client{
137 APIHost: h.Config.cluster.Services.Controller.ExternalURL.Host,
138 Insecure: h.Config.cluster.TLS.Insecure,
139 }).WithRequestID(r.Header.Get("X-Request-Id"))
140 var aca arvados.APIClientAuthorization
141 ctx := arvados.ContextWithAuthorization(r.Context(), "Bearer "+h.Config.cluster.SystemRootToken)
142 err := client.RequestAndDecodeContext(ctx, &aca, "GET", "arvados/v1/api_client_authorizations/"+key, nil, nil)
144 ctxlog.FromContext(ctx).WithError(err).WithField("UUID", key).Info("token lookup failed")
145 return "", errors.New("invalid access key")
147 expect, err := s3signature(s3SignAlgorithm, aca.APIToken, scope, signedHeaders, r)
150 } else if expect != signature {
151 return "", errors.New("signature does not match")
153 return aca.TokenV2(), nil
156 // serveS3 handles r and returns true if r is a request from an S3
157 // client, otherwise it returns false.
158 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
160 if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
161 split := strings.SplitN(auth[4:], ":", 2)
163 http.Error(w, "malformed Authorization header", http.StatusUnauthorized)
167 } else if strings.HasPrefix(auth, s3SignAlgorithm+" ") {
168 t, err := h.checks3signature(r)
170 http.Error(w, "signature verification failed: "+err.Error(), http.StatusForbidden)
178 _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
180 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
185 fs := client.SiteFileSystem(kc)
186 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
188 objectNameGiven := strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
191 case r.Method == http.MethodGet && !objectNameGiven:
192 // Path is "/{uuid}" or "/{uuid}/", has no object name
193 if _, ok := r.URL.Query()["versioning"]; ok {
194 // GetBucketVersioning
195 w.Header().Set("Content-Type", "application/xml")
196 io.WriteString(w, xml.Header)
197 fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
203 case r.Method == http.MethodGet || r.Method == http.MethodHead:
204 fspath := "/by_id" + r.URL.Path
205 fi, err := fs.Stat(fspath)
206 if r.Method == "HEAD" && !objectNameGiven {
208 if err == nil && fi.IsDir() {
209 w.WriteHeader(http.StatusOK)
210 } else if os.IsNotExist(err) {
211 w.WriteHeader(http.StatusNotFound)
213 http.Error(w, err.Error(), http.StatusBadGateway)
217 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Config.cluster.Collections.S3FolderObjects {
218 w.Header().Set("Content-Type", "application/x-directory")
219 w.WriteHeader(http.StatusOK)
222 if os.IsNotExist(err) ||
223 (err != nil && err.Error() == "not a directory") ||
224 (fi != nil && fi.IsDir()) {
225 http.Error(w, "not found", http.StatusNotFound)
228 // shallow copy r, and change URL path
231 http.FileServer(fs).ServeHTTP(w, &r)
233 case r.Method == http.MethodPut:
234 if !objectNameGiven {
235 http.Error(w, "missing object name in PUT request", http.StatusBadRequest)
238 fspath := "by_id" + r.URL.Path
240 if strings.HasSuffix(fspath, "/") {
241 if !h.Config.cluster.Collections.S3FolderObjects {
242 http.Error(w, "invalid object name: trailing slash", http.StatusBadRequest)
245 n, err := r.Body.Read(make([]byte, 1))
246 if err != nil && err != io.EOF {
247 http.Error(w, fmt.Sprintf("error reading request body: %s", err), http.StatusInternalServerError)
250 http.Error(w, "cannot create object with trailing '/' char unless content is empty", http.StatusBadRequest)
252 } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
253 http.Error(w, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", http.StatusBadRequest)
256 // Given PUT "foo/bar/", we'll use "foo/bar/."
257 // in the "ensure parents exist" block below,
258 // and then we'll be done.
262 fi, err := fs.Stat(fspath)
263 if err != nil && err.Error() == "not a directory" {
264 // requested foo/bar, but foo is a file
265 http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
268 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
269 // requested foo/bar/, but foo/bar is a file
270 http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
273 // create missing parent/intermediate directories, if any
274 for i, c := range fspath {
275 if i > 0 && c == '/' {
277 if strings.HasSuffix(dir, "/") {
278 err = errors.New("invalid object name (consecutive '/' chars)")
279 http.Error(w, err.Error(), http.StatusBadRequest)
282 err = fs.Mkdir(dir, 0755)
283 if err == arvados.ErrInvalidArgument {
284 // Cannot create a directory
286 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
287 http.Error(w, err.Error(), http.StatusBadRequest)
289 } else if err != nil && !os.IsExist(err) {
290 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
291 http.Error(w, err.Error(), http.StatusInternalServerError)
297 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
298 if os.IsNotExist(err) {
299 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
302 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
303 http.Error(w, err.Error(), http.StatusBadRequest)
307 _, err = io.Copy(f, r.Body)
309 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
310 http.Error(w, err.Error(), http.StatusBadGateway)
315 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
316 http.Error(w, err.Error(), http.StatusBadGateway)
322 err = fmt.Errorf("sync failed: %w", err)
323 http.Error(w, err.Error(), http.StatusInternalServerError)
326 w.WriteHeader(http.StatusOK)
328 case r.Method == http.MethodDelete:
329 if !objectNameGiven || r.URL.Path == "/" {
330 http.Error(w, "missing object name in DELETE request", http.StatusBadRequest)
333 fspath := "by_id" + r.URL.Path
334 if strings.HasSuffix(fspath, "/") {
335 fspath = strings.TrimSuffix(fspath, "/")
336 fi, err := fs.Stat(fspath)
337 if os.IsNotExist(err) {
338 w.WriteHeader(http.StatusNoContent)
340 } else if err != nil {
341 http.Error(w, err.Error(), http.StatusInternalServerError)
343 } else if !fi.IsDir() {
344 // if "foo" exists and is a file, then
345 // "foo/" doesn't exist, so we say
346 // delete was successful.
347 w.WriteHeader(http.StatusNoContent)
350 } else if fi, err := fs.Stat(fspath); err == nil && fi.IsDir() {
351 // if "foo" is a dir, it is visible via S3
352 // only as "foo/", not "foo" -- so we leave
353 // the dir alone and return 204 to indicate
354 // that "foo" does not exist.
355 w.WriteHeader(http.StatusNoContent)
358 err = fs.Remove(fspath)
359 if os.IsNotExist(err) {
360 w.WriteHeader(http.StatusNoContent)
364 err = fmt.Errorf("rm failed: %w", err)
365 http.Error(w, err.Error(), http.StatusBadRequest)
370 err = fmt.Errorf("sync failed: %w", err)
371 http.Error(w, err.Error(), http.StatusInternalServerError)
374 w.WriteHeader(http.StatusNoContent)
377 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
382 // Call fn on the given path (directory) and its contents, in
383 // lexicographic order.
385 // If isRoot==true and path is not a directory, return nil.
387 // If fn returns filepath.SkipDir when called on a directory, don't
388 // descend into that directory.
389 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
391 fi, err := fs.Stat(path)
392 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
394 } else if err != nil {
398 if err == filepath.SkipDir {
400 } else if err != nil {
404 f, err := fs.Open(path)
405 if os.IsNotExist(err) && isRoot {
407 } else if err != nil {
408 return fmt.Errorf("open %q: %w", path, err)
414 fis, err := f.Readdir(-1)
418 sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
419 for _, fi := range fis {
420 err = fn(path+"/"+fi.Name(), fi)
421 if err == filepath.SkipDir {
423 } else if err != nil {
427 err = walkFS(fs, path+"/"+fi.Name(), false, fn)
436 var errDone = errors.New("done")
438 func (h *handler) s3list(w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
446 params.bucket = strings.SplitN(r.URL.Path[1:], "/", 2)[0]
447 params.delimiter = r.FormValue("delimiter")
448 params.marker = r.FormValue("marker")
449 if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
450 params.maxKeys = int(mk)
452 params.maxKeys = s3MaxKeys
454 params.prefix = r.FormValue("prefix")
456 bucketdir := "by_id/" + params.bucket
457 // walkpath is the directory (relative to bucketdir) we need
458 // to walk: the innermost directory that is guaranteed to
459 // contain all paths that have the requested prefix. Examples:
460 // prefix "foo/bar" => walkpath "foo"
461 // prefix "foo/bar/" => walkpath "foo/bar"
462 // prefix "foo" => walkpath ""
463 // prefix "" => walkpath ""
464 walkpath := params.prefix
465 if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
466 walkpath = walkpath[:cut]
471 type commonPrefix struct {
474 type listResp struct {
475 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
477 // s3.ListResp marshals an empty tag when
478 // CommonPrefixes is nil, which confuses some clients.
479 // Fix by using this nested struct instead.
480 CommonPrefixes []commonPrefix
481 // Similarly, we need omitempty here, because an empty
482 // tag confuses some clients (e.g.,
483 // github.com/aws/aws-sdk-net never terminates its
485 NextMarker string `xml:"NextMarker,omitempty"`
488 ListResp: s3.ListResp{
489 Name: strings.SplitN(r.URL.Path[1:], "/", 2)[0],
490 Prefix: params.prefix,
491 Delimiter: params.delimiter,
492 Marker: params.marker,
493 MaxKeys: params.maxKeys,
496 commonPrefixes := map[string]bool{}
497 err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
498 if path == bucketdir {
501 path = path[len(bucketdir)+1:]
502 filesize := fi.Size()
507 if len(path) <= len(params.prefix) {
508 if path > params.prefix[:len(path)] {
509 // with prefix "foobar", walking "fooz" means we're done
512 if path < params.prefix[:len(path)] {
513 // with prefix "foobar", walking "foobag" is pointless
514 return filepath.SkipDir
516 if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
517 // with prefix "foo/bar", walking "fo"
518 // is pointless (but walking "foo" or
519 // "foo/bar" is necessary)
520 return filepath.SkipDir
522 if len(path) < len(params.prefix) {
523 // can't skip anything, and this entry
524 // isn't in the results, so just
529 if path[:len(params.prefix)] > params.prefix {
530 // with prefix "foobar", nothing we
531 // see after "foozzz" is relevant
535 if path < params.marker || path < params.prefix {
538 if fi.IsDir() && !h.Config.cluster.Collections.S3FolderObjects {
539 // Note we don't add anything to
540 // commonPrefixes here even if delimiter is
541 // "/". We descend into the directory, and
542 // return a commonPrefix only if we end up
543 // finding a regular file inside it.
546 if params.delimiter != "" {
547 idx := strings.Index(path[len(params.prefix):], params.delimiter)
549 // with prefix "foobar" and delimiter
550 // "z", when we hit "foobar/baz", we
551 // add "/baz" to commonPrefixes and
553 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
554 return filepath.SkipDir
557 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
558 resp.IsTruncated = true
559 if params.delimiter != "" {
560 resp.NextMarker = path
564 resp.Contents = append(resp.Contents, s3.Key{
566 LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
571 if err != nil && err != errDone {
572 http.Error(w, err.Error(), http.StatusInternalServerError)
575 if params.delimiter != "" {
576 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
577 for prefix := range commonPrefixes {
578 resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
580 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
582 w.Header().Set("Content-Type", "application/xml")
583 io.WriteString(w, xml.Header)
584 if err := xml.NewEncoder(w).Encode(resp); err != nil {
585 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")