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 == "OPTIONS" {
98 method := r.Header.Get("Access-Control-Request-Method")
99 if method != "GET" && method != "POST" {
100 statusCode = http.StatusMethodNotAllowed
103 w.Header().Set("Access-Control-Allow-Headers", "Range")
104 w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
105 w.Header().Set("Access-Control-Allow-Origin", "*")
106 w.Header().Set("Access-Control-Max-Age", "86400")
107 statusCode = http.StatusOK
111 if r.Method != "GET" && r.Method != "POST" {
112 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
116 if r.Header.Get("Origin") != "" {
117 // Allow simple cross-origin requests without user
118 // credentials ("user credentials" as defined by CORS,
119 // i.e., cookies, HTTP authentication, and client-side
120 // SSL certificates. See
121 // http://www.w3.org/TR/cors/#user-credentials).
122 w.Header().Set("Access-Control-Allow-Origin", "*")
125 arv := h.clientPool.Get()
127 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
130 defer h.clientPool.Put(arv)
132 pathParts := strings.Split(r.URL.Path[1:], "/")
135 var targetPath []string
137 var reqTokens []string
140 credentialsOK := h.Config.TrustAllContent
142 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
145 } else if r.FormValue("disposition") == "attachment" {
149 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
150 // http://ID.collections.example/PATH...
152 targetPath = pathParts
153 } else if len(pathParts) >= 2 && strings.HasPrefix(pathParts[0], "c=") {
155 targetID = parseCollectionIDFromURL(pathParts[0][2:])
156 targetPath = pathParts[1:]
157 } else if len(pathParts) >= 3 && pathParts[0] == "collections" {
158 if len(pathParts) >= 5 && pathParts[1] == "download" {
159 // /collections/download/ID/TOKEN/PATH...
160 targetID = parseCollectionIDFromURL(pathParts[2])
161 tokens = []string{pathParts[3]}
162 targetPath = pathParts[4:]
165 // /collections/ID/PATH...
166 targetID = parseCollectionIDFromURL(pathParts[1])
167 tokens = h.Config.AnonymousTokens
168 targetPath = pathParts[2:]
173 statusCode = http.StatusNotFound
177 formToken := r.FormValue("api_token")
178 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
179 // The client provided an explicit token in the POST
180 // body. The Origin header indicates this *might* be
181 // an AJAX request, in which case redirect-with-cookie
182 // won't work: we should just serve the content in the
183 // POST response. This is safe because:
185 // * We're supplying an attachment, not inline
186 // content, so we don't need to convert the POST to
187 // a GET and avoid the "really resubmit form?"
190 // * The token isn't embedded in the URL, so we don't
191 // need to worry about bookmarks and copy/paste.
192 tokens = append(tokens, formToken)
193 } else if formToken != "" {
194 // The client provided an explicit token in the query
195 // string, or a form in POST body. We must put the
196 // token in an HttpOnly cookie, and redirect to the
197 // same URL with the query param redacted and method =
201 // It is not safe to copy the provided token
202 // into a cookie unless the current vhost
203 // (origin) serves only a single collection or
204 // we are in TrustAllContent mode.
205 statusCode = http.StatusBadRequest
209 // The HttpOnly flag is necessary to prevent
210 // JavaScript code (included in, or loaded by, a page
211 // in the collection being served) from employing the
212 // user's token beyond reading other files in the same
213 // domain, i.e., same collection.
215 // The 303 redirect is necessary in the case of a GET
216 // request to avoid exposing the token in the Location
217 // bar, and in the case of a POST request to avoid
218 // raising warnings when the user refreshes the
221 http.SetCookie(w, &http.Cookie{
222 Name: "arvados_api_token",
223 Value: auth.EncodeTokenCookie([]byte(formToken)),
228 // Propagate query parameters (except api_token) from
229 // the original request.
230 redirQuery := r.URL.Query()
231 redirQuery.Del("api_token")
236 RawQuery: redirQuery.Encode(),
239 w.Header().Add("Location", redir)
240 statusCode, statusText = http.StatusSeeOther, redir
241 w.WriteHeader(statusCode)
242 io.WriteString(w, `<A href="`)
243 io.WriteString(w, html.EscapeString(redir))
244 io.WriteString(w, `">Continue</A>`)
248 if tokens == nil && strings.HasPrefix(targetPath[0], "t=") {
249 // http://ID.example/t=TOKEN/PATH...
250 // /c=ID/t=TOKEN/PATH...
252 // This form must only be used to pass scoped tokens
253 // that give permission for a single collection. See
254 // FormValue case above.
255 tokens = []string{targetPath[0][2:]}
257 targetPath = targetPath[1:]
262 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
264 tokens = append(reqTokens, h.Config.AnonymousTokens...)
267 if len(targetPath) > 0 && targetPath[0] == "_" {
268 // If a collection has a directory called "t=foo" or
269 // "_", it can be served at
270 // //collections.example/_/t=foo/ or
271 // //collections.example/_/_/ respectively:
272 // //collections.example/t=foo/ won't work because
273 // t=foo will be interpreted as a token "foo".
274 targetPath = targetPath[1:]
277 tokenResult := make(map[string]int)
278 collection := make(map[string]interface{})
280 for _, arv.ApiToken = range tokens {
281 err := arv.Get("collections", targetID, nil, &collection)
287 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
288 switch srvErr.HttpStatusCode {
290 // Token broken or insufficient to
291 // retrieve collection
292 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
296 // Something more serious is wrong
297 statusCode, statusText = http.StatusInternalServerError, err.Error()
301 if pathToken || !credentialsOK {
302 // Either the URL is a "secret sharing link"
303 // that didn't work out (and asking the client
304 // for additional credentials would just be
305 // confusing), or we don't even accept
306 // credentials at this path.
307 statusCode = http.StatusNotFound
310 for _, t := range reqTokens {
311 if tokenResult[t] == 404 {
312 // The client provided valid token(s), but the
313 // collection was not found.
314 statusCode = http.StatusNotFound
318 // The client's token was invalid (e.g., expired), or
319 // the client didn't even provide one. Propagate the
320 // 401 to encourage the client to use a [different]
323 // TODO(TC): This response would be confusing to
324 // someone trying (anonymously) to download public
325 // data that has been deleted. Allow a referrer to
326 // provide this context somehow?
327 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
328 statusCode = http.StatusUnauthorized
332 filename := strings.Join(targetPath, "/")
333 kc, err := keepclient.MakeKeepClient(arv)
335 statusCode, statusText = http.StatusInternalServerError, err.Error()
338 if kc.Client != nil && kc.Client.Transport != nil {
339 // Workaround for https://dev.arvados.org/issues/9005
340 if t, ok := kc.Client.Transport.(*http.Transport); ok {
341 defer t.CloseIdleConnections()
344 rdr, err := kc.CollectionFileReader(collection, filename)
345 if os.IsNotExist(err) {
346 statusCode = http.StatusNotFound
348 } else if err != nil {
349 statusCode, statusText = http.StatusBadGateway, err.Error()
354 basename := path.Base(filename)
355 applyContentDispositionHdr(w, r, basename, attachment)
357 modstr, _ := collection["modified_at"].(string)
358 modtime, err := time.Parse(time.RFC3339Nano, modstr)
362 http.ServeContent(w, r, basename, modtime, rdr)
365 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
366 disposition := "inline"
368 disposition = "attachment"
370 if strings.ContainsRune(r.RequestURI, '?') {
371 // Help the UA realize that the filename is just
372 // "filename.txt", not
373 // "filename.txt?disposition=attachment".
375 // TODO(TC): Follow advice at RFC 6266 appendix D
376 disposition += "; filename=" + strconv.QuoteToASCII(filename)
378 if disposition != "inline" {
379 w.Header().Set("Content-Disposition", disposition)