16535: Improve error message.
[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         switch {
69         case r.Method == "GET" && strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") == 1:
70                 // Path is "/{uuid}" or "/{uuid}/", has no object name
71                 h.s3list(w, r, fs)
72                 return true
73         case r.Method == "GET":
74                 fspath := "/by_id" + r.URL.Path
75                 fi, err := fs.Stat(fspath)
76                 if os.IsNotExist(err) ||
77                         (err != nil && err.Error() == "not a directory") ||
78                         (fi != nil && fi.IsDir()) {
79                         http.Error(w, "not found", http.StatusNotFound)
80                         return true
81                 }
82                 // shallow copy r, and change URL path
83                 r := *r
84                 r.URL.Path = fspath
85                 http.FileServer(fs).ServeHTTP(w, &r)
86                 return true
87         case r.Method == "PUT":
88                 if strings.HasSuffix(r.URL.Path, "/") {
89                         http.Error(w, "invalid object name (trailing '/' char)", http.StatusBadRequest)
90                         return true
91                 }
92                 fspath := "by_id" + r.URL.Path
93                 _, err = fs.Stat(fspath)
94                 if err != nil && err.Error() == "not a directory" {
95                         // requested foo/bar, but foo is a file
96                         http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
97                         return true
98                 }
99                 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
100                 if os.IsNotExist(err) {
101                         // create missing intermediate directories, then try again
102                         for i, c := range fspath {
103                                 if i > 0 && c == '/' {
104                                         dir := fspath[:i]
105                                         if strings.HasSuffix(dir, "/") {
106                                                 err = errors.New("invalid object name (consecutive '/' chars)")
107                                                 http.Error(w, err.Error(), http.StatusBadRequest)
108                                                 return true
109                                         }
110                                         err := fs.Mkdir(dir, 0755)
111                                         if err != nil && err != os.ErrExist {
112                                                 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
113                                                 http.Error(w, err.Error(), http.StatusInternalServerError)
114                                                 return true
115                                         }
116                                 }
117                         }
118                         f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
119                 }
120                 if err != nil {
121                         err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
122                         http.Error(w, err.Error(), http.StatusBadRequest)
123                         return true
124                 }
125                 defer f.Close()
126                 _, err = io.Copy(f, r.Body)
127                 if err != nil {
128                         err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
129                         http.Error(w, err.Error(), http.StatusBadGateway)
130                         return true
131                 }
132                 err = f.Close()
133                 if err != nil {
134                         err = fmt.Errorf("write to %q failed: close: %w", r.URL.Path, err)
135                         http.Error(w, err.Error(), http.StatusBadGateway)
136                         return true
137                 }
138                 err = fs.Sync()
139                 if err != nil {
140                         err = fmt.Errorf("sync failed: %w", err)
141                         http.Error(w, err.Error(), http.StatusInternalServerError)
142                         return true
143                 }
144                 w.WriteHeader(http.StatusOK)
145                 return true
146         default:
147                 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
148                 return true
149         }
150 }
151
152 func walkFS(fs arvados.CustomFileSystem, path string, ignoreNotFound bool, fn func(path string, fi os.FileInfo) error) error {
153         f, err := fs.Open(path)
154         if os.IsNotExist(err) && ignoreNotFound {
155                 return nil
156         } else if err != nil {
157                 return fmt.Errorf("open %q: %w", path, err)
158         }
159         defer f.Close()
160         if path == "/" {
161                 path = ""
162         }
163         fis, err := f.Readdir(-1)
164         if err != nil {
165                 return err
166         }
167         sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
168         for _, fi := range fis {
169                 err = fn(path+"/"+fi.Name(), fi)
170                 if err == filepath.SkipDir {
171                         continue
172                 } else if err != nil {
173                         return err
174                 }
175                 if fi.IsDir() {
176                         err = walkFS(fs, path+"/"+fi.Name(), false, fn)
177                         if err != nil {
178                                 return err
179                         }
180                 }
181         }
182         return nil
183 }
184
185 var errDone = errors.New("done")
186
187 func (h *handler) s3list(w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
188         var params struct {
189                 bucket    string
190                 delimiter string
191                 marker    string
192                 maxKeys   int
193                 prefix    string
194         }
195         params.bucket = strings.SplitN(r.URL.Path[1:], "/", 2)[0]
196         params.delimiter = r.FormValue("delimiter")
197         params.marker = r.FormValue("marker")
198         if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 && mk < s3MaxKeys {
199                 params.maxKeys = int(mk)
200         } else {
201                 params.maxKeys = s3MaxKeys
202         }
203         params.prefix = r.FormValue("prefix")
204
205         bucketdir := "by_id/" + params.bucket
206         // walkpath is the directory (relative to bucketdir) we need
207         // to walk: the innermost directory that is guaranteed to
208         // contain all paths that have the requested prefix. Examples:
209         // prefix "foo/bar"  => walkpath "foo"
210         // prefix "foo/bar/" => walkpath "foo/bar"
211         // prefix "foo"      => walkpath ""
212         // prefix ""         => walkpath ""
213         walkpath := params.prefix
214         if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
215                 walkpath = walkpath[:cut]
216         } else {
217                 walkpath = ""
218         }
219
220         resp := s3.ListResp{
221                 Name:      strings.SplitN(r.URL.Path[1:], "/", 2)[0],
222                 Prefix:    params.prefix,
223                 Delimiter: params.delimiter,
224                 Marker:    params.marker,
225                 MaxKeys:   params.maxKeys,
226         }
227         commonPrefixes := map[string]bool{}
228         err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
229                 path = path[len(bucketdir)+1:]
230                 if len(path) <= len(params.prefix) {
231                         if path > params.prefix[:len(path)] {
232                                 // with prefix "foobar", walking "fooz" means we're done
233                                 return errDone
234                         }
235                         if path < params.prefix[:len(path)] {
236                                 // with prefix "foobar", walking "foobag" is pointless
237                                 return filepath.SkipDir
238                         }
239                         if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path+"/") {
240                                 // with prefix "foo/bar", walking "fo"
241                                 // is pointless (but walking "foo" or
242                                 // "foo/bar" is necessary)
243                                 return filepath.SkipDir
244                         }
245                         if len(path) < len(params.prefix) {
246                                 // can't skip anything, and this entry
247                                 // isn't in the results, so just
248                                 // continue descent
249                                 return nil
250                         }
251                 } else {
252                         if path[:len(params.prefix)] > params.prefix {
253                                 // with prefix "foobar", nothing we
254                                 // see after "foozzz" is relevant
255                                 return errDone
256                         }
257                 }
258                 if path < params.marker || path < params.prefix {
259                         return nil
260                 }
261                 if fi.IsDir() {
262                         return nil
263                 }
264                 if params.delimiter != "" {
265                         idx := strings.Index(path[len(params.prefix):], params.delimiter)
266                         if idx >= 0 {
267                                 // with prefix "foobar" and delimiter
268                                 // "z", when we hit "foobar/baz", we
269                                 // add "/baz" to commonPrefixes and
270                                 // stop descending (note that even if
271                                 // delimiter is "/" we don't add
272                                 // anything to commonPrefixes when
273                                 // seeing a dir: we wait until we see
274                                 // a file, so we don't incorrectly
275                                 // return results for empty dirs)
276                                 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
277                                 return filepath.SkipDir
278                         }
279                 }
280                 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
281                         resp.IsTruncated = true
282                         if params.delimiter != "" {
283                                 resp.NextMarker = path
284                         }
285                         return errDone
286                 }
287                 resp.Contents = append(resp.Contents, s3.Key{
288                         Key: path,
289                 })
290                 return nil
291         })
292         if err != nil && err != errDone {
293                 http.Error(w, err.Error(), http.StatusInternalServerError)
294                 return
295         }
296         if params.delimiter != "" {
297                 for prefix := range commonPrefixes {
298                         resp.CommonPrefixes = append(resp.CommonPrefixes, prefix)
299                         sort.Strings(resp.CommonPrefixes)
300                 }
301         }
302         if err := xml.NewEncoder(w).Encode(resp); err != nil {
303                 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")
304         }
305 }