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", "*")
152 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
155 arv := h.clientPool.Get()
157 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
160 defer h.clientPool.Put(arv)
162 pathParts := strings.Split(r.URL.Path[1:], "/")
167 var reqTokens []string
170 credentialsOK := h.Config.TrustAllContent
172 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
175 } else if r.FormValue("disposition") == "attachment" {
179 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
180 // http://ID.collections.example/PATH...
182 } else if r.URL.Path == "/status.json" {
185 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
187 targetID = parseCollectionIDFromURL(pathParts[0][2:])
189 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
190 if len(pathParts) >= 4 && pathParts[1] == "download" {
191 // /collections/download/ID/TOKEN/PATH...
192 targetID = parseCollectionIDFromURL(pathParts[2])
193 tokens = []string{pathParts[3]}
197 // /collections/ID/PATH...
198 targetID = parseCollectionIDFromURL(pathParts[1])
199 tokens = h.Config.AnonymousTokens
205 statusCode = http.StatusNotFound
209 formToken := r.FormValue("api_token")
210 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
211 // The client provided an explicit token in the POST
212 // body. The Origin header indicates this *might* be
213 // an AJAX request, in which case redirect-with-cookie
214 // won't work: we should just serve the content in the
215 // POST response. This is safe because:
217 // * We're supplying an attachment, not inline
218 // content, so we don't need to convert the POST to
219 // a GET and avoid the "really resubmit form?"
222 // * The token isn't embedded in the URL, so we don't
223 // need to worry about bookmarks and copy/paste.
224 tokens = append(tokens, formToken)
225 } else if formToken != "" {
226 // The client provided an explicit token in the query
227 // string, or a form in POST body. We must put the
228 // token in an HttpOnly cookie, and redirect to the
229 // same URL with the query param redacted and method =
231 h.seeOtherWithCookie(w, r, "", credentialsOK)
235 targetPath := pathParts[stripParts:]
236 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
237 // http://ID.example/t=TOKEN/PATH...
238 // /c=ID/t=TOKEN/PATH...
240 // This form must only be used to pass scoped tokens
241 // that give permission for a single collection. See
242 // FormValue case above.
243 tokens = []string{targetPath[0][2:]}
245 targetPath = targetPath[1:]
251 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
253 tokens = append(reqTokens, h.Config.AnonymousTokens...)
256 if len(targetPath) > 0 && targetPath[0] == "_" {
257 // If a collection has a directory called "t=foo" or
258 // "_", it can be served at
259 // //collections.example/_/t=foo/ or
260 // //collections.example/_/_/ respectively:
261 // //collections.example/t=foo/ won't work because
262 // t=foo will be interpreted as a token "foo".
263 targetPath = targetPath[1:]
268 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
272 var collection *arvados.Collection
273 tokenResult := make(map[string]int)
274 for _, arv.ApiToken = range tokens {
276 collection, err = h.Config.Cache.Get(arv, targetID, forceReload)
281 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
282 switch srvErr.HttpStatusCode {
284 // Token broken or insufficient to
285 // retrieve collection
286 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
290 // Something more serious is wrong
291 statusCode, statusText = http.StatusInternalServerError, err.Error()
294 if collection == nil {
295 if pathToken || !credentialsOK {
296 // Either the URL is a "secret sharing link"
297 // that didn't work out (and asking the client
298 // for additional credentials would just be
299 // confusing), or we don't even accept
300 // credentials at this path.
301 statusCode = http.StatusNotFound
304 for _, t := range reqTokens {
305 if tokenResult[t] == 404 {
306 // The client provided valid token(s), but the
307 // collection was not found.
308 statusCode = http.StatusNotFound
312 // The client's token was invalid (e.g., expired), or
313 // the client didn't even provide one. Propagate the
314 // 401 to encourage the client to use a [different]
317 // TODO(TC): This response would be confusing to
318 // someone trying (anonymously) to download public
319 // data that has been deleted. Allow a referrer to
320 // provide this context somehow?
321 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
322 statusCode = http.StatusUnauthorized
326 kc, err := keepclient.MakeKeepClient(arv)
328 statusCode, statusText = http.StatusInternalServerError, err.Error()
332 basename := targetPath[len(targetPath)-1]
333 applyContentDispositionHdr(w, r, basename, attachment)
335 fs := collection.FileSystem(&arvados.Client{
336 APIHost: arv.ApiServer,
337 AuthToken: arv.ApiToken,
338 Insecure: arv.ApiInsecure,
340 openPath := "/" + strings.Join(targetPath, "/")
341 if f, err := fs.Open(openPath); os.IsNotExist(err) {
342 // Requested non-existent path
343 statusCode = http.StatusNotFound
344 } else if err != nil {
345 // Some other (unexpected) error
346 statusCode, statusText = http.StatusInternalServerError, err.Error()
347 } else if stat, err := f.Stat(); err != nil {
348 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
349 statusCode, statusText = http.StatusInternalServerError, err.Error()
350 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
351 // If client requests ".../dirname", redirect to
352 // ".../dirname/". This way, relative links in the
353 // listing for "dirname" can always be "fnm", never
355 h.seeOtherWithCookie(w, r, basename+"/", credentialsOK)
356 } else if stat.IsDir() {
357 h.serveDirectory(w, r, collection.Name, fs, openPath, stripParts)
359 http.ServeContent(w, r, basename, stat.ModTime(), f)
360 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
361 // If we wrote fewer bytes than expected, it's
362 // too late to change the real response code
363 // or send an error message to the client, but
364 // at least we can try to put some useful
365 // debugging info in the logs.
366 n, err := f.Read(make([]byte, 1024))
367 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)
373 var dirListingTemplate = `<!DOCTYPE HTML>
375 <META name="robots" content="NOINDEX">
376 <TITLE>{{ .Collection.Name }}</TITLE>
377 <STYLE type="text/css">
382 background-color: #D9EDF7;
383 border-radius: .25em;
394 font-family: monospace;
400 <H1>{{ .CollectionName }}</H1>
402 <P>This collection of data files is being shared with you through
403 Arvados. You can download individual files listed below. To download
404 the entire collection with wget, try:</P>
406 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL }}</PRE>
408 <H2>File Listing</H2>
412 {{range .Files}} <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{.Name}}">{{.Name}}</A></LI>{{end}}
415 <P>(No files; this collection is empty.)</P>
422 Arvados is a free and open source software bioinformatics platform.
423 To learn more, visit arvados.org.
424 Arvados is not responsible for the files listed on this page.
431 type fileListEnt struct {
436 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, stripParts int) {
437 var files []fileListEnt
438 var walk func(string) error
439 if !strings.HasSuffix(base, "/") {
442 walk = func(path string) error {
443 dirname := base + path
445 dirname = strings.TrimSuffix(dirname, "/")
447 d, err := fs.Open(dirname)
451 ents, err := d.Readdir(-1)
455 for _, ent := range ents {
457 err = walk(path + ent.Name() + "/")
462 files = append(files, fileListEnt{
463 Name: path + ent.Name(),
470 if err := walk(""); err != nil {
471 http.Error(w, err.Error(), http.StatusInternalServerError)
475 funcs := template.FuncMap{
476 "nbsp": func(s string) template.HTML {
477 return template.HTML(strings.Replace(s, " ", " ", -1))
480 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
482 http.Error(w, err.Error(), http.StatusInternalServerError)
485 sort.Slice(files, func(i, j int) bool {
486 return files[i].Name < files[j].Name
488 w.WriteHeader(http.StatusOK)
489 tmpl.Execute(w, map[string]interface{}{
490 "CollectionName": collectionName,
493 "StripParts": stripParts,
497 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
498 disposition := "inline"
500 disposition = "attachment"
502 if strings.ContainsRune(r.RequestURI, '?') {
503 // Help the UA realize that the filename is just
504 // "filename.txt", not
505 // "filename.txt?disposition=attachment".
507 // TODO(TC): Follow advice at RFC 6266 appendix D
508 disposition += "; filename=" + strconv.QuoteToASCII(filename)
510 if disposition != "inline" {
511 w.Header().Set("Content-Disposition", disposition)
515 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
517 // It is not safe to copy the provided token
518 // into a cookie unless the current vhost
519 // (origin) serves only a single collection or
520 // we are in TrustAllContent mode.
521 w.WriteHeader(http.StatusBadRequest)
525 if formToken := r.FormValue("api_token"); formToken != "" {
526 // The HttpOnly flag is necessary to prevent
527 // JavaScript code (included in, or loaded by, a page
528 // in the collection being served) from employing the
529 // user's token beyond reading other files in the same
530 // domain, i.e., same collection.
532 // The 303 redirect is necessary in the case of a GET
533 // request to avoid exposing the token in the Location
534 // bar, and in the case of a POST request to avoid
535 // raising warnings when the user refreshes the
538 http.SetCookie(w, &http.Cookie{
539 Name: "arvados_api_token",
540 Value: auth.EncodeTokenCookie([]byte(formToken)),
546 // Propagate query parameters (except api_token) from
547 // the original request.
548 redirQuery := r.URL.Query()
549 redirQuery.Del("api_token")
553 newu, err := u.Parse(location)
555 w.WriteHeader(http.StatusInternalServerError)
563 RawQuery: redirQuery.Encode(),
566 w.Header().Add("Location", redir)
567 w.WriteHeader(http.StatusSeeOther)
568 io.WriteString(w, `<A href="`)
569 io.WriteString(w, html.EscapeString(redir))
570 io.WriteString(w, `">Continue</A>`)