1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "git.curoverse.com/arvados.git/sdk/go/arvados"
23 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
24 "git.curoverse.com/arvados.git/sdk/go/auth"
25 "git.curoverse.com/arvados.git/sdk/go/health"
26 "git.curoverse.com/arvados.git/sdk/go/httpserver"
27 "git.curoverse.com/arvados.git/sdk/go/keepclient"
28 log "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
110 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
112 uos.WriteHeader(http.StatusOK)
117 return uos.ResponseWriter.Write(p)
120 func (uos *updateOnSuccess) WriteHeader(code int) {
122 uos.sentHeader = true
123 if code >= 200 && code < 400 {
124 if uos.err = uos.update(); uos.err != nil {
125 code := http.StatusInternalServerError
126 if err, ok := uos.err.(*arvados.TransactionError); ok {
127 code = err.StatusCode
129 log.Printf("update() changes response to HTTP %d: %T %q", code, uos.err, uos.err)
130 http.Error(uos.ResponseWriter, uos.err.Error(), code)
135 uos.ResponseWriter.WriteHeader(code)
139 corsAllowHeadersHeader = strings.Join([]string{
140 "Authorization", "Content-Type", "Range",
141 // WebDAV request headers:
142 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout",
144 writeMethod = map[string]bool{
155 webdavMethod = map[string]bool{
168 browserMethod = map[string]bool{
173 // top-level dirs to serve with siteFS
174 siteFSDir = map[string]bool{
175 "": true, // root directory
181 // ServeHTTP implements http.Handler.
182 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
183 h.setupOnce.Do(h.setup)
186 var statusText string
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)
199 statusCode = w.WroteStatus()
200 } else if w.WroteStatus() == 0 {
201 w.WriteHeader(statusCode)
202 } else if w.WroteStatus() != statusCode {
203 log.WithField("RequestID", r.Header.Get("X-Request-Id")).Warn(
204 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
206 if statusText == "" {
207 statusText = http.StatusText(statusCode)
211 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
212 h.healthHandler.ServeHTTP(w, r)
216 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
217 if !browserMethod[method] && !webdavMethod[method] {
218 statusCode = http.StatusMethodNotAllowed
221 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
222 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
223 w.Header().Set("Access-Control-Allow-Origin", "*")
224 w.Header().Set("Access-Control-Max-Age", "86400")
225 statusCode = http.StatusOK
229 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
230 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
234 if r.Header.Get("Origin") != "" {
235 // Allow simple cross-origin requests without user
236 // credentials ("user credentials" as defined by CORS,
237 // i.e., cookies, HTTP authentication, and client-side
238 // SSL certificates. See
239 // http://www.w3.org/TR/cors/#user-credentials).
240 w.Header().Set("Access-Control-Allow-Origin", "*")
241 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
244 pathParts := strings.Split(r.URL.Path[1:], "/")
247 var collectionID string
249 var reqTokens []string
253 credentialsOK := h.Config.cluster.Collections.TrustAllContent
255 if r.Host != "" && r.Host == h.Config.cluster.Services.WebDAVDownload.ExternalURL.Host {
258 } else if r.FormValue("disposition") == "attachment" {
262 if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
263 // http://ID.collections.example/PATH...
265 } else if r.URL.Path == "/status.json" {
268 } else if strings.HasPrefix(r.URL.Path, "/metrics") {
269 h.MetricsAPI.ServeHTTP(w, r)
271 } else if siteFSDir[pathParts[0]] {
273 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
275 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
277 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
278 if len(pathParts) >= 4 && pathParts[1] == "download" {
279 // /collections/download/ID/TOKEN/PATH...
280 collectionID = parseCollectionIDFromURL(pathParts[2])
281 tokens = []string{pathParts[3]}
285 // /collections/ID/PATH...
286 collectionID = parseCollectionIDFromURL(pathParts[1])
288 // This path is only meant to work for public
289 // data. Tokens provided with the request are
291 credentialsOK = false
295 if collectionID == "" && !useSiteFS {
296 statusCode = http.StatusNotFound
301 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
306 reqTokens = auth.CredentialsFromRequest(r).Tokens
309 formToken := r.FormValue("api_token")
310 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
311 // The client provided an explicit token in the POST
312 // body. The Origin header indicates this *might* be
313 // an AJAX request, in which case redirect-with-cookie
314 // won't work: we should just serve the content in the
315 // POST response. This is safe because:
317 // * We're supplying an attachment, not inline
318 // content, so we don't need to convert the POST to
319 // a GET and avoid the "really resubmit form?"
322 // * The token isn't embedded in the URL, so we don't
323 // need to worry about bookmarks and copy/paste.
324 reqTokens = append(reqTokens, formToken)
325 } else if formToken != "" && browserMethod[r.Method] {
326 // The client provided an explicit token in the query
327 // string, or a form in POST body. We must put the
328 // token in an HttpOnly cookie, and redirect to the
329 // same URL with the query param redacted and method =
331 h.seeOtherWithCookie(w, r, "", credentialsOK)
336 h.serveSiteFS(w, r, reqTokens, credentialsOK, attachment)
340 targetPath := pathParts[stripParts:]
341 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
342 // http://ID.example/t=TOKEN/PATH...
343 // /c=ID/t=TOKEN/PATH...
345 // This form must only be used to pass scoped tokens
346 // that give permission for a single collection. See
347 // FormValue case above.
348 tokens = []string{targetPath[0][2:]}
350 targetPath = targetPath[1:]
355 tokens = append(reqTokens, h.Config.cluster.Users.AnonymousUserToken)
358 if len(targetPath) > 0 && targetPath[0] == "_" {
359 // If a collection has a directory called "t=foo" or
360 // "_", it can be served at
361 // //collections.example/_/t=foo/ or
362 // //collections.example/_/_/ respectively:
363 // //collections.example/t=foo/ won't work because
364 // t=foo will be interpreted as a token "foo".
365 targetPath = targetPath[1:]
369 arv := h.clientPool.Get()
371 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
374 defer h.clientPool.Put(arv)
376 var collection *arvados.Collection
377 tokenResult := make(map[string]int)
378 for _, arv.ApiToken = range tokens {
380 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
385 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
386 switch srvErr.HttpStatusCode {
388 // Token broken or insufficient to
389 // retrieve collection
390 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
394 // Something more serious is wrong
395 statusCode, statusText = http.StatusInternalServerError, err.Error()
398 if collection == nil {
399 if pathToken || !credentialsOK {
400 // Either the URL is a "secret sharing link"
401 // that didn't work out (and asking the client
402 // for additional credentials would just be
403 // confusing), or we don't even accept
404 // credentials at this path.
405 statusCode = http.StatusNotFound
408 for _, t := range reqTokens {
409 if tokenResult[t] == 404 {
410 // The client provided valid token(s), but the
411 // collection was not found.
412 statusCode = http.StatusNotFound
416 // The client's token was invalid (e.g., expired), or
417 // the client didn't even provide one. Propagate the
418 // 401 to encourage the client to use a [different]
421 // TODO(TC): This response would be confusing to
422 // someone trying (anonymously) to download public
423 // data that has been deleted. Allow a referrer to
424 // provide this context somehow?
425 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
426 statusCode = http.StatusUnauthorized
430 kc, err := keepclient.MakeKeepClient(arv)
432 statusCode, statusText = http.StatusInternalServerError, err.Error()
435 kc.RequestID = r.Header.Get("X-Request-Id")
438 if len(targetPath) > 0 {
439 basename = targetPath[len(targetPath)-1]
441 applyContentDispositionHdr(w, r, basename, attachment)
443 client := (&arvados.Client{
444 APIHost: arv.ApiServer,
445 AuthToken: arv.ApiToken,
446 Insecure: arv.ApiInsecure,
447 }).WithRequestID(r.Header.Get("X-Request-Id"))
449 fs, err := collection.FileSystem(client, kc)
451 statusCode, statusText = http.StatusInternalServerError, err.Error()
455 writefs, writeOK := fs.(arvados.CollectionFileSystem)
456 targetIsPDH := arvadosclient.PDHMatch(collectionID)
457 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
458 statusCode, statusText = http.StatusMethodNotAllowed, errReadOnly.Error()
462 if webdavMethod[r.Method] {
463 if writeMethod[r.Method] {
464 // Save the collection only if/when all
465 // webdav->filesystem operations succeed --
466 // and send a 500 error if the modified
467 // collection can't be saved.
468 w = &updateOnSuccess{
470 update: func() error {
471 return h.Config.Cache.Update(client, *collection, writefs)
475 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
476 FileSystem: &webdavFS{
478 writing: writeMethod[r.Method],
479 alwaysReadEOF: r.Method == "PROPFIND",
481 LockSystem: h.webdavLS,
482 Logger: func(_ *http.Request, err error) {
484 log.Printf("error from webdav handler: %q", err)
492 openPath := "/" + strings.Join(targetPath, "/")
493 if f, err := fs.Open(openPath); os.IsNotExist(err) {
494 // Requested non-existent path
495 statusCode = http.StatusNotFound
496 } else if err != nil {
497 // Some other (unexpected) error
498 statusCode, statusText = http.StatusInternalServerError, err.Error()
499 } else if stat, err := f.Stat(); err != nil {
500 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
501 statusCode, statusText = http.StatusInternalServerError, err.Error()
502 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
503 // If client requests ".../dirname", redirect to
504 // ".../dirname/". This way, relative links in the
505 // listing for "dirname" can always be "fnm", never
507 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
508 } else if stat.IsDir() {
509 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
511 http.ServeContent(w, r, basename, stat.ModTime(), f)
512 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
513 // If we wrote fewer bytes than expected, it's
514 // too late to change the real response code
515 // or send an error message to the client, but
516 // at least we can try to put some useful
517 // debugging info in the logs.
518 n, err := f.Read(make([]byte, 1024))
519 statusCode, statusText = http.StatusInternalServerError, fmt.Sprintf("f.Size()==%d but only wrote %d bytes; read(1024) returns %d, %s", stat.Size(), w.WroteBodyBytes(), n, err)
525 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
526 if len(tokens) == 0 {
527 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
528 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
531 if writeMethod[r.Method] {
532 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
535 arv := h.clientPool.Get()
537 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
540 defer h.clientPool.Put(arv)
541 arv.ApiToken = tokens[0]
543 kc, err := keepclient.MakeKeepClient(arv)
545 http.Error(w, err.Error(), http.StatusInternalServerError)
548 kc.RequestID = r.Header.Get("X-Request-Id")
549 client := (&arvados.Client{
550 APIHost: arv.ApiServer,
551 AuthToken: arv.ApiToken,
552 Insecure: arv.ApiInsecure,
553 }).WithRequestID(r.Header.Get("X-Request-Id"))
554 fs := client.SiteFileSystem(kc)
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 log.Printf("error from webdav handler: %q", err)
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, 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, 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 w.WriteHeader(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 w.WriteHeader(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>`)