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 h.clientPool = arvadosclient.MakeClientPool()
81 keepclient.RefreshServiceDiscoveryOnSIGHUP()
82 keepclient.DefaultBlockCache.MaxBlocks = h.Config.cluster.Collections.WebDAVCache.MaxBlockEntries
84 h.healthHandler = &health.Handler{
85 Token: h.Config.cluster.ManagementToken,
89 // Even though we don't accept LOCK requests, every webdav
90 // handler must have a non-nil LockSystem.
91 h.webdavLS = &noLockSystem{}
94 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
95 json.NewEncoder(w).Encode(struct{ Version string }{version})
98 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
99 // sends an HTTP header indicating success, updateOnSuccess first
100 // calls the provided update func. If the update func fails, a 500
101 // response is sent, and the status code and body sent by the handler
102 // are ignored (all response writes return the update error).
103 type updateOnSuccess struct {
104 httpserver.ResponseWriter
105 logger logrus.FieldLogger
111 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
113 uos.WriteHeader(http.StatusOK)
118 return uos.ResponseWriter.Write(p)
121 func (uos *updateOnSuccess) WriteHeader(code int) {
123 uos.sentHeader = true
124 if code >= 200 && code < 400 {
125 if uos.err = uos.update(); uos.err != nil {
126 code := http.StatusInternalServerError
127 if err, ok := uos.err.(*arvados.TransactionError); ok {
128 code = err.StatusCode
130 uos.logger.WithError(uos.err).Errorf("update() returned error type %T, changing response to HTTP %d", uos.err, code)
131 http.Error(uos.ResponseWriter, uos.err.Error(), code)
136 uos.ResponseWriter.WriteHeader(code)
140 corsAllowHeadersHeader = strings.Join([]string{
141 "Authorization", "Content-Type", "Range",
142 // WebDAV request headers:
143 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout",
145 writeMethod = map[string]bool{
156 webdavMethod = map[string]bool{
169 browserMethod = map[string]bool{
174 // top-level dirs to serve with siteFS
175 siteFSDir = map[string]bool{
176 "": true, // root directory
182 // ServeHTTP implements http.Handler.
183 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
184 h.setupOnce.Do(h.setup)
186 remoteAddr := r.RemoteAddr
187 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
188 remoteAddr = xff + "," + remoteAddr
190 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
194 w := httpserver.WrapResponseWriter(wOrig)
196 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
197 h.healthHandler.ServeHTTP(w, r)
201 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
202 if !browserMethod[method] && !webdavMethod[method] {
203 w.WriteHeader(http.StatusMethodNotAllowed)
206 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
207 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
208 w.Header().Set("Access-Control-Allow-Origin", "*")
209 w.Header().Set("Access-Control-Max-Age", "86400")
213 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
214 w.WriteHeader(http.StatusMethodNotAllowed)
218 if r.Header.Get("Origin") != "" {
219 // Allow simple cross-origin requests without user
220 // credentials ("user credentials" as defined by CORS,
221 // i.e., cookies, HTTP authentication, and client-side
222 // SSL certificates. See
223 // http://www.w3.org/TR/cors/#user-credentials).
224 w.Header().Set("Access-Control-Allow-Origin", "*")
225 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
228 pathParts := strings.Split(r.URL.Path[1:], "/")
231 var collectionID string
233 var reqTokens []string
237 credentialsOK := h.Config.cluster.Collections.TrustAllContent
239 if r.Host != "" && r.Host == h.Config.cluster.Services.WebDAVDownload.ExternalURL.Host {
242 } else if r.FormValue("disposition") == "attachment" {
246 if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
247 // http://ID.collections.example/PATH...
249 } else if r.URL.Path == "/status.json" {
252 } else if strings.HasPrefix(r.URL.Path, "/metrics") {
253 h.MetricsAPI.ServeHTTP(w, r)
255 } else if siteFSDir[pathParts[0]] {
257 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
259 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
261 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
262 if len(pathParts) >= 4 && pathParts[1] == "download" {
263 // /collections/download/ID/TOKEN/PATH...
264 collectionID = parseCollectionIDFromURL(pathParts[2])
265 tokens = []string{pathParts[3]}
269 // /collections/ID/PATH...
270 collectionID = parseCollectionIDFromURL(pathParts[1])
272 // This path is only meant to work for public
273 // data. Tokens provided with the request are
275 credentialsOK = false
279 if collectionID == "" && !useSiteFS {
280 w.WriteHeader(http.StatusNotFound)
285 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
290 reqTokens = auth.CredentialsFromRequest(r).Tokens
293 formToken := r.FormValue("api_token")
294 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
295 // The client provided an explicit token in the POST
296 // body. The Origin header indicates this *might* be
297 // an AJAX request, in which case redirect-with-cookie
298 // won't work: we should just serve the content in the
299 // POST response. This is safe because:
301 // * We're supplying an attachment, not inline
302 // content, so we don't need to convert the POST to
303 // a GET and avoid the "really resubmit form?"
306 // * The token isn't embedded in the URL, so we don't
307 // need to worry about bookmarks and copy/paste.
308 reqTokens = append(reqTokens, formToken)
309 } else if formToken != "" && browserMethod[r.Method] {
310 // The client provided an explicit token in the query
311 // string, or a form in POST body. We must put the
312 // token in an HttpOnly cookie, and redirect to the
313 // same URL with the query param redacted and method =
315 h.seeOtherWithCookie(w, r, "", credentialsOK)
320 h.serveSiteFS(w, r, reqTokens, credentialsOK, attachment)
324 targetPath := pathParts[stripParts:]
325 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
326 // http://ID.example/t=TOKEN/PATH...
327 // /c=ID/t=TOKEN/PATH...
329 // This form must only be used to pass scoped tokens
330 // that give permission for a single collection. See
331 // FormValue case above.
332 tokens = []string{targetPath[0][2:]}
334 targetPath = targetPath[1:]
339 tokens = append(reqTokens, h.Config.cluster.Users.AnonymousUserToken)
342 if len(targetPath) > 0 && targetPath[0] == "_" {
343 // If a collection has a directory called "t=foo" or
344 // "_", it can be served at
345 // //collections.example/_/t=foo/ or
346 // //collections.example/_/_/ respectively:
347 // //collections.example/t=foo/ won't work because
348 // t=foo will be interpreted as a token "foo".
349 targetPath = targetPath[1:]
353 arv := h.clientPool.Get()
355 http.Error(w, "client pool error: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
358 defer h.clientPool.Put(arv)
360 var collection *arvados.Collection
361 tokenResult := make(map[string]int)
362 for _, arv.ApiToken = range tokens {
364 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
369 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
370 switch srvErr.HttpStatusCode {
372 // Token broken or insufficient to
373 // retrieve collection
374 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
378 // Something more serious is wrong
379 http.Error(w, "cache error: "+err.Error(), http.StatusInternalServerError)
382 if collection == nil {
383 if pathToken || !credentialsOK {
384 // Either the URL is a "secret sharing link"
385 // that didn't work out (and asking the client
386 // for additional credentials would just be
387 // confusing), or we don't even accept
388 // credentials at this path.
389 w.WriteHeader(http.StatusNotFound)
392 for _, t := range reqTokens {
393 if tokenResult[t] == 404 {
394 // The client provided valid token(s), but the
395 // collection was not found.
396 w.WriteHeader(http.StatusNotFound)
400 // The client's token was invalid (e.g., expired), or
401 // the client didn't even provide one. Propagate the
402 // 401 to encourage the client to use a [different]
405 // TODO(TC): This response would be confusing to
406 // someone trying (anonymously) to download public
407 // data that has been deleted. Allow a referrer to
408 // provide this context somehow?
409 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
410 w.WriteHeader(http.StatusUnauthorized)
414 kc, err := keepclient.MakeKeepClient(arv)
416 http.Error(w, "error setting up keep client: "+err.Error(), http.StatusInternalServerError)
419 kc.RequestID = r.Header.Get("X-Request-Id")
422 if len(targetPath) > 0 {
423 basename = targetPath[len(targetPath)-1]
425 applyContentDispositionHdr(w, r, basename, attachment)
427 client := (&arvados.Client{
428 APIHost: arv.ApiServer,
429 AuthToken: arv.ApiToken,
430 Insecure: arv.ApiInsecure,
431 }).WithRequestID(r.Header.Get("X-Request-Id"))
433 fs, err := collection.FileSystem(client, kc)
435 http.Error(w, "error creating collection filesystem: "+err.Error(), http.StatusInternalServerError)
439 writefs, writeOK := fs.(arvados.CollectionFileSystem)
440 targetIsPDH := arvadosclient.PDHMatch(collectionID)
441 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
442 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
446 if webdavMethod[r.Method] {
447 if writeMethod[r.Method] {
448 // Save the collection only if/when all
449 // webdav->filesystem operations succeed --
450 // and send a 500 error if the modified
451 // collection can't be saved.
452 w = &updateOnSuccess{
454 logger: ctxlog.FromContext(r.Context()),
455 update: func() error {
456 return h.Config.Cache.Update(client, *collection, writefs)
460 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
461 FileSystem: &webdavFS{
463 writing: writeMethod[r.Method],
464 alwaysReadEOF: r.Method == "PROPFIND",
466 LockSystem: h.webdavLS,
467 Logger: func(_ *http.Request, err error) {
469 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
477 openPath := "/" + strings.Join(targetPath, "/")
478 if f, err := fs.Open(openPath); os.IsNotExist(err) {
479 // Requested non-existent path
480 w.WriteHeader(http.StatusNotFound)
481 } else if err != nil {
482 // Some other (unexpected) error
483 http.Error(w, "open: "+err.Error(), http.StatusInternalServerError)
484 } else if stat, err := f.Stat(); err != nil {
485 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
486 http.Error(w, "stat: "+err.Error(), http.StatusInternalServerError)
487 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
488 // If client requests ".../dirname", redirect to
489 // ".../dirname/". This way, relative links in the
490 // listing for "dirname" can always be "fnm", never
492 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
493 } else if stat.IsDir() {
494 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
496 http.ServeContent(w, r, basename, stat.ModTime(), f)
497 if wrote := int64(w.WroteBodyBytes()); wrote != stat.Size() && r.Header.Get("Range") == "" {
498 // If we wrote fewer bytes than expected, it's
499 // too late to change the real response code
500 // or send an error message to the client, but
501 // at least we can try to put some useful
502 // debugging info in the logs.
503 n, err := f.Read(make([]byte, 1024))
504 ctxlog.FromContext(r.Context()).Errorf("stat.Size()==%d but only wrote %d bytes; read(1024) returns %d, %s", stat.Size(), wrote, n, err)
510 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
511 if len(tokens) == 0 {
512 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
513 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
516 if writeMethod[r.Method] {
517 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
520 arv := h.clientPool.Get()
522 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
525 defer h.clientPool.Put(arv)
526 arv.ApiToken = tokens[0]
528 kc, err := keepclient.MakeKeepClient(arv)
530 http.Error(w, "error setting up keep client: "+err.Error(), http.StatusInternalServerError)
533 kc.RequestID = r.Header.Get("X-Request-Id")
534 client := (&arvados.Client{
535 APIHost: arv.ApiServer,
536 AuthToken: arv.ApiToken,
537 Insecure: arv.ApiInsecure,
538 }).WithRequestID(r.Header.Get("X-Request-Id"))
539 fs := client.SiteFileSystem(kc)
540 fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
541 f, err := fs.Open(r.URL.Path)
542 if os.IsNotExist(err) {
543 http.Error(w, err.Error(), http.StatusNotFound)
545 } else if err != nil {
546 http.Error(w, err.Error(), http.StatusInternalServerError)
550 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
551 if !strings.HasSuffix(r.URL.Path, "/") {
552 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
554 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
558 if r.Method == "GET" {
559 _, basename := filepath.Split(r.URL.Path)
560 applyContentDispositionHdr(w, r, basename, attachment)
562 wh := webdav.Handler{
564 FileSystem: &webdavFS{
566 writing: writeMethod[r.Method],
567 alwaysReadEOF: r.Method == "PROPFIND",
569 LockSystem: h.webdavLS,
570 Logger: func(_ *http.Request, err error) {
572 ctxlog.FromContext(r.Context()).WithError(err).Error("error reported by webdav handler")
579 var dirListingTemplate = `<!DOCTYPE HTML>
581 <META name="robots" content="NOINDEX">
582 <TITLE>{{ .CollectionName }}</TITLE>
583 <STYLE type="text/css">
588 background-color: #D9EDF7;
589 border-radius: .25em;
600 font-family: monospace;
607 <H1>{{ .CollectionName }}</H1>
609 <P>This collection of data files is being shared with you through
610 Arvados. You can download individual files listed below. To download
611 the entire directory tree with wget, try:</P>
613 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
615 <H2>File Listing</H2>
621 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
623 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
628 <P>(No files; this collection is empty.)</P>
635 Arvados is a free and open source software bioinformatics platform.
636 To learn more, visit arvados.org.
637 Arvados is not responsible for the files listed on this page.
644 type fileListEnt struct {
650 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
651 var files []fileListEnt
652 var walk func(string) error
653 if !strings.HasSuffix(base, "/") {
656 walk = func(path string) error {
657 dirname := base + path
659 dirname = strings.TrimSuffix(dirname, "/")
661 d, err := fs.Open(dirname)
665 ents, err := d.Readdir(-1)
669 for _, ent := range ents {
670 if recurse && ent.IsDir() {
671 err = walk(path + ent.Name() + "/")
676 files = append(files, fileListEnt{
677 Name: path + ent.Name(),
685 if err := walk(""); err != nil {
686 http.Error(w, "error getting directory listing: "+err.Error(), http.StatusInternalServerError)
690 funcs := template.FuncMap{
691 "nbsp": func(s string) template.HTML {
692 return template.HTML(strings.Replace(s, " ", " ", -1))
695 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
697 http.Error(w, "error parsing template: "+err.Error(), http.StatusInternalServerError)
700 sort.Slice(files, func(i, j int) bool {
701 return files[i].Name < files[j].Name
703 w.WriteHeader(http.StatusOK)
704 tmpl.Execute(w, map[string]interface{}{
705 "CollectionName": collectionName,
708 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
712 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
713 disposition := "inline"
715 disposition = "attachment"
717 if strings.ContainsRune(r.RequestURI, '?') {
718 // Help the UA realize that the filename is just
719 // "filename.txt", not
720 // "filename.txt?disposition=attachment".
722 // TODO(TC): Follow advice at RFC 6266 appendix D
723 disposition += "; filename=" + strconv.QuoteToASCII(filename)
725 if disposition != "inline" {
726 w.Header().Set("Content-Disposition", disposition)
730 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
731 if formToken := r.FormValue("api_token"); formToken != "" {
733 // It is not safe to copy the provided token
734 // into a cookie unless the current vhost
735 // (origin) serves only a single collection or
736 // we are in TrustAllContent mode.
737 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)
741 // The HttpOnly flag is necessary to prevent
742 // JavaScript code (included in, or loaded by, a page
743 // in the collection being served) from employing the
744 // user's token beyond reading other files in the same
745 // domain, i.e., same collection.
747 // The 303 redirect is necessary in the case of a GET
748 // request to avoid exposing the token in the Location
749 // bar, and in the case of a POST request to avoid
750 // raising warnings when the user refreshes the
752 http.SetCookie(w, &http.Cookie{
753 Name: "arvados_api_token",
754 Value: auth.EncodeTokenCookie([]byte(formToken)),
760 // Propagate query parameters (except api_token) from
761 // the original request.
762 redirQuery := r.URL.Query()
763 redirQuery.Del("api_token")
767 newu, err := u.Parse(location)
769 http.Error(w, "error resolving redirect target: "+err.Error(), http.StatusInternalServerError)
775 Scheme: r.URL.Scheme,
778 RawQuery: redirQuery.Encode(),
781 w.Header().Add("Location", redir)
782 w.WriteHeader(http.StatusSeeOther)
783 io.WriteString(w, `<A href="`)
784 io.WriteString(w, html.EscapeString(redir))
785 io.WriteString(w, `">Continue</A>`)