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