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) {
95 cacheStats: h.Config.Cache.Stats(),
97 json.NewEncoder(w).Encode(status)
100 // updateOnSuccess wraps httpserver.ResponseWriter. If the handler
101 // sends an HTTP header indicating success, updateOnSuccess first
102 // calls the provided update func. If the update func fails, a 500
103 // response is sent, and the status code and body sent by the handler
104 // are ignored (all response writes return the update error).
105 type updateOnSuccess struct {
106 httpserver.ResponseWriter
112 func (uos *updateOnSuccess) Write(p []byte) (int, error) {
117 uos.WriteHeader(http.StatusOK)
119 return uos.ResponseWriter.Write(p)
122 func (uos *updateOnSuccess) WriteHeader(code int) {
124 uos.sentHeader = true
125 if code >= 200 && code < 400 {
126 if uos.err = uos.update(); uos.err != nil {
127 code := http.StatusInternalServerError
128 if err, ok := uos.err.(*arvados.TransactionError); ok {
129 code = err.StatusCode
131 log.Printf("update() changes response to HTTP %d: %T %q", code, uos.err, uos.err)
132 http.Error(uos.ResponseWriter, uos.err.Error(), code)
137 uos.ResponseWriter.WriteHeader(code)
141 writeMethod = map[string]bool{
149 webdavMethod = map[string]bool{
159 browserMethod = map[string]bool{
166 // ServeHTTP implements http.Handler.
167 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
168 h.setupOnce.Do(h.setup)
171 var statusText string
173 remoteAddr := r.RemoteAddr
174 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
175 remoteAddr = xff + "," + remoteAddr
178 w := httpserver.WrapResponseWriter(wOrig)
181 statusCode = w.WroteStatus()
182 } else if w.WroteStatus() == 0 {
183 w.WriteHeader(statusCode)
184 } else if w.WroteStatus() != statusCode {
185 httpserver.Log(r.RemoteAddr, "WARNING",
186 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
188 if statusText == "" {
189 statusText = http.StatusText(statusCode)
191 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
194 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
195 h.healthHandler.ServeHTTP(w, r)
199 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
200 if !browserMethod[method] && !webdavMethod[method] {
201 statusCode = http.StatusMethodNotAllowed
204 w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Range")
205 w.Header().Set("Access-Control-Allow-Methods", "COPY, DELETE, GET, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PUT, RMCOL")
206 w.Header().Set("Access-Control-Allow-Origin", "*")
207 w.Header().Set("Access-Control-Max-Age", "86400")
208 statusCode = http.StatusOK
212 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
213 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
217 if r.Header.Get("Origin") != "" {
218 // Allow simple cross-origin requests without user
219 // credentials ("user credentials" as defined by CORS,
220 // i.e., cookies, HTTP authentication, and client-side
221 // SSL certificates. See
222 // http://www.w3.org/TR/cors/#user-credentials).
223 w.Header().Set("Access-Control-Allow-Origin", "*")
224 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
227 arv := h.clientPool.Get()
229 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
232 defer h.clientPool.Put(arv)
234 pathParts := strings.Split(r.URL.Path[1:], "/")
239 var reqTokens []string
242 credentialsOK := h.Config.TrustAllContent
244 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
247 } else if r.FormValue("disposition") == "attachment" {
251 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
252 // http://ID.collections.example/PATH...
254 } else if r.URL.Path == "/status.json" {
257 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
259 targetID = parseCollectionIDFromURL(pathParts[0][2:])
261 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
262 if len(pathParts) >= 4 && pathParts[1] == "download" {
263 // /collections/download/ID/TOKEN/PATH...
264 targetID = parseCollectionIDFromURL(pathParts[2])
265 tokens = []string{pathParts[3]}
269 // /collections/ID/PATH...
270 targetID = parseCollectionIDFromURL(pathParts[1])
271 tokens = h.Config.AnonymousTokens
277 statusCode = http.StatusNotFound
281 formToken := r.FormValue("api_token")
282 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
283 // The client provided an explicit token in the POST
284 // body. The Origin header indicates this *might* be
285 // an AJAX request, in which case redirect-with-cookie
286 // won't work: we should just serve the content in the
287 // POST response. This is safe because:
289 // * We're supplying an attachment, not inline
290 // content, so we don't need to convert the POST to
291 // a GET and avoid the "really resubmit form?"
294 // * The token isn't embedded in the URL, so we don't
295 // need to worry about bookmarks and copy/paste.
296 tokens = append(tokens, formToken)
297 } else if formToken != "" && browserMethod[r.Method] {
298 // The client provided an explicit token in the query
299 // string, or a form in POST body. We must put the
300 // token in an HttpOnly cookie, and redirect to the
301 // same URL with the query param redacted and method =
303 h.seeOtherWithCookie(w, r, "", credentialsOK)
307 targetPath := pathParts[stripParts:]
308 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
309 // http://ID.example/t=TOKEN/PATH...
310 // /c=ID/t=TOKEN/PATH...
312 // This form must only be used to pass scoped tokens
313 // that give permission for a single collection. See
314 // FormValue case above.
315 tokens = []string{targetPath[0][2:]}
317 targetPath = targetPath[1:]
323 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
325 tokens = append(reqTokens, h.Config.AnonymousTokens...)
328 if len(targetPath) > 0 && targetPath[0] == "_" {
329 // If a collection has a directory called "t=foo" or
330 // "_", it can be served at
331 // //collections.example/_/t=foo/ or
332 // //collections.example/_/_/ respectively:
333 // //collections.example/t=foo/ won't work because
334 // t=foo will be interpreted as a token "foo".
335 targetPath = targetPath[1:]
340 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
344 var collection *arvados.Collection
345 tokenResult := make(map[string]int)
346 for _, arv.ApiToken = range tokens {
348 collection, err = h.Config.Cache.Get(arv, targetID, forceReload)
353 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
354 switch srvErr.HttpStatusCode {
356 // Token broken or insufficient to
357 // retrieve collection
358 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
362 // Something more serious is wrong
363 statusCode, statusText = http.StatusInternalServerError, err.Error()
366 if collection == nil {
367 if pathToken || !credentialsOK {
368 // Either the URL is a "secret sharing link"
369 // that didn't work out (and asking the client
370 // for additional credentials would just be
371 // confusing), or we don't even accept
372 // credentials at this path.
373 statusCode = http.StatusNotFound
376 for _, t := range reqTokens {
377 if tokenResult[t] == 404 {
378 // The client provided valid token(s), but the
379 // collection was not found.
380 statusCode = http.StatusNotFound
384 // The client's token was invalid (e.g., expired), or
385 // the client didn't even provide one. Propagate the
386 // 401 to encourage the client to use a [different]
389 // TODO(TC): This response would be confusing to
390 // someone trying (anonymously) to download public
391 // data that has been deleted. Allow a referrer to
392 // provide this context somehow?
393 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
394 statusCode = http.StatusUnauthorized
398 kc, err := keepclient.MakeKeepClient(arv)
400 statusCode, statusText = http.StatusInternalServerError, err.Error()
405 if len(targetPath) > 0 {
406 basename = targetPath[len(targetPath)-1]
408 applyContentDispositionHdr(w, r, basename, attachment)
410 client := &arvados.Client{
411 APIHost: arv.ApiServer,
412 AuthToken: arv.ApiToken,
413 Insecure: arv.ApiInsecure,
415 fs, err := collection.FileSystem(client, kc)
417 statusCode, statusText = http.StatusInternalServerError, err.Error()
420 if webdavMethod[r.Method] {
421 writing := !arvadosclient.PDHMatch(targetID) && writeMethod[r.Method]
423 // Save the collection only if/when all
424 // webdav->filesystem operations succeed --
425 // and send a 500 error if the modified
426 // collection can't be saved.
427 w = &updateOnSuccess{
429 update: func() error {
430 return h.Config.Cache.Update(client, *collection, fs)
434 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
435 FileSystem: &webdavFS{
439 LockSystem: h.webdavLS,
440 Logger: func(_ *http.Request, err error) {
442 log.Printf("error from webdav handler: %q", err)
450 openPath := "/" + strings.Join(targetPath, "/")
451 if f, err := fs.Open(openPath); os.IsNotExist(err) {
452 // Requested non-existent path
453 statusCode = http.StatusNotFound
454 } else if err != nil {
455 // Some other (unexpected) error
456 statusCode, statusText = http.StatusInternalServerError, err.Error()
457 } else if stat, err := f.Stat(); err != nil {
458 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
459 statusCode, statusText = http.StatusInternalServerError, err.Error()
460 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
461 // If client requests ".../dirname", redirect to
462 // ".../dirname/". This way, relative links in the
463 // listing for "dirname" can always be "fnm", never
465 h.seeOtherWithCookie(w, r, r.URL.Path+"/", credentialsOK)
466 } else if stat.IsDir() {
467 h.serveDirectory(w, r, collection.Name, fs, openPath, stripParts)
469 http.ServeContent(w, r, basename, stat.ModTime(), f)
470 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
471 // If we wrote fewer bytes than expected, it's
472 // too late to change the real response code
473 // or send an error message to the client, but
474 // at least we can try to put some useful
475 // debugging info in the logs.
476 n, err := f.Read(make([]byte, 1024))
477 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)
483 var dirListingTemplate = `<!DOCTYPE HTML>
485 <META name="robots" content="NOINDEX">
486 <TITLE>{{ .Collection.Name }}</TITLE>
487 <STYLE type="text/css">
492 background-color: #D9EDF7;
493 border-radius: .25em;
504 font-family: monospace;
510 <H1>{{ .CollectionName }}</H1>
512 <P>This collection of data files is being shared with you through
513 Arvados. You can download individual files listed below. To download
514 the entire collection with wget, try:</P>
516 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL }}</PRE>
518 <H2>File Listing</H2>
522 {{range .Files}} <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{.Name}}">{{.Name}}</A></LI>{{end}}
525 <P>(No files; this collection is empty.)</P>
532 Arvados is a free and open source software bioinformatics platform.
533 To learn more, visit arvados.org.
534 Arvados is not responsible for the files listed on this page.
541 type fileListEnt struct {
546 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, stripParts int) {
547 var files []fileListEnt
548 var walk func(string) error
549 if !strings.HasSuffix(base, "/") {
552 walk = func(path string) error {
553 dirname := base + path
555 dirname = strings.TrimSuffix(dirname, "/")
557 d, err := fs.Open(dirname)
561 ents, err := d.Readdir(-1)
565 for _, ent := range ents {
567 err = walk(path + ent.Name() + "/")
572 files = append(files, fileListEnt{
573 Name: path + ent.Name(),
580 if err := walk(""); err != nil {
581 http.Error(w, err.Error(), http.StatusInternalServerError)
585 funcs := template.FuncMap{
586 "nbsp": func(s string) template.HTML {
587 return template.HTML(strings.Replace(s, " ", " ", -1))
590 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
592 http.Error(w, err.Error(), http.StatusInternalServerError)
595 sort.Slice(files, func(i, j int) bool {
596 return files[i].Name < files[j].Name
598 w.WriteHeader(http.StatusOK)
599 tmpl.Execute(w, map[string]interface{}{
600 "CollectionName": collectionName,
603 "StripParts": stripParts,
607 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
608 disposition := "inline"
610 disposition = "attachment"
612 if strings.ContainsRune(r.RequestURI, '?') {
613 // Help the UA realize that the filename is just
614 // "filename.txt", not
615 // "filename.txt?disposition=attachment".
617 // TODO(TC): Follow advice at RFC 6266 appendix D
618 disposition += "; filename=" + strconv.QuoteToASCII(filename)
620 if disposition != "inline" {
621 w.Header().Set("Content-Disposition", disposition)
625 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
626 if formToken := r.FormValue("api_token"); formToken != "" {
628 // It is not safe to copy the provided token
629 // into a cookie unless the current vhost
630 // (origin) serves only a single collection or
631 // we are in TrustAllContent mode.
632 w.WriteHeader(http.StatusBadRequest)
636 // The HttpOnly flag is necessary to prevent
637 // JavaScript code (included in, or loaded by, a page
638 // in the collection being served) from employing the
639 // user's token beyond reading other files in the same
640 // domain, i.e., same collection.
642 // The 303 redirect is necessary in the case of a GET
643 // request to avoid exposing the token in the Location
644 // bar, and in the case of a POST request to avoid
645 // raising warnings when the user refreshes the
647 http.SetCookie(w, &http.Cookie{
648 Name: "arvados_api_token",
649 Value: auth.EncodeTokenCookie([]byte(formToken)),
655 // Propagate query parameters (except api_token) from
656 // the original request.
657 redirQuery := r.URL.Query()
658 redirQuery.Del("api_token")
662 newu, err := u.Parse(location)
664 w.WriteHeader(http.StatusInternalServerError)
672 RawQuery: redirQuery.Encode(),
675 w.Header().Add("Location", redir)
676 w.WriteHeader(http.StatusSeeOther)
677 io.WriteString(w, `<A href="`)
678 io.WriteString(w, html.EscapeString(redir))
679 io.WriteString(w, `">Continue</A>`)