15 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
16 "git.curoverse.com/arvados.git/sdk/go/auth"
17 "git.curoverse.com/arvados.git/sdk/go/httpserver"
18 "git.curoverse.com/arvados.git/sdk/go/keepclient"
24 clientPool = arvadosclient.MakeClientPool()
25 trustAllContent = false
26 attachmentOnlyHost = ""
30 flag.StringVar(&attachmentOnlyHost, "attachment-only-host", "",
31 "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.")
32 flag.BoolVar(&trustAllContent, "trust-all-content", false,
33 "Serve non-public content from a single origin. Dangerous: read docs before using!")
36 // return a UUID or PDH if s begins with a UUID or URL-encoded PDH;
37 // otherwise return "".
38 func parseCollectionIDFromDNSName(s string) string {
40 if i := strings.IndexRune(s, '.'); i >= 0 {
43 // Names like {uuid}--collections.example.com serve the same
44 // purpose as {uuid}.collections.example.com but can reduce
45 // cost/effort of using [additional] wildcard certificates.
46 if i := strings.Index(s, "--"); i >= 0 {
49 if arvadosclient.UUIDMatch(s) {
52 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
58 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
60 // return a UUID or PDH if s is a UUID or a PDH (even if it is a PDH
61 // with "+" replaced by " " or "-"); otherwise return "".
62 func parseCollectionIDFromURL(s string) string {
63 if arvadosclient.UUIDMatch(s) {
66 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
72 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
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 arv := clientPool.Get()
104 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+clientPool.Err().Error()
107 defer clientPool.Put(arv)
109 pathParts := strings.Split(r.URL.Path[1:], "/")
112 var targetPath []string
114 var reqTokens []string
117 credentialsOK := trustAllContent
119 if r.Host != "" && r.Host == attachmentOnlyHost {
122 } else if r.FormValue("disposition") == "attachment" {
126 if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
127 // http://ID.collections.example/PATH...
129 targetPath = pathParts
130 } else if len(pathParts) >= 2 && strings.HasPrefix(pathParts[0], "c=") {
132 targetID = parseCollectionIDFromURL(pathParts[0][2:])
133 targetPath = pathParts[1:]
134 } else if len(pathParts) >= 3 && pathParts[0] == "collections" {
135 if len(pathParts) >= 5 && pathParts[1] == "download" {
136 // /collections/download/ID/TOKEN/PATH...
137 targetID = pathParts[2]
138 tokens = []string{pathParts[3]}
139 targetPath = pathParts[4:]
142 // /collections/ID/PATH...
143 targetID = pathParts[1]
144 tokens = anonymousTokens
145 targetPath = pathParts[2:]
148 statusCode = http.StatusNotFound
151 if t := r.FormValue("api_token"); t != "" {
152 // The client provided an explicit token in the query
153 // string, or a form in POST body. We must put the
154 // token in an HttpOnly cookie, and redirect to the
155 // same URL with the query param redacted and method =
159 // It is not safe to copy the provided token
160 // into a cookie unless the current vhost
161 // (origin) serves only a single collection or
162 // we are in trustAllContent mode.
163 statusCode = http.StatusBadRequest
167 // The HttpOnly flag is necessary to prevent
168 // JavaScript code (included in, or loaded by, a page
169 // in the collection being served) from employing the
170 // user's token beyond reading other files in the same
171 // domain, i.e., same collection.
173 // The 303 redirect is necessary in the case of a GET
174 // request to avoid exposing the token in the Location
175 // bar, and in the case of a POST request to avoid
176 // raising warnings when the user refreshes the
179 http.SetCookie(w, &http.Cookie{
180 Name: "arvados_api_token",
181 Value: auth.EncodeTokenCookie([]byte(t)),
183 Expires: time.Now().AddDate(10, 0, 0),
186 redir := (&url.URL{Host: r.Host, Path: r.URL.Path}).String()
188 w.Header().Add("Location", redir)
189 statusCode, statusText = http.StatusSeeOther, redir
190 w.WriteHeader(statusCode)
191 io.WriteString(w, `<A href="`)
192 io.WriteString(w, html.EscapeString(redir))
193 io.WriteString(w, `">Continue</A>`)
197 if tokens == nil && strings.HasPrefix(targetPath[0], "t=") {
198 // http://ID.example/t=TOKEN/PATH...
199 // /c=ID/t=TOKEN/PATH...
201 // This form must only be used to pass scoped tokens
202 // that give permission for a single collection. See
203 // FormValue case above.
204 tokens = []string{targetPath[0][2:]}
206 targetPath = targetPath[1:]
211 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
213 tokens = append(reqTokens, anonymousTokens...)
216 if len(targetPath) > 0 && targetPath[0] == "_" {
217 // If a collection has a directory called "t=foo" or
218 // "_", it can be served at
219 // //collections.example/_/t=foo/ or
220 // //collections.example/_/_/ respectively:
221 // //collections.example/t=foo/ won't work because
222 // t=foo will be interpreted as a token "foo".
223 targetPath = targetPath[1:]
226 tokenResult := make(map[string]int)
227 collection := make(map[string]interface{})
229 for _, arv.ApiToken = range tokens {
230 err := arv.Get("collections", targetID, nil, &collection)
236 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
237 switch srvErr.HttpStatusCode {
239 // Token broken or insufficient to
240 // retrieve collection
241 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
245 // Something more serious is wrong
246 statusCode, statusText = http.StatusInternalServerError, err.Error()
250 if pathToken || !credentialsOK {
251 // Either the URL is a "secret sharing link"
252 // that didn't work out (and asking the client
253 // for additional credentials would just be
254 // confusing), or we don't even accept
255 // credentials at this path.
256 statusCode = http.StatusNotFound
259 for _, t := range reqTokens {
260 if tokenResult[t] == 404 {
261 // The client provided valid token(s), but the
262 // collection was not found.
263 statusCode = http.StatusNotFound
267 // The client's token was invalid (e.g., expired), or
268 // the client didn't even provide one. Propagate the
269 // 401 to encourage the client to use a [different]
272 // TODO(TC): This response would be confusing to
273 // someone trying (anonymously) to download public
274 // data that has been deleted. Allow a referrer to
275 // provide this context somehow?
276 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
277 statusCode = http.StatusUnauthorized
281 filename := strings.Join(targetPath, "/")
282 kc, err := keepclient.MakeKeepClient(arv)
284 statusCode, statusText = http.StatusInternalServerError, err.Error()
287 rdr, err := kc.CollectionFileReader(collection, filename)
288 if os.IsNotExist(err) {
289 statusCode = http.StatusNotFound
291 } else if err != nil {
292 statusCode, statusText = http.StatusBadGateway, err.Error()
297 // One or both of these can be -1 if not found:
298 basenamePos := strings.LastIndex(filename, "/")
299 extPos := strings.LastIndex(filename, ".")
300 if extPos > basenamePos {
301 // Now extPos is safely >= 0.
302 if t := mime.TypeByExtension(filename[extPos:]); t != "" {
303 w.Header().Set("Content-Type", t)
306 if rdr, ok := rdr.(keepclient.ReadCloserWithLen); ok {
307 w.Header().Set("Content-Length", fmt.Sprintf("%d", rdr.Len()))
310 w.Header().Set("Content-Disposition", "attachment")
313 w.WriteHeader(http.StatusOK)
314 _, err = io.Copy(w, rdr)
316 statusCode, statusText = http.StatusBadGateway, err.Error()