7709: Merge branch 'master' into 7709-api-rails4
[arvados.git] / services / keep-web / handler.go
1 package main
2
3 import (
4         "fmt"
5         "html"
6         "io"
7         "net/http"
8         "net/url"
9         "os"
10         "path"
11         "strconv"
12         "strings"
13         "sync"
14         "time"
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 == "OPTIONS" {
98                 method := r.Header.Get("Access-Control-Request-Method")
99                 if method != "GET" && method != "POST" {
100                         statusCode = http.StatusMethodNotAllowed
101                         return
102                 }
103                 w.Header().Set("Access-Control-Allow-Headers", "Range")
104                 w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
105                 w.Header().Set("Access-Control-Allow-Origin", "*")
106                 w.Header().Set("Access-Control-Max-Age", "86400")
107                 statusCode = http.StatusOK
108                 return
109         }
110
111         if r.Method != "GET" && r.Method != "POST" {
112                 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
113                 return
114         }
115
116         if r.Header.Get("Origin") != "" {
117                 // Allow simple cross-origin requests without user
118                 // credentials ("user credentials" as defined by CORS,
119                 // i.e., cookies, HTTP authentication, and client-side
120                 // SSL certificates. See
121                 // http://www.w3.org/TR/cors/#user-credentials).
122                 w.Header().Set("Access-Control-Allow-Origin", "*")
123         }
124
125         arv := h.clientPool.Get()
126         if arv == nil {
127                 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+h.clientPool.Err().Error()
128                 return
129         }
130         defer h.clientPool.Put(arv)
131
132         pathParts := strings.Split(r.URL.Path[1:], "/")
133
134         var targetID string
135         var targetPath []string
136         var tokens []string
137         var reqTokens []string
138         var pathToken bool
139         var attachment bool
140         credentialsOK := h.Config.TrustAllContent
141
142         if r.Host != "" && r.Host == h.Config.AttachmentOnlyHost {
143                 credentialsOK = true
144                 attachment = true
145         } else if r.FormValue("disposition") == "attachment" {
146                 attachment = true
147         }
148
149         if targetID = parseCollectionIDFromDNSName(r.Host); targetID != "" {
150                 // http://ID.collections.example/PATH...
151                 credentialsOK = true
152                 targetPath = pathParts
153         } else if len(pathParts) >= 2 && strings.HasPrefix(pathParts[0], "c=") {
154                 // /c=ID/PATH...
155                 targetID = parseCollectionIDFromURL(pathParts[0][2:])
156                 targetPath = pathParts[1:]
157         } else if len(pathParts) >= 3 && pathParts[0] == "collections" {
158                 if len(pathParts) >= 5 && pathParts[1] == "download" {
159                         // /collections/download/ID/TOKEN/PATH...
160                         targetID = parseCollectionIDFromURL(pathParts[2])
161                         tokens = []string{pathParts[3]}
162                         targetPath = pathParts[4:]
163                         pathToken = true
164                 } else {
165                         // /collections/ID/PATH...
166                         targetID = parseCollectionIDFromURL(pathParts[1])
167                         tokens = h.Config.AnonymousTokens
168                         targetPath = pathParts[2:]
169                 }
170         }
171
172         if targetID == "" {
173                 statusCode = http.StatusNotFound
174                 return
175         }
176
177         formToken := r.FormValue("api_token")
178         if formToken != "" && r.Header.Get("Origin") != "" && attachment && r.URL.Query().Get("api_token") == "" {
179                 // The client provided an explicit token in the POST
180                 // body. The Origin header indicates this *might* be
181                 // an AJAX request, in which case redirect-with-cookie
182                 // won't work: we should just serve the content in the
183                 // POST response. This is safe because:
184                 //
185                 // * We're supplying an attachment, not inline
186                 //   content, so we don't need to convert the POST to
187                 //   a GET and avoid the "really resubmit form?"
188                 //   problem.
189                 //
190                 // * The token isn't embedded in the URL, so we don't
191                 //   need to worry about bookmarks and copy/paste.
192                 tokens = append(tokens, formToken)
193         } else if formToken != "" {
194                 // The client provided an explicit token in the query
195                 // string, or a form in POST body. We must put the
196                 // token in an HttpOnly cookie, and redirect to the
197                 // same URL with the query param redacted and method =
198                 // GET.
199
200                 if !credentialsOK {
201                         // It is not safe to copy the provided token
202                         // into a cookie unless the current vhost
203                         // (origin) serves only a single collection or
204                         // we are in TrustAllContent mode.
205                         statusCode = http.StatusBadRequest
206                         return
207                 }
208
209                 // The HttpOnly flag is necessary to prevent
210                 // JavaScript code (included in, or loaded by, a page
211                 // in the collection being served) from employing the
212                 // user's token beyond reading other files in the same
213                 // domain, i.e., same collection.
214                 //
215                 // The 303 redirect is necessary in the case of a GET
216                 // request to avoid exposing the token in the Location
217                 // bar, and in the case of a POST request to avoid
218                 // raising warnings when the user refreshes the
219                 // resulting page.
220
221                 http.SetCookie(w, &http.Cookie{
222                         Name:     "arvados_api_token",
223                         Value:    auth.EncodeTokenCookie([]byte(formToken)),
224                         Path:     "/",
225                         HttpOnly: true,
226                 })
227
228                 // Propagate query parameters (except api_token) from
229                 // the original request.
230                 redirQuery := r.URL.Query()
231                 redirQuery.Del("api_token")
232
233                 redir := (&url.URL{
234                         Host:     r.Host,
235                         Path:     r.URL.Path,
236                         RawQuery: redirQuery.Encode(),
237                 }).String()
238
239                 w.Header().Add("Location", redir)
240                 statusCode, statusText = http.StatusSeeOther, redir
241                 w.WriteHeader(statusCode)
242                 io.WriteString(w, `<A href="`)
243                 io.WriteString(w, html.EscapeString(redir))
244                 io.WriteString(w, `">Continue</A>`)
245                 return
246         }
247
248         if tokens == nil && strings.HasPrefix(targetPath[0], "t=") {
249                 // http://ID.example/t=TOKEN/PATH...
250                 // /c=ID/t=TOKEN/PATH...
251                 //
252                 // This form must only be used to pass scoped tokens
253                 // that give permission for a single collection. See
254                 // FormValue case above.
255                 tokens = []string{targetPath[0][2:]}
256                 pathToken = true
257                 targetPath = targetPath[1:]
258         }
259
260         if tokens == nil {
261                 if credentialsOK {
262                         reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
263                 }
264                 tokens = append(reqTokens, h.Config.AnonymousTokens...)
265         }
266
267         if len(targetPath) > 0 && targetPath[0] == "_" {
268                 // If a collection has a directory called "t=foo" or
269                 // "_", it can be served at
270                 // //collections.example/_/t=foo/ or
271                 // //collections.example/_/_/ respectively:
272                 // //collections.example/t=foo/ won't work because
273                 // t=foo will be interpreted as a token "foo".
274                 targetPath = targetPath[1:]
275         }
276
277         tokenResult := make(map[string]int)
278         collection := make(map[string]interface{})
279         found := false
280         for _, arv.ApiToken = range tokens {
281                 err := arv.Get("collections", targetID, nil, &collection)
282                 if err == nil {
283                         // Success
284                         found = true
285                         break
286                 }
287                 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
288                         switch srvErr.HttpStatusCode {
289                         case 404, 401:
290                                 // Token broken or insufficient to
291                                 // retrieve collection
292                                 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
293                                 continue
294                         }
295                 }
296                 // Something more serious is wrong
297                 statusCode, statusText = http.StatusInternalServerError, err.Error()
298                 return
299         }
300         if !found {
301                 if pathToken || !credentialsOK {
302                         // Either the URL is a "secret sharing link"
303                         // that didn't work out (and asking the client
304                         // for additional credentials would just be
305                         // confusing), or we don't even accept
306                         // credentials at this path.
307                         statusCode = http.StatusNotFound
308                         return
309                 }
310                 for _, t := range reqTokens {
311                         if tokenResult[t] == 404 {
312                                 // The client provided valid token(s), but the
313                                 // collection was not found.
314                                 statusCode = http.StatusNotFound
315                                 return
316                         }
317                 }
318                 // The client's token was invalid (e.g., expired), or
319                 // the client didn't even provide one.  Propagate the
320                 // 401 to encourage the client to use a [different]
321                 // token.
322                 //
323                 // TODO(TC): This response would be confusing to
324                 // someone trying (anonymously) to download public
325                 // data that has been deleted.  Allow a referrer to
326                 // provide this context somehow?
327                 w.Header().Add("WWW-Authenticate", "Basic realm=\"collections\"")
328                 statusCode = http.StatusUnauthorized
329                 return
330         }
331
332         filename := strings.Join(targetPath, "/")
333         kc, err := keepclient.MakeKeepClient(arv)
334         if err != nil {
335                 statusCode, statusText = http.StatusInternalServerError, err.Error()
336                 return
337         }
338         if kc.Client != nil && kc.Client.Transport != nil {
339                 // Workaround for https://dev.arvados.org/issues/9005
340                 if t, ok := kc.Client.Transport.(*http.Transport); ok {
341                         defer t.CloseIdleConnections()
342                 }
343         }
344         rdr, err := kc.CollectionFileReader(collection, filename)
345         if os.IsNotExist(err) {
346                 statusCode = http.StatusNotFound
347                 return
348         } else if err != nil {
349                 statusCode, statusText = http.StatusBadGateway, err.Error()
350                 return
351         }
352         defer rdr.Close()
353
354         basename := path.Base(filename)
355         applyContentDispositionHdr(w, r, basename, attachment)
356
357         modstr, _ := collection["modified_at"].(string)
358         modtime, err := time.Parse(time.RFC3339Nano, modstr)
359         if err != nil {
360                 modtime = time.Now()
361         }
362         http.ServeContent(w, r, basename, modtime, rdr)
363 }
364
365 func applyContentDispositionHdr(w http.ResponseWriter, r *http.Request, filename string, isAttachment bool) {
366         disposition := "inline"
367         if isAttachment {
368                 disposition = "attachment"
369         }
370         if strings.ContainsRune(r.RequestURI, '?') {
371                 // Help the UA realize that the filename is just
372                 // "filename.txt", not
373                 // "filename.txt?disposition=attachment".
374                 //
375                 // TODO(TC): Follow advice at RFC 6266 appendix D
376                 disposition += "; filename=" + strconv.QuoteToASCII(filename)
377         }
378         if disposition != "inline" {
379                 w.Header().Set("Content-Disposition", disposition)
380         }
381 }