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