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