5824: Implement "trust all content" mode.
[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         "strings"
13         "time"
14
15         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
16         "git.curoverse.com/arvados.git/sdk/go/auth"
17         "git.curoverse.com/arvados.git/sdk/go/httpserver"
18         "git.curoverse.com/arvados.git/sdk/go/keepclient"
19 )
20
21 type handler struct{}
22
23 var (
24         clientPool      = arvadosclient.MakeClientPool()
25         trustAllContent = false
26         anonymousTokens []string
27 )
28
29 func init() {
30         flag.BoolVar(&trustAllContent, "trust-all-content", false,
31                 "Serve non-public content from a single origin. Dangerous: read docs before using!")
32 }
33
34 // return a UUID or PDH if s begins with a UUID or URL-encoded PDH;
35 // otherwise return "".
36 func parseCollectionIdFromDNSName(s string) string {
37         // Strip domain.
38         if i := strings.IndexRune(s, '.'); i >= 0 {
39                 s = s[:i]
40         }
41         // Names like {uuid}--dl.example.com serve the same purpose as
42         // {uuid}.dl.example.com but can reduce cost/effort of using
43         // [additional] wildcard certificates.
44         if i := strings.Index(s, "--"); i >= 0 {
45                 s = s[:i]
46         }
47         if arvadosclient.UUIDMatch(s) {
48                 return s
49         }
50         if pdh := strings.Replace(s, "-", "+", 1); arvadosclient.PDHMatch(pdh) {
51                 return pdh
52         }
53         return ""
54 }
55
56 var urlPDHDecoder = strings.NewReplacer(" ", "+", "-", "+")
57
58 // return a UUID or PDH if s is a UUID or a PDH (even if it is a PDH
59 // with "+" replaced by " " or "-"); otherwise return "".
60 func parseCollectionIdFromURL(s string) string {
61         if arvadosclient.UUIDMatch(s) {
62                 return s
63         }
64         if pdh := urlPDHDecoder.Replace(s); arvadosclient.PDHMatch(pdh) {
65                 return pdh
66         }
67         return ""
68 }
69
70 func (h *handler) ServeHTTP(wOrig http.ResponseWriter, r *http.Request) {
71         var statusCode = 0
72         var statusText string
73
74         remoteAddr := r.RemoteAddr
75         if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
76                 remoteAddr = xff + "," + remoteAddr
77         }
78
79         w := httpserver.WrapResponseWriter(wOrig)
80         defer func() {
81                 if statusCode == 0 {
82                         statusCode = w.WroteStatus()
83                 } else if w.WroteStatus() == 0 {
84                         w.WriteHeader(statusCode)
85                 } else if w.WroteStatus() != statusCode {
86                         httpserver.Log(r.RemoteAddr, "WARNING",
87                                 fmt.Sprintf("Our status changed from %d to %d after we sent headers", w.WroteStatus(), statusCode))
88                 }
89                 if statusText == "" {
90                         statusText = http.StatusText(statusCode)
91                 }
92                 httpserver.Log(remoteAddr, statusCode, statusText, w.WroteBodyBytes(), r.Method, r.Host, r.URL.Path, r.URL.RawQuery)
93         }()
94
95         if r.Method != "GET" && r.Method != "POST" {
96                 statusCode, statusText = http.StatusMethodNotAllowed, r.Method
97                 return
98         }
99
100         arv := clientPool.Get()
101         if arv == nil {
102                 statusCode, statusText = http.StatusInternalServerError, "Pool failed: "+clientPool.Err().Error()
103                 return
104         }
105         defer clientPool.Put(arv)
106
107         pathParts := strings.Split(r.URL.Path[1:], "/")
108
109         var targetId string
110         var targetPath []string
111         var tokens []string
112         var reqTokens []string
113         var pathToken bool
114         credentialsOK := trustAllContent
115
116         if targetId = parseCollectionIdFromDNSName(r.Host); targetId != "" {
117                 // http://ID.dl.example/PATH...
118                 credentialsOK = true
119                 targetPath = pathParts
120         } else if len(pathParts) >= 2 && strings.HasPrefix(pathParts[0], "c=") {
121                 // /c=ID/PATH...
122                 targetId = parseCollectionIdFromURL(pathParts[0][2:])
123                 targetPath = pathParts[1:]
124         } else if len(pathParts) >= 3 && pathParts[0] == "collections" {
125                 if len(pathParts) >= 5 && pathParts[1] == "download" {
126                         // /collections/download/ID/TOKEN/PATH...
127                         targetId = pathParts[2]
128                         tokens = []string{pathParts[3]}
129                         targetPath = pathParts[4:]
130                         pathToken = true
131                 } else {
132                         // /collections/ID/PATH...
133                         targetId = pathParts[1]
134                         tokens = anonymousTokens
135                         targetPath = pathParts[2:]
136                 }
137         } else {
138                 statusCode = http.StatusNotFound
139                 return
140         }
141         if t := r.FormValue("api_token"); t != "" {
142                 // The client provided an explicit token in the query
143                 // string, or a form in POST body. We must put the
144                 // token in an HttpOnly cookie, and redirect to the
145                 // same URL with the query param redacted and method =
146                 // GET.
147
148                 if !credentialsOK {
149                         // It is not safe to copy the provided token
150                         // into a cookie unless the current vhost
151                         // (origin) serves only a single collection or
152                         // we are in trustAllContent mode.
153                         statusCode = http.StatusBadRequest
154                         return
155                 }
156
157                 // The HttpOnly flag is necessary to prevent
158                 // JavaScript code (included in, or loaded by, a page
159                 // in the collection being served) from employing the
160                 // user's token beyond reading other files in the same
161                 // domain, i.e., same collection.
162                 //
163                 // The 303 redirect is necessary in the case of a GET
164                 // request to avoid exposing the token in the Location
165                 // bar, and in the case of a POST request to avoid
166                 // raising warnings when the user refreshes the
167                 // resulting page.
168
169                 http.SetCookie(w, &http.Cookie{
170                         Name:     "api_token",
171                         Value:    auth.EncodeTokenCookie([]byte(t)),
172                         Path:     "/",
173                         Expires:  time.Now().AddDate(10, 0, 0),
174                         HttpOnly: true,
175                 })
176                 redir := (&url.URL{Host: r.Host, Path: r.URL.Path}).String()
177
178                 w.Header().Add("Location", redir)
179                 statusCode, statusText = http.StatusSeeOther, redir
180                 w.WriteHeader(statusCode)
181                 io.WriteString(w, `<A href="`)
182                 io.WriteString(w, html.EscapeString(redir))
183                 io.WriteString(w, `">Continue</A>`)
184                 return
185         }
186
187         if tokens == nil && strings.HasPrefix(targetPath[0], "t=") {
188                 // http://ID.example/t=TOKEN/PATH...
189                 // /c=ID/t=TOKEN/PATH...
190                 //
191                 // This form must only be used to pass scoped tokens
192                 // that give permission for a single collection. See
193                 // FormValue case above.
194                 tokens = []string{targetPath[0][2:]}
195                 pathToken = true
196                 targetPath = targetPath[1:]
197         }
198
199         if tokens == nil {
200                 if credentialsOK {
201                         reqTokens = auth.NewCredentialsFromHTTPRequest(r).Tokens
202                 }
203                 tokens = append(reqTokens, anonymousTokens...)
204         }
205
206         if len(targetPath) > 0 && targetPath[0] == "_" {
207                 // If a collection has a directory called "t=foo" or
208                 // "_", it can be served at //dl.example/_/t=foo/ or
209                 // //dl.example/_/_/ respectively: //dl.example/t=foo/
210                 // won't work because t=foo will be interpreted as a
211                 // token "foo".
212                 targetPath = targetPath[1:]
213         }
214
215         tokenResult := make(map[string]int)
216         collection := make(map[string]interface{})
217         found := false
218         for _, arv.ApiToken = range tokens {
219                 err := arv.Get("collections", targetId, nil, &collection)
220                 if err == nil {
221                         // Success
222                         found = true
223                         break
224                 }
225                 if srvErr, ok := err.(arvadosclient.APIServerError); ok {
226                         switch srvErr.HttpStatusCode {
227                         case 404, 401:
228                                 // Token broken or insufficient to
229                                 // retrieve collection
230                                 tokenResult[arv.ApiToken] = srvErr.HttpStatusCode
231                                 continue
232                         }
233                 }
234                 // Something more serious is wrong
235                 statusCode, statusText = http.StatusInternalServerError, err.Error()
236                 return
237         }
238         if !found {
239                 if pathToken || !credentialsOK {
240                         // Either the URL is a "secret sharing link"
241                         // that didn't work out (and asking the client
242                         // for additional credentials would just be
243                         // confusing), or we don't even accept
244                         // credentials at this path.
245                         statusCode = http.StatusNotFound
246                         return
247                 }
248                 for _, t := range reqTokens {
249                         if tokenResult[t] == 404 {
250                                 // The client provided valid token(s), but the
251                                 // collection was not found.
252                                 statusCode = http.StatusNotFound
253                                 return
254                         }
255                 }
256                 // The client's token was invalid (e.g., expired), or
257                 // the client didn't even provide one.  Propagate the
258                 // 401 to encourage the client to use a [different]
259                 // token.
260                 //
261                 // TODO(TC): This response would be confusing to
262                 // someone trying (anonymously) to download public
263                 // data that has been deleted.  Allow a referrer to
264                 // provide this context somehow?
265                 w.Header().Add("WWW-Authenticate", "Basic realm=\"dl\"")
266                 statusCode = http.StatusUnauthorized
267                 return
268         }
269
270         filename := strings.Join(targetPath, "/")
271         kc, err := keepclient.MakeKeepClient(arv)
272         if err != nil {
273                 statusCode, statusText = http.StatusInternalServerError, err.Error()
274                 return
275         }
276         rdr, err := kc.CollectionFileReader(collection, filename)
277         if os.IsNotExist(err) {
278                 statusCode = http.StatusNotFound
279                 return
280         } else if err != nil {
281                 statusCode, statusText = http.StatusBadGateway, err.Error()
282                 return
283         }
284         defer rdr.Close()
285
286         // One or both of these can be -1 if not found:
287         basenamePos := strings.LastIndex(filename, "/")
288         extPos := strings.LastIndex(filename, ".")
289         if extPos > basenamePos {
290                 // Now extPos is safely >= 0.
291                 if t := mime.TypeByExtension(filename[extPos:]); t != "" {
292                         w.Header().Set("Content-Type", t)
293                 }
294         }
295         w.Header().Set("Content-Length", fmt.Sprintf("%d", rdr.Len()))
296
297         w.WriteHeader(http.StatusOK)
298         _, err = io.Copy(w, rdr)
299         if err != nil {
300                 statusCode, statusText = http.StatusBadGateway, err.Error()
301         }
302 }