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 user
105 // credentials ("user credentials" as defined by CORS,
106 // i.e., cookies, HTTP authentication, and client-side
107 // SSL certificates. See
108 // http://www.w3.org/TR/cors/#user-credentials).
109 w.Header().Set("Access-Control-Allow-Origin", "*")
112 arv := clientPool.Get()
114 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+clientPool.Err().Error()
117 defer clientPool.Put(arv)
119 pathParts := strings.Split(r.URL.Path[1:], "/")
122 var targetPath []string
124 var reqTokens []string
127 credentialsOK := trustAllContent
129 if r.Host != "" && r.Host == attachmentOnlyHost {
132 } else if r.FormValue("disposition") == "attachment" {
136 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
137 // http://ID.collections.example/PATH...
139 targetPath = pathParts
140 } else if len(pathParts) >= 2 && strings.HasPrefix(pathParts[0], "c=") {
142 targetID = parseCollectionIDFromURL(pathParts[0][2:])
143 targetPath = pathParts[1:]
144 } else if len(pathParts) >= 3 && pathParts[0] == "collections" {
145 if len(pathParts) >= 5 && pathParts[1] == "download" {
146 // /collections/download/ID/TOKEN/PATH...
147 targetID = pathParts[2]
148 tokens = []string{pathParts[3]}
149 targetPath = pathParts[4:]
152 // /collections/ID/PATH...
153 targetID = pathParts[1]
154 tokens = anonymousTokens
155 targetPath = pathParts[2:]
158 statusCode = http.StatusNotFound
162 formToken := r.FormValue("api_token")
163 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
164 // The client provided an explicit token in the POST
165 // body. The Origin header indicates this *might* be
166 // an AJAX request, in which case redirect-with-cookie
167 // won't work: we should just serve the content in the
168 // POST response. This is safe because:
170 // * We're supplying an attachment, not inline
171 // content, so we don't need to convert the POST to
172 // a GET and avoid the "really resubmit form?"
175 // * The token isn't embedded in the URL, so we don't
176 // need to worry about bookmarks and copy/paste.
177 tokens = append(tokens, formToken)
178 } else if formToken != "" {
179 // The client provided an explicit token in the query
180 // string, or a form in POST body. We must put the
181 // token in an HttpOnly cookie, and redirect to the
182 // same URL with the query param redacted and method =
186 // It is not safe to copy the provided token
187 // into a cookie unless the current vhost
188 // (origin) serves only a single collection or
189 // we are in trustAllContent mode.
190 statusCode = http.StatusBadRequest
194 // The HttpOnly flag is necessary to prevent
195 // JavaScript code (included in, or loaded by, a page
196 // in the collection being served) from employing the
197 // user's token beyond reading other files in the same
198 // domain, i.e., same collection.
200 // The 303 redirect is necessary in the case of a GET
201 // request to avoid exposing the token in the Location
202 // bar, and in the case of a POST request to avoid
203 // raising warnings when the user refreshes the
206 http.SetCookie(w, &http.Cookie{
207 Name: "arvados_api_token",
208 Value: auth.EncodeTokenCookie([]byte(formToken)),
213 // Propagate query parameters (except api_token) from
214 // the original request.
215 redirQuery := r.URL.Query()
216 redirQuery.Del("api_token")
221 RawQuery: redirQuery.Encode(),
224 w.Header().Add("Location", redir)
225 statusCode, statusText = http.StatusSeeOther, redir
226 w.WriteHeader(statusCode)
227 io.WriteString(w, `<A href="`)
228 io.WriteString(w, html.EscapeString(redir))
229 io.WriteString(w, `">Continue</A>`)
233 if tokens == nil && strings.HasPrefix(targetPath[0], "t=") {
234 // http://ID.example/t=TOKEN/PATH...
235 // /c=ID/t=TOKEN/PATH...
237 // This form must only be used to pass scoped tokens
238 // that give permission for a single collection. See
239 // FormValue case above.
240 tokens = []string{targetPath[0][2:]}
242 targetPath = targetPath[1:]
247 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
249 tokens = append(reqTokens, anonymousTokens...)
252 if len(targetPath) > 0 && targetPath[0] == "_" {
253 // If a collection has a directory called "t=foo" or
254 // "_", it can be served at
255 // //collections.example/_/t=foo/ or
256 // //collections.example/_/_/ respectively:
257 // //collections.example/t=foo/ won't work because
258 // t=foo will be interpreted as a token "foo".
259 targetPath = targetPath[1:]
262 tokenResult := make(map[string]int)
263 collection := make(map[string]interface{})
265 for _, arv.ApiToken = range tokens {
266 err := arv.Get("collections", targetID, nil, &collection)
272 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
273 switch srvErr.HttpStatusCode {
275 // Token broken or insufficient to
276 // retrieve collection
277 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
281 // Something more serious is wrong
282 statusCode, statusText = http.StatusInternalServerError, err.Error()
286 if pathToken || !credentialsOK {
287 // Either the URL is a "secret sharing link"
288 // that didn't work out (and asking the client
289 // for additional credentials would just be
290 // confusing), or we don't even accept
291 // credentials at this path.
292 statusCode = http.StatusNotFound
295 for _, t := range reqTokens {
296 if tokenResult[t] == 404 {
297 // The client provided valid token(s), but the
298 // collection was not found.
299 statusCode = http.StatusNotFound
303 // The client's token was invalid (e.g., expired), or
304 // the client didn't even provide one. Propagate the
305 // 401 to encourage the client to use a [different]
308 // TODO(TC): This response would be confusing to
309 // someone trying (anonymously) to download public
310 // data that has been deleted. Allow a referrer to
311 // provide this context somehow?
312 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
313 statusCode = http.StatusUnauthorized
317 filename := strings.Join(targetPath, "/")
318 kc, err := keepclient.MakeKeepClient(arv)
320 statusCode, statusText = http.StatusInternalServerError, err.Error()
323 if kc.Client != nil && kc.Client.Transport != nil {
324 // Workaround for https://dev.arvados.org/issues/9005
325 if t, ok := kc.Client.Transport.(*http.Transport); ok {
326 defer t.CloseIdleConnections()
329 rdr, err := kc.CollectionFileReader(collection, filename)
330 if os.IsNotExist(err) {
331 statusCode = http.StatusNotFound
333 } else if err != nil {
334 statusCode, statusText = http.StatusBadGateway, err.Error()
339 basenamePos := strings.LastIndex(filename, "/")
343 extPos := strings.LastIndex(filename, ".")
344 if extPos > basenamePos {
345 // Now extPos is safely >= 0.
346 if t := mime.TypeByExtension(filename[extPos:]); t != "" {
347 w.Header().Set("Content-Type", t)
350 if rdr, ok := rdr.(keepclient.ReadCloserWithLen); ok {
351 w.Header().Set("Content-Length", fmt.Sprintf("%d", rdr.Len()))
354 applyContentDispositionHdr(w, r, filename[basenamePos:], attachment)
355 rangeRdr, statusCode := applyRangeHdr(w, r, rdr)
357 w.WriteHeader(statusCode)
358 _, err = io.Copy(w, rangeRdr)
360 statusCode, statusText = http.StatusBadGateway, err.Error()
364 var rangeRe = regexp.MustCompile(`^bytes=0-([0-9]*)$`)
366 func applyRangeHdr(w http.ResponseWriter, r *http.Request, rdr keepclient.ReadCloserWithLen) (io.Reader, int) {
367 w.Header().Set("Accept-Ranges", "bytes")
368 hdr := r.Header.Get("Range")
369 fields := rangeRe.FindStringSubmatch(hdr)
371 return rdr, http.StatusOK
373 rangeEnd, err := strconv.ParseInt(fields[1], 10, 64)
375 // Empty or too big for int64 == send entire content
376 return rdr, http.StatusOK
378 if uint64(rangeEnd) >= rdr.Len() {
379 return rdr, http.StatusOK
381 w.Header().Set("Content-Length", fmt.Sprintf("%d", rangeEnd+1))
382 w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", 0, rangeEnd, rdr.Len()))
383 return &io.LimitedReader{R: rdr, N: rangeEnd + 1}, http.StatusPartialContent
386 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
387 disposition := "inline"
389 disposition = "attachment"
391 if strings.ContainsRune(r.RequestURI, '?') {
392 // Help the UA realize that the filename is just
393 // "filename.txt", not
394 // "filename.txt?disposition=attachment".
396 // TODO(TC): Follow advice at RFC 6266 appendix D
397 disposition += "; filename=" + strconv.QuoteToASCII(filename)
399 if disposition != "inline" {
400 w.Header().Set("Content-Disposition", disposition)