12483: Update docs to acknowledge read/write webdav support.
[arvados.git] / services / keep-web / handler.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/json"
9         "fmt"
10         "html"
11         "html/template"
12         "io"
13         "log"
14         "net/http"
15         "net/url"
16         "os"
17         "sort"
18         "strconv"
19         "strings"
20         "sync"
21
22         "git.curoverse.com/arvados.git/sdk/go/arvados"
23         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
24         "git.curoverse.com/arvados.git/sdk/go/auth"
25         "git.curoverse.com/arvados.git/sdk/go/health"
26         "git.curoverse.com/arvados.git/sdk/go/httpserver"
27         "git.curoverse.com/arvados.git/sdk/go/keepclient"
28         "golang.org/x/net/webdav"
29 )
30
31 type handler struct {
32         Config        *Config
33         clientPool    *arvadosclient.ClientPool
34         setupOnce     sync.Once
35         healthHandler http.Handler
36         webdavLS      webdav.LockSystem
37 }
38
39 // parseCollectionIDFromDNSName returns a UUID or PDH if s begins with
40 // a UUID or URL-encoded PDH; otherwise "".
41 func parseCollectionIDFromDNSName(s string) string {
42         // Strip domain.
43         if i := strings.IndexRune(s, '.'); i >= 0 {
44                 s = s[:i]
45         }
46         // Names like {uuid}--collections.example.com serve the same
47         // purpose as {uuid}.collections.example.com but can reduce
48         // cost/effort of using [additional] wildcard certificates.
49         if i := strings.Index(s, "--"); i >= 0 {
50                 s = s[:i]
51         }
52         if arvadosclient.UUIDMatch(s) {
53                 return s
54         }
55         if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
56                 return pdh
57         }
58         return ""
59 }
60
61 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
62
63 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
64 // PDH (even if it is a PDH with "+" replaced by " " or "-");
65 // otherwise "".
66 func parseCollectionIDFromURL(s string) string {
67         if arvadosclient.UUIDMatch(s) {
68                 return s
69         }
70         if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
71                 return pdh
72         }
73         return ""
74 }
75
76 func (h *handler) setup() {
77         h.clientPool = arvadosclient.MakeClientPool()
78
79         keepclient.RefreshServiceDiscoveryOnSIGHUP()
80
81         h.healthHandler = &health.Handler{
82                 Token:  h.Config.ManagementToken,
83                 Prefix: "/_health/",
84         }
85
86         // Even though we don't accept LOCK requests, every webdav
87         // handler must have a non-nil LockSystem.
88         h.webdavLS = &noLockSystem{}
89 }
90
91 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
92         status := struct {
93                 cacheStats
94         }{
95                 cacheStats: h.Config.Cache.Stats(),
96         }
97         json.NewEncoder(w).Encode(status)
98 }
99
100 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
101 // sends an HTTP header indicating success, updateOnSuccess first
102 // calls the provided update func. If the update func fails, a 500
103 // response is sent, and the status code and body sent by the handler
104 // are ignored (all response writes return the update error).
105 type updateOnSuccess struct {
106         httpserver.ResponseWriter
107         update     func() error
108         sentHeader bool
109         err        error
110 }
111
112 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
113         if uos.err != nil {
114                 return 0, uos.err
115         }
116         if !uos.sentHeader {
117                 uos.WriteHeader(http.StatusOK)
118         }
119         return uos.ResponseWriter.Write(p)
120 }
121
122 func (uos *updateOnSuccess) WriteHeader(code int) {
123         if !uos.sentHeader {
124                 uos.sentHeader = true
125                 if code >= 200 && code < 400 {
126                         if uos.err = uos.update(); uos.err != nil {
127                                 code := http.StatusInternalServerError
128                                 if err, ok := uos.err.(*arvados.TransactionError); ok {
129                                         code = err.StatusCode
130                                 }
131                                 log.Printf("update() changes response to HTTP %d: %T %q", code, uos.err, uos.err)
132                                 http.Error(uos.ResponseWriter, uos.err.Error(), code)
133                                 return
134                         }
135                 }
136         }
137         uos.ResponseWriter.WriteHeader(code)
138 }
139
140 var (
141         writeMethod = map[string]bool{
142                 "COPY":   true,
143                 "DELETE": true,
144                 "MKCOL":  true,
145                 "MOVE":   true,
146                 "PUT":    true,
147                 "RMCOL":  true,
148         }
149         webdavMethod = map[string]bool{
150                 "COPY":     true,
151                 "DELETE":   true,
152                 "MKCOL":    true,
153                 "MOVE":     true,
154                 "OPTIONS":  true,
155                 "PROPFIND": true,
156                 "PUT":      true,
157                 "RMCOL":    true,
158         }
159         browserMethod = map[string]bool{
160                 "GET":  true,
161                 "HEAD": true,
162                 "POST": true,
163         }
164 )
165
166 // ServeHTTP implements http.Handler.
167 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
168         h.setupOnce.Do(h.setup)
169
170         var statusCode = 0
171         var statusText string
172
173         remoteAddr := r.RemoteAddr
174         if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
175                 remoteAddr = xff + "," + remoteAddr
176         }
177
178         w := httpserver.WrapResponseWriter(wOrig)
179         defer func() {
180                 if statusCode == 0 {
181                         statusCode = w.WroteStatus()
182                 } else if w.WroteStatus() == 0 {
183                         w.WriteHeader(statusCode)
184                 } else if w.WroteStatus() != statusCode {
185                         httpserver.Log(r.RemoteAddr, "WARNING",
186                                 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
187                 }
188                 if statusText == "" {
189                         statusText = http.StatusText(statusCode)
190                 }
191                 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
192         }()
193
194         if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
195                 h.healthHandler.ServeHTTP(w, r)
196                 return
197         }
198
199         if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
200                 if !browserMethod[method] && !webdavMethod[method] {
201                         statusCode = http.StatusMethodNotAllowed
202                         return
203                 }
204                 w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Range")
205                 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PUT, RMCOL")
206                 w.Header().Set("Access-Control-Allow-Origin", "*")
207                 w.Header().Set("Access-Control-Max-Age", "86400")
208                 statusCode = http.StatusOK
209                 return
210         }
211
212         if !browserMethod[r.Method] && !webdavMethod[r.Method] {
213                 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
214                 return
215         }
216
217         if r.Header.Get("Origin") != "" {
218                 // Allow simple cross-origin requests without user
219                 // credentials ("user credentials" as defined by CORS,
220                 // i.e., cookies, HTTP authentication, and client-side
221                 // SSL certificates. See
222                 // http://www.w3.org/TR/cors/#user-credentials).
223                 w.Header().Set("Access-Control-Allow-Origin", "*")
224                 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
225         }
226
227         arv := h.clientPool.Get()
228         if arv == nil {
229                 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
230                 return
231         }
232         defer h.clientPool.Put(arv)
233
234         pathParts := strings.Split(r.URL.Path[1:], "/")
235
236         var stripParts int
237         var targetID string
238         var tokens []string
239         var reqTokens []string
240         var pathToken bool
241         var attachment bool
242         credentialsOK := h.Config.TrustAllContent
243
244         if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
245                 credentialsOK = true
246                 attachment = true
247         } else if r.FormValue("disposition") == "attachment" {
248                 attachment = true
249         }
250
251         if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
252                 // http://ID.collections.example/PATH...
253                 credentialsOK = true
254         } else if r.URL.Path == "/status.json" {
255                 h.serveStatus(w, r)
256                 return
257         } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
258                 // /c=ID[/PATH...]
259                 targetID = parseCollectionIDFromURL(pathParts[0][2:])
260                 stripParts = 1
261         } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
262                 if len(pathParts) >= 4 && pathParts[1] == "download" {
263                         // /collections/download/ID/TOKEN/PATH...
264                         targetID = parseCollectionIDFromURL(pathParts[2])
265                         tokens = []string{pathParts[3]}
266                         stripParts = 4
267                         pathToken = true
268                 } else {
269                         // /collections/ID/PATH...
270                         targetID = parseCollectionIDFromURL(pathParts[1])
271                         tokens = h.Config.AnonymousTokens
272                         stripParts = 2
273                 }
274         }
275
276         if targetID == "" {
277                 statusCode = http.StatusNotFound
278                 return
279         }
280
281         formToken := r.FormValue("api_token")
282         if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
283                 // The client provided an explicit token in the POST
284                 // body. The Origin header indicates this *might* be
285                 // an AJAX request, in which case redirect-with-cookie
286                 // won't work: we should just serve the content in the
287                 // POST response. This is safe because:
288                 //
289                 // * We're supplying an attachment, not inline
290                 //   content, so we don't need to convert the POST to
291                 //   a GET and avoid the "really resubmit form?"
292                 //   problem.
293                 //
294                 // * The token isn't embedded in the URL, so we don't
295                 //   need to worry about bookmarks and copy/paste.
296                 tokens = append(tokens, formToken)
297         } else if formToken != "" && browserMethod[r.Method] {
298                 // The client provided an explicit token in the query
299                 // string, or a form in POST body. We must put the
300                 // token in an HttpOnly cookie, and redirect to the
301                 // same URL with the query param redacted and method =
302                 // GET.
303                 h.seeOtherWithCookie(w, r, "", credentialsOK)
304                 return
305         }
306
307         targetPath := pathParts[stripParts:]
308         if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
309                 // http://ID.example/t=TOKEN/PATH...
310                 // /c=ID/t=TOKEN/PATH...
311                 //
312                 // This form must only be used to pass scoped tokens
313                 // that give permission for a single collection. See
314                 // FormValue case above.
315                 tokens = []string{targetPath[0][2:]}
316                 pathToken = true
317                 targetPath = targetPath[1:]
318                 stripParts++
319         }
320
321         if tokens == nil {
322                 if credentialsOK {
323                         reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
324                 }
325                 tokens = append(reqTokens, h.Config.AnonymousTokens...)
326         }
327
328         if len(targetPath) > 0 && targetPath[0] == "_" {
329                 // If a collection has a directory called "t=foo" or
330                 // "_", it can be served at
331                 // //collections.example/_/t=foo/ or
332                 // //collections.example/_/_/ respectively:
333                 // //collections.example/t=foo/ won't work because
334                 // t=foo will be interpreted as a token "foo".
335                 targetPath = targetPath[1:]
336                 stripParts++
337         }
338
339         forceReload := false
340         if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
341                 forceReload = true
342         }
343
344         var collection *arvados.Collection
345         tokenResult := make(map[string]int)
346         for _, arv.ApiToken = range tokens {
347                 var err error
348                 collection, err = h.Config.Cache.Get(arv, targetID, forceReload)
349                 if err == nil {
350                         // Success
351                         break
352                 }
353                 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
354                         switch srvErr.HttpStatusCode {
355                         case 404, 401:
356                                 // Token broken or insufficient to
357                                 // retrieve collection
358                                 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
359                                 continue
360                         }
361                 }
362                 // Something more serious is wrong
363                 statusCode, statusText = http.StatusInternalServerError, err.Error()
364                 return
365         }
366         if collection == nil {
367                 if pathToken || !credentialsOK {
368                         // Either the URL is a "secret sharing link"
369                         // that didn't work out (and asking the client
370                         // for additional credentials would just be
371                         // confusing), or we don't even accept
372                         // credentials at this path.
373                         statusCode = http.StatusNotFound
374                         return
375                 }
376                 for _, t := range reqTokens {
377                         if tokenResult[t] == 404 {
378                                 // The client provided valid token(s), but the
379                                 // collection was not found.
380                                 statusCode = http.StatusNotFound
381                                 return
382                         }
383                 }
384                 // The client's token was invalid (e.g., expired), or
385                 // the client didn't even provide one.  Propagate the
386                 // 401 to encourage the client to use a [different]
387                 // token.
388                 //
389                 // TODO(TC): This response would be confusing to
390                 // someone trying (anonymously) to download public
391                 // data that has been deleted.  Allow a referrer to
392                 // provide this context somehow?
393                 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
394                 statusCode = http.StatusUnauthorized
395                 return
396         }
397
398         kc, err := keepclient.MakeKeepClient(arv)
399         if err != nil {
400                 statusCode, statusText = http.StatusInternalServerError, err.Error()
401                 return
402         }
403
404         var basename string
405         if len(targetPath) > 0 {
406                 basename = targetPath[len(targetPath)-1]
407         }
408         applyContentDispositionHdr(w, r, basename, attachment)
409
410         client := &arvados.Client{
411                 APIHost:   arv.ApiServer,
412                 AuthToken: arv.ApiToken,
413                 Insecure:  arv.ApiInsecure,
414         }
415         fs, err := collection.FileSystem(client, kc)
416         if err != nil {
417                 statusCode, statusText = http.StatusInternalServerError, err.Error()
418                 return
419         }
420
421         targetIsPDH := arvadosclient.PDHMatch(targetID)
422         if targetIsPDH && writeMethod[r.Method] {
423                 statusCode, statusText = http.StatusMethodNotAllowed, errReadOnly.Error()
424                 return
425         }
426
427         if webdavMethod[r.Method] {
428                 if writeMethod[r.Method] {
429                         // Save the collection only if/when all
430                         // webdav->filesystem operations succeed --
431                         // and send a 500 error if the modified
432                         // collection can't be saved.
433                         w = &updateOnSuccess{
434                                 ResponseWriter: w,
435                                 update: func() error {
436                                         return h.Config.Cache.Update(client, *collection, fs)
437                                 }}
438                 }
439                 h := webdav.Handler{
440                         Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
441                         FileSystem: &webdavFS{
442                                 collfs:  fs,
443                                 writing: writeMethod[r.Method],
444                         },
445                         LockSystem: h.webdavLS,
446                         Logger: func(_ *http.Request, err error) {
447                                 if err != nil {
448                                         log.Printf("error from webdav handler: %q", err)
449                                 }
450                         },
451                 }
452                 h.ServeHTTP(w, r)
453                 return
454         }
455
456         openPath := "/" + strings.Join(targetPath, "/")
457         if f, err := fs.Open(openPath); os.IsNotExist(err) {
458                 // Requested non-existent path
459                 statusCode = http.StatusNotFound
460         } else if err != nil {
461                 // Some other (unexpected) error
462                 statusCode, statusText = http.StatusInternalServerError, err.Error()
463         } else if stat, err := f.Stat(); err != nil {
464                 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
465                 statusCode, statusText = http.StatusInternalServerError, err.Error()
466         } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
467                 // If client requests ".../dirname", redirect to
468                 // ".../dirname/". This way, relative links in the
469                 // listing for "dirname" can always be "fnm", never
470                 // "dirname/fnm".
471                 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
472         } else if stat.IsDir() {
473                 h.serveDirectory(w, r, collection.Name, fs, openPath, stripParts)
474         } else {
475                 http.ServeContent(w, r, basename, stat.ModTime(), f)
476                 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
477                         // If we wrote fewer bytes than expected, it's
478                         // too late to change the real response code
479                         // or send an error message to the client, but
480                         // at least we can try to put some useful
481                         // debugging info in the logs.
482                         n, err := f.Read(make([]byte, 1024))
483                         statusCode, statusText = http.StatusInternalServerError, fmt.Sprintf("f.Size()==%d but only wrote %d bytes; read(1024) returns %d, %s", stat.Size(), w.WroteBodyBytes(), n, err)
484
485                 }
486         }
487 }
488
489 var dirListingTemplate = `<!DOCTYPE HTML>
490 <HTML><HEAD>
491   <META name="robots" content="NOINDEX">
492   <TITLE>{{ .Collection.Name }}</TITLE>
493   <STYLE type="text/css">
494     body {
495       margin: 1.5em;
496     }
497     pre {
498       background-color: #D9EDF7;
499       border-radius: .25em;
500       padding: .75em;
501       overflow: auto;
502     }
503     .footer p {
504       font-size: 82%;
505     }
506     ul {
507       padding: 0;
508     }
509     ul li {
510       font-family: monospace;
511       list-style: none;
512     }
513   </STYLE>
514 </HEAD>
515 <BODY>
516 <H1>{{ .CollectionName }}</H1>
517
518 <P>This collection of data files is being shared with you through
519 Arvados.  You can download individual files listed below.  To download
520 the entire collection with wget, try:</P>
521
522 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL }}</PRE>
523
524 <H2>File Listing</H2>
525
526 {{if .Files}}
527 <UL>
528 {{range .Files}}  <LI>{{.Size | printf "%15d  " | nbsp}}<A href="{{.Name}}">{{.Name}}</A></LI>{{end}}
529 </UL>
530 {{else}}
531 <P>(No files; this collection is empty.)</P>
532 {{end}}
533
534 <HR noshade>
535 <DIV class="footer">
536   <P>
537     About Arvados:
538     Arvados is a free and open source software bioinformatics platform.
539     To learn more, visit arvados.org.
540     Arvados is not responsible for the files listed on this page.
541   </P>
542 </DIV>
543
544 </BODY>
545 `
546
547 type fileListEnt struct {
548         Name string
549         Size int64
550 }
551
552 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, stripParts int) {
553         var files []fileListEnt
554         var walk func(string) error
555         if !strings.HasSuffix(base, "/") {
556                 base = base + "/"
557         }
558         walk = func(path string) error {
559                 dirname := base + path
560                 if dirname != "/" {
561                         dirname = strings.TrimSuffix(dirname, "/")
562                 }
563                 d, err := fs.Open(dirname)
564                 if err != nil {
565                         return err
566                 }
567                 ents, err := d.Readdir(-1)
568                 if err != nil {
569                         return err
570                 }
571                 for _, ent := range ents {
572                         if ent.IsDir() {
573                                 err = walk(path + ent.Name() + "/")
574                                 if err != nil {
575                                         return err
576                                 }
577                         } else {
578                                 files = append(files, fileListEnt{
579                                         Name: path + ent.Name(),
580                                         Size: ent.Size(),
581                                 })
582                         }
583                 }
584                 return nil
585         }
586         if err := walk(""); err != nil {
587                 http.Error(w, err.Error(), http.StatusInternalServerError)
588                 return
589         }
590
591         funcs := template.FuncMap{
592                 "nbsp": func(s string) template.HTML {
593                         return template.HTML(strings.Replace(s, " ", "&nbsp;", -1))
594                 },
595         }
596         tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
597         if err != nil {
598                 http.Error(w, err.Error(), http.StatusInternalServerError)
599                 return
600         }
601         sort.Slice(files, func(i, j int) bool {
602                 return files[i].Name < files[j].Name
603         })
604         w.WriteHeader(http.StatusOK)
605         tmpl.Execute(w, map[string]interface{}{
606                 "CollectionName": collectionName,
607                 "Files":          files,
608                 "Request":        r,
609                 "StripParts":     stripParts,
610         })
611 }
612
613 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
614         disposition := "inline"
615         if isAttachment {
616                 disposition = "attachment"
617         }
618         if strings.ContainsRune(r.RequestURI, '?') {
619                 // Help the UA realize that the filename is just
620                 // "filename.txt", not
621                 // "filename.txt?disposition=attachment".
622                 //
623                 // TODO(TC): Follow advice at RFC 6266 appendix D
624                 disposition += "; filename=" + strconv.QuoteToASCII(filename)
625         }
626         if disposition != "inline" {
627                 w.Header().Set("Content-Disposition", disposition)
628         }
629 }
630
631 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
632         if formToken := r.FormValue("api_token"); formToken != "" {
633                 if !credentialsOK {
634                         // It is not safe to copy the provided token
635                         // into a cookie unless the current vhost
636                         // (origin) serves only a single collection or
637                         // we are in TrustAllContent mode.
638                         w.WriteHeader(http.StatusBadRequest)
639                         return
640                 }
641
642                 // The HttpOnly flag is necessary to prevent
643                 // JavaScript code (included in, or loaded by, a page
644                 // in the collection being served) from employing the
645                 // user's token beyond reading other files in the same
646                 // domain, i.e., same collection.
647                 //
648                 // The 303 redirect is necessary in the case of a GET
649                 // request to avoid exposing the token in the Location
650                 // bar, and in the case of a POST request to avoid
651                 // raising warnings when the user refreshes the
652                 // resulting page.
653                 http.SetCookie(w, &http.Cookie{
654                         Name:     "arvados_api_token",
655                         Value:    auth.EncodeTokenCookie([]byte(formToken)),
656                         Path:     "/",
657                         HttpOnly: true,
658                 })
659         }
660
661         // Propagate query parameters (except api_token) from
662         // the original request.
663         redirQuery := r.URL.Query()
664         redirQuery.Del("api_token")
665
666         u := r.URL
667         if location != "" {
668                 newu, err := u.Parse(location)
669                 if err != nil {
670                         w.WriteHeader(http.StatusInternalServerError)
671                         return
672                 }
673                 u = newu
674         }
675         redir := (&url.URL{
676                 Host:     r.Host,
677                 Path:     u.Path,
678                 RawQuery: redirQuery.Encode(),
679         }).String()
680
681         w.Header().Add("Location", redir)
682         w.WriteHeader(http.StatusSeeOther)
683         io.WriteString(w, `<A href="`)
684         io.WriteString(w, html.EscapeString(redir))
685         io.WriteString(w, `">Continue</A>`)
686 }