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