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