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