12483: Use real modTimes.
[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         if webdavMethod[r.Method] {
421                 writing := !arvadosclient.PDHMatch(targetID) && writeMethod[r.Method]
422                 if writing {
423                         // Save the collection only if/when all
424                         // webdav->filesystem operations succeed --
425                         // and send a 500 error if the modified
426                         // collection can't be saved.
427                         w = &updateOnSuccess{
428                                 ResponseWriter: w,
429                                 update: func() error {
430                                         return h.Config.Cache.Update(client, *collection, fs)
431                                 }}
432                 }
433                 h := webdav.Handler{
434                         Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
435                         FileSystem: &webdavFS{
436                                 collfs:  fs,
437                                 writing: writing,
438                         },
439                         LockSystem: h.webdavLS,
440                         Logger: func(_ *http.Request, err error) {
441                                 if err != nil {
442                                         log.Printf("error from webdav handler: %q", err)
443                                 }
444                         },
445                 }
446                 h.ServeHTTP(w, r)
447                 return
448         }
449
450         openPath := "/" + strings.Join(targetPath, "/")
451         if f, err := fs.Open(openPath); os.IsNotExist(err) {
452                 // Requested non-existent path
453                 statusCode = http.StatusNotFound
454         } else if err != nil {
455                 // Some other (unexpected) error
456                 statusCode, statusText = http.StatusInternalServerError, err.Error()
457         } else if stat, err := f.Stat(); err != nil {
458                 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
459                 statusCode, statusText = http.StatusInternalServerError, err.Error()
460         } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
461                 // If client requests ".../dirname", redirect to
462                 // ".../dirname/". This way, relative links in the
463                 // listing for "dirname" can always be "fnm", never
464                 // "dirname/fnm".
465                 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
466         } else if stat.IsDir() {
467                 h.serveDirectory(w, r, collection.Name, fs, openPath, stripParts)
468         } else {
469                 http.ServeContent(w, r, basename, stat.ModTime(), f)
470                 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
471                         // If we wrote fewer bytes than expected, it's
472                         // too late to change the real response code
473                         // or send an error message to the client, but
474                         // at least we can try to put some useful
475                         // debugging info in the logs.
476                         n, err := f.Read(make([]byte, 1024))
477                         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)
478
479                 }
480         }
481 }
482
483 var dirListingTemplate = `<!DOCTYPE HTML>
484 <HTML><HEAD>
485   <META name="robots" content="NOINDEX">
486   <TITLE>{{ .Collection.Name }}</TITLE>
487   <STYLE type="text/css">
488     body {
489       margin: 1.5em;
490     }
491     pre {
492       background-color: #D9EDF7;
493       border-radius: .25em;
494       padding: .75em;
495       overflow: auto;
496     }
497     .footer p {
498       font-size: 82%;
499     }
500     ul {
501       padding: 0;
502     }
503     ul li {
504       font-family: monospace;
505       list-style: none;
506     }
507   </STYLE>
508 </HEAD>
509 <BODY>
510 <H1>{{ .CollectionName }}</H1>
511
512 <P>This collection of data files is being shared with you through
513 Arvados.  You can download individual files listed below.  To download
514 the entire collection with wget, try:</P>
515
516 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL }}</PRE>
517
518 <H2>File Listing</H2>
519
520 {{if .Files}}
521 <UL>
522 {{range .Files}}  <LI>{{.Size | printf "%15d  " | nbsp}}<A href="{{.Name}}">{{.Name}}</A></LI>{{end}}
523 </UL>
524 {{else}}
525 <P>(No files; this collection is empty.)</P>
526 {{end}}
527
528 <HR noshade>
529 <DIV class="footer">
530   <P>
531     About Arvados:
532     Arvados is a free and open source software bioinformatics platform.
533     To learn more, visit arvados.org.
534     Arvados is not responsible for the files listed on this page.
535   </P>
536 </DIV>
537
538 </BODY>
539 `
540
541 type fileListEnt struct {
542         Name string
543         Size int64
544 }
545
546 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, stripParts int) {
547         var files []fileListEnt
548         var walk func(string) error
549         if !strings.HasSuffix(base, "/") {
550                 base = base + "/"
551         }
552         walk = func(path string) error {
553                 dirname := base + path
554                 if dirname != "/" {
555                         dirname = strings.TrimSuffix(dirname, "/")
556                 }
557                 d, err := fs.Open(dirname)
558                 if err != nil {
559                         return err
560                 }
561                 ents, err := d.Readdir(-1)
562                 if err != nil {
563                         return err
564                 }
565                 for _, ent := range ents {
566                         if ent.IsDir() {
567                                 err = walk(path + ent.Name() + "/")
568                                 if err != nil {
569                                         return err
570                                 }
571                         } else {
572                                 files = append(files, fileListEnt{
573                                         Name: path + ent.Name(),
574                                         Size: ent.Size(),
575                                 })
576                         }
577                 }
578                 return nil
579         }
580         if err := walk(""); err != nil {
581                 http.Error(w, err.Error(), http.StatusInternalServerError)
582                 return
583         }
584
585         funcs := template.FuncMap{
586                 "nbsp": func(s string) template.HTML {
587                         return template.HTML(strings.Replace(s, " ", "&nbsp;", -1))
588                 },
589         }
590         tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
591         if err != nil {
592                 http.Error(w, err.Error(), http.StatusInternalServerError)
593                 return
594         }
595         sort.Slice(files, func(i, j int) bool {
596                 return files[i].Name < files[j].Name
597         })
598         w.WriteHeader(http.StatusOK)
599         tmpl.Execute(w, map[string]interface{}{
600                 "CollectionName": collectionName,
601                 "Files":          files,
602                 "Request":        r,
603                 "StripParts":     stripParts,
604         })
605 }
606
607 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
608         disposition := "inline"
609         if isAttachment {
610                 disposition = "attachment"
611         }
612         if strings.ContainsRune(r.RequestURI, '?') {
613                 // Help the UA realize that the filename is just
614                 // "filename.txt", not
615                 // "filename.txt?disposition=attachment".
616                 //
617                 // TODO(TC): Follow advice at RFC 6266 appendix D
618                 disposition += "; filename=" + strconv.QuoteToASCII(filename)
619         }
620         if disposition != "inline" {
621                 w.Header().Set("Content-Disposition", disposition)
622         }
623 }
624
625 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
626         if formToken := r.FormValue("api_token"); formToken != "" {
627                 if !credentialsOK {
628                         // It is not safe to copy the provided token
629                         // into a cookie unless the current vhost
630                         // (origin) serves only a single collection or
631                         // we are in TrustAllContent mode.
632                         w.WriteHeader(http.StatusBadRequest)
633                         return
634                 }
635
636                 // The HttpOnly flag is necessary to prevent
637                 // JavaScript code (included in, or loaded by, a page
638                 // in the collection being served) from employing the
639                 // user's token beyond reading other files in the same
640                 // domain, i.e., same collection.
641                 //
642                 // The 303 redirect is necessary in the case of a GET
643                 // request to avoid exposing the token in the Location
644                 // bar, and in the case of a POST request to avoid
645                 // raising warnings when the user refreshes the
646                 // resulting page.
647                 http.SetCookie(w, &http.Cookie{
648                         Name:     "arvados_api_token",
649                         Value:    auth.EncodeTokenCookie([]byte(formToken)),
650                         Path:     "/",
651                         HttpOnly: true,
652                 })
653         }
654
655         // Propagate query parameters (except api_token) from
656         // the original request.
657         redirQuery := r.URL.Query()
658         redirQuery.Del("api_token")
659
660         u := r.URL
661         if location != "" {
662                 newu, err := u.Parse(location)
663                 if err != nil {
664                         w.WriteHeader(http.StatusInternalServerError)
665                         return
666                 }
667                 u = newu
668         }
669         redir := (&url.URL{
670                 Host:     r.Host,
671                 Path:     u.Path,
672                 RawQuery: redirQuery.Encode(),
673         }).String()
674
675         w.Header().Add("Location", redir)
676         w.WriteHeader(http.StatusSeeOther)
677         io.WriteString(w, `<A href="`)
678         io.WriteString(w, html.EscapeString(redir))
679         io.WriteString(w, `">Continue</A>`)
680 }