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