1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
28 "git.arvados.org/arvados.git/lib/cmd"
29 "git.arvados.org/arvados.git/lib/ctrlctx"
30 "git.arvados.org/arvados.git/lib/webdavfs"
31 "git.arvados.org/arvados.git/sdk/go/arvados"
32 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
33 "git.arvados.org/arvados.git/sdk/go/auth"
34 "git.arvados.org/arvados.git/sdk/go/ctxlog"
35 "git.arvados.org/arvados.git/sdk/go/httpserver"
36 "github.com/gotd/contrib/http_range"
37 "github.com/sirupsen/logrus"
38 "golang.org/x/net/webdav"
43 Cluster *arvados.Cluster
46 fileEventLogs map[fileEventLog]time.Time
47 fileEventLogsMtx sync.Mutex
48 fileEventLogsNextTidy time.Time
50 s3SecretCache map[string]*cachedS3Secret
51 s3SecretCacheMtx sync.Mutex
52 s3SecretCacheNextTidy time.Time
54 dbConnector *ctrlctx.DBConnector
55 dbConnectorMtx sync.Mutex
60 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
62 var notFoundMessage = "Not Found"
63 var unauthorizedMessage = "401 Unauthorized\n\nA valid Arvados token must be provided to access this resource."
65 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
66 // PDH (even if it is a PDH with "+" replaced by " " or "-");
68 func parseCollectionIDFromURL(s string) string {
69 if arvadosclient.UUIDMatch(s) {
72 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
78 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
79 json.NewEncoder(w).Encode(struct{ Version string }{cmd.Version.String()})
82 type errorWithHTTPStatus interface {
86 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
87 // sends an HTTP header indicating success, updateOnSuccess first
88 // calls the provided update func. If the update func fails, an error
89 // response is sent (using the error's HTTP status or 500 if none),
90 // and the status code and body sent by the handler are ignored (all
91 // response writes return the update error).
92 type updateOnSuccess struct {
93 httpserver.ResponseWriter
94 logger logrus.FieldLogger
100 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
102 uos.WriteHeader(http.StatusOK)
107 return uos.ResponseWriter.Write(p)
110 func (uos *updateOnSuccess) WriteHeader(code int) {
112 uos.sentHeader = true
113 if code >= 200 && code < 400 {
114 if uos.err = uos.update(); uos.err != nil {
115 code := http.StatusInternalServerError
116 if he := errorWithHTTPStatus(nil); errors.As(uos.err, &he) {
117 code = he.HTTPStatus()
119 uos.logger.WithError(uos.err).Errorf("update() returned %T error, changing response to HTTP %d", uos.err, code)
120 http.Error(uos.ResponseWriter, uos.err.Error(), code)
125 uos.ResponseWriter.WriteHeader(code)
129 corsAllowHeadersHeader = strings.Join([]string{
130 "Authorization", "Content-Type", "Range",
131 // WebDAV request headers:
132 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout", "Cache-Control",
134 writeMethod = map[string]bool{
144 webdavMethod = map[string]bool{
157 browserMethod = map[string]bool{
162 // top-level dirs to serve with siteFS
163 siteFSDir = map[string]bool{
164 "": true, // root directory
170 func stripDefaultPort(host string) string {
171 // Will consider port 80 and port 443 to be the same vhost. I think that's fine.
172 u := &url.URL{Host: host}
173 if p := u.Port(); p == "80" || p == "443" {
174 return strings.ToLower(u.Hostname())
176 return strings.ToLower(host)
180 // CheckHealth implements service.Handler.
181 func (h *handler) CheckHealth() error {
185 // Done implements service.Handler.
186 func (h *handler) Done() <-chan struct{} {
190 // Close releases the active database connection, if any.
192 // Currently Close() is not part of the service.Handler interface.
193 // However, it is used by the test suite to avoid accumulating
194 // database connections when starting up lots of keep-web
196 func (h *handler) Close() {
197 h.getDBConnector().Close()
200 func (h *handler) getDBConnector() *ctrlctx.DBConnector {
201 h.dbConnectorMtx.Lock()
202 defer h.dbConnectorMtx.Unlock()
203 if h.dbConnector == nil {
204 h.dbConnector = &ctrlctx.DBConnector{PostgreSQL: h.Cluster.PostgreSQL}
209 // ServeHTTP implements http.Handler.
210 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
211 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
215 httpserver.SetResponseLogFields(r.Context(), logrus.Fields{
216 "webdavDepth": r.Header.Get("Depth"),
217 "webdavDestination": r.Header.Get("Destination"),
218 "webdavOverwrite": r.Header.Get("Overwrite"),
221 wbuffer := newWriteBuffer(wOrig, int(h.Cluster.Collections.WebDAVOutputBuffer))
222 defer wbuffer.Close()
223 w := httpserver.WrapResponseWriter(responseWriter{
225 ResponseWriter: wOrig,
228 if r.Method == "OPTIONS" && ServeCORSPreflight(w, r.Header) {
232 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
233 w.WriteHeader(http.StatusMethodNotAllowed)
237 if r.Header.Get("Origin") != "" {
238 // Allow simple cross-origin requests without user
239 // credentials ("user credentials" as defined by CORS,
240 // i.e., cookies, HTTP authentication, and client-side
241 // SSL certificates. See
242 // http://www.w3.org/TR/cors/#user-credentials).
243 w.Header().Set("Access-Control-Allow-Origin", "*")
244 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
251 // webdavPrefix is the leading portion of r.URL.Path that
252 // should be ignored by the webdav handler, if any.
254 // req "/c={id}/..." -> webdavPrefix "/c={id}"
255 // req "/by_id/..." -> webdavPrefix ""
257 // Note: in the code immediately below, we set webdavPrefix
258 // only if it was explicitly set by the client. Otherwise, it
259 // gets set later, after checking the request path for cases
260 // like "/c={id}/...".
262 arvPath := r.URL.Path
263 if prefix := r.Header.Get("X-Webdav-Prefix"); prefix != "" {
264 // Enable a proxy (e.g., container log handler in
265 // controller) to satisfy a request for path
266 // "/foo/bar/baz.txt" using content from
267 // "//abc123-4.internal/bar/baz.txt", by adding a
268 // request header "X-Webdav-Prefix: /foo"
269 if !strings.HasPrefix(arvPath, prefix) {
270 http.Error(w, "X-Webdav-Prefix header is not a prefix of the requested path", http.StatusBadRequest)
273 arvPath = r.URL.Path[len(prefix):]
277 w.Header().Set("Vary", "X-Webdav-Prefix, "+w.Header().Get("Vary"))
278 webdavPrefix = prefix
280 pathParts := strings.Split(arvPath[1:], "/")
283 var collectionID string
285 var reqTokens []string
289 credentialsOK := h.Cluster.Collections.TrustAllContent
290 reasonNotAcceptingCredentials := ""
292 if r.Host != "" && stripDefaultPort(r.Host) == stripDefaultPort(h.Cluster.Services.WebDAVDownload.ExternalURL.Host) {
295 } else if r.FormValue("disposition") == "attachment" {
300 reasonNotAcceptingCredentials = fmt.Sprintf("vhost %q does not specify a single collection ID or match Services.WebDAVDownload.ExternalURL %q, and Collections.TrustAllContent is false",
301 r.Host, h.Cluster.Services.WebDAVDownload.ExternalURL)
304 if collectionID = arvados.CollectionIDFromDNSName(r.Host); collectionID != "" {
305 // http://ID.collections.example/PATH...
307 } else if r.URL.Path == "/status.json" {
310 } else if siteFSDir[pathParts[0]] {
312 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
314 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
316 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
317 if len(pathParts) >= 4 && pathParts[1] == "download" {
318 // /collections/download/ID/TOKEN/PATH...
319 collectionID = parseCollectionIDFromURL(pathParts[2])
320 tokens = []string{pathParts[3]}
324 // /collections/ID/PATH...
325 collectionID = parseCollectionIDFromURL(pathParts[1])
327 // This path is only meant to work for public
328 // data. Tokens provided with the request are
330 credentialsOK = false
331 reasonNotAcceptingCredentials = "the '/collections/UUID/PATH' form only works for public data"
336 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
341 reqTokens = auth.CredentialsFromRequest(r).Tokens
345 origin := r.Header.Get("Origin")
346 cors := origin != "" && !strings.HasSuffix(origin, "://"+r.Host)
347 safeAjax := cors && (r.Method == http.MethodGet || r.Method == http.MethodHead)
348 // Important distinction: safeAttachment checks whether api_token exists
349 // as a query parameter. haveFormTokens checks whether api_token exists
350 // as request form data *or* a query parameter. Different checks are
351 // necessary because both the request disposition and the location of
352 // the API token affect whether or not the request needs to be
353 // redirected. The different branch comments below explain further.
354 safeAttachment := attachment && !r.URL.Query().Has("api_token")
355 if formTokens, haveFormTokens := r.Form["api_token"]; !haveFormTokens {
356 // No token to use or redact.
357 } else if safeAjax || safeAttachment {
358 // If this is a cross-origin request, the URL won't
359 // appear in the browser's address bar, so
360 // substituting a clipboard-safe URL is pointless.
361 // Redirect-with-cookie wouldn't work anyway, because
362 // it's not safe to allow third-party use of our
365 // If we're supplying an attachment, we don't need to
366 // convert POST to GET to avoid the "really resubmit
367 // form?" problem, so provided the token isn't
368 // embedded in the URL, there's no reason to do
369 // redirect-with-cookie in this case either.
370 for _, tok := range formTokens {
371 reqTokens = append(reqTokens, tok)
373 } else if browserMethod[r.Method] {
374 // If this is a page view, and the client provided a
375 // token via query string or POST body, we must put
376 // the token in an HttpOnly cookie, and redirect to an
377 // equivalent URL with the query param redacted and
379 h.seeOtherWithCookie(w, r, "", credentialsOK)
383 targetPath := pathParts[stripParts:]
384 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
385 // http://ID.example/t=TOKEN/PATH...
386 // /c=ID/t=TOKEN/PATH...
388 // This form must only be used to pass scoped tokens
389 // that give permission for a single collection. See
390 // FormValue case above.
391 tokens = []string{targetPath[0][2:]}
393 targetPath = targetPath[1:]
397 // fsprefix is the path from sitefs root to the sitefs
398 // directory (implicitly or explicitly) indicated by the
399 // leading / in the request path.
401 // Request "/by_id/..." -> fsprefix ""
402 // Request "/c={id}/..." -> fsprefix "/by_id/{id}/"
405 if writeMethod[r.Method] {
406 http.Error(w, webdavfs.ErrReadOnly.Error(), http.StatusMethodNotAllowed)
409 if len(reqTokens) == 0 {
410 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
411 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
415 } else if collectionID == "" {
416 http.Error(w, notFoundMessage, http.StatusNotFound)
419 fsprefix = "by_id/" + collectionID + "/"
422 if src := r.Header.Get("X-Webdav-Source"); strings.HasPrefix(src, "/") && !strings.Contains(src, "//") && !strings.Contains(src, "/../") {
423 // Clients (specifically, the container log gateway)
424 // use X-Webdav-Source to specify that although the
425 // request path (and other webdav fields in the
426 // request) refer to target "/abc", the intended
427 // target is actually
428 // "{x-webdav-source-value}/abc".
430 // This, combined with X-Webdav-Prefix, enables the
431 // container log gateway to effectively alter the
432 // target path when proxying a request, without
433 // needing to rewrite all the other webdav
434 // request/response fields that might mention the
441 if h.Cluster.Users.AnonymousUserToken != "" {
442 tokens = append(tokens, h.Cluster.Users.AnonymousUserToken)
446 if len(targetPath) > 0 && targetPath[0] == "_" {
447 // If a collection has a directory called "t=foo" or
448 // "_", it can be served at
449 // //collections.example/_/t=foo/ or
450 // //collections.example/_/_/ respectively:
451 // //collections.example/t=foo/ won't work because
452 // t=foo will be interpreted as a token "foo".
453 targetPath = targetPath[1:]
457 dirOpenMode := os.O_RDONLY
458 if writeMethod[r.Method] {
459 dirOpenMode = os.O_RDWR
463 var tokenScopeProblem bool
465 var tokenUser *arvados.User
466 var sessionFS arvados.CustomFileSystem
467 var targetFS arvados.FileSystem
468 var session *cachedSession
469 var collectionDir arvados.File
470 for _, token = range tokens {
471 var statusErr errorWithHTTPStatus
472 fs, sess, user, err := h.Cache.GetSession(token)
473 if errors.As(err, &statusErr) && statusErr.HTTPStatus() == http.StatusUnauthorized {
476 } else if err != nil {
477 http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
480 if token != h.Cluster.Users.AnonymousUserToken {
483 f, err := fs.OpenFile(fsprefix, dirOpenMode, 0)
484 if errors.As(err, &statusErr) &&
485 statusErr.HTTPStatus() == http.StatusForbidden &&
486 token != h.Cluster.Users.AnonymousUserToken {
487 // collection id is outside scope of supplied
489 tokenScopeProblem = true
492 } else if os.IsNotExist(err) {
493 // collection does not exist or is not
494 // readable using this token
497 } else if err != nil {
498 http.Error(w, err.Error(), http.StatusInternalServerError)
504 collectionDir, sessionFS, session, tokenUser = f, fs, sess, user
510 // The URL is a "secret sharing link" that
511 // didn't work out. Asking the client for
512 // additional credentials would just be
514 http.Error(w, notFoundMessage, http.StatusNotFound)
518 // The client provided valid token(s), but the
519 // collection was not found.
520 http.Error(w, notFoundMessage, http.StatusNotFound)
523 if tokenScopeProblem {
524 // The client provided a valid token but
525 // fetching a collection returned 401, which
526 // means the token scope doesn't permit
527 // fetching that collection.
528 http.Error(w, notFoundMessage, http.StatusForbidden)
531 // The client's token was invalid (e.g., expired), or
532 // the client didn't even provide one. Redirect to
533 // workbench2's login-and-redirect-to-download url if
534 // this is a browser navigation request. (The redirect
535 // flow can't preserve the original method if it's not
536 // GET, and doesn't make sense if the UA is a
537 // command-line tool, is trying to load an inline
538 // image, etc.; in these cases, there's nothing we can
539 // do, so return 401 unauthorized.)
541 // Note Sec-Fetch-Mode is sent by all non-EOL
542 // browsers, except Safari.
543 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-Fetch-Mode
545 // TODO(TC): This response would be confusing to
546 // someone trying (anonymously) to download public
547 // data that has been deleted. Allow a referrer to
548 // provide this context somehow?
549 if r.Method == http.MethodGet && r.Header.Get("Sec-Fetch-Mode") == "navigate" {
550 target := url.URL(h.Cluster.Services.Workbench2.ExternalURL)
551 redirkey := "redirectToPreview"
553 redirkey = "redirectToDownload"
555 callback := "/c=" + collectionID + "/" + strings.Join(targetPath, "/")
556 query := url.Values{redirkey: {callback}}
557 queryString := query.Encode()
558 // Note: Encode (and QueryEscape function) turns space
559 // into plus sign (+) rather than %20 (the plus sign
560 // becomes %2B); that is the rule for web forms data
561 // sent in URL query part via GET, but we're not
562 // emulating forms here. Client JS APIs
563 // (URLSearchParam#get, decodeURIComponent) will
564 // decode %20, but while the former also expects the
565 // form-specific encoding, the latter doesn't.
566 // Encode() almost encodes everything; RFC 3986 3.4
567 // says "it is sometimes better for usability" to not
568 // encode / and ? when passing URI reference in query.
569 // This is also legal according to WHATWG URL spec and
570 // can be desirable for debugging webapp.
571 // We can let slash / appear in the encoded query, and
572 // equality-sign = too, but exempting ? is not very
574 // Plus-sign, hash, and ampersand are never exempt.
575 r := strings.NewReplacer("+", "%20", "%2F", "/", "%3D", "=")
576 target.RawQuery = r.Replace(queryString)
577 w.Header().Add("Location", target.String())
578 w.WriteHeader(http.StatusSeeOther)
582 http.Error(w, fmt.Sprintf("Authorization tokens are not accepted here: %v, and no anonymous user token is configured.", reasonNotAcceptingCredentials), http.StatusUnauthorized)
585 // If none of the above cases apply, suggest the
586 // user-agent (which is either a non-browser agent
587 // like wget, or a browser that can't redirect through
588 // a login flow) prompt the user for credentials.
589 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
590 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
594 // The first call to releaseSession() calls session.Release(),
595 // then subsequent calls are no-ops. This lets us use a defer
596 // call here to ensure it gets called in all code paths, and
597 // also call it inline (see below) in the cases where we want
598 // to release the lock before returning.
599 var releaseSessionOnce sync.Once
600 releaseSession := func() { releaseSessionOnce.Do(func() { session.Release() }) }
601 defer releaseSession()
603 colltarget := strings.Join(targetPath, "/")
604 colltarget = strings.TrimSuffix(colltarget, "/")
605 fstarget := fsprefix + colltarget
607 need, err := h.needSync(r.Context(), sessionFS, fstarget)
609 http.Error(w, err.Error(), http.StatusBadGateway)
615 err := collectionDir.Sync()
617 if he := errorWithHTTPStatus(nil); errors.As(err, &he) {
618 http.Error(w, err.Error(), he.HTTPStatus())
620 http.Error(w, err.Error(), http.StatusInternalServerError)
626 if accept := strings.Split(r.Header.Get("Accept"), ","); len(accept) == 1 {
627 mediatype, _, err := mime.ParseMediaType(accept[0])
628 if err == nil && mediatype == "application/zip" {
630 h.serveZip(w, r, session, sessionFS, fstarget, tokenUser)
634 if r.Method == http.MethodGet || r.Method == http.MethodHead {
635 if fi, err := sessionFS.Stat(fstarget); err == nil && fi.IsDir() {
636 releaseSession() // because we won't be writing anything
637 if !strings.HasSuffix(r.URL.Path, "/") {
638 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
640 h.serveDirectory(w, r, fi.Name(), sessionFS, fstarget, !useSiteFS)
647 if len(targetPath) > 0 {
648 basename = targetPath[len(targetPath)-1]
650 if arvadosclient.PDHMatch(collectionID) && writeMethod[r.Method] {
651 http.Error(w, webdavfs.ErrReadOnly.Error(), http.StatusMethodNotAllowed)
654 if !h.userPermittedToUploadOrDownload(r.Method, tokenUser) {
655 http.Error(w, "Not permitted", http.StatusForbidden)
658 h.logUploadOrDownload(r, session.arvadosclient, sessionFS, fstarget, 1, nil, tokenUser)
660 if webdavPrefix == "" && stripParts > 0 {
661 webdavPrefix = "/" + strings.Join(pathParts[:stripParts], "/")
664 writing := writeMethod[r.Method]
666 // We implement write operations by writing to a
667 // temporary collection, then applying the change to
668 // the real collection using the replace_files option
669 // in a collection update request. This lets us do
670 // the slow part (i.e., receive the file data from the
671 // client and write it to Keep) without worrying about
672 // side effects of other read/write operations.
674 // Collection update requests for a given collection
675 // are serialized by the controller, so we don't need
676 // to do any locking for that part either.
678 // collprefix is the subdirectory in the target
679 // collection which (according to X-Webdav-Source) we
680 // should pretend is "/" for this request.
681 collprefix := strings.TrimPrefix(fsprefix, "by_id/"+collectionID+"/")
682 if len(collprefix) == len(fsprefix) {
683 http.Error(w, "internal error: writing to anything other than /by_id/{collectionID}", http.StatusInternalServerError)
687 // Create a temporary collection filesystem for webdav
689 var tmpcoll arvados.Collection
690 client := session.client.WithRequestID(r.Header.Get("X-Request-Id"))
691 tmpfs, err := tmpcoll.FileSystem(client, session.keepclient)
693 http.Error(w, err.Error(), http.StatusInternalServerError)
696 snap, err := arvados.Snapshot(sessionFS, "by_id/"+collectionID+"/")
698 http.Error(w, "snapshot: "+err.Error(), http.StatusInternalServerError)
701 err = arvados.Splice(tmpfs, "/", snap)
703 http.Error(w, "splice: "+err.Error(), http.StatusInternalServerError)
708 fsprefix = collprefix
709 replace := make(map[string]string)
713 dsttarget, err := copyMoveDestination(r, webdavPrefix)
715 http.Error(w, err.Error(), http.StatusBadRequest)
719 srcspec := "current/" + colltarget
720 // RFC 4918 9.8.3: A COPY of "Depth: 0" only
721 // instructs that the collection and its
722 // properties, but not resources identified by
723 // its internal member URLs, are to be copied.
725 // ...meaning we will be creating an empty
728 // RFC 4918 9.9.2: A client MUST NOT submit a
729 // Depth header on a MOVE on a collection with
730 // any value but "infinity".
732 // ...meaning we only need to consider this
733 // case for COPY, not for MOVE.
734 if fi, err := tmpfs.Stat(colltarget); err == nil && fi.IsDir() && r.Method == "COPY" && r.Header.Get("Depth") == "0" {
735 srcspec = "manifest_text/"
738 replace[strings.TrimSuffix(dsttarget, "/")] = srcspec
739 if r.Method == "MOVE" {
740 replace["/"+colltarget] = ""
743 replace["/"+colltarget] = "manifest_text/"
745 if depth := r.Header.Get("Depth"); depth != "" && depth != "infinity" {
746 http.Error(w, "invalid depth header, see RFC 4918 9.6.1", http.StatusBadRequest)
749 replace["/"+colltarget] = ""
751 // changes will be applied by updateOnSuccess
753 case "LOCK", "UNLOCK", "PROPPATCH":
756 http.Error(w, "method missing", http.StatusInternalServerError)
760 // Save the collection only if/when all
761 // webdav->filesystem operations succeed using our
762 // temporary collection -- and send a 500 error if the
763 // updates can't be saved.
764 logger := ctxlog.FromContext(r.Context())
765 w = &updateOnSuccess{
768 update: func() error {
770 var snap *arvados.Subtree
772 if r.Method == "PUT" {
773 snap, err = arvados.Snapshot(tmpfs, colltarget)
775 return fmt.Errorf("snapshot tmpfs: %w", err)
777 tmpfs, err = (&arvados.Collection{}).FileSystem(client, session.keepclient)
778 err = arvados.Splice(tmpfs, "file", snap)
780 return fmt.Errorf("splice tmpfs: %w", err)
782 manifest, err = tmpfs.MarshalManifest(".")
784 return fmt.Errorf("marshal tmpfs: %w", err)
786 replace["/"+colltarget] = "manifest_text/file"
787 } else if len(replace) == 0 {
790 var updated arvados.Collection
791 err = client.RequestAndDecode(&updated, "PATCH", "arvados/v1/collections/"+collectionID, nil, map[string]interface{}{
792 "replace_files": replace,
793 "collection": map[string]interface{}{"manifest_text": manifest}})
794 var te arvados.TransactionError
795 if errors.As(err, &te) {
801 if r.Method == "PUT" {
802 h.repack(r.Context(), session, logger, &updated)
807 // When writing, we need to block session renewal
808 // until we're finished, in order to guarantee the
809 // effect of the write is visible in future responses.
810 // But if we're not writing, we can release the lock
811 // early. This enables us to keep renewing sessions
812 // and processing more requests even if a slow client
813 // takes a long time to download a large file.
817 if r.Method == http.MethodGet {
818 applyContentDispositionHdr(w, r, basename, attachment)
820 wh := &webdav.Handler{
821 Prefix: webdavPrefix,
822 FileSystem: &webdavfs.FS{
823 FileSystem: targetFS,
825 Writing: writeMethod[r.Method],
826 AlwaysReadEOF: r.Method == "PROPFIND",
828 LockSystem: webdavfs.NoLockSystem,
829 Logger: func(r *http.Request, err error) {
830 if err != nil && !os.IsNotExist(err) {
831 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
835 h.metrics.track(wh, w, r)
836 if r.Method == http.MethodGet && w.WroteStatus() == http.StatusOK {
837 wrote := int64(w.WroteBodyBytes())
838 fi, err := wh.FileSystem.Stat(r.Context(), colltarget)
839 if err == nil && fi.Size() != wrote {
841 f, err := wh.FileSystem.OpenFile(r.Context(), colltarget, os.O_RDONLY, 0)
843 n, err = f.Read(make([]byte, 1024))
846 ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %v", fi.Size(), wrote, n, err)
851 // Repack the given collection after uploading a file.
852 func (h *handler) repack(ctx context.Context, session *cachedSession, logger logrus.FieldLogger, updated *arvados.Collection) {
853 if _, busy := h.repacking.LoadOrStore(updated.UUID, true); busy {
854 // Another goroutine is already repacking the same
858 defer h.repacking.Delete(updated.UUID)
860 // Repacking is best-effort, so we disable retries, and don't
862 client := *session.client
864 repackfs, err := updated.FileSystem(&client, session.keepclient)
866 logger.Warnf("setting up repackfs: %s", err)
869 repacked, err := repackfs.Repack(ctx, arvados.RepackOptions{CachedOnly: true})
871 logger.Warnf("repack: %s", err)
875 err := repackfs.Sync()
877 logger.Infof("sync repack: %s", err)
882 var dirListingTemplate = `<!DOCTYPE HTML>
884 <META name="robots" content="NOINDEX">
885 <TITLE>{{ .CollectionName }}</TITLE>
886 <STYLE type="text/css">
891 background-color: #D9EDF7;
892 border-radius: .25em;
900 border: 1px solid #808080;
906 font-family: monospace;
913 <H1>{{ .CollectionName }}</H1>
915 <P>This collection of data files is being shared with you through
916 Arvados. You can download individual files listed below. To download
917 the entire directory tree with <CODE>wget</CODE>, try:</P>
919 <PRE id="wget-example">$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} {{ .QuotedUrlForWget }}</PRE>
921 <H2>File Listing</H2>
927 <LI>{{" " | printf "%15s " | nbsp}}<A class="item" href="{{ .Href }}/">{{ .Name }}/</A></LI>
929 <LI>{{.Size | printf "%15d " | nbsp}}<A class="item" href="{{ .Href }}">{{ .Name }}</A></LI>
934 <P>(No files; this collection is empty.)</P>
941 Arvados is a free and open source software bioinformatics platform.
942 To learn more, visit arvados.org.
943 Arvados is not responsible for the files listed on this page.
951 type fileListEnt struct {
958 // Given a filesystem path like `foo/"bar baz"`, return an escaped
959 // (percent-encoded) relative path like `./foo/%22bar%20%baz%22`.
961 // Note the result may contain html-unsafe characters like '&'. These
962 // will be handled separately by the HTML templating engine as needed.
963 func relativeHref(path string) string {
964 u := &url.URL{Path: path}
965 return "./" + u.EscapedPath()
968 // Return a shell-quoted URL suitable for pasting to a command line
969 // ("wget ...") to repeat the given HTTP request.
970 func makeQuotedUrlForWget(r *http.Request) string {
971 scheme := r.Header.Get("X-Forwarded-Proto")
972 if scheme == "http" || scheme == "https" {
973 // use protocol reported by load balancer / proxy
974 } else if r.TLS != nil {
979 p := r.URL.EscapedPath()
980 // An escaped path may still contain single quote chars, which
981 // would interfere with our shell quoting. Avoid this by
982 // escaping them as %27.
983 return fmt.Sprintf("'%s://%s%s'", scheme, r.Host, strings.Replace(p, "'", "%27", -1))
986 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
987 var files []fileListEnt
988 var walk func(string) error
989 if !strings.HasSuffix(base, "/") {
992 walk = func(path string) error {
993 dirname := base + path
995 dirname = strings.TrimSuffix(dirname, "/")
997 d, err := fs.Open(dirname)
1001 ents, err := d.Readdir(-1)
1005 for _, ent := range ents {
1006 if recurse && ent.IsDir() {
1007 err = walk(path + ent.Name() + "/")
1012 listingName := path + ent.Name()
1013 files = append(files, fileListEnt{
1015 Href: relativeHref(listingName),
1023 if err := walk(""); err != nil {
1024 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
1028 funcs := template.FuncMap{
1029 "nbsp": func(s string) template.HTML {
1030 return template.HTML(strings.Replace(s, " ", " ", -1))
1033 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
1035 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
1038 sort.Slice(files, func(i, j int) bool {
1039 return files[i].Name < files[j].Name
1041 w.WriteHeader(http.StatusOK)
1042 tmpl.Execute(w, map[string]interface{}{
1043 "CollectionName": collectionName,
1046 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
1047 "QuotedUrlForWget": makeQuotedUrlForWget(r),
1051 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
1052 disposition := "inline"
1054 disposition = "attachment"
1056 if strings.ContainsRune(r.RequestURI, '?') {
1057 // Help the UA realize that the filename is just
1058 // "filename.txt", not
1059 // "filename.txt?disposition=attachment".
1061 // TODO(TC): Follow advice at RFC 6266 appendix D
1062 disposition += "; filename=" + strconv.QuoteToASCII(filename)
1064 if disposition != "inline" {
1065 w.Header().Set("Content-Disposition", disposition)
1069 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
1070 if formTokens, haveFormTokens := r.Form["api_token"]; haveFormTokens {
1072 // It is not safe to copy the provided token
1073 // into a cookie unless the current vhost
1074 // (origin) serves only a single collection or
1075 // we are in TrustAllContent mode.
1076 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)
1080 // The HttpOnly flag is necessary to prevent
1081 // JavaScript code (included in, or loaded by, a page
1082 // in the collection being served) from employing the
1083 // user's token beyond reading other files in the same
1084 // domain, i.e., same collection.
1086 // The 303 redirect is necessary in the case of a GET
1087 // request to avoid exposing the token in the Location
1088 // bar, and in the case of a POST request to avoid
1089 // raising warnings when the user refreshes the
1091 for _, tok := range formTokens {
1095 http.SetCookie(w, &http.Cookie{
1096 Name: "arvados_api_token",
1097 Value: auth.EncodeTokenCookie([]byte(tok)),
1100 SameSite: http.SameSiteLaxMode,
1106 // Propagate query parameters (except api_token) from
1107 // the original request.
1108 redirQuery := r.URL.Query()
1109 redirQuery.Del("api_token")
1113 newu, err := u.Parse(location)
1115 http.Error(w, "error resolving redirect target: "+err.Error(), http.StatusInternalServerError)
1121 Scheme: r.URL.Scheme,
1124 RawQuery: redirQuery.Encode(),
1127 w.Header().Add("Location", redir)
1128 w.WriteHeader(http.StatusSeeOther)
1129 io.WriteString(w, `<A href="`)
1130 io.WriteString(w, html.EscapeString(redir))
1131 io.WriteString(w, `">Continue</A>`)
1134 func (h *handler) userPermittedToUploadOrDownload(method string, tokenUser *arvados.User) bool {
1135 var permitDownload bool
1136 var permitUpload bool
1137 if tokenUser != nil && tokenUser.IsAdmin {
1138 permitUpload = h.Cluster.Collections.WebDAVPermission.Admin.Upload
1139 permitDownload = h.Cluster.Collections.WebDAVPermission.Admin.Download
1141 permitUpload = h.Cluster.Collections.WebDAVPermission.User.Upload
1142 permitDownload = h.Cluster.Collections.WebDAVPermission.User.Download
1144 if (method == "PUT" || method == "POST") && !permitUpload {
1145 // Disallow operations that upload new files.
1146 // Permit webdav operations that move existing files around.
1148 } else if method == "GET" && !permitDownload {
1149 // Disallow downloading file contents.
1150 // Permit webdav operations like PROPFIND that retrieve metadata
1151 // but not file contents.
1157 // Parse the request's Destination header and return the destination
1158 // path relative to the current collection, i.e., with webdavPrefix
1160 func copyMoveDestination(r *http.Request, webdavPrefix string) (string, error) {
1161 dsturl, err := url.Parse(r.Header.Get("Destination"))
1165 if dsturl.Host != "" && dsturl.Host != r.Host {
1166 return "", errors.New("destination host mismatch")
1168 if webdavPrefix == "" {
1169 return dsturl.Path, nil
1171 dsttarget := strings.TrimPrefix(dsturl.Path, webdavPrefix)
1172 if len(dsttarget) == len(dsturl.Path) {
1173 return "", errors.New("destination path not supported")
1175 return dsttarget, nil
1178 // Check whether fstarget is in a collection whose PDH has changed
1179 // since it was last Sync()ed in sessionFS.
1181 // If fstarget doesn't exist, but would be in such a collection if it
1182 // did exist, return true.
1183 func (h *handler) needSync(ctx context.Context, sessionFS arvados.CustomFileSystem, fstarget string) (bool, error) {
1184 collection, _ := h.determineCollection(sessionFS, fstarget)
1185 if collection == nil || len(collection.UUID) != 27 || !strings.HasPrefix(collection.UUID, h.Cluster.ClusterID) {
1188 db, err := h.getDBConnector().GetDB(ctx)
1192 var currentPDH string
1193 err = db.QueryRowContext(ctx, `select portable_data_hash from collections where uuid=$1`, collection.UUID).Scan(¤tPDH)
1197 if currentPDH != collection.PortableDataHash {
1203 type fileEventLog struct {
1216 func newFileEventLog(
1221 collection *arvados.Collection,
1225 var eventType string
1228 eventType = "file_upload"
1230 eventType = "file_download"
1235 // We want to log the address of the proxy closest to keep-web—the last
1236 // value in the X-Forwarded-For list—or the client address if there is no
1238 var clientAddr string
1239 // 1. Build a slice of proxy addresses from X-Forwarded-For.
1240 xff := strings.Join(r.Header.Values("X-Forwarded-For"), ",")
1241 addrs := strings.Split(xff, ",")
1242 // 2. Reverse the slice so it's in our most preferred order for logging.
1243 slices.Reverse(addrs)
1244 // 3. Append the client address to that slice.
1245 if addr, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
1246 addrs = append(addrs, addr)
1248 // 4. Use the first valid address in the slice.
1249 for _, addr := range addrs {
1250 if ip := net.ParseIP(strings.TrimSpace(addr)); ip != nil {
1251 clientAddr = ip.String()
1256 ev := &fileEventLog{
1257 requestPath: r.URL.Path,
1258 eventType: eventType,
1259 clientAddr: clientAddr,
1261 fileCount: fileCount,
1265 ev.userUUID = user.UUID
1266 ev.userFullName = user.FullName
1268 ev.userUUID = fmt.Sprintf("%s-tpzed-anonymouspublic", h.Cluster.ClusterID)
1271 if collection != nil {
1272 ev.collFilePath = filepath
1273 // h.determineCollection populates the collection_uuid
1274 // prop with the PDH, if this collection is being
1275 // accessed via PDH. For logging, we use a different
1276 // field depending on whether it's a UUID or PDH.
1277 if len(collection.UUID) > 32 {
1278 ev.collPDH = collection.UUID
1280 ev.collPDH = collection.PortableDataHash
1281 ev.collUUID = collection.UUID
1288 func (ev *fileEventLog) shouldLogPDH() bool {
1289 return ev.eventType == "file_download" && ev.collPDH != ""
1292 func (ev *fileEventLog) asDict() arvadosclient.Dict {
1293 props := arvadosclient.Dict{
1294 "reqPath": ev.requestPath,
1295 "collection_uuid": ev.collUUID,
1296 "collection_file_path": ev.collFilePath,
1297 "file_count": ev.fileCount,
1299 if ev.shouldLogPDH() {
1300 props["portable_data_hash"] = ev.collPDH
1302 return arvadosclient.Dict{
1303 "object_uuid": ev.userUUID,
1304 "event_type": ev.eventType,
1305 "properties": props,
1309 func (ev *fileEventLog) asFields() logrus.Fields {
1310 fields := logrus.Fields{
1311 "collection_file_path": ev.collFilePath,
1312 "collection_uuid": ev.collUUID,
1313 "user_uuid": ev.userUUID,
1314 "file_count": ev.fileCount,
1316 if ev.shouldLogPDH() {
1317 fields["portable_data_hash"] = ev.collPDH
1319 if !strings.HasSuffix(ev.userUUID, "-tpzed-anonymouspublic") {
1320 fields["user_full_name"] = ev.userFullName
1325 func (h *handler) shouldLogEvent(
1326 event *fileEventLog,
1328 fileInfo os.FileInfo,
1333 } else if event.eventType != "file_download" ||
1334 h.Cluster.Collections.WebDAVLogDownloadInterval == 0 ||
1338 td := h.Cluster.Collections.WebDAVLogDownloadInterval.Duration()
1339 cutoff := t.Add(-td)
1341 h.fileEventLogsMtx.Lock()
1342 defer h.fileEventLogsMtx.Unlock()
1343 if h.fileEventLogs == nil {
1344 h.fileEventLogs = make(map[fileEventLog]time.Time)
1346 shouldLog := h.fileEventLogs[ev].Before(cutoff)
1348 // Go's http fs server evaluates http.Request.Header.Get("Range")
1349 // (as of Go 1.22) so we should do the same.
1350 // Don't worry about merging multiple headers, etc.
1351 ranges, err := http_range.ParseRange(req.Header.Get("Range"), fileInfo.Size())
1352 if ranges == nil || err != nil {
1353 // The Range header was either empty or malformed.
1354 // Err on the side of logging.
1357 // Log this request only if it requested the first byte
1358 // (our heuristic for "starting a new download").
1359 for _, reqRange := range ranges {
1360 if reqRange.Start == 0 {
1368 h.fileEventLogs[ev] = t
1370 if t.After(h.fileEventLogsNextTidy) {
1371 for key, logTime := range h.fileEventLogs {
1372 if logTime.Before(cutoff) {
1373 delete(h.fileEventLogs, key)
1376 h.fileEventLogsNextTidy = t.Add(td)
1381 func (h *handler) logUploadOrDownload(
1383 client *arvadosclient.ArvadosClient,
1384 fs arvados.CustomFileSystem,
1387 collection *arvados.Collection,
1390 var fileInfo os.FileInfo
1392 if collection == nil {
1393 collection, filepath = h.determineCollection(fs, filepath)
1395 if collection != nil {
1396 // It's okay to ignore this error because shouldLogEvent will
1397 // always return true if fileInfo == nil.
1398 fileInfo, _ = fs.Stat(path.Join("by_id", collection.UUID, filepath))
1401 event := newFileEventLog(h, r, filepath, fileCount, collection, user, client.ApiToken)
1402 if !h.shouldLogEvent(event, r, fileInfo, time.Now()) {
1405 log := ctxlog.FromContext(r.Context()).WithFields(event.asFields())
1406 log.Info(strings.Replace(event.eventType, "file_", "File ", 1))
1407 if h.Cluster.Collections.WebDAVLogEvents {
1409 logReq := arvadosclient.Dict{"log": event.asDict()}
1410 err := client.Create("logs", logReq, nil)
1412 log.WithError(err).Errorf("Failed to create %s log event on API server", event.eventType)
1418 func (h *handler) determineCollection(fs arvados.CustomFileSystem, path string) (*arvados.Collection, string) {
1419 target := strings.TrimSuffix(path, "/")
1420 for cut := len(target); cut >= 0; cut = strings.LastIndexByte(target, '/') {
1421 target = target[:cut]
1422 fi, err := fs.Stat(target)
1423 if os.IsNotExist(err) {
1424 // creating a new file/dir, or download
1427 } else if err != nil {
1430 switch src := fi.Sys().(type) {
1431 case *arvados.Collection:
1432 return src, strings.TrimPrefix(path[len(target):], "/")
1433 case *arvados.Group:
1436 if _, ok := src.(error); ok {
1444 func ServeCORSPreflight(w http.ResponseWriter, header http.Header) bool {
1445 method := header.Get("Access-Control-Request-Method")
1449 if !browserMethod[method] && !webdavMethod[method] {
1450 w.WriteHeader(http.StatusMethodNotAllowed)
1453 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
1454 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
1455 w.Header().Set("Access-Control-Allow-Origin", "*")
1456 w.Header().Set("Access-Control-Max-Age", "86400")