15606: Add error message and doc link to XSS protection error.
[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         "html"
10         "html/template"
11         "io"
12         "net/http"
13         "net/url"
14         "os"
15         "path/filepath"
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/ctxlog"
25         "git.curoverse.com/arvados.git/sdk/go/health"
26         "git.curoverse.com/arvados.git/sdk/go/httpserver"
27         "git.curoverse.com/arvados.git/sdk/go/keepclient"
28         "github.com/sirupsen/logrus"
29         "golang.org/x/net/webdav"
30 )
31
32 type handler struct {
33         Config        *Config
34         MetricsAPI    http.Handler
35         clientPool    *arvadosclient.ClientPool
36         setupOnce     sync.Once
37         healthHandler http.Handler
38         webdavLS      webdav.LockSystem
39 }
40
41 // parseCollectionIDFromDNSName returns a UUID or PDH if s begins with
42 // a UUID or URL-encoded PDH; otherwise "".
43 func parseCollectionIDFromDNSName(s string) string {
44         // Strip domain.
45         if i := strings.IndexRune(s, '.'); i >= 0 {
46                 s = s[:i]
47         }
48         // Names like {uuid}--collections.example.com serve the same
49         // purpose as {uuid}.collections.example.com but can reduce
50         // cost/effort of using [additional] wildcard certificates.
51         if i := strings.Index(s, "--"); i >= 0 {
52                 s = s[:i]
53         }
54         if arvadosclient.UUIDMatch(s) {
55                 return s
56         }
57         if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
58                 return pdh
59         }
60         return ""
61 }
62
63 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
64
65 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
66 // PDH (even if it is a PDH with "+" replaced by " " or "-");
67 // otherwise "".
68 func parseCollectionIDFromURL(s string) string {
69         if arvadosclient.UUIDMatch(s) {
70                 return s
71         }
72         if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
73                 return pdh
74         }
75         return ""
76 }
77
78 func (h *handler) setup() {
79         h.clientPool = arvadosclient.MakeClientPool()
80
81         keepclient.RefreshServiceDiscoveryOnSIGHUP()
82         keepclient.DefaultBlockCache.MaxBlocks = h.Config.cluster.Collections.WebDAVCache.MaxBlockEntries
83
84         h.healthHandler = &health.Handler{
85                 Token:  h.Config.cluster.ManagementToken,
86                 Prefix: "/_health/",
87         }
88
89         // Even though we don't accept LOCK requests, every webdav
90         // handler must have a non-nil LockSystem.
91         h.webdavLS = &noLockSystem{}
92 }
93
94 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
95         json.NewEncoder(w).Encode(struct{ Version string }{version})
96 }
97
98 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
99 // sends an HTTP header indicating success, updateOnSuccess first
100 // calls the provided update func. If the update func fails, a 500
101 // response is sent, and the status code and body sent by the handler
102 // are ignored (all response writes return the update error).
103 type updateOnSuccess struct {
104         httpserver.ResponseWriter
105         logger     logrus.FieldLogger
106         update     func() error
107         sentHeader bool
108         err        error
109 }
110
111 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
112         if !uos.sentHeader {
113                 uos.WriteHeader(http.StatusOK)
114         }
115         if uos.err != nil {
116                 return 0, uos.err
117         }
118         return uos.ResponseWriter.Write(p)
119 }
120
121 func (uos *updateOnSuccess) WriteHeader(code int) {
122         if !uos.sentHeader {
123                 uos.sentHeader = true
124                 if code >= 200 && code < 400 {
125                         if uos.err = uos.update(); uos.err != nil {
126                                 code := http.StatusInternalServerError
127                                 if err, ok := uos.err.(*arvados.TransactionError); ok {
128                                         code = err.StatusCode
129                                 }
130                                 uos.logger.WithError(uos.err).Errorf("update() returned error type %T, changing response to HTTP %d", uos.err, code)
131                                 http.Error(uos.ResponseWriter, uos.err.Error(), code)
132                                 return
133                         }
134                 }
135         }
136         uos.ResponseWriter.WriteHeader(code)
137 }
138
139 var (
140         corsAllowHeadersHeader = strings.Join([]string{
141                 "Authorization", "Content-Type", "Range",
142                 // WebDAV request headers:
143                 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout",
144         }, ", ")
145         writeMethod = map[string]bool{
146                 "COPY":      true,
147                 "DELETE":    true,
148                 "LOCK":      true,
149                 "MKCOL":     true,
150                 "MOVE":      true,
151                 "PROPPATCH": true,
152                 "PUT":       true,
153                 "RMCOL":     true,
154                 "UNLOCK":    true,
155         }
156         webdavMethod = map[string]bool{
157                 "COPY":      true,
158                 "DELETE":    true,
159                 "LOCK":      true,
160                 "MKCOL":     true,
161                 "MOVE":      true,
162                 "OPTIONS":   true,
163                 "PROPFIND":  true,
164                 "PROPPATCH": true,
165                 "PUT":       true,
166                 "RMCOL":     true,
167                 "UNLOCK":    true,
168         }
169         browserMethod = map[string]bool{
170                 "GET":  true,
171                 "HEAD": true,
172                 "POST": true,
173         }
174         // top-level dirs to serve with siteFS
175         siteFSDir = map[string]bool{
176                 "":      true, // root directory
177                 "by_id": true,
178                 "users": true,
179         }
180 )
181
182 // ServeHTTP implements http.Handler.
183 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
184         h.setupOnce.Do(h.setup)
185
186         remoteAddr := r.RemoteAddr
187         if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
188                 remoteAddr = xff + "," + remoteAddr
189         }
190         if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
191                 r.URL.Scheme = xfp
192         }
193
194         w := httpserver.WrapResponseWriter(wOrig)
195
196         if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
197                 h.healthHandler.ServeHTTP(w, r)
198                 return
199         }
200
201         if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
202                 if !browserMethod[method] && !webdavMethod[method] {
203                         w.WriteHeader(http.StatusMethodNotAllowed)
204                         return
205                 }
206                 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
207                 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
208                 w.Header().Set("Access-Control-Allow-Origin", "*")
209                 w.Header().Set("Access-Control-Max-Age", "86400")
210                 return
211         }
212
213         if !browserMethod[r.Method] && !webdavMethod[r.Method] {
214                 w.WriteHeader(http.StatusMethodNotAllowed)
215                 return
216         }
217
218         if r.Header.Get("Origin") != "" {
219                 // Allow simple cross-origin requests without user
220                 // credentials ("user credentials" as defined by CORS,
221                 // i.e., cookies, HTTP authentication, and client-side
222                 // SSL certificates. See
223                 // http://www.w3.org/TR/cors/#user-credentials).
224                 w.Header().Set("Access-Control-Allow-Origin", "*")
225                 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
226         }
227
228         pathParts := strings.Split(r.URL.Path[1:], "/")
229
230         var stripParts int
231         var collectionID string
232         var tokens []string
233         var reqTokens []string
234         var pathToken bool
235         var attachment bool
236         var useSiteFS bool
237         credentialsOK := h.Config.cluster.Collections.TrustAllContent
238
239         if r.Host != "" && r.Host == h.Config.cluster.Services.WebDAVDownload.ExternalURL.Host {
240                 credentialsOK = true
241                 attachment = true
242         } else if r.FormValue("disposition") == "attachment" {
243                 attachment = true
244         }
245
246         if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
247                 // http://ID.collections.example/PATH...
248                 credentialsOK = true
249         } else if r.URL.Path == "/status.json" {
250                 h.serveStatus(w, r)
251                 return
252         } else if strings.HasPrefix(r.URL.Path, "/metrics") {
253                 h.MetricsAPI.ServeHTTP(w, r)
254                 return
255         } else if siteFSDir[pathParts[0]] {
256                 useSiteFS = true
257         } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
258                 // /c=ID[/PATH...]
259                 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
260                 stripParts = 1
261         } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
262                 if len(pathParts) >= 4 && pathParts[1] == "download" {
263                         // /collections/download/ID/TOKEN/PATH...
264                         collectionID = parseCollectionIDFromURL(pathParts[2])
265                         tokens = []string{pathParts[3]}
266                         stripParts = 4
267                         pathToken = true
268                 } else {
269                         // /collections/ID/PATH...
270                         collectionID = parseCollectionIDFromURL(pathParts[1])
271                         stripParts = 2
272                         // This path is only meant to work for public
273                         // data. Tokens provided with the request are
274                         // ignored.
275                         credentialsOK = false
276                 }
277         }
278
279         if collectionID == "" && !useSiteFS {
280                 w.WriteHeader(http.StatusNotFound)
281                 return
282         }
283
284         forceReload := false
285         if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
286                 forceReload = true
287         }
288
289         if credentialsOK {
290                 reqTokens = auth.CredentialsFromRequest(r).Tokens
291         }
292
293         formToken := r.FormValue("api_token")
294         if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
295                 // The client provided an explicit token in the POST
296                 // body. The Origin header indicates this *might* be
297                 // an AJAX request, in which case redirect-with-cookie
298                 // won't work: we should just serve the content in the
299                 // POST response. This is safe because:
300                 //
301                 // * We're supplying an attachment, not inline
302                 //   content, so we don't need to convert the POST to
303                 //   a GET and avoid the "really resubmit form?"
304                 //   problem.
305                 //
306                 // * The token isn't embedded in the URL, so we don't
307                 //   need to worry about bookmarks and copy/paste.
308                 reqTokens = append(reqTokens, formToken)
309         } else if formToken != "" && browserMethod[r.Method] {
310                 // The client provided an explicit token in the query
311                 // string, or a form in POST body. We must put the
312                 // token in an HttpOnly cookie, and redirect to the
313                 // same URL with the query param redacted and method =
314                 // GET.
315                 h.seeOtherWithCookie(w, r, "", credentialsOK)
316                 return
317         }
318
319         if useSiteFS {
320                 h.serveSiteFS(w, r, reqTokens, credentialsOK, attachment)
321                 return
322         }
323
324         targetPath := pathParts[stripParts:]
325         if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
326                 // http://ID.example/t=TOKEN/PATH...
327                 // /c=ID/t=TOKEN/PATH...
328                 //
329                 // This form must only be used to pass scoped tokens
330                 // that give permission for a single collection. See
331                 // FormValue case above.
332                 tokens = []string{targetPath[0][2:]}
333                 pathToken = true
334                 targetPath = targetPath[1:]
335                 stripParts++
336         }
337
338         if tokens == nil {
339                 tokens = append(reqTokens, h.Config.cluster.Users.AnonymousUserToken)
340         }
341
342         if len(targetPath) > 0 && targetPath[0] == "_" {
343                 // If a collection has a directory called "t=foo" or
344                 // "_", it can be served at
345                 // //collections.example/_/t=foo/ or
346                 // //collections.example/_/_/ respectively:
347                 // //collections.example/t=foo/ won't work because
348                 // t=foo will be interpreted as a token "foo".
349                 targetPath = targetPath[1:]
350                 stripParts++
351         }
352
353         arv := h.clientPool.Get()
354         if arv == nil {
355                 http.Error(w, "client pool error: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
356                 return
357         }
358         defer h.clientPool.Put(arv)
359
360         var collection *arvados.Collection
361         tokenResult := make(map[string]int)
362         for _, arv.ApiToken = range tokens {
363                 var err error
364                 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
365                 if err == nil {
366                         // Success
367                         break
368                 }
369                 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
370                         switch srvErr.HttpStatusCode {
371                         case 404, 401:
372                                 // Token broken or insufficient to
373                                 // retrieve collection
374                                 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
375                                 continue
376                         }
377                 }
378                 // Something more serious is wrong
379                 http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
380                 return
381         }
382         if collection == nil {
383                 if pathToken || !credentialsOK {
384                         // Either the URL is a "secret sharing link"
385                         // that didn't work out (and asking the client
386                         // for additional credentials would just be
387                         // confusing), or we don't even accept
388                         // credentials at this path.
389                         w.WriteHeader(http.StatusNotFound)
390                         return
391                 }
392                 for _, t := range reqTokens {
393                         if tokenResult[t] == 404 {
394                                 // The client provided valid token(s), but the
395                                 // collection was not found.
396                                 w.WriteHeader(http.StatusNotFound)
397                                 return
398                         }
399                 }
400                 // The client's token was invalid (e.g., expired), or
401                 // the client didn't even provide one.  Propagate the
402                 // 401 to encourage the client to use a [different]
403                 // token.
404                 //
405                 // TODO(TC): This response would be confusing to
406                 // someone trying (anonymously) to download public
407                 // data that has been deleted.  Allow a referrer to
408                 // provide this context somehow?
409                 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
410                 w.WriteHeader(http.StatusUnauthorized)
411                 return
412         }
413
414         kc, err := keepclient.MakeKeepClient(arv)
415         if err != nil {
416                 http.Error(w, "error setting up keep client: "+err.Error(), http.StatusInternalServerError)
417                 return
418         }
419         kc.RequestID = r.Header.Get("X-Request-Id")
420
421         var basename string
422         if len(targetPath) > 0 {
423                 basename = targetPath[len(targetPath)-1]
424         }
425         applyContentDispositionHdr(w, r, basename, attachment)
426
427         client := (&arvados.Client{
428                 APIHost:   arv.ApiServer,
429                 AuthToken: arv.ApiToken,
430                 Insecure:  arv.ApiInsecure,
431         }).WithRequestID(r.Header.Get("X-Request-Id"))
432
433         fs, err := collection.FileSystem(client, kc)
434         if err != nil {
435                 http.Error(w, "error creating collection filesystem: "+err.Error(), http.StatusInternalServerError)
436                 return
437         }
438
439         writefs, writeOK := fs.(arvados.CollectionFileSystem)
440         targetIsPDH := arvadosclient.PDHMatch(collectionID)
441         if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
442                 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
443                 return
444         }
445
446         if webdavMethod[r.Method] {
447                 if writeMethod[r.Method] {
448                         // Save the collection only if/when all
449                         // webdav->filesystem operations succeed --
450                         // and send a 500 error if the modified
451                         // collection can't be saved.
452                         w = &updateOnSuccess{
453                                 ResponseWriter: w,
454                                 logger:         ctxlog.FromContext(r.Context()),
455                                 update: func() error {
456                                         return h.Config.Cache.Update(client, *collection, writefs)
457                                 }}
458                 }
459                 h := webdav.Handler{
460                         Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
461                         FileSystem: &webdavFS{
462                                 collfs:        fs,
463                                 writing:       writeMethod[r.Method],
464                                 alwaysReadEOF: r.Method == "PROPFIND",
465                         },
466                         LockSystem: h.webdavLS,
467                         Logger: func(_ *http.Request, err error) {
468                                 if err != nil {
469                                         ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
470                                 }
471                         },
472                 }
473                 h.ServeHTTP(w, r)
474                 return
475         }
476
477         openPath := "/" + strings.Join(targetPath, "/")
478         if f, err := fs.Open(openPath); os.IsNotExist(err) {
479                 // Requested non-existent path
480                 w.WriteHeader(http.StatusNotFound)
481         } else if err != nil {
482                 // Some other (unexpected) error
483                 http.Error(w, "open: "+err.Error(), http.StatusInternalServerError)
484         } else if stat, err := f.Stat(); err != nil {
485                 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
486                 http.Error(w, "stat: "+err.Error(), http.StatusInternalServerError)
487         } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
488                 // If client requests ".../dirname", redirect to
489                 // ".../dirname/". This way, relative links in the
490                 // listing for "dirname" can always be "fnm", never
491                 // "dirname/fnm".
492                 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
493         } else if stat.IsDir() {
494                 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
495         } else {
496                 http.ServeContent(w, r, basename, stat.ModTime(), f)
497                 if wrote := int64(w.WroteBodyBytes()); wrote != stat.Size() && r.Header.Get("Range") == "" {
498                         // If we wrote fewer bytes than expected, it's
499                         // too late to change the real response code
500                         // or send an error message to the client, but
501                         // at least we can try to put some useful
502                         // debugging info in the logs.
503                         n, err := f.Read(make([]byte, 1024))
504                         ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %s", stat.Size(), wrote, n, err)
505
506                 }
507         }
508 }
509
510 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
511         if len(tokens) == 0 {
512                 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
513                 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
514                 return
515         }
516         if writeMethod[r.Method] {
517                 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
518                 return
519         }
520         arv := h.clientPool.Get()
521         if arv == nil {
522                 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
523                 return
524         }
525         defer h.clientPool.Put(arv)
526         arv.ApiToken = tokens[0]
527
528         kc, err := keepclient.MakeKeepClient(arv)
529         if err != nil {
530                 http.Error(w, "error setting up keep client: "+err.Error(), http.StatusInternalServerError)
531                 return
532         }
533         kc.RequestID = r.Header.Get("X-Request-Id")
534         client := (&arvados.Client{
535                 APIHost:   arv.ApiServer,
536                 AuthToken: arv.ApiToken,
537                 Insecure:  arv.ApiInsecure,
538         }).WithRequestID(r.Header.Get("X-Request-Id"))
539         fs := client.SiteFileSystem(kc)
540         f, err := fs.Open(r.URL.Path)
541         if os.IsNotExist(err) {
542                 http.Error(w, err.Error(), http.StatusNotFound)
543                 return
544         } else if err != nil {
545                 http.Error(w, err.Error(), http.StatusInternalServerError)
546                 return
547         }
548         defer f.Close()
549         if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
550                 if !strings.HasSuffix(r.URL.Path, "/") {
551                         h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
552                 } else {
553                         h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
554                 }
555                 return
556         }
557         if r.Method == "GET" {
558                 _, basename := filepath.Split(r.URL.Path)
559                 applyContentDispositionHdr(w, r, basename, attachment)
560         }
561         wh := webdav.Handler{
562                 Prefix: "/",
563                 FileSystem: &webdavFS{
564                         collfs:        fs,
565                         writing:       writeMethod[r.Method],
566                         alwaysReadEOF: r.Method == "PROPFIND",
567                 },
568                 LockSystem: h.webdavLS,
569                 Logger: func(_ *http.Request, err error) {
570                         if err != nil {
571                                 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
572                         }
573                 },
574         }
575         wh.ServeHTTP(w, r)
576 }
577
578 var dirListingTemplate = `<!DOCTYPE HTML>
579 <HTML><HEAD>
580   <META name="robots" content="NOINDEX">
581   <TITLE>{{ .CollectionName }}</TITLE>
582   <STYLE type="text/css">
583     body {
584       margin: 1.5em;
585     }
586     pre {
587       background-color: #D9EDF7;
588       border-radius: .25em;
589       padding: .75em;
590       overflow: auto;
591     }
592     .footer p {
593       font-size: 82%;
594     }
595     ul {
596       padding: 0;
597     }
598     ul li {
599       font-family: monospace;
600       list-style: none;
601     }
602   </STYLE>
603 </HEAD>
604 <BODY>
605
606 <H1>{{ .CollectionName }}</H1>
607
608 <P>This collection of data files is being shared with you through
609 Arvados.  You can download individual files listed below.  To download
610 the entire directory tree with wget, try:</P>
611
612 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
613
614 <H2>File Listing</H2>
615
616 {{if .Files}}
617 <UL>
618 {{range .Files}}
619 {{if .IsDir }}
620   <LI>{{" " | printf "%15s  " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
621 {{else}}
622   <LI>{{.Size | printf "%15d  " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
623 {{end}}
624 {{end}}
625 </UL>
626 {{else}}
627 <P>(No files; this collection is empty.)</P>
628 {{end}}
629
630 <HR noshade>
631 <DIV class="footer">
632   <P>
633     About Arvados:
634     Arvados is a free and open source software bioinformatics platform.
635     To learn more, visit arvados.org.
636     Arvados is not responsible for the files listed on this page.
637   </P>
638 </DIV>
639
640 </BODY>
641 `
642
643 type fileListEnt struct {
644         Name  string
645         Size  int64
646         IsDir bool
647 }
648
649 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
650         var files []fileListEnt
651         var walk func(string) error
652         if !strings.HasSuffix(base, "/") {
653                 base = base + "/"
654         }
655         walk = func(path string) error {
656                 dirname := base + path
657                 if dirname != "/" {
658                         dirname = strings.TrimSuffix(dirname, "/")
659                 }
660                 d, err := fs.Open(dirname)
661                 if err != nil {
662                         return err
663                 }
664                 ents, err := d.Readdir(-1)
665                 if err != nil {
666                         return err
667                 }
668                 for _, ent := range ents {
669                         if recurse && ent.IsDir() {
670                                 err = walk(path + ent.Name() + "/")
671                                 if err != nil {
672                                         return err
673                                 }
674                         } else {
675                                 files = append(files, fileListEnt{
676                                         Name:  path + ent.Name(),
677                                         Size:  ent.Size(),
678                                         IsDir: ent.IsDir(),
679                                 })
680                         }
681                 }
682                 return nil
683         }
684         if err := walk(""); err != nil {
685                 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
686                 return
687         }
688
689         funcs := template.FuncMap{
690                 "nbsp": func(s string) template.HTML {
691                         return template.HTML(strings.Replace(s, " ", "&nbsp;", -1))
692                 },
693         }
694         tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
695         if err != nil {
696                 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
697                 return
698         }
699         sort.Slice(files, func(i, j int) bool {
700                 return files[i].Name < files[j].Name
701         })
702         w.WriteHeader(http.StatusOK)
703         tmpl.Execute(w, map[string]interface{}{
704                 "CollectionName": collectionName,
705                 "Files":          files,
706                 "Request":        r,
707                 "StripParts":     strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
708         })
709 }
710
711 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
712         disposition := "inline"
713         if isAttachment {
714                 disposition = "attachment"
715         }
716         if strings.ContainsRune(r.RequestURI, '?') {
717                 // Help the UA realize that the filename is just
718                 // "filename.txt", not
719                 // "filename.txt?disposition=attachment".
720                 //
721                 // TODO(TC): Follow advice at RFC 6266 appendix D
722                 disposition += "; filename=" + strconv.QuoteToASCII(filename)
723         }
724         if disposition != "inline" {
725                 w.Header().Set("Content-Disposition", disposition)
726         }
727 }
728
729 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
730         if formToken := r.FormValue("api_token"); formToken != "" {
731                 if !credentialsOK {
732                         // It is not safe to copy the provided token
733                         // into a cookie unless the current vhost
734                         // (origin) serves only a single collection or
735                         // we are in TrustAllContent mode.
736                         http.Error(w, "cannot serve inline content at this URL (possible configuration error; see https://doc.arvados.org/install/install-keep-web.html#dns)", http.StatusBadRequest)
737                         return
738                 }
739
740                 // The HttpOnly flag is necessary to prevent
741                 // JavaScript code (included in, or loaded by, a page
742                 // in the collection being served) from employing the
743                 // user's token beyond reading other files in the same
744                 // domain, i.e., same collection.
745                 //
746                 // The 303 redirect is necessary in the case of a GET
747                 // request to avoid exposing the token in the Location
748                 // bar, and in the case of a POST request to avoid
749                 // raising warnings when the user refreshes the
750                 // resulting page.
751                 http.SetCookie(w, &http.Cookie{
752                         Name:     "arvados_api_token",
753                         Value:    auth.EncodeTokenCookie([]byte(formToken)),
754                         Path:     "/",
755                         HttpOnly: true,
756                 })
757         }
758
759         // Propagate query parameters (except api_token) from
760         // the original request.
761         redirQuery := r.URL.Query()
762         redirQuery.Del("api_token")
763
764         u := r.URL
765         if location != "" {
766                 newu, err := u.Parse(location)
767                 if err != nil {
768                         w.WriteHeader(http.StatusInternalServerError)
769                         return
770                 }
771                 u = newu
772         }
773         redir := (&url.URL{
774                 Scheme:   r.URL.Scheme,
775                 Host:     r.Host,
776                 Path:     u.Path,
777                 RawQuery: redirQuery.Encode(),
778         }).String()
779
780         w.Header().Add("Location", redir)
781         w.WriteHeader(http.StatusSeeOther)
782         io.WriteString(w, `<A href="`)
783         io.WriteString(w, html.EscapeString(redir))
784         io.WriteString(w, `">Continue</A>`)
785 }