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{
151 webdavMethod = map[string]bool{
161 browserMethod = map[string]bool{
166 // top-level dirs to serve with siteFS
167 siteFSDir = map[string]bool{
168 "": true, // root directory
174 // ServeHTTP implements http.Handler.
175 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
176 h.setupOnce.Do(h.setup)
179 var statusText string
181 remoteAddr := r.RemoteAddr
182 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
183 remoteAddr = xff + "," + remoteAddr
185 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" && xfp != "http" {
189 w := httpserver.WrapResponseWriter(wOrig)
192 statusCode = w.WroteStatus()
193 } else if w.WroteStatus() == 0 {
194 w.WriteHeader(statusCode)
195 } else if w.WroteStatus() != statusCode {
196 log.WithField("RequestID", r.Header.Get("X-Request-Id")).Warn(
197 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
199 if statusText == "" {
200 statusText = http.StatusText(statusCode)
204 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
205 h.healthHandler.ServeHTTP(w, r)
209 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
210 if !browserMethod[method] && !webdavMethod[method] {
211 statusCode = http.StatusMethodNotAllowed
214 w.Header().Set("Access-Control-Allow-Headers", corsAllowHeadersHeader)
215 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PUT, RMCOL")
216 w.Header().Set("Access-Control-Allow-Origin", "*")
217 w.Header().Set("Access-Control-Max-Age", "86400")
218 statusCode = http.StatusOK
222 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
223 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
227 if r.Header.Get("Origin") != "" {
228 // Allow simple cross-origin requests without user
229 // credentials ("user credentials" as defined by CORS,
230 // i.e., cookies, HTTP authentication, and client-side
231 // SSL certificates. See
232 // http://www.w3.org/TR/cors/#user-credentials).
233 w.Header().Set("Access-Control-Allow-Origin", "*")
234 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
237 pathParts := strings.Split(r.URL.Path[1:], "/")
240 var collectionID string
242 var reqTokens []string
246 credentialsOK := h.Config.TrustAllContent
248 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
251 } else if r.FormValue("disposition") == "attachment" {
255 if collectionID = parseCollectionIDFromDNSName(r.Host); collectionID != "" {
256 // http://ID.collections.example/PATH...
258 } else if r.URL.Path == "/status.json" {
261 } else if strings.HasPrefix(r.URL.Path, "/metrics") {
262 h.MetricsAPI.ServeHTTP(w, r)
264 } else if siteFSDir[pathParts[0]] {
266 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
268 collectionID = parseCollectionIDFromURL(pathParts[0][2:])
270 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
271 if len(pathParts) >= 4 && pathParts[1] == "download" {
272 // /collections/download/ID/TOKEN/PATH...
273 collectionID = parseCollectionIDFromURL(pathParts[2])
274 tokens = []string{pathParts[3]}
278 // /collections/ID/PATH...
279 collectionID = parseCollectionIDFromURL(pathParts[1])
280 tokens = h.Config.AnonymousTokens
285 if collectionID == "" && !useSiteFS {
286 statusCode = http.StatusNotFound
291 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
295 formToken := r.FormValue("api_token")
296 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
297 // The client provided an explicit token in the POST
298 // body. The Origin header indicates this *might* be
299 // an AJAX request, in which case redirect-with-cookie
300 // won't work: we should just serve the content in the
301 // POST response. This is safe because:
303 // * We're supplying an attachment, not inline
304 // content, so we don't need to convert the POST to
305 // a GET and avoid the "really resubmit form?"
308 // * The token isn't embedded in the URL, so we don't
309 // need to worry about bookmarks and copy/paste.
310 tokens = append(tokens, formToken)
311 } else if formToken != "" && browserMethod[r.Method] {
312 // The client provided an explicit token in the query
313 // string, or a form in POST body. We must put the
314 // token in an HttpOnly cookie, and redirect to the
315 // same URL with the query param redacted and method =
317 h.seeOtherWithCookie(w, r, "", credentialsOK)
323 tokens = auth.CredentialsFromRequest(r).Tokens
325 h.serveSiteFS(w, r, tokens, credentialsOK, attachment)
329 targetPath := pathParts[stripParts:]
330 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
331 // http://ID.example/t=TOKEN/PATH...
332 // /c=ID/t=TOKEN/PATH...
334 // This form must only be used to pass scoped tokens
335 // that give permission for a single collection. See
336 // FormValue case above.
337 tokens = []string{targetPath[0][2:]}
339 targetPath = targetPath[1:]
345 reqTokens = auth.CredentialsFromRequest(r).Tokens
347 tokens = append(reqTokens, h.Config.AnonymousTokens...)
350 if len(targetPath) > 0 && targetPath[0] == "_" {
351 // If a collection has a directory called "t=foo" or
352 // "_", it can be served at
353 // //collections.example/_/t=foo/ or
354 // //collections.example/_/_/ respectively:
355 // //collections.example/t=foo/ won't work because
356 // t=foo will be interpreted as a token "foo".
357 targetPath = targetPath[1:]
361 arv := h.clientPool.Get()
363 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
366 defer h.clientPool.Put(arv)
368 var collection *arvados.Collection
369 tokenResult := make(map[string]int)
370 for _, arv.ApiToken = range tokens {
372 collection, err = h.Config.Cache.Get(arv, collectionID, forceReload)
377 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
378 switch srvErr.HttpStatusCode {
380 // Token broken or insufficient to
381 // retrieve collection
382 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
386 // Something more serious is wrong
387 statusCode, statusText = http.StatusInternalServerError, err.Error()
390 if collection == nil {
391 if pathToken || !credentialsOK {
392 // Either the URL is a "secret sharing link"
393 // that didn't work out (and asking the client
394 // for additional credentials would just be
395 // confusing), or we don't even accept
396 // credentials at this path.
397 statusCode = http.StatusNotFound
400 for _, t := range reqTokens {
401 if tokenResult[t] == 404 {
402 // The client provided valid token(s), but the
403 // collection was not found.
404 statusCode = http.StatusNotFound
408 // The client's token was invalid (e.g., expired), or
409 // the client didn't even provide one. Propagate the
410 // 401 to encourage the client to use a [different]
413 // TODO(TC): This response would be confusing to
414 // someone trying (anonymously) to download public
415 // data that has been deleted. Allow a referrer to
416 // provide this context somehow?
417 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
418 statusCode = http.StatusUnauthorized
422 kc, err := keepclient.MakeKeepClient(arv)
424 statusCode, statusText = http.StatusInternalServerError, err.Error()
427 kc.RequestID = r.Header.Get("X-Request-Id")
430 if len(targetPath) > 0 {
431 basename = targetPath[len(targetPath)-1]
433 applyContentDispositionHdr(w, r, basename, attachment)
435 client := (&arvados.Client{
436 APIHost: arv.ApiServer,
437 AuthToken: arv.ApiToken,
438 Insecure: arv.ApiInsecure,
439 }).WithRequestID(r.Header.Get("X-Request-Id"))
441 fs, err := collection.FileSystem(client, kc)
443 statusCode, statusText = http.StatusInternalServerError, err.Error()
447 writefs, writeOK := fs.(arvados.CollectionFileSystem)
448 targetIsPDH := arvadosclient.PDHMatch(collectionID)
449 if (targetIsPDH || !writeOK) && writeMethod[r.Method] {
450 statusCode, statusText = http.StatusMethodNotAllowed, errReadOnly.Error()
454 if webdavMethod[r.Method] {
455 if writeMethod[r.Method] {
456 // Save the collection only if/when all
457 // webdav->filesystem operations succeed --
458 // and send a 500 error if the modified
459 // collection can't be saved.
460 w = &updateOnSuccess{
462 update: func() error {
463 return h.Config.Cache.Update(client, *collection, writefs)
467 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
468 FileSystem: &webdavFS{
470 writing: writeMethod[r.Method],
471 alwaysReadEOF: r.Method == "PROPFIND",
473 LockSystem: h.webdavLS,
474 Logger: func(_ *http.Request, err error) {
476 log.Printf("error from webdav handler: %q", err)
484 openPath := "/" + strings.Join(targetPath, "/")
485 if f, err := fs.Open(openPath); os.IsNotExist(err) {
486 // Requested non-existent path
487 statusCode = http.StatusNotFound
488 } else if err != nil {
489 // Some other (unexpected) error
490 statusCode, statusText = http.StatusInternalServerError, err.Error()
491 } else if stat, err := f.Stat(); err != nil {
492 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
493 statusCode, statusText = http.StatusInternalServerError, err.Error()
494 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
495 // If client requests ".../dirname", redirect to
496 // ".../dirname/". This way, relative links in the
497 // listing for "dirname" can always be "fnm", never
499 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
500 } else if stat.IsDir() {
501 h.serveDirectory(w, r, collection.Name, fs, openPath, true)
503 http.ServeContent(w, r, basename, stat.ModTime(), f)
504 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
505 // If we wrote fewer bytes than expected, it's
506 // too late to change the real response code
507 // or send an error message to the client, but
508 // at least we can try to put some useful
509 // debugging info in the logs.
510 n, err := f.Read(make([]byte, 1024))
511 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)
517 func (h *handler) serveSiteFS(w http.ResponseWriter, r *http.Request, tokens []string, credentialsOK, attachment bool) {
518 if len(tokens) == 0 {
519 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
520 http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
523 if writeMethod[r.Method] {
524 http.Error(w, errReadOnly.Error(), http.StatusMethodNotAllowed)
527 arv := h.clientPool.Get()
529 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
532 defer h.clientPool.Put(arv)
533 arv.ApiToken = tokens[0]
535 kc, err := keepclient.MakeKeepClient(arv)
537 http.Error(w, err.Error(), http.StatusInternalServerError)
540 kc.RequestID = r.Header.Get("X-Request-Id")
541 client := (&arvados.Client{
542 APIHost: arv.ApiServer,
543 AuthToken: arv.ApiToken,
544 Insecure: arv.ApiInsecure,
545 }).WithRequestID(r.Header.Get("X-Request-Id"))
546 fs := client.SiteFileSystem(kc)
547 f, err := fs.Open(r.URL.Path)
548 if os.IsNotExist(err) {
549 http.Error(w, err.Error(), http.StatusNotFound)
551 } else if err != nil {
552 http.Error(w, err.Error(), http.StatusInternalServerError)
556 if fi, err := f.Stat(); err == nil && fi.IsDir() && r.Method == "GET" {
557 if !strings.HasSuffix(r.URL.Path, "/") {
558 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
560 h.serveDirectory(w, r, fi.Name(), fs, r.URL.Path, false)
564 if r.Method == "GET" {
565 _, basename := filepath.Split(r.URL.Path)
566 applyContentDispositionHdr(w, r, basename, attachment)
568 wh := webdav.Handler{
570 FileSystem: &webdavFS{
572 writing: writeMethod[r.Method],
573 alwaysReadEOF: r.Method == "PROPFIND",
575 LockSystem: h.webdavLS,
576 Logger: func(_ *http.Request, err error) {
578 log.Printf("error from webdav handler: %q", err)
585 var dirListingTemplate = `<!DOCTYPE HTML>
587 <META name="robots" content="NOINDEX">
588 <TITLE>{{ .CollectionName }}</TITLE>
589 <STYLE type="text/css">
594 background-color: #D9EDF7;
595 border-radius: .25em;
606 font-family: monospace;
613 <H1>{{ .CollectionName }}</H1>
615 <P>This collection of data files is being shared with you through
616 Arvados. You can download individual files listed below. To download
617 the entire directory tree with wget, try:</P>
619 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL.Path }}</PRE>
621 <H2>File Listing</H2>
627 <LI>{{" " | printf "%15s " | nbsp}}<A href="{{print "./" .Name}}/">{{.Name}}/</A></LI>
629 <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{print "./" .Name}}">{{.Name}}</A></LI>
634 <P>(No files; this collection is empty.)</P>
641 Arvados is a free and open source software bioinformatics platform.
642 To learn more, visit arvados.org.
643 Arvados is not responsible for the files listed on this page.
650 type fileListEnt struct {
656 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, recurse bool) {
657 var files []fileListEnt
658 var walk func(string) error
659 if !strings.HasSuffix(base, "/") {
662 walk = func(path string) error {
663 dirname := base + path
665 dirname = strings.TrimSuffix(dirname, "/")
667 d, err := fs.Open(dirname)
671 ents, err := d.Readdir(-1)
675 for _, ent := range ents {
676 if recurse && ent.IsDir() {
677 err = walk(path + ent.Name() + "/")
682 files = append(files, fileListEnt{
683 Name: path + ent.Name(),
691 if err := walk(""); err != nil {
692 http.Error(w, err.Error(), http.StatusInternalServerError)
696 funcs := template.FuncMap{
697 "nbsp": func(s string) template.HTML {
698 return template.HTML(strings.Replace(s, " ", " ", -1))
701 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
703 http.Error(w, err.Error(), http.StatusInternalServerError)
706 sort.Slice(files, func(i, j int) bool {
707 return files[i].Name < files[j].Name
709 w.WriteHeader(http.StatusOK)
710 tmpl.Execute(w, map[string]interface{}{
711 "CollectionName": collectionName,
714 "StripParts": strings.Count(strings.TrimRight(r.URL.Path, "/"), "/"),
718 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
719 disposition := "inline"
721 disposition = "attachment"
723 if strings.ContainsRune(r.RequestURI, '?') {
724 // Help the UA realize that the filename is just
725 // "filename.txt", not
726 // "filename.txt?disposition=attachment".
728 // TODO(TC): Follow advice at RFC 6266 appendix D
729 disposition += "; filename=" + strconv.QuoteToASCII(filename)
731 if disposition != "inline" {
732 w.Header().Set("Content-Disposition", disposition)
736 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
737 if formToken := r.FormValue("api_token"); formToken != "" {
739 // It is not safe to copy the provided token
740 // into a cookie unless the current vhost
741 // (origin) serves only a single collection or
742 // we are in TrustAllContent mode.
743 w.WriteHeader(http.StatusBadRequest)
747 // The HttpOnly flag is necessary to prevent
748 // JavaScript code (included in, or loaded by, a page
749 // in the collection being served) from employing the
750 // user's token beyond reading other files in the same
751 // domain, i.e., same collection.
753 // The 303 redirect is necessary in the case of a GET
754 // request to avoid exposing the token in the Location
755 // bar, and in the case of a POST request to avoid
756 // raising warnings when the user refreshes the
758 http.SetCookie(w, &http.Cookie{
759 Name: "arvados_api_token",
760 Value: auth.EncodeTokenCookie([]byte(formToken)),
766 // Propagate query parameters (except api_token) from
767 // the original request.
768 redirQuery := r.URL.Query()
769 redirQuery.Del("api_token")
773 newu, err := u.Parse(location)
775 w.WriteHeader(http.StatusInternalServerError)
781 Scheme: r.URL.Scheme,
784 RawQuery: redirQuery.Encode(),
787 w.Header().Add("Location", redir)
788 w.WriteHeader(http.StatusSeeOther)
789 io.WriteString(w, `<A href="`)
790 io.WriteString(w, html.EscapeString(redir))
791 io.WriteString(w, `">Continue</A>`)