16 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
17 "git.curoverse.com/arvados.git/sdk/go/auth"
18 "git.curoverse.com/arvados.git/sdk/go/httpserver"
19 "git.curoverse.com/arvados.git/sdk/go/keepclient"
25 clientPool = arvadosclient.MakeClientPool()
26 trustAllContent = false
27 attachmentOnlyHost = ""
31 flag.StringVar(&attachmentOnlyHost, "attachment-only-host", "",
32 "Accept credentials, and add \"Content-Disposition: attachment\" response headers, for requests at this hostname:port. Prohibiting inline display makes it possible to serve untrusted and non-public content from a single origin, i.e., without wildcard DNS or SSL.")
33 flag.BoolVar(&trustAllContent, "trust-all-content", false,
34 "Serve non-public content from a single origin. Dangerous: read docs before using!")
37 // return a UUID or PDH if s begins with a UUID or URL-encoded PDH;
38 // otherwise return "".
39 func parseCollectionIDFromDNSName(s string) string {
41 if i := strings.IndexRune(s, '.'); i >= 0 {
44 // Names like {uuid}--collections.example.com serve the same
45 // purpose as {uuid}.collections.example.com but can reduce
46 // cost/effort of using [additional] wildcard certificates.
47 if i := strings.Index(s, "--"); i >= 0 {
50 if arvadosclient.UUIDMatch(s) {
53 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
59 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
61 // return a UUID or PDH if s is a UUID or a PDH (even if it is a PDH
62 // with "+" replaced by " " or "-"); otherwise return "".
63 func parseCollectionIDFromURL(s string) string {
64 if arvadosclient.UUIDMatch(s) {
67 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
73 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
77 remoteAddr := r.RemoteAddr
78 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
79 remoteAddr = xff + "," + remoteAddr
82 w := httpserver.WrapResponseWriter(wOrig)
85 statusCode = w.WroteStatus()
86 } else if w.WroteStatus() == 0 {
87 w.WriteHeader(statusCode)
88 } else if w.WroteStatus() != statusCode {
89 httpserver.Log(r.RemoteAddr, "WARNING",
90 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
93 statusText = http.StatusText(statusCode)
95 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
98 if r.Method != "GET" && r.Method != "POST" {
99 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
103 if r.Header.Get("Origin") != "" {
104 // Allow simple cross-origin requests, without
106 w.Header().Set("Access-Control-Allow-Origin", "*")
109 arv := clientPool.Get()
111 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+clientPool.Err().Error()
114 defer clientPool.Put(arv)
116 pathParts := strings.Split(r.URL.Path[1:], "/")
119 var targetPath []string
121 var reqTokens []string
124 credentialsOK := trustAllContent
126 if r.Host != "" && r.Host == attachmentOnlyHost {
129 } else if r.FormValue("disposition") == "attachment" {
133 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
134 // http://ID.collections.example/PATH...
136 targetPath = pathParts
137 } else if len(pathParts) >= 2 && strings.HasPrefix(pathParts[0], "c=") {
139 targetID = parseCollectionIDFromURL(pathParts[0][2:])
140 targetPath = pathParts[1:]
141 } else if len(pathParts) >= 3 && pathParts[0] == "collections" {
142 if len(pathParts) >= 5 && pathParts[1] == "download" {
143 // /collections/download/ID/TOKEN/PATH...
144 targetID = pathParts[2]
145 tokens = []string{pathParts[3]}
146 targetPath = pathParts[4:]
149 // /collections/ID/PATH...
150 targetID = pathParts[1]
151 tokens = anonymousTokens
152 targetPath = pathParts[2:]
155 statusCode = http.StatusNotFound
159 formToken := r.FormValue("api_token")
160 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
161 // The client provided an explicit token in the POST
162 // body. The Origin header indicates this *might* be
163 // an AJAX request, in which case redirect-with-cookie
164 // won't work: we should just serve the content in the
165 // POST response. This is safe because:
167 // * We're supplying an attachment, not inline
168 // content, so we don't need to convert the POST to
169 // a GET and avoid the "really resubmit form?"
172 // * The token isn't embedded in the URL, so we don't
173 // need to worry about bookmarks and copy/paste.
174 tokens = append(tokens, formToken)
175 } else if formToken != "" {
176 // The client provided an explicit token in the query
177 // string, or a form in POST body. We must put the
178 // token in an HttpOnly cookie, and redirect to the
179 // same URL with the query param redacted and method =
183 // It is not safe to copy the provided token
184 // into a cookie unless the current vhost
185 // (origin) serves only a single collection or
186 // we are in trustAllContent mode.
187 statusCode = http.StatusBadRequest
191 // The HttpOnly flag is necessary to prevent
192 // JavaScript code (included in, or loaded by, a page
193 // in the collection being served) from employing the
194 // user's token beyond reading other files in the same
195 // domain, i.e., same collection.
197 // The 303 redirect is necessary in the case of a GET
198 // request to avoid exposing the token in the Location
199 // bar, and in the case of a POST request to avoid
200 // raising warnings when the user refreshes the
203 http.SetCookie(w, &http.Cookie{
204 Name: "arvados_api_token",
205 Value: auth.EncodeTokenCookie([]byte(formToken)),
210 // Propagate query parameters (except api_token) from
211 // the original request.
212 redirQuery := r.URL.Query()
213 redirQuery.Del("api_token")
218 RawQuery: redirQuery.Encode(),
221 w.Header().Add("Location", redir)
222 statusCode, statusText = http.StatusSeeOther, redir
223 w.WriteHeader(statusCode)
224 io.WriteString(w, `<A href="`)
225 io.WriteString(w, html.EscapeString(redir))
226 io.WriteString(w, `">Continue</A>`)
230 if tokens == nil && strings.HasPrefix(targetPath[0], "t=") {
231 // http://ID.example/t=TOKEN/PATH...
232 // /c=ID/t=TOKEN/PATH...
234 // This form must only be used to pass scoped tokens
235 // that give permission for a single collection. See
236 // FormValue case above.
237 tokens = []string{targetPath[0][2:]}
239 targetPath = targetPath[1:]
244 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
246 tokens = append(reqTokens, anonymousTokens...)
249 if len(targetPath) > 0 && targetPath[0] == "_" {
250 // If a collection has a directory called "t=foo" or
251 // "_", it can be served at
252 // //collections.example/_/t=foo/ or
253 // //collections.example/_/_/ respectively:
254 // //collections.example/t=foo/ won't work because
255 // t=foo will be interpreted as a token "foo".
256 targetPath = targetPath[1:]
259 tokenResult := make(map[string]int)
260 collection := make(map[string]interface{})
262 for _, arv.ApiToken = range tokens {
263 err := arv.Get("collections", targetID, nil, &collection)
269 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
270 switch srvErr.HttpStatusCode {
272 // Token broken or insufficient to
273 // retrieve collection
274 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
278 // Something more serious is wrong
279 statusCode, statusText = http.StatusInternalServerError, err.Error()
283 if pathToken || !credentialsOK {
284 // Either the URL is a "secret sharing link"
285 // that didn't work out (and asking the client
286 // for additional credentials would just be
287 // confusing), or we don't even accept
288 // credentials at this path.
289 statusCode = http.StatusNotFound
292 for _, t := range reqTokens {
293 if tokenResult[t] == 404 {
294 // The client provided valid token(s), but the
295 // collection was not found.
296 statusCode = http.StatusNotFound
300 // The client's token was invalid (e.g., expired), or
301 // the client didn't even provide one. Propagate the
302 // 401 to encourage the client to use a [different]
305 // TODO(TC): This response would be confusing to
306 // someone trying (anonymously) to download public
307 // data that has been deleted. Allow a referrer to
308 // provide this context somehow?
309 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
310 statusCode = http.StatusUnauthorized
314 filename := strings.Join(targetPath, "/")
315 kc, err := keepclient.MakeKeepClient(arv)
317 statusCode, statusText = http.StatusInternalServerError, err.Error()
320 rdr, err := kc.CollectionFileReader(collection, filename)
321 if os.IsNotExist(err) {
322 statusCode = http.StatusNotFound
324 } else if err != nil {
325 statusCode, statusText = http.StatusBadGateway, err.Error()
330 basenamePos := strings.LastIndex(filename, "/")
334 extPos := strings.LastIndex(filename, ".")
335 if extPos > basenamePos {
336 // Now extPos is safely >= 0.
337 if t := mime.TypeByExtension(filename[extPos:]); t != "" {
338 w.Header().Set("Content-Type", t)
341 if rdr, ok := rdr.(keepclient.ReadCloserWithLen); ok {
342 w.Header().Set("Content-Length", fmt.Sprintf("%d", rdr.Len()))
345 applyContentDispositionHdr(w, r, filename[basenamePos:], attachment)
346 rangeRdr, statusCode := applyRangeHdr(w, r, rdr)
348 w.WriteHeader(statusCode)
349 _, err = io.Copy(w, rangeRdr)
351 statusCode, statusText = http.StatusBadGateway, err.Error()
355 var rangeRe = regexp.MustCompile(`^bytes=0-([0-9]*)$`)
357 func applyRangeHdr(w http.ResponseWriter, r *http.Request, rdr keepclient.ReadCloserWithLen) (io.Reader, int) {
358 w.Header().Set("Accept-Ranges", "bytes")
359 hdr := r.Header.Get("Range")
360 fields := rangeRe.FindStringSubmatch(hdr)
362 return rdr, http.StatusOK
364 rangeEnd, err := strconv.ParseInt(fields[1], 10, 64)
366 // Empty or too big for int64 == send entire content
367 return rdr, http.StatusOK
369 if uint64(rangeEnd) >= rdr.Len() {
370 return rdr, http.StatusOK
372 w.Header().Set("Content-Length", fmt.Sprintf("%d", rangeEnd+1))
373 w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", 0, rangeEnd, rdr.Len()))
374 return &io.LimitedReader{R: rdr, N: rangeEnd + 1}, http.StatusPartialContent
377 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
378 disposition := "inline"
380 disposition = "attachment"
382 if strings.ContainsRune(r.RequestURI, '?') {
383 // Help the UA realize that the filename is just
384 // "filename.txt", not
385 // "filename.txt?disposition=attachment".
387 // TODO(TC): Follow advice at RFC 6266 appendix D
388 disposition += "; filename=" + strconv.QuoteToASCII(filename)
390 if disposition != "inline" {
391 w.Header().Set("Content-Disposition", disposition)