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