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\r\n\r\nThe requested path was not found, or you do not have permission to access it.\r"
66 var unauthorizedMessage = "401 Unauthorized\r\n\r\nA valid Arvados token must be provided to access this resource.\r"
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 origin := r.Header.Get("Origin")
300 cors := origin != "" && !strings.HasSuffix(origin, "://"+r.Host)
301 safeAjax := cors && (r.Method == http.MethodGet || r.Method == http.MethodHead)
302 safeAttachment := attachment && r.URL.Query().Get("api_token") == ""
304 // No token to use or redact.
305 } else if safeAjax || safeAttachment {
306 // If this is a cross-origin request, the URL won't
307 // appear in the browser's address bar, so
308 // substituting a clipboard-safe URL is pointless.
309 // Redirect-with-cookie wouldn't work anyway, because
310 // it's not safe to allow third-party use of our
313 // If we're supplying an attachment, we don't need to
314 // convert POST to GET to avoid the "really resubmit
315 // form?" problem, so provided the token isn't
316 // embedded in the URL, there's no reason to do
317 // redirect-with-cookie in this case either.
318 reqTokens = append(reqTokens, formToken)
319 } else if browserMethod[r.Method] {
320 // If this is a page view, and the client provided a
321 // token via query string or POST body, we must put
322 // the token in an HttpOnly cookie, and redirect to an
323 // equivalent URL with the query param redacted and
325 h.seeOtherWithCookie(w, r, "", credentialsOK)
330 h.serveSiteFS(w, r, reqTokens, credentialsOK, attachment)
334 targetPath := pathParts[stripParts:]
335 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
336 // http://ID.example/t=TOKEN/PATH...
337 // /c=ID/t=TOKEN/PATH...
339 // This form must only be used to pass scoped tokens
340 // that give permission for a single collection. See
341 // FormValue case above.
342 tokens = []string{targetPath[0][2:]}
344 targetPath = targetPath[1:]
349 tokens = append(reqTokens, h.Config.cluster.Users.AnonymousUserToken)
352 if len(targetPath) > 0 && targetPath[0] == "_" {
353 // If a collection has a directory called "t=foo" or
354 // "_", it can be served at
355 // //collections.example/_/t=foo/ or
356 // //collections.example/_/_/ respectively:
357 // //collections.example/t=foo/ won't work because
358 // t=foo will be interpreted as a token "foo".
359 targetPath = targetPath[1:]
363 arv := h.clientPool.Get()
365 http.Error(w, "client pool error: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
368 defer h.clientPool.Put(arv)
370 var collection *arvados.Collection
371 tokenResult := make(map[string]int)
372 for _, arv.ApiToken = range tokens {
374 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
379 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
380 switch srvErr.HttpStatusCode {
382 // Token broken or insufficient to
383 // retrieve collection
384 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
388 // Something more serious is wrong
389 http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
392 if collection == nil {
393 if pathToken || !credentialsOK {
394 // Either the URL is a "secret sharing link"
395 // that didn't work out (and asking the client
396 // for additional credentials would just be
397 // confusing), or we don't even accept
398 // credentials at this path.
399 http.Error(w, notFoundMessage, http.StatusNotFound)
402 for _, t := range reqTokens {
403 if tokenResult[t] == 404 {
404 // The client provided valid token(s), but the
405 // collection was not found.
406 http.Error(w, notFoundMessage, http.StatusNotFound)
410 // The client's token was invalid (e.g., expired), or
411 // the client didn't even provide one. Propagate the
412 // 401 to encourage the client to use a [different]
415 // TODO(TC): This response would be confusing to
416 // someone trying (anonymously) to download public
417 // data that has been deleted. Allow a referrer to
418 // provide this context somehow?
419 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
420 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
424 kc, err := keepclient.MakeKeepClient(arv)
426 http.Error(w, "error setting up keep client: "+err.Error(), http.StatusInternalServerError)
429 kc.RequestID = r.Header.Get("X-Request-Id")
432 if len(targetPath) > 0 {
433 basename = targetPath[len(targetPath)-1]
435 applyContentDispositionHdr(w, r, basename, attachment)
437 client := (&arvados.Client{
438 APIHost: arv.ApiServer,
439 AuthToken: arv.ApiToken,
440 Insecure: arv.ApiInsecure,
441 }).WithRequestID(r.Header.Get("X-Request-Id"))
443 fs, err := collection.FileSystem(client, kc)
445 http.Error(w, "error creating collection filesystem: "+err.Error(), http.StatusInternalServerError)
449 writefs, writeOK := fs.(arvados.CollectionFileSystem)
450 targetIsPDH := arvadosclient.PDHMatch(collectionID)
451 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
452 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
456 if webdavMethod[r.Method] {
457 if writeMethod[r.Method] {
458 // Save the collection only if/when all
459 // webdav->filesystem operations succeed --
460 // and send a 500 error if the modified
461 // collection can't be saved.
462 w = &updateOnSuccess{
464 logger: ctxlog.FromContext(r.Context()),
465 update: func() error {
466 return h.Config.Cache.Update(client, *collection, writefs)
470 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
471 FileSystem: &webdavFS{
473 writing: writeMethod[r.Method],
474 alwaysReadEOF: r.Method == "PROPFIND",
476 LockSystem: h.webdavLS,
477 Logger: func(_ *http.Request, err error) {
479 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
487 openPath := "/" + strings.Join(targetPath, "/")
488 if f, err := fs.Open(openPath); os.IsNotExist(err) {
489 // Requested non-existent path
490 http.Error(w, notFoundMessage, http.StatusNotFound)
491 } else if err != nil {
492 // Some other (unexpected) error
493 http.Error(w, "open: "+err.Error(), http.StatusInternalServerError)
494 } else if stat, err := f.Stat(); err != nil {
495 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
496 http.Error(w, "stat: "+err.Error(), http.StatusInternalServerError)
497 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
498 // If client requests ".../dirname", redirect to
499 // ".../dirname/". This way, relative links in the
500 // listing for "dirname" can always be "fnm", never
502 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
503 } else if stat.IsDir() {
504 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
506 http.ServeContent(w, r, basename, stat.ModTime(), f)
507 if wrote := int64(w.WroteBodyBytes()); wrote != stat.Size() && r.Header.Get("Range") == "" {
508 // If we wrote fewer bytes than expected, it's
509 // too late to change the real response code
510 // or send an error message to the client, but
511 // at least we can try to put some useful
512 // debugging info in the logs.
513 n, err := f.Read(make([]byte, 1024))
514 ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %s", stat.Size(), wrote, n, err)
520 func (h *handler) getClients(reqID, token string) (arv *arvadosclient.ArvadosClient, kc *keepclient.KeepClient, client *arvados.Client, release func(), err error) {
521 arv = h.clientPool.Get()
523 return nil, nil, nil, nil, err
525 release = func() { h.clientPool.Put(arv) }
527 kc, err = keepclient.MakeKeepClient(arv)
533 client = (&arvados.Client{
534 APIHost: arv.ApiServer,
535 AuthToken: arv.ApiToken,
536 Insecure: arv.ApiInsecure,
537 }).WithRequestID(reqID)
541 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
542 if len(tokens) == 0 {
543 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
544 http.Error(w, unauthorizedMessage, http.StatusUnauthorized)
547 if writeMethod[r.Method] {
548 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
551 _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), tokens[0])
553 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
558 fs := client.SiteFileSystem(kc)
559 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
560 f, err := fs.Open(r.URL.Path)
561 if os.IsNotExist(err) {
562 http.Error(w, err.Error(), http.StatusNotFound)
564 } else if err != nil {
565 http.Error(w, err.Error(), http.StatusInternalServerError)
569 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
570 if !strings.HasSuffix(r.URL.Path, "/") {
571 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
573 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
577 if r.Method == "GET" {
578 _, basename := filepath.Split(r.URL.Path)
579 applyContentDispositionHdr(w, r, basename, attachment)
581 wh := webdav.Handler{
583 FileSystem: &webdavFS{
585 writing: writeMethod[r.Method],
586 alwaysReadEOF: r.Method == "PROPFIND",
588 LockSystem: h.webdavLS,
589 Logger: func(_ *http.Request, err error) {
591 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
598 var dirListingTemplate = `<!DOCTYPE HTML>
600 <META name="robots" content="NOINDEX">
601 <TITLE>{{ .CollectionName }}</TITLE>
602 <STYLE type="text/css">
607 background-color: #D9EDF7;
608 border-radius: .25em;
619 font-family: monospace;
626 <H1>{{ .CollectionName }}</H1>
628 <P>This collection of data files is being shared with you through
629 Arvados. You can download individual files listed below. To download
630 the entire directory tree with wget, try:</P>
632 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
634 <H2>File Listing</H2>
640 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
642 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
647 <P>(No files; this collection is empty.)</P>
654 Arvados is a free and open source software bioinformatics platform.
655 To learn more, visit arvados.org.
656 Arvados is not responsible for the files listed on this page.
663 type fileListEnt struct {
669 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
670 var files []fileListEnt
671 var walk func(string) error
672 if !strings.HasSuffix(base, "/") {
675 walk = func(path string) error {
676 dirname := base + path
678 dirname = strings.TrimSuffix(dirname, "/")
680 d, err := fs.Open(dirname)
684 ents, err := d.Readdir(-1)
688 for _, ent := range ents {
689 if recurse && ent.IsDir() {
690 err = walk(path + ent.Name() + "/")
695 files = append(files, fileListEnt{
696 Name: path + ent.Name(),
704 if err := walk(""); err != nil {
705 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
709 funcs := template.FuncMap{
710 "nbsp": func(s string) template.HTML {
711 return template.HTML(strings.Replace(s, " ", " ", -1))
714 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
716 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
719 sort.Slice(files, func(i, j int) bool {
720 return files[i].Name < files[j].Name
722 w.WriteHeader(http.StatusOK)
723 tmpl.Execute(w, map[string]interface{}{
724 "CollectionName": collectionName,
727 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
731 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
732 disposition := "inline"
734 disposition = "attachment"
736 if strings.ContainsRune(r.RequestURI, '?') {
737 // Help the UA realize that the filename is just
738 // "filename.txt", not
739 // "filename.txt?disposition=attachment".
741 // TODO(TC): Follow advice at RFC 6266 appendix D
742 disposition += "; filename=" + strconv.QuoteToASCII(filename)
744 if disposition != "inline" {
745 w.Header().Set("Content-Disposition", disposition)
749 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
750 if formToken := r.FormValue("api_token"); formToken != "" {
752 // It is not safe to copy the provided token
753 // into a cookie unless the current vhost
754 // (origin) serves only a single collection or
755 // we are in TrustAllContent mode.
756 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)
760 // The HttpOnly flag is necessary to prevent
761 // JavaScript code (included in, or loaded by, a page
762 // in the collection being served) from employing the
763 // user's token beyond reading other files in the same
764 // domain, i.e., same collection.
766 // The 303 redirect is necessary in the case of a GET
767 // request to avoid exposing the token in the Location
768 // bar, and in the case of a POST request to avoid
769 // raising warnings when the user refreshes the
771 http.SetCookie(w, &http.Cookie{
772 Name: "arvados_api_token",
773 Value: auth.EncodeTokenCookie([]byte(formToken)),
776 SameSite: http.SameSiteLaxMode,
780 // Propagate query parameters (except api_token) from
781 // the original request.
782 redirQuery := r.URL.Query()
783 redirQuery.Del("api_token")
787 newu, err := u.Parse(location)
789 http.Error(w, "error resolving redirect target: "+err.Error(), http.StatusInternalServerError)
795 Scheme: r.URL.Scheme,
798 RawQuery: redirQuery.Encode(),
801 w.Header().Add("Location", redir)
802 w.WriteHeader(http.StatusSeeOther)
803 io.WriteString(w, `<A href="`)
804 io.WriteString(w, html.EscapeString(redir))
805 io.WriteString(w, `">Continue</A>`)