1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
21 "git.arvados.org/arvados.git/sdk/go/arvados"
22 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
23 "git.arvados.org/arvados.git/sdk/go/auth"
24 "git.arvados.org/arvados.git/sdk/go/ctxlog"
25 "git.arvados.org/arvados.git/sdk/go/health"
26 "git.arvados.org/arvados.git/sdk/go/httpserver"
27 "git.arvados.org/arvados.git/sdk/go/keepclient"
28 "github.com/sirupsen/logrus"
29 "golang.org/x/net/webdav"
34 MetricsAPI http.Handler
35 clientPool *arvadosclient.ClientPool
37 healthHandler http.Handler
38 webdavLS webdav.LockSystem
41 // parseCollectionIDFromDNSName returns a UUID or PDH if s begins with
42 // a UUID or URL-encoded PDH; otherwise "".
43 func parseCollectionIDFromDNSName(s string) string {
45 if i := strings.IndexRune(s, '.'); i >= 0 {
48 // Names like {uuid}--collections.example.com serve the same
49 // purpose as {uuid}.collections.example.com but can reduce
50 // cost/effort of using [additional] wildcard certificates.
51 if i := strings.Index(s, "--"); i >= 0 {
54 if arvadosclient.UUIDMatch(s) {
57 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
63 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
65 var notFoundMessage = "404 Not found\n\nThe requested path was not found, or you do not have permission to access it."
66 var unauthorizedMessage = "401 Unauthorized\n\nA valid Arvados token must be provided to access this resource."
68 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
69 // PDH (even if it is a PDH with "+" replaced by " " or "-");
71 func parseCollectionIDFromURL(s string) string {
72 if arvadosclient.UUIDMatch(s) {
75 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
81 func (h *handler) setup() {
82 // Errors will be handled at the client pool.
83 arv, _ := arvados.NewClientFromConfig(h.Config.cluster)
84 h.clientPool = arvadosclient.MakeClientPoolWith(arv)
86 keepclient.RefreshServiceDiscoveryOnSIGHUP()
87 keepclient.DefaultBlockCache.MaxBlocks = h.Config.cluster.Collections.WebDAVCache.MaxBlockEntries
89 h.healthHandler = &health.Handler{
90 Token: h.Config.cluster.ManagementToken,
94 // Even though we don't accept LOCK requests, every webdav
95 // handler must have a non-nil LockSystem.
96 h.webdavLS = &noLockSystem{}
99 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
100 json.NewEncoder(w).Encode(struct{ Version string }{version})
103 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
104 // sends an HTTP header indicating success, updateOnSuccess first
105 // calls the provided update func. If the update func fails, a 500
106 // response is sent, and the status code and body sent by the handler
107 // are ignored (all response writes return the update error).
108 type updateOnSuccess struct {
109 httpserver.ResponseWriter
110 logger logrus.FieldLogger
116 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
118 uos.WriteHeader(http.StatusOK)
123 return uos.ResponseWriter.Write(p)
126 func (uos *updateOnSuccess) WriteHeader(code int) {
128 uos.sentHeader = true
129 if code >= 200 && code < 400 {
130 if uos.err = uos.update(); uos.err != nil {
131 code := http.StatusInternalServerError
132 if err, ok := uos.err.(*arvados.TransactionError); ok {
133 code = err.StatusCode
135 uos.logger.WithError(uos.err).Errorf("update() returned error type %T, changing response to HTTP %d", uos.err, code)
136 http.Error(uos.ResponseWriter, uos.err.Error(), code)
141 uos.ResponseWriter.WriteHeader(code)
145 corsAllowHeadersHeader = strings.Join([]string{
146 "Authorization", "Content-Type", "Range",
147 // WebDAV request headers:
148 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout",
150 writeMethod = map[string]bool{
161 webdavMethod = map[string]bool{
174 browserMethod = map[string]bool{
179 // top-level dirs to serve with siteFS
180 siteFSDir = map[string]bool{
181 "": true, // root directory
187 // ServeHTTP implements http.Handler.
188 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
189 h.setupOnce.Do(h.setup)
191 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
195 w := httpserver.WrapResponseWriter(wOrig)
197 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
198 h.healthHandler.ServeHTTP(w, r)
202 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
203 if !browserMethod[method] && !webdavMethod[method] {
204 w.WriteHeader(http.StatusMethodNotAllowed)
207 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
208 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
209 w.Header().Set("Access-Control-Allow-Origin", "*")
210 w.Header().Set("Access-Control-Max-Age", "86400")
214 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
215 w.WriteHeader(http.StatusMethodNotAllowed)
219 if r.Header.Get("Origin") != "" {
220 // Allow simple cross-origin requests without user
221 // credentials ("user credentials" as defined by CORS,
222 // i.e., cookies, HTTP authentication, and client-side
223 // SSL certificates. See
224 // http://www.w3.org/TR/cors/#user-credentials).
225 w.Header().Set("Access-Control-Allow-Origin", "*")
226 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
233 pathParts := strings.Split(r.URL.Path[1:], "/")
236 var collectionID string
238 var reqTokens []string
242 credentialsOK := h.Config.cluster.Collections.TrustAllContent
244 if r.Host != "" && r.Host == h.Config.cluster.Services.WebDAVDownload.ExternalURL.Host {
247 } else if r.FormValue("disposition") == "attachment" {
251 if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
252 // http://ID.collections.example/PATH...
254 } else if r.URL.Path == "/status.json" {
257 } else if strings.HasPrefix(r.URL.Path, "/metrics") {
258 h.MetricsAPI.ServeHTTP(w, r)
260 } else if siteFSDir[pathParts[0]] {
262 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
264 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
266 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
267 if len(pathParts) >= 4 && pathParts[1] == "download" {
268 // /collections/download/ID/TOKEN/PATH...
269 collectionID = parseCollectionIDFromURL(pathParts[2])
270 tokens = []string{pathParts[3]}
274 // /collections/ID/PATH...
275 collectionID = parseCollectionIDFromURL(pathParts[1])
277 // This path is only meant to work for public
278 // data. Tokens provided with the request are
280 credentialsOK = false
284 if collectionID == "" && !useSiteFS {
285 http.Error(w, notFoundMessage, http.StatusNotFound)
290 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
295 reqTokens = auth.CredentialsFromRequest(r).Tokens
298 formToken := r.FormValue("api_token")
299 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
300 // The client provided an explicit token in the POST
301 // body. The Origin header indicates this *might* be
302 // an AJAX request, in which case redirect-with-cookie
303 // won't work: we should just serve the content in the
304 // POST response. This is safe because:
306 // * We're supplying an attachment, not inline
307 // content, so we don't need to convert the POST to
308 // a GET and avoid the "really resubmit form?"
311 // * The token isn't embedded in the URL, so we don't
312 // need to worry about bookmarks and copy/paste.
313 reqTokens = append(reqTokens, formToken)
314 } else if formToken != "" && browserMethod[r.Method] {
315 // The client provided an explicit token in the query
316 // string, or a form in POST body. We must put the
317 // token in an HttpOnly cookie, and redirect to the
318 // same URL with the query param redacted and method =
320 h.seeOtherWithCookie(w, r, "", credentialsOK)
325 h.serveSiteFS(w, r, reqTokens, credentialsOK, attachment)
329 targetPath := pathParts[stripParts:]
330 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
331 // http://ID.example/t=TOKEN/PATH...
332 // /c=ID/t=TOKEN/PATH...
334 // This form must only be used to pass scoped tokens
335 // that give permission for a single collection. See
336 // FormValue case above.
337 tokens = []string{targetPath[0][2:]}
339 targetPath = targetPath[1:]
344 tokens = append(reqTokens, h.Config.cluster.Users.AnonymousUserToken)
347 if len(targetPath) > 0 && targetPath[0] == "_" {
348 // If a collection has a directory called "t=foo" or
349 // "_", it can be served at
350 // //collections.example/_/t=foo/ or
351 // //collections.example/_/_/ respectively:
352 // //collections.example/t=foo/ won't work because
353 // t=foo will be interpreted as a token "foo".
354 targetPath = targetPath[1:]
358 arv := h.clientPool.Get()
360 http.Error(w, "client pool error: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
363 defer h.clientPool.Put(arv)
365 var collection *arvados.Collection
366 tokenResult := make(map[string]int)
367 for _, arv.ApiToken = range tokens {
369 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
374 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
375 switch srvErr.HttpStatusCode {
377 // Token broken or insufficient to
378 // retrieve collection
379 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
383 // Something more serious is wrong
384 http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
387 if collection == nil {
388 if pathToken || !credentialsOK {
389 // Either the URL is a "secret sharing link"
390 // that didn't work out (and asking the client
391 // for additional credentials would just be
392 // confusing), or we don't even accept
393 // credentials at this path.
394 http.Error(w, notFoundMessage, http.StatusNotFound)
397 for _, t := range reqTokens {
398 if tokenResult[t] == 404 {
399 // The client provided valid token(s), but the
400 // collection was not found.
401 http.Error(w, notFoundMessage, http.StatusNotFound)
405 // The client's token was invalid (e.g., expired), or
406 // the client didn't even provide one. Propagate the
407 // 401 to encourage the client to use a [different]
410 // TODO(TC): This response would be confusing to
411 // someone trying (anonymously) to download public
412 // data that has been deleted. Allow a referrer to
413 // provide this context somehow?
414 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
415 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
419 kc, err := keepclient.MakeKeepClient(arv)
421 http.Error(w, "error setting up keep client: "+err.Error(), http.StatusInternalServerError)
424 kc.RequestID = r.Header.Get("X-Request-Id")
427 if len(targetPath) > 0 {
428 basename = targetPath[len(targetPath)-1]
430 applyContentDispositionHdr(w, r, basename, attachment)
432 client := (&arvados.Client{
433 APIHost: arv.ApiServer,
434 AuthToken: arv.ApiToken,
435 Insecure: arv.ApiInsecure,
436 }).WithRequestID(r.Header.Get("X-Request-Id"))
438 fs, err := collection.FileSystem(client, kc)
440 http.Error(w, "error creating collection filesystem: "+err.Error(), http.StatusInternalServerError)
444 writefs, writeOK := fs.(arvados.CollectionFileSystem)
445 targetIsPDH := arvadosclient.PDHMatch(collectionID)
446 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
447 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
451 if webdavMethod[r.Method] {
452 if writeMethod[r.Method] {
453 // Save the collection only if/when all
454 // webdav->filesystem operations succeed --
455 // and send a 500 error if the modified
456 // collection can't be saved.
457 w = &updateOnSuccess{
459 logger: ctxlog.FromContext(r.Context()),
460 update: func() error {
461 return h.Config.Cache.Update(client, *collection, writefs)
465 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
466 FileSystem: &webdavFS{
468 writing: writeMethod[r.Method],
469 alwaysReadEOF: r.Method == "PROPFIND",
471 LockSystem: h.webdavLS,
472 Logger: func(_ *http.Request, err error) {
474 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
482 openPath := "/" + strings.Join(targetPath, "/")
483 if f, err := fs.Open(openPath); os.IsNotExist(err) {
484 // Requested non-existent path
485 http.Error(w, notFoundMessage, http.StatusNotFound)
486 } else if err != nil {
487 // Some other (unexpected) error
488 http.Error(w, "open: "+err.Error(), http.StatusInternalServerError)
489 } else if stat, err := f.Stat(); err != nil {
490 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
491 http.Error(w, "stat: "+err.Error(), http.StatusInternalServerError)
492 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
493 // If client requests ".../dirname", redirect to
494 // ".../dirname/". This way, relative links in the
495 // listing for "dirname" can always be "fnm", never
497 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
498 } else if stat.IsDir() {
499 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
501 http.ServeContent(w, r, basename, stat.ModTime(), f)
502 if wrote := int64(w.WroteBodyBytes()); wrote != stat.Size() && r.Header.Get("Range") == "" {
503 // If we wrote fewer bytes than expected, it's
504 // too late to change the real response code
505 // or send an error message to the client, but
506 // at least we can try to put some useful
507 // debugging info in the logs.
508 n, err := f.Read(make([]byte, 1024))
509 ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %s", stat.Size(), wrote, n, err)
515 func (h *handler) getClients(reqID, token string) (arv *arvadosclient.ArvadosClient, kc *keepclient.KeepClient, client *arvados.Client, release func(), err error) {
516 arv = h.clientPool.Get()
518 return nil, nil, nil, nil, err
520 release = func() { h.clientPool.Put(arv) }
522 kc, err = keepclient.MakeKeepClient(arv)
528 client = (&arvados.Client{
529 APIHost: arv.ApiServer,
530 AuthToken: arv.ApiToken,
531 Insecure: arv.ApiInsecure,
532 }).WithRequestID(reqID)
536 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
537 if len(tokens) == 0 {
538 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
539 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
542 if writeMethod[r.Method] {
543 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
546 _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), tokens[0])
548 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
553 fs := client.SiteFileSystem(kc)
554 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
555 f, err := fs.Open(r.URL.Path)
556 if os.IsNotExist(err) {
557 http.Error(w, err.Error(), http.StatusNotFound)
559 } else if err != nil {
560 http.Error(w, err.Error(), http.StatusInternalServerError)
564 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
565 if !strings.HasSuffix(r.URL.Path, "/") {
566 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
568 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
572 if r.Method == "GET" {
573 _, basename := filepath.Split(r.URL.Path)
574 applyContentDispositionHdr(w, r, basename, attachment)
576 wh := webdav.Handler{
578 FileSystem: &webdavFS{
580 writing: writeMethod[r.Method],
581 alwaysReadEOF: r.Method == "PROPFIND",
583 LockSystem: h.webdavLS,
584 Logger: func(_ *http.Request, err error) {
586 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
593 var dirListingTemplate = `<!DOCTYPE HTML>
595 <META name="robots" content="NOINDEX">
596 <TITLE>{{ .CollectionName }}</TITLE>
597 <STYLE type="text/css">
602 background-color: #D9EDF7;
603 border-radius: .25em;
614 font-family: monospace;
621 <H1>{{ .CollectionName }}</H1>
623 <P>This collection of data files is being shared with you through
624 Arvados. You can download individual files listed below. To download
625 the entire directory tree with wget, try:</P>
627 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
629 <H2>File Listing</H2>
635 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
637 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
642 <P>(No files; this collection is empty.)</P>
649 Arvados is a free and open source software bioinformatics platform.
650 To learn more, visit arvados.org.
651 Arvados is not responsible for the files listed on this page.
658 type fileListEnt struct {
664 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
665 var files []fileListEnt
666 var walk func(string) error
667 if !strings.HasSuffix(base, "/") {
670 walk = func(path string) error {
671 dirname := base + path
673 dirname = strings.TrimSuffix(dirname, "/")
675 d, err := fs.Open(dirname)
679 ents, err := d.Readdir(-1)
683 for _, ent := range ents {
684 if recurse && ent.IsDir() {
685 err = walk(path + ent.Name() + "/")
690 files = append(files, fileListEnt{
691 Name: path + ent.Name(),
699 if err := walk(""); err != nil {
700 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
704 funcs := template.FuncMap{
705 "nbsp": func(s string) template.HTML {
706 return template.HTML(strings.Replace(s, " ", " ", -1))
709 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
711 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
714 sort.Slice(files, func(i, j int) bool {
715 return files[i].Name < files[j].Name
717 w.WriteHeader(http.StatusOK)
718 tmpl.Execute(w, map[string]interface{}{
719 "CollectionName": collectionName,
722 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
726 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
727 disposition := "inline"
729 disposition = "attachment"
731 if strings.ContainsRune(r.RequestURI, '?') {
732 // Help the UA realize that the filename is just
733 // "filename.txt", not
734 // "filename.txt?disposition=attachment".
736 // TODO(TC): Follow advice at RFC 6266 appendix D
737 disposition += "; filename=" + strconv.QuoteToASCII(filename)
739 if disposition != "inline" {
740 w.Header().Set("Content-Disposition", disposition)
744 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
745 if formToken := r.FormValue("api_token"); formToken != "" {
747 // It is not safe to copy the provided token
748 // into a cookie unless the current vhost
749 // (origin) serves only a single collection or
750 // we are in TrustAllContent mode.
751 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)
755 // The HttpOnly flag is necessary to prevent
756 // JavaScript code (included in, or loaded by, a page
757 // in the collection being served) from employing the
758 // user's token beyond reading other files in the same
759 // domain, i.e., same collection.
761 // The 303 redirect is necessary in the case of a GET
762 // request to avoid exposing the token in the Location
763 // bar, and in the case of a POST request to avoid
764 // raising warnings when the user refreshes the
766 http.SetCookie(w, &http.Cookie{
767 Name: "arvados_api_token",
768 Value: auth.EncodeTokenCookie([]byte(formToken)),
774 // Propagate query parameters (except api_token) from
775 // the original request.
776 redirQuery := r.URL.Query()
777 redirQuery.Del("api_token")
781 newu, err := u.Parse(location)
783 http.Error(w, "error resolving redirect target: "+err.Error(), http.StatusInternalServerError)
789 Scheme: r.URL.Scheme,
792 RawQuery: redirQuery.Encode(),
795 w.Header().Add("Location", redir)
796 w.WriteHeader(http.StatusSeeOther)
797 io.WriteString(w, `<A href="`)
798 io.WriteString(w, html.EscapeString(redir))
799 io.WriteString(w, `">Continue</A>`)