1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
21 "git.curoverse.com/arvados.git/sdk/go/arvados"
22 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
23 "git.curoverse.com/arvados.git/sdk/go/auth"
24 "git.curoverse.com/arvados.git/sdk/go/health"
25 "git.curoverse.com/arvados.git/sdk/go/httpserver"
26 "git.curoverse.com/arvados.git/sdk/go/keepclient"
27 "golang.org/x/net/webdav"
32 clientPool *arvadosclient.ClientPool
34 healthHandler http.Handler
35 webdavLS webdav.LockSystem
38 // parseCollectionIDFromDNSName returns a UUID or PDH if s begins with
39 // a UUID or URL-encoded PDH; otherwise "".
40 func parseCollectionIDFromDNSName(s string) string {
42 if i := strings.IndexRune(s, '.'); i >= 0 {
45 // Names like {uuid}--collections.example.com serve the same
46 // purpose as {uuid}.collections.example.com but can reduce
47 // cost/effort of using [additional] wildcard certificates.
48 if i := strings.Index(s, "--"); i >= 0 {
51 if arvadosclient.UUIDMatch(s) {
54 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
60 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
62 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
63 // PDH (even if it is a PDH with "+" replaced by " " or "-");
65 func parseCollectionIDFromURL(s string) string {
66 if arvadosclient.UUIDMatch(s) {
69 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
75 func (h *handler) setup() {
76 h.clientPool = arvadosclient.MakeClientPool()
78 keepclient.RefreshServiceDiscoveryOnSIGHUP()
80 h.healthHandler = &health.Handler{
81 Token: h.Config.ManagementToken,
85 // Even though we don't accept LOCK requests, every webdav
86 // handler must have a non-nil LockSystem.
87 h.webdavLS = &noLockSystem{}
90 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
94 cacheStats: h.Config.Cache.Stats(),
96 json.NewEncoder(w).Encode(status)
100 webdavMethod = map[string]bool{
104 browserMethod = map[string]bool{
111 // ServeHTTP implements http.Handler.
112 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
113 h.setupOnce.Do(h.setup)
116 var statusText string
118 remoteAddr := r.RemoteAddr
119 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
120 remoteAddr = xff + "," + remoteAddr
123 w := httpserver.WrapResponseWriter(wOrig)
126 statusCode = w.WroteStatus()
127 } else if w.WroteStatus() == 0 {
128 w.WriteHeader(statusCode)
129 } else if w.WroteStatus() != statusCode {
130 httpserver.Log(r.RemoteAddr, "WARNING",
131 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
133 if statusText == "" {
134 statusText = http.StatusText(statusCode)
136 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
139 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
140 h.healthHandler.ServeHTTP(w, r)
144 if method := r.Header.Get("Access-Control-Request-Method"); method != "" && r.Method == "OPTIONS" {
145 if !browserMethod[method] && !webdavMethod[method] {
146 statusCode = http.StatusMethodNotAllowed
149 w.Header().Set("Access-Control-Allow-Headers", "Range")
150 w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PROPFIND")
151 w.Header().Set("Access-Control-Allow-Origin", "*")
152 w.Header().Set("Access-Control-Max-Age", "86400")
153 statusCode = http.StatusOK
157 if !browserMethod[r.Method] && !webdavMethod[r.Method] {
158 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
162 if r.Header.Get("Origin") != "" {
163 // Allow simple cross-origin requests without user
164 // credentials ("user credentials" as defined by CORS,
165 // i.e., cookies, HTTP authentication, and client-side
166 // SSL certificates. See
167 // http://www.w3.org/TR/cors/#user-credentials).
168 w.Header().Set("Access-Control-Allow-Origin", "*")
169 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
172 arv := h.clientPool.Get()
174 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
177 defer h.clientPool.Put(arv)
179 pathParts := strings.Split(r.URL.Path[1:], "/")
184 var reqTokens []string
187 credentialsOK := h.Config.TrustAllContent
189 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
192 } else if r.FormValue("disposition") == "attachment" {
196 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
197 // http://ID.collections.example/PATH...
199 } else if r.URL.Path == "/status.json" {
202 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
204 targetID = parseCollectionIDFromURL(pathParts[0][2:])
206 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
207 if len(pathParts) >= 4 && pathParts[1] == "download" {
208 // /collections/download/ID/TOKEN/PATH...
209 targetID = parseCollectionIDFromURL(pathParts[2])
210 tokens = []string{pathParts[3]}
214 // /collections/ID/PATH...
215 targetID = parseCollectionIDFromURL(pathParts[1])
216 tokens = h.Config.AnonymousTokens
222 statusCode = http.StatusNotFound
226 formToken := r.FormValue("api_token")
227 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
228 // The client provided an explicit token in the POST
229 // body. The Origin header indicates this *might* be
230 // an AJAX request, in which case redirect-with-cookie
231 // won't work: we should just serve the content in the
232 // POST response. This is safe because:
234 // * We're supplying an attachment, not inline
235 // content, so we don't need to convert the POST to
236 // a GET and avoid the "really resubmit form?"
239 // * The token isn't embedded in the URL, so we don't
240 // need to worry about bookmarks and copy/paste.
241 tokens = append(tokens, formToken)
242 } else if formToken != "" && browserMethod[r.Method] {
243 // The client provided an explicit token in the query
244 // string, or a form in POST body. We must put the
245 // token in an HttpOnly cookie, and redirect to the
246 // same URL with the query param redacted and method =
248 h.seeOtherWithCookie(w, r, "", credentialsOK)
252 targetPath := pathParts[stripParts:]
253 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
254 // http://ID.example/t=TOKEN/PATH...
255 // /c=ID/t=TOKEN/PATH...
257 // This form must only be used to pass scoped tokens
258 // that give permission for a single collection. See
259 // FormValue case above.
260 tokens = []string{targetPath[0][2:]}
262 targetPath = targetPath[1:]
268 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
270 tokens = append(reqTokens, h.Config.AnonymousTokens...)
273 if len(targetPath) > 0 && targetPath[0] == "_" {
274 // If a collection has a directory called "t=foo" or
275 // "_", it can be served at
276 // //collections.example/_/t=foo/ or
277 // //collections.example/_/_/ respectively:
278 // //collections.example/t=foo/ won't work because
279 // t=foo will be interpreted as a token "foo".
280 targetPath = targetPath[1:]
285 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
289 var collection *arvados.Collection
290 tokenResult := make(map[string]int)
291 for _, arv.ApiToken = range tokens {
293 collection, err = h.Config.Cache.Get(arv, targetID, forceReload)
298 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
299 switch srvErr.HttpStatusCode {
301 // Token broken or insufficient to
302 // retrieve collection
303 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
307 // Something more serious is wrong
308 statusCode, statusText = http.StatusInternalServerError, err.Error()
311 if collection == nil {
312 if pathToken || !credentialsOK {
313 // Either the URL is a "secret sharing link"
314 // that didn't work out (and asking the client
315 // for additional credentials would just be
316 // confusing), or we don't even accept
317 // credentials at this path.
318 statusCode = http.StatusNotFound
321 for _, t := range reqTokens {
322 if tokenResult[t] == 404 {
323 // The client provided valid token(s), but the
324 // collection was not found.
325 statusCode = http.StatusNotFound
329 // The client's token was invalid (e.g., expired), or
330 // the client didn't even provide one. Propagate the
331 // 401 to encourage the client to use a [different]
334 // TODO(TC): This response would be confusing to
335 // someone trying (anonymously) to download public
336 // data that has been deleted. Allow a referrer to
337 // provide this context somehow?
338 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
339 statusCode = http.StatusUnauthorized
343 kc, err := keepclient.MakeKeepClient(arv)
345 statusCode, statusText = http.StatusInternalServerError, err.Error()
349 basename := targetPath[len(targetPath)-1]
350 applyContentDispositionHdr(w, r, basename, attachment)
352 fs := collection.FileSystem(&arvados.Client{
353 APIHost: arv.ApiServer,
354 AuthToken: arv.ApiToken,
355 Insecure: arv.ApiInsecure,
357 if webdavMethod[r.Method] {
359 Prefix: "/" + strings.Join(pathParts[:stripParts], "/"),
360 FileSystem: &webdavFS{httpfs: fs},
361 LockSystem: h.webdavLS,
362 Logger: func(_ *http.Request, err error) {
363 if os.IsNotExist(err) {
364 statusCode, statusText = http.StatusNotFound, err.Error()
365 } else if err != nil {
366 statusCode, statusText = http.StatusInternalServerError, err.Error()
374 openPath := "/" + strings.Join(targetPath, "/")
375 if f, err := fs.Open(openPath); os.IsNotExist(err) {
376 // Requested non-existent path
377 statusCode = http.StatusNotFound
378 } else if err != nil {
379 // Some other (unexpected) error
380 statusCode, statusText = http.StatusInternalServerError, err.Error()
381 } else if stat, err := f.Stat(); err != nil {
382 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
383 statusCode, statusText = http.StatusInternalServerError, err.Error()
384 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
385 // If client requests ".../dirname", redirect to
386 // ".../dirname/". This way, relative links in the
387 // listing for "dirname" can always be "fnm", never
389 h.seeOtherWithCookie(w, r, basename+"/", credentialsOK)
390 } else if stat.IsDir() {
391 h.serveDirectory(w, r, collection.Name, fs, openPath, stripParts)
393 http.ServeContent(w, r, basename, stat.ModTime(), f)
394 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
395 // If we wrote fewer bytes than expected, it's
396 // too late to change the real response code
397 // or send an error message to the client, but
398 // at least we can try to put some useful
399 // debugging info in the logs.
400 n, err := f.Read(make([]byte, 1024))
401 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)
407 var dirListingTemplate = `<!DOCTYPE HTML>
409 <META name="robots" content="NOINDEX">
410 <TITLE>{{ .Collection.Name }}</TITLE>
411 <STYLE type="text/css">
416 background-color: #D9EDF7;
417 border-radius: .25em;
428 font-family: monospace;
434 <H1>{{ .CollectionName }}</H1>
436 <P>This collection of data files is being shared with you through
437 Arvados. You can download individual files listed below. To download
438 the entire collection with wget, try:</P>
440 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL }}</PRE>
442 <H2>File Listing</H2>
446 {{range .Files}} <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{.Name}}">{{.Name}}</A></LI>{{end}}
449 <P>(No files; this collection is empty.)</P>
456 Arvados is a free and open source software bioinformatics platform.
457 To learn more, visit arvados.org.
458 Arvados is not responsible for the files listed on this page.
465 type fileListEnt struct {
470 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, stripParts int) {
471 var files []fileListEnt
472 var walk func(string) error
473 if !strings.HasSuffix(base, "/") {
476 walk = func(path string) error {
477 dirname := base + path
479 dirname = strings.TrimSuffix(dirname, "/")
481 d, err := fs.Open(dirname)
485 ents, err := d.Readdir(-1)
489 for _, ent := range ents {
491 err = walk(path + ent.Name() + "/")
496 files = append(files, fileListEnt{
497 Name: path + ent.Name(),
504 if err := walk(""); err != nil {
505 http.Error(w, err.Error(), http.StatusInternalServerError)
509 funcs := template.FuncMap{
510 "nbsp": func(s string) template.HTML {
511 return template.HTML(strings.Replace(s, " ", " ", -1))
514 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
516 http.Error(w, err.Error(), http.StatusInternalServerError)
519 sort.Slice(files, func(i, j int) bool {
520 return files[i].Name < files[j].Name
522 w.WriteHeader(http.StatusOK)
523 tmpl.Execute(w, map[string]interface{}{
524 "CollectionName": collectionName,
527 "StripParts": stripParts,
531 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
532 disposition := "inline"
534 disposition = "attachment"
536 if strings.ContainsRune(r.RequestURI, '?') {
537 // Help the UA realize that the filename is just
538 // "filename.txt", not
539 // "filename.txt?disposition=attachment".
541 // TODO(TC): Follow advice at RFC 6266 appendix D
542 disposition += "; filename=" + strconv.QuoteToASCII(filename)
544 if disposition != "inline" {
545 w.Header().Set("Content-Disposition", disposition)
549 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
551 // It is not safe to copy the provided token
552 // into a cookie unless the current vhost
553 // (origin) serves only a single collection or
554 // we are in TrustAllContent mode.
555 w.WriteHeader(http.StatusBadRequest)
559 if formToken := r.FormValue("api_token"); formToken != "" {
560 // The HttpOnly flag is necessary to prevent
561 // JavaScript code (included in, or loaded by, a page
562 // in the collection being served) from employing the
563 // user's token beyond reading other files in the same
564 // domain, i.e., same collection.
566 // The 303 redirect is necessary in the case of a GET
567 // request to avoid exposing the token in the Location
568 // bar, and in the case of a POST request to avoid
569 // raising warnings when the user refreshes the
572 http.SetCookie(w, &http.Cookie{
573 Name: "arvados_api_token",
574 Value: auth.EncodeTokenCookie([]byte(formToken)),
580 // Propagate query parameters (except api_token) from
581 // the original request.
582 redirQuery := r.URL.Query()
583 redirQuery.Del("api_token")
587 newu, err := u.Parse(location)
589 w.WriteHeader(http.StatusInternalServerError)
597 RawQuery: redirQuery.Encode(),
600 w.Header().Add("Location", redir)
601 w.WriteHeader(http.StatusSeeOther)
602 io.WriteString(w, `<A href="`)
603 io.WriteString(w, html.EscapeString(redir))
604 io.WriteString(w, `">Continue</A>`)