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