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()
83 h.healthHandler = &health.Handler{
84 Token: h.Config.ManagementToken,
88 // Even though we don't accept LOCK requests, every webdav
89 // handler must have a non-nil LockSystem.
90 h.webdavLS = &noLockSystem{}
93 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
98 cacheStats: h.Config.Cache.Stats(),
101 json.NewEncoder(w).Encode(status)
104 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
105 // sends an HTTP header indicating success, updateOnSuccess first
106 // calls the provided update func. If the update func fails, a 500
107 // response is sent, and the status code and body sent by the handler
108 // are ignored (all response writes return the update error).
109 type updateOnSuccess struct {
110 httpserver.ResponseWriter
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 log.Printf("update() changes response to HTTP %d: %T %q", code, uos.err, uos.err)
136 http.Error(uos.ResponseWriter, uos.err.Error(), code)
141 uos.ResponseWriter.WriteHeader(code)
145 writeMethod = map[string]bool{
153 webdavMethod = map[string]bool{
163 browserMethod = map[string]bool{
168 // top-level dirs to serve with siteFS
169 siteFSDir = map[string]bool{
170 "": true, // root directory
176 // ServeHTTP implements http.Handler.
177 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
178 h.setupOnce.Do(h.setup)
181 var statusText string
183 remoteAddr := r.RemoteAddr
184 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
185 remoteAddr = xff + "," + remoteAddr
187 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
191 w := httpserver.WrapResponseWriter(wOrig)
194 statusCode = w.WroteStatus()
195 } else if w.WroteStatus() == 0 {
196 w.WriteHeader(statusCode)
197 } else if w.WroteStatus() != statusCode {
198 log.WithField("RequestID", r.Header.Get("X-Request-Id")).Warn(
199 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
201 if statusText == "" {
202 statusText = http.StatusText(statusCode)
206 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
207 h.healthHandler.ServeHTTP(w, r)
211 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
212 if !browserMethod[method] && !webdavMethod[method] {
213 statusCode = http.StatusMethodNotAllowed
216 w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Range")
217 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PUT, RMCOL")
218 w.Header().Set("Access-Control-Allow-Origin", "*")
219 w.Header().Set("Access-Control-Max-Age", "86400")
220 statusCode = http.StatusOK
224 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
225 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
229 if r.Header.Get("Origin") != "" {
230 // Allow simple cross-origin requests without user
231 // credentials ("user credentials" as defined by CORS,
232 // i.e., cookies, HTTP authentication, and client-side
233 // SSL certificates. See
234 // http://www.w3.org/TR/cors/#user-credentials).
235 w.Header().Set("Access-Control-Allow-Origin", "*")
236 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
239 pathParts := strings.Split(r.URL.Path[1:], "/")
242 var collectionID string
244 var reqTokens []string
248 credentialsOK := h.Config.TrustAllContent
250 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
253 } else if r.FormValue("disposition") == "attachment" {
257 if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
258 // http://ID.collections.example/PATH...
260 } else if r.URL.Path == "/status.json" {
263 } else if strings.HasPrefix(r.URL.Path, "/metrics") {
264 h.MetricsAPI.ServeHTTP(w, r)
266 } else if siteFSDir[pathParts[0]] {
268 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
270 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
272 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
273 if len(pathParts) >= 4 && pathParts[1] == "download" {
274 // /collections/download/ID/TOKEN/PATH...
275 collectionID = parseCollectionIDFromURL(pathParts[2])
276 tokens = []string{pathParts[3]}
280 // /collections/ID/PATH...
281 collectionID = parseCollectionIDFromURL(pathParts[1])
282 tokens = h.Config.AnonymousTokens
287 if collectionID == "" && !useSiteFS {
288 statusCode = http.StatusNotFound
293 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
297 formToken := r.FormValue("api_token")
298 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
299 // The client provided an explicit token in the POST
300 // body. The Origin header indicates this *might* be
301 // an AJAX request, in which case redirect-with-cookie
302 // won't work: we should just serve the content in the
303 // POST response. This is safe because:
305 // * We're supplying an attachment, not inline
306 // content, so we don't need to convert the POST to
307 // a GET and avoid the "really resubmit form?"
310 // * The token isn't embedded in the URL, so we don't
311 // need to worry about bookmarks and copy/paste.
312 tokens = append(tokens, formToken)
313 } else if formToken != "" && browserMethod[r.Method] {
314 // The client provided an explicit token in the query
315 // string, or a form in POST body. We must put the
316 // token in an HttpOnly cookie, and redirect to the
317 // same URL with the query param redacted and method =
319 h.seeOtherWithCookie(w, r, "", credentialsOK)
325 tokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
327 h.serveSiteFS(w, r, tokens, credentialsOK, attachment)
331 targetPath := pathParts[stripParts:]
332 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
333 // http://ID.example/t=TOKEN/PATH...
334 // /c=ID/t=TOKEN/PATH...
336 // This form must only be used to pass scoped tokens
337 // that give permission for a single collection. See
338 // FormValue case above.
339 tokens = []string{targetPath[0][2:]}
341 targetPath = targetPath[1:]
347 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
349 tokens = append(reqTokens, h.Config.AnonymousTokens...)
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 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
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 statusCode, statusText = http.StatusInternalServerError, err.Error()
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 statusCode = 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 statusCode = 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 statusCode = http.StatusUnauthorized
424 kc, err := keepclient.MakeKeepClient(arv)
426 statusCode, statusText = http.StatusInternalServerError, err.Error()
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 statusCode, statusText = http.StatusInternalServerError, err.Error()
449 writefs, writeOK := fs.(arvados.CollectionFileSystem)
450 targetIsPDH := arvadosclient.PDHMatch(collectionID)
451 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
452 statusCode, statusText = http.StatusMethodNotAllowed, errReadOnly.Error()
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 update: func() error {
465 return h.Config.Cache.Update(client, *collection, writefs)
469 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
470 FileSystem: &webdavFS{
472 writing: writeMethod[r.Method],
473 alwaysReadEOF: r.Method == "PROPFIND",
475 LockSystem: h.webdavLS,
476 Logger: func(_ *http.Request, err error) {
478 log.Printf("error from webdav handler: %q", err)
486 openPath := "/" + strings.Join(targetPath, "/")
487 if f, err := fs.Open(openPath); os.IsNotExist(err) {
488 // Requested non-existent path
489 statusCode = http.StatusNotFound
490 } else if err != nil {
491 // Some other (unexpected) error
492 statusCode, statusText = http.StatusInternalServerError, err.Error()
493 } else if stat, err := f.Stat(); err != nil {
494 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
495 statusCode, statusText = http.StatusInternalServerError, err.Error()
496 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
497 // If client requests ".../dirname", redirect to
498 // ".../dirname/". This way, relative links in the
499 // listing for "dirname" can always be "fnm", never
501 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
502 } else if stat.IsDir() {
503 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
505 http.ServeContent(w, r, basename, stat.ModTime(), f)
506 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
507 // If we wrote fewer bytes than expected, it's
508 // too late to change the real response code
509 // or send an error message to the client, but
510 // at least we can try to put some useful
511 // debugging info in the logs.
512 n, err := f.Read(make([]byte, 1024))
513 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)
519 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
520 if len(tokens) == 0 {
521 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
522 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
525 if writeMethod[r.Method] {
526 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
529 arv := h.clientPool.Get()
531 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
534 defer h.clientPool.Put(arv)
535 arv.ApiToken = tokens[0]
537 kc, err := keepclient.MakeKeepClient(arv)
539 http.Error(w, err.Error(), http.StatusInternalServerError)
542 kc.RequestID = r.Header.Get("X-Request-Id")
543 client := (&arvados.Client{
544 APIHost: arv.ApiServer,
545 AuthToken: arv.ApiToken,
546 Insecure: arv.ApiInsecure,
547 }).WithRequestID(r.Header.Get("X-Request-Id"))
548 fs := client.SiteFileSystem(kc)
549 f, err := fs.Open(r.URL.Path)
550 if os.IsNotExist(err) {
551 http.Error(w, err.Error(), http.StatusNotFound)
553 } else if err != nil {
554 http.Error(w, err.Error(), http.StatusInternalServerError)
558 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
559 if !strings.HasSuffix(r.URL.Path, "/") {
560 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
562 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
566 if r.Method == "GET" {
567 _, basename := filepath.Split(r.URL.Path)
568 applyContentDispositionHdr(w, r, basename, attachment)
570 wh := webdav.Handler{
572 FileSystem: &webdavFS{
574 writing: writeMethod[r.Method],
575 alwaysReadEOF: r.Method == "PROPFIND",
577 LockSystem: h.webdavLS,
578 Logger: func(_ *http.Request, err error) {
580 log.Printf("error from webdav handler: %q", err)
587 var dirListingTemplate = `<!DOCTYPE HTML>
589 <META name="robots" content="NOINDEX">
590 <TITLE>{{ .CollectionName }}</TITLE>
591 <STYLE type="text/css">
596 background-color: #D9EDF7;
597 border-radius: .25em;
608 font-family: monospace;
615 <H1>{{ .CollectionName }}</H1>
617 <P>This collection of data files is being shared with you through
618 Arvados. You can download individual files listed below. To download
619 the entire directory tree with wget, try:</P>
621 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
623 <H2>File Listing</H2>
629 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
631 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
636 <P>(No files; this collection is empty.)</P>
643 Arvados is a free and open source software bioinformatics platform.
644 To learn more, visit arvados.org.
645 Arvados is not responsible for the files listed on this page.
652 type fileListEnt struct {
658 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
659 var files []fileListEnt
660 var walk func(string) error
661 if !strings.HasSuffix(base, "/") {
664 walk = func(path string) error {
665 dirname := base + path
667 dirname = strings.TrimSuffix(dirname, "/")
669 d, err := fs.Open(dirname)
673 ents, err := d.Readdir(-1)
677 for _, ent := range ents {
678 if recurse && ent.IsDir() {
679 err = walk(path + ent.Name() + "/")
684 files = append(files, fileListEnt{
685 Name: path + ent.Name(),
693 if err := walk(""); err != nil {
694 http.Error(w, err.Error(), http.StatusInternalServerError)
698 funcs := template.FuncMap{
699 "nbsp": func(s string) template.HTML {
700 return template.HTML(strings.Replace(s, " ", " ", -1))
703 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
705 http.Error(w, err.Error(), http.StatusInternalServerError)
708 sort.Slice(files, func(i, j int) bool {
709 return files[i].Name < files[j].Name
711 w.WriteHeader(http.StatusOK)
712 tmpl.Execute(w, map[string]interface{}{
713 "CollectionName": collectionName,
716 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
720 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
721 disposition := "inline"
723 disposition = "attachment"
725 if strings.ContainsRune(r.RequestURI, '?') {
726 // Help the UA realize that the filename is just
727 // "filename.txt", not
728 // "filename.txt?disposition=attachment".
730 // TODO(TC): Follow advice at RFC 6266 appendix D
731 disposition += "; filename=" + strconv.QuoteToASCII(filename)
733 if disposition != "inline" {
734 w.Header().Set("Content-Disposition", disposition)
738 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
739 if formToken := r.FormValue("api_token"); formToken != "" {
741 // It is not safe to copy the provided token
742 // into a cookie unless the current vhost
743 // (origin) serves only a single collection or
744 // we are in TrustAllContent mode.
745 w.WriteHeader(http.StatusBadRequest)
749 // The HttpOnly flag is necessary to prevent
750 // JavaScript code (included in, or loaded by, a page
751 // in the collection being served) from employing the
752 // user's token beyond reading other files in the same
753 // domain, i.e., same collection.
755 // The 303 redirect is necessary in the case of a GET
756 // request to avoid exposing the token in the Location
757 // bar, and in the case of a POST request to avoid
758 // raising warnings when the user refreshes the
760 http.SetCookie(w, &http.Cookie{
761 Name: "arvados_api_token",
762 Value: auth.EncodeTokenCookie([]byte(formToken)),
768 // Propagate query parameters (except api_token) from
769 // the original request.
770 redirQuery := r.URL.Query()
771 redirQuery.Del("api_token")
775 newu, err := u.Parse(location)
777 w.WriteHeader(http.StatusInternalServerError)
783 Scheme: r.URL.Scheme,
786 RawQuery: redirQuery.Encode(),
789 w.Header().Add("Location", redir)
790 w.WriteHeader(http.StatusSeeOther)
791 io.WriteString(w, `<A href="`)
792 io.WriteString(w, html.EscapeString(redir))
793 io.WriteString(w, `">Continue</A>`)