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/httpserver"
25 "git.curoverse.com/arvados.git/sdk/go/keepclient"
30 clientPool *arvadosclient.ClientPool
34 // parseCollectionIDFromDNSName returns a UUID or PDH if s begins with
35 // a UUID or URL-encoded PDH; otherwise "".
36 func parseCollectionIDFromDNSName(s string) string {
38 if i := strings.IndexRune(s, '.'); i >= 0 {
41 // Names like {uuid}--collections.example.com serve the same
42 // purpose as {uuid}.collections.example.com but can reduce
43 // cost/effort of using [additional] wildcard certificates.
44 if i := strings.Index(s, "--"); i >= 0 {
47 if arvadosclient.UUIDMatch(s) {
50 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
56 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
58 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
59 // PDH (even if it is a PDH with "+" replaced by " " or "-");
61 func parseCollectionIDFromURL(s string) string {
62 if arvadosclient.UUIDMatch(s) {
65 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
71 func (h *handler) setup() {
72 h.clientPool = arvadosclient.MakeClientPool()
73 keepclient.RefreshServiceDiscoveryOnSIGHUP()
76 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
80 cacheStats: h.Config.Cache.Stats(),
82 json.NewEncoder(w).Encode(status)
85 // ServeHTTP implements http.Handler.
86 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
87 h.setupOnce.Do(h.setup)
92 remoteAddr := r.RemoteAddr
93 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
94 remoteAddr = xff + "," + remoteAddr
97 w := httpserver.WrapResponseWriter(wOrig)
100 statusCode = w.WroteStatus()
101 } else if w.WroteStatus() == 0 {
102 w.WriteHeader(statusCode)
103 } else if w.WroteStatus() != statusCode {
104 httpserver.Log(r.RemoteAddr, "WARNING",
105 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
107 if statusText == "" {
108 statusText = http.StatusText(statusCode)
110 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
113 if r.Method == "OPTIONS" {
114 method := r.Header.Get("Access-Control-Request-Method")
115 if method != "GET" && method != "POST" {
116 statusCode = http.StatusMethodNotAllowed
119 w.Header().Set("Access-Control-Allow-Headers", "Range")
120 w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
121 w.Header().Set("Access-Control-Allow-Origin", "*")
122 w.Header().Set("Access-Control-Max-Age", "86400")
123 statusCode = http.StatusOK
127 if r.Method != "GET" && r.Method != "POST" {
128 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
132 if r.Header.Get("Origin") != "" {
133 // Allow simple cross-origin requests without user
134 // credentials ("user credentials" as defined by CORS,
135 // i.e., cookies, HTTP authentication, and client-side
136 // SSL certificates. See
137 // http://www.w3.org/TR/cors/#user-credentials).
138 w.Header().Set("Access-Control-Allow-Origin", "*")
139 w.Header().Set("Access-Control-Expose-Headers", "Content-Range")
142 arv := h.clientPool.Get()
144 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
147 defer h.clientPool.Put(arv)
149 pathParts := strings.Split(r.URL.Path[1:], "/")
154 var reqTokens []string
157 credentialsOK := h.Config.TrustAllContent
159 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
162 } else if r.FormValue("disposition") == "attachment" {
166 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
167 // http://ID.collections.example/PATH...
169 } else if r.URL.Path == "/status.json" {
172 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
174 targetID = parseCollectionIDFromURL(pathParts[0][2:])
176 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
177 if len(pathParts) >= 4 && pathParts[1] == "download" {
178 // /collections/download/ID/TOKEN/PATH...
179 targetID = parseCollectionIDFromURL(pathParts[2])
180 tokens = []string{pathParts[3]}
184 // /collections/ID/PATH...
185 targetID = parseCollectionIDFromURL(pathParts[1])
186 tokens = h.Config.AnonymousTokens
192 statusCode = http.StatusNotFound
196 formToken := r.FormValue("api_token")
197 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
198 // The client provided an explicit token in the POST
199 // body. The Origin header indicates this *might* be
200 // an AJAX request, in which case redirect-with-cookie
201 // won't work: we should just serve the content in the
202 // POST response. This is safe because:
204 // * We're supplying an attachment, not inline
205 // content, so we don't need to convert the POST to
206 // a GET and avoid the "really resubmit form?"
209 // * The token isn't embedded in the URL, so we don't
210 // need to worry about bookmarks and copy/paste.
211 tokens = append(tokens, formToken)
212 } else if formToken != "" {
213 // The client provided an explicit token in the query
214 // string, or a form in POST body. We must put the
215 // token in an HttpOnly cookie, and redirect to the
216 // same URL with the query param redacted and method =
218 h.seeOtherWithCookie(w, r, "", credentialsOK)
222 targetPath := pathParts[stripParts:]
223 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
224 // http://ID.example/t=TOKEN/PATH...
225 // /c=ID/t=TOKEN/PATH...
227 // This form must only be used to pass scoped tokens
228 // that give permission for a single collection. See
229 // FormValue case above.
230 tokens = []string{targetPath[0][2:]}
232 targetPath = targetPath[1:]
238 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
240 tokens = append(reqTokens, h.Config.AnonymousTokens...)
243 if len(targetPath) > 0 && targetPath[0] == "_" {
244 // If a collection has a directory called "t=foo" or
245 // "_", it can be served at
246 // //collections.example/_/t=foo/ or
247 // //collections.example/_/_/ respectively:
248 // //collections.example/t=foo/ won't work because
249 // t=foo will be interpreted as a token "foo".
250 targetPath = targetPath[1:]
255 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
259 var collection *arvados.Collection
260 tokenResult := make(map[string]int)
261 for _, arv.ApiToken = range tokens {
263 collection, err = h.Config.Cache.Get(arv, targetID, forceReload)
268 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
269 switch srvErr.HttpStatusCode {
271 // Token broken or insufficient to
272 // retrieve collection
273 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
277 // Something more serious is wrong
278 statusCode, statusText = http.StatusInternalServerError, err.Error()
281 if collection == nil {
282 if pathToken || !credentialsOK {
283 // Either the URL is a "secret sharing link"
284 // that didn't work out (and asking the client
285 // for additional credentials would just be
286 // confusing), or we don't even accept
287 // credentials at this path.
288 statusCode = http.StatusNotFound
291 for _, t := range reqTokens {
292 if tokenResult[t] == 404 {
293 // The client provided valid token(s), but the
294 // collection was not found.
295 statusCode = http.StatusNotFound
299 // The client's token was invalid (e.g., expired), or
300 // the client didn't even provide one. Propagate the
301 // 401 to encourage the client to use a [different]
304 // TODO(TC): This response would be confusing to
305 // someone trying (anonymously) to download public
306 // data that has been deleted. Allow a referrer to
307 // provide this context somehow?
308 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
309 statusCode = http.StatusUnauthorized
313 kc, err := keepclient.MakeKeepClient(arv)
315 statusCode, statusText = http.StatusInternalServerError, err.Error()
319 basename := targetPath[len(targetPath)-1]
320 applyContentDispositionHdr(w, r, basename, attachment)
322 fs := collection.FileSystem(&arvados.Client{
323 APIHost: arv.ApiServer,
324 AuthToken: arv.ApiToken,
325 Insecure: arv.ApiInsecure,
327 openPath := "/" + strings.Join(targetPath, "/")
328 if f, err := fs.Open(openPath); os.IsNotExist(err) {
329 // Requested non-existent path
330 statusCode = http.StatusNotFound
331 } else if err != nil {
332 // Some other (unexpected) error
333 statusCode, statusText = http.StatusInternalServerError, err.Error()
334 } else if stat, err := f.Stat(); err != nil {
335 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
336 statusCode, statusText = http.StatusInternalServerError, err.Error()
337 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
338 // If client requests ".../dirname", redirect to
339 // ".../dirname/". This way, relative links in the
340 // listing for "dirname" can always be "fnm", never
342 h.seeOtherWithCookie(w, r, basename+"/", credentialsOK)
343 } else if stat.IsDir() {
344 h.serveDirectory(w, r, collection.Name, fs, openPath, stripParts)
346 http.ServeContent(w, r, basename, stat.ModTime(), f)
347 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
348 // If we wrote fewer bytes than expected, it's
349 // too late to change the real response code
350 // or send an error message to the client, but
351 // at least we can try to put some useful
352 // debugging info in the logs.
353 n, err := f.Read(make([]byte, 1024))
354 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)
360 var dirListingTemplate = `<!DOCTYPE HTML>
362 <META name="robots" content="NOINDEX">
363 <TITLE>{{ .Collection.Name }}</TITLE>
364 <STYLE type="text/css">
369 background-color: #D9EDF7;
370 border-radius: .25em;
381 font-family: monospace;
387 <H1>{{ .CollectionName }}</H1>
389 <P>This collection of data files is being shared with you through
390 Arvados. You can download individual files listed below. To download
391 the entire collection with wget, try:</P>
393 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL }}</PRE>
395 <H2>File Listing</H2>
399 {{range .Files}} <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{.Name}}">{{.Name}}</A></LI>{{end}}
402 <P>(No files; this collection is empty.)</P>
409 Arvados is a free and open source software bioinformatics platform.
410 To learn more, visit arvados.org.
411 Arvados is not responsible for the files listed on this page.
418 type fileListEnt struct {
423 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, stripParts int) {
424 var files []fileListEnt
425 var walk func(string) error
426 if !strings.HasSuffix(base, "/") {
429 walk = func(path string) error {
430 dirname := base + path
432 dirname = strings.TrimSuffix(dirname, "/")
434 d, err := fs.Open(dirname)
438 ents, err := d.Readdir(-1)
442 for _, ent := range ents {
444 err = walk(path + ent.Name() + "/")
449 files = append(files, fileListEnt{
450 Name: path + ent.Name(),
457 if err := walk(""); err != nil {
458 http.Error(w, err.Error(), http.StatusInternalServerError)
462 funcs := template.FuncMap{
463 "nbsp": func(s string) template.HTML {
464 return template.HTML(strings.Replace(s, " ", " ", -1))
467 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
469 http.Error(w, err.Error(), http.StatusInternalServerError)
472 sort.Slice(files, func(i, j int) bool {
473 return files[i].Name < files[j].Name
475 w.WriteHeader(http.StatusOK)
476 tmpl.Execute(w, map[string]interface{}{
477 "CollectionName": collectionName,
480 "StripParts": stripParts,
484 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
485 disposition := "inline"
487 disposition = "attachment"
489 if strings.ContainsRune(r.RequestURI, '?') {
490 // Help the UA realize that the filename is just
491 // "filename.txt", not
492 // "filename.txt?disposition=attachment".
494 // TODO(TC): Follow advice at RFC 6266 appendix D
495 disposition += "; filename=" + strconv.QuoteToASCII(filename)
497 if disposition != "inline" {
498 w.Header().Set("Content-Disposition", disposition)
502 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
504 // It is not safe to copy the provided token
505 // into a cookie unless the current vhost
506 // (origin) serves only a single collection or
507 // we are in TrustAllContent mode.
508 w.WriteHeader(http.StatusBadRequest)
512 if formToken := r.FormValue("api_token"); formToken != "" {
513 // The HttpOnly flag is necessary to prevent
514 // JavaScript code (included in, or loaded by, a page
515 // in the collection being served) from employing the
516 // user's token beyond reading other files in the same
517 // domain, i.e., same collection.
519 // The 303 redirect is necessary in the case of a GET
520 // request to avoid exposing the token in the Location
521 // bar, and in the case of a POST request to avoid
522 // raising warnings when the user refreshes the
525 http.SetCookie(w, &http.Cookie{
526 Name: "arvados_api_token",
527 Value: auth.EncodeTokenCookie([]byte(formToken)),
533 // Propagate query parameters (except api_token) from
534 // the original request.
535 redirQuery := r.URL.Query()
536 redirQuery.Del("api_token")
540 newu, err := u.Parse(location)
542 w.WriteHeader(http.StatusInternalServerError)
550 RawQuery: redirQuery.Encode(),
553 w.Header().Add("Location", redir)
554 w.WriteHeader(http.StatusSeeOther)
555 io.WriteString(w, `<A href="`)
556 io.WriteString(w, html.EscapeString(redir))
557 io.WriteString(w, `">Continue</A>`)