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