1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
35 MetricsAPI http.Handler
36 clientPool *arvadosclient.ClientPool
38 healthHandler http.Handler
39 webdavLS webdav.LockSystem
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 {
46 if i := strings.IndexRune(s, '.'); i >= 0 {
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 {
55 if arvadosclient.UUIDMatch(s) {
58 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
64 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
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"
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 "-");
72 func parseCollectionIDFromURL(s string) string {
73 if arvadosclient.UUIDMatch(s) {
76 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
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)
87 keepclient.RefreshServiceDiscoveryOnSIGHUP()
88 keepclient.DefaultBlockCache.MaxBlocks = h.Config.cluster.Collections.WebDAVCache.MaxBlockEntries
90 h.healthHandler = &health.Handler{
91 Token: h.Config.cluster.ManagementToken,
95 // Even though we don't accept LOCK requests, every webdav
96 // handler must have a non-nil LockSystem.
97 h.webdavLS = &noLockSystem{}
100 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
101 json.NewEncoder(w).Encode(struct{ Version string }{version})
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
117 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
119 uos.WriteHeader(http.StatusOK)
124 return uos.ResponseWriter.Write(p)
127 func (uos *updateOnSuccess) WriteHeader(code int) {
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
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)
142 uos.ResponseWriter.WriteHeader(code)
146 corsAllowHeadersHeader = strings.Join([]string{
147 "Authorization", "Content-Type", "Range",
148 // WebDAV request headers:
149 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout",
151 writeMethod = map[string]bool{
162 webdavMethod = map[string]bool{
175 browserMethod = map[string]bool{
180 // top-level dirs to serve with siteFS
181 siteFSDir = map[string]bool{
182 "": true, // root directory
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 if strings.HasSuffix(host, ":80") || strings.HasSuffix(host, ":443") {
191 return host[0:strings.Index(host, ":")]
196 // ServeHTTP implements http.Handler.
197 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
198 h.setupOnce.Do(h.setup)
200 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
204 w := httpserver.WrapResponseWriter(wOrig)
206 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
207 h.healthHandler.ServeHTTP(w, r)
211 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
212 if !browserMethod[method] && !webdavMethod[method] {
213 w.WriteHeader(http.StatusMethodNotAllowed)
216 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
217 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
218 w.Header().Set("Access-Control-Allow-Origin", "*")
219 w.Header().Set("Access-Control-Max-Age", "86400")
223 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
224 w.WriteHeader(http.StatusMethodNotAllowed)
228 if r.Header.Get("Origin") != "" {
229 // Allow simple cross-origin requests without user
230 // credentials ("user credentials" as defined by CORS,
231 // i.e., cookies, HTTP authentication, and client-side
232 // SSL certificates. See
233 // http://www.w3.org/TR/cors/#user-credentials).
234 w.Header().Set("Access-Control-Allow-Origin", "*")
235 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
242 pathParts := strings.Split(r.URL.Path[1:], "/")
245 var collectionID string
247 var reqTokens []string
251 credentialsOK := h.Config.cluster.Collections.TrustAllContent
252 reasonNotAcceptingCredentials := ""
254 if r.Host != "" && StripDefaultPort(r.Host) == StripDefaultPort(h.Config.cluster.Services.WebDAVDownload.ExternalURL.Host) {
257 } else if r.FormValue("disposition") == "attachment" {
262 reasonNotAcceptingCredentials = fmt.Sprintf("Collections.TrustAllContent is false and provided virtual host '%s' did not match either Services.WebDAV or Services.WebDAVDownload", r.Host)
265 if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
266 // http://ID.collections.example/PATH...
268 } else if r.URL.Path == "/status.json" {
271 } else if strings.HasPrefix(r.URL.Path, "/metrics") {
272 h.MetricsAPI.ServeHTTP(w, r)
274 } else if siteFSDir[pathParts[0]] {
276 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
278 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
280 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
281 if len(pathParts) >= 4 && pathParts[1] == "download" {
282 // /collections/download/ID/TOKEN/PATH...
283 collectionID = parseCollectionIDFromURL(pathParts[2])
284 tokens = []string{pathParts[3]}
288 // /collections/ID/PATH...
289 collectionID = parseCollectionIDFromURL(pathParts[1])
291 // This path is only meant to work for public
292 // data. Tokens provided with the request are
294 credentialsOK = false
295 reasonNotAcceptingCredentials = "the '/collections/UUID/PATH' form only works for public data"
299 if collectionID == "" && !useSiteFS {
300 http.Error(w, notFoundMessage, http.StatusNotFound)
305 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
310 reqTokens = auth.CredentialsFromRequest(r).Tokens
313 formToken := r.FormValue("api_token")
314 origin := r.Header.Get("Origin")
315 cors := origin != "" && !strings.HasSuffix(origin, "://"+r.Host)
316 safeAjax := cors && (r.Method == http.MethodGet || r.Method == http.MethodHead)
317 safeAttachment := attachment && r.URL.Query().Get("api_token") == ""
319 // No token to use or redact.
320 } else if safeAjax || safeAttachment {
321 // If this is a cross-origin request, the URL won't
322 // appear in the browser's address bar, so
323 // substituting a clipboard-safe URL is pointless.
324 // Redirect-with-cookie wouldn't work anyway, because
325 // it's not safe to allow third-party use of our
328 // If we're supplying an attachment, we don't need to
329 // convert POST to GET to avoid the "really resubmit
330 // form?" problem, so provided the token isn't
331 // embedded in the URL, there's no reason to do
332 // redirect-with-cookie in this case either.
333 reqTokens = append(reqTokens, formToken)
334 } else if browserMethod[r.Method] {
335 // If this is a page view, and the client provided a
336 // token via query string or POST body, we must put
337 // the token in an HttpOnly cookie, and redirect to an
338 // equivalent URL with the query param redacted and
340 h.seeOtherWithCookie(w, r, "", credentialsOK)
345 h.serveSiteFS(w, r, reqTokens, credentialsOK, attachment)
349 targetPath := pathParts[stripParts:]
350 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
351 // http://ID.example/t=TOKEN/PATH...
352 // /c=ID/t=TOKEN/PATH...
354 // This form must only be used to pass scoped tokens
355 // that give permission for a single collection. See
356 // FormValue case above.
357 tokens = []string{targetPath[0][2:]}
359 targetPath = targetPath[1:]
365 if h.Config.cluster.Users.AnonymousUserToken != "" {
366 tokens = append(tokens, h.Config.cluster.Users.AnonymousUserToken)
372 http.Error(w, fmt.Sprintf("Authorization tokens were not accepted because %v, and no anonymous user token is configured.", reasonNotAcceptingCredentials), http.StatusUnauthorized)
374 http.Error(w, fmt.Sprintf("No authorization token in request, and no anonymous user token is configured."), http.StatusUnauthorized)
379 if len(targetPath) > 0 && targetPath[0] == "_" {
380 // If a collection has a directory called "t=foo" or
381 // "_", it can be served at
382 // //collections.example/_/t=foo/ or
383 // //collections.example/_/_/ respectively:
384 // //collections.example/t=foo/ won't work because
385 // t=foo will be interpreted as a token "foo".
386 targetPath = targetPath[1:]
390 arv := h.clientPool.Get()
392 http.Error(w, "client pool error: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
395 defer h.clientPool.Put(arv)
397 var collection *arvados.Collection
398 tokenResult := make(map[string]int)
399 for _, arv.ApiToken = range tokens {
401 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
406 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
407 switch srvErr.HttpStatusCode {
409 // Token broken or insufficient to
410 // retrieve collection
411 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
415 // Something more serious is wrong
416 http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
419 if collection == nil {
420 if pathToken || !credentialsOK {
421 // Either the URL is a "secret sharing link"
422 // that didn't work out (and asking the client
423 // for additional credentials would just be
424 // confusing), or we don't even accept
425 // credentials at this path.
426 http.Error(w, notFoundMessage, http.StatusNotFound)
429 for _, t := range reqTokens {
430 if tokenResult[t] == 404 {
431 // The client provided valid token(s), but the
432 // collection was not found.
433 http.Error(w, notFoundMessage, http.StatusNotFound)
437 // The client's token was invalid (e.g., expired), or
438 // the client didn't even provide one. Propagate the
439 // 401 to encourage the client to use a [different]
442 // TODO(TC): This response would be confusing to
443 // someone trying (anonymously) to download public
444 // data that has been deleted. Allow a referrer to
445 // provide this context somehow?
446 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
447 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
451 kc, err := keepclient.MakeKeepClient(arv)
453 http.Error(w, "error setting up keep client: "+err.Error(), http.StatusInternalServerError)
456 kc.RequestID = r.Header.Get("X-Request-Id")
459 if len(targetPath) > 0 {
460 basename = targetPath[len(targetPath)-1]
462 applyContentDispositionHdr(w, r, basename, attachment)
464 client := (&arvados.Client{
465 APIHost: arv.ApiServer,
466 AuthToken: arv.ApiToken,
467 Insecure: arv.ApiInsecure,
468 }).WithRequestID(r.Header.Get("X-Request-Id"))
470 fs, err := collection.FileSystem(client, kc)
472 http.Error(w, "error creating collection filesystem: "+err.Error(), http.StatusInternalServerError)
476 writefs, writeOK := fs.(arvados.CollectionFileSystem)
477 targetIsPDH := arvadosclient.PDHMatch(collectionID)
478 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
479 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
483 if webdavMethod[r.Method] {
484 if writeMethod[r.Method] {
485 // Save the collection only if/when all
486 // webdav->filesystem operations succeed --
487 // and send a 500 error if the modified
488 // collection can't be saved.
489 w = &updateOnSuccess{
491 logger: ctxlog.FromContext(r.Context()),
492 update: func() error {
493 return h.Config.Cache.Update(client, *collection, writefs)
497 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
498 FileSystem: &webdavFS{
500 writing: writeMethod[r.Method],
501 alwaysReadEOF: r.Method == "PROPFIND",
503 LockSystem: h.webdavLS,
504 Logger: func(_ *http.Request, err error) {
506 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
514 openPath := "/" + strings.Join(targetPath, "/")
515 f, err := fs.Open(openPath)
516 if os.IsNotExist(err) {
517 // Requested non-existent path
518 http.Error(w, notFoundMessage, http.StatusNotFound)
520 } else if err != nil {
521 // Some other (unexpected) error
522 http.Error(w, "open: "+err.Error(), http.StatusInternalServerError)
526 if stat, err := f.Stat(); err != nil {
527 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
528 http.Error(w, "stat: "+err.Error(), http.StatusInternalServerError)
529 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
530 // If client requests ".../dirname", redirect to
531 // ".../dirname/". This way, relative links in the
532 // listing for "dirname" can always be "fnm", never
534 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
535 } else if stat.IsDir() {
536 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
538 http.ServeContent(w, r, basename, stat.ModTime(), f)
539 if wrote := int64(w.WroteBodyBytes()); wrote != stat.Size() && w.WroteStatus() == http.StatusOK {
540 // If we wrote fewer bytes than expected, it's
541 // too late to change the real response code
542 // or send an error message to the client, but
543 // at least we can try to put some useful
544 // debugging info in the logs.
545 n, err := f.Read(make([]byte, 1024))
546 ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %v", stat.Size(), wrote, n, err)
551 func (h *handler) getClients(reqID, token string) (arv *arvadosclient.ArvadosClient, kc *keepclient.KeepClient, client *arvados.Client, release func(), err error) {
552 arv = h.clientPool.Get()
554 err = h.clientPool.Err()
557 release = func() { h.clientPool.Put(arv) }
559 kc, err = keepclient.MakeKeepClient(arv)
565 client = (&arvados.Client{
566 APIHost: arv.ApiServer,
567 AuthToken: arv.ApiToken,
568 Insecure: arv.ApiInsecure,
569 }).WithRequestID(reqID)
573 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
574 if len(tokens) == 0 {
575 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
576 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
579 if writeMethod[r.Method] {
580 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
583 fs, err := h.Config.Cache.GetSession(tokens[0])
585 http.Error(w, err.Error(), http.StatusInternalServerError)
588 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
589 f, err := fs.Open(r.URL.Path)
590 if os.IsNotExist(err) {
591 http.Error(w, err.Error(), http.StatusNotFound)
593 } else if err != nil {
594 http.Error(w, err.Error(), http.StatusInternalServerError)
598 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
599 if !strings.HasSuffix(r.URL.Path, "/") {
600 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
602 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
606 if r.Method == "GET" {
607 _, basename := filepath.Split(r.URL.Path)
608 applyContentDispositionHdr(w, r, basename, attachment)
610 wh := webdav.Handler{
612 FileSystem: &webdavFS{
614 writing: writeMethod[r.Method],
615 alwaysReadEOF: r.Method == "PROPFIND",
617 LockSystem: h.webdavLS,
618 Logger: func(_ *http.Request, err error) {
620 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
627 var dirListingTemplate = `<!DOCTYPE HTML>
629 <META name="robots" content="NOINDEX">
630 <TITLE>{{ .CollectionName }}</TITLE>
631 <STYLE type="text/css">
636 background-color: #D9EDF7;
637 border-radius: .25em;
648 font-family: monospace;
655 <H1>{{ .CollectionName }}</H1>
657 <P>This collection of data files is being shared with you through
658 Arvados. You can download individual files listed below. To download
659 the entire directory tree with wget, try:</P>
661 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
663 <H2>File Listing</H2>
669 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
671 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
676 <P>(No files; this collection is empty.)</P>
683 Arvados is a free and open source software bioinformatics platform.
684 To learn more, visit arvados.org.
685 Arvados is not responsible for the files listed on this page.
692 type fileListEnt struct {
698 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
699 var files []fileListEnt
700 var walk func(string) error
701 if !strings.HasSuffix(base, "/") {
704 walk = func(path string) error {
705 dirname := base + path
707 dirname = strings.TrimSuffix(dirname, "/")
709 d, err := fs.Open(dirname)
713 ents, err := d.Readdir(-1)
717 for _, ent := range ents {
718 if recurse && ent.IsDir() {
719 err = walk(path + ent.Name() + "/")
724 files = append(files, fileListEnt{
725 Name: path + ent.Name(),
733 if err := walk(""); err != nil {
734 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
738 funcs := template.FuncMap{
739 "nbsp": func(s string) template.HTML {
740 return template.HTML(strings.Replace(s, " ", " ", -1))
743 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
745 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
748 sort.Slice(files, func(i, j int) bool {
749 return files[i].Name < files[j].Name
751 w.WriteHeader(http.StatusOK)
752 tmpl.Execute(w, map[string]interface{}{
753 "CollectionName": collectionName,
756 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
760 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
761 disposition := "inline"
763 disposition = "attachment"
765 if strings.ContainsRune(r.RequestURI, '?') {
766 // Help the UA realize that the filename is just
767 // "filename.txt", not
768 // "filename.txt?disposition=attachment".
770 // TODO(TC): Follow advice at RFC 6266 appendix D
771 disposition += "; filename=" + strconv.QuoteToASCII(filename)
773 if disposition != "inline" {
774 w.Header().Set("Content-Disposition", disposition)
778 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
779 if formToken := r.FormValue("api_token"); formToken != "" {
781 // It is not safe to copy the provided token
782 // into a cookie unless the current vhost
783 // (origin) serves only a single collection or
784 // we are in TrustAllContent mode.
785 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)
789 // The HttpOnly flag is necessary to prevent
790 // JavaScript code (included in, or loaded by, a page
791 // in the collection being served) from employing the
792 // user's token beyond reading other files in the same
793 // domain, i.e., same collection.
795 // The 303 redirect is necessary in the case of a GET
796 // request to avoid exposing the token in the Location
797 // bar, and in the case of a POST request to avoid
798 // raising warnings when the user refreshes the
800 http.SetCookie(w, &http.Cookie{
801 Name: "arvados_api_token",
802 Value: auth.EncodeTokenCookie([]byte(formToken)),
805 SameSite: http.SameSiteLaxMode,
809 // Propagate query parameters (except api_token) from
810 // the original request.
811 redirQuery := r.URL.Query()
812 redirQuery.Del("api_token")
816 newu, err := u.Parse(location)
818 http.Error(w, "error resolving redirect target: "+err.Error(), http.StatusInternalServerError)
824 Scheme: r.URL.Scheme,
827 RawQuery: redirQuery.Encode(),
830 w.Header().Add("Location", redir)
831 w.WriteHeader(http.StatusSeeOther)
832 io.WriteString(w, `<A href="`)
833 io.WriteString(w, html.EscapeString(redir))
834 io.WriteString(w, `">Continue</A>`)