1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
23 "git.curoverse.com/arvados.git/sdk/go/arvados"
24 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
25 "git.curoverse.com/arvados.git/sdk/go/auth"
26 "git.curoverse.com/arvados.git/sdk/go/health"
27 "git.curoverse.com/arvados.git/sdk/go/httpserver"
28 "git.curoverse.com/arvados.git/sdk/go/keepclient"
29 "golang.org/x/net/webdav"
34 clientPool *arvadosclient.ClientPool
36 healthHandler http.Handler
37 webdavLS webdav.LockSystem
40 // parseCollectionIDFromDNSName returns a UUID or PDH if s begins with
41 // a UUID or URL-encoded PDH; otherwise "".
42 func parseCollectionIDFromDNSName(s string) string {
44 if i := strings.IndexRune(s, '.'); i >= 0 {
47 // Names like {uuid}--collections.example.com serve the same
48 // purpose as {uuid}.collections.example.com but can reduce
49 // cost/effort of using [additional] wildcard certificates.
50 if i := strings.Index(s, "--"); i >= 0 {
53 if arvadosclient.UUIDMatch(s) {
56 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
62 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
64 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
65 // PDH (even if it is a PDH with "+" replaced by " " or "-");
67 func parseCollectionIDFromURL(s string) string {
68 if arvadosclient.UUIDMatch(s) {
71 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
77 func (h *handler) setup() {
78 h.clientPool = arvadosclient.MakeClientPool()
80 keepclient.RefreshServiceDiscoveryOnSIGHUP()
82 h.healthHandler = &health.Handler{
83 Token: h.Config.ManagementToken,
87 // Even though we don't accept LOCK requests, every webdav
88 // handler must have a non-nil LockSystem.
89 h.webdavLS = &noLockSystem{}
92 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
97 cacheStats: h.Config.Cache.Stats(),
100 json.NewEncoder(w).Encode(status)
103 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
104 // sends an HTTP header indicating success, updateOnSuccess first
105 // calls the provided update func. If the update func fails, a 500
106 // response is sent, and the status code and body sent by the handler
107 // are ignored (all response writes return the update error).
108 type updateOnSuccess struct {
109 httpserver.ResponseWriter
115 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
117 uos.WriteHeader(http.StatusOK)
122 return uos.ResponseWriter.Write(p)
125 func (uos *updateOnSuccess) WriteHeader(code int) {
127 uos.sentHeader = true
128 if code >= 200 && code < 400 {
129 if uos.err = uos.update(); uos.err != nil {
130 code := http.StatusInternalServerError
131 if err, ok := uos.err.(*arvados.TransactionError); ok {
132 code = err.StatusCode
134 log.Printf("update() changes response to HTTP %d: %T %q", code, uos.err, uos.err)
135 http.Error(uos.ResponseWriter, uos.err.Error(), code)
140 uos.ResponseWriter.WriteHeader(code)
144 writeMethod = map[string]bool{
152 webdavMethod = map[string]bool{
162 browserMethod = map[string]bool{
167 // top-level dirs to serve with siteFS
168 siteFSDir = map[string]bool{
169 "": true, // root directory
175 // ServeHTTP implements http.Handler.
176 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
177 h.setupOnce.Do(h.setup)
180 var statusText string
182 remoteAddr := r.RemoteAddr
183 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
184 remoteAddr = xff + "," + remoteAddr
187 w := httpserver.WrapResponseWriter(wOrig)
190 statusCode = w.WroteStatus()
191 } else if w.WroteStatus() == 0 {
192 w.WriteHeader(statusCode)
193 } else if w.WroteStatus() != statusCode {
194 httpserver.Log(r.RemoteAddr, "WARNING",
195 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
197 if statusText == "" {
198 statusText = http.StatusText(statusCode)
200 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
203 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
204 h.healthHandler.ServeHTTP(w, r)
208 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
209 if !browserMethod[method] && !webdavMethod[method] {
210 statusCode = http.StatusMethodNotAllowed
213 w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Range")
214 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PUT, RMCOL")
215 w.Header().Set("Access-Control-Allow-Origin", "*")
216 w.Header().Set("Access-Control-Max-Age", "86400")
217 statusCode = http.StatusOK
221 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
222 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
226 if r.Header.Get("Origin") != "" {
227 // Allow simple cross-origin requests without user
228 // credentials ("user credentials" as defined by CORS,
229 // i.e., cookies, HTTP authentication, and client-side
230 // SSL certificates. See
231 // http://www.w3.org/TR/cors/#user-credentials).
232 w.Header().Set("Access-Control-Allow-Origin", "*")
233 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
236 pathParts := strings.Split(r.URL.Path[1:], "/")
239 var collectionID string
241 var reqTokens []string
245 credentialsOK := h.Config.TrustAllContent
247 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
250 } else if r.FormValue("disposition") == "attachment" {
254 if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
255 // http://ID.collections.example/PATH...
257 } else if r.URL.Path == "/status.json" {
260 } else if siteFSDir[pathParts[0]] {
262 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
264 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
266 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
267 if len(pathParts) >= 4 && pathParts[1] == "download" {
268 // /collections/download/ID/TOKEN/PATH...
269 collectionID = parseCollectionIDFromURL(pathParts[2])
270 tokens = []string{pathParts[3]}
274 // /collections/ID/PATH...
275 collectionID = parseCollectionIDFromURL(pathParts[1])
276 tokens = h.Config.AnonymousTokens
281 if collectionID == "" && !useSiteFS {
282 statusCode = http.StatusNotFound
287 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
291 formToken := r.FormValue("api_token")
292 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
293 // The client provided an explicit token in the POST
294 // body. The Origin header indicates this *might* be
295 // an AJAX request, in which case redirect-with-cookie
296 // won't work: we should just serve the content in the
297 // POST response. This is safe because:
299 // * We're supplying an attachment, not inline
300 // content, so we don't need to convert the POST to
301 // a GET and avoid the "really resubmit form?"
304 // * The token isn't embedded in the URL, so we don't
305 // need to worry about bookmarks and copy/paste.
306 tokens = append(tokens, formToken)
307 } else if formToken != "" && browserMethod[r.Method] {
308 // The client provided an explicit token in the query
309 // string, or a form in POST body. We must put the
310 // token in an HttpOnly cookie, and redirect to the
311 // same URL with the query param redacted and method =
313 h.seeOtherWithCookie(w, r, "", credentialsOK)
319 tokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
321 h.serveSiteFS(w, r, tokens, credentialsOK, attachment)
325 targetPath := pathParts[stripParts:]
326 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
327 // http://ID.example/t=TOKEN/PATH...
328 // /c=ID/t=TOKEN/PATH...
330 // This form must only be used to pass scoped tokens
331 // that give permission for a single collection. See
332 // FormValue case above.
333 tokens = []string{targetPath[0][2:]}
335 targetPath = targetPath[1:]
341 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
343 tokens = append(reqTokens, h.Config.AnonymousTokens...)
346 if len(targetPath) > 0 && targetPath[0] == "_" {
347 // If a collection has a directory called "t=foo" or
348 // "_", it can be served at
349 // //collections.example/_/t=foo/ or
350 // //collections.example/_/_/ respectively:
351 // //collections.example/t=foo/ won't work because
352 // t=foo will be interpreted as a token "foo".
353 targetPath = targetPath[1:]
357 arv := h.clientPool.Get()
359 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
362 defer h.clientPool.Put(arv)
364 var collection *arvados.Collection
365 tokenResult := make(map[string]int)
366 for _, arv.ApiToken = range tokens {
368 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
373 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
374 switch srvErr.HttpStatusCode {
376 // Token broken or insufficient to
377 // retrieve collection
378 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
382 // Something more serious is wrong
383 statusCode, statusText = http.StatusInternalServerError, err.Error()
386 if collection == nil {
387 if pathToken || !credentialsOK {
388 // Either the URL is a "secret sharing link"
389 // that didn't work out (and asking the client
390 // for additional credentials would just be
391 // confusing), or we don't even accept
392 // credentials at this path.
393 statusCode = http.StatusNotFound
396 for _, t := range reqTokens {
397 if tokenResult[t] == 404 {
398 // The client provided valid token(s), but the
399 // collection was not found.
400 statusCode = http.StatusNotFound
404 // The client's token was invalid (e.g., expired), or
405 // the client didn't even provide one. Propagate the
406 // 401 to encourage the client to use a [different]
409 // TODO(TC): This response would be confusing to
410 // someone trying (anonymously) to download public
411 // data that has been deleted. Allow a referrer to
412 // provide this context somehow?
413 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
414 statusCode = http.StatusUnauthorized
418 kc, err := keepclient.MakeKeepClient(arv)
420 statusCode, statusText = http.StatusInternalServerError, err.Error()
425 if len(targetPath) > 0 {
426 basename = targetPath[len(targetPath)-1]
428 applyContentDispositionHdr(w, r, basename, attachment)
430 client := &arvados.Client{
431 APIHost: arv.ApiServer,
432 AuthToken: arv.ApiToken,
433 Insecure: arv.ApiInsecure,
436 fs, err := collection.FileSystem(client, kc)
438 statusCode, statusText = http.StatusInternalServerError, err.Error()
442 writefs, writeOK := fs.(arvados.CollectionFileSystem)
443 targetIsPDH := arvadosclient.PDHMatch(collectionID)
444 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
445 statusCode, statusText = http.StatusMethodNotAllowed, errReadOnly.Error()
449 if webdavMethod[r.Method] {
450 if writeMethod[r.Method] {
451 // Save the collection only if/when all
452 // webdav->filesystem operations succeed --
453 // and send a 500 error if the modified
454 // collection can't be saved.
455 w = &updateOnSuccess{
457 update: func() error {
458 return h.Config.Cache.Update(client, *collection, writefs)
462 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
463 FileSystem: &webdavFS{
465 writing: writeMethod[r.Method],
466 alwaysReadEOF: r.Method == "PROPFIND",
468 LockSystem: h.webdavLS,
469 Logger: func(_ *http.Request, err error) {
471 log.Printf("error from webdav handler: %q", err)
479 openPath := "/" + strings.Join(targetPath, "/")
480 if f, err := fs.Open(openPath); os.IsNotExist(err) {
481 // Requested non-existent path
482 statusCode = http.StatusNotFound
483 } else if err != nil {
484 // Some other (unexpected) error
485 statusCode, statusText = http.StatusInternalServerError, err.Error()
486 } else if stat, err := f.Stat(); err != nil {
487 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
488 statusCode, statusText = http.StatusInternalServerError, err.Error()
489 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
490 // If client requests ".../dirname", redirect to
491 // ".../dirname/". This way, relative links in the
492 // listing for "dirname" can always be "fnm", never
494 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
495 } else if stat.IsDir() {
496 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
498 http.ServeContent(w, r, basename, stat.ModTime(), f)
499 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
500 // If we wrote fewer bytes than expected, it's
501 // too late to change the real response code
502 // or send an error message to the client, but
503 // at least we can try to put some useful
504 // debugging info in the logs.
505 n, err := f.Read(make([]byte, 1024))
506 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)
512 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
513 if len(tokens) == 0 {
514 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
515 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
518 if writeMethod[r.Method] {
519 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
522 arv := h.clientPool.Get()
524 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
527 defer h.clientPool.Put(arv)
528 arv.ApiToken = tokens[0]
530 kc, err := keepclient.MakeKeepClient(arv)
532 http.Error(w, err.Error(), http.StatusInternalServerError)
535 client := &arvados.Client{
536 APIHost: arv.ApiServer,
537 AuthToken: arv.ApiToken,
538 Insecure: arv.ApiInsecure,
540 fs := client.SiteFileSystem(kc)
541 f, err := fs.Open(r.URL.Path)
542 if os.IsNotExist(err) {
543 http.Error(w, err.Error(), http.StatusNotFound)
545 } else if err != nil {
546 http.Error(w, err.Error(), http.StatusInternalServerError)
550 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
551 if !strings.HasSuffix(r.URL.Path, "/") {
552 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
554 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
558 if r.Method == "GET" {
559 _, basename := filepath.Split(r.URL.Path)
560 applyContentDispositionHdr(w, r, basename, attachment)
562 wh := webdav.Handler{
564 FileSystem: &webdavFS{
566 writing: writeMethod[r.Method],
567 alwaysReadEOF: r.Method == "PROPFIND",
569 LockSystem: h.webdavLS,
570 Logger: func(_ *http.Request, err error) {
572 log.Printf("error from webdav handler: %q", err)
579 var dirListingTemplate = `<!DOCTYPE HTML>
581 <META name="robots" content="NOINDEX">
582 <TITLE>{{ .CollectionName }}</TITLE>
583 <STYLE type="text/css">
588 background-color: #D9EDF7;
589 border-radius: .25em;
600 font-family: monospace;
607 <H1>{{ .CollectionName }}</H1>
609 <P>This collection of data files is being shared with you through
610 Arvados. You can download individual files listed below. To download
611 the entire directory tree with wget, try:</P>
613 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
615 <H2>File Listing</H2>
621 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
623 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
628 <P>(No files; this collection is empty.)</P>
635 Arvados is a free and open source software bioinformatics platform.
636 To learn more, visit arvados.org.
637 Arvados is not responsible for the files listed on this page.
644 type fileListEnt struct {
650 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
651 var files []fileListEnt
652 var walk func(string) error
653 if !strings.HasSuffix(base, "/") {
656 walk = func(path string) error {
657 dirname := base + path
659 dirname = strings.TrimSuffix(dirname, "/")
661 d, err := fs.Open(dirname)
665 ents, err := d.Readdir(-1)
669 for _, ent := range ents {
670 if recurse && ent.IsDir() {
671 err = walk(path + ent.Name() + "/")
676 files = append(files, fileListEnt{
677 Name: path + ent.Name(),
685 if err := walk(""); err != nil {
686 http.Error(w, err.Error(), http.StatusInternalServerError)
690 funcs := template.FuncMap{
691 "nbsp": func(s string) template.HTML {
692 return template.HTML(strings.Replace(s, " ", " ", -1))
695 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
697 http.Error(w, err.Error(), http.StatusInternalServerError)
700 sort.Slice(files, func(i, j int) bool {
701 return files[i].Name < files[j].Name
703 w.WriteHeader(http.StatusOK)
704 tmpl.Execute(w, map[string]interface{}{
705 "CollectionName": collectionName,
708 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
712 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
713 disposition := "inline"
715 disposition = "attachment"
717 if strings.ContainsRune(r.RequestURI, '?') {
718 // Help the UA realize that the filename is just
719 // "filename.txt", not
720 // "filename.txt?disposition=attachment".
722 // TODO(TC): Follow advice at RFC 6266 appendix D
723 disposition += "; filename=" + strconv.QuoteToASCII(filename)
725 if disposition != "inline" {
726 w.Header().Set("Content-Disposition", disposition)
730 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
731 if formToken := r.FormValue("api_token"); formToken != "" {
733 // It is not safe to copy the provided token
734 // into a cookie unless the current vhost
735 // (origin) serves only a single collection or
736 // we are in TrustAllContent mode.
737 w.WriteHeader(http.StatusBadRequest)
741 // The HttpOnly flag is necessary to prevent
742 // JavaScript code (included in, or loaded by, a page
743 // in the collection being served) from employing the
744 // user's token beyond reading other files in the same
745 // domain, i.e., same collection.
747 // The 303 redirect is necessary in the case of a GET
748 // request to avoid exposing the token in the Location
749 // bar, and in the case of a POST request to avoid
750 // raising warnings when the user refreshes the
752 http.SetCookie(w, &http.Cookie{
753 Name: "arvados_api_token",
754 Value: auth.EncodeTokenCookie([]byte(formToken)),
760 // Propagate query parameters (except api_token) from
761 // the original request.
762 redirQuery := r.URL.Query()
763 redirQuery.Del("api_token")
767 newu, err := u.Parse(location)
769 w.WriteHeader(http.StatusInternalServerError)
777 RawQuery: redirQuery.Encode(),
780 w.Header().Add("Location", redir)
781 w.WriteHeader(http.StatusSeeOther)
782 io.WriteString(w, `<A href="`)
783 io.WriteString(w, html.EscapeString(redir))
784 io.WriteString(w, `">Continue</A>`)