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 // 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) setup() {
79 // Errors will be handled at the client pool.
80 arv, _ := arvados.NewClientFromConfig(h.Config.cluster)
81 h.clientPool = arvadosclient.MakeClientPoolWith(arv)
83 keepclient.RefreshServiceDiscoveryOnSIGHUP()
84 keepclient.DefaultBlockCache.MaxBlocks = h.Config.cluster.Collections.WebDAVCache.MaxBlockEntries
86 h.healthHandler = &health.Handler{
87 Token: h.Config.cluster.ManagementToken,
91 // Even though we don't accept LOCK requests, every webdav
92 // handler must have a non-nil LockSystem.
93 h.webdavLS = &noLockSystem{}
96 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
97 json.NewEncoder(w).Encode(struct{ Version string }{version})
100 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
101 // sends an HTTP header indicating success, updateOnSuccess first
102 // calls the provided update func. If the update func fails, a 500
103 // response is sent, and the status code and body sent by the handler
104 // are ignored (all response writes return the update error).
105 type updateOnSuccess struct {
106 httpserver.ResponseWriter
107 logger logrus.FieldLogger
113 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
115 uos.WriteHeader(http.StatusOK)
120 return uos.ResponseWriter.Write(p)
123 func (uos *updateOnSuccess) WriteHeader(code int) {
125 uos.sentHeader = true
126 if code >= 200 && code < 400 {
127 if uos.err = uos.update(); uos.err != nil {
128 code := http.StatusInternalServerError
129 if err, ok := uos.err.(*arvados.TransactionError); ok {
130 code = err.StatusCode
132 uos.logger.WithError(uos.err).Errorf("update() returned error type %T, changing response to HTTP %d", uos.err, code)
133 http.Error(uos.ResponseWriter, uos.err.Error(), code)
138 uos.ResponseWriter.WriteHeader(code)
142 corsAllowHeadersHeader = strings.Join([]string{
143 "Authorization", "Content-Type", "Range",
144 // WebDAV request headers:
145 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout",
147 writeMethod = map[string]bool{
158 webdavMethod = map[string]bool{
171 browserMethod = map[string]bool{
176 // top-level dirs to serve with siteFS
177 siteFSDir = map[string]bool{
178 "": true, // root directory
184 // ServeHTTP implements http.Handler.
185 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
186 h.setupOnce.Do(h.setup)
188 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
192 w := httpserver.WrapResponseWriter(wOrig)
194 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
195 h.healthHandler.ServeHTTP(w, r)
199 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
200 if !browserMethod[method] && !webdavMethod[method] {
201 w.WriteHeader(http.StatusMethodNotAllowed)
204 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
205 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
206 w.Header().Set("Access-Control-Allow-Origin", "*")
207 w.Header().Set("Access-Control-Max-Age", "86400")
211 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
212 w.WriteHeader(http.StatusMethodNotAllowed)
216 if r.Header.Get("Origin") != "" {
217 // Allow simple cross-origin requests without user
218 // credentials ("user credentials" as defined by CORS,
219 // i.e., cookies, HTTP authentication, and client-side
220 // SSL certificates. See
221 // http://www.w3.org/TR/cors/#user-credentials).
222 w.Header().Set("Access-Control-Allow-Origin", "*")
223 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
230 pathParts := strings.Split(r.URL.Path[1:], "/")
233 var collectionID string
235 var reqTokens []string
239 credentialsOK := h.Config.cluster.Collections.TrustAllContent
241 if r.Host != "" && r.Host == h.Config.cluster.Services.WebDAVDownload.ExternalURL.Host {
244 } else if r.FormValue("disposition") == "attachment" {
248 if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
249 // http://ID.collections.example/PATH...
251 } else if r.URL.Path == "/status.json" {
254 } else if strings.HasPrefix(r.URL.Path, "/metrics") {
255 h.MetricsAPI.ServeHTTP(w, r)
257 } else if siteFSDir[pathParts[0]] {
259 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
261 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
263 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
264 if len(pathParts) >= 4 && pathParts[1] == "download" {
265 // /collections/download/ID/TOKEN/PATH...
266 collectionID = parseCollectionIDFromURL(pathParts[2])
267 tokens = []string{pathParts[3]}
271 // /collections/ID/PATH...
272 collectionID = parseCollectionIDFromURL(pathParts[1])
274 // This path is only meant to work for public
275 // data. Tokens provided with the request are
277 credentialsOK = false
281 if collectionID == "" && !useSiteFS {
282 w.WriteHeader(http.StatusNotFound)
287 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
292 reqTokens = auth.CredentialsFromRequest(r).Tokens
295 formToken := r.FormValue("api_token")
296 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
297 // The client provided an explicit token in the POST
298 // body. The Origin header indicates this *might* be
299 // an AJAX request, in which case redirect-with-cookie
300 // won't work: we should just serve the content in the
301 // POST response. This is safe because:
303 // * We're supplying an attachment, not inline
304 // content, so we don't need to convert the POST to
305 // a GET and avoid the "really resubmit form?"
308 // * The token isn't embedded in the URL, so we don't
309 // need to worry about bookmarks and copy/paste.
310 reqTokens = append(reqTokens, formToken)
311 } else if formToken != "" && browserMethod[r.Method] {
312 // The client provided an explicit token in the query
313 // string, or a form in POST body. We must put the
314 // token in an HttpOnly cookie, and redirect to the
315 // same URL with the query param redacted and method =
317 h.seeOtherWithCookie(w, r, "", credentialsOK)
322 h.serveSiteFS(w, r, reqTokens, credentialsOK, attachment)
326 targetPath := pathParts[stripParts:]
327 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
328 // http://ID.example/t=TOKEN/PATH...
329 // /c=ID/t=TOKEN/PATH...
331 // This form must only be used to pass scoped tokens
332 // that give permission for a single collection. See
333 // FormValue case above.
334 tokens = []string{targetPath[0][2:]}
336 targetPath = targetPath[1:]
341 tokens = append(reqTokens, h.Config.cluster.Users.AnonymousUserToken)
344 if len(targetPath) > 0 && targetPath[0] == "_" {
345 // If a collection has a directory called "t=foo" or
346 // "_", it can be served at
347 // //collections.example/_/t=foo/ or
348 // //collections.example/_/_/ respectively:
349 // //collections.example/t=foo/ won't work because
350 // t=foo will be interpreted as a token "foo".
351 targetPath = targetPath[1:]
355 arv := h.clientPool.Get()
357 http.Error(w, "client pool error: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
360 defer h.clientPool.Put(arv)
362 var collection *arvados.Collection
363 tokenResult := make(map[string]int)
364 for _, arv.ApiToken = range tokens {
366 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
371 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
372 switch srvErr.HttpStatusCode {
374 // Token broken or insufficient to
375 // retrieve collection
376 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
380 // Something more serious is wrong
381 http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
384 if collection == nil {
385 if pathToken || !credentialsOK {
386 // Either the URL is a "secret sharing link"
387 // that didn't work out (and asking the client
388 // for additional credentials would just be
389 // confusing), or we don't even accept
390 // credentials at this path.
391 w.WriteHeader(http.StatusNotFound)
394 for _, t := range reqTokens {
395 if tokenResult[t] == 404 {
396 // The client provided valid token(s), but the
397 // collection was not found.
398 w.WriteHeader(http.StatusNotFound)
402 // The client's token was invalid (e.g., expired), or
403 // the client didn't even provide one. Propagate the
404 // 401 to encourage the client to use a [different]
407 // TODO(TC): This response would be confusing to
408 // someone trying (anonymously) to download public
409 // data that has been deleted. Allow a referrer to
410 // provide this context somehow?
411 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
412 w.WriteHeader(http.StatusUnauthorized)
416 kc, err := keepclient.MakeKeepClient(arv)
418 http.Error(w, "error setting up keep client: "+err.Error(), http.StatusInternalServerError)
421 kc.RequestID = r.Header.Get("X-Request-Id")
424 if len(targetPath) > 0 {
425 basename = targetPath[len(targetPath)-1]
427 applyContentDispositionHdr(w, r, basename, attachment)
429 client := (&arvados.Client{
430 APIHost: arv.ApiServer,
431 AuthToken: arv.ApiToken,
432 Insecure: arv.ApiInsecure,
433 }).WithRequestID(r.Header.Get("X-Request-Id"))
435 fs, err := collection.FileSystem(client, kc)
437 http.Error(w, "error creating collection filesystem: "+err.Error(), http.StatusInternalServerError)
441 writefs, writeOK := fs.(arvados.CollectionFileSystem)
442 targetIsPDH := arvadosclient.PDHMatch(collectionID)
443 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
444 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
448 if webdavMethod[r.Method] {
449 if writeMethod[r.Method] {
450 // Save the collection only if/when all
451 // webdav->filesystem operations succeed --
452 // and send a 500 error if the modified
453 // collection can't be saved.
454 w = &updateOnSuccess{
456 logger: ctxlog.FromContext(r.Context()),
457 update: func() error {
458 return h.Config.Cache.Update(client, *collection, writefs)
462 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
463 FileSystem: &webdavFS{
465 writing: writeMethod[r.Method],
466 alwaysReadEOF: r.Method == "PROPFIND",
468 LockSystem: h.webdavLS,
469 Logger: func(_ *http.Request, err error) {
471 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
479 openPath := "/" + strings.Join(targetPath, "/")
480 if f, err := fs.Open(openPath); os.IsNotExist(err) {
481 // Requested non-existent path
482 w.WriteHeader(http.StatusNotFound)
483 } else if err != nil {
484 // Some other (unexpected) error
485 http.Error(w, "open: "+err.Error(), http.StatusInternalServerError)
486 } else if stat, err := f.Stat(); err != nil {
487 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
488 http.Error(w, "stat: "+err.Error(), http.StatusInternalServerError)
489 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
490 // If client requests ".../dirname", redirect to
491 // ".../dirname/". This way, relative links in the
492 // listing for "dirname" can always be "fnm", never
494 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
495 } else if stat.IsDir() {
496 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
498 http.ServeContent(w, r, basename, stat.ModTime(), f)
499 if wrote := int64(w.WroteBodyBytes()); wrote != stat.Size() && r.Header.Get("Range") == "" {
500 // If we wrote fewer bytes than expected, it's
501 // too late to change the real response code
502 // or send an error message to the client, but
503 // at least we can try to put some useful
504 // debugging info in the logs.
505 n, err := f.Read(make([]byte, 1024))
506 ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %s", stat.Size(), wrote, n, err)
512 func (h *handler) getClients(reqID, token string) (arv *arvadosclient.ArvadosClient, kc *keepclient.KeepClient, client *arvados.Client, release func(), err error) {
513 arv = h.clientPool.Get()
515 return nil, nil, nil, nil, err
517 release = func() { h.clientPool.Put(arv) }
519 kc, err = keepclient.MakeKeepClient(arv)
525 client = (&arvados.Client{
526 APIHost: arv.ApiServer,
527 AuthToken: arv.ApiToken,
528 Insecure: arv.ApiInsecure,
529 }).WithRequestID(reqID)
533 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
534 if len(tokens) == 0 {
535 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
536 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
539 if writeMethod[r.Method] {
540 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
543 _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), tokens[0])
545 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
550 fs := client.SiteFileSystem(kc)
551 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
552 f, err := fs.Open(r.URL.Path)
553 if os.IsNotExist(err) {
554 http.Error(w, err.Error(), http.StatusNotFound)
556 } else if err != nil {
557 http.Error(w, err.Error(), http.StatusInternalServerError)
561 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
562 if !strings.HasSuffix(r.URL.Path, "/") {
563 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
565 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
569 if r.Method == "GET" {
570 _, basename := filepath.Split(r.URL.Path)
571 applyContentDispositionHdr(w, r, basename, attachment)
573 wh := webdav.Handler{
575 FileSystem: &webdavFS{
577 writing: writeMethod[r.Method],
578 alwaysReadEOF: r.Method == "PROPFIND",
580 LockSystem: h.webdavLS,
581 Logger: func(_ *http.Request, err error) {
583 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
590 var dirListingTemplate = `<!DOCTYPE HTML>
592 <META name="robots" content="NOINDEX">
593 <TITLE>{{ .CollectionName }}</TITLE>
594 <STYLE type="text/css">
599 background-color: #D9EDF7;
600 border-radius: .25em;
611 font-family: monospace;
618 <H1>{{ .CollectionName }}</H1>
620 <P>This collection of data files is being shared with you through
621 Arvados. You can download individual files listed below. To download
622 the entire directory tree with wget, try:</P>
624 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
626 <H2>File Listing</H2>
632 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
634 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
639 <P>(No files; this collection is empty.)</P>
646 Arvados is a free and open source software bioinformatics platform.
647 To learn more, visit arvados.org.
648 Arvados is not responsible for the files listed on this page.
655 type fileListEnt struct {
661 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
662 var files []fileListEnt
663 var walk func(string) error
664 if !strings.HasSuffix(base, "/") {
667 walk = func(path string) error {
668 dirname := base + path
670 dirname = strings.TrimSuffix(dirname, "/")
672 d, err := fs.Open(dirname)
676 ents, err := d.Readdir(-1)
680 for _, ent := range ents {
681 if recurse && ent.IsDir() {
682 err = walk(path + ent.Name() + "/")
687 files = append(files, fileListEnt{
688 Name: path + ent.Name(),
696 if err := walk(""); err != nil {
697 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
701 funcs := template.FuncMap{
702 "nbsp": func(s string) template.HTML {
703 return template.HTML(strings.Replace(s, " ", " ", -1))
706 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
708 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
711 sort.Slice(files, func(i, j int) bool {
712 return files[i].Name < files[j].Name
714 w.WriteHeader(http.StatusOK)
715 tmpl.Execute(w, map[string]interface{}{
716 "CollectionName": collectionName,
719 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
723 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
724 disposition := "inline"
726 disposition = "attachment"
728 if strings.ContainsRune(r.RequestURI, '?') {
729 // Help the UA realize that the filename is just
730 // "filename.txt", not
731 // "filename.txt?disposition=attachment".
733 // TODO(TC): Follow advice at RFC 6266 appendix D
734 disposition += "; filename=" + strconv.QuoteToASCII(filename)
736 if disposition != "inline" {
737 w.Header().Set("Content-Disposition", disposition)
741 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
742 if formToken := r.FormValue("api_token"); formToken != "" {
744 // It is not safe to copy the provided token
745 // into a cookie unless the current vhost
746 // (origin) serves only a single collection or
747 // we are in TrustAllContent mode.
748 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)
752 // The HttpOnly flag is necessary to prevent
753 // JavaScript code (included in, or loaded by, a page
754 // in the collection being served) from employing the
755 // user's token beyond reading other files in the same
756 // domain, i.e., same collection.
758 // The 303 redirect is necessary in the case of a GET
759 // request to avoid exposing the token in the Location
760 // bar, and in the case of a POST request to avoid
761 // raising warnings when the user refreshes the
763 http.SetCookie(w, &http.Cookie{
764 Name: "arvados_api_token",
765 Value: auth.EncodeTokenCookie([]byte(formToken)),
771 // Propagate query parameters (except api_token) from
772 // the original request.
773 redirQuery := r.URL.Query()
774 redirQuery.Del("api_token")
778 newu, err := u.Parse(location)
780 http.Error(w, "error resolving redirect target: "+err.Error(), http.StatusInternalServerError)
786 Scheme: r.URL.Scheme,
789 RawQuery: redirQuery.Encode(),
792 w.Header().Add("Location", redir)
793 w.WriteHeader(http.StatusSeeOther)
794 io.WriteString(w, `<A href="`)
795 io.WriteString(w, html.EscapeString(redir))
796 io.WriteString(w, `">Continue</A>`)