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