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