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", "*")
141 arv := h.clientPool.Get()
143 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
146 defer h.clientPool.Put(arv)
148 pathParts := strings.Split(r.URL.Path[1:], "/")
153 var reqTokens []string
156 credentialsOK := h.Config.TrustAllContent
158 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
161 } else if r.FormValue("disposition") == "attachment" {
165 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
166 // http://ID.collections.example/PATH...
168 } else if r.URL.Path == "/status.json" {
171 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
173 targetID = parseCollectionIDFromURL(pathParts[0][2:])
175 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
176 if len(pathParts) >= 4 && pathParts[1] == "download" {
177 // /collections/download/ID/TOKEN/PATH...
178 targetID = parseCollectionIDFromURL(pathParts[2])
179 tokens = []string{pathParts[3]}
183 // /collections/ID/PATH...
184 targetID = parseCollectionIDFromURL(pathParts[1])
185 tokens = h.Config.AnonymousTokens
191 statusCode = http.StatusNotFound
195 formToken := r.FormValue("api_token")
196 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
197 // The client provided an explicit token in the POST
198 // body. The Origin header indicates this *might* be
199 // an AJAX request, in which case redirect-with-cookie
200 // won't work: we should just serve the content in the
201 // POST response. This is safe because:
203 // * We're supplying an attachment, not inline
204 // content, so we don't need to convert the POST to
205 // a GET and avoid the "really resubmit form?"
208 // * The token isn't embedded in the URL, so we don't
209 // need to worry about bookmarks and copy/paste.
210 tokens = append(tokens, formToken)
211 } else if formToken != "" {
212 // The client provided an explicit token in the query
213 // string, or a form in POST body. We must put the
214 // token in an HttpOnly cookie, and redirect to the
215 // same URL with the query param redacted and method =
217 h.seeOtherWithCookie(w, r, "", credentialsOK)
221 targetPath := pathParts[stripParts:]
222 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
223 // http://ID.example/t=TOKEN/PATH...
224 // /c=ID/t=TOKEN/PATH...
226 // This form must only be used to pass scoped tokens
227 // that give permission for a single collection. See
228 // FormValue case above.
229 tokens = []string{targetPath[0][2:]}
231 targetPath = targetPath[1:]
237 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
239 tokens = append(reqTokens, h.Config.AnonymousTokens...)
242 if len(targetPath) > 0 && targetPath[0] == "_" {
243 // If a collection has a directory called "t=foo" or
244 // "_", it can be served at
245 // //collections.example/_/t=foo/ or
246 // //collections.example/_/_/ respectively:
247 // //collections.example/t=foo/ won't work because
248 // t=foo will be interpreted as a token "foo".
249 targetPath = targetPath[1:]
254 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
258 var collection *arvados.Collection
259 tokenResult := make(map[string]int)
260 for _, arv.ApiToken = range tokens {
262 collection, err = h.Config.Cache.Get(arv, targetID, forceReload)
267 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
268 switch srvErr.HttpStatusCode {
270 // Token broken or insufficient to
271 // retrieve collection
272 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
276 // Something more serious is wrong
277 statusCode, statusText = http.StatusInternalServerError, err.Error()
280 if collection == nil {
281 if pathToken || !credentialsOK {
282 // Either the URL is a "secret sharing link"
283 // that didn't work out (and asking the client
284 // for additional credentials would just be
285 // confusing), or we don't even accept
286 // credentials at this path.
287 statusCode = http.StatusNotFound
290 for _, t := range reqTokens {
291 if tokenResult[t] == 404 {
292 // The client provided valid token(s), but the
293 // collection was not found.
294 statusCode = http.StatusNotFound
298 // The client's token was invalid (e.g., expired), or
299 // the client didn't even provide one. Propagate the
300 // 401 to encourage the client to use a [different]
303 // TODO(TC): This response would be confusing to
304 // someone trying (anonymously) to download public
305 // data that has been deleted. Allow a referrer to
306 // provide this context somehow?
307 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
308 statusCode = http.StatusUnauthorized
312 kc, err := keepclient.MakeKeepClient(arv)
314 statusCode, statusText = http.StatusInternalServerError, err.Error()
318 basename := targetPath[len(targetPath)-1]
319 applyContentDispositionHdr(w, r, basename, attachment)
321 fs := collection.FileSystem(&arvados.Client{
322 APIHost: arv.ApiServer,
323 AuthToken: arv.ApiToken,
324 Insecure: arv.ApiInsecure,
326 openPath := "/" + strings.Join(targetPath, "/")
327 if f, err := fs.Open(openPath); os.IsNotExist(err) {
328 // Requested non-existent path
329 statusCode = http.StatusNotFound
330 } else if err != nil {
331 // Some other (unexpected) error
332 statusCode, statusText = http.StatusInternalServerError, err.Error()
333 } else if stat, err := f.Stat(); err != nil {
334 // Can't get Size/IsDir (shouldn't happen with a collectionFS!)
335 statusCode, statusText = http.StatusInternalServerError, err.Error()
336 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
337 // If client requests ".../dirname", redirect to
338 // ".../dirname/". This way, relative links in the
339 // listing for "dirname" can always be "fnm", never
341 h.seeOtherWithCookie(w, r, basename+"/", credentialsOK)
342 } else if stat.IsDir() {
343 h.serveDirectory(w, r, collection.Name, fs, openPath, stripParts)
345 http.ServeContent(w, r, basename, stat.ModTime(), f)
346 if r.Header.Get("Range") == "" && int64(w.WroteBodyBytes()) != stat.Size() {
347 // If we wrote fewer bytes than expected, it's
348 // too late to change the real response code
349 // or send an error message to the client, but
350 // at least we can try to put some useful
351 // debugging info in the logs.
352 n, err := f.Read(make([]byte, 1024))
353 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)
359 var dirListingTemplate = `<!DOCTYPE HTML>
361 <META name="robots" content="NOINDEX">
362 <TITLE>{{ .Collection.Name }}</TITLE>
363 <STYLE type="text/css">
368 background-color: #D9EDF7;
369 border-radius: .25em;
380 font-family: monospace;
386 <H1>{{ .CollectionName }}</H1>
388 <P>This collection of data files is being shared with you through
389 Arvados. You can download individual files listed below. To download
390 the entire collection with wget, try:</P>
392 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs={{ .StripParts }} https://{{ .Request.Host }}{{ .Request.URL }}</PRE>
394 <H2>File Listing</H2>
398 {{range .Files}} <LI>{{.Size | printf "%15d " | nbsp}}<A href="{{.Name}}">{{.Name}}</A></LI>{{end}}
401 <P>(No files; this collection is empty.)</P>
408 Arvados is a free and open source software bioinformatics platform.
409 To learn more, visit arvados.org.
410 Arvados is not responsible for the files listed on this page.
417 type fileListEnt struct {
422 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collectionName string, fs http.FileSystem, base string, stripParts int) {
423 var files []fileListEnt
424 var walk func(string) error
425 if !strings.HasSuffix(base, "/") {
428 walk = func(path string) error {
429 dirname := base + path
431 dirname = strings.TrimSuffix(dirname, "/")
433 d, err := fs.Open(dirname)
437 ents, err := d.Readdir(-1)
441 for _, ent := range ents {
443 err = walk(path + ent.Name() + "/")
448 files = append(files, fileListEnt{
449 Name: path + ent.Name(),
456 if err := walk(""); err != nil {
457 http.Error(w, err.Error(), http.StatusInternalServerError)
461 funcs := template.FuncMap{
462 "nbsp": func(s string) template.HTML {
463 return template.HTML(strings.Replace(s, " ", " ", -1))
466 tmpl, err := template.New("dir").Funcs(funcs).Parse(dirListingTemplate)
468 http.Error(w, err.Error(), http.StatusInternalServerError)
471 sort.Slice(files, func(i, j int) bool {
472 return files[i].Name < files[j].Name
474 w.WriteHeader(http.StatusOK)
475 tmpl.Execute(w, map[string]interface{}{
476 "CollectionName": collectionName,
479 "StripParts": stripParts,
483 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
484 disposition := "inline"
486 disposition = "attachment"
488 if strings.ContainsRune(r.RequestURI, '?') {
489 // Help the UA realize that the filename is just
490 // "filename.txt", not
491 // "filename.txt?disposition=attachment".
493 // TODO(TC): Follow advice at RFC 6266 appendix D
494 disposition += "; filename=" + strconv.QuoteToASCII(filename)
496 if disposition != "inline" {
497 w.Header().Set("Content-Disposition", disposition)
501 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
503 // It is not safe to copy the provided token
504 // into a cookie unless the current vhost
505 // (origin) serves only a single collection or
506 // we are in TrustAllContent mode.
507 w.WriteHeader(http.StatusBadRequest)
511 if formToken := r.FormValue("api_token"); formToken != "" {
512 // The HttpOnly flag is necessary to prevent
513 // JavaScript code (included in, or loaded by, a page
514 // in the collection being served) from employing the
515 // user's token beyond reading other files in the same
516 // domain, i.e., same collection.
518 // The 303 redirect is necessary in the case of a GET
519 // request to avoid exposing the token in the Location
520 // bar, and in the case of a POST request to avoid
521 // raising warnings when the user refreshes the
524 http.SetCookie(w, &http.Cookie{
525 Name: "arvados_api_token",
526 Value: auth.EncodeTokenCookie([]byte(formToken)),
532 // Propagate query parameters (except api_token) from
533 // the original request.
534 redirQuery := r.URL.Query()
535 redirQuery.Del("api_token")
539 newu, err := u.Parse(location)
541 w.WriteHeader(http.StatusInternalServerError)
549 RawQuery: redirQuery.Encode(),
552 w.Header().Add("Location", redir)
553 w.WriteHeader(http.StatusSeeOther)
554 io.WriteString(w, `<A href="`)
555 io.WriteString(w, html.EscapeString(redir))
556 io.WriteString(w, `">Continue</A>`)