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