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