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
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.hmux = http.NewServeMux()
79 h.hmux.Handle("/_health/", &health.Handler{
80 Token: h.Config.ManagementToken,
85 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
89 cacheStats: h.Config.Cache.Stats(),
91 json.NewEncoder(w).Encode(status)
94 func (h *handler) healthCheck(w http.ResponseWriter, r *http.Request) {
95 h.hmux.ServeHTTP(w, r)
98 // ServeHTTP implements http.Handler.
99 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
100 h.setupOnce.Do(h.setup)
103 var statusText string
105 remoteAddr := r.RemoteAddr
106 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
107 remoteAddr = xff + "," + remoteAddr
110 w := httpserver.WrapResponseWriter(wOrig)
113 statusCode = w.WroteStatus()
114 } else if w.WroteStatus() == 0 {
115 w.WriteHeader(statusCode)
116 } else if w.WroteStatus() != statusCode {
117 httpserver.Log(r.RemoteAddr, "WARNING",
118 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
120 if statusText == "" {
121 statusText = http.StatusText(statusCode)
123 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
126 if strings.HasPrefix(r.URL.Path, "/_health/") && r.Method == "GET" {
131 if r.Method == "OPTIONS" {
132 method := r.Header.Get("Access-Control-Request-Method")
133 if method != "GET" && method != "POST" {
134 statusCode = http.StatusMethodNotAllowed
137 w.Header().Set("Access-Control-Allow-Headers", "Range")
138 w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
139 w.Header().Set("Access-Control-Allow-Origin", "*")
140 w.Header().Set("Access-Control-Max-Age", "86400")
141 statusCode = http.StatusOK
145 if r.Method != "GET" && r.Method != "POST" {
146 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
150 if r.Header.Get("Origin") != "" {
151 // Allow simple cross-origin requests without user
152 // credentials ("user credentials" as defined by CORS,
153 // i.e., cookies, HTTP authentication, and client-side
154 // SSL certificates. See
155 // http://www.w3.org/TR/cors/#user-credentials).
156 w.Header().Set("Access-Control-Allow-Origin", "*")
159 arv := h.clientPool.Get()
161 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
164 defer h.clientPool.Put(arv)
166 pathParts := strings.Split(r.URL.Path[1:], "/")
171 var reqTokens []string
174 credentialsOK := h.Config.TrustAllContent
176 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
179 } else if r.FormValue("disposition") == "attachment" {
183 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
184 // http://ID.collections.example/PATH...
186 } else if r.URL.Path == "/status.json" {
189 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
191 targetID = parseCollectionIDFromURL(pathParts[0][2:])
193 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
194 if len(pathParts) >= 4 && pathParts[1] == "download" {
195 // /collections/download/ID/TOKEN/PATH...
196 targetID = parseCollectionIDFromURL(pathParts[2])
197 tokens = []string{pathParts[3]}
201 // /collections/ID/PATH...
202 targetID = parseCollectionIDFromURL(pathParts[1])
203 tokens = h.Config.AnonymousTokens
209 statusCode = http.StatusNotFound
213 formToken := r.FormValue("api_token")
214 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
215 // The client provided an explicit token in the POST
216 // body. The Origin header indicates this *might* be
217 // an AJAX request, in which case redirect-with-cookie
218 // won't work: we should just serve the content in the
219 // POST response. This is safe because:
221 // * We're supplying an attachment, not inline
222 // content, so we don't need to convert the POST to
223 // a GET and avoid the "really resubmit form?"
226 // * The token isn't embedded in the URL, so we don't
227 // need to worry about bookmarks and copy/paste.
228 tokens = append(tokens, formToken)
229 } else if formToken != "" {
230 // The client provided an explicit token in the query
231 // string, or a form in POST body. We must put the
232 // token in an HttpOnly cookie, and redirect to the
233 // same URL with the query param redacted and method =
235 h.seeOtherWithCookie(w, r, "", credentialsOK)
239 targetPath := pathParts[stripParts:]
240 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
241 // http://ID.example/t=TOKEN/PATH...
242 // /c=ID/t=TOKEN/PATH...
244 // This form must only be used to pass scoped tokens
245 // that give permission for a single collection. See
246 // FormValue case above.
247 tokens = []string{targetPath[0][2:]}
249 targetPath = targetPath[1:]
255 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
257 tokens = append(reqTokens, h.Config.AnonymousTokens...)
260 if len(targetPath) > 0 && targetPath[0] == "_" {
261 // If a collection has a directory called "t=foo" or
262 // "_", it can be served at
263 // //collections.example/_/t=foo/ or
264 // //collections.example/_/_/ respectively:
265 // //collections.example/t=foo/ won't work because
266 // t=foo will be interpreted as a token "foo".
267 targetPath = targetPath[1:]
272 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
276 var collection *arvados.Collection
277 tokenResult := make(map[string]int)
278 for _, arv.ApiToken = range tokens {
280 collection, err = h.Config.Cache.Get(arv, targetID, forceReload)
285 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
286 switch srvErr.HttpStatusCode {
288 // Token broken or insufficient to
289 // retrieve collection
290 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
294 // Something more serious is wrong
295 statusCode, statusText = http.StatusInternalServerError, err.Error()
298 if collection == nil {
299 if pathToken || !credentialsOK {
300 // Either the URL is a "secret sharing link"
301 // that didn't work out (and asking the client
302 // for additional credentials would just be
303 // confusing), or we don't even accept
304 // credentials at this path.
305 statusCode = http.StatusNotFound
308 for _, t := range reqTokens {
309 if tokenResult[t] == 404 {
310 // The client provided valid token(s), but the
311 // collection was not found.
312 statusCode = http.StatusNotFound
316 // The client's token was invalid (e.g., expired), or
317 // the client didn't even provide one. Propagate the
318 // 401 to encourage the client to use a [different]
321 // TODO(TC): This response would be confusing to
322 // someone trying (anonymously) to download public
323 // data that has been deleted. Allow a referrer to
324 // provide this context somehow?
325 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
326 statusCode = http.StatusUnauthorized
330 kc, err := keepclient.MakeKeepClient(arv)
332 statusCode, statusText = http.StatusInternalServerError, err.Error()
336 basename := targetPath[len(targetPath)-1]
337 applyContentDispositionHdr(w, r, basename, attachment)
339 fs := collection.FileSystem(&arvados.Client{
340 APIHost: arv.ApiServer,
341 AuthToken: arv.ApiToken,
342 Insecure: arv.ApiInsecure,
344 openPath := "/" + strings.Join(targetPath, "/")
345 if f, err := fs.Open(openPath); os.IsNotExist(err) {
346 // Requested non-existent path
347 statusCode = http.StatusNotFound
348 } else if err != nil {
349 // Some other (unexpected) error
350 statusCode, statusText = http.StatusInternalServerError, err.Error()
351 } else if stat, err := f.Stat(); err != nil {
352 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
353 statusCode, statusText = http.StatusInternalServerError, err.Error()
354 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
355 // If client requests ".../dirname", redirect to
356 // ".../dirname/". This way, relative links in the
357 // listing for "dirname" can always be "fnm", never
359 h.seeOtherWithCookie(w, r, basename+"/", credentialsOK)
360 } else if stat.IsDir() {
361 h.serveDirectory(w, r, collection.Name, fs, openPath, stripParts)
363 http.ServeContent(w, r, basename, stat.ModTime(), f)
364 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
365 // If we wrote fewer bytes than expected, it's
366 // too late to change the real response code
367 // or send an error message to the client, but
368 // at least we can try to put some useful
369 // debugging info in the logs.
370 n, err := f.Read(make([]byte, 1024))
371 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)
377 var dirListingTemplate = `<!DOCTYPE HTML>
379 <META name="robots" content="NOINDEX">
380 <TITLE>{{ .Collection.Name }}</TITLE>
381 <STYLE type="text/css">
386 background-color: #D9EDF7;
387 border-radius: .25em;
398 font-family: monospace;
404 <H1>{{ .CollectionName }}</H1>
406 <P>This collection of data files is being shared with you through
407 Arvados. You can download individual files listed below. To download
408 the entire collection with wget, try:</P>
410 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL }}</PRE>
412 <H2>File Listing</H2>
416 {{range .Files}} <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{.Name}}">{{.Name}}</A></LI>{{end}}
419 <P>(No files; this collection is empty.)</P>
426 Arvados is a free and open source software bioinformatics platform.
427 To learn more, visit arvados.org.
428 Arvados is not responsible for the files listed on this page.
435 type fileListEnt struct {
440 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, stripParts int) {
441 var files []fileListEnt
442 var walk func(string) error
443 if !strings.HasSuffix(base, "/") {
446 walk = func(path string) error {
447 dirname := base + path
449 dirname = strings.TrimSuffix(dirname, "/")
451 d, err := fs.Open(dirname)
455 ents, err := d.Readdir(-1)
459 for _, ent := range ents {
461 err = walk(path + ent.Name() + "/")
466 files = append(files, fileListEnt{
467 Name: path + ent.Name(),
474 if err := walk(""); err != nil {
475 http.Error(w, err.Error(), http.StatusInternalServerError)
479 funcs := template.FuncMap{
480 "nbsp": func(s string) template.HTML {
481 return template.HTML(strings.Replace(s, " ", " ", -1))
484 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
486 http.Error(w, err.Error(), http.StatusInternalServerError)
489 sort.Slice(files, func(i, j int) bool {
490 return files[i].Name < files[j].Name
492 w.WriteHeader(http.StatusOK)
493 tmpl.Execute(w, map[string]interface{}{
494 "CollectionName": collectionName,
497 "StripParts": stripParts,
501 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
502 disposition := "inline"
504 disposition = "attachment"
506 if strings.ContainsRune(r.RequestURI, '?') {
507 // Help the UA realize that the filename is just
508 // "filename.txt", not
509 // "filename.txt?disposition=attachment".
511 // TODO(TC): Follow advice at RFC 6266 appendix D
512 disposition += "; filename=" + strconv.QuoteToASCII(filename)
514 if disposition != "inline" {
515 w.Header().Set("Content-Disposition", disposition)
519 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
521 // It is not safe to copy the provided token
522 // into a cookie unless the current vhost
523 // (origin) serves only a single collection or
524 // we are in TrustAllContent mode.
525 w.WriteHeader(http.StatusBadRequest)
529 if formToken := r.FormValue("api_token"); formToken != "" {
530 // The HttpOnly flag is necessary to prevent
531 // JavaScript code (included in, or loaded by, a page
532 // in the collection being served) from employing the
533 // user's token beyond reading other files in the same
534 // domain, i.e., same collection.
536 // The 303 redirect is necessary in the case of a GET
537 // request to avoid exposing the token in the Location
538 // bar, and in the case of a POST request to avoid
539 // raising warnings when the user refreshes the
542 http.SetCookie(w, &http.Cookie{
543 Name: "arvados_api_token",
544 Value: auth.EncodeTokenCookie([]byte(formToken)),
550 // Propagate query parameters (except api_token) from
551 // the original request.
552 redirQuery := r.URL.Query()
553 redirQuery.Del("api_token")
557 newu, err := u.Parse(location)
559 w.WriteHeader(http.StatusInternalServerError)
567 RawQuery: redirQuery.Encode(),
570 w.Header().Add("Location", redir)
571 w.WriteHeader(http.StatusSeeOther)
572 io.WriteString(w, `<A href="`)
573 io.WriteString(w, html.EscapeString(redir))
574 io.WriteString(w, `">Continue</A>`)