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 "golang.org/x/net/webdav"
33 clientPool *arvadosclient.ClientPool
35 healthHandler http.Handler
36 webdavLS webdav.LockSystem
39 // parseCollectionIDFromDNSName returns a UUID or PDH if s begins with
40 // a UUID or URL-encoded PDH; otherwise "".
41 func parseCollectionIDFromDNSName(s string) string {
43 if i := strings.IndexRune(s, '.'); i >= 0 {
46 // Names like {uuid}--collections.example.com serve the same
47 // purpose as {uuid}.collections.example.com but can reduce
48 // cost/effort of using [additional] wildcard certificates.
49 if i := strings.Index(s, "--"); i >= 0 {
52 if arvadosclient.UUIDMatch(s) {
55 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
61 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
63 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
64 // PDH (even if it is a PDH with "+" replaced by " " or "-");
66 func parseCollectionIDFromURL(s string) string {
67 if arvadosclient.UUIDMatch(s) {
70 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
76 func (h *handler) setup() {
77 h.clientPool = arvadosclient.MakeClientPool()
79 keepclient.RefreshServiceDiscoveryOnSIGHUP()
81 h.healthHandler = &health.Handler{
82 Token: h.Config.ManagementToken,
86 // Even though we don't accept LOCK requests, every webdav
87 // handler must have a non-nil LockSystem.
88 h.webdavLS = &noLockSystem{}
91 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
96 cacheStats: h.Config.Cache.Stats(),
99 json.NewEncoder(w).Encode(status)
102 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
103 // sends an HTTP header indicating success, updateOnSuccess first
104 // calls the provided update func. If the update func fails, a 500
105 // response is sent, and the status code and body sent by the handler
106 // are ignored (all response writes return the update error).
107 type updateOnSuccess struct {
108 httpserver.ResponseWriter
114 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
119 uos.WriteHeader(http.StatusOK)
121 return uos.ResponseWriter.Write(p)
124 func (uos *updateOnSuccess) WriteHeader(code int) {
126 uos.sentHeader = true
127 if code >= 200 && code < 400 {
128 if uos.err = uos.update(); uos.err != nil {
129 code := http.StatusInternalServerError
130 if err, ok := uos.err.(*arvados.TransactionError); ok {
131 code = err.StatusCode
133 log.Printf("update() changes response to HTTP %d: %T %q", code, uos.err, uos.err)
134 http.Error(uos.ResponseWriter, uos.err.Error(), code)
139 uos.ResponseWriter.WriteHeader(code)
143 writeMethod = map[string]bool{
151 webdavMethod = map[string]bool{
161 browserMethod = map[string]bool{
168 // ServeHTTP implements http.Handler.
169 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
170 h.setupOnce.Do(h.setup)
173 var statusText string
175 remoteAddr := r.RemoteAddr
176 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
177 remoteAddr = xff + "," + remoteAddr
180 w := httpserver.WrapResponseWriter(wOrig)
183 statusCode = w.WroteStatus()
184 } else if w.WroteStatus() == 0 {
185 w.WriteHeader(statusCode)
186 } else if w.WroteStatus() != statusCode {
187 httpserver.Log(r.RemoteAddr, "WARNING",
188 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
190 if statusText == "" {
191 statusText = http.StatusText(statusCode)
193 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
196 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
197 h.healthHandler.ServeHTTP(w, r)
201 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
202 if !browserMethod[method] && !webdavMethod[method] {
203 statusCode = http.StatusMethodNotAllowed
206 w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Range")
207 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PUT, RMCOL")
208 w.Header().Set("Access-Control-Allow-Origin", "*")
209 w.Header().Set("Access-Control-Max-Age", "86400")
210 statusCode = http.StatusOK
214 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
215 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
219 if r.Header.Get("Origin") != "" {
220 // Allow simple cross-origin requests without user
221 // credentials ("user credentials" as defined by CORS,
222 // i.e., cookies, HTTP authentication, and client-side
223 // SSL certificates. See
224 // http://www.w3.org/TR/cors/#user-credentials).
225 w.Header().Set("Access-Control-Allow-Origin", "*")
226 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
229 pathParts := strings.Split(r.URL.Path[1:], "/")
232 var collectionID string
234 var reqTokens []string
238 credentialsOK := h.Config.TrustAllContent
240 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
243 } else if r.FormValue("disposition") == "attachment" {
247 if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
248 // http://ID.collections.example/PATH...
250 } else if r.URL.Path == "/status.json" {
253 } else if len(pathParts) >= 1 && pathParts[0] == "users" {
255 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
257 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
259 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
260 if len(pathParts) >= 4 && pathParts[1] == "download" {
261 // /collections/download/ID/TOKEN/PATH...
262 collectionID = parseCollectionIDFromURL(pathParts[2])
263 tokens = []string{pathParts[3]}
267 // /collections/ID/PATH...
268 collectionID = parseCollectionIDFromURL(pathParts[1])
269 tokens = h.Config.AnonymousTokens
274 if collectionID == "" && !useSiteFS {
275 statusCode = http.StatusNotFound
280 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
284 formToken := r.FormValue("api_token")
285 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
286 // The client provided an explicit token in the POST
287 // body. The Origin header indicates this *might* be
288 // an AJAX request, in which case redirect-with-cookie
289 // won't work: we should just serve the content in the
290 // POST response. This is safe because:
292 // * We're supplying an attachment, not inline
293 // content, so we don't need to convert the POST to
294 // a GET and avoid the "really resubmit form?"
297 // * The token isn't embedded in the URL, so we don't
298 // need to worry about bookmarks and copy/paste.
299 tokens = append(tokens, formToken)
300 } else if formToken != "" && browserMethod[r.Method] {
301 // The client provided an explicit token in the query
302 // string, or a form in POST body. We must put the
303 // token in an HttpOnly cookie, and redirect to the
304 // same URL with the query param redacted and method =
306 h.seeOtherWithCookie(w, r, "", credentialsOK)
310 targetPath := pathParts[stripParts:]
311 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
312 // http://ID.example/t=TOKEN/PATH...
313 // /c=ID/t=TOKEN/PATH...
315 // This form must only be used to pass scoped tokens
316 // that give permission for a single collection. See
317 // FormValue case above.
318 tokens = []string{targetPath[0][2:]}
320 targetPath = targetPath[1:]
326 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
328 tokens = append(reqTokens, h.Config.AnonymousTokens...)
332 h.serveSiteFS(w, r, tokens)
336 if len(targetPath) > 0 && targetPath[0] == "_" {
337 // If a collection has a directory called "t=foo" or
338 // "_", it can be served at
339 // //collections.example/_/t=foo/ or
340 // //collections.example/_/_/ respectively:
341 // //collections.example/t=foo/ won't work because
342 // t=foo will be interpreted as a token "foo".
343 targetPath = targetPath[1:]
347 arv := h.clientPool.Get()
349 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
352 defer h.clientPool.Put(arv)
354 var collection *arvados.Collection
355 tokenResult := make(map[string]int)
356 for _, arv.ApiToken = range tokens {
358 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
363 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
364 switch srvErr.HttpStatusCode {
366 // Token broken or insufficient to
367 // retrieve collection
368 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
372 // Something more serious is wrong
373 statusCode, statusText = http.StatusInternalServerError, err.Error()
376 if collection == nil {
377 if pathToken || !credentialsOK {
378 // Either the URL is a "secret sharing link"
379 // that didn't work out (and asking the client
380 // for additional credentials would just be
381 // confusing), or we don't even accept
382 // credentials at this path.
383 statusCode = http.StatusNotFound
386 for _, t := range reqTokens {
387 if tokenResult[t] == 404 {
388 // The client provided valid token(s), but the
389 // collection was not found.
390 statusCode = http.StatusNotFound
394 // The client's token was invalid (e.g., expired), or
395 // the client didn't even provide one. Propagate the
396 // 401 to encourage the client to use a [different]
399 // TODO(TC): This response would be confusing to
400 // someone trying (anonymously) to download public
401 // data that has been deleted. Allow a referrer to
402 // provide this context somehow?
403 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
404 statusCode = http.StatusUnauthorized
408 kc, err := keepclient.MakeKeepClient(arv)
410 statusCode, statusText = http.StatusInternalServerError, err.Error()
415 if len(targetPath) > 0 {
416 basename = targetPath[len(targetPath)-1]
418 applyContentDispositionHdr(w, r, basename, attachment)
420 client := &arvados.Client{
421 APIHost: arv.ApiServer,
422 AuthToken: arv.ApiToken,
423 Insecure: arv.ApiInsecure,
426 fs, err := collection.FileSystem(client, kc)
428 statusCode, statusText = http.StatusInternalServerError, err.Error()
432 writefs, writeOK := fs.(arvados.CollectionFileSystem)
433 targetIsPDH := arvadosclient.PDHMatch(collectionID)
434 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
435 statusCode, statusText = http.StatusMethodNotAllowed, errReadOnly.Error()
439 if webdavMethod[r.Method] {
440 if writeMethod[r.Method] {
441 // Save the collection only if/when all
442 // webdav->filesystem operations succeed --
443 // and send a 500 error if the modified
444 // collection can't be saved.
445 w = &updateOnSuccess{
447 update: func() error {
448 return h.Config.Cache.Update(client, *collection, writefs)
452 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
453 FileSystem: &webdavFS{
455 writing: writeMethod[r.Method],
456 alwaysReadEOF: r.Method == "PROPFIND",
458 LockSystem: h.webdavLS,
459 Logger: func(_ *http.Request, err error) {
461 log.Printf("error from webdav handler: %q", err)
469 openPath := "/" + strings.Join(targetPath, "/")
470 if f, err := fs.Open(openPath); os.IsNotExist(err) {
471 // Requested non-existent path
472 statusCode = http.StatusNotFound
473 } else if err != nil {
474 // Some other (unexpected) error
475 statusCode, statusText = http.StatusInternalServerError, err.Error()
476 } else if stat, err := f.Stat(); err != nil {
477 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
478 statusCode, statusText = http.StatusInternalServerError, err.Error()
479 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
480 // If client requests ".../dirname", redirect to
481 // ".../dirname/". This way, relative links in the
482 // listing for "dirname" can always be "fnm", never
484 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
485 } else if stat.IsDir() {
486 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
488 http.ServeContent(w, r, basename, stat.ModTime(), f)
489 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
490 // If we wrote fewer bytes than expected, it's
491 // too late to change the real response code
492 // or send an error message to the client, but
493 // at least we can try to put some useful
494 // debugging info in the logs.
495 n, err := f.Read(make([]byte, 1024))
496 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)
502 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string) {
503 if len(tokens) == 0 {
504 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
505 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
508 if writeMethod[r.Method] {
509 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
512 arv := h.clientPool.Get()
514 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
517 defer h.clientPool.Put(arv)
518 arv.ApiToken = tokens[0]
520 kc, err := keepclient.MakeKeepClient(arv)
522 http.Error(w, err.Error(), http.StatusInternalServerError)
525 client := &arvados.Client{
526 APIHost: arv.ApiServer,
527 AuthToken: arv.ApiToken,
528 Insecure: arv.ApiInsecure,
530 fs := client.SiteFileSystem(kc)
531 if f, err := fs.Open(r.URL.Path); os.IsNotExist(err) {
532 http.Error(w, err.Error(), http.StatusNotFound)
534 } else if err != nil {
535 http.Error(w, err.Error(), http.StatusInternalServerError)
537 } else if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
539 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
544 wh := webdav.Handler{
546 FileSystem: &webdavFS{
548 writing: writeMethod[r.Method],
549 alwaysReadEOF: r.Method == "PROPFIND",
551 LockSystem: h.webdavLS,
552 Logger: func(_ *http.Request, err error) {
554 log.Printf("error from webdav handler: %q", err)
561 var dirListingTemplate = `<!DOCTYPE HTML>
563 <META name="robots" content="NOINDEX">
564 <TITLE>{{ .CollectionName }}</TITLE>
565 <STYLE type="text/css">
570 background-color: #D9EDF7;
571 border-radius: .25em;
582 font-family: monospace;
589 <H1>{{ .CollectionName }}</H1>
591 <P>This collection of data files is being shared with you through
592 Arvados. You can download individual files listed below. To download
593 the entire directory tree with wget, try:</P>
595 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
597 <H2>File Listing</H2>
603 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{.Name}}/">{{.Name}}/</A></LI>
605 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{.Name}}">{{.Name}}</A></LI>
610 <P>(No files; this collection is empty.)</P>
617 Arvados is a free and open source software bioinformatics platform.
618 To learn more, visit arvados.org.
619 Arvados is not responsible for the files listed on this page.
626 type fileListEnt struct {
632 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
633 var files []fileListEnt
634 var walk func(string) error
635 if !strings.HasSuffix(base, "/") {
638 walk = func(path string) error {
639 dirname := base + path
641 dirname = strings.TrimSuffix(dirname, "/")
643 d, err := fs.Open(dirname)
647 ents, err := d.Readdir(-1)
651 for _, ent := range ents {
652 if recurse && ent.IsDir() {
653 err = walk(path + ent.Name() + "/")
658 files = append(files, fileListEnt{
659 Name: path + ent.Name(),
667 if err := walk(""); err != nil {
668 http.Error(w, err.Error(), http.StatusInternalServerError)
672 funcs := template.FuncMap{
673 "nbsp": func(s string) template.HTML {
674 return template.HTML(strings.Replace(s, " ", " ", -1))
677 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
679 http.Error(w, err.Error(), http.StatusInternalServerError)
682 sort.Slice(files, func(i, j int) bool {
683 return files[i].Name < files[j].Name
685 w.WriteHeader(http.StatusOK)
686 tmpl.Execute(w, map[string]interface{}{
687 "CollectionName": collectionName,
690 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
694 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
695 disposition := "inline"
697 disposition = "attachment"
699 if strings.ContainsRune(r.RequestURI, '?') {
700 // Help the UA realize that the filename is just
701 // "filename.txt", not
702 // "filename.txt?disposition=attachment".
704 // TODO(TC): Follow advice at RFC 6266 appendix D
705 disposition += "; filename=" + strconv.QuoteToASCII(filename)
707 if disposition != "inline" {
708 w.Header().Set("Content-Disposition", disposition)
712 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
713 if formToken := r.FormValue("api_token"); formToken != "" {
715 // It is not safe to copy the provided token
716 // into a cookie unless the current vhost
717 // (origin) serves only a single collection or
718 // we are in TrustAllContent mode.
719 w.WriteHeader(http.StatusBadRequest)
723 // The HttpOnly flag is necessary to prevent
724 // JavaScript code (included in, or loaded by, a page
725 // in the collection being served) from employing the
726 // user's token beyond reading other files in the same
727 // domain, i.e., same collection.
729 // The 303 redirect is necessary in the case of a GET
730 // request to avoid exposing the token in the Location
731 // bar, and in the case of a POST request to avoid
732 // raising warnings when the user refreshes the
734 http.SetCookie(w, &http.Cookie{
735 Name: "arvados_api_token",
736 Value: auth.EncodeTokenCookie([]byte(formToken)),
742 // Propagate query parameters (except api_token) from
743 // the original request.
744 redirQuery := r.URL.Query()
745 redirQuery.Del("api_token")
749 newu, err := u.Parse(location)
751 w.WriteHeader(http.StatusInternalServerError)
759 RawQuery: redirQuery.Encode(),
762 w.Header().Add("Location", redir)
763 w.WriteHeader(http.StatusSeeOther)
764 io.WriteString(w, `<A href="`)
765 io.WriteString(w, html.EscapeString(redir))
766 io.WriteString(w, `">Continue</A>`)