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