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) {
94 json.NewEncoder(w).Encode(struct{ Version string }{version})
97 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
98 // sends an HTTP header indicating success, updateOnSuccess first
99 // calls the provided update func. If the update func fails, a 500
100 // response is sent, and the status code and body sent by the handler
101 // are ignored (all response writes return the update error).
102 type updateOnSuccess struct {
103 httpserver.ResponseWriter
109 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
111 uos.WriteHeader(http.StatusOK)
116 return uos.ResponseWriter.Write(p)
119 func (uos *updateOnSuccess) WriteHeader(code int) {
121 uos.sentHeader = true
122 if code >= 200 && code < 400 {
123 if uos.err = uos.update(); uos.err != nil {
124 code := http.StatusInternalServerError
125 if err, ok := uos.err.(*arvados.TransactionError); ok {
126 code = err.StatusCode
128 log.Printf("update() changes response to HTTP %d: %T %q", code, uos.err, uos.err)
129 http.Error(uos.ResponseWriter, uos.err.Error(), code)
134 uos.ResponseWriter.WriteHeader(code)
138 corsAllowHeadersHeader = strings.Join([]string{
139 "Authorization", "Content-Type", "Range",
140 // WebDAV request headers:
141 "Depth", "Destination", "If", "Lock-Token", "Overwrite", "Timeout",
143 writeMethod = map[string]bool{
154 webdavMethod = map[string]bool{
167 browserMethod = map[string]bool{
172 // top-level dirs to serve with siteFS
173 siteFSDir = map[string]bool{
174 "": true, // root directory
180 // ServeHTTP implements http.Handler.
181 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
182 h.setupOnce.Do(h.setup)
185 var statusText string
187 remoteAddr := r.RemoteAddr
188 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
189 remoteAddr = xff + "," + remoteAddr
191 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
195 w := httpserver.WrapResponseWriter(wOrig)
198 statusCode = w.WroteStatus()
199 } else if w.WroteStatus() == 0 {
200 w.WriteHeader(statusCode)
201 } else if w.WroteStatus() != statusCode {
202 log.WithField("RequestID", r.Header.Get("X-Request-Id")).Warn(
203 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
205 if statusText == "" {
206 statusText = http.StatusText(statusCode)
210 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
211 h.healthHandler.ServeHTTP(w, r)
215 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
216 if !browserMethod[method] && !webdavMethod[method] {
217 statusCode = http.StatusMethodNotAllowed
220 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
221 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
222 w.Header().Set("Access-Control-Allow-Origin", "*")
223 w.Header().Set("Access-Control-Max-Age", "86400")
224 statusCode = http.StatusOK
228 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
229 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
233 if r.Header.Get("Origin") != "" {
234 // Allow simple cross-origin requests without user
235 // credentials ("user credentials" as defined by CORS,
236 // i.e., cookies, HTTP authentication, and client-side
237 // SSL certificates. See
238 // http://www.w3.org/TR/cors/#user-credentials).
239 w.Header().Set("Access-Control-Allow-Origin", "*")
240 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
243 pathParts := strings.Split(r.URL.Path[1:], "/")
246 var collectionID string
248 var reqTokens []string
252 credentialsOK := h.Config.TrustAllContent
254 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
257 } else if r.FormValue("disposition") == "attachment" {
261 if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
262 // http://ID.collections.example/PATH...
264 } else if r.URL.Path == "/status.json" {
267 } else if strings.HasPrefix(r.URL.Path, "/metrics") {
268 h.MetricsAPI.ServeHTTP(w, r)
270 } else if siteFSDir[pathParts[0]] {
272 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
274 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
276 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
277 if len(pathParts) >= 4 && pathParts[1] == "download" {
278 // /collections/download/ID/TOKEN/PATH...
279 collectionID = parseCollectionIDFromURL(pathParts[2])
280 tokens = []string{pathParts[3]}
284 // /collections/ID/PATH...
285 collectionID = parseCollectionIDFromURL(pathParts[1])
286 tokens = h.Config.AnonymousTokens
291 if collectionID == "" && !useSiteFS {
292 statusCode = http.StatusNotFound
297 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
301 formToken := r.FormValue("api_token")
302 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
303 // The client provided an explicit token in the POST
304 // body. The Origin header indicates this *might* be
305 // an AJAX request, in which case redirect-with-cookie
306 // won't work: we should just serve the content in the
307 // POST response. This is safe because:
309 // * We're supplying an attachment, not inline
310 // content, so we don't need to convert the POST to
311 // a GET and avoid the "really resubmit form?"
314 // * The token isn't embedded in the URL, so we don't
315 // need to worry about bookmarks and copy/paste.
316 tokens = append(tokens, formToken)
317 } else if formToken != "" && browserMethod[r.Method] {
318 // The client provided an explicit token in the query
319 // string, or a form in POST body. We must put the
320 // token in an HttpOnly cookie, and redirect to the
321 // same URL with the query param redacted and method =
323 h.seeOtherWithCookie(w, r, "", credentialsOK)
329 tokens = auth.CredentialsFromRequest(r).Tokens
331 h.serveSiteFS(w, r, tokens, credentialsOK, attachment)
335 targetPath := pathParts[stripParts:]
336 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
337 // http://ID.example/t=TOKEN/PATH...
338 // /c=ID/t=TOKEN/PATH...
340 // This form must only be used to pass scoped tokens
341 // that give permission for a single collection. See
342 // FormValue case above.
343 tokens = []string{targetPath[0][2:]}
345 targetPath = targetPath[1:]
351 reqTokens = auth.CredentialsFromRequest(r).Tokens
353 tokens = append(reqTokens, h.Config.AnonymousTokens...)
356 if len(targetPath) > 0 && targetPath[0] == "_" {
357 // If a collection has a directory called "t=foo" or
358 // "_", it can be served at
359 // //collections.example/_/t=foo/ or
360 // //collections.example/_/_/ respectively:
361 // //collections.example/t=foo/ won't work because
362 // t=foo will be interpreted as a token "foo".
363 targetPath = targetPath[1:]
367 arv := h.clientPool.Get()
369 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
372 defer h.clientPool.Put(arv)
374 var collection *arvados.Collection
375 tokenResult := make(map[string]int)
376 for _, arv.ApiToken = range tokens {
378 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
383 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
384 switch srvErr.HttpStatusCode {
386 // Token broken or insufficient to
387 // retrieve collection
388 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
392 // Something more serious is wrong
393 statusCode, statusText = http.StatusInternalServerError, err.Error()
396 if collection == nil {
397 if pathToken || !credentialsOK {
398 // Either the URL is a "secret sharing link"
399 // that didn't work out (and asking the client
400 // for additional credentials would just be
401 // confusing), or we don't even accept
402 // credentials at this path.
403 statusCode = http.StatusNotFound
406 for _, t := range reqTokens {
407 if tokenResult[t] == 404 {
408 // The client provided valid token(s), but the
409 // collection was not found.
410 statusCode = http.StatusNotFound
414 // The client's token was invalid (e.g., expired), or
415 // the client didn't even provide one. Propagate the
416 // 401 to encourage the client to use a [different]
419 // TODO(TC): This response would be confusing to
420 // someone trying (anonymously) to download public
421 // data that has been deleted. Allow a referrer to
422 // provide this context somehow?
423 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
424 statusCode = http.StatusUnauthorized
428 kc, err := keepclient.MakeKeepClient(arv)
430 statusCode, statusText = http.StatusInternalServerError, err.Error()
433 kc.RequestID = r.Header.Get("X-Request-Id")
436 if len(targetPath) > 0 {
437 basename = targetPath[len(targetPath)-1]
439 applyContentDispositionHdr(w, r, basename, attachment)
441 client := (&arvados.Client{
442 APIHost: arv.ApiServer,
443 AuthToken: arv.ApiToken,
444 Insecure: arv.ApiInsecure,
445 }).WithRequestID(r.Header.Get("X-Request-Id"))
447 fs, err := collection.FileSystem(client, kc)
449 statusCode, statusText = http.StatusInternalServerError, err.Error()
453 writefs, writeOK := fs.(arvados.CollectionFileSystem)
454 targetIsPDH := arvadosclient.PDHMatch(collectionID)
455 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
456 statusCode, statusText = http.StatusMethodNotAllowed, errReadOnly.Error()
460 if webdavMethod[r.Method] {
461 if writeMethod[r.Method] {
462 // Save the collection only if/when all
463 // webdav->filesystem operations succeed --
464 // and send a 500 error if the modified
465 // collection can't be saved.
466 w = &updateOnSuccess{
468 update: func() error {
469 return h.Config.Cache.Update(client, *collection, writefs)
473 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
474 FileSystem: &webdavFS{
476 writing: writeMethod[r.Method],
477 alwaysReadEOF: r.Method == "PROPFIND",
479 LockSystem: h.webdavLS,
480 Logger: func(_ *http.Request, err error) {
482 log.Printf("error from webdav handler: %q", err)
490 openPath := "/" + strings.Join(targetPath, "/")
491 if f, err := fs.Open(openPath); os.IsNotExist(err) {
492 // Requested non-existent path
493 statusCode = http.StatusNotFound
494 } else if err != nil {
495 // Some other (unexpected) error
496 statusCode, statusText = http.StatusInternalServerError, err.Error()
497 } else if stat, err := f.Stat(); err != nil {
498 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
499 statusCode, statusText = http.StatusInternalServerError, err.Error()
500 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
501 // If client requests ".../dirname", redirect to
502 // ".../dirname/". This way, relative links in the
503 // listing for "dirname" can always be "fnm", never
505 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
506 } else if stat.IsDir() {
507 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
509 http.ServeContent(w, r, basename, stat.ModTime(), f)
510 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
511 // If we wrote fewer bytes than expected, it's
512 // too late to change the real response code
513 // or send an error message to the client, but
514 // at least we can try to put some useful
515 // debugging info in the logs.
516 n, err := f.Read(make([]byte, 1024))
517 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)
523 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
524 if len(tokens) == 0 {
525 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
526 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
529 if writeMethod[r.Method] {
530 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
533 arv := h.clientPool.Get()
535 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
538 defer h.clientPool.Put(arv)
539 arv.ApiToken = tokens[0]
541 kc, err := keepclient.MakeKeepClient(arv)
543 http.Error(w, err.Error(), http.StatusInternalServerError)
546 kc.RequestID = r.Header.Get("X-Request-Id")
547 client := (&arvados.Client{
548 APIHost: arv.ApiServer,
549 AuthToken: arv.ApiToken,
550 Insecure: arv.ApiInsecure,
551 }).WithRequestID(r.Header.Get("X-Request-Id"))
552 fs := client.SiteFileSystem(kc)
553 f, err := fs.Open(r.URL.Path)
554 if os.IsNotExist(err) {
555 http.Error(w, err.Error(), http.StatusNotFound)
557 } else if err != nil {
558 http.Error(w, err.Error(), http.StatusInternalServerError)
562 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
563 if !strings.HasSuffix(r.URL.Path, "/") {
564 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
566 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
570 if r.Method == "GET" {
571 _, basename := filepath.Split(r.URL.Path)
572 applyContentDispositionHdr(w, r, basename, attachment)
574 wh := webdav.Handler{
576 FileSystem: &webdavFS{
578 writing: writeMethod[r.Method],
579 alwaysReadEOF: r.Method == "PROPFIND",
581 LockSystem: h.webdavLS,
582 Logger: func(_ *http.Request, err error) {
584 log.Printf("error from webdav handler: %q", err)
591 var dirListingTemplate = `<!DOCTYPE HTML>
593 <META name="robots" content="NOINDEX">
594 <TITLE>{{ .CollectionName }}</TITLE>
595 <STYLE type="text/css">
600 background-color: #D9EDF7;
601 border-radius: .25em;
612 font-family: monospace;
619 <H1>{{ .CollectionName }}</H1>
621 <P>This collection of data files is being shared with you through
622 Arvados. You can download individual files listed below. To download
623 the entire directory tree with wget, try:</P>
625 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
627 <H2>File Listing</H2>
633 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
635 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
640 <P>(No files; this collection is empty.)</P>
647 Arvados is a free and open source software bioinformatics platform.
648 To learn more, visit arvados.org.
649 Arvados is not responsible for the files listed on this page.
656 type fileListEnt struct {
662 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
663 var files []fileListEnt
664 var walk func(string) error
665 if !strings.HasSuffix(base, "/") {
668 walk = func(path string) error {
669 dirname := base + path
671 dirname = strings.TrimSuffix(dirname, "/")
673 d, err := fs.Open(dirname)
677 ents, err := d.Readdir(-1)
681 for _, ent := range ents {
682 if recurse && ent.IsDir() {
683 err = walk(path + ent.Name() + "/")
688 files = append(files, fileListEnt{
689 Name: path + ent.Name(),
697 if err := walk(""); err != nil {
698 http.Error(w, err.Error(), http.StatusInternalServerError)
702 funcs := template.FuncMap{
703 "nbsp": func(s string) template.HTML {
704 return template.HTML(strings.Replace(s, " ", " ", -1))
707 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
709 http.Error(w, err.Error(), http.StatusInternalServerError)
712 sort.Slice(files, func(i, j int) bool {
713 return files[i].Name < files[j].Name
715 w.WriteHeader(http.StatusOK)
716 tmpl.Execute(w, map[string]interface{}{
717 "CollectionName": collectionName,
720 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
724 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
725 disposition := "inline"
727 disposition = "attachment"
729 if strings.ContainsRune(r.RequestURI, '?') {
730 // Help the UA realize that the filename is just
731 // "filename.txt", not
732 // "filename.txt?disposition=attachment".
734 // TODO(TC): Follow advice at RFC 6266 appendix D
735 disposition += "; filename=" + strconv.QuoteToASCII(filename)
737 if disposition != "inline" {
738 w.Header().Set("Content-Disposition", disposition)
742 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
743 if formToken := r.FormValue("api_token"); formToken != "" {
745 // It is not safe to copy the provided token
746 // into a cookie unless the current vhost
747 // (origin) serves only a single collection or
748 // we are in TrustAllContent mode.
749 w.WriteHeader(http.StatusBadRequest)
753 // The HttpOnly flag is necessary to prevent
754 // JavaScript code (included in, or loaded by, a page
755 // in the collection being served) from employing the
756 // user's token beyond reading other files in the same
757 // domain, i.e., same collection.
759 // The 303 redirect is necessary in the case of a GET
760 // request to avoid exposing the token in the Location
761 // bar, and in the case of a POST request to avoid
762 // raising warnings when the user refreshes the
764 http.SetCookie(w, &http.Cookie{
765 Name: "arvados_api_token",
766 Value: auth.EncodeTokenCookie([]byte(formToken)),
772 // Propagate query parameters (except api_token) from
773 // the original request.
774 redirQuery := r.URL.Query()
775 redirQuery.Del("api_token")
779 newu, err := u.Parse(location)
781 w.WriteHeader(http.StatusInternalServerError)
787 Scheme: r.URL.Scheme,
790 RawQuery: redirQuery.Encode(),
793 w.Header().Add("Location", redir)
794 w.WriteHeader(http.StatusSeeOther)
795 io.WriteString(w, `<A href="`)
796 io.WriteString(w, html.EscapeString(redir))
797 io.WriteString(w, `">Continue</A>`)