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