16809: Accept S3 requests with V4 signatures.
[arvados.git] / services / keep-web / s3.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "crypto/hmac"
9         "crypto/sha256"
10         "encoding/xml"
11         "errors"
12         "fmt"
13         "io"
14         "net/http"
15         "net/url"
16         "os"
17         "path/filepath"
18         "sort"
19         "strconv"
20         "strings"
21         "time"
22
23         "git.arvados.org/arvados.git/sdk/go/arvados"
24         "git.arvados.org/arvados.git/sdk/go/ctxlog"
25         "github.com/AdRoll/goamz/s3"
26 )
27
28 const (
29         s3MaxKeys       = 1000
30         s3SignAlgorithm = "AWS4-HMAC-SHA256"
31         s3MaxClockSkew  = 5 * time.Minute
32 )
33
34 func hmacstring(msg string, key []byte) []byte {
35         h := hmac.New(sha256.New, key)
36         io.WriteString(h, msg)
37         return h.Sum(nil)
38 }
39
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)))))
46 }
47
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)
58                         if values[k] != "" {
59                                 values[k] += "&"
60                         }
61                         values[k] += k + "=" + v
62                 }
63         }
64         sort.Strings(keys)
65         for i, k := range keys {
66                 keys[i] = values[k]
67         }
68         return strings.Join(keys, "&")
69 }
70
71 func s3signature(alg, secretKey, scope, signedHeaders string, r *http.Request) (string, error) {
72         timefmt, timestr := "20060102T150405Z", r.Header.Get("X-Amz-Date")
73         if timestr == "" {
74                 timefmt, timestr = time.RFC1123, r.Header.Get("Date")
75         }
76         t, err := time.Parse(timefmt, timestr)
77         if err != nil {
78                 return "", fmt.Errorf("invalid timestamp %q: %s", timestr, err)
79         }
80         if skew := time.Now().Sub(t); skew < -s3MaxClockSkew || skew > s3MaxClockSkew {
81                 return "", errors.New("exceeded max clock skew")
82         }
83
84         var canonicalHeaders string
85         for _, h := range strings.Split(signedHeaders, ";") {
86                 if h == "host" {
87                         canonicalHeaders += h + ":" + r.URL.Host + "\n"
88                 } else {
89                         canonicalHeaders += h + ":" + r.Header.Get(h) + "\n"
90                 }
91         }
92
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))
96
97         payload := fmt.Sprintf("%s\n%s\n%s\n%s", alg, r.Header.Get("X-Amz-Date"), scope, crdigest)
98
99         // scope is {datestamp}/{region}/{service}/aws4_request
100         drs := strings.Split(scope, "/")
101         if len(drs) != 4 {
102                 return "", fmt.Errorf("invalid scope %q", scope)
103         }
104
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
109 }
110
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
114 // does not match.
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)
121                 switch {
122                 case len(split) != 2:
123                         // (?) ignore
124                 case split[0] == "Credential":
125                         keyandscope := strings.SplitN(split[1], "/", 2)
126                         if len(keyandscope) == 2 {
127                                 key, scope = keyandscope[0], keyandscope[1]
128                         }
129                 case split[0] == "SignedHeaders":
130                         signedHeaders = split[1]
131                 case split[0] == "Signature":
132                         signature = split[1]
133                 }
134         }
135
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)
143         if err != nil {
144                 ctxlog.FromContext(ctx).WithError(err).WithField("UUID", key).Info("token lookup failed")
145                 return "", errors.New("invalid access key")
146         }
147         expect, err := s3signature(s3SignAlgorithm, aca.APIToken, scope, signedHeaders, r)
148         if err != nil {
149                 return "", err
150         } else if expect != signature {
151                 return "", errors.New("signature does not match")
152         }
153         return aca.TokenV2(), nil
154 }
155
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 {
159         var token string
160         if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
161                 split := strings.SplitN(auth[4:], ":", 2)
162                 if len(split) < 2 {
163                         http.Error(w, "malformed Authorization header", http.StatusUnauthorized)
164                         return true
165                 }
166                 token = split[0]
167         } else if strings.HasPrefix(auth, s3SignAlgorithm+" ") {
168                 t, err := h.checks3signature(r)
169                 if err != nil {
170                         http.Error(w, "signature verification failed: "+err.Error(), http.StatusForbidden)
171                         return true
172                 }
173                 token = t
174         } else {
175                 return false
176         }
177
178         _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
179         if err != nil {
180                 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
181                 return true
182         }
183         defer release()
184
185         fs := client.SiteFileSystem(kc)
186         fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
187
188         objectNameGiven := strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
189
190         switch {
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/"/>`)
198                 } else {
199                         // ListObjects
200                         h.s3list(w, r, fs)
201                 }
202                 return true
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 {
207                         // HeadBucket
208                         if err == nil && fi.IsDir() {
209                                 w.WriteHeader(http.StatusOK)
210                         } else if os.IsNotExist(err) {
211                                 w.WriteHeader(http.StatusNotFound)
212                         } else {
213                                 http.Error(w, err.Error(), http.StatusBadGateway)
214                         }
215                         return true
216                 }
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)
220                         return true
221                 }
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)
226                         return true
227                 }
228                 // shallow copy r, and change URL path
229                 r := *r
230                 r.URL.Path = fspath
231                 http.FileServer(fs).ServeHTTP(w, &r)
232                 return true
233         case r.Method == http.MethodPut:
234                 if !objectNameGiven {
235                         http.Error(w, "missing object name in PUT request", http.StatusBadRequest)
236                         return true
237                 }
238                 fspath := "by_id" + r.URL.Path
239                 var objectIsDir bool
240                 if strings.HasSuffix(fspath, "/") {
241                         if !h.Config.cluster.Collections.S3FolderObjects {
242                                 http.Error(w, "invalid object name: trailing slash", http.StatusBadRequest)
243                                 return true
244                         }
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)
248                                 return true
249                         } else if n > 0 {
250                                 http.Error(w, "cannot create object with trailing '/' char unless content is empty", http.StatusBadRequest)
251                                 return true
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)
254                                 return true
255                         }
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.
259                         fspath += "."
260                         objectIsDir = true
261                 }
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)
266                         return true
267                 }
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)
271                         return true
272                 }
273                 // create missing parent/intermediate directories, if any
274                 for i, c := range fspath {
275                         if i > 0 && c == '/' {
276                                 dir := fspath[:i]
277                                 if strings.HasSuffix(dir, "/") {
278                                         err = errors.New("invalid object name (consecutive '/' chars)")
279                                         http.Error(w, err.Error(), http.StatusBadRequest)
280                                         return true
281                                 }
282                                 err = fs.Mkdir(dir, 0755)
283                                 if err == arvados.ErrInvalidArgument {
284                                         // Cannot create a directory
285                                         // here.
286                                         err = fmt.Errorf("mkdir %q failed: %w", dir, err)
287                                         http.Error(w, err.Error(), http.StatusBadRequest)
288                                         return true
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)
292                                         return true
293                                 }
294                         }
295                 }
296                 if !objectIsDir {
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)
300                         }
301                         if err != nil {
302                                 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
303                                 http.Error(w, err.Error(), http.StatusBadRequest)
304                                 return true
305                         }
306                         defer f.Close()
307                         _, err = io.Copy(f, r.Body)
308                         if err != nil {
309                                 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
310                                 http.Error(w, err.Error(), http.StatusBadGateway)
311                                 return true
312                         }
313                         err = f.Close()
314                         if err != nil {
315                                 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
316                                 http.Error(w, err.Error(), http.StatusBadGateway)
317                                 return true
318                         }
319                 }
320                 err = fs.Sync()
321                 if err != nil {
322                         err = fmt.Errorf("sync failed: %w", err)
323                         http.Error(w, err.Error(), http.StatusInternalServerError)
324                         return true
325                 }
326                 w.WriteHeader(http.StatusOK)
327                 return true
328         case r.Method == http.MethodDelete:
329                 if !objectNameGiven || r.URL.Path == "/" {
330                         http.Error(w, "missing object name in DELETE request", http.StatusBadRequest)
331                         return true
332                 }
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)
339                                 return true
340                         } else if err != nil {
341                                 http.Error(w, err.Error(), http.StatusInternalServerError)
342                                 return true
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)
348                                 return true
349                         }
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)
356                         return true
357                 }
358                 err = fs.Remove(fspath)
359                 if os.IsNotExist(err) {
360                         w.WriteHeader(http.StatusNoContent)
361                         return true
362                 }
363                 if err != nil {
364                         err = fmt.Errorf("rm failed: %w", err)
365                         http.Error(w, err.Error(), http.StatusBadRequest)
366                         return true
367                 }
368                 err = fs.Sync()
369                 if err != nil {
370                         err = fmt.Errorf("sync failed: %w", err)
371                         http.Error(w, err.Error(), http.StatusInternalServerError)
372                         return true
373                 }
374                 w.WriteHeader(http.StatusNoContent)
375                 return true
376         default:
377                 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
378                 return true
379         }
380 }
381
382 // Call fn on the given path (directory) and its contents, in
383 // lexicographic order.
384 //
385 // If isRoot==true and path is not a directory, return nil.
386 //
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 {
390         if isRoot {
391                 fi, err := fs.Stat(path)
392                 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
393                         return nil
394                 } else if err != nil {
395                         return err
396                 }
397                 err = fn(path, fi)
398                 if err == filepath.SkipDir {
399                         return nil
400                 } else if err != nil {
401                         return err
402                 }
403         }
404         f, err := fs.Open(path)
405         if os.IsNotExist(err) && isRoot {
406                 return nil
407         } else if err != nil {
408                 return fmt.Errorf("open %q: %w", path, err)
409         }
410         defer f.Close()
411         if path == "/" {
412                 path = ""
413         }
414         fis, err := f.Readdir(-1)
415         if err != nil {
416                 return err
417         }
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 {
422                         continue
423                 } else if err != nil {
424                         return err
425                 }
426                 if fi.IsDir() {
427                         err = walkFS(fs, path+"/"+fi.Name(), false, fn)
428                         if err != nil {
429                                 return err
430                         }
431                 }
432         }
433         return nil
434 }
435
436 var errDone = errors.New("done")
437
438 func (h *handler) s3list(w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
439         var params struct {
440                 bucket    string
441                 delimiter string
442                 marker    string
443                 maxKeys   int
444                 prefix    string
445         }
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)
451         } else {
452                 params.maxKeys = s3MaxKeys
453         }
454         params.prefix = r.FormValue("prefix")
455
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]
467         } else {
468                 walkpath = ""
469         }
470
471         type commonPrefix struct {
472                 Prefix string
473         }
474         type listResp struct {
475                 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
476                 s3.ListResp
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
484                 // paging loop).
485                 NextMarker string `xml:"NextMarker,omitempty"`
486         }
487         resp := listResp{
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,
494                 },
495         }
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 {
499                         return nil
500                 }
501                 path = path[len(bucketdir)+1:]
502                 filesize := fi.Size()
503                 if fi.IsDir() {
504                         path += "/"
505                         filesize = 0
506                 }
507                 if len(path) <= len(params.prefix) {
508                         if path > params.prefix[:len(path)] {
509                                 // with prefix "foobar", walking "fooz" means we're done
510                                 return errDone
511                         }
512                         if path < params.prefix[:len(path)] {
513                                 // with prefix "foobar", walking "foobag" is pointless
514                                 return filepath.SkipDir
515                         }
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
521                         }
522                         if len(path) < len(params.prefix) {
523                                 // can't skip anything, and this entry
524                                 // isn't in the results, so just
525                                 // continue descent
526                                 return nil
527                         }
528                 } else {
529                         if path[:len(params.prefix)] > params.prefix {
530                                 // with prefix "foobar", nothing we
531                                 // see after "foozzz" is relevant
532                                 return errDone
533                         }
534                 }
535                 if path < params.marker || path < params.prefix {
536                         return nil
537                 }
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.
544                         return nil
545                 }
546                 if params.delimiter != "" {
547                         idx := strings.Index(path[len(params.prefix):], params.delimiter)
548                         if idx >= 0 {
549                                 // with prefix "foobar" and delimiter
550                                 // "z", when we hit "foobar/baz", we
551                                 // add "/baz" to commonPrefixes and
552                                 // stop descending.
553                                 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
554                                 return filepath.SkipDir
555                         }
556                 }
557                 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
558                         resp.IsTruncated = true
559                         if params.delimiter != "" {
560                                 resp.NextMarker = path
561                         }
562                         return errDone
563                 }
564                 resp.Contents = append(resp.Contents, s3.Key{
565                         Key:          path,
566                         LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
567                         Size:         filesize,
568                 })
569                 return nil
570         })
571         if err != nil && err != errDone {
572                 http.Error(w, err.Error(), http.StatusInternalServerError)
573                 return
574         }
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})
579                 }
580                 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
581         }
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")
586         }
587 }