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"
24 clientPool *arvadosclient.ClientPool
28 // parseCollectionIDFromDNSName returns a UUID or PDH if s begins with
29 // a UUID or URL-encoded PDH; otherwise "".
30 func parseCollectionIDFromDNSName(s string) string {
32 if i := strings.IndexRune(s, '.'); i >= 0 {
35 // Names like {uuid}--collections.example.com serve the same
36 // purpose as {uuid}.collections.example.com but can reduce
37 // cost/effort of using [additional] wildcard certificates.
38 if i := strings.Index(s, "--"); i >= 0 {
41 if arvadosclient.UUIDMatch(s) {
44 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
50 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
52 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
53 // PDH (even if it is a PDH with "+" replaced by " " or "-");
55 func parseCollectionIDFromURL(s string) string {
56 if arvadosclient.UUIDMatch(s) {
59 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
65 func (h *handler) setup() {
66 h.clientPool = arvadosclient.MakeClientPool()
69 // ServeHTTP implements http.Handler.
70 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
71 h.setupOnce.Do(h.setup)
76 remoteAddr := r.RemoteAddr
77 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
78 remoteAddr = xff + "," + remoteAddr
81 w := httpserver.WrapResponseWriter(wOrig)
84 statusCode = w.WroteStatus()
85 } else if w.WroteStatus() == 0 {
86 w.WriteHeader(statusCode)
87 } else if w.WroteStatus() != statusCode {
88 httpserver.Log(r.RemoteAddr, "WARNING",
89 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
92 statusText = http.StatusText(statusCode)
94 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
97 if r.Method != "GET" && r.Method != "POST" {
98 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
102 if r.Header.Get("Origin") != "" {
103 // Allow simple cross-origin requests without user
104 // credentials ("user credentials" as defined by CORS,
105 // i.e., cookies, HTTP authentication, and client-side
106 // SSL certificates. See
107 // http://www.w3.org/TR/cors/#user-credentials).
108 w.Header().Set("Access-Control-Allow-Origin", "*")
111 arv := h.clientPool.Get()
113 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
116 defer h.clientPool.Put(arv)
118 pathParts := strings.Split(r.URL.Path[1:], "/")
121 var targetPath []string
123 var reqTokens []string
126 credentialsOK := h.Config.TrustAllContent
128 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
131 } else if r.FormValue("disposition") == "attachment" {
135 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
136 // http://ID.collections.example/PATH...
138 targetPath = pathParts
139 } else if len(pathParts) >= 2 && strings.HasPrefix(pathParts[0], "c=") {
141 targetID = parseCollectionIDFromURL(pathParts[0][2:])
142 targetPath = pathParts[1:]
143 } else if len(pathParts) >= 3 && pathParts[0] == "collections" {
144 if len(pathParts) >= 5 && pathParts[1] == "download" {
145 // /collections/download/ID/TOKEN/PATH...
146 targetID = pathParts[2]
147 tokens = []string{pathParts[3]}
148 targetPath = pathParts[4:]
151 // /collections/ID/PATH...
152 targetID = pathParts[1]
153 tokens = h.Config.AnonymousTokens
154 targetPath = pathParts[2:]
157 statusCode = http.StatusNotFound
161 formToken := r.FormValue("api_token")
162 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
163 // The client provided an explicit token in the POST
164 // body. The Origin header indicates this *might* be
165 // an AJAX request, in which case redirect-with-cookie
166 // won't work: we should just serve the content in the
167 // POST response. This is safe because:
169 // * We're supplying an attachment, not inline
170 // content, so we don't need to convert the POST to
171 // a GET and avoid the "really resubmit form?"
174 // * The token isn't embedded in the URL, so we don't
175 // need to worry about bookmarks and copy/paste.
176 tokens = append(tokens, formToken)
177 } else if formToken != "" {
178 // The client provided an explicit token in the query
179 // string, or a form in POST body. We must put the
180 // token in an HttpOnly cookie, and redirect to the
181 // same URL with the query param redacted and method =
185 // It is not safe to copy the provided token
186 // into a cookie unless the current vhost
187 // (origin) serves only a single collection or
188 // we are in TrustAllContent mode.
189 statusCode = http.StatusBadRequest
193 // The HttpOnly flag is necessary to prevent
194 // JavaScript code (included in, or loaded by, a page
195 // in the collection being served) from employing the
196 // user's token beyond reading other files in the same
197 // domain, i.e., same collection.
199 // The 303 redirect is necessary in the case of a GET
200 // request to avoid exposing the token in the Location
201 // bar, and in the case of a POST request to avoid
202 // raising warnings when the user refreshes the
205 http.SetCookie(w, &http.Cookie{
206 Name: "arvados_api_token",
207 Value: auth.EncodeTokenCookie([]byte(formToken)),
212 // Propagate query parameters (except api_token) from
213 // the original request.
214 redirQuery := r.URL.Query()
215 redirQuery.Del("api_token")
220 RawQuery: redirQuery.Encode(),
223 w.Header().Add("Location", redir)
224 statusCode, statusText = http.StatusSeeOther, redir
225 w.WriteHeader(statusCode)
226 io.WriteString(w, `<A href="`)
227 io.WriteString(w, html.EscapeString(redir))
228 io.WriteString(w, `">Continue</A>`)
232 if tokens == nil && strings.HasPrefix(targetPath[0], "t=") {
233 // http://ID.example/t=TOKEN/PATH...
234 // /c=ID/t=TOKEN/PATH...
236 // This form must only be used to pass scoped tokens
237 // that give permission for a single collection. See
238 // FormValue case above.
239 tokens = []string{targetPath[0][2:]}
241 targetPath = targetPath[1:]
246 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
248 tokens = append(reqTokens, h.Config.AnonymousTokens...)
251 if len(targetPath) > 0 && targetPath[0] == "_" {
252 // If a collection has a directory called "t=foo" or
253 // "_", it can be served at
254 // //collections.example/_/t=foo/ or
255 // //collections.example/_/_/ respectively:
256 // //collections.example/t=foo/ won't work because
257 // t=foo will be interpreted as a token "foo".
258 targetPath = targetPath[1:]
261 tokenResult := make(map[string]int)
262 collection := make(map[string]interface{})
264 for _, arv.ApiToken = range tokens {
265 err := arv.Get("collections", targetID, nil, &collection)
271 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
272 switch srvErr.HttpStatusCode {
274 // Token broken or insufficient to
275 // retrieve collection
276 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
280 // Something more serious is wrong
281 statusCode, statusText = http.StatusInternalServerError, err.Error()
285 if pathToken || !credentialsOK {
286 // Either the URL is a "secret sharing link"
287 // that didn't work out (and asking the client
288 // for additional credentials would just be
289 // confusing), or we don't even accept
290 // credentials at this path.
291 statusCode = http.StatusNotFound
294 for _, t := range reqTokens {
295 if tokenResult[t] == 404 {
296 // The client provided valid token(s), but the
297 // collection was not found.
298 statusCode = http.StatusNotFound
302 // The client's token was invalid (e.g., expired), or
303 // the client didn't even provide one. Propagate the
304 // 401 to encourage the client to use a [different]
307 // TODO(TC): This response would be confusing to
308 // someone trying (anonymously) to download public
309 // data that has been deleted. Allow a referrer to
310 // provide this context somehow?
311 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
312 statusCode = http.StatusUnauthorized
316 filename := strings.Join(targetPath, "/")
317 kc, err := keepclient.MakeKeepClient(arv)
319 statusCode, statusText = http.StatusInternalServerError, err.Error()
322 if kc.Client != nil && kc.Client.Transport != nil {
323 // Workaround for https://dev.arvados.org/issues/9005
324 if t, ok := kc.Client.Transport.(*http.Transport); ok {
325 defer t.CloseIdleConnections()
328 rdr, err := kc.CollectionFileReader(collection, filename)
329 if os.IsNotExist(err) {
330 statusCode = http.StatusNotFound
332 } else if err != nil {
333 statusCode, statusText = http.StatusBadGateway, err.Error()
338 basenamePos := strings.LastIndex(filename, "/")
342 extPos := strings.LastIndex(filename, ".")
343 if extPos > basenamePos {
344 // Now extPos is safely >= 0.
345 if t := mime.TypeByExtension(filename[extPos:]); t != "" {
346 w.Header().Set("Content-Type", t)
349 if rdr, ok := rdr.(keepclient.ReadCloserWithLen); ok {
350 w.Header().Set("Content-Length", fmt.Sprintf("%d", rdr.Len()))
353 applyContentDispositionHdr(w, r, filename[basenamePos:], attachment)
354 rangeRdr, statusCode := applyRangeHdr(w, r, rdr)
356 w.WriteHeader(statusCode)
357 _, err = io.Copy(w, rangeRdr)
359 statusCode, statusText = http.StatusBadGateway, err.Error()
363 var rangeRe = regexp.MustCompile(`^bytes=0-([0-9]*)$`)
365 func applyRangeHdr(w http.ResponseWriter, r *http.Request, rdr keepclient.ReadCloserWithLen) (io.Reader, int) {
366 w.Header().Set("Accept-Ranges", "bytes")
367 hdr := r.Header.Get("Range")
368 fields := rangeRe.FindStringSubmatch(hdr)
370 return rdr, http.StatusOK
372 rangeEnd, err := strconv.ParseInt(fields[1], 10, 64)
374 // Empty or too big for int64 == send entire content
375 return rdr, http.StatusOK
377 if uint64(rangeEnd) >= rdr.Len() {
378 return rdr, http.StatusOK
380 w.Header().Set("Content-Length", fmt.Sprintf("%d", rangeEnd+1))
381 w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", 0, rangeEnd, rdr.Len()))
382 return &io.LimitedReader{R: rdr, N: rangeEnd + 1}, http.StatusPartialContent
385 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
386 disposition := "inline"
388 disposition = "attachment"
390 if strings.ContainsRune(r.RequestURI, '?') {
391 // Help the UA realize that the filename is just
392 // "filename.txt", not
393 // "filename.txt?disposition=attachment".
395 // TODO(TC): Follow advice at RFC 6266 appendix D
396 disposition += "; filename=" + strconv.QuoteToASCII(filename)
398 if disposition != "inline" {
399 w.Header().Set("Content-Disposition", disposition)