Merge branch '16773-webshell-js' into 16796-arvbox-webshell
[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         "encoding/xml"
9         "errors"
10         "fmt"
11         "io"
12         "net/http"
13         "os"
14         "path/filepath"
15         "sort"
16         "strconv"
17         "strings"
18
19         "git.arvados.org/arvados.git/sdk/go/arvados"
20         "git.arvados.org/arvados.git/sdk/go/ctxlog"
21         "github.com/AdRoll/goamz/s3"
22 )
23
24 const s3MaxKeys = 1000
25
26 // serveS3 handles r and returns true if r is a request from an S3
27 // client, otherwise it returns false.
28 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
29         var token string
30         if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
31                 split := strings.SplitN(auth[4:], ":", 2)
32                 if len(split) < 2 {
33                         w.WriteHeader(http.StatusUnauthorized)
34                         return true
35                 }
36                 token = split[0]
37         } else if strings.HasPrefix(auth, "AWS4-HMAC-SHA256 ") {
38                 for _, cmpt := range strings.Split(auth[17:], ",") {
39                         cmpt = strings.TrimSpace(cmpt)
40                         split := strings.SplitN(cmpt, "=", 2)
41                         if len(split) == 2 && split[0] == "Credential" {
42                                 keyandscope := strings.Split(split[1], "/")
43                                 if len(keyandscope[0]) > 0 {
44                                         token = keyandscope[0]
45                                         break
46                                 }
47                         }
48                 }
49                 if token == "" {
50                         w.WriteHeader(http.StatusBadRequest)
51                         fmt.Println(w, "invalid V4 signature")
52                         return true
53                 }
54         } else {
55                 return false
56         }
57
58         _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
59         if err != nil {
60                 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
61                 return true
62         }
63         defer release()
64
65         fs := client.SiteFileSystem(kc)
66         fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
67
68         objectNameGiven := strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") > 1
69
70         switch {
71         case r.Method == http.MethodGet && !objectNameGiven:
72                 // Path is "/{uuid}" or "/{uuid}/", has no object name
73                 if _, ok := r.URL.Query()["versioning"]; ok {
74                         // GetBucketVersioning
75                         w.Header().Set("Content-Type", "application/xml")
76                         io.WriteString(w, xml.Header)
77                         fmt.Fprintln(w, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`)
78                 } else {
79                         // ListObjects
80                         h.s3list(w, r, fs)
81                 }
82                 return true
83         case r.Method == http.MethodGet || r.Method == http.MethodHead:
84                 fspath := "/by_id" + r.URL.Path
85                 fi, err := fs.Stat(fspath)
86                 if r.Method == "HEAD" && !objectNameGiven {
87                         // HeadBucket
88                         if err == nil && fi.IsDir() {
89                                 w.WriteHeader(http.StatusOK)
90                         } else if os.IsNotExist(err) {
91                                 w.WriteHeader(http.StatusNotFound)
92                         } else {
93                                 http.Error(w, err.Error(), http.StatusBadGateway)
94                         }
95                         return true
96                 }
97                 if err == nil && fi.IsDir() && objectNameGiven && strings.HasSuffix(fspath, "/") && h.Config.cluster.Collections.S3FolderObjects {
98                         w.Header().Set("Content-Type", "application/x-directory")
99                         w.WriteHeader(http.StatusOK)
100                         return true
101                 }
102                 if os.IsNotExist(err) ||
103                         (err != nil && err.Error() == "not a directory") ||
104                         (fi != nil && fi.IsDir()) {
105                         http.Error(w, "not found", http.StatusNotFound)
106                         return true
107                 }
108                 // shallow copy r, and change URL path
109                 r := *r
110                 r.URL.Path = fspath
111                 http.FileServer(fs).ServeHTTP(w, &r)
112                 return true
113         case r.Method == http.MethodPut:
114                 if !objectNameGiven {
115                         http.Error(w, "missing object name in PUT request", http.StatusBadRequest)
116                         return true
117                 }
118                 fspath := "by_id" + r.URL.Path
119                 var objectIsDir bool
120                 if strings.HasSuffix(fspath, "/") {
121                         if !h.Config.cluster.Collections.S3FolderObjects {
122                                 http.Error(w, "invalid object name: trailing slash", http.StatusBadRequest)
123                                 return true
124                         }
125                         n, err := r.Body.Read(make([]byte, 1))
126                         if err != nil && err != io.EOF {
127                                 http.Error(w, fmt.Sprintf("error reading request body: %s", err), http.StatusInternalServerError)
128                                 return true
129                         } else if n > 0 {
130                                 http.Error(w, "cannot create object with trailing '/' char unless content is empty", http.StatusBadRequest)
131                                 return true
132                         } else if strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0] != "application/x-directory" {
133                                 http.Error(w, "cannot create object with trailing '/' char unless Content-Type is 'application/x-directory'", http.StatusBadRequest)
134                                 return true
135                         }
136                         // Given PUT "foo/bar/", we'll use "foo/bar/."
137                         // in the "ensure parents exist" block below,
138                         // and then we'll be done.
139                         fspath += "."
140                         objectIsDir = true
141                 }
142                 fi, err := fs.Stat(fspath)
143                 if err != nil && err.Error() == "not a directory" {
144                         // requested foo/bar, but foo is a file
145                         http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
146                         return true
147                 }
148                 if strings.HasSuffix(r.URL.Path, "/") && err == nil && !fi.IsDir() {
149                         // requested foo/bar/, but foo/bar is a file
150                         http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
151                         return true
152                 }
153                 // create missing parent/intermediate directories, if any
154                 for i, c := range fspath {
155                         if i > 0 && c == '/' {
156                                 dir := fspath[:i]
157                                 if strings.HasSuffix(dir, "/") {
158                                         err = errors.New("invalid object name (consecutive '/' chars)")
159                                         http.Error(w, err.Error(), http.StatusBadRequest)
160                                         return true
161                                 }
162                                 err = fs.Mkdir(dir, 0755)
163                                 if err == arvados.ErrInvalidArgument {
164                                         // Cannot create a directory
165                                         // here.
166                                         err = fmt.Errorf("mkdir %q failed: %w", dir, err)
167                                         http.Error(w, err.Error(), http.StatusBadRequest)
168                                         return true
169                                 } else if err != nil && !os.IsExist(err) {
170                                         err = fmt.Errorf("mkdir %q failed: %w", dir, err)
171                                         http.Error(w, err.Error(), http.StatusInternalServerError)
172                                         return true
173                                 }
174                         }
175                 }
176                 if !objectIsDir {
177                         f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
178                         if os.IsNotExist(err) {
179                                 f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
180                         }
181                         if err != nil {
182                                 err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
183                                 http.Error(w, err.Error(), http.StatusBadRequest)
184                                 return true
185                         }
186                         defer f.Close()
187                         _, err = io.Copy(f, r.Body)
188                         if err != nil {
189                                 err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
190                                 http.Error(w, err.Error(), http.StatusBadGateway)
191                                 return true
192                         }
193                         err = f.Close()
194                         if err != nil {
195                                 err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
196                                 http.Error(w, err.Error(), http.StatusBadGateway)
197                                 return true
198                         }
199                 }
200                 err = fs.Sync()
201                 if err != nil {
202                         err = fmt.Errorf("sync failed: %w", err)
203                         http.Error(w, err.Error(), http.StatusInternalServerError)
204                         return true
205                 }
206                 w.WriteHeader(http.StatusOK)
207                 return true
208         case r.Method == http.MethodDelete:
209                 if !objectNameGiven || r.URL.Path == "/" {
210                         http.Error(w, "missing object name in DELETE request", http.StatusBadRequest)
211                         return true
212                 }
213                 fspath := "by_id" + r.URL.Path
214                 if strings.HasSuffix(fspath, "/") {
215                         fspath = strings.TrimSuffix(fspath, "/")
216                         fi, err := fs.Stat(fspath)
217                         if os.IsNotExist(err) {
218                                 w.WriteHeader(http.StatusNoContent)
219                                 return true
220                         } else if err != nil {
221                                 http.Error(w, err.Error(), http.StatusInternalServerError)
222                                 return true
223                         } else if !fi.IsDir() {
224                                 // if "foo" exists and is a file, then
225                                 // "foo/" doesn't exist, so we say
226                                 // delete was successful.
227                                 w.WriteHeader(http.StatusNoContent)
228                                 return true
229                         }
230                 } else if fi, err := fs.Stat(fspath); err == nil && fi.IsDir() {
231                         // if "foo" is a dir, it is visible via S3
232                         // only as "foo/", not "foo" -- so we leave
233                         // the dir alone and return 204 to indicate
234                         // that "foo" does not exist.
235                         w.WriteHeader(http.StatusNoContent)
236                         return true
237                 }
238                 err = fs.Remove(fspath)
239                 if os.IsNotExist(err) {
240                         w.WriteHeader(http.StatusNoContent)
241                         return true
242                 }
243                 if err != nil {
244                         err = fmt.Errorf("rm failed: %w", err)
245                         http.Error(w, err.Error(), http.StatusBadRequest)
246                         return true
247                 }
248                 err = fs.Sync()
249                 if err != nil {
250                         err = fmt.Errorf("sync failed: %w", err)
251                         http.Error(w, err.Error(), http.StatusInternalServerError)
252                         return true
253                 }
254                 w.WriteHeader(http.StatusNoContent)
255                 return true
256         default:
257                 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
258                 return true
259         }
260 }
261
262 // Call fn on the given path (directory) and its contents, in
263 // lexicographic order.
264 //
265 // If isRoot==true and path is not a directory, return nil.
266 //
267 // If fn returns filepath.SkipDir when called on a directory, don't
268 // descend into that directory.
269 func walkFS(fs arvados.CustomFileSystem, path string, isRoot bool, fn func(path string, fi os.FileInfo) error) error {
270         if isRoot {
271                 fi, err := fs.Stat(path)
272                 if os.IsNotExist(err) || (err == nil && !fi.IsDir()) {
273                         return nil
274                 } else if err != nil {
275                         return err
276                 }
277                 err = fn(path, fi)
278                 if err == filepath.SkipDir {
279                         return nil
280                 } else if err != nil {
281                         return err
282                 }
283         }
284         f, err := fs.Open(path)
285         if os.IsNotExist(err) && isRoot {
286                 return nil
287         } else if err != nil {
288                 return fmt.Errorf("open %q: %w", path, err)
289         }
290         defer f.Close()
291         if path == "/" {
292                 path = ""
293         }
294         fis, err := f.Readdir(-1)
295         if err != nil {
296                 return err
297         }
298         sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
299         for _, fi := range fis {
300                 err = fn(path+"/"+fi.Name(), fi)
301                 if err == filepath.SkipDir {
302                         continue
303                 } else if err != nil {
304                         return err
305                 }
306                 if fi.IsDir() {
307                         err = walkFS(fs, path+"/"+fi.Name(), false, fn)
308                         if err != nil {
309                                 return err
310                         }
311                 }
312         }
313         return nil
314 }
315
316 var errDone = errors.New("done")
317
318 func (h *handler) s3list(w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
319         var params struct {
320                 bucket    string
321                 delimiter string
322                 marker    string
323                 maxKeys   int
324                 prefix    string
325         }
326         params.bucket = strings.SplitN(r.URL.Path[1:], "/", 2)[0]
327         params.delimiter = r.FormValue("delimiter")
328         params.marker = r.FormValue("marker")
329         if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
330                 params.maxKeys = int(mk)
331         } else {
332                 params.maxKeys = s3MaxKeys
333         }
334         params.prefix = r.FormValue("prefix")
335
336         bucketdir := "by_id/" + params.bucket
337         // walkpath is the directory (relative to bucketdir) we need
338         // to walk: the innermost directory that is guaranteed to
339         // contain all paths that have the requested prefix. Examples:
340         // prefix "foo/bar"  => walkpath "foo"
341         // prefix "foo/bar/" => walkpath "foo/bar"
342         // prefix "foo"      => walkpath ""
343         // prefix ""         => walkpath ""
344         walkpath := params.prefix
345         if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
346                 walkpath = walkpath[:cut]
347         } else {
348                 walkpath = ""
349         }
350
351         type commonPrefix struct {
352                 Prefix string
353         }
354         type listResp struct {
355                 XMLName string `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
356                 s3.ListResp
357                 // s3.ListResp marshals an empty tag when
358                 // CommonPrefixes is nil, which confuses some clients.
359                 // Fix by using this nested struct instead.
360                 CommonPrefixes []commonPrefix
361         }
362         resp := listResp{
363                 ListResp: s3.ListResp{
364                         Name:      strings.SplitN(r.URL.Path[1:], "/", 2)[0],
365                         Prefix:    params.prefix,
366                         Delimiter: params.delimiter,
367                         Marker:    params.marker,
368                         MaxKeys:   params.maxKeys,
369                 },
370         }
371         commonPrefixes := map[string]bool{}
372         err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
373                 if path == bucketdir {
374                         return nil
375                 }
376                 path = path[len(bucketdir)+1:]
377                 filesize := fi.Size()
378                 if fi.IsDir() {
379                         path += "/"
380                         filesize = 0
381                 }
382                 if len(path) <= len(params.prefix) {
383                         if path > params.prefix[:len(path)] {
384                                 // with prefix "foobar", walking "fooz" means we're done
385                                 return errDone
386                         }
387                         if path < params.prefix[:len(path)] {
388                                 // with prefix "foobar", walking "foobag" is pointless
389                                 return filepath.SkipDir
390                         }
391                         if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path) {
392                                 // with prefix "foo/bar", walking "fo"
393                                 // is pointless (but walking "foo" or
394                                 // "foo/bar" is necessary)
395                                 return filepath.SkipDir
396                         }
397                         if len(path) < len(params.prefix) {
398                                 // can't skip anything, and this entry
399                                 // isn't in the results, so just
400                                 // continue descent
401                                 return nil
402                         }
403                 } else {
404                         if path[:len(params.prefix)] > params.prefix {
405                                 // with prefix "foobar", nothing we
406                                 // see after "foozzz" is relevant
407                                 return errDone
408                         }
409                 }
410                 if path < params.marker || path < params.prefix {
411                         return nil
412                 }
413                 if fi.IsDir() && !h.Config.cluster.Collections.S3FolderObjects {
414                         // Note we don't add anything to
415                         // commonPrefixes here even if delimiter is
416                         // "/". We descend into the directory, and
417                         // return a commonPrefix only if we end up
418                         // finding a regular file inside it.
419                         return nil
420                 }
421                 if params.delimiter != "" {
422                         idx := strings.Index(path[len(params.prefix):], params.delimiter)
423                         if idx >= 0 {
424                                 // with prefix "foobar" and delimiter
425                                 // "z", when we hit "foobar/baz", we
426                                 // add "/baz" to commonPrefixes and
427                                 // stop descending.
428                                 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
429                                 return filepath.SkipDir
430                         }
431                 }
432                 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
433                         resp.IsTruncated = true
434                         if params.delimiter != "" {
435                                 resp.NextMarker = path
436                         }
437                         return errDone
438                 }
439                 resp.Contents = append(resp.Contents, s3.Key{
440                         Key:          path,
441                         LastModified: fi.ModTime().UTC().Format("2006-01-02T15:04:05.999") + "Z",
442                         Size:         filesize,
443                 })
444                 return nil
445         })
446         if err != nil && err != errDone {
447                 http.Error(w, err.Error(), http.StatusInternalServerError)
448                 return
449         }
450         if params.delimiter != "" {
451                 resp.CommonPrefixes = make([]commonPrefix, 0, len(commonPrefixes))
452                 for prefix := range commonPrefixes {
453                         resp.CommonPrefixes = append(resp.CommonPrefixes, commonPrefix{prefix})
454                 }
455                 sort.Slice(resp.CommonPrefixes, func(i, j int) bool { return resp.CommonPrefixes[i].Prefix < resp.CommonPrefixes[j].Prefix })
456         }
457         w.Header().Set("Content-Type", "application/xml")
458         io.WriteString(w, xml.Header)
459         if err := xml.NewEncoder(w).Encode(resp); err != nil {
460                 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")
461         }
462 }