20259: Add documentation for banner and tooltip features
[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 keepweb
6
7 import (
8         "encoding/json"
9         "errors"
10         "fmt"
11         "html"
12         "html/template"
13         "io"
14         "net/http"
15         "net/url"
16         "os"
17         "sort"
18         "strconv"
19         "strings"
20         "sync"
21
22         "git.arvados.org/arvados.git/lib/cmd"
23         "git.arvados.org/arvados.git/sdk/go/arvados"
24         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
25         "git.arvados.org/arvados.git/sdk/go/auth"
26         "git.arvados.org/arvados.git/sdk/go/ctxlog"
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         Cache     cache
35         Cluster   *arvados.Cluster
36         setupOnce sync.Once
37         webdavLS  webdav.LockSystem
38 }
39
40 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
41
42 var notFoundMessage = "Not Found"
43 var unauthorizedMessage = "401 Unauthorized\n\nA valid Arvados token must be provided to access this resource."
44
45 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
46 // PDH (even if it is a PDH with "+" replaced by " " or "-");
47 // otherwise "".
48 func parseCollectionIDFromURL(s string) string {
49         if arvadosclient.UUIDMatch(s) {
50                 return s
51         }
52         if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
53                 return pdh
54         }
55         return ""
56 }
57
58 func (h *handler) setup() {
59         keepclient.DefaultBlockCache.MaxBlocks = h.Cluster.Collections.WebDAVCache.MaxBlockEntries
60
61         // Even though we don't accept LOCK requests, every webdav
62         // handler must have a non-nil LockSystem.
63         h.webdavLS = &noLockSystem{}
64 }
65
66 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
67         json.NewEncoder(w).Encode(struct{ Version string }{cmd.Version.String()})
68 }
69
70 type errorWithHTTPStatus interface {
71         HTTPStatus() int
72 }
73
74 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
75 // sends an HTTP header indicating success, updateOnSuccess first
76 // calls the provided update func. If the update func fails, an error
77 // response is sent (using the error's HTTP status or 500 if none),
78 // and the status code and body sent by the handler are ignored (all
79 // response writes return the update error).
80 type updateOnSuccess struct {
81         httpserver.ResponseWriter
82         logger     logrus.FieldLogger
83         update     func() error
84         sentHeader bool
85         err        error
86 }
87
88 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
89         if !uos.sentHeader {
90                 uos.WriteHeader(http.StatusOK)
91         }
92         if uos.err != nil {
93                 return 0, uos.err
94         }
95         return uos.ResponseWriter.Write(p)
96 }
97
98 func (uos *updateOnSuccess) WriteHeader(code int) {
99         if !uos.sentHeader {
100                 uos.sentHeader = true
101                 if code >= 200 && code < 400 {
102                         if uos.err = uos.update(); uos.err != nil {
103                                 code := http.StatusInternalServerError
104                                 if he := errorWithHTTPStatus(nil); errors.As(uos.err, &he) {
105                                         code = he.HTTPStatus()
106                                 }
107                                 uos.logger.WithError(uos.err).Errorf("update() returned %T error, changing response to HTTP %d", uos.err, code)
108                                 http.Error(uos.ResponseWriter, uos.err.Error(), code)
109                                 return
110                         }
111                 }
112         }
113         uos.ResponseWriter.WriteHeader(code)
114 }
115
116 var (
117         corsAllowHeadersHeader = strings.Join([]string{
118                 "Authorization", "Content-Type", "Range",
119                 // WebDAV request headers:
120                 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout", "Cache-Control",
121         }, ", ")
122         writeMethod = map[string]bool{
123                 "COPY":      true,
124                 "DELETE":    true,
125                 "LOCK":      true,
126                 "MKCOL":     true,
127                 "MOVE":      true,
128                 "PROPPATCH": true,
129                 "PUT":       true,
130                 "RMCOL":     true,
131                 "UNLOCK":    true,
132         }
133         webdavMethod = map[string]bool{
134                 "COPY":      true,
135                 "DELETE":    true,
136                 "LOCK":      true,
137                 "MKCOL":     true,
138                 "MOVE":      true,
139                 "OPTIONS":   true,
140                 "PROPFIND":  true,
141                 "PROPPATCH": true,
142                 "PUT":       true,
143                 "RMCOL":     true,
144                 "UNLOCK":    true,
145         }
146         browserMethod = map[string]bool{
147                 "GET":  true,
148                 "HEAD": true,
149                 "POST": true,
150         }
151         // top-level dirs to serve with siteFS
152         siteFSDir = map[string]bool{
153                 "":      true, // root directory
154                 "by_id": true,
155                 "users": true,
156         }
157 )
158
159 func stripDefaultPort(host string) string {
160         // Will consider port 80 and port 443 to be the same vhost.  I think that's fine.
161         u := &url.URL{Host: host}
162         if p := u.Port(); p == "80" || p == "443" {
163                 return strings.ToLower(u.Hostname())
164         } else {
165                 return strings.ToLower(host)
166         }
167 }
168
169 // CheckHealth implements service.Handler.
170 func (h *handler) CheckHealth() error {
171         return nil
172 }
173
174 // Done implements service.Handler.
175 func (h *handler) Done() <-chan struct{} {
176         return nil
177 }
178
179 // ServeHTTP implements http.Handler.
180 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
181         h.setupOnce.Do(h.setup)
182
183         if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
184                 r.URL.Scheme = xfp
185         }
186
187         w := httpserver.WrapResponseWriter(wOrig)
188
189         if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
190                 if !browserMethod[method] && !webdavMethod[method] {
191                         w.WriteHeader(http.StatusMethodNotAllowed)
192                         return
193                 }
194                 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
195                 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
196                 w.Header().Set("Access-Control-Allow-Origin", "*")
197                 w.Header().Set("Access-Control-Max-Age", "86400")
198                 return
199         }
200
201         if !browserMethod[r.Method] && !webdavMethod[r.Method] {
202                 w.WriteHeader(http.StatusMethodNotAllowed)
203                 return
204         }
205
206         if r.Header.Get("Origin") != "" {
207                 // Allow simple cross-origin requests without user
208                 // credentials ("user credentials" as defined by CORS,
209                 // i.e., cookies, HTTP authentication, and client-side
210                 // SSL certificates. See
211                 // http://www.w3.org/TR/cors/#user-credentials).
212                 w.Header().Set("Access-Control-Allow-Origin", "*")
213                 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
214         }
215
216         if h.serveS3(w, r) {
217                 return
218         }
219
220         pathParts := strings.Split(r.URL.Path[1:], "/")
221
222         var stripParts int
223         var collectionID string
224         var tokens []string
225         var reqTokens []string
226         var pathToken bool
227         var attachment bool
228         var useSiteFS bool
229         credentialsOK := h.Cluster.Collections.TrustAllContent
230         reasonNotAcceptingCredentials := ""
231
232         if r.Host != "" && stripDefaultPort(r.Host) == stripDefaultPort(h.Cluster.Services.WebDAVDownload.ExternalURL.Host) {
233                 credentialsOK = true
234                 attachment = true
235         } else if r.FormValue("disposition") == "attachment" {
236                 attachment = true
237         }
238
239         if !credentialsOK {
240                 reasonNotAcceptingCredentials = fmt.Sprintf("vhost %q does not specify a single collection ID or match Services.WebDAVDownload.ExternalURL %q, and Collections.TrustAllContent is false",
241                         r.Host, h.Cluster.Services.WebDAVDownload.ExternalURL)
242         }
243
244         if collectionID = arvados.CollectionIDFromDNSName(r.Host); collectionID != "" {
245                 // http://ID.collections.example/PATH...
246                 credentialsOK = true
247         } else if r.URL.Path == "/status.json" {
248                 h.serveStatus(w, r)
249                 return
250         } else if siteFSDir[pathParts[0]] {
251                 useSiteFS = true
252         } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
253                 // /c=ID[/PATH...]
254                 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
255                 stripParts = 1
256         } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
257                 if len(pathParts) >= 4 && pathParts[1] == "download" {
258                         // /collections/download/ID/TOKEN/PATH...
259                         collectionID = parseCollectionIDFromURL(pathParts[2])
260                         tokens = []string{pathParts[3]}
261                         stripParts = 4
262                         pathToken = true
263                 } else {
264                         // /collections/ID/PATH...
265                         collectionID = parseCollectionIDFromURL(pathParts[1])
266                         stripParts = 2
267                         // This path is only meant to work for public
268                         // data. Tokens provided with the request are
269                         // ignored.
270                         credentialsOK = false
271                         reasonNotAcceptingCredentials = "the '/collections/UUID/PATH' form only works for public data"
272                 }
273         }
274
275         forceReload := false
276         if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
277                 forceReload = true
278         }
279
280         if credentialsOK {
281                 reqTokens = auth.CredentialsFromRequest(r).Tokens
282         }
283
284         formToken := r.FormValue("api_token")
285         origin := r.Header.Get("Origin")
286         cors := origin != "" && !strings.HasSuffix(origin, "://"+r.Host)
287         safeAjax := cors && (r.Method == http.MethodGet || r.Method == http.MethodHead)
288         safeAttachment := attachment && r.URL.Query().Get("api_token") == ""
289         if formToken == "" {
290                 // No token to use or redact.
291         } else if safeAjax || safeAttachment {
292                 // If this is a cross-origin request, the URL won't
293                 // appear in the browser's address bar, so
294                 // substituting a clipboard-safe URL is pointless.
295                 // Redirect-with-cookie wouldn't work anyway, because
296                 // it's not safe to allow third-party use of our
297                 // cookie.
298                 //
299                 // If we're supplying an attachment, we don't need to
300                 // convert POST to GET to avoid the "really resubmit
301                 // form?" problem, so provided the token isn't
302                 // embedded in the URL, there's no reason to do
303                 // redirect-with-cookie in this case either.
304                 reqTokens = append(reqTokens, formToken)
305         } else if browserMethod[r.Method] {
306                 // If this is a page view, and the client provided a
307                 // token via query string or POST body, we must put
308                 // the token in an HttpOnly cookie, and redirect to an
309                 // equivalent URL with the query param redacted and
310                 // method = GET.
311                 h.seeOtherWithCookie(w, r, "", credentialsOK)
312                 return
313         }
314
315         targetPath := pathParts[stripParts:]
316         if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
317                 // http://ID.example/t=TOKEN/PATH...
318                 // /c=ID/t=TOKEN/PATH...
319                 //
320                 // This form must only be used to pass scoped tokens
321                 // that give permission for a single collection. See
322                 // FormValue case above.
323                 tokens = []string{targetPath[0][2:]}
324                 pathToken = true
325                 targetPath = targetPath[1:]
326                 stripParts++
327         }
328
329         fsprefix := ""
330         if useSiteFS {
331                 if writeMethod[r.Method] {
332                         http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
333                         return
334                 }
335                 if len(reqTokens) == 0 {
336                         w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
337                         http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
338                         return
339                 }
340                 tokens = reqTokens
341         } else if collectionID == "" {
342                 http.Error(w, notFoundMessage, http.StatusNotFound)
343                 return
344         } else {
345                 fsprefix = "by_id/" + collectionID + "/"
346         }
347
348         if tokens == nil {
349                 tokens = reqTokens
350                 if h.Cluster.Users.AnonymousUserToken != "" {
351                         tokens = append(tokens, h.Cluster.Users.AnonymousUserToken)
352                 }
353         }
354
355         if len(targetPath) > 0 && targetPath[0] == "_" {
356                 // If a collection has a directory called "t=foo" or
357                 // "_", it can be served at
358                 // //collections.example/_/t=foo/ or
359                 // //collections.example/_/_/ respectively:
360                 // //collections.example/t=foo/ won't work because
361                 // t=foo will be interpreted as a token "foo".
362                 targetPath = targetPath[1:]
363                 stripParts++
364         }
365
366         dirOpenMode := os.O_RDONLY
367         if writeMethod[r.Method] {
368                 dirOpenMode = os.O_RDWR
369         }
370
371         var tokenValid bool
372         var tokenScopeProblem bool
373         var token string
374         var tokenUser *arvados.User
375         var sessionFS arvados.CustomFileSystem
376         var session *cachedSession
377         var collectionDir arvados.File
378         for _, token = range tokens {
379                 var statusErr errorWithHTTPStatus
380                 fs, sess, user, err := h.Cache.GetSession(token)
381                 if errors.As(err, &statusErr) && statusErr.HTTPStatus() == http.StatusUnauthorized {
382                         // bad token
383                         continue
384                 } else if err != nil {
385                         http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
386                         return
387                 }
388                 if token != h.Cluster.Users.AnonymousUserToken {
389                         tokenValid = true
390                 }
391                 f, err := fs.OpenFile(fsprefix, dirOpenMode, 0)
392                 if errors.As(err, &statusErr) &&
393                         statusErr.HTTPStatus() == http.StatusForbidden &&
394                         token != h.Cluster.Users.AnonymousUserToken {
395                         // collection id is outside scope of supplied
396                         // token
397                         tokenScopeProblem = true
398                         continue
399                 } else if os.IsNotExist(err) {
400                         // collection does not exist or is not
401                         // readable using this token
402                         continue
403                 } else if err != nil {
404                         http.Error(w, err.Error(), http.StatusInternalServerError)
405                         return
406                 }
407                 defer f.Close()
408
409                 collectionDir, sessionFS, session, tokenUser = f, fs, sess, user
410                 break
411         }
412         if forceReload && collectionDir != nil {
413                 err := collectionDir.Sync()
414                 if err != nil {
415                         if he := errorWithHTTPStatus(nil); errors.As(err, &he) {
416                                 http.Error(w, err.Error(), he.HTTPStatus())
417                         } else {
418                                 http.Error(w, err.Error(), http.StatusInternalServerError)
419                         }
420                         return
421                 }
422         }
423         if session == nil {
424                 if pathToken {
425                         // The URL is a "secret sharing link" that
426                         // didn't work out.  Asking the client for
427                         // additional credentials would just be
428                         // confusing.
429                         http.Error(w, notFoundMessage, http.StatusNotFound)
430                         return
431                 }
432                 if tokenValid {
433                         // The client provided valid token(s), but the
434                         // collection was not found.
435                         http.Error(w, notFoundMessage, http.StatusNotFound)
436                         return
437                 }
438                 if tokenScopeProblem {
439                         // The client provided a valid token but
440                         // fetching a collection returned 401, which
441                         // means the token scope doesn't permit
442                         // fetching that collection.
443                         http.Error(w, notFoundMessage, http.StatusForbidden)
444                         return
445                 }
446                 // The client's token was invalid (e.g., expired), or
447                 // the client didn't even provide one.  Redirect to
448                 // workbench2's login-and-redirect-to-download url if
449                 // this is a browser navigation request. (The redirect
450                 // flow can't preserve the original method if it's not
451                 // GET, and doesn't make sense if the UA is a
452                 // command-line tool, is trying to load an inline
453                 // image, etc.; in these cases, there's nothing we can
454                 // do, so return 401 unauthorized.)
455                 //
456                 // Note Sec-Fetch-Mode is sent by all non-EOL
457                 // browsers, except Safari.
458                 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-Fetch-Mode
459                 //
460                 // TODO(TC): This response would be confusing to
461                 // someone trying (anonymously) to download public
462                 // data that has been deleted.  Allow a referrer to
463                 // provide this context somehow?
464                 if r.Method == http.MethodGet && r.Header.Get("Sec-Fetch-Mode") == "navigate" {
465                         target := url.URL(h.Cluster.Services.Workbench2.ExternalURL)
466                         redirkey := "redirectToPreview"
467                         if attachment {
468                                 redirkey = "redirectToDownload"
469                         }
470                         callback := "/c=" + collectionID + "/" + strings.Join(targetPath, "/")
471                         // target.RawQuery = url.Values{redirkey:
472                         // {target}}.Encode() would be the obvious
473                         // thing to do here, but wb2 doesn't decode
474                         // this as a query param -- it takes
475                         // everything after "${redirkey}=" as the
476                         // target URL. If we encode "/" as "%2F" etc.,
477                         // the redirect won't work.
478                         target.RawQuery = redirkey + "=" + callback
479                         w.Header().Add("Location", target.String())
480                         w.WriteHeader(http.StatusSeeOther)
481                         return
482                 }
483                 if !credentialsOK {
484                         http.Error(w, fmt.Sprintf("Authorization tokens are not accepted here: %v, and no anonymous user token is configured.", reasonNotAcceptingCredentials), http.StatusUnauthorized)
485                         return
486                 }
487                 // If none of the above cases apply, suggest the
488                 // user-agent (which is either a non-browser agent
489                 // like wget, or a browser that can't redirect through
490                 // a login flow) prompt the user for credentials.
491                 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
492                 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
493                 return
494         }
495
496         if r.Method == http.MethodGet || r.Method == http.MethodHead {
497                 targetfnm := fsprefix + strings.Join(pathParts[stripParts:], "/")
498                 if fi, err := sessionFS.Stat(targetfnm); err == nil && fi.IsDir() {
499                         if !strings.HasSuffix(r.URL.Path, "/") {
500                                 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
501                         } else {
502                                 h.serveDirectory(w, r, fi.Name(), sessionFS, targetfnm, !useSiteFS)
503                         }
504                         return
505                 }
506         }
507
508         var basename string
509         if len(targetPath) > 0 {
510                 basename = targetPath[len(targetPath)-1]
511         }
512         if arvadosclient.PDHMatch(collectionID) && writeMethod[r.Method] {
513                 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
514                 return
515         }
516         if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
517                 http.Error(w, "Not permitted", http.StatusForbidden)
518                 return
519         }
520         h.logUploadOrDownload(r, session.arvadosclient, sessionFS, fsprefix+strings.Join(targetPath, "/"), nil, tokenUser)
521
522         if writeMethod[r.Method] {
523                 // Save the collection only if/when all
524                 // webdav->filesystem operations succeed --
525                 // and send a 500 error if the modified
526                 // collection can't be saved.
527                 //
528                 // Perform the write in a separate sitefs, so
529                 // concurrent read operations on the same
530                 // collection see the previous saved
531                 // state. After the write succeeds and the
532                 // collection record is updated, we reset the
533                 // session so the updates are visible in
534                 // subsequent read requests.
535                 client := session.client.WithRequestID(r.Header.Get("X-Request-Id"))
536                 sessionFS = client.SiteFileSystem(session.keepclient)
537                 writingDir, err := sessionFS.OpenFile(fsprefix, os.O_RDONLY, 0)
538                 if err != nil {
539                         http.Error(w, err.Error(), http.StatusInternalServerError)
540                         return
541                 }
542                 defer writingDir.Close()
543                 w = &updateOnSuccess{
544                         ResponseWriter: w,
545                         logger:         ctxlog.FromContext(r.Context()),
546                         update: func() error {
547                                 err := writingDir.Sync()
548                                 var te arvados.TransactionError
549                                 if errors.As(err, &te) {
550                                         err = te
551                                 }
552                                 if err != nil {
553                                         return err
554                                 }
555                                 // Sync the changes to the persistent
556                                 // sessionfs for this token.
557                                 snap, err := writingDir.Snapshot()
558                                 if err != nil {
559                                         return err
560                                 }
561                                 collectionDir.Splice(snap)
562                                 return nil
563                         }}
564         }
565         if r.Method == http.MethodGet {
566                 applyContentDispositionHdr(w, r, basename, attachment)
567         }
568         wh := webdav.Handler{
569                 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
570                 FileSystem: &webdavFS{
571                         collfs:        sessionFS,
572                         prefix:        fsprefix,
573                         writing:       writeMethod[r.Method],
574                         alwaysReadEOF: r.Method == "PROPFIND",
575                 },
576                 LockSystem: h.webdavLS,
577                 Logger: func(r *http.Request, err error) {
578                         if err != nil {
579                                 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
580                         }
581                 },
582         }
583         wh.ServeHTTP(w, r)
584         if r.Method == http.MethodGet && w.WroteStatus() == http.StatusOK {
585                 wrote := int64(w.WroteBodyBytes())
586                 fnm := strings.Join(pathParts[stripParts:], "/")
587                 fi, err := wh.FileSystem.Stat(r.Context(), fnm)
588                 if err == nil && fi.Size() != wrote {
589                         var n int
590                         f, err := wh.FileSystem.OpenFile(r.Context(), fnm, os.O_RDONLY, 0)
591                         if err == nil {
592                                 n, err = f.Read(make([]byte, 1024))
593                                 f.Close()
594                         }
595                         ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %v", fi.Size(), wrote, n, err)
596                 }
597         }
598 }
599
600 var dirListingTemplate = `<!DOCTYPE HTML>
601 <HTML><HEAD>
602   <META name="robots" content="NOINDEX">
603   <TITLE>{{ .CollectionName }}</TITLE>
604   <STYLE type="text/css">
605     body {
606       margin: 1.5em;
607     }
608     pre {
609       background-color: #D9EDF7;
610       border-radius: .25em;
611       padding: .75em;
612       overflow: auto;
613     }
614     .footer p {
615       font-size: 82%;
616     }
617     ul {
618       padding: 0;
619     }
620     ul li {
621       font-family: monospace;
622       list-style: none;
623     }
624   </STYLE>
625 </HEAD>
626 <BODY>
627
628 <H1>{{ .CollectionName }}</H1>
629
630 <P>This collection of data files is being shared with you through
631 Arvados.  You can download individual files listed below.  To download
632 the entire directory tree with wget, try:</P>
633
634 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
635
636 <H2>File Listing</H2>
637
638 {{if .Files}}
639 <UL>
640 {{range .Files}}
641 {{if .IsDir }}
642   <LI>{{" " | printf "%15s  " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
643 {{else}}
644   <LI>{{.Size | printf "%15d  " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
645 {{end}}
646 {{end}}
647 </UL>
648 {{else}}
649 <P>(No files; this collection is empty.)</P>
650 {{end}}
651
652 <HR noshade>
653 <DIV class="footer">
654   <P>
655     About Arvados:
656     Arvados is a free and open source software bioinformatics platform.
657     To learn more, visit arvados.org.
658     Arvados is not responsible for the files listed on this page.
659   </P>
660 </DIV>
661
662 </BODY>
663 `
664
665 type fileListEnt struct {
666         Name  string
667         Size  int64
668         IsDir bool
669 }
670
671 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
672         var files []fileListEnt
673         var walk func(string) error
674         if !strings.HasSuffix(base, "/") {
675                 base = base + "/"
676         }
677         walk = func(path string) error {
678                 dirname := base + path
679                 if dirname != "/" {
680                         dirname = strings.TrimSuffix(dirname, "/")
681                 }
682                 d, err := fs.Open(dirname)
683                 if err != nil {
684                         return err
685                 }
686                 ents, err := d.Readdir(-1)
687                 if err != nil {
688                         return err
689                 }
690                 for _, ent := range ents {
691                         if recurse && ent.IsDir() {
692                                 err = walk(path + ent.Name() + "/")
693                                 if err != nil {
694                                         return err
695                                 }
696                         } else {
697                                 files = append(files, fileListEnt{
698                                         Name:  path + ent.Name(),
699                                         Size:  ent.Size(),
700                                         IsDir: ent.IsDir(),
701                                 })
702                         }
703                 }
704                 return nil
705         }
706         if err := walk(""); err != nil {
707                 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
708                 return
709         }
710
711         funcs := template.FuncMap{
712                 "nbsp": func(s string) template.HTML {
713                         return template.HTML(strings.Replace(s, " ", "&nbsp;", -1))
714                 },
715         }
716         tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
717         if err != nil {
718                 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
719                 return
720         }
721         sort.Slice(files, func(i, j int) bool {
722                 return files[i].Name < files[j].Name
723         })
724         w.WriteHeader(http.StatusOK)
725         tmpl.Execute(w, map[string]interface{}{
726                 "CollectionName": collectionName,
727                 "Files":          files,
728                 "Request":        r,
729                 "StripParts":     strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
730         })
731 }
732
733 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
734         disposition := "inline"
735         if isAttachment {
736                 disposition = "attachment"
737         }
738         if strings.ContainsRune(r.RequestURI, '?') {
739                 // Help the UA realize that the filename is just
740                 // "filename.txt", not
741                 // "filename.txt?disposition=attachment".
742                 //
743                 // TODO(TC): Follow advice at RFC 6266 appendix D
744                 disposition += "; filename=" + strconv.QuoteToASCII(filename)
745         }
746         if disposition != "inline" {
747                 w.Header().Set("Content-Disposition", disposition)
748         }
749 }
750
751 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
752         if formToken := r.FormValue("api_token"); formToken != "" {
753                 if !credentialsOK {
754                         // It is not safe to copy the provided token
755                         // into a cookie unless the current vhost
756                         // (origin) serves only a single collection or
757                         // we are in TrustAllContent mode.
758                         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)
759                         return
760                 }
761
762                 // The HttpOnly flag is necessary to prevent
763                 // JavaScript code (included in, or loaded by, a page
764                 // in the collection being served) from employing the
765                 // user's token beyond reading other files in the same
766                 // domain, i.e., same collection.
767                 //
768                 // The 303 redirect is necessary in the case of a GET
769                 // request to avoid exposing the token in the Location
770                 // bar, and in the case of a POST request to avoid
771                 // raising warnings when the user refreshes the
772                 // resulting page.
773                 http.SetCookie(w, &http.Cookie{
774                         Name:     "arvados_api_token",
775                         Value:    auth.EncodeTokenCookie([]byte(formToken)),
776                         Path:     "/",
777                         HttpOnly: true,
778                         SameSite: http.SameSiteLaxMode,
779                 })
780         }
781
782         // Propagate query parameters (except api_token) from
783         // the original request.
784         redirQuery := r.URL.Query()
785         redirQuery.Del("api_token")
786
787         u := r.URL
788         if location != "" {
789                 newu, err := u.Parse(location)
790                 if err != nil {
791                         http.Error(w, "error resolving redirect target: "+err.Error(), http.StatusInternalServerError)
792                         return
793                 }
794                 u = newu
795         }
796         redir := (&url.URL{
797                 Scheme:   r.URL.Scheme,
798                 Host:     r.Host,
799                 Path:     u.Path,
800                 RawQuery: redirQuery.Encode(),
801         }).String()
802
803         w.Header().Add("Location", redir)
804         w.WriteHeader(http.StatusSeeOther)
805         io.WriteString(w, `<A href="`)
806         io.WriteString(w, html.EscapeString(redir))
807         io.WriteString(w, `">Continue</A>`)
808 }
809
810 func (h *handler) userPermittedToUploadOrDownload(method string, tokenUser *arvados.User) bool {
811         var permitDownload bool
812         var permitUpload bool
813         if tokenUser != nil && tokenUser.IsAdmin {
814                 permitUpload = h.Cluster.Collections.WebDAVPermission.Admin.Upload
815                 permitDownload = h.Cluster.Collections.WebDAVPermission.Admin.Download
816         } else {
817                 permitUpload = h.Cluster.Collections.WebDAVPermission.User.Upload
818                 permitDownload = h.Cluster.Collections.WebDAVPermission.User.Download
819         }
820         if (method == "PUT" || method == "POST") && !permitUpload {
821                 // Disallow operations that upload new files.
822                 // Permit webdav operations that move existing files around.
823                 return false
824         } else if method == "GET" && !permitDownload {
825                 // Disallow downloading file contents.
826                 // Permit webdav operations like PROPFIND that retrieve metadata
827                 // but not file contents.
828                 return false
829         }
830         return true
831 }
832
833 func (h *handler) logUploadOrDownload(
834         r *http.Request,
835         client *arvadosclient.ArvadosClient,
836         fs arvados.CustomFileSystem,
837         filepath string,
838         collection *arvados.Collection,
839         user *arvados.User) {
840
841         log := ctxlog.FromContext(r.Context())
842         props := make(map[string]string)
843         props["reqPath"] = r.URL.Path
844         var useruuid string
845         if user != nil {
846                 log = log.WithField("user_uuid", user.UUID).
847                         WithField("user_full_name", user.FullName)
848                 useruuid = user.UUID
849         } else {
850                 useruuid = fmt.Sprintf("%s-tpzed-anonymouspublic", h.Cluster.ClusterID)
851         }
852         if collection == nil && fs != nil {
853                 collection, filepath = h.determineCollection(fs, filepath)
854         }
855         if collection != nil {
856                 log = log.WithField("collection_file_path", filepath)
857                 props["collection_file_path"] = filepath
858                 // h.determineCollection populates the collection_uuid
859                 // prop with the PDH, if this collection is being
860                 // accessed via PDH. For logging, we use a different
861                 // field depending on whether it's a UUID or PDH.
862                 if len(collection.UUID) > 32 {
863                         log = log.WithField("portable_data_hash", collection.UUID)
864                         props["portable_data_hash"] = collection.UUID
865                 } else {
866                         log = log.WithField("collection_uuid", collection.UUID)
867                         props["collection_uuid"] = collection.UUID
868                 }
869         }
870         if r.Method == "PUT" || r.Method == "POST" {
871                 log.Info("File upload")
872                 if h.Cluster.Collections.WebDAVLogEvents {
873                         go func() {
874                                 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
875                                         "object_uuid": useruuid,
876                                         "event_type":  "file_upload",
877                                         "properties":  props}}
878                                 err := client.Create("logs", lr, nil)
879                                 if err != nil {
880                                         log.WithError(err).Error("Failed to create upload log event on API server")
881                                 }
882                         }()
883                 }
884         } else if r.Method == "GET" {
885                 if collection != nil && collection.PortableDataHash != "" {
886                         log = log.WithField("portable_data_hash", collection.PortableDataHash)
887                         props["portable_data_hash"] = collection.PortableDataHash
888                 }
889                 log.Info("File download")
890                 if h.Cluster.Collections.WebDAVLogEvents {
891                         go func() {
892                                 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
893                                         "object_uuid": useruuid,
894                                         "event_type":  "file_download",
895                                         "properties":  props}}
896                                 err := client.Create("logs", lr, nil)
897                                 if err != nil {
898                                         log.WithError(err).Error("Failed to create download log event on API server")
899                                 }
900                         }()
901                 }
902         }
903 }
904
905 func (h *handler) determineCollection(fs arvados.CustomFileSystem, path string) (*arvados.Collection, string) {
906         target := strings.TrimSuffix(path, "/")
907         for cut := len(target); cut >= 0; cut = strings.LastIndexByte(target, '/') {
908                 target = target[:cut]
909                 fi, err := fs.Stat(target)
910                 if os.IsNotExist(err) {
911                         // creating a new file/dir, or download
912                         // destined to fail
913                         continue
914                 } else if err != nil {
915                         return nil, ""
916                 }
917                 switch src := fi.Sys().(type) {
918                 case *arvados.Collection:
919                         return src, strings.TrimPrefix(path[len(target):], "/")
920                 case *arvados.Group:
921                         return nil, ""
922                 default:
923                         if _, ok := src.(error); ok {
924                                 return nil, ""
925                         }
926                 }
927         }
928         return nil, ""
929 }