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"
31 clientPool *arvadosclient.ClientPool
33 healthHandler http.Handler
36 // parseCollectionIDFromDNSName returns a UUID or PDH if s begins with
37 // a UUID or URL-encoded PDH; otherwise "".
38 func parseCollectionIDFromDNSName(s string) string {
40 if i := strings.IndexRune(s, '.'); i >= 0 {
43 // Names like {uuid}--collections.example.com serve the same
44 // purpose as {uuid}.collections.example.com but can reduce
45 // cost/effort of using [additional] wildcard certificates.
46 if i := strings.Index(s, "--"); i >= 0 {
49 if arvadosclient.UUIDMatch(s) {
52 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
58 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
60 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
61 // PDH (even if it is a PDH with "+" replaced by " " or "-");
63 func parseCollectionIDFromURL(s string) string {
64 if arvadosclient.UUIDMatch(s) {
67 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
73 func (h *handler) setup() {
74 h.clientPool = arvadosclient.MakeClientPool()
76 keepclient.RefreshServiceDiscoveryOnSIGHUP()
78 h.healthHandler = &health.Handler{
79 Token: h.Config.ManagementToken,
84 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
88 cacheStats: h.Config.Cache.Stats(),
90 json.NewEncoder(w).Encode(status)
93 // ServeHTTP implements http.Handler.
94 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
95 h.setupOnce.Do(h.setup)
100 remoteAddr := r.RemoteAddr
101 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
102 remoteAddr = xff + "," + remoteAddr
105 w := httpserver.WrapResponseWriter(wOrig)
108 statusCode = w.WroteStatus()
109 } else if w.WroteStatus() == 0 {
110 w.WriteHeader(statusCode)
111 } else if w.WroteStatus() != statusCode {
112 httpserver.Log(r.RemoteAddr, "WARNING",
113 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
115 if statusText == "" {
116 statusText = http.StatusText(statusCode)
118 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
121 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
122 h.healthHandler.ServeHTTP(w, r)
126 if r.Method == "OPTIONS" {
127 method := r.Header.Get("Access-Control-Request-Method")
128 if method != "GET" && method != "POST" {
129 statusCode = http.StatusMethodNotAllowed
132 w.Header().Set("Access-Control-Allow-Headers", "Range")
133 w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
134 w.Header().Set("Access-Control-Allow-Origin", "*")
135 w.Header().Set("Access-Control-Max-Age", "86400")
136 statusCode = http.StatusOK
140 if r.Method != "GET" && r.Method != "POST" {
141 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
145 if r.Header.Get("Origin") != "" {
146 // Allow simple cross-origin requests without user
147 // credentials ("user credentials" as defined by CORS,
148 // i.e., cookies, HTTP authentication, and client-side
149 // SSL certificates. See
150 // http://www.w3.org/TR/cors/#user-credentials).
151 w.Header().Set("Access-Control-Allow-Origin", "*")
154 arv := h.clientPool.Get()
156 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
159 defer h.clientPool.Put(arv)
161 pathParts := strings.Split(r.URL.Path[1:], "/")
166 var reqTokens []string
169 credentialsOK := h.Config.TrustAllContent
171 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
174 } else if r.FormValue("disposition") == "attachment" {
178 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
179 // http://ID.collections.example/PATH...
181 } else if r.URL.Path == "/status.json" {
184 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
186 targetID = parseCollectionIDFromURL(pathParts[0][2:])
188 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
189 if len(pathParts) >= 4 && pathParts[1] == "download" {
190 // /collections/download/ID/TOKEN/PATH...
191 targetID = parseCollectionIDFromURL(pathParts[2])
192 tokens = []string{pathParts[3]}
196 // /collections/ID/PATH...
197 targetID = parseCollectionIDFromURL(pathParts[1])
198 tokens = h.Config.AnonymousTokens
204 statusCode = http.StatusNotFound
208 formToken := r.FormValue("api_token")
209 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
210 // The client provided an explicit token in the POST
211 // body. The Origin header indicates this *might* be
212 // an AJAX request, in which case redirect-with-cookie
213 // won't work: we should just serve the content in the
214 // POST response. This is safe because:
216 // * We're supplying an attachment, not inline
217 // content, so we don't need to convert the POST to
218 // a GET and avoid the "really resubmit form?"
221 // * The token isn't embedded in the URL, so we don't
222 // need to worry about bookmarks and copy/paste.
223 tokens = append(tokens, formToken)
224 } else if formToken != "" {
225 // The client provided an explicit token in the query
226 // string, or a form in POST body. We must put the
227 // token in an HttpOnly cookie, and redirect to the
228 // same URL with the query param redacted and method =
230 h.seeOtherWithCookie(w, r, "", credentialsOK)
234 targetPath := pathParts[stripParts:]
235 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
236 // http://ID.example/t=TOKEN/PATH...
237 // /c=ID/t=TOKEN/PATH...
239 // This form must only be used to pass scoped tokens
240 // that give permission for a single collection. See
241 // FormValue case above.
242 tokens = []string{targetPath[0][2:]}
244 targetPath = targetPath[1:]
250 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
252 tokens = append(reqTokens, h.Config.AnonymousTokens...)
255 if len(targetPath) > 0 && targetPath[0] == "_" {
256 // If a collection has a directory called "t=foo" or
257 // "_", it can be served at
258 // //collections.example/_/t=foo/ or
259 // //collections.example/_/_/ respectively:
260 // //collections.example/t=foo/ won't work because
261 // t=foo will be interpreted as a token "foo".
262 targetPath = targetPath[1:]
267 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
271 var collection *arvados.Collection
272 tokenResult := make(map[string]int)
273 for _, arv.ApiToken = range tokens {
275 collection, err = h.Config.Cache.Get(arv, targetID, forceReload)
280 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
281 switch srvErr.HttpStatusCode {
283 // Token broken or insufficient to
284 // retrieve collection
285 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
289 // Something more serious is wrong
290 statusCode, statusText = http.StatusInternalServerError, err.Error()
293 if collection == nil {
294 if pathToken || !credentialsOK {
295 // Either the URL is a "secret sharing link"
296 // that didn't work out (and asking the client
297 // for additional credentials would just be
298 // confusing), or we don't even accept
299 // credentials at this path.
300 statusCode = http.StatusNotFound
303 for _, t := range reqTokens {
304 if tokenResult[t] == 404 {
305 // The client provided valid token(s), but the
306 // collection was not found.
307 statusCode = http.StatusNotFound
311 // The client's token was invalid (e.g., expired), or
312 // the client didn't even provide one. Propagate the
313 // 401 to encourage the client to use a [different]
316 // TODO(TC): This response would be confusing to
317 // someone trying (anonymously) to download public
318 // data that has been deleted. Allow a referrer to
319 // provide this context somehow?
320 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
321 statusCode = http.StatusUnauthorized
325 kc, err := keepclient.MakeKeepClient(arv)
327 statusCode, statusText = http.StatusInternalServerError, err.Error()
331 basename := targetPath[len(targetPath)-1]
332 applyContentDispositionHdr(w, r, basename, attachment)
334 fs := collection.FileSystem(&arvados.Client{
335 APIHost: arv.ApiServer,
336 AuthToken: arv.ApiToken,
337 Insecure: arv.ApiInsecure,
339 openPath := "/" + strings.Join(targetPath, "/")
340 if f, err := fs.Open(openPath); os.IsNotExist(err) {
341 // Requested non-existent path
342 statusCode = http.StatusNotFound
343 } else if err != nil {
344 // Some other (unexpected) error
345 statusCode, statusText = http.StatusInternalServerError, err.Error()
346 } else if stat, err := f.Stat(); err != nil {
347 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
348 statusCode, statusText = http.StatusInternalServerError, err.Error()
349 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
350 // If client requests ".../dirname", redirect to
351 // ".../dirname/". This way, relative links in the
352 // listing for "dirname" can always be "fnm", never
354 h.seeOtherWithCookie(w, r, basename+"/", credentialsOK)
355 } else if stat.IsDir() {
356 h.serveDirectory(w, r, collection.Name, fs, openPath, stripParts)
358 http.ServeContent(w, r, basename, stat.ModTime(), f)
359 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
360 // If we wrote fewer bytes than expected, it's
361 // too late to change the real response code
362 // or send an error message to the client, but
363 // at least we can try to put some useful
364 // debugging info in the logs.
365 n, err := f.Read(make([]byte, 1024))
366 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)
372 var dirListingTemplate = `<!DOCTYPE HTML>
374 <META name="robots" content="NOINDEX">
375 <TITLE>{{ .Collection.Name }}</TITLE>
376 <STYLE type="text/css">
381 background-color: #D9EDF7;
382 border-radius: .25em;
393 font-family: monospace;
399 <H1>{{ .CollectionName }}</H1>
401 <P>This collection of data files is being shared with you through
402 Arvados. You can download individual files listed below. To download
403 the entire collection with wget, try:</P>
405 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL }}</PRE>
407 <H2>File Listing</H2>
411 {{range .Files}} <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{.Name}}">{{.Name}}</A></LI>{{end}}
414 <P>(No files; this collection is empty.)</P>
421 Arvados is a free and open source software bioinformatics platform.
422 To learn more, visit arvados.org.
423 Arvados is not responsible for the files listed on this page.
430 type fileListEnt struct {
435 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, stripParts int) {
436 var files []fileListEnt
437 var walk func(string) error
438 if !strings.HasSuffix(base, "/") {
441 walk = func(path string) error {
442 dirname := base + path
444 dirname = strings.TrimSuffix(dirname, "/")
446 d, err := fs.Open(dirname)
450 ents, err := d.Readdir(-1)
454 for _, ent := range ents {
456 err = walk(path + ent.Name() + "/")
461 files = append(files, fileListEnt{
462 Name: path + ent.Name(),
469 if err := walk(""); err != nil {
470 http.Error(w, err.Error(), http.StatusInternalServerError)
474 funcs := template.FuncMap{
475 "nbsp": func(s string) template.HTML {
476 return template.HTML(strings.Replace(s, " ", " ", -1))
479 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
481 http.Error(w, err.Error(), http.StatusInternalServerError)
484 sort.Slice(files, func(i, j int) bool {
485 return files[i].Name < files[j].Name
487 w.WriteHeader(http.StatusOK)
488 tmpl.Execute(w, map[string]interface{}{
489 "CollectionName": collectionName,
492 "StripParts": stripParts,
496 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
497 disposition := "inline"
499 disposition = "attachment"
501 if strings.ContainsRune(r.RequestURI, '?') {
502 // Help the UA realize that the filename is just
503 // "filename.txt", not
504 // "filename.txt?disposition=attachment".
506 // TODO(TC): Follow advice at RFC 6266 appendix D
507 disposition += "; filename=" + strconv.QuoteToASCII(filename)
509 if disposition != "inline" {
510 w.Header().Set("Content-Disposition", disposition)
514 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
516 // It is not safe to copy the provided token
517 // into a cookie unless the current vhost
518 // (origin) serves only a single collection or
519 // we are in TrustAllContent mode.
520 w.WriteHeader(http.StatusBadRequest)
524 if formToken := r.FormValue("api_token"); formToken != "" {
525 // The HttpOnly flag is necessary to prevent
526 // JavaScript code (included in, or loaded by, a page
527 // in the collection being served) from employing the
528 // user's token beyond reading other files in the same
529 // domain, i.e., same collection.
531 // The 303 redirect is necessary in the case of a GET
532 // request to avoid exposing the token in the Location
533 // bar, and in the case of a POST request to avoid
534 // raising warnings when the user refreshes the
537 http.SetCookie(w, &http.Cookie{
538 Name: "arvados_api_token",
539 Value: auth.EncodeTokenCookie([]byte(formToken)),
545 // Propagate query parameters (except api_token) from
546 // the original request.
547 redirQuery := r.URL.Query()
548 redirQuery.Del("api_token")
552 newu, err := u.Parse(location)
554 w.WriteHeader(http.StatusInternalServerError)
562 RawQuery: redirQuery.Encode(),
565 w.Header().Add("Location", redir)
566 w.WriteHeader(http.StatusSeeOther)
567 io.WriteString(w, `<A href="`)
568 io.WriteString(w, html.EscapeString(redir))
569 io.WriteString(w, `">Continue</A>`)