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{
153 webdavMethod = map[string]bool{
165 browserMethod = map[string]bool{
170 // top-level dirs to serve with siteFS
171 siteFSDir = map[string]bool{
172 "": true, // root directory
178 // ServeHTTP implements http.Handler.
179 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
180 h.setupOnce.Do(h.setup)
183 var statusText string
185 remoteAddr := r.RemoteAddr
186 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
187 remoteAddr = xff + "," + remoteAddr
189 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
193 w := httpserver.WrapResponseWriter(wOrig)
196 statusCode = w.WroteStatus()
197 } else if w.WroteStatus() == 0 {
198 w.WriteHeader(statusCode)
199 } else if w.WroteStatus() != statusCode {
200 log.WithField("RequestID", r.Header.Get("X-Request-Id")).Warn(
201 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
203 if statusText == "" {
204 statusText = http.StatusText(statusCode)
208 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
209 h.healthHandler.ServeHTTP(w, r)
213 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
214 if !browserMethod[method] && !webdavMethod[method] {
215 statusCode = http.StatusMethodNotAllowed
218 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
219 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PUT, RMCOL")
220 w.Header().Set("Access-Control-Allow-Origin", "*")
221 w.Header().Set("Access-Control-Max-Age", "86400")
222 statusCode = http.StatusOK
226 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
227 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
231 if r.Header.Get("Origin") != "" {
232 // Allow simple cross-origin requests without user
233 // credentials ("user credentials" as defined by CORS,
234 // i.e., cookies, HTTP authentication, and client-side
235 // SSL certificates. See
236 // http://www.w3.org/TR/cors/#user-credentials).
237 w.Header().Set("Access-Control-Allow-Origin", "*")
238 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
241 pathParts := strings.Split(r.URL.Path[1:], "/")
244 var collectionID string
246 var reqTokens []string
250 credentialsOK := h.Config.TrustAllContent
252 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
255 } else if r.FormValue("disposition") == "attachment" {
259 if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
260 // http://ID.collections.example/PATH...
262 } else if r.URL.Path == "/status.json" {
265 } else if strings.HasPrefix(r.URL.Path, "/metrics") {
266 h.MetricsAPI.ServeHTTP(w, r)
268 } else if siteFSDir[pathParts[0]] {
270 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
272 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
274 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
275 if len(pathParts) >= 4 && pathParts[1] == "download" {
276 // /collections/download/ID/TOKEN/PATH...
277 collectionID = parseCollectionIDFromURL(pathParts[2])
278 tokens = []string{pathParts[3]}
282 // /collections/ID/PATH...
283 collectionID = parseCollectionIDFromURL(pathParts[1])
284 tokens = h.Config.AnonymousTokens
289 if collectionID == "" && !useSiteFS {
290 statusCode = http.StatusNotFound
295 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
299 formToken := r.FormValue("api_token")
300 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
301 // The client provided an explicit token in the POST
302 // body. The Origin header indicates this *might* be
303 // an AJAX request, in which case redirect-with-cookie
304 // won't work: we should just serve the content in the
305 // POST response. This is safe because:
307 // * We're supplying an attachment, not inline
308 // content, so we don't need to convert the POST to
309 // a GET and avoid the "really resubmit form?"
312 // * The token isn't embedded in the URL, so we don't
313 // need to worry about bookmarks and copy/paste.
314 tokens = append(tokens, formToken)
315 } else if formToken != "" && browserMethod[r.Method] {
316 // The client provided an explicit token in the query
317 // string, or a form in POST body. We must put the
318 // token in an HttpOnly cookie, and redirect to the
319 // same URL with the query param redacted and method =
321 h.seeOtherWithCookie(w, r, "", credentialsOK)
327 tokens = auth.CredentialsFromRequest(r).Tokens
329 h.serveSiteFS(w, r, tokens, credentialsOK, attachment)
333 targetPath := pathParts[stripParts:]
334 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
335 // http://ID.example/t=TOKEN/PATH...
336 // /c=ID/t=TOKEN/PATH...
338 // This form must only be used to pass scoped tokens
339 // that give permission for a single collection. See
340 // FormValue case above.
341 tokens = []string{targetPath[0][2:]}
343 targetPath = targetPath[1:]
349 reqTokens = auth.CredentialsFromRequest(r).Tokens
351 tokens = append(reqTokens, h.Config.AnonymousTokens...)
354 if len(targetPath) > 0 && targetPath[0] == "_" {
355 // If a collection has a directory called "t=foo" or
356 // "_", it can be served at
357 // //collections.example/_/t=foo/ or
358 // //collections.example/_/_/ respectively:
359 // //collections.example/t=foo/ won't work because
360 // t=foo will be interpreted as a token "foo".
361 targetPath = targetPath[1:]
365 arv := h.clientPool.Get()
367 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
370 defer h.clientPool.Put(arv)
372 var collection *arvados.Collection
373 tokenResult := make(map[string]int)
374 for _, arv.ApiToken = range tokens {
376 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
381 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
382 switch srvErr.HttpStatusCode {
384 // Token broken or insufficient to
385 // retrieve collection
386 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
390 // Something more serious is wrong
391 statusCode, statusText = http.StatusInternalServerError, err.Error()
394 if collection == nil {
395 if pathToken || !credentialsOK {
396 // Either the URL is a "secret sharing link"
397 // that didn't work out (and asking the client
398 // for additional credentials would just be
399 // confusing), or we don't even accept
400 // credentials at this path.
401 statusCode = http.StatusNotFound
404 for _, t := range reqTokens {
405 if tokenResult[t] == 404 {
406 // The client provided valid token(s), but the
407 // collection was not found.
408 statusCode = http.StatusNotFound
412 // The client's token was invalid (e.g., expired), or
413 // the client didn't even provide one. Propagate the
414 // 401 to encourage the client to use a [different]
417 // TODO(TC): This response would be confusing to
418 // someone trying (anonymously) to download public
419 // data that has been deleted. Allow a referrer to
420 // provide this context somehow?
421 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
422 statusCode = http.StatusUnauthorized
426 kc, err := keepclient.MakeKeepClient(arv)
428 statusCode, statusText = http.StatusInternalServerError, err.Error()
431 kc.RequestID = r.Header.Get("X-Request-Id")
434 if len(targetPath) > 0 {
435 basename = targetPath[len(targetPath)-1]
437 applyContentDispositionHdr(w, r, basename, attachment)
439 client := (&arvados.Client{
440 APIHost: arv.ApiServer,
441 AuthToken: arv.ApiToken,
442 Insecure: arv.ApiInsecure,
443 }).WithRequestID(r.Header.Get("X-Request-Id"))
445 fs, err := collection.FileSystem(client, kc)
447 statusCode, statusText = http.StatusInternalServerError, err.Error()
451 writefs, writeOK := fs.(arvados.CollectionFileSystem)
452 targetIsPDH := arvadosclient.PDHMatch(collectionID)
453 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
454 statusCode, statusText = http.StatusMethodNotAllowed, errReadOnly.Error()
458 if webdavMethod[r.Method] {
459 if writeMethod[r.Method] {
460 // Save the collection only if/when all
461 // webdav->filesystem operations succeed --
462 // and send a 500 error if the modified
463 // collection can't be saved.
464 w = &updateOnSuccess{
466 update: func() error {
467 return h.Config.Cache.Update(client, *collection, writefs)
471 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
472 FileSystem: &webdavFS{
474 writing: writeMethod[r.Method],
475 alwaysReadEOF: r.Method == "PROPFIND",
477 LockSystem: h.webdavLS,
478 Logger: func(_ *http.Request, err error) {
480 log.Printf("error from webdav handler: %q", err)
488 openPath := "/" + strings.Join(targetPath, "/")
489 if f, err := fs.Open(openPath); os.IsNotExist(err) {
490 // Requested non-existent path
491 statusCode = http.StatusNotFound
492 } else if err != nil {
493 // Some other (unexpected) error
494 statusCode, statusText = http.StatusInternalServerError, err.Error()
495 } else if stat, err := f.Stat(); err != nil {
496 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
497 statusCode, statusText = http.StatusInternalServerError, err.Error()
498 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
499 // If client requests ".../dirname", redirect to
500 // ".../dirname/". This way, relative links in the
501 // listing for "dirname" can always be "fnm", never
503 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
504 } else if stat.IsDir() {
505 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
507 http.ServeContent(w, r, basename, stat.ModTime(), f)
508 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
509 // If we wrote fewer bytes than expected, it's
510 // too late to change the real response code
511 // or send an error message to the client, but
512 // at least we can try to put some useful
513 // debugging info in the logs.
514 n, err := f.Read(make([]byte, 1024))
515 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)
521 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
522 if len(tokens) == 0 {
523 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
524 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
527 if writeMethod[r.Method] {
528 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
531 arv := h.clientPool.Get()
533 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
536 defer h.clientPool.Put(arv)
537 arv.ApiToken = tokens[0]
539 kc, err := keepclient.MakeKeepClient(arv)
541 http.Error(w, err.Error(), http.StatusInternalServerError)
544 kc.RequestID = r.Header.Get("X-Request-Id")
545 client := (&arvados.Client{
546 APIHost: arv.ApiServer,
547 AuthToken: arv.ApiToken,
548 Insecure: arv.ApiInsecure,
549 }).WithRequestID(r.Header.Get("X-Request-Id"))
550 fs := client.SiteFileSystem(kc)
551 f, err := fs.Open(r.URL.Path)
552 if os.IsNotExist(err) {
553 http.Error(w, err.Error(), http.StatusNotFound)
555 } else if err != nil {
556 http.Error(w, err.Error(), http.StatusInternalServerError)
560 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
561 if !strings.HasSuffix(r.URL.Path, "/") {
562 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
564 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
568 if r.Method == "GET" {
569 _, basename := filepath.Split(r.URL.Path)
570 applyContentDispositionHdr(w, r, basename, attachment)
572 wh := webdav.Handler{
574 FileSystem: &webdavFS{
576 writing: writeMethod[r.Method],
577 alwaysReadEOF: r.Method == "PROPFIND",
579 LockSystem: h.webdavLS,
580 Logger: func(_ *http.Request, err error) {
582 log.Printf("error from webdav handler: %q", err)
589 var dirListingTemplate = `<!DOCTYPE HTML>
591 <META name="robots" content="NOINDEX">
592 <TITLE>{{ .CollectionName }}</TITLE>
593 <STYLE type="text/css">
598 background-color: #D9EDF7;
599 border-radius: .25em;
610 font-family: monospace;
617 <H1>{{ .CollectionName }}</H1>
619 <P>This collection of data files is being shared with you through
620 Arvados. You can download individual files listed below. To download
621 the entire directory tree with wget, try:</P>
623 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
625 <H2>File Listing</H2>
631 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
633 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
638 <P>(No files; this collection is empty.)</P>
645 Arvados is a free and open source software bioinformatics platform.
646 To learn more, visit arvados.org.
647 Arvados is not responsible for the files listed on this page.
654 type fileListEnt struct {
660 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
661 var files []fileListEnt
662 var walk func(string) error
663 if !strings.HasSuffix(base, "/") {
666 walk = func(path string) error {
667 dirname := base + path
669 dirname = strings.TrimSuffix(dirname, "/")
671 d, err := fs.Open(dirname)
675 ents, err := d.Readdir(-1)
679 for _, ent := range ents {
680 if recurse && ent.IsDir() {
681 err = walk(path + ent.Name() + "/")
686 files = append(files, fileListEnt{
687 Name: path + ent.Name(),
695 if err := walk(""); err != nil {
696 http.Error(w, err.Error(), http.StatusInternalServerError)
700 funcs := template.FuncMap{
701 "nbsp": func(s string) template.HTML {
702 return template.HTML(strings.Replace(s, " ", " ", -1))
705 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
707 http.Error(w, err.Error(), http.StatusInternalServerError)
710 sort.Slice(files, func(i, j int) bool {
711 return files[i].Name < files[j].Name
713 w.WriteHeader(http.StatusOK)
714 tmpl.Execute(w, map[string]interface{}{
715 "CollectionName": collectionName,
718 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
722 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
723 disposition := "inline"
725 disposition = "attachment"
727 if strings.ContainsRune(r.RequestURI, '?') {
728 // Help the UA realize that the filename is just
729 // "filename.txt", not
730 // "filename.txt?disposition=attachment".
732 // TODO(TC): Follow advice at RFC 6266 appendix D
733 disposition += "; filename=" + strconv.QuoteToASCII(filename)
735 if disposition != "inline" {
736 w.Header().Set("Content-Disposition", disposition)
740 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
741 if formToken := r.FormValue("api_token"); formToken != "" {
743 // It is not safe to copy the provided token
744 // into a cookie unless the current vhost
745 // (origin) serves only a single collection or
746 // we are in TrustAllContent mode.
747 w.WriteHeader(http.StatusBadRequest)
751 // The HttpOnly flag is necessary to prevent
752 // JavaScript code (included in, or loaded by, a page
753 // in the collection being served) from employing the
754 // user's token beyond reading other files in the same
755 // domain, i.e., same collection.
757 // The 303 redirect is necessary in the case of a GET
758 // request to avoid exposing the token in the Location
759 // bar, and in the case of a POST request to avoid
760 // raising warnings when the user refreshes the
762 http.SetCookie(w, &http.Cookie{
763 Name: "arvados_api_token",
764 Value: auth.EncodeTokenCookie([]byte(formToken)),
770 // Propagate query parameters (except api_token) from
771 // the original request.
772 redirQuery := r.URL.Query()
773 redirQuery.Del("api_token")
777 newu, err := u.Parse(location)
779 w.WriteHeader(http.StatusInternalServerError)
785 Scheme: r.URL.Scheme,
788 RawQuery: redirQuery.Encode(),
791 w.Header().Add("Location", redir)
792 w.WriteHeader(http.StatusSeeOther)
793 io.WriteString(w, `<A href="`)
794 io.WriteString(w, html.EscapeString(redir))
795 io.WriteString(w, `">Continue</A>`)