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 arv := h.clientPool.Get()
231 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
234 defer h.clientPool.Put(arv)
236 pathParts := strings.Split(r.URL.Path[1:], "/")
241 var reqTokens []string
244 credentialsOK := h.Config.TrustAllContent
246 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
249 } else if r.FormValue("disposition") == "attachment" {
253 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
254 // http://ID.collections.example/PATH...
256 } else if r.URL.Path == "/status.json" {
259 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
261 targetID = parseCollectionIDFromURL(pathParts[0][2:])
263 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
264 if len(pathParts) >= 4 && pathParts[1] == "download" {
265 // /collections/download/ID/TOKEN/PATH...
266 targetID = parseCollectionIDFromURL(pathParts[2])
267 tokens = []string{pathParts[3]}
271 // /collections/ID/PATH...
272 targetID = parseCollectionIDFromURL(pathParts[1])
273 tokens = h.Config.AnonymousTokens
279 statusCode = http.StatusNotFound
283 formToken := r.FormValue("api_token")
284 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
285 // The client provided an explicit token in the POST
286 // body. The Origin header indicates this *might* be
287 // an AJAX request, in which case redirect-with-cookie
288 // won't work: we should just serve the content in the
289 // POST response. This is safe because:
291 // * We're supplying an attachment, not inline
292 // content, so we don't need to convert the POST to
293 // a GET and avoid the "really resubmit form?"
296 // * The token isn't embedded in the URL, so we don't
297 // need to worry about bookmarks and copy/paste.
298 tokens = append(tokens, formToken)
299 } else if formToken != "" && browserMethod[r.Method] {
300 // The client provided an explicit token in the query
301 // string, or a form in POST body. We must put the
302 // token in an HttpOnly cookie, and redirect to the
303 // same URL with the query param redacted and method =
305 h.seeOtherWithCookie(w, r, "", credentialsOK)
309 targetPath := pathParts[stripParts:]
310 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
311 // http://ID.example/t=TOKEN/PATH...
312 // /c=ID/t=TOKEN/PATH...
314 // This form must only be used to pass scoped tokens
315 // that give permission for a single collection. See
316 // FormValue case above.
317 tokens = []string{targetPath[0][2:]}
319 targetPath = targetPath[1:]
325 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
327 tokens = append(reqTokens, h.Config.AnonymousTokens...)
330 if len(targetPath) > 0 && targetPath[0] == "_" {
331 // If a collection has a directory called "t=foo" or
332 // "_", it can be served at
333 // //collections.example/_/t=foo/ or
334 // //collections.example/_/_/ respectively:
335 // //collections.example/t=foo/ won't work because
336 // t=foo will be interpreted as a token "foo".
337 targetPath = targetPath[1:]
342 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
346 var collection *arvados.Collection
347 tokenResult := make(map[string]int)
348 for _, arv.ApiToken = range tokens {
350 collection, err = h.Config.Cache.Get(arv, targetID, forceReload)
355 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
356 switch srvErr.HttpStatusCode {
358 // Token broken or insufficient to
359 // retrieve collection
360 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
364 // Something more serious is wrong
365 statusCode, statusText = http.StatusInternalServerError, err.Error()
368 if collection == nil {
369 if pathToken || !credentialsOK {
370 // Either the URL is a "secret sharing link"
371 // that didn't work out (and asking the client
372 // for additional credentials would just be
373 // confusing), or we don't even accept
374 // credentials at this path.
375 statusCode = http.StatusNotFound
378 for _, t := range reqTokens {
379 if tokenResult[t] == 404 {
380 // The client provided valid token(s), but the
381 // collection was not found.
382 statusCode = http.StatusNotFound
386 // The client's token was invalid (e.g., expired), or
387 // the client didn't even provide one. Propagate the
388 // 401 to encourage the client to use a [different]
391 // TODO(TC): This response would be confusing to
392 // someone trying (anonymously) to download public
393 // data that has been deleted. Allow a referrer to
394 // provide this context somehow?
395 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
396 statusCode = http.StatusUnauthorized
400 kc, err := keepclient.MakeKeepClient(arv)
402 statusCode, statusText = http.StatusInternalServerError, err.Error()
407 if len(targetPath) > 0 {
408 basename = targetPath[len(targetPath)-1]
410 applyContentDispositionHdr(w, r, basename, attachment)
412 client := &arvados.Client{
413 APIHost: arv.ApiServer,
414 AuthToken: arv.ApiToken,
415 Insecure: arv.ApiInsecure,
417 fs, err := collection.FileSystem(client, kc)
419 statusCode, statusText = http.StatusInternalServerError, err.Error()
423 targetIsPDH := arvadosclient.PDHMatch(targetID)
424 if targetIsPDH && writeMethod[r.Method] {
425 statusCode, statusText = http.StatusMethodNotAllowed, errReadOnly.Error()
429 if webdavMethod[r.Method] {
430 if writeMethod[r.Method] {
431 // Save the collection only if/when all
432 // webdav->filesystem operations succeed --
433 // and send a 500 error if the modified
434 // collection can't be saved.
435 w = &updateOnSuccess{
437 update: func() error {
438 return h.Config.Cache.Update(client, *collection, fs)
442 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
443 FileSystem: &webdavFS{
445 writing: writeMethod[r.Method],
446 alwaysReadEOF: r.Method == "PROPFIND",
448 LockSystem: h.webdavLS,
449 Logger: func(_ *http.Request, err error) {
451 log.Printf("error from webdav handler: %q", err)
459 openPath := "/" + strings.Join(targetPath, "/")
460 if f, err := fs.Open(openPath); os.IsNotExist(err) {
461 // Requested non-existent path
462 statusCode = http.StatusNotFound
463 } else if err != nil {
464 // Some other (unexpected) error
465 statusCode, statusText = http.StatusInternalServerError, err.Error()
466 } else if stat, err := f.Stat(); err != nil {
467 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
468 statusCode, statusText = http.StatusInternalServerError, err.Error()
469 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
470 // If client requests ".../dirname", redirect to
471 // ".../dirname/". This way, relative links in the
472 // listing for "dirname" can always be "fnm", never
474 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
475 } else if stat.IsDir() {
476 h.serveDirectory(w, r, collection.Name, fs, openPath, stripParts)
478 http.ServeContent(w, r, basename, stat.ModTime(), f)
479 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
480 // If we wrote fewer bytes than expected, it's
481 // too late to change the real response code
482 // or send an error message to the client, but
483 // at least we can try to put some useful
484 // debugging info in the logs.
485 n, err := f.Read(make([]byte, 1024))
486 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)
492 var dirListingTemplate = `<!DOCTYPE HTML>
494 <META name="robots" content="NOINDEX">
495 <TITLE>{{ .Collection.Name }}</TITLE>
496 <STYLE type="text/css">
501 background-color: #D9EDF7;
502 border-radius: .25em;
513 font-family: monospace;
519 <H1>{{ .CollectionName }}</H1>
521 <P>This collection of data files is being shared with you through
522 Arvados. You can download individual files listed below. To download
523 the entire collection with wget, try:</P>
525 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL }}</PRE>
527 <H2>File Listing</H2>
531 {{range .Files}} <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{.Name}}">{{.Name}}</A></LI>{{end}}
534 <P>(No files; this collection is empty.)</P>
541 Arvados is a free and open source software bioinformatics platform.
542 To learn more, visit arvados.org.
543 Arvados is not responsible for the files listed on this page.
550 type fileListEnt struct {
555 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, stripParts int) {
556 var files []fileListEnt
557 var walk func(string) error
558 if !strings.HasSuffix(base, "/") {
561 walk = func(path string) error {
562 dirname := base + path
564 dirname = strings.TrimSuffix(dirname, "/")
566 d, err := fs.Open(dirname)
570 ents, err := d.Readdir(-1)
574 for _, ent := range ents {
576 err = walk(path + ent.Name() + "/")
581 files = append(files, fileListEnt{
582 Name: path + ent.Name(),
589 if err := walk(""); err != nil {
590 http.Error(w, err.Error(), http.StatusInternalServerError)
594 funcs := template.FuncMap{
595 "nbsp": func(s string) template.HTML {
596 return template.HTML(strings.Replace(s, " ", " ", -1))
599 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
601 http.Error(w, err.Error(), http.StatusInternalServerError)
604 sort.Slice(files, func(i, j int) bool {
605 return files[i].Name < files[j].Name
607 w.WriteHeader(http.StatusOK)
608 tmpl.Execute(w, map[string]interface{}{
609 "CollectionName": collectionName,
612 "StripParts": stripParts,
616 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
617 disposition := "inline"
619 disposition = "attachment"
621 if strings.ContainsRune(r.RequestURI, '?') {
622 // Help the UA realize that the filename is just
623 // "filename.txt", not
624 // "filename.txt?disposition=attachment".
626 // TODO(TC): Follow advice at RFC 6266 appendix D
627 disposition += "; filename=" + strconv.QuoteToASCII(filename)
629 if disposition != "inline" {
630 w.Header().Set("Content-Disposition", disposition)
634 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
635 if formToken := r.FormValue("api_token"); formToken != "" {
637 // It is not safe to copy the provided token
638 // into a cookie unless the current vhost
639 // (origin) serves only a single collection or
640 // we are in TrustAllContent mode.
641 w.WriteHeader(http.StatusBadRequest)
645 // The HttpOnly flag is necessary to prevent
646 // JavaScript code (included in, or loaded by, a page
647 // in the collection being served) from employing the
648 // user's token beyond reading other files in the same
649 // domain, i.e., same collection.
651 // The 303 redirect is necessary in the case of a GET
652 // request to avoid exposing the token in the Location
653 // bar, and in the case of a POST request to avoid
654 // raising warnings when the user refreshes the
656 http.SetCookie(w, &http.Cookie{
657 Name: "arvados_api_token",
658 Value: auth.EncodeTokenCookie([]byte(formToken)),
664 // Propagate query parameters (except api_token) from
665 // the original request.
666 redirQuery := r.URL.Query()
667 redirQuery.Del("api_token")
671 newu, err := u.Parse(location)
673 w.WriteHeader(http.StatusInternalServerError)
681 RawQuery: redirQuery.Encode(),
684 w.Header().Add("Location", redir)
685 w.WriteHeader(http.StatusSeeOther)
686 io.WriteString(w, `<A href="`)
687 io.WriteString(w, html.EscapeString(redir))
688 io.WriteString(w, `">Continue</A>`)