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()
67 keepclient.ClearCacheOnSIGHUP()
70 // ServeHTTP implements http.Handler.
71 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
72 h.setupOnce.Do(h.setup)
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 == "OPTIONS" {
99 method := r.Header.Get("Access-Control-Request-Method")
100 if method != "GET" && method != "POST" {
101 statusCode = http.StatusMethodNotAllowed
104 w.Header().Set("Access-Control-Allow-Headers", "Range")
105 w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
106 w.Header().Set("Access-Control-Allow-Origin", "*")
107 w.Header().Set("Access-Control-Max-Age", "86400")
108 statusCode = http.StatusOK
112 if r.Method != "GET" && r.Method != "POST" {
113 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
117 if r.Header.Get("Origin") != "" {
118 // Allow simple cross-origin requests without user
119 // credentials ("user credentials" as defined by CORS,
120 // i.e., cookies, HTTP authentication, and client-side
121 // SSL certificates. See
122 // http://www.w3.org/TR/cors/#user-credentials).
123 w.Header().Set("Access-Control-Allow-Origin", "*")
126 arv := h.clientPool.Get()
128 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
131 defer h.clientPool.Put(arv)
133 pathParts := strings.Split(r.URL.Path[1:], "/")
136 var targetPath []string
138 var reqTokens []string
141 credentialsOK := h.Config.TrustAllContent
143 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
146 } else if r.FormValue("disposition") == "attachment" {
150 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
151 // http://ID.collections.example/PATH...
153 targetPath = pathParts
154 } else if len(pathParts) >= 2 && strings.HasPrefix(pathParts[0], "c=") {
156 targetID = parseCollectionIDFromURL(pathParts[0][2:])
157 targetPath = pathParts[1:]
158 } else if len(pathParts) >= 3 && pathParts[0] == "collections" {
159 if len(pathParts) >= 5 && pathParts[1] == "download" {
160 // /collections/download/ID/TOKEN/PATH...
161 targetID = parseCollectionIDFromURL(pathParts[2])
162 tokens = []string{pathParts[3]}
163 targetPath = pathParts[4:]
166 // /collections/ID/PATH...
167 targetID = parseCollectionIDFromURL(pathParts[1])
168 tokens = h.Config.AnonymousTokens
169 targetPath = pathParts[2:]
174 statusCode = http.StatusNotFound
178 formToken := r.FormValue("api_token")
179 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
180 // The client provided an explicit token in the POST
181 // body. The Origin header indicates this *might* be
182 // an AJAX request, in which case redirect-with-cookie
183 // won't work: we should just serve the content in the
184 // POST response. This is safe because:
186 // * We're supplying an attachment, not inline
187 // content, so we don't need to convert the POST to
188 // a GET and avoid the "really resubmit form?"
191 // * The token isn't embedded in the URL, so we don't
192 // need to worry about bookmarks and copy/paste.
193 tokens = append(tokens, formToken)
194 } else if formToken != "" {
195 // The client provided an explicit token in the query
196 // string, or a form in POST body. We must put the
197 // token in an HttpOnly cookie, and redirect to the
198 // same URL with the query param redacted and method =
202 // It is not safe to copy the provided token
203 // into a cookie unless the current vhost
204 // (origin) serves only a single collection or
205 // we are in TrustAllContent mode.
206 statusCode = http.StatusBadRequest
210 // The HttpOnly flag is necessary to prevent
211 // JavaScript code (included in, or loaded by, a page
212 // in the collection being served) from employing the
213 // user's token beyond reading other files in the same
214 // domain, i.e., same collection.
216 // The 303 redirect is necessary in the case of a GET
217 // request to avoid exposing the token in the Location
218 // bar, and in the case of a POST request to avoid
219 // raising warnings when the user refreshes the
222 http.SetCookie(w, &http.Cookie{
223 Name: "arvados_api_token",
224 Value: auth.EncodeTokenCookie([]byte(formToken)),
229 // Propagate query parameters (except api_token) from
230 // the original request.
231 redirQuery := r.URL.Query()
232 redirQuery.Del("api_token")
237 RawQuery: redirQuery.Encode(),
240 w.Header().Add("Location", redir)
241 statusCode, statusText = http.StatusSeeOther, redir
242 w.WriteHeader(statusCode)
243 io.WriteString(w, `<A href="`)
244 io.WriteString(w, html.EscapeString(redir))
245 io.WriteString(w, `">Continue</A>`)
249 if tokens == nil && strings.HasPrefix(targetPath[0], "t=") {
250 // http://ID.example/t=TOKEN/PATH...
251 // /c=ID/t=TOKEN/PATH...
253 // This form must only be used to pass scoped tokens
254 // that give permission for a single collection. See
255 // FormValue case above.
256 tokens = []string{targetPath[0][2:]}
258 targetPath = targetPath[1:]
263 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
265 tokens = append(reqTokens, h.Config.AnonymousTokens...)
268 if len(targetPath) > 0 && targetPath[0] == "_" {
269 // If a collection has a directory called "t=foo" or
270 // "_", it can be served at
271 // //collections.example/_/t=foo/ or
272 // //collections.example/_/_/ respectively:
273 // //collections.example/t=foo/ won't work because
274 // t=foo will be interpreted as a token "foo".
275 targetPath = targetPath[1:]
278 tokenResult := make(map[string]int)
279 collection := make(map[string]interface{})
281 for _, arv.ApiToken = range tokens {
282 err := arv.Get("collections", targetID, nil, &collection)
288 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
289 switch srvErr.HttpStatusCode {
291 // Token broken or insufficient to
292 // retrieve collection
293 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
297 // Something more serious is wrong
298 statusCode, statusText = http.StatusInternalServerError, err.Error()
302 if pathToken || !credentialsOK {
303 // Either the URL is a "secret sharing link"
304 // that didn't work out (and asking the client
305 // for additional credentials would just be
306 // confusing), or we don't even accept
307 // credentials at this path.
308 statusCode = http.StatusNotFound
311 for _, t := range reqTokens {
312 if tokenResult[t] == 404 {
313 // The client provided valid token(s), but the
314 // collection was not found.
315 statusCode = http.StatusNotFound
319 // The client's token was invalid (e.g., expired), or
320 // the client didn't even provide one. Propagate the
321 // 401 to encourage the client to use a [different]
324 // TODO(TC): This response would be confusing to
325 // someone trying (anonymously) to download public
326 // data that has been deleted. Allow a referrer to
327 // provide this context somehow?
328 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
329 statusCode = http.StatusUnauthorized
333 filename := strings.Join(targetPath, "/")
334 kc, err := keepclient.MakeKeepClient(arv)
336 statusCode, statusText = http.StatusInternalServerError, err.Error()
339 rdr, err := kc.CollectionFileReader(collection, filename)
340 if os.IsNotExist(err) {
341 statusCode = http.StatusNotFound
343 } else if err != nil {
344 statusCode, statusText = http.StatusBadGateway, err.Error()
349 basename := path.Base(filename)
350 applyContentDispositionHdr(w, r, basename, attachment)
352 modstr, _ := collection["modified_at"].(string)
353 modtime, err := time.Parse(time.RFC3339Nano, modstr)
357 http.ServeContent(w, r, basename, modtime, rdr)
360 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
361 disposition := "inline"
363 disposition = "attachment"
365 if strings.ContainsRune(r.RequestURI, '?') {
366 // Help the UA realize that the filename is just
367 // "filename.txt", not
368 // "filename.txt?disposition=attachment".
370 // TODO(TC): Follow advice at RFC 6266 appendix D
371 disposition += "; filename=" + strconv.QuoteToASCII(filename)
373 if disposition != "inline" {
374 w.Header().Set("Content-Disposition", disposition)