14 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
15 "git.curoverse.com/arvados.git/sdk/go/auth"
16 "git.curoverse.com/arvados.git/sdk/go/httpserver"
17 "git.curoverse.com/arvados.git/sdk/go/keepclient"
23 clientPool = arvadosclient.MakeClientPool()
24 trustAllContent = false
25 attachmentOnlyHost = ""
29 flag.StringVar(&attachmentOnlyHost, "attachment-only-host", "",
30 "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.")
31 flag.BoolVar(&trustAllContent, "trust-all-content", false,
32 "Serve non-public content from a single origin. Dangerous: read docs before using!")
35 // return a UUID or PDH if s begins with a UUID or URL-encoded PDH;
36 // otherwise return "".
37 func parseCollectionIDFromDNSName(s string) string {
39 if i := strings.IndexRune(s, '.'); i >= 0 {
42 // Names like {uuid}--collections.example.com serve the same
43 // purpose as {uuid}.collections.example.com but can reduce
44 // cost/effort of using [additional] wildcard certificates.
45 if i := strings.Index(s, "--"); i >= 0 {
48 if arvadosclient.UUIDMatch(s) {
51 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
57 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
59 // return a UUID or PDH if s is a UUID or a PDH (even if it is a PDH
60 // with "+" replaced by " " or "-"); otherwise return "".
61 func parseCollectionIDFromURL(s string) string {
62 if arvadosclient.UUIDMatch(s) {
65 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
71 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
75 remoteAddr := r.RemoteAddr
76 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
77 remoteAddr = xff + "," + remoteAddr
80 w := httpserver.WrapResponseWriter(wOrig)
83 statusCode = w.WroteStatus()
84 } else if w.WroteStatus() == 0 {
85 w.WriteHeader(statusCode)
86 } else if w.WroteStatus() != statusCode {
87 httpserver.Log(r.RemoteAddr, "WARNING",
88 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
91 statusText = http.StatusText(statusCode)
93 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
96 if r.Method != "GET" && r.Method != "POST" {
97 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
101 arv := clientPool.Get()
103 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+clientPool.Err().Error()
106 defer clientPool.Put(arv)
108 pathParts := strings.Split(r.URL.Path[1:], "/")
111 var targetPath []string
113 var reqTokens []string
116 credentialsOK := trustAllContent
118 if r.Host != "" && r.Host == attachmentOnlyHost {
121 } else if r.FormValue("disposition") == "attachment" {
125 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
126 // http://ID.collections.example/PATH...
128 targetPath = pathParts
129 } else if len(pathParts) >= 2 && strings.HasPrefix(pathParts[0], "c=") {
131 targetID = parseCollectionIDFromURL(pathParts[0][2:])
132 targetPath = pathParts[1:]
133 } else if len(pathParts) >= 3 && pathParts[0] == "collections" {
134 if len(pathParts) >= 5 && pathParts[1] == "download" {
135 // /collections/download/ID/TOKEN/PATH...
136 targetID = pathParts[2]
137 tokens = []string{pathParts[3]}
138 targetPath = pathParts[4:]
141 // /collections/ID/PATH...
142 targetID = pathParts[1]
143 tokens = anonymousTokens
144 targetPath = pathParts[2:]
147 statusCode = http.StatusNotFound
150 if t := r.FormValue("api_token"); t != "" {
151 // The client provided an explicit token in the query
152 // string, or a form in POST body. We must put the
153 // token in an HttpOnly cookie, and redirect to the
154 // same URL with the query param redacted and method =
158 // It is not safe to copy the provided token
159 // into a cookie unless the current vhost
160 // (origin) serves only a single collection or
161 // we are in trustAllContent mode.
162 statusCode = http.StatusBadRequest
166 // The HttpOnly flag is necessary to prevent
167 // JavaScript code (included in, or loaded by, a page
168 // in the collection being served) from employing the
169 // user's token beyond reading other files in the same
170 // domain, i.e., same collection.
172 // The 303 redirect is necessary in the case of a GET
173 // request to avoid exposing the token in the Location
174 // bar, and in the case of a POST request to avoid
175 // raising warnings when the user refreshes the
178 http.SetCookie(w, &http.Cookie{
179 Name: "arvados_api_token",
180 Value: auth.EncodeTokenCookie([]byte(t)),
184 redir := (&url.URL{Host: r.Host, Path: r.URL.Path}).String()
186 w.Header().Add("Location", redir)
187 statusCode, statusText = http.StatusSeeOther, redir
188 w.WriteHeader(statusCode)
189 io.WriteString(w, `<A href="`)
190 io.WriteString(w, html.EscapeString(redir))
191 io.WriteString(w, `">Continue</A>`)
195 if tokens == nil && strings.HasPrefix(targetPath[0], "t=") {
196 // http://ID.example/t=TOKEN/PATH...
197 // /c=ID/t=TOKEN/PATH...
199 // This form must only be used to pass scoped tokens
200 // that give permission for a single collection. See
201 // FormValue case above.
202 tokens = []string{targetPath[0][2:]}
204 targetPath = targetPath[1:]
209 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
211 tokens = append(reqTokens, anonymousTokens...)
214 if len(targetPath) > 0 && targetPath[0] == "_" {
215 // If a collection has a directory called "t=foo" or
216 // "_", it can be served at
217 // //collections.example/_/t=foo/ or
218 // //collections.example/_/_/ respectively:
219 // //collections.example/t=foo/ won't work because
220 // t=foo will be interpreted as a token "foo".
221 targetPath = targetPath[1:]
224 tokenResult := make(map[string]int)
225 collection := make(map[string]interface{})
227 for _, arv.ApiToken = range tokens {
228 err := arv.Get("collections", targetID, nil, &collection)
234 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
235 switch srvErr.HttpStatusCode {
237 // Token broken or insufficient to
238 // retrieve collection
239 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
243 // Something more serious is wrong
244 statusCode, statusText = http.StatusInternalServerError, err.Error()
248 if pathToken || !credentialsOK {
249 // Either the URL is a "secret sharing link"
250 // that didn't work out (and asking the client
251 // for additional credentials would just be
252 // confusing), or we don't even accept
253 // credentials at this path.
254 statusCode = http.StatusNotFound
257 for _, t := range reqTokens {
258 if tokenResult[t] == 404 {
259 // The client provided valid token(s), but the
260 // collection was not found.
261 statusCode = http.StatusNotFound
265 // The client's token was invalid (e.g., expired), or
266 // the client didn't even provide one. Propagate the
267 // 401 to encourage the client to use a [different]
270 // TODO(TC): This response would be confusing to
271 // someone trying (anonymously) to download public
272 // data that has been deleted. Allow a referrer to
273 // provide this context somehow?
274 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
275 statusCode = http.StatusUnauthorized
279 filename := strings.Join(targetPath, "/")
280 kc, err := keepclient.MakeKeepClient(arv)
282 statusCode, statusText = http.StatusInternalServerError, err.Error()
285 rdr, err := kc.CollectionFileReader(collection, filename)
286 if os.IsNotExist(err) {
287 statusCode = http.StatusNotFound
289 } else if err != nil {
290 statusCode, statusText = http.StatusBadGateway, err.Error()
295 // One or both of these can be -1 if not found:
296 basenamePos := strings.LastIndex(filename, "/")
297 extPos := strings.LastIndex(filename, ".")
298 if extPos > basenamePos {
299 // Now extPos is safely >= 0.
300 if t := mime.TypeByExtension(filename[extPos:]); t != "" {
301 w.Header().Set("Content-Type", t)
304 if rdr, ok := rdr.(keepclient.ReadCloserWithLen); ok {
305 w.Header().Set("Content-Length", fmt.Sprintf("%d", rdr.Len()))
308 w.Header().Set("Content-Disposition", "attachment")
311 w.WriteHeader(http.StatusOK)
312 _, err = io.Copy(w, rdr)
314 statusCode, statusText = http.StatusBadGateway, err.Error()