17 "git.curoverse.com/arvados.git/sdk/go/arvados"
18 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
19 "git.curoverse.com/arvados.git/sdk/go/auth"
20 "git.curoverse.com/arvados.git/sdk/go/httpserver"
21 "git.curoverse.com/arvados.git/sdk/go/keepclient"
26 clientPool *arvadosclient.ClientPool
30 // parseCollectionIDFromDNSName returns a UUID or PDH if s begins with
31 // a UUID or URL-encoded PDH; otherwise "".
32 func parseCollectionIDFromDNSName(s string) string {
34 if i := strings.IndexRune(s, '.'); i >= 0 {
37 // Names like {uuid}--collections.example.com serve the same
38 // purpose as {uuid}.collections.example.com but can reduce
39 // cost/effort of using [additional] wildcard certificates.
40 if i := strings.Index(s, "--"); i >= 0 {
43 if arvadosclient.UUIDMatch(s) {
46 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
52 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
54 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
55 // PDH (even if it is a PDH with "+" replaced by " " or "-");
57 func parseCollectionIDFromURL(s string) string {
58 if arvadosclient.UUIDMatch(s) {
61 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
67 func (h *handler) setup() {
68 h.clientPool = arvadosclient.MakeClientPool()
69 keepclient.RefreshServiceDiscoveryOnSIGHUP()
72 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
76 cacheStats: h.Config.Cache.Stats(),
78 json.NewEncoder(w).Encode(status)
81 // ServeHTTP implements http.Handler.
82 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
83 h.setupOnce.Do(h.setup)
88 remoteAddr := r.RemoteAddr
89 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
90 remoteAddr = xff + "," + remoteAddr
93 w := httpserver.WrapResponseWriter(wOrig)
96 statusCode = w.WroteStatus()
97 } else if w.WroteStatus() == 0 {
98 w.WriteHeader(statusCode)
99 } else if w.WroteStatus() != statusCode {
100 httpserver.Log(r.RemoteAddr, "WARNING",
101 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
103 if statusText == "" {
104 statusText = http.StatusText(statusCode)
106 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
109 if r.Method == "OPTIONS" {
110 method := r.Header.Get("Access-Control-Request-Method")
111 if method != "GET" && method != "POST" {
112 statusCode = http.StatusMethodNotAllowed
115 w.Header().Set("Access-Control-Allow-Headers", "Range")
116 w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
117 w.Header().Set("Access-Control-Allow-Origin", "*")
118 w.Header().Set("Access-Control-Max-Age", "86400")
119 statusCode = http.StatusOK
123 if r.Method != "GET" && r.Method != "POST" {
124 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
128 if r.Header.Get("Origin") != "" {
129 // Allow simple cross-origin requests without user
130 // credentials ("user credentials" as defined by CORS,
131 // i.e., cookies, HTTP authentication, and client-side
132 // SSL certificates. See
133 // http://www.w3.org/TR/cors/#user-credentials).
134 w.Header().Set("Access-Control-Allow-Origin", "*")
137 arv := h.clientPool.Get()
139 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
142 defer h.clientPool.Put(arv)
144 pathParts := strings.Split(r.URL.Path[1:], "/")
149 var reqTokens []string
152 credentialsOK := h.Config.TrustAllContent
154 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
157 } else if r.FormValue("disposition") == "attachment" {
161 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
162 // http://ID.collections.example/PATH...
164 } else if r.URL.Path == "/status.json" {
167 } else if len(pathParts) >= 1 && strings.HasPrefix(pathParts[0], "c=") {
169 targetID = parseCollectionIDFromURL(pathParts[0][2:])
171 } else if len(pathParts) >= 2 && pathParts[0] == "collections" {
172 if len(pathParts) >= 4 && pathParts[1] == "download" {
173 // /collections/download/ID/TOKEN/PATH...
174 targetID = parseCollectionIDFromURL(pathParts[2])
175 tokens = []string{pathParts[3]}
179 // /collections/ID/PATH...
180 targetID = parseCollectionIDFromURL(pathParts[1])
181 tokens = h.Config.AnonymousTokens
187 statusCode = http.StatusNotFound
191 formToken := r.FormValue("api_token")
192 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
193 // The client provided an explicit token in the POST
194 // body. The Origin header indicates this *might* be
195 // an AJAX request, in which case redirect-with-cookie
196 // won't work: we should just serve the content in the
197 // POST response. This is safe because:
199 // * We're supplying an attachment, not inline
200 // content, so we don't need to convert the POST to
201 // a GET and avoid the "really resubmit form?"
204 // * The token isn't embedded in the URL, so we don't
205 // need to worry about bookmarks and copy/paste.
206 tokens = append(tokens, formToken)
207 } else if formToken != "" {
208 // The client provided an explicit token in the query
209 // string, or a form in POST body. We must put the
210 // token in an HttpOnly cookie, and redirect to the
211 // same URL with the query param redacted and method =
213 h.seeOtherWithCookie(w, r, "", credentialsOK)
217 targetPath := pathParts[stripParts:]
218 if tokens == nil && len(targetPath) > 0 && strings.HasPrefix(targetPath[0], "t=") {
219 // http://ID.example/t=TOKEN/PATH...
220 // /c=ID/t=TOKEN/PATH...
222 // This form must only be used to pass scoped tokens
223 // that give permission for a single collection. See
224 // FormValue case above.
225 tokens = []string{targetPath[0][2:]}
227 targetPath = targetPath[1:]
233 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
235 tokens = append(reqTokens, h.Config.AnonymousTokens...)
238 if len(targetPath) > 0 && targetPath[0] == "_" {
239 // If a collection has a directory called "t=foo" or
240 // "_", it can be served at
241 // //collections.example/_/t=foo/ or
242 // //collections.example/_/_/ respectively:
243 // //collections.example/t=foo/ won't work because
244 // t=foo will be interpreted as a token "foo".
245 targetPath = targetPath[1:]
250 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
254 var collection map[string]interface{}
255 tokenResult := make(map[string]int)
257 for _, arv.ApiToken = range tokens {
259 collection, err = h.Config.Cache.Get(arv, targetID, forceReload)
265 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
266 switch srvErr.HttpStatusCode {
268 // Token broken or insufficient to
269 // retrieve collection
270 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
274 // Something more serious is wrong
275 statusCode, statusText = http.StatusInternalServerError, err.Error()
279 if pathToken || !credentialsOK {
280 // Either the URL is a "secret sharing link"
281 // that didn't work out (and asking the client
282 // for additional credentials would just be
283 // confusing), or we don't even accept
284 // credentials at this path.
285 statusCode = http.StatusNotFound
288 for _, t := range reqTokens {
289 if tokenResult[t] == 404 {
290 // The client provided valid token(s), but the
291 // collection was not found.
292 statusCode = http.StatusNotFound
296 // The client's token was invalid (e.g., expired), or
297 // the client didn't even provide one. Propagate the
298 // 401 to encourage the client to use a [different]
301 // TODO(TC): This response would be confusing to
302 // someone trying (anonymously) to download public
303 // data that has been deleted. Allow a referrer to
304 // provide this context somehow?
305 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
306 statusCode = http.StatusUnauthorized
310 kc, err := keepclient.MakeKeepClient(arv)
312 statusCode, statusText = http.StatusInternalServerError, err.Error()
316 basename := targetPath[len(targetPath)-1]
317 applyContentDispositionHdr(w, r, basename, attachment)
319 j, err := json.Marshal(collection)
323 var coll arvados.Collection
324 err = json.Unmarshal(j, &coll)
328 fs := coll.FileSystem(&arvados.Client{
329 APIHost: arv.ApiServer,
330 AuthToken: arv.ApiToken,
331 Insecure: arv.ApiInsecure,
333 openPath := "/" + strings.Join(targetPath, "/")
334 if f, err := fs.Open(openPath); os.IsNotExist(err) {
335 statusCode = http.StatusNotFound
336 } else if err != nil {
337 statusCode, statusText = http.StatusInternalServerError, err.Error()
338 } else if stat, err := f.Stat(); err != nil {
339 statusCode, statusText = http.StatusInternalServerError, err.Error()
340 } else if stat.IsDir() && !strings.HasSuffix(r.URL.Path, "/") {
341 h.seeOtherWithCookie(w, r, basename+"/", credentialsOK)
342 } else if stat.IsDir() {
343 h.serveDirectory(w, r, &coll, fs, openPath)
345 http.ServeContent(w, r, basename, stat.ModTime(), f)
346 if int64(w.WroteBodyBytes()) != stat.Size() {
347 n, err := f.Read(make([]byte, 1024))
348 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)
354 var dirListingTemplate = `<!DOCTYPE HTML>
355 <HTML><HEAD><TITLE>{{ .Collection.Name }}</TITLE></HEAD>
357 <H1>{{ .Collection.Name }}</H1>
359 <P>This collection of data files is being shared with you through
360 Arvados. You can download individual files listed below. To download
361 the entire collection with wget, try:</P>
363 <PRE>$ wget --mirror --no-parent --no-host --cut-dirs=3 {{ .Request.URL }}</PRE>
365 <H2>File Listing</H2>
368 {{range .Files}} <LI><A href="{{.}}">{{.}}</A></LI>{{end}}
372 <H2>About Arvados</H2>
374 Arvados is a free and open source software bioinformatics platform.
375 To learn more, visit arvados.org.
376 Arvados is not responsible for the files listed on this page.
383 func (h *handler) serveDirectory(w http.ResponseWriter, r *http.Request, collection *arvados.Collection, fs http.FileSystem, base string) {
385 var walk func(string) error
386 if !strings.HasSuffix(base, "/") {
389 walk = func(path string) error {
390 dirname := base + path
392 dirname = strings.TrimSuffix(dirname, "/")
394 d, err := fs.Open(dirname)
398 ents, err := d.Readdir(-1)
402 for _, ent := range ents {
404 err = walk(path + ent.Name() + "/")
409 files = append(files, path+ent.Name())
414 if err := walk(""); err != nil {
415 http.Error(w, err.Error(), http.StatusInternalServerError)
418 tmpl, err := template.New("dir").Parse(dirListingTemplate)
420 http.Error(w, err.Error(), http.StatusInternalServerError)
424 w.WriteHeader(http.StatusOK)
425 tmpl.Execute(w, map[string]interface{}{
426 "Collection": collection,
432 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
433 disposition := "inline"
435 disposition = "attachment"
437 if strings.ContainsRune(r.RequestURI, '?') {
438 // Help the UA realize that the filename is just
439 // "filename.txt", not
440 // "filename.txt?disposition=attachment".
442 // TODO(TC): Follow advice at RFC 6266 appendix D
443 disposition += "; filename=" + strconv.QuoteToASCII(filename)
445 if disposition != "inline" {
446 w.Header().Set("Content-Disposition", disposition)
450 func (h *handler) seeOtherWithCookie(w http.ResponseWriter, r *http.Request, location string, credentialsOK bool) {
452 // It is not safe to copy the provided token
453 // into a cookie unless the current vhost
454 // (origin) serves only a single collection or
455 // we are in TrustAllContent mode.
456 w.WriteHeader(http.StatusBadRequest)
460 if formToken := r.FormValue("api_token"); formToken != "" {
461 // The HttpOnly flag is necessary to prevent
462 // JavaScript code (included in, or loaded by, a page
463 // in the collection being served) from employing the
464 // user's token beyond reading other files in the same
465 // domain, i.e., same collection.
467 // The 303 redirect is necessary in the case of a GET
468 // request to avoid exposing the token in the Location
469 // bar, and in the case of a POST request to avoid
470 // raising warnings when the user refreshes the
473 http.SetCookie(w, &http.Cookie{
474 Name: "arvados_api_token",
475 Value: auth.EncodeTokenCookie([]byte(formToken)),
481 // Propagate query parameters (except api_token) from
482 // the original request.
483 redirQuery := r.URL.Query()
484 redirQuery.Del("api_token")
488 newu, err := u.Parse(location)
490 w.WriteHeader(http.StatusInternalServerError)
498 RawQuery: redirQuery.Encode(),
501 w.Header().Add("Location", redir)
502 w.WriteHeader(http.StatusSeeOther)
503 io.WriteString(w, `<A href="`)
504 io.WriteString(w, html.EscapeString(redir))
505 io.WriteString(w, `">Continue</A>`)