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])
287 // This path is only meant to work for public
288 // data. Tokens provided with the request are
290 credentialsOK = false
294 if collectionID == "" && !useSiteFS {
295 statusCode = http.StatusNotFound
300 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
305 reqTokens = auth.CredentialsFromRequest(r).Tokens
308 formToken := r.FormValue("api_token")
309 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
310 // The client provided an explicit token in the POST
311 // body. The Origin header indicates this *might* be
312 // an AJAX request, in which case redirect-with-cookie
313 // won't work: we should just serve the content in the
314 // POST response. This is safe because:
316 // * We're supplying an attachment, not inline
317 // content, so we don't need to convert the POST to
318 // a GET and avoid the "really resubmit form?"
321 // * The token isn't embedded in the URL, so we don't
322 // need to worry about bookmarks and copy/paste.
323 reqTokens = append(reqTokens, formToken)
324 } else if formToken != "" && browserMethod[r.Method] {
325 // The client provided an explicit token in the query
326 // string, or a form in POST body. We must put the
327 // token in an HttpOnly cookie, and redirect to the
328 // same URL with the query param redacted and method =
330 h.seeOtherWithCookie(w, r, "", credentialsOK)
335 h.serveSiteFS(w, r, reqTokens, credentialsOK, attachment)
339 targetPath := pathParts[stripParts:]
340 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
341 // http://ID.example/t=TOKEN/PATH...
342 // /c=ID/t=TOKEN/PATH...
344 // This form must only be used to pass scoped tokens
345 // that give permission for a single collection. See
346 // FormValue case above.
347 tokens = []string{targetPath[0][2:]}
349 targetPath = targetPath[1:]
354 tokens = append(reqTokens, h.Config.AnonymousTokens...)
357 if len(targetPath) > 0 && targetPath[0] == "_" {
358 // If a collection has a directory called "t=foo" or
359 // "_", it can be served at
360 // //collections.example/_/t=foo/ or
361 // //collections.example/_/_/ respectively:
362 // //collections.example/t=foo/ won't work because
363 // t=foo will be interpreted as a token "foo".
364 targetPath = targetPath[1:]
368 arv := h.clientPool.Get()
370 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
373 defer h.clientPool.Put(arv)
375 var collection *arvados.Collection
376 tokenResult := make(map[string]int)
377 for _, arv.ApiToken = range tokens {
379 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
384 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
385 switch srvErr.HttpStatusCode {
387 // Token broken or insufficient to
388 // retrieve collection
389 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
393 // Something more serious is wrong
394 statusCode, statusText = http.StatusInternalServerError, err.Error()
397 if collection == nil {
398 if pathToken || !credentialsOK {
399 // Either the URL is a "secret sharing link"
400 // that didn't work out (and asking the client
401 // for additional credentials would just be
402 // confusing), or we don't even accept
403 // credentials at this path.
404 statusCode = http.StatusNotFound
407 for _, t := range reqTokens {
408 if tokenResult[t] == 404 {
409 // The client provided valid token(s), but the
410 // collection was not found.
411 statusCode = http.StatusNotFound
415 // The client's token was invalid (e.g., expired), or
416 // the client didn't even provide one. Propagate the
417 // 401 to encourage the client to use a [different]
420 // TODO(TC): This response would be confusing to
421 // someone trying (anonymously) to download public
422 // data that has been deleted. Allow a referrer to
423 // provide this context somehow?
424 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
425 statusCode = http.StatusUnauthorized
429 kc, err := keepclient.MakeKeepClient(arv)
431 statusCode, statusText = http.StatusInternalServerError, err.Error()
434 kc.RequestID = r.Header.Get("X-Request-Id")
437 if len(targetPath) > 0 {
438 basename = targetPath[len(targetPath)-1]
440 applyContentDispositionHdr(w, r, basename, attachment)
442 client := (&arvados.Client{
443 APIHost: arv.ApiServer,
444 AuthToken: arv.ApiToken,
445 Insecure: arv.ApiInsecure,
446 }).WithRequestID(r.Header.Get("X-Request-Id"))
448 fs, err := collection.FileSystem(client, kc)
450 statusCode, statusText = http.StatusInternalServerError, err.Error()
454 writefs, writeOK := fs.(arvados.CollectionFileSystem)
455 targetIsPDH := arvadosclient.PDHMatch(collectionID)
456 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
457 statusCode, statusText = http.StatusMethodNotAllowed, errReadOnly.Error()
461 if webdavMethod[r.Method] {
462 if writeMethod[r.Method] {
463 // Save the collection only if/when all
464 // webdav->filesystem operations succeed --
465 // and send a 500 error if the modified
466 // collection can't be saved.
467 w = &updateOnSuccess{
469 update: func() error {
470 return h.Config.Cache.Update(client, *collection, writefs)
474 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
475 FileSystem: &webdavFS{
477 writing: writeMethod[r.Method],
478 alwaysReadEOF: r.Method == "PROPFIND",
480 LockSystem: h.webdavLS,
481 Logger: func(_ *http.Request, err error) {
483 log.Printf("error from webdav handler: %q", err)
491 openPath := "/" + strings.Join(targetPath, "/")
492 if f, err := fs.Open(openPath); os.IsNotExist(err) {
493 // Requested non-existent path
494 statusCode = http.StatusNotFound
495 } else if err != nil {
496 // Some other (unexpected) error
497 statusCode, statusText = http.StatusInternalServerError, err.Error()
498 } else if stat, err := f.Stat(); err != nil {
499 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
500 statusCode, statusText = http.StatusInternalServerError, err.Error()
501 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
502 // If client requests ".../dirname", redirect to
503 // ".../dirname/". This way, relative links in the
504 // listing for "dirname" can always be "fnm", never
506 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
507 } else if stat.IsDir() {
508 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
510 http.ServeContent(w, r, basename, stat.ModTime(), f)
511 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
512 // If we wrote fewer bytes than expected, it's
513 // too late to change the real response code
514 // or send an error message to the client, but
515 // at least we can try to put some useful
516 // debugging info in the logs.
517 n, err := f.Read(make([]byte, 1024))
518 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)
524 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
525 if len(tokens) == 0 {
526 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
527 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
530 if writeMethod[r.Method] {
531 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
534 arv := h.clientPool.Get()
536 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
539 defer h.clientPool.Put(arv)
540 arv.ApiToken = tokens[0]
542 kc, err := keepclient.MakeKeepClient(arv)
544 http.Error(w, err.Error(), http.StatusInternalServerError)
547 kc.RequestID = r.Header.Get("X-Request-Id")
548 client := (&arvados.Client{
549 APIHost: arv.ApiServer,
550 AuthToken: arv.ApiToken,
551 Insecure: arv.ApiInsecure,
552 }).WithRequestID(r.Header.Get("X-Request-Id"))
553 fs := client.SiteFileSystem(kc)
554 f, err := fs.Open(r.URL.Path)
555 if os.IsNotExist(err) {
556 http.Error(w, err.Error(), http.StatusNotFound)
558 } else if err != nil {
559 http.Error(w, err.Error(), http.StatusInternalServerError)
563 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
564 if !strings.HasSuffix(r.URL.Path, "/") {
565 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
567 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
571 if r.Method == "GET" {
572 _, basename := filepath.Split(r.URL.Path)
573 applyContentDispositionHdr(w, r, basename, attachment)
575 wh := webdav.Handler{
577 FileSystem: &webdavFS{
579 writing: writeMethod[r.Method],
580 alwaysReadEOF: r.Method == "PROPFIND",
582 LockSystem: h.webdavLS,
583 Logger: func(_ *http.Request, err error) {
585 log.Printf("error from webdav handler: %q", err)
592 var dirListingTemplate = `<!DOCTYPE HTML>
594 <META name="robots" content="NOINDEX">
595 <TITLE>{{ .CollectionName }}</TITLE>
596 <STYLE type="text/css">
601 background-color: #D9EDF7;
602 border-radius: .25em;
613 font-family: monospace;
620 <H1>{{ .CollectionName }}</H1>
622 <P>This collection of data files is being shared with you through
623 Arvados. You can download individual files listed below. To download
624 the entire directory tree with wget, try:</P>
626 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
628 <H2>File Listing</H2>
634 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
636 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
641 <P>(No files; this collection is empty.)</P>
648 Arvados is a free and open source software bioinformatics platform.
649 To learn more, visit arvados.org.
650 Arvados is not responsible for the files listed on this page.
657 type fileListEnt struct {
663 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
664 var files []fileListEnt
665 var walk func(string) error
666 if !strings.HasSuffix(base, "/") {
669 walk = func(path string) error {
670 dirname := base + path
672 dirname = strings.TrimSuffix(dirname, "/")
674 d, err := fs.Open(dirname)
678 ents, err := d.Readdir(-1)
682 for _, ent := range ents {
683 if recurse && ent.IsDir() {
684 err = walk(path + ent.Name() + "/")
689 files = append(files, fileListEnt{
690 Name: path + ent.Name(),
698 if err := walk(""); err != nil {
699 http.Error(w, err.Error(), http.StatusInternalServerError)
703 funcs := template.FuncMap{
704 "nbsp": func(s string) template.HTML {
705 return template.HTML(strings.Replace(s, " ", " ", -1))
708 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
710 http.Error(w, err.Error(), http.StatusInternalServerError)
713 sort.Slice(files, func(i, j int) bool {
714 return files[i].Name < files[j].Name
716 w.WriteHeader(http.StatusOK)
717 tmpl.Execute(w, map[string]interface{}{
718 "CollectionName": collectionName,
721 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
725 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
726 disposition := "inline"
728 disposition = "attachment"
730 if strings.ContainsRune(r.RequestURI, '?') {
731 // Help the UA realize that the filename is just
732 // "filename.txt", not
733 // "filename.txt?disposition=attachment".
735 // TODO(TC): Follow advice at RFC 6266 appendix D
736 disposition += "; filename=" + strconv.QuoteToASCII(filename)
738 if disposition != "inline" {
739 w.Header().Set("Content-Disposition", disposition)
743 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
744 if formToken := r.FormValue("api_token"); formToken != "" {
746 // It is not safe to copy the provided token
747 // into a cookie unless the current vhost
748 // (origin) serves only a single collection or
749 // we are in TrustAllContent mode.
750 w.WriteHeader(http.StatusBadRequest)
754 // The HttpOnly flag is necessary to prevent
755 // JavaScript code (included in, or loaded by, a page
756 // in the collection being served) from employing the
757 // user's token beyond reading other files in the same
758 // domain, i.e., same collection.
760 // The 303 redirect is necessary in the case of a GET
761 // request to avoid exposing the token in the Location
762 // bar, and in the case of a POST request to avoid
763 // raising warnings when the user refreshes the
765 http.SetCookie(w, &http.Cookie{
766 Name: "arvados_api_token",
767 Value: auth.EncodeTokenCookie([]byte(formToken)),
773 // Propagate query parameters (except api_token) from
774 // the original request.
775 redirQuery := r.URL.Query()
776 redirQuery.Del("api_token")
780 newu, err := u.Parse(location)
782 w.WriteHeader(http.StatusInternalServerError)
788 Scheme: r.URL.Scheme,
791 RawQuery: redirQuery.Encode(),
794 w.Header().Add("Location", redir)
795 w.WriteHeader(http.StatusSeeOther)
796 io.WriteString(w, `<A href="`)
797 io.WriteString(w, html.EscapeString(redir))
798 io.WriteString(w, `">Continue</A>`)