17 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
18 "git.curoverse.com/arvados.git/sdk/go/auth"
19 "git.curoverse.com/arvados.git/sdk/go/httpserver"
20 "git.curoverse.com/arvados.git/sdk/go/keepclient"
25 clientPool *arvadosclient.ClientPool
29 // parseCollectionIDFromDNSName returns a UUID or PDH if s begins with
30 // a UUID or URL-encoded PDH; otherwise "".
31 func parseCollectionIDFromDNSName(s string) string {
33 if i := strings.IndexRune(s, '.'); i >= 0 {
36 // Names like {uuid}--collections.example.com serve the same
37 // purpose as {uuid}.collections.example.com but can reduce
38 // cost/effort of using [additional] wildcard certificates.
39 if i := strings.Index(s, "--"); i >= 0 {
42 if arvadosclient.UUIDMatch(s) {
45 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
51 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
53 // parseCollectionIDFromURL returns a UUID or PDH if s is a UUID or a
54 // PDH (even if it is a PDH with "+" replaced by " " or "-");
56 func parseCollectionIDFromURL(s string) string {
57 if arvadosclient.UUIDMatch(s) {
60 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
66 func (h *handler) setup() {
67 h.clientPool = arvadosclient.MakeClientPool()
68 keepclient.RefreshServiceDiscoveryOnSIGHUP()
71 func (h *handler) serveStatus(w http.ResponseWriter, r *http.Request) {
75 cacheStats: h.Config.Cache.Stats(),
77 json.NewEncoder(w).Encode(status)
80 // ServeHTTP implements http.Handler.
81 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
82 h.setupOnce.Do(h.setup)
87 remoteAddr := r.RemoteAddr
88 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
89 remoteAddr = xff + "," + remoteAddr
92 w := httpserver.WrapResponseWriter(wOrig)
95 statusCode = w.WroteStatus()
96 } else if w.WroteStatus() == 0 {
97 w.WriteHeader(statusCode)
98 } else if w.WroteStatus() != statusCode {
99 httpserver.Log(r.RemoteAddr, "WARNING",
100 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
102 if statusText == "" {
103 statusText = http.StatusText(statusCode)
105 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
108 if r.Method == "OPTIONS" {
109 method := r.Header.Get("Access-Control-Request-Method")
110 if method != "GET" && method != "POST" {
111 statusCode = http.StatusMethodNotAllowed
114 w.Header().Set("Access-Control-Allow-Headers", "Range")
115 w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
116 w.Header().Set("Access-Control-Allow-Origin", "*")
117 w.Header().Set("Access-Control-Max-Age", "86400")
118 statusCode = http.StatusOK
122 if r.Method != "GET" && r.Method != "POST" {
123 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
127 if r.Header.Get("Origin") != "" {
128 // Allow simple cross-origin requests without user
129 // credentials ("user credentials" as defined by CORS,
130 // i.e., cookies, HTTP authentication, and client-side
131 // SSL certificates. See
132 // http://www.w3.org/TR/cors/#user-credentials).
133 w.Header().Set("Access-Control-Allow-Origin", "*")
136 arv := h.clientPool.Get()
138 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
141 defer h.clientPool.Put(arv)
143 pathParts := strings.Split(r.URL.Path[1:], "/")
146 var targetPath []string
148 var reqTokens []string
151 credentialsOK := h.Config.TrustAllContent
153 if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
156 } else if r.FormValue("disposition") == "attachment" {
160 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
161 // http://ID.collections.example/PATH...
163 targetPath = pathParts
164 } else if r.URL.Path == "/status.json" {
167 } else if len(pathParts) >= 2 && strings.HasPrefix(pathParts[0], "c=") {
169 targetID = parseCollectionIDFromURL(pathParts[0][2:])
170 targetPath = pathParts[1:]
171 } else if len(pathParts) >= 3 && pathParts[0] == "collections" {
172 if len(pathParts) >= 5 && pathParts[1] == "download" {
173 // /collections/download/ID/TOKEN/PATH...
174 targetID = parseCollectionIDFromURL(pathParts[2])
175 tokens = []string{pathParts[3]}
176 targetPath = pathParts[4:]
179 // /collections/ID/PATH...
180 targetID = parseCollectionIDFromURL(pathParts[1])
181 tokens = h.Config.AnonymousTokens
182 targetPath = pathParts[2:]
187 statusCode = http.StatusNotFound
191 formToken := r.FormValue("api_token")
192 if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
193 // The client provided an explicit token in the POST
194 // body. The Origin header indicates this *might* be
195 // an AJAX request, in which case redirect-with-cookie
196 // won't work: we should just serve the content in the
197 // POST response. This is safe because:
199 // * We're supplying an attachment, not inline
200 // content, so we don't need to convert the POST to
201 // a GET and avoid the "really resubmit form?"
204 // * The token isn't embedded in the URL, so we don't
205 // need to worry about bookmarks and copy/paste.
206 tokens = append(tokens, formToken)
207 } else if formToken != "" {
208 // The client provided an explicit token in the query
209 // string, or a form in POST body. We must put the
210 // token in an HttpOnly cookie, and redirect to the
211 // same URL with the query param redacted and method =
215 // It is not safe to copy the provided token
216 // into a cookie unless the current vhost
217 // (origin) serves only a single collection or
218 // we are in TrustAllContent mode.
219 statusCode = http.StatusBadRequest
223 // The HttpOnly flag is necessary to prevent
224 // JavaScript code (included in, or loaded by, a page
225 // in the collection being served) from employing the
226 // user's token beyond reading other files in the same
227 // domain, i.e., same collection.
229 // The 303 redirect is necessary in the case of a GET
230 // request to avoid exposing the token in the Location
231 // bar, and in the case of a POST request to avoid
232 // raising warnings when the user refreshes the
235 http.SetCookie(w, &http.Cookie{
236 Name: "arvados_api_token",
237 Value: auth.EncodeTokenCookie([]byte(formToken)),
242 // Propagate query parameters (except api_token) from
243 // the original request.
244 redirQuery := r.URL.Query()
245 redirQuery.Del("api_token")
250 RawQuery: redirQuery.Encode(),
253 w.Header().Add("Location", redir)
254 statusCode, statusText = http.StatusSeeOther, redir
255 w.WriteHeader(statusCode)
256 io.WriteString(w, `<A href="`)
257 io.WriteString(w, html.EscapeString(redir))
258 io.WriteString(w, `">Continue</A>`)
262 if tokens == nil && strings.HasPrefix(targetPath[0], "t=") {
263 // http://ID.example/t=TOKEN/PATH...
264 // /c=ID/t=TOKEN/PATH...
266 // This form must only be used to pass scoped tokens
267 // that give permission for a single collection. See
268 // FormValue case above.
269 tokens = []string{targetPath[0][2:]}
271 targetPath = targetPath[1:]
276 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
278 tokens = append(reqTokens, h.Config.AnonymousTokens...)
281 if len(targetPath) > 0 && targetPath[0] == "_" {
282 // If a collection has a directory called "t=foo" or
283 // "_", it can be served at
284 // //collections.example/_/t=foo/ or
285 // //collections.example/_/_/ respectively:
286 // //collections.example/t=foo/ won't work because
287 // t=foo will be interpreted as a token "foo".
288 targetPath = targetPath[1:]
292 if cc := r.Header.Get("Cache-Control"); strings.Contains(cc, "no-cache") || strings.Contains(cc, "must-revalidate") {
296 var collection map[string]interface{}
297 tokenResult := make(map[string]int)
299 for _, arv.ApiToken = range tokens {
301 collection, err = h.Config.Cache.Get(arv, targetID, forceReload)
307 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
308 switch srvErr.HttpStatusCode {
310 // Token broken or insufficient to
311 // retrieve collection
312 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
316 // Something more serious is wrong
317 statusCode, statusText = http.StatusInternalServerError, err.Error()
321 if pathToken || !credentialsOK {
322 // Either the URL is a "secret sharing link"
323 // that didn't work out (and asking the client
324 // for additional credentials would just be
325 // confusing), or we don't even accept
326 // credentials at this path.
327 statusCode = http.StatusNotFound
330 for _, t := range reqTokens {
331 if tokenResult[t] == 404 {
332 // The client provided valid token(s), but the
333 // collection was not found.
334 statusCode = http.StatusNotFound
338 // The client's token was invalid (e.g., expired), or
339 // the client didn't even provide one. Propagate the
340 // 401 to encourage the client to use a [different]
343 // TODO(TC): This response would be confusing to
344 // someone trying (anonymously) to download public
345 // data that has been deleted. Allow a referrer to
346 // provide this context somehow?
347 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
348 statusCode = http.StatusUnauthorized
352 filename := strings.Join(targetPath, "/")
353 kc, err := keepclient.MakeKeepClient(arv)
355 statusCode, statusText = http.StatusInternalServerError, err.Error()
358 rdr, err := kc.CollectionFileReader(collection, filename)
359 if os.IsNotExist(err) {
360 statusCode = http.StatusNotFound
362 } else if err != nil {
363 statusCode, statusText = http.StatusBadGateway, err.Error()
368 basename := path.Base(filename)
369 applyContentDispositionHdr(w, r, basename, attachment)
371 modstr, _ := collection["modified_at"].(string)
372 modtime, err := time.Parse(time.RFC3339Nano, modstr)
376 http.ServeContent(w, r, basename, modtime, rdr)
379 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
380 disposition := "inline"
382 disposition = "attachment"
384 if strings.ContainsRune(r.RequestURI, '?') {
385 // Help the UA realize that the filename is just
386 // "filename.txt", not
387 // "filename.txt?disposition=attachment".
389 // TODO(TC): Follow advice at RFC 6266 appendix D
390 disposition += "; filename=" + strconv.QuoteToASCII(filename)
392 if disposition != "inline" {
393 w.Header().Set("Content-Disposition", disposition)