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