7884: Serve simple cross-origin AJAX POST requests without redirecting.
[arvados.git] / services / keep-web / handler.go
1 package main
2
3 import (
4         "flag"
5         "fmt"
6         "html"
7         "io"
8         "mime"
9         "net/http"
10         "net/url"
11         "os"
12         "regexp"
13         "strconv"
14         "strings"
15
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"
20 )
21
22 type handler struct{}
23
24 var (
25         clientPool         = arvadosclient.MakeClientPool()
26         trustAllContent    = false
27         attachmentOnlyHost = ""
28 )
29
30 func init() {
31         flag.StringVar(&attachmentOnlyHost, "attachment-only-host", "",
32                 "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.")
33         flag.BoolVar(&trustAllContent, "trust-all-content", false,
34                 "Serve non-public content from a single origin. Dangerous: read docs before using!")
35 }
36
37 // return a UUID or PDH if s begins with a UUID or URL-encoded PDH;
38 // otherwise return "".
39 func parseCollectionIDFromDNSName(s string) string {
40         // Strip domain.
41         if i := strings.IndexRune(s, '.'); i >= 0 {
42                 s = s[:i]
43         }
44         // Names like {uuid}--collections.example.com serve the same
45         // purpose as {uuid}.collections.example.com but can reduce
46         // cost/effort of using [additional] wildcard certificates.
47         if i := strings.Index(s, "--"); i >= 0 {
48                 s = s[:i]
49         }
50         if arvadosclient.UUIDMatch(s) {
51                 return s
52         }
53         if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
54                 return pdh
55         }
56         return ""
57 }
58
59 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
60
61 // return a UUID or PDH if s is a UUID or a PDH (even if it is a PDH
62 // with "+" replaced by " " or "-"); otherwise return "".
63 func parseCollectionIDFromURL(s string) string {
64         if arvadosclient.UUIDMatch(s) {
65                 return s
66         }
67         if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
68                 return pdh
69         }
70         return ""
71 }
72
73 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
74         var statusCode = 0
75         var statusText string
76
77         remoteAddr := r.RemoteAddr
78         if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
79                 remoteAddr = xff + "," + remoteAddr
80         }
81
82         w := httpserver.WrapResponseWriter(wOrig)
83         defer func() {
84                 if statusCode == 0 {
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))
91                 }
92                 if statusText == "" {
93                         statusText = http.StatusText(statusCode)
94                 }
95                 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
96         }()
97
98         if r.Method != "GET" && r.Method != "POST" {
99                 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
100                 return
101         }
102
103         if r.Header.Get("Origin") != "" {
104                 // Allow simple cross-origin requests, without
105                 // credentials.
106                 w.Header().Set("Access-Control-Allow-Origin", "*")
107         }
108
109         arv := clientPool.Get()
110         if arv == nil {
111                 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+clientPool.Err().Error()
112                 return
113         }
114         defer clientPool.Put(arv)
115
116         pathParts := strings.Split(r.URL.Path[1:], "/")
117
118         var targetID string
119         var targetPath []string
120         var tokens []string
121         var reqTokens []string
122         var pathToken bool
123         var attachment bool
124         credentialsOK := trustAllContent
125
126         if r.Host != "" && r.Host == attachmentOnlyHost {
127                 credentialsOK = true
128                 attachment = true
129         } else if r.FormValue("disposition") == "attachment" {
130                 attachment = true
131         }
132
133         if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
134                 // http://ID.collections.example/PATH...
135                 credentialsOK = true
136                 targetPath = pathParts
137         } else if len(pathParts) >= 2 && strings.HasPrefix(pathParts[0], "c=") {
138                 // /c=ID/PATH...
139                 targetID = parseCollectionIDFromURL(pathParts[0][2:])
140                 targetPath = pathParts[1:]
141         } else if len(pathParts) >= 3 && pathParts[0] == "collections" {
142                 if len(pathParts) >= 5 && pathParts[1] == "download" {
143                         // /collections/download/ID/TOKEN/PATH...
144                         targetID = pathParts[2]
145                         tokens = []string{pathParts[3]}
146                         targetPath = pathParts[4:]
147                         pathToken = true
148                 } else {
149                         // /collections/ID/PATH...
150                         targetID = pathParts[1]
151                         tokens = anonymousTokens
152                         targetPath = pathParts[2:]
153                 }
154         } else {
155                 statusCode = http.StatusNotFound
156                 return
157         }
158
159         formToken := r.FormValue("api_token")
160         if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
161                 // The client provided an explicit token in the POST
162                 // body. The Origin header indicates this *might* be
163                 // an AJAX request, in which case redirect-with-cookie
164                 // won't work: we should just serve the content in the
165                 // POST response. This is safe because:
166                 //
167                 // * We're supplying an attachment, not inline
168                 //   content, so we don't need to convert the POST to
169                 //   a GET and avoid the "really resubmit form?"
170                 //   problem.
171                 //
172                 // * The token isn't embedded in the URL, so we don't
173                 //   need to worry about bookmarks and copy/paste.
174                 tokens = append(tokens, formToken)
175         } else if formToken != "" {
176                 // The client provided an explicit token in the query
177                 // string, or a form in POST body. We must put the
178                 // token in an HttpOnly cookie, and redirect to the
179                 // same URL with the query param redacted and method =
180                 // GET.
181
182                 if !credentialsOK {
183                         // It is not safe to copy the provided token
184                         // into a cookie unless the current vhost
185                         // (origin) serves only a single collection or
186                         // we are in trustAllContent mode.
187                         statusCode = http.StatusBadRequest
188                         return
189                 }
190
191                 // The HttpOnly flag is necessary to prevent
192                 // JavaScript code (included in, or loaded by, a page
193                 // in the collection being served) from employing the
194                 // user's token beyond reading other files in the same
195                 // domain, i.e., same collection.
196                 //
197                 // The 303 redirect is necessary in the case of a GET
198                 // request to avoid exposing the token in the Location
199                 // bar, and in the case of a POST request to avoid
200                 // raising warnings when the user refreshes the
201                 // resulting page.
202
203                 http.SetCookie(w, &http.Cookie{
204                         Name:     "arvados_api_token",
205                         Value:    auth.EncodeTokenCookie([]byte(formToken)),
206                         Path:     "/",
207                         HttpOnly: true,
208                 })
209
210                 // Propagate query parameters (except api_token) from
211                 // the original request.
212                 redirQuery := r.URL.Query()
213                 redirQuery.Del("api_token")
214
215                 redir := (&url.URL{
216                         Host:     r.Host,
217                         Path:     r.URL.Path,
218                         RawQuery: redirQuery.Encode(),
219                 }).String()
220
221                 w.Header().Add("Location", redir)
222                 statusCode, statusText = http.StatusSeeOther, redir
223                 w.WriteHeader(statusCode)
224                 io.WriteString(w, `<A href="`)
225                 io.WriteString(w, html.EscapeString(redir))
226                 io.WriteString(w, `">Continue</A>`)
227                 return
228         }
229
230         if tokens == nil && strings.HasPrefix(targetPath[0], "t=") {
231                 // http://ID.example/t=TOKEN/PATH...
232                 // /c=ID/t=TOKEN/PATH...
233                 //
234                 // This form must only be used to pass scoped tokens
235                 // that give permission for a single collection. See
236                 // FormValue case above.
237                 tokens = []string{targetPath[0][2:]}
238                 pathToken = true
239                 targetPath = targetPath[1:]
240         }
241
242         if tokens == nil {
243                 if credentialsOK {
244                         reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
245                 }
246                 tokens = append(reqTokens, anonymousTokens...)
247         }
248
249         if len(targetPath) > 0 && targetPath[0] == "_" {
250                 // If a collection has a directory called "t=foo" or
251                 // "_", it can be served at
252                 // //collections.example/_/t=foo/ or
253                 // //collections.example/_/_/ respectively:
254                 // //collections.example/t=foo/ won't work because
255                 // t=foo will be interpreted as a token "foo".
256                 targetPath = targetPath[1:]
257         }
258
259         tokenResult := make(map[string]int)
260         collection := make(map[string]interface{})
261         found := false
262         for _, arv.ApiToken = range tokens {
263                 err := arv.Get("collections", targetID, nil, &collection)
264                 if err == nil {
265                         // Success
266                         found = true
267                         break
268                 }
269                 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
270                         switch srvErr.HttpStatusCode {
271                         case 404, 401:
272                                 // Token broken or insufficient to
273                                 // retrieve collection
274                                 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
275                                 continue
276                         }
277                 }
278                 // Something more serious is wrong
279                 statusCode, statusText = http.StatusInternalServerError, err.Error()
280                 return
281         }
282         if !found {
283                 if pathToken || !credentialsOK {
284                         // Either the URL is a "secret sharing link"
285                         // that didn't work out (and asking the client
286                         // for additional credentials would just be
287                         // confusing), or we don't even accept
288                         // credentials at this path.
289                         statusCode = http.StatusNotFound
290                         return
291                 }
292                 for _, t := range reqTokens {
293                         if tokenResult[t] == 404 {
294                                 // The client provided valid token(s), but the
295                                 // collection was not found.
296                                 statusCode = http.StatusNotFound
297                                 return
298                         }
299                 }
300                 // The client's token was invalid (e.g., expired), or
301                 // the client didn't even provide one.  Propagate the
302                 // 401 to encourage the client to use a [different]
303                 // token.
304                 //
305                 // TODO(TC): This response would be confusing to
306                 // someone trying (anonymously) to download public
307                 // data that has been deleted.  Allow a referrer to
308                 // provide this context somehow?
309                 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
310                 statusCode = http.StatusUnauthorized
311                 return
312         }
313
314         filename := strings.Join(targetPath, "/")
315         kc, err := keepclient.MakeKeepClient(arv)
316         if err != nil {
317                 statusCode, statusText = http.StatusInternalServerError, err.Error()
318                 return
319         }
320         rdr, err := kc.CollectionFileReader(collection, filename)
321         if os.IsNotExist(err) {
322                 statusCode = http.StatusNotFound
323                 return
324         } else if err != nil {
325                 statusCode, statusText = http.StatusBadGateway, err.Error()
326                 return
327         }
328         defer rdr.Close()
329
330         basenamePos := strings.LastIndex(filename, "/")
331         if basenamePos < 0 {
332                 basenamePos = 0
333         }
334         extPos := strings.LastIndex(filename, ".")
335         if extPos > basenamePos {
336                 // Now extPos is safely >= 0.
337                 if t := mime.TypeByExtension(filename[extPos:]); t != "" {
338                         w.Header().Set("Content-Type", t)
339                 }
340         }
341         if rdr, ok := rdr.(keepclient.ReadCloserWithLen); ok {
342                 w.Header().Set("Content-Length", fmt.Sprintf("%d", rdr.Len()))
343         }
344
345         applyContentDispositionHdr(w, r, filename[basenamePos:], attachment)
346         rangeRdr, statusCode := applyRangeHdr(w, r, rdr)
347
348         w.WriteHeader(statusCode)
349         _, err = io.Copy(w, rangeRdr)
350         if err != nil {
351                 statusCode, statusText = http.StatusBadGateway, err.Error()
352         }
353 }
354
355 var rangeRe = regexp.MustCompile(`^bytes=0-([0-9]*)$`)
356
357 func applyRangeHdr(w http.ResponseWriter, r *http.Request, rdr keepclient.ReadCloserWithLen) (io.Reader, int) {
358         w.Header().Set("Accept-Ranges", "bytes")
359         hdr := r.Header.Get("Range")
360         fields := rangeRe.FindStringSubmatch(hdr)
361         if fields == nil {
362                 return rdr, http.StatusOK
363         }
364         rangeEnd, err := strconv.ParseInt(fields[1], 10, 64)
365         if err != nil {
366                 // Empty or too big for int64 == send entire content
367                 return rdr, http.StatusOK
368         }
369         if uint64(rangeEnd) >= rdr.Len() {
370                 return rdr, http.StatusOK
371         }
372         w.Header().Set("Content-Length", fmt.Sprintf("%d", rangeEnd+1))
373         w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", 0, rangeEnd, rdr.Len()))
374         return &io.LimitedReader{R: rdr, N: rangeEnd + 1}, http.StatusPartialContent
375 }
376
377 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
378         disposition := "inline"
379         if isAttachment {
380                 disposition = "attachment"
381         }
382         if strings.ContainsRune(r.RequestURI, '?') {
383                 // Help the UA realize that the filename is just
384                 // "filename.txt", not
385                 // "filename.txt?disposition=attachment".
386                 //
387                 // TODO(TC): Follow advice at RFC 6266 appendix D
388                 disposition += "; filename=" + strconv.QuoteToASCII(filename)
389         }
390         if disposition != "inline" {
391                 w.Header().Set("Content-Disposition", disposition)
392         }
393 }