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