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 anonymousTokens []string
30 flag.BoolVar(&trustAllContent, "trust-all-content", false,
31 "Serve non-public content from a single origin. Dangerous: read docs before using!")
34 // return a UUID or PDH if s begins with a UUID or URL-encoded PDH;
35 // otherwise return "".
36 func parseCollectionIdFromDNSName(s string) string {
38 if i := strings.IndexRune(s, '.'); i >= 0 {
41 // Names like {uuid}--dl.example.com serve the same purpose as
42 // {uuid}.dl.example.com but can reduce cost/effort of using
43 // [additional] wildcard certificates.
44 if i := strings.Index(s, "--"); i >= 0 {
47 if arvadosclient.UUIDMatch(s) {
50 if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
56 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
58 // return a UUID or PDH if s is a UUID or a PDH (even if it is a PDH
59 // with "+" replaced by " " or "-"); otherwise return "".
60 func parseCollectionIdFromURL(s string) string {
61 if arvadosclient.UUIDMatch(s) {
64 if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
70 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
74 remoteAddr := r.RemoteAddr
75 if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
76 remoteAddr = xff + "," + remoteAddr
79 w := httpserver.WrapResponseWriter(wOrig)
82 statusCode = w.WroteStatus()
83 } else if w.WroteStatus() == 0 {
84 w.WriteHeader(statusCode)
85 } else if w.WroteStatus() != statusCode {
86 httpserver.Log(r.RemoteAddr, "WARNING",
87 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
90 statusText = http.StatusText(statusCode)
92 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
95 if r.Method != "GET" && r.Method != "POST" {
96 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
100 arv := clientPool.Get()
102 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+clientPool.Err().Error()
105 defer clientPool.Put(arv)
107 pathParts := strings.Split(r.URL.Path[1:], "/")
110 var targetPath []string
112 var reqTokens []string
114 credentialsOK := trustAllContent
116 if targetId = parseCollectionIdFromDNSName(r.Host); targetId != "" {
117 // http://ID.dl.example/PATH...
119 targetPath = pathParts
120 } else if len(pathParts) >= 2 && strings.HasPrefix(pathParts[0], "c=") {
122 targetId = parseCollectionIdFromURL(pathParts[0][2:])
123 targetPath = pathParts[1:]
124 } else if len(pathParts) >= 3 && pathParts[0] == "collections" {
125 if len(pathParts) >= 5 && pathParts[1] == "download" {
126 // /collections/download/ID/TOKEN/PATH...
127 targetId = pathParts[2]
128 tokens = []string{pathParts[3]}
129 targetPath = pathParts[4:]
132 // /collections/ID/PATH...
133 targetId = pathParts[1]
134 tokens = anonymousTokens
135 targetPath = pathParts[2:]
138 statusCode = http.StatusNotFound
141 if t := r.FormValue("api_token"); t != "" {
142 // The client provided an explicit token in the query
143 // string, or a form in POST body. We must put the
144 // token in an HttpOnly cookie, and redirect to the
145 // same URL with the query param redacted and method =
149 // It is not safe to copy the provided token
150 // into a cookie unless the current vhost
151 // (origin) serves only a single collection or
152 // we are in trustAllContent mode.
153 statusCode = http.StatusBadRequest
157 // The HttpOnly flag is necessary to prevent
158 // JavaScript code (included in, or loaded by, a page
159 // in the collection being served) from employing the
160 // user's token beyond reading other files in the same
161 // domain, i.e., same collection.
163 // The 303 redirect is necessary in the case of a GET
164 // request to avoid exposing the token in the Location
165 // bar, and in the case of a POST request to avoid
166 // raising warnings when the user refreshes the
169 http.SetCookie(w, &http.Cookie{
171 Value: auth.EncodeTokenCookie([]byte(t)),
173 Expires: time.Now().AddDate(10, 0, 0),
176 redir := (&url.URL{Host: r.Host, Path: r.URL.Path}).String()
178 w.Header().Add("Location", redir)
179 statusCode, statusText = http.StatusSeeOther, redir
180 w.WriteHeader(statusCode)
181 io.WriteString(w, `<A href="`)
182 io.WriteString(w, html.EscapeString(redir))
183 io.WriteString(w, `">Continue</A>`)
187 if tokens == nil && strings.HasPrefix(targetPath[0], "t=") {
188 // http://ID.example/t=TOKEN/PATH...
189 // /c=ID/t=TOKEN/PATH...
191 // This form must only be used to pass scoped tokens
192 // that give permission for a single collection. See
193 // FormValue case above.
194 tokens = []string{targetPath[0][2:]}
196 targetPath = targetPath[1:]
201 reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
203 tokens = append(reqTokens, anonymousTokens...)
206 if len(targetPath) > 0 && targetPath[0] == "_" {
207 // If a collection has a directory called "t=foo" or
208 // "_", it can be served at //dl.example/_/t=foo/ or
209 // //dl.example/_/_/ respectively: //dl.example/t=foo/
210 // won't work because t=foo will be interpreted as a
212 targetPath = targetPath[1:]
215 tokenResult := make(map[string]int)
216 collection := make(map[string]interface{})
218 for _, arv.ApiToken = range tokens {
219 err := arv.Get("collections", targetId, nil, &collection)
225 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
226 switch srvErr.HttpStatusCode {
228 // Token broken or insufficient to
229 // retrieve collection
230 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
234 // Something more serious is wrong
235 statusCode, statusText = http.StatusInternalServerError, err.Error()
239 if pathToken || !credentialsOK {
240 // Either the URL is a "secret sharing link"
241 // that didn't work out (and asking the client
242 // for additional credentials would just be
243 // confusing), or we don't even accept
244 // credentials at this path.
245 statusCode = http.StatusNotFound
248 for _, t := range reqTokens {
249 if tokenResult[t] == 404 {
250 // The client provided valid token(s), but the
251 // collection was not found.
252 statusCode = http.StatusNotFound
256 // The client's token was invalid (e.g., expired), or
257 // the client didn't even provide one. Propagate the
258 // 401 to encourage the client to use a [different]
261 // TODO(TC): This response would be confusing to
262 // someone trying (anonymously) to download public
263 // data that has been deleted. Allow a referrer to
264 // provide this context somehow?
265 w.Header().Add("WWW-Authenticate", "Basic realm=\"dl\"")
266 statusCode = http.StatusUnauthorized
270 filename := strings.Join(targetPath, "/")
271 kc, err := keepclient.MakeKeepClient(arv)
273 statusCode, statusText = http.StatusInternalServerError, err.Error()
276 rdr, err := kc.CollectionFileReader(collection, filename)
277 if os.IsNotExist(err) {
278 statusCode = http.StatusNotFound
280 } else if err != nil {
281 statusCode, statusText = http.StatusBadGateway, err.Error()
286 // One or both of these can be -1 if not found:
287 basenamePos := strings.LastIndex(filename, "/")
288 extPos := strings.LastIndex(filename, ".")
289 if extPos > basenamePos {
290 // Now extPos is safely >= 0.
291 if t := mime.TypeByExtension(filename[extPos:]); t != "" {
292 w.Header().Set("Content-Type", t)
295 w.Header().Set("Content-Length", fmt.Sprintf("%d", rdr.Len()))
297 w.WriteHeader(http.StatusOK)
298 _, err = io.Copy(w, rdr)
300 statusCode, statusText = http.StatusBadGateway, err.Error()