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