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 remoteAddr := r.RemoteAddr
189 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
190 remoteAddr = xff + "," + remoteAddr
192 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
196 w := httpserver.WrapResponseWriter(wOrig)
198 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
199 h.healthHandler.ServeHTTP(w, r)
203 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
204 if !browserMethod[method] && !webdavMethod[method] {
205 w.WriteHeader(http.StatusMethodNotAllowed)
208 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
209 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
210 w.Header().Set("Access-Control-Allow-Origin", "*")
211 w.Header().Set("Access-Control-Max-Age", "86400")
215 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
216 w.WriteHeader(http.StatusMethodNotAllowed)
220 if r.Header.Get("Origin") != "" {
221 // Allow simple cross-origin requests without user
222 // credentials ("user credentials" as defined by CORS,
223 // i.e., cookies, HTTP authentication, and client-side
224 // SSL certificates. See
225 // http://www.w3.org/TR/cors/#user-credentials).
226 w.Header().Set("Access-Control-Allow-Origin", "*")
227 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) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
513 if len(tokens) == 0 {
514 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
515 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
518 if writeMethod[r.Method] {
519 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
522 arv := h.clientPool.Get()
524 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
527 defer h.clientPool.Put(arv)
528 arv.ApiToken = tokens[0]
530 kc, err := keepclient.MakeKeepClient(arv)
532 http.Error(w, "error setting up keep client: "+err.Error(), http.StatusInternalServerError)
535 kc.RequestID = r.Header.Get("X-Request-Id")
536 client := (&arvados.Client{
537 APIHost: arv.ApiServer,
538 AuthToken: arv.ApiToken,
539 Insecure: arv.ApiInsecure,
540 }).WithRequestID(r.Header.Get("X-Request-Id"))
541 fs := client.SiteFileSystem(kc)
542 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
543 f, err := fs.Open(r.URL.Path)
544 if os.IsNotExist(err) {
545 http.Error(w, err.Error(), http.StatusNotFound)
547 } else if err != nil {
548 http.Error(w, err.Error(), http.StatusInternalServerError)
552 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
553 if !strings.HasSuffix(r.URL.Path, "/") {
554 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
556 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
560 if r.Method == "GET" {
561 _, basename := filepath.Split(r.URL.Path)
562 applyContentDispositionHdr(w, r, basename, attachment)
564 wh := webdav.Handler{
566 FileSystem: &webdavFS{
568 writing: writeMethod[r.Method],
569 alwaysReadEOF: r.Method == "PROPFIND",
571 LockSystem: h.webdavLS,
572 Logger: func(_ *http.Request, err error) {
574 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
581 var dirListingTemplate = `<!DOCTYPE HTML>
583 <META name="robots" content="NOINDEX">
584 <TITLE>{{ .CollectionName }}</TITLE>
585 <STYLE type="text/css">
590 background-color: #D9EDF7;
591 border-radius: .25em;
602 font-family: monospace;
609 <H1>{{ .CollectionName }}</H1>
611 <P>This collection of data files is being shared with you through
612 Arvados. You can download individual files listed below. To download
613 the entire directory tree with wget, try:</P>
615 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
617 <H2>File Listing</H2>
623 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
625 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
630 <P>(No files; this collection is empty.)</P>
637 Arvados is a free and open source software bioinformatics platform.
638 To learn more, visit arvados.org.
639 Arvados is not responsible for the files listed on this page.
646 type fileListEnt struct {
652 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
653 var files []fileListEnt
654 var walk func(string) error
655 if !strings.HasSuffix(base, "/") {
658 walk = func(path string) error {
659 dirname := base + path
661 dirname = strings.TrimSuffix(dirname, "/")
663 d, err := fs.Open(dirname)
667 ents, err := d.Readdir(-1)
671 for _, ent := range ents {
672 if recurse && ent.IsDir() {
673 err = walk(path + ent.Name() + "/")
678 files = append(files, fileListEnt{
679 Name: path + ent.Name(),
687 if err := walk(""); err != nil {
688 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
692 funcs := template.FuncMap{
693 "nbsp": func(s string) template.HTML {
694 return template.HTML(strings.Replace(s, " ", " ", -1))
697 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
699 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
702 sort.Slice(files, func(i, j int) bool {
703 return files[i].Name < files[j].Name
705 w.WriteHeader(http.StatusOK)
706 tmpl.Execute(w, map[string]interface{}{
707 "CollectionName": collectionName,
710 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
714 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
715 disposition := "inline"
717 disposition = "attachment"
719 if strings.ContainsRune(r.RequestURI, '?') {
720 // Help the UA realize that the filename is just
721 // "filename.txt", not
722 // "filename.txt?disposition=attachment".
724 // TODO(TC): Follow advice at RFC 6266 appendix D
725 disposition += "; filename=" + strconv.QuoteToASCII(filename)
727 if disposition != "inline" {
728 w.Header().Set("Content-Disposition", disposition)
732 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
733 if formToken := r.FormValue("api_token"); formToken != "" {
735 // It is not safe to copy the provided token
736 // into a cookie unless the current vhost
737 // (origin) serves only a single collection or
738 // we are in TrustAllContent mode.
739 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)
743 // The HttpOnly flag is necessary to prevent
744 // JavaScript code (included in, or loaded by, a page
745 // in the collection being served) from employing the
746 // user's token beyond reading other files in the same
747 // domain, i.e., same collection.
749 // The 303 redirect is necessary in the case of a GET
750 // request to avoid exposing the token in the Location
751 // bar, and in the case of a POST request to avoid
752 // raising warnings when the user refreshes the
754 http.SetCookie(w, &http.Cookie{
755 Name: "arvados_api_token",
756 Value: auth.EncodeTokenCookie([]byte(formToken)),
762 // Propagate query parameters (except api_token) from
763 // the original request.
764 redirQuery := r.URL.Query()
765 redirQuery.Del("api_token")
769 newu, err := u.Parse(location)
771 http.Error(w, "error resolving redirect target: "+err.Error(), http.StatusInternalServerError)
777 Scheme: r.URL.Scheme,
780 RawQuery: redirQuery.Encode(),
783 w.Header().Add("Location", redir)
784 w.WriteHeader(http.StatusSeeOther)
785 io.WriteString(w, `<A href="`)
786 io.WriteString(w, html.EscapeString(redir))
787 io.WriteString(w, `">Continue</A>`)