19362: Move non-S3 collection-addressed reqs to sitefs code path.
[arvados.git] / services / keep-web / handler_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package keepweb
6
7 import (
8         "bytes"
9         "context"
10         "fmt"
11         "html"
12         "io"
13         "io/ioutil"
14         "net/http"
15         "net/http/httptest"
16         "net/url"
17         "os"
18         "path/filepath"
19         "regexp"
20         "strings"
21         "time"
22
23         "git.arvados.org/arvados.git/lib/config"
24         "git.arvados.org/arvados.git/sdk/go/arvados"
25         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
26         "git.arvados.org/arvados.git/sdk/go/arvadostest"
27         "git.arvados.org/arvados.git/sdk/go/auth"
28         "git.arvados.org/arvados.git/sdk/go/ctxlog"
29         "git.arvados.org/arvados.git/sdk/go/keepclient"
30         "github.com/prometheus/client_golang/prometheus"
31         "github.com/sirupsen/logrus"
32         check "gopkg.in/check.v1"
33 )
34
35 var _ = check.Suite(&UnitSuite{})
36
37 func init() {
38         arvados.DebugLocksPanicMode = true
39 }
40
41 type UnitSuite struct {
42         cluster *arvados.Cluster
43         handler *handler
44 }
45
46 func (s *UnitSuite) SetUpTest(c *check.C) {
47         logger := ctxlog.TestLogger(c)
48         ldr := config.NewLoader(bytes.NewBufferString("Clusters: {zzzzz: {}}"), logger)
49         ldr.Path = "-"
50         cfg, err := ldr.Load()
51         c.Assert(err, check.IsNil)
52         cc, err := cfg.GetCluster("")
53         c.Assert(err, check.IsNil)
54         s.cluster = cc
55         s.handler = &handler{
56                 Cluster: cc,
57                 Cache: cache{
58                         cluster:  cc,
59                         logger:   logger,
60                         registry: prometheus.NewRegistry(),
61                 },
62         }
63 }
64
65 func (s *UnitSuite) TestCORSPreflight(c *check.C) {
66         h := s.handler
67         u := mustParseURL("http://keep-web.example/c=" + arvadostest.FooCollection + "/foo")
68         req := &http.Request{
69                 Method:     "OPTIONS",
70                 Host:       u.Host,
71                 URL:        u,
72                 RequestURI: u.RequestURI(),
73                 Header: http.Header{
74                         "Origin":                        {"https://workbench.example"},
75                         "Access-Control-Request-Method": {"POST"},
76                 },
77         }
78
79         // Check preflight for an allowed request
80         resp := httptest.NewRecorder()
81         h.ServeHTTP(resp, req)
82         c.Check(resp.Code, check.Equals, http.StatusOK)
83         c.Check(resp.Body.String(), check.Equals, "")
84         c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, "*")
85         c.Check(resp.Header().Get("Access-Control-Allow-Methods"), check.Equals, "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
86         c.Check(resp.Header().Get("Access-Control-Allow-Headers"), check.Equals, "Authorization, Content-Type, Range, Depth, Destination, If, Lock-Token, Overwrite, Timeout")
87
88         // Check preflight for a disallowed request
89         resp = httptest.NewRecorder()
90         req.Header.Set("Access-Control-Request-Method", "MAKE-COFFEE")
91         h.ServeHTTP(resp, req)
92         c.Check(resp.Body.String(), check.Equals, "")
93         c.Check(resp.Code, check.Equals, http.StatusMethodNotAllowed)
94 }
95
96 func (s *UnitSuite) TestEmptyResponse(c *check.C) {
97         for _, trial := range []struct {
98                 dataExists    bool
99                 sendIMSHeader bool
100                 expectStatus  int
101                 logRegexp     string
102         }{
103                 // If we return no content due to a Keep read error,
104                 // we should emit a log message.
105                 {false, false, http.StatusOK, `(?ms).*only wrote 0 bytes.*`},
106
107                 // If we return no content because the client sent an
108                 // If-Modified-Since header, our response should be
109                 // 304.  We still expect a "File download" log since it
110                 // counts as a file access for auditing.
111                 {true, true, http.StatusNotModified, `(?ms).*msg="File download".*`},
112         } {
113                 c.Logf("trial: %+v", trial)
114                 arvadostest.StartKeep(2, true)
115                 if trial.dataExists {
116                         arv, err := arvadosclient.MakeArvadosClient()
117                         c.Assert(err, check.IsNil)
118                         arv.ApiToken = arvadostest.ActiveToken
119                         kc, err := keepclient.MakeKeepClient(arv)
120                         c.Assert(err, check.IsNil)
121                         _, _, err = kc.PutB([]byte("foo"))
122                         c.Assert(err, check.IsNil)
123                 }
124
125                 u := mustParseURL("http://" + arvadostest.FooCollection + ".keep-web.example/foo")
126                 req := &http.Request{
127                         Method:     "GET",
128                         Host:       u.Host,
129                         URL:        u,
130                         RequestURI: u.RequestURI(),
131                         Header: http.Header{
132                                 "Authorization": {"Bearer " + arvadostest.ActiveToken},
133                         },
134                 }
135                 if trial.sendIMSHeader {
136                         req.Header.Set("If-Modified-Since", strings.Replace(time.Now().UTC().Format(time.RFC1123), "UTC", "GMT", -1))
137                 }
138
139                 var logbuf bytes.Buffer
140                 logger := logrus.New()
141                 logger.Out = &logbuf
142                 req = req.WithContext(ctxlog.Context(context.Background(), logger))
143
144                 resp := httptest.NewRecorder()
145                 s.handler.ServeHTTP(resp, req)
146                 c.Check(resp.Code, check.Equals, trial.expectStatus)
147                 c.Check(resp.Body.String(), check.Equals, "")
148
149                 c.Log(logbuf.String())
150                 c.Check(logbuf.String(), check.Matches, trial.logRegexp)
151         }
152 }
153
154 func (s *UnitSuite) TestInvalidUUID(c *check.C) {
155         bogusID := strings.Replace(arvadostest.FooCollectionPDH, "+", "-", 1) + "-"
156         token := arvadostest.ActiveToken
157         for _, trial := range []string{
158                 "http://keep-web/c=" + bogusID + "/foo",
159                 "http://keep-web/c=" + bogusID + "/t=" + token + "/foo",
160                 "http://keep-web/collections/download/" + bogusID + "/" + token + "/foo",
161                 "http://keep-web/collections/" + bogusID + "/foo",
162                 "http://" + bogusID + ".keep-web/" + bogusID + "/foo",
163                 "http://" + bogusID + ".keep-web/t=" + token + "/" + bogusID + "/foo",
164         } {
165                 c.Log(trial)
166                 u := mustParseURL(trial)
167                 req := &http.Request{
168                         Method:     "GET",
169                         Host:       u.Host,
170                         URL:        u,
171                         RequestURI: u.RequestURI(),
172                 }
173                 resp := httptest.NewRecorder()
174                 s.cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
175                 s.handler.ServeHTTP(resp, req)
176                 c.Check(resp.Code, check.Equals, http.StatusNotFound)
177         }
178 }
179
180 func mustParseURL(s string) *url.URL {
181         r, err := url.Parse(s)
182         if err != nil {
183                 panic("parse URL: " + s)
184         }
185         return r
186 }
187
188 func (s *IntegrationSuite) TestVhost404(c *check.C) {
189         for _, testURL := range []string{
190                 arvadostest.NonexistentCollection + ".example.com/theperthcountyconspiracy",
191                 arvadostest.NonexistentCollection + ".example.com/t=" + arvadostest.ActiveToken + "/theperthcountyconspiracy",
192         } {
193                 resp := httptest.NewRecorder()
194                 u := mustParseURL(testURL)
195                 req := &http.Request{
196                         Method:     "GET",
197                         URL:        u,
198                         RequestURI: u.RequestURI(),
199                 }
200                 s.handler.ServeHTTP(resp, req)
201                 c.Check(resp.Code, check.Equals, http.StatusNotFound)
202                 c.Check(resp.Body.String(), check.Equals, notFoundMessage+"\n")
203         }
204 }
205
206 // An authorizer modifies an HTTP request to make use of the given
207 // token -- by adding it to a header, cookie, query param, or whatever
208 // -- and returns the HTTP status code we should expect from keep-web if
209 // the token is invalid.
210 type authorizer func(*http.Request, string) int
211
212 func (s *IntegrationSuite) TestVhostViaAuthzHeaderOAuth2(c *check.C) {
213         s.doVhostRequests(c, authzViaAuthzHeaderOAuth2)
214 }
215 func authzViaAuthzHeaderOAuth2(r *http.Request, tok string) int {
216         r.Header.Add("Authorization", "Bearer "+tok)
217         return http.StatusUnauthorized
218 }
219 func (s *IntegrationSuite) TestVhostViaAuthzHeaderBearer(c *check.C) {
220         s.doVhostRequests(c, authzViaAuthzHeaderBearer)
221 }
222 func authzViaAuthzHeaderBearer(r *http.Request, tok string) int {
223         r.Header.Add("Authorization", "Bearer "+tok)
224         return http.StatusUnauthorized
225 }
226
227 func (s *IntegrationSuite) TestVhostViaCookieValue(c *check.C) {
228         s.doVhostRequests(c, authzViaCookieValue)
229 }
230 func authzViaCookieValue(r *http.Request, tok string) int {
231         r.AddCookie(&http.Cookie{
232                 Name:  "arvados_api_token",
233                 Value: auth.EncodeTokenCookie([]byte(tok)),
234         })
235         return http.StatusUnauthorized
236 }
237
238 func (s *IntegrationSuite) TestVhostViaPath(c *check.C) {
239         s.doVhostRequests(c, authzViaPath)
240 }
241 func authzViaPath(r *http.Request, tok string) int {
242         r.URL.Path = "/t=" + tok + r.URL.Path
243         return http.StatusNotFound
244 }
245
246 func (s *IntegrationSuite) TestVhostViaQueryString(c *check.C) {
247         s.doVhostRequests(c, authzViaQueryString)
248 }
249 func authzViaQueryString(r *http.Request, tok string) int {
250         r.URL.RawQuery = "api_token=" + tok
251         return http.StatusUnauthorized
252 }
253
254 func (s *IntegrationSuite) TestVhostViaPOST(c *check.C) {
255         s.doVhostRequests(c, authzViaPOST)
256 }
257 func authzViaPOST(r *http.Request, tok string) int {
258         r.Method = "POST"
259         r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
260         r.Body = ioutil.NopCloser(strings.NewReader(
261                 url.Values{"api_token": {tok}}.Encode()))
262         return http.StatusUnauthorized
263 }
264
265 func (s *IntegrationSuite) TestVhostViaXHRPOST(c *check.C) {
266         s.doVhostRequests(c, authzViaPOST)
267 }
268 func authzViaXHRPOST(r *http.Request, tok string) int {
269         r.Method = "POST"
270         r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
271         r.Header.Add("Origin", "https://origin.example")
272         r.Body = ioutil.NopCloser(strings.NewReader(
273                 url.Values{
274                         "api_token":   {tok},
275                         "disposition": {"attachment"},
276                 }.Encode()))
277         return http.StatusUnauthorized
278 }
279
280 // Try some combinations of {url, token} using the given authorization
281 // mechanism, and verify the result is correct.
282 func (s *IntegrationSuite) doVhostRequests(c *check.C, authz authorizer) {
283         for _, hostPath := range []string{
284                 arvadostest.FooCollection + ".example.com/foo",
285                 arvadostest.FooCollection + "--collections.example.com/foo",
286                 arvadostest.FooCollection + "--collections.example.com/_/foo",
287                 arvadostest.FooCollectionPDH + ".example.com/foo",
288                 strings.Replace(arvadostest.FooCollectionPDH, "+", "-", -1) + "--collections.example.com/foo",
289                 arvadostest.FooBarDirCollection + ".example.com/dir1/foo",
290         } {
291                 c.Log("doRequests: ", hostPath)
292                 s.doVhostRequestsWithHostPath(c, authz, hostPath)
293         }
294 }
295
296 func (s *IntegrationSuite) doVhostRequestsWithHostPath(c *check.C, authz authorizer, hostPath string) {
297         for _, tok := range []string{
298                 arvadostest.ActiveToken,
299                 arvadostest.ActiveToken[:15],
300                 arvadostest.SpectatorToken,
301                 "bogus",
302                 "",
303         } {
304                 u := mustParseURL("http://" + hostPath)
305                 req := &http.Request{
306                         Method:     "GET",
307                         Host:       u.Host,
308                         URL:        u,
309                         RequestURI: u.RequestURI(),
310                         Header:     http.Header{},
311                 }
312                 failCode := authz(req, tok)
313                 req, resp := s.doReq(req)
314                 code, body := resp.Code, resp.Body.String()
315
316                 // If the initial request had a (non-empty) token
317                 // showing in the query string, we should have been
318                 // redirected in order to hide it in a cookie.
319                 c.Check(req.URL.String(), check.Not(check.Matches), `.*api_token=.+`)
320
321                 if tok == arvadostest.ActiveToken {
322                         c.Check(code, check.Equals, http.StatusOK)
323                         c.Check(body, check.Equals, "foo")
324                 } else {
325                         c.Check(code >= 400, check.Equals, true)
326                         c.Check(code < 500, check.Equals, true)
327                         if tok == arvadostest.SpectatorToken {
328                                 // Valid token never offers to retry
329                                 // with different credentials.
330                                 c.Check(code, check.Equals, http.StatusNotFound)
331                         } else {
332                                 // Invalid token can ask to retry
333                                 // depending on the authz method.
334                                 c.Check(code, check.Equals, failCode)
335                         }
336                         if code == 404 {
337                                 c.Check(body, check.Equals, notFoundMessage+"\n")
338                         } else {
339                                 c.Check(body, check.Equals, unauthorizedMessage+"\n")
340                         }
341                 }
342         }
343 }
344
345 func (s *IntegrationSuite) TestVhostPortMatch(c *check.C) {
346         for _, host := range []string{"download.example.com", "DOWNLOAD.EXAMPLE.COM"} {
347                 for _, port := range []string{"80", "443", "8000"} {
348                         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = fmt.Sprintf("download.example.com:%v", port)
349                         u := mustParseURL(fmt.Sprintf("http://%v/by_id/%v/foo", host, arvadostest.FooCollection))
350                         req := &http.Request{
351                                 Method:     "GET",
352                                 Host:       u.Host,
353                                 URL:        u,
354                                 RequestURI: u.RequestURI(),
355                                 Header:     http.Header{"Authorization": []string{"Bearer " + arvadostest.ActiveToken}},
356                         }
357                         req, resp := s.doReq(req)
358                         code, _ := resp.Code, resp.Body.String()
359
360                         if port == "8000" {
361                                 c.Check(code, check.Equals, 401)
362                         } else {
363                                 c.Check(code, check.Equals, 200)
364                         }
365                 }
366         }
367 }
368
369 func (s *IntegrationSuite) do(method string, urlstring string, token string, hdr http.Header) (*http.Request, *httptest.ResponseRecorder) {
370         u := mustParseURL(urlstring)
371         if hdr == nil && token != "" {
372                 hdr = http.Header{"Authorization": {"Bearer " + token}}
373         } else if hdr == nil {
374                 hdr = http.Header{}
375         } else if token != "" {
376                 panic("must not pass both token and hdr")
377         }
378         return s.doReq(&http.Request{
379                 Method:     method,
380                 Host:       u.Host,
381                 URL:        u,
382                 RequestURI: u.RequestURI(),
383                 Header:     hdr,
384         })
385 }
386
387 func (s *IntegrationSuite) doReq(req *http.Request) (*http.Request, *httptest.ResponseRecorder) {
388         resp := httptest.NewRecorder()
389         s.handler.ServeHTTP(resp, req)
390         if resp.Code != http.StatusSeeOther {
391                 return req, resp
392         }
393         cookies := (&http.Response{Header: resp.Header()}).Cookies()
394         u, _ := req.URL.Parse(resp.Header().Get("Location"))
395         req = &http.Request{
396                 Method:     "GET",
397                 Host:       u.Host,
398                 URL:        u,
399                 RequestURI: u.RequestURI(),
400                 Header:     http.Header{},
401         }
402         for _, c := range cookies {
403                 req.AddCookie(c)
404         }
405         return s.doReq(req)
406 }
407
408 func (s *IntegrationSuite) TestVhostRedirectQueryTokenToCookie(c *check.C) {
409         s.testVhostRedirectTokenToCookie(c, "GET",
410                 arvadostest.FooCollection+".example.com/foo",
411                 "?api_token="+arvadostest.ActiveToken,
412                 nil,
413                 "",
414                 http.StatusOK,
415                 "foo",
416         )
417 }
418
419 func (s *IntegrationSuite) TestSingleOriginSecretLink(c *check.C) {
420         s.testVhostRedirectTokenToCookie(c, "GET",
421                 "example.com/c="+arvadostest.FooCollection+"/t="+arvadostest.ActiveToken+"/foo",
422                 "",
423                 nil,
424                 "",
425                 http.StatusOK,
426                 "foo",
427         )
428 }
429
430 func (s *IntegrationSuite) TestCollectionSharingToken(c *check.C) {
431         s.testVhostRedirectTokenToCookie(c, "GET",
432                 "example.com/c="+arvadostest.FooFileCollectionUUID+"/t="+arvadostest.FooFileCollectionSharingToken+"/foo",
433                 "",
434                 nil,
435                 "",
436                 http.StatusOK,
437                 "foo",
438         )
439         // Same valid sharing token, but requesting a different collection
440         s.testVhostRedirectTokenToCookie(c, "GET",
441                 "example.com/c="+arvadostest.FooCollection+"/t="+arvadostest.FooFileCollectionSharingToken+"/foo",
442                 "",
443                 nil,
444                 "",
445                 http.StatusNotFound,
446                 notFoundMessage+"\n",
447         )
448 }
449
450 // Bad token in URL is 404 Not Found because it doesn't make sense to
451 // retry the same URL with different authorization.
452 func (s *IntegrationSuite) TestSingleOriginSecretLinkBadToken(c *check.C) {
453         s.testVhostRedirectTokenToCookie(c, "GET",
454                 "example.com/c="+arvadostest.FooCollection+"/t=bogus/foo",
455                 "",
456                 nil,
457                 "",
458                 http.StatusNotFound,
459                 notFoundMessage+"\n",
460         )
461 }
462
463 // Bad token in a cookie (even if it got there via our own
464 // query-string-to-cookie redirect) is, in principle, retryable via
465 // wb2-login-and-redirect flow.
466 func (s *IntegrationSuite) TestVhostRedirectQueryTokenToBogusCookie(c *check.C) {
467         // Inline
468         resp := s.testVhostRedirectTokenToCookie(c, "GET",
469                 arvadostest.FooCollection+".example.com/foo",
470                 "?api_token=thisisabogustoken",
471                 http.Header{"Sec-Fetch-Mode": {"navigate"}},
472                 "",
473                 http.StatusSeeOther,
474                 "",
475         )
476         u, err := url.Parse(resp.Header().Get("Location"))
477         c.Assert(err, check.IsNil)
478         c.Logf("redirected to %s", u)
479         c.Check(u.Host, check.Equals, s.handler.Cluster.Services.Workbench2.ExternalURL.Host)
480         c.Check(u.Query().Get("redirectToPreview"), check.Equals, "/c="+arvadostest.FooCollection+"/foo")
481         c.Check(u.Query().Get("redirectToDownload"), check.Equals, "")
482
483         // Download/attachment indicated by ?disposition=attachment
484         resp = s.testVhostRedirectTokenToCookie(c, "GET",
485                 arvadostest.FooCollection+".example.com/foo",
486                 "?api_token=thisisabogustoken&disposition=attachment",
487                 http.Header{"Sec-Fetch-Mode": {"navigate"}},
488                 "",
489                 http.StatusSeeOther,
490                 "",
491         )
492         u, err = url.Parse(resp.Header().Get("Location"))
493         c.Assert(err, check.IsNil)
494         c.Logf("redirected to %s", u)
495         c.Check(u.Host, check.Equals, s.handler.Cluster.Services.Workbench2.ExternalURL.Host)
496         c.Check(u.Query().Get("redirectToPreview"), check.Equals, "")
497         c.Check(u.Query().Get("redirectToDownload"), check.Equals, "/c="+arvadostest.FooCollection+"/foo")
498
499         // Download/attachment indicated by vhost
500         resp = s.testVhostRedirectTokenToCookie(c, "GET",
501                 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host+"/c="+arvadostest.FooCollection+"/foo",
502                 "?api_token=thisisabogustoken",
503                 http.Header{"Sec-Fetch-Mode": {"navigate"}},
504                 "",
505                 http.StatusSeeOther,
506                 "",
507         )
508         u, err = url.Parse(resp.Header().Get("Location"))
509         c.Assert(err, check.IsNil)
510         c.Logf("redirected to %s", u)
511         c.Check(u.Host, check.Equals, s.handler.Cluster.Services.Workbench2.ExternalURL.Host)
512         c.Check(u.Query().Get("redirectToPreview"), check.Equals, "")
513         c.Check(u.Query().Get("redirectToDownload"), check.Equals, "/c="+arvadostest.FooCollection+"/foo")
514
515         // Without "Sec-Fetch-Mode: navigate" header, just 401.
516         s.testVhostRedirectTokenToCookie(c, "GET",
517                 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host+"/c="+arvadostest.FooCollection+"/foo",
518                 "?api_token=thisisabogustoken",
519                 http.Header{"Sec-Fetch-Mode": {"cors"}},
520                 "",
521                 http.StatusUnauthorized,
522                 unauthorizedMessage+"\n",
523         )
524         s.testVhostRedirectTokenToCookie(c, "GET",
525                 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host+"/c="+arvadostest.FooCollection+"/foo",
526                 "?api_token=thisisabogustoken",
527                 nil,
528                 "",
529                 http.StatusUnauthorized,
530                 unauthorizedMessage+"\n",
531         )
532 }
533
534 func (s *IntegrationSuite) TestVhostRedirectQueryTokenSingleOriginError(c *check.C) {
535         s.testVhostRedirectTokenToCookie(c, "GET",
536                 "example.com/c="+arvadostest.FooCollection+"/foo",
537                 "?api_token="+arvadostest.ActiveToken,
538                 nil,
539                 "",
540                 http.StatusBadRequest,
541                 "cannot serve inline content at this URL (possible configuration error; see https://doc.arvados.org/install/install-keep-web.html#dns)\n",
542         )
543 }
544
545 // If client requests an attachment by putting ?disposition=attachment
546 // in the query string, and gets redirected, the redirect target
547 // should respond with an attachment.
548 func (s *IntegrationSuite) TestVhostRedirectQueryTokenRequestAttachment(c *check.C) {
549         resp := s.testVhostRedirectTokenToCookie(c, "GET",
550                 arvadostest.FooCollection+".example.com/foo",
551                 "?disposition=attachment&api_token="+arvadostest.ActiveToken,
552                 nil,
553                 "",
554                 http.StatusOK,
555                 "foo",
556         )
557         c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
558 }
559
560 func (s *IntegrationSuite) TestVhostRedirectQueryTokenSiteFS(c *check.C) {
561         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
562         resp := s.testVhostRedirectTokenToCookie(c, "GET",
563                 "download.example.com/by_id/"+arvadostest.FooCollection+"/foo",
564                 "?api_token="+arvadostest.ActiveToken,
565                 nil,
566                 "",
567                 http.StatusOK,
568                 "foo",
569         )
570         c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
571 }
572
573 func (s *IntegrationSuite) TestPastCollectionVersionFileAccess(c *check.C) {
574         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
575         resp := s.testVhostRedirectTokenToCookie(c, "GET",
576                 "download.example.com/c="+arvadostest.WazVersion1Collection+"/waz",
577                 "?api_token="+arvadostest.ActiveToken,
578                 nil,
579                 "",
580                 http.StatusOK,
581                 "waz",
582         )
583         c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
584         resp = s.testVhostRedirectTokenToCookie(c, "GET",
585                 "download.example.com/by_id/"+arvadostest.WazVersion1Collection+"/waz",
586                 "?api_token="+arvadostest.ActiveToken,
587                 nil,
588                 "",
589                 http.StatusOK,
590                 "waz",
591         )
592         c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
593 }
594
595 func (s *IntegrationSuite) TestVhostRedirectQueryTokenTrustAllContent(c *check.C) {
596         s.handler.Cluster.Collections.TrustAllContent = true
597         s.testVhostRedirectTokenToCookie(c, "GET",
598                 "example.com/c="+arvadostest.FooCollection+"/foo",
599                 "?api_token="+arvadostest.ActiveToken,
600                 nil,
601                 "",
602                 http.StatusOK,
603                 "foo",
604         )
605 }
606
607 func (s *IntegrationSuite) TestVhostRedirectQueryTokenAttachmentOnlyHost(c *check.C) {
608         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "example.com:1234"
609
610         s.testVhostRedirectTokenToCookie(c, "GET",
611                 "example.com/c="+arvadostest.FooCollection+"/foo",
612                 "?api_token="+arvadostest.ActiveToken,
613                 nil,
614                 "",
615                 http.StatusBadRequest,
616                 "cannot serve inline content at this URL (possible configuration error; see https://doc.arvados.org/install/install-keep-web.html#dns)\n",
617         )
618
619         resp := s.testVhostRedirectTokenToCookie(c, "GET",
620                 "example.com:1234/c="+arvadostest.FooCollection+"/foo",
621                 "?api_token="+arvadostest.ActiveToken,
622                 nil,
623                 "",
624                 http.StatusOK,
625                 "foo",
626         )
627         c.Check(resp.Header().Get("Content-Disposition"), check.Equals, "attachment")
628 }
629
630 func (s *IntegrationSuite) TestVhostRedirectPOSTFormTokenToCookie(c *check.C) {
631         s.testVhostRedirectTokenToCookie(c, "POST",
632                 arvadostest.FooCollection+".example.com/foo",
633                 "",
634                 http.Header{"Content-Type": {"application/x-www-form-urlencoded"}},
635                 url.Values{"api_token": {arvadostest.ActiveToken}}.Encode(),
636                 http.StatusOK,
637                 "foo",
638         )
639 }
640
641 func (s *IntegrationSuite) TestVhostRedirectPOSTFormTokenToCookie404(c *check.C) {
642         s.testVhostRedirectTokenToCookie(c, "POST",
643                 arvadostest.FooCollection+".example.com/foo",
644                 "",
645                 http.Header{"Content-Type": {"application/x-www-form-urlencoded"}},
646                 url.Values{"api_token": {arvadostest.SpectatorToken}}.Encode(),
647                 http.StatusNotFound,
648                 notFoundMessage+"\n",
649         )
650 }
651
652 func (s *IntegrationSuite) TestAnonymousTokenOK(c *check.C) {
653         s.handler.Cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
654         s.testVhostRedirectTokenToCookie(c, "GET",
655                 "example.com/c="+arvadostest.HelloWorldCollection+"/Hello%20world.txt",
656                 "",
657                 nil,
658                 "",
659                 http.StatusOK,
660                 "Hello world\n",
661         )
662 }
663
664 func (s *IntegrationSuite) TestAnonymousTokenError(c *check.C) {
665         s.handler.Cluster.Users.AnonymousUserToken = "anonymousTokenConfiguredButInvalid"
666         s.testVhostRedirectTokenToCookie(c, "GET",
667                 "example.com/c="+arvadostest.HelloWorldCollection+"/Hello%20world.txt",
668                 "",
669                 nil,
670                 "",
671                 http.StatusNotFound,
672                 notFoundMessage+"\n",
673         )
674 }
675
676 func (s *IntegrationSuite) TestSpecialCharsInPath(c *check.C) {
677         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
678
679         client := arvados.NewClientFromEnv()
680         client.AuthToken = arvadostest.ActiveToken
681         fs, err := (&arvados.Collection{}).FileSystem(client, nil)
682         c.Assert(err, check.IsNil)
683         f, err := fs.OpenFile("https:\\\"odd' path chars", os.O_CREATE, 0777)
684         c.Assert(err, check.IsNil)
685         f.Close()
686         mtxt, err := fs.MarshalManifest(".")
687         c.Assert(err, check.IsNil)
688         var coll arvados.Collection
689         err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
690                 "collection": map[string]string{
691                         "manifest_text": mtxt,
692                 },
693         })
694         c.Assert(err, check.IsNil)
695
696         u, _ := url.Parse("http://download.example.com/c=" + coll.UUID + "/")
697         req := &http.Request{
698                 Method:     "GET",
699                 Host:       u.Host,
700                 URL:        u,
701                 RequestURI: u.RequestURI(),
702                 Header: http.Header{
703                         "Authorization": {"Bearer " + client.AuthToken},
704                 },
705         }
706         resp := httptest.NewRecorder()
707         s.handler.ServeHTTP(resp, req)
708         c.Check(resp.Code, check.Equals, http.StatusOK)
709         c.Check(resp.Body.String(), check.Matches, `(?ms).*href="./https:%5c%22odd%27%20path%20chars"\S+https:\\&#34;odd&#39; path chars.*`)
710 }
711
712 func (s *IntegrationSuite) TestForwardSlashSubstitution(c *check.C) {
713         arv := arvados.NewClientFromEnv()
714         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
715         s.handler.Cluster.Collections.ForwardSlashNameSubstitution = "{SOLIDUS}"
716         name := "foo/bar/baz"
717         nameShown := strings.Replace(name, "/", "{SOLIDUS}", -1)
718         nameShownEscaped := strings.Replace(name, "/", "%7bSOLIDUS%7d", -1)
719
720         client := arvados.NewClientFromEnv()
721         client.AuthToken = arvadostest.ActiveToken
722         fs, err := (&arvados.Collection{}).FileSystem(client, nil)
723         c.Assert(err, check.IsNil)
724         f, err := fs.OpenFile("filename", os.O_CREATE, 0777)
725         c.Assert(err, check.IsNil)
726         f.Close()
727         mtxt, err := fs.MarshalManifest(".")
728         c.Assert(err, check.IsNil)
729         var coll arvados.Collection
730         err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
731                 "collection": map[string]string{
732                         "manifest_text": mtxt,
733                         "name":          name,
734                         "owner_uuid":    arvadostest.AProjectUUID,
735                 },
736         })
737         c.Assert(err, check.IsNil)
738         defer arv.RequestAndDecode(&coll, "DELETE", "arvados/v1/collections/"+coll.UUID, nil, nil)
739
740         base := "http://download.example.com/by_id/" + coll.OwnerUUID + "/"
741         for tryURL, expectRegexp := range map[string]string{
742                 base:                          `(?ms).*href="./` + nameShownEscaped + `/"\S+` + nameShown + `.*`,
743                 base + nameShownEscaped + "/": `(?ms).*href="./filename"\S+filename.*`,
744         } {
745                 u, _ := url.Parse(tryURL)
746                 req := &http.Request{
747                         Method:     "GET",
748                         Host:       u.Host,
749                         URL:        u,
750                         RequestURI: u.RequestURI(),
751                         Header: http.Header{
752                                 "Authorization": {"Bearer " + client.AuthToken},
753                         },
754                 }
755                 resp := httptest.NewRecorder()
756                 s.handler.ServeHTTP(resp, req)
757                 c.Check(resp.Code, check.Equals, http.StatusOK)
758                 c.Check(resp.Body.String(), check.Matches, expectRegexp)
759         }
760 }
761
762 // XHRs can't follow redirect-with-cookie so they rely on method=POST
763 // and disposition=attachment (telling us it's acceptable to respond
764 // with content instead of a redirect) and an Origin header that gets
765 // added automatically by the browser (telling us it's desirable to do
766 // so).
767 func (s *IntegrationSuite) TestXHRNoRedirect(c *check.C) {
768         u, _ := url.Parse("http://example.com/c=" + arvadostest.FooCollection + "/foo")
769         req := &http.Request{
770                 Method:     "POST",
771                 Host:       u.Host,
772                 URL:        u,
773                 RequestURI: u.RequestURI(),
774                 Header: http.Header{
775                         "Origin":       {"https://origin.example"},
776                         "Content-Type": {"application/x-www-form-urlencoded"},
777                 },
778                 Body: ioutil.NopCloser(strings.NewReader(url.Values{
779                         "api_token":   {arvadostest.ActiveToken},
780                         "disposition": {"attachment"},
781                 }.Encode())),
782         }
783         resp := httptest.NewRecorder()
784         s.handler.ServeHTTP(resp, req)
785         c.Check(resp.Code, check.Equals, http.StatusOK)
786         c.Check(resp.Body.String(), check.Equals, "foo")
787         c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, "*")
788
789         // GET + Origin header is representative of both AJAX GET
790         // requests and inline images via <IMG crossorigin="anonymous"
791         // src="...">.
792         u.RawQuery = "api_token=" + url.QueryEscape(arvadostest.ActiveTokenV2)
793         req = &http.Request{
794                 Method:     "GET",
795                 Host:       u.Host,
796                 URL:        u,
797                 RequestURI: u.RequestURI(),
798                 Header: http.Header{
799                         "Origin": {"https://origin.example"},
800                 },
801         }
802         resp = httptest.NewRecorder()
803         s.handler.ServeHTTP(resp, req)
804         c.Check(resp.Code, check.Equals, http.StatusOK)
805         c.Check(resp.Body.String(), check.Equals, "foo")
806         c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, "*")
807 }
808
809 func (s *IntegrationSuite) testVhostRedirectTokenToCookie(c *check.C, method, hostPath, queryString string, reqHeader http.Header, reqBody string, expectStatus int, expectRespBody string) *httptest.ResponseRecorder {
810         if reqHeader == nil {
811                 reqHeader = http.Header{}
812         }
813         u, _ := url.Parse(`http://` + hostPath + queryString)
814         c.Logf("requesting %s", u)
815         req := &http.Request{
816                 Method:     method,
817                 Host:       u.Host,
818                 URL:        u,
819                 RequestURI: u.RequestURI(),
820                 Header:     reqHeader,
821                 Body:       ioutil.NopCloser(strings.NewReader(reqBody)),
822         }
823
824         resp := httptest.NewRecorder()
825         defer func() {
826                 c.Check(resp.Code, check.Equals, expectStatus)
827                 c.Check(resp.Body.String(), check.Equals, expectRespBody)
828         }()
829
830         s.handler.ServeHTTP(resp, req)
831         if resp.Code != http.StatusSeeOther {
832                 return resp
833         }
834         c.Check(resp.Body.String(), check.Matches, `.*href="http://`+regexp.QuoteMeta(html.EscapeString(hostPath))+`(\?[^"]*)?".*`)
835         c.Check(strings.Split(resp.Header().Get("Location"), "?")[0], check.Equals, "http://"+hostPath)
836         cookies := (&http.Response{Header: resp.Header()}).Cookies()
837
838         u, err := u.Parse(resp.Header().Get("Location"))
839         c.Assert(err, check.IsNil)
840         c.Logf("following redirect to %s", u)
841         req = &http.Request{
842                 Method:     "GET",
843                 Host:       u.Host,
844                 URL:        u,
845                 RequestURI: u.RequestURI(),
846                 Header:     reqHeader,
847         }
848         for _, c := range cookies {
849                 req.AddCookie(c)
850         }
851
852         resp = httptest.NewRecorder()
853         s.handler.ServeHTTP(resp, req)
854
855         if resp.Code != http.StatusSeeOther {
856                 c.Check(resp.Header().Get("Location"), check.Equals, "")
857         }
858         return resp
859 }
860
861 func (s *IntegrationSuite) TestDirectoryListingWithAnonymousToken(c *check.C) {
862         s.handler.Cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
863         s.testDirectoryListing(c)
864 }
865
866 func (s *IntegrationSuite) TestDirectoryListingWithNoAnonymousToken(c *check.C) {
867         s.handler.Cluster.Users.AnonymousUserToken = ""
868         s.testDirectoryListing(c)
869 }
870
871 func (s *IntegrationSuite) testDirectoryListing(c *check.C) {
872         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
873         authHeader := http.Header{
874                 "Authorization": {"OAuth2 " + arvadostest.ActiveToken},
875         }
876         for _, trial := range []struct {
877                 uri      string
878                 header   http.Header
879                 expect   []string
880                 redirect string
881                 cutDirs  int
882         }{
883                 {
884                         uri:     strings.Replace(arvadostest.FooAndBarFilesInDirPDH, "+", "-", -1) + ".example.com/",
885                         header:  authHeader,
886                         expect:  []string{"dir1/foo", "dir1/bar"},
887                         cutDirs: 0,
888                 },
889                 {
890                         uri:     strings.Replace(arvadostest.FooAndBarFilesInDirPDH, "+", "-", -1) + ".example.com/dir1/",
891                         header:  authHeader,
892                         expect:  []string{"foo", "bar"},
893                         cutDirs: 1,
894                 },
895                 {
896                         // URLs of this form ignore authHeader, and
897                         // FooAndBarFilesInDirUUID isn't public, so
898                         // this returns 401.
899                         uri:    "download.example.com/collections/" + arvadostest.FooAndBarFilesInDirUUID + "/",
900                         header: authHeader,
901                         expect: nil,
902                 },
903                 {
904                         uri:     "download.example.com/users/active/foo_file_in_dir/",
905                         header:  authHeader,
906                         expect:  []string{"dir1/"},
907                         cutDirs: 3,
908                 },
909                 {
910                         uri:     "download.example.com/users/active/foo_file_in_dir/dir1/",
911                         header:  authHeader,
912                         expect:  []string{"bar"},
913                         cutDirs: 4,
914                 },
915                 {
916                         uri:     "download.example.com/",
917                         header:  authHeader,
918                         expect:  []string{"users/"},
919                         cutDirs: 0,
920                 },
921                 {
922                         uri:      "download.example.com/users",
923                         header:   authHeader,
924                         redirect: "/users/",
925                         expect:   []string{"active/"},
926                         cutDirs:  1,
927                 },
928                 {
929                         uri:     "download.example.com/users/",
930                         header:  authHeader,
931                         expect:  []string{"active/"},
932                         cutDirs: 1,
933                 },
934                 {
935                         uri:      "download.example.com/users/active",
936                         header:   authHeader,
937                         redirect: "/users/active/",
938                         expect:   []string{"foo_file_in_dir/"},
939                         cutDirs:  2,
940                 },
941                 {
942                         uri:     "download.example.com/users/active/",
943                         header:  authHeader,
944                         expect:  []string{"foo_file_in_dir/"},
945                         cutDirs: 2,
946                 },
947                 {
948                         uri:     "collections.example.com/collections/download/" + arvadostest.FooAndBarFilesInDirUUID + "/" + arvadostest.ActiveToken + "/",
949                         header:  nil,
950                         expect:  []string{"dir1/foo", "dir1/bar"},
951                         cutDirs: 4,
952                 },
953                 {
954                         uri:     "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/t=" + arvadostest.ActiveToken + "/",
955                         header:  nil,
956                         expect:  []string{"dir1/foo", "dir1/bar"},
957                         cutDirs: 2,
958                 },
959                 {
960                         uri:     "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/t=" + arvadostest.ActiveToken,
961                         header:  nil,
962                         expect:  []string{"dir1/foo", "dir1/bar"},
963                         cutDirs: 2,
964                 },
965                 {
966                         uri:     "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID,
967                         header:  authHeader,
968                         expect:  []string{"dir1/foo", "dir1/bar"},
969                         cutDirs: 1,
970                 },
971                 {
972                         uri:      "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/dir1",
973                         header:   authHeader,
974                         redirect: "/c=" + arvadostest.FooAndBarFilesInDirUUID + "/dir1/",
975                         expect:   []string{"foo", "bar"},
976                         cutDirs:  2,
977                 },
978                 {
979                         uri:     "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/_/dir1/",
980                         header:  authHeader,
981                         expect:  []string{"foo", "bar"},
982                         cutDirs: 3,
983                 },
984                 {
985                         uri:      arvadostest.FooAndBarFilesInDirUUID + ".example.com/dir1?api_token=" + arvadostest.ActiveToken,
986                         header:   authHeader,
987                         redirect: "/dir1/",
988                         expect:   []string{"foo", "bar"},
989                         cutDirs:  1,
990                 },
991                 {
992                         uri:    "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/theperthcountyconspiracydoesnotexist/",
993                         header: authHeader,
994                         expect: nil,
995                 },
996                 {
997                         uri:     "download.example.com/c=" + arvadostest.WazVersion1Collection,
998                         header:  authHeader,
999                         expect:  []string{"waz"},
1000                         cutDirs: 1,
1001                 },
1002                 {
1003                         uri:     "download.example.com/by_id/" + arvadostest.WazVersion1Collection,
1004                         header:  authHeader,
1005                         expect:  []string{"waz"},
1006                         cutDirs: 2,
1007                 },
1008         } {
1009                 comment := check.Commentf("HTML: %q => %q", trial.uri, trial.expect)
1010                 resp := httptest.NewRecorder()
1011                 u := mustParseURL("//" + trial.uri)
1012                 req := &http.Request{
1013                         Method:     "GET",
1014                         Host:       u.Host,
1015                         URL:        u,
1016                         RequestURI: u.RequestURI(),
1017                         Header:     copyHeader(trial.header),
1018                 }
1019                 s.handler.ServeHTTP(resp, req)
1020                 var cookies []*http.Cookie
1021                 for resp.Code == http.StatusSeeOther {
1022                         u, _ := req.URL.Parse(resp.Header().Get("Location"))
1023                         req = &http.Request{
1024                                 Method:     "GET",
1025                                 Host:       u.Host,
1026                                 URL:        u,
1027                                 RequestURI: u.RequestURI(),
1028                                 Header:     copyHeader(trial.header),
1029                         }
1030                         cookies = append(cookies, (&http.Response{Header: resp.Header()}).Cookies()...)
1031                         for _, c := range cookies {
1032                                 req.AddCookie(c)
1033                         }
1034                         resp = httptest.NewRecorder()
1035                         s.handler.ServeHTTP(resp, req)
1036                 }
1037                 if trial.redirect != "" {
1038                         c.Check(req.URL.Path, check.Equals, trial.redirect, comment)
1039                 }
1040                 if trial.expect == nil {
1041                         if s.handler.Cluster.Users.AnonymousUserToken == "" {
1042                                 c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
1043                         } else {
1044                                 c.Check(resp.Code, check.Equals, http.StatusNotFound, comment)
1045                         }
1046                 } else {
1047                         c.Check(resp.Code, check.Equals, http.StatusOK, comment)
1048                         for _, e := range trial.expect {
1049                                 c.Check(resp.Body.String(), check.Matches, `(?ms).*href="./`+e+`".*`, comment)
1050                         }
1051                         c.Check(resp.Body.String(), check.Matches, `(?ms).*--cut-dirs=`+fmt.Sprintf("%d", trial.cutDirs)+` .*`, comment)
1052                 }
1053
1054                 comment = check.Commentf("WebDAV: %q => %q", trial.uri, trial.expect)
1055                 req = &http.Request{
1056                         Method:     "OPTIONS",
1057                         Host:       u.Host,
1058                         URL:        u,
1059                         RequestURI: u.RequestURI(),
1060                         Header:     copyHeader(trial.header),
1061                         Body:       ioutil.NopCloser(&bytes.Buffer{}),
1062                 }
1063                 resp = httptest.NewRecorder()
1064                 s.handler.ServeHTTP(resp, req)
1065                 if trial.expect == nil {
1066                         if s.handler.Cluster.Users.AnonymousUserToken == "" {
1067                                 c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
1068                         } else {
1069                                 c.Check(resp.Code, check.Equals, http.StatusNotFound, comment)
1070                         }
1071                 } else {
1072                         c.Check(resp.Code, check.Equals, http.StatusOK, comment)
1073                 }
1074
1075                 req = &http.Request{
1076                         Method:     "PROPFIND",
1077                         Host:       u.Host,
1078                         URL:        u,
1079                         RequestURI: u.RequestURI(),
1080                         Header:     copyHeader(trial.header),
1081                         Body:       ioutil.NopCloser(&bytes.Buffer{}),
1082                 }
1083                 resp = httptest.NewRecorder()
1084                 s.handler.ServeHTTP(resp, req)
1085                 if trial.expect == nil {
1086                         if s.handler.Cluster.Users.AnonymousUserToken == "" {
1087                                 c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
1088                         } else {
1089                                 c.Check(resp.Code, check.Equals, http.StatusNotFound, comment)
1090                         }
1091                 } else {
1092                         c.Check(resp.Code, check.Equals, http.StatusMultiStatus, comment)
1093                         for _, e := range trial.expect {
1094                                 if strings.HasSuffix(e, "/") {
1095                                         e = filepath.Join(u.Path, e) + "/"
1096                                 } else {
1097                                         e = filepath.Join(u.Path, e)
1098                                 }
1099                                 c.Check(resp.Body.String(), check.Matches, `(?ms).*<D:href>`+e+`</D:href>.*`, comment)
1100                         }
1101                 }
1102         }
1103 }
1104
1105 func (s *IntegrationSuite) TestDeleteLastFile(c *check.C) {
1106         arv := arvados.NewClientFromEnv()
1107         var newCollection arvados.Collection
1108         err := arv.RequestAndDecode(&newCollection, "POST", "arvados/v1/collections", nil, map[string]interface{}{
1109                 "collection": map[string]string{
1110                         "owner_uuid":    arvadostest.ActiveUserUUID,
1111                         "manifest_text": ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo.txt 0:3:bar.txt\n",
1112                         "name":          "keep-web test collection",
1113                 },
1114                 "ensure_unique_name": true,
1115         })
1116         c.Assert(err, check.IsNil)
1117         defer arv.RequestAndDecode(&newCollection, "DELETE", "arvados/v1/collections/"+newCollection.UUID, nil, nil)
1118
1119         var updated arvados.Collection
1120         for _, fnm := range []string{"foo.txt", "bar.txt"} {
1121                 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "example.com"
1122                 u, _ := url.Parse("http://example.com/c=" + newCollection.UUID + "/" + fnm)
1123                 req := &http.Request{
1124                         Method:     "DELETE",
1125                         Host:       u.Host,
1126                         URL:        u,
1127                         RequestURI: u.RequestURI(),
1128                         Header: http.Header{
1129                                 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1130                         },
1131                 }
1132                 resp := httptest.NewRecorder()
1133                 s.handler.ServeHTTP(resp, req)
1134                 c.Check(resp.Code, check.Equals, http.StatusNoContent)
1135
1136                 updated = arvados.Collection{}
1137                 err = arv.RequestAndDecode(&updated, "GET", "arvados/v1/collections/"+newCollection.UUID, nil, nil)
1138                 c.Check(err, check.IsNil)
1139                 c.Check(updated.ManifestText, check.Not(check.Matches), `(?ms).*\Q`+fnm+`\E.*`)
1140                 c.Logf("updated manifest_text %q", updated.ManifestText)
1141         }
1142         c.Check(updated.ManifestText, check.Equals, "")
1143 }
1144
1145 func (s *IntegrationSuite) TestFileContentType(c *check.C) {
1146         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
1147
1148         client := arvados.NewClientFromEnv()
1149         client.AuthToken = arvadostest.ActiveToken
1150         arv, err := arvadosclient.New(client)
1151         c.Assert(err, check.Equals, nil)
1152         kc, err := keepclient.MakeKeepClient(arv)
1153         c.Assert(err, check.Equals, nil)
1154
1155         fs, err := (&arvados.Collection{}).FileSystem(client, kc)
1156         c.Assert(err, check.IsNil)
1157
1158         trials := []struct {
1159                 filename    string
1160                 content     string
1161                 contentType string
1162         }{
1163                 {"picture.txt", "BMX bikes are small this year\n", "text/plain; charset=utf-8"},
1164                 {"picture.bmp", "BMX bikes are small this year\n", "image/(x-ms-)?bmp"},
1165                 {"picture.jpg", "BMX bikes are small this year\n", "image/jpeg"},
1166                 {"picture1", "BMX bikes are small this year\n", "image/bmp"},            // content sniff; "BM" is the magic signature for .bmp
1167                 {"picture2", "Cars are small this year\n", "text/plain; charset=utf-8"}, // content sniff
1168         }
1169         for _, trial := range trials {
1170                 f, err := fs.OpenFile(trial.filename, os.O_CREATE|os.O_WRONLY, 0777)
1171                 c.Assert(err, check.IsNil)
1172                 _, err = f.Write([]byte(trial.content))
1173                 c.Assert(err, check.IsNil)
1174                 c.Assert(f.Close(), check.IsNil)
1175         }
1176         mtxt, err := fs.MarshalManifest(".")
1177         c.Assert(err, check.IsNil)
1178         var coll arvados.Collection
1179         err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
1180                 "collection": map[string]string{
1181                         "manifest_text": mtxt,
1182                 },
1183         })
1184         c.Assert(err, check.IsNil)
1185
1186         for _, trial := range trials {
1187                 u, _ := url.Parse("http://download.example.com/by_id/" + coll.UUID + "/" + trial.filename)
1188                 req := &http.Request{
1189                         Method:     "GET",
1190                         Host:       u.Host,
1191                         URL:        u,
1192                         RequestURI: u.RequestURI(),
1193                         Header: http.Header{
1194                                 "Authorization": {"Bearer " + client.AuthToken},
1195                         },
1196                 }
1197                 resp := httptest.NewRecorder()
1198                 s.handler.ServeHTTP(resp, req)
1199                 c.Check(resp.Code, check.Equals, http.StatusOK)
1200                 c.Check(resp.Header().Get("Content-Type"), check.Matches, trial.contentType)
1201                 c.Check(resp.Body.String(), check.Equals, trial.content)
1202         }
1203 }
1204
1205 func (s *IntegrationSuite) TestKeepClientBlockCache(c *check.C) {
1206         s.handler.Cluster.Collections.WebDAVCache.MaxBlockEntries = 42
1207         c.Check(keepclient.DefaultBlockCache.MaxBlocks, check.Not(check.Equals), 42)
1208         u := mustParseURL("http://keep-web.example/c=" + arvadostest.FooCollection + "/t=" + arvadostest.ActiveToken + "/foo")
1209         req := &http.Request{
1210                 Method:     "GET",
1211                 Host:       u.Host,
1212                 URL:        u,
1213                 RequestURI: u.RequestURI(),
1214         }
1215         resp := httptest.NewRecorder()
1216         s.handler.ServeHTTP(resp, req)
1217         c.Check(resp.Code, check.Equals, http.StatusOK)
1218         c.Check(keepclient.DefaultBlockCache.MaxBlocks, check.Equals, 42)
1219 }
1220
1221 // Writing to a collection shouldn't affect its entry in the
1222 // PDH-to-manifest cache.
1223 func (s *IntegrationSuite) TestCacheWriteCollectionSamePDH(c *check.C) {
1224         arv, err := arvadosclient.MakeArvadosClient()
1225         c.Assert(err, check.Equals, nil)
1226         arv.ApiToken = arvadostest.ActiveToken
1227
1228         u := mustParseURL("http://x.example/testfile")
1229         req := &http.Request{
1230                 Method:     "GET",
1231                 Host:       u.Host,
1232                 URL:        u,
1233                 RequestURI: u.RequestURI(),
1234                 Header:     http.Header{"Authorization": {"Bearer " + arv.ApiToken}},
1235         }
1236
1237         checkWithID := func(id string, status int) {
1238                 req.URL.Host = strings.Replace(id, "+", "-", -1) + ".example"
1239                 req.Host = req.URL.Host
1240                 resp := httptest.NewRecorder()
1241                 s.handler.ServeHTTP(resp, req)
1242                 c.Check(resp.Code, check.Equals, status)
1243         }
1244
1245         var colls [2]arvados.Collection
1246         for i := range colls {
1247                 err := arv.Create("collections",
1248                         map[string]interface{}{
1249                                 "ensure_unique_name": true,
1250                                 "collection": map[string]interface{}{
1251                                         "name": "test collection",
1252                                 },
1253                         }, &colls[i])
1254                 c.Assert(err, check.Equals, nil)
1255         }
1256
1257         // Populate cache with empty collection
1258         checkWithID(colls[0].PortableDataHash, http.StatusNotFound)
1259
1260         // write a file to colls[0]
1261         reqPut := *req
1262         reqPut.Method = "PUT"
1263         reqPut.URL.Host = colls[0].UUID + ".example"
1264         reqPut.Host = req.URL.Host
1265         reqPut.Body = ioutil.NopCloser(bytes.NewBufferString("testdata"))
1266         resp := httptest.NewRecorder()
1267         s.handler.ServeHTTP(resp, &reqPut)
1268         c.Check(resp.Code, check.Equals, http.StatusCreated)
1269
1270         // new file should not appear in colls[1]
1271         checkWithID(colls[1].PortableDataHash, http.StatusNotFound)
1272         checkWithID(colls[1].UUID, http.StatusNotFound)
1273
1274         checkWithID(colls[0].UUID, http.StatusOK)
1275 }
1276
1277 func copyHeader(h http.Header) http.Header {
1278         hc := http.Header{}
1279         for k, v := range h {
1280                 hc[k] = append([]string(nil), v...)
1281         }
1282         return hc
1283 }
1284
1285 func (s *IntegrationSuite) checkUploadDownloadRequest(c *check.C, req *http.Request,
1286         successCode int, direction string, perm bool, userUuid, collectionUuid, collectionPDH, filepath string) {
1287
1288         client := arvados.NewClientFromEnv()
1289         client.AuthToken = arvadostest.AdminToken
1290         var logentries arvados.LogList
1291         limit1 := 1
1292         err := client.RequestAndDecode(&logentries, "GET", "arvados/v1/logs", nil,
1293                 arvados.ResourceListParams{
1294                         Limit: &limit1,
1295                         Order: "created_at desc"})
1296         c.Check(err, check.IsNil)
1297         c.Check(logentries.Items, check.HasLen, 1)
1298         lastLogId := logentries.Items[0].ID
1299         c.Logf("lastLogId: %d", lastLogId)
1300
1301         var logbuf bytes.Buffer
1302         logger := logrus.New()
1303         logger.Out = &logbuf
1304         resp := httptest.NewRecorder()
1305         req = req.WithContext(ctxlog.Context(context.Background(), logger))
1306         s.handler.ServeHTTP(resp, req)
1307
1308         if perm {
1309                 c.Check(resp.Result().StatusCode, check.Equals, successCode)
1310                 c.Check(logbuf.String(), check.Matches, `(?ms).*msg="File `+direction+`".*`)
1311                 c.Check(logbuf.String(), check.Not(check.Matches), `(?ms).*level=error.*`)
1312
1313                 deadline := time.Now().Add(time.Second)
1314                 for {
1315                         c.Assert(time.Now().After(deadline), check.Equals, false, check.Commentf("timed out waiting for log entry"))
1316                         logentries = arvados.LogList{}
1317                         err = client.RequestAndDecode(&logentries, "GET", "arvados/v1/logs", nil,
1318                                 arvados.ResourceListParams{
1319                                         Filters: []arvados.Filter{
1320                                                 {Attr: "event_type", Operator: "=", Operand: "file_" + direction},
1321                                                 {Attr: "object_uuid", Operator: "=", Operand: userUuid},
1322                                         },
1323                                         Limit: &limit1,
1324                                         Order: "created_at desc",
1325                                 })
1326                         c.Assert(err, check.IsNil)
1327                         if len(logentries.Items) > 0 &&
1328                                 logentries.Items[0].ID > lastLogId &&
1329                                 logentries.Items[0].ObjectUUID == userUuid &&
1330                                 logentries.Items[0].Properties["collection_uuid"] == collectionUuid &&
1331                                 (collectionPDH == "" || logentries.Items[0].Properties["portable_data_hash"] == collectionPDH) &&
1332                                 logentries.Items[0].Properties["collection_file_path"] == filepath {
1333                                 break
1334                         }
1335                         c.Logf("logentries.Items: %+v", logentries.Items)
1336                         time.Sleep(50 * time.Millisecond)
1337                 }
1338         } else {
1339                 c.Check(resp.Result().StatusCode, check.Equals, http.StatusForbidden)
1340                 c.Check(logbuf.String(), check.Equals, "")
1341         }
1342 }
1343
1344 func (s *IntegrationSuite) TestDownloadLoggingPermission(c *check.C) {
1345         u := mustParseURL("http://" + arvadostest.FooCollection + ".keep-web.example/foo")
1346
1347         s.handler.Cluster.Collections.TrustAllContent = true
1348
1349         for _, adminperm := range []bool{true, false} {
1350                 for _, userperm := range []bool{true, false} {
1351                         s.handler.Cluster.Collections.WebDAVPermission.Admin.Download = adminperm
1352                         s.handler.Cluster.Collections.WebDAVPermission.User.Download = userperm
1353
1354                         // Test admin permission
1355                         req := &http.Request{
1356                                 Method:     "GET",
1357                                 Host:       u.Host,
1358                                 URL:        u,
1359                                 RequestURI: u.RequestURI(),
1360                                 Header: http.Header{
1361                                         "Authorization": {"Bearer " + arvadostest.AdminToken},
1362                                 },
1363                         }
1364                         s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", adminperm,
1365                                 arvadostest.AdminUserUUID, arvadostest.FooCollection, arvadostest.FooCollectionPDH, "foo")
1366
1367                         // Test user permission
1368                         req = &http.Request{
1369                                 Method:     "GET",
1370                                 Host:       u.Host,
1371                                 URL:        u,
1372                                 RequestURI: u.RequestURI(),
1373                                 Header: http.Header{
1374                                         "Authorization": {"Bearer " + arvadostest.ActiveToken},
1375                                 },
1376                         }
1377                         s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", userperm,
1378                                 arvadostest.ActiveUserUUID, arvadostest.FooCollection, arvadostest.FooCollectionPDH, "foo")
1379                 }
1380         }
1381
1382         s.handler.Cluster.Collections.WebDAVPermission.User.Download = true
1383
1384         for _, tryurl := range []string{"http://" + arvadostest.MultilevelCollection1 + ".keep-web.example/dir1/subdir/file1",
1385                 "http://keep-web/users/active/multilevel_collection_1/dir1/subdir/file1"} {
1386
1387                 u = mustParseURL(tryurl)
1388                 req := &http.Request{
1389                         Method:     "GET",
1390                         Host:       u.Host,
1391                         URL:        u,
1392                         RequestURI: u.RequestURI(),
1393                         Header: http.Header{
1394                                 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1395                         },
1396                 }
1397                 s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", true,
1398                         arvadostest.ActiveUserUUID, arvadostest.MultilevelCollection1, arvadostest.MultilevelCollection1PDH, "dir1/subdir/file1")
1399         }
1400
1401         u = mustParseURL("http://" + strings.Replace(arvadostest.FooCollectionPDH, "+", "-", 1) + ".keep-web.example/foo")
1402         req := &http.Request{
1403                 Method:     "GET",
1404                 Host:       u.Host,
1405                 URL:        u,
1406                 RequestURI: u.RequestURI(),
1407                 Header: http.Header{
1408                         "Authorization": {"Bearer " + arvadostest.ActiveToken},
1409                 },
1410         }
1411         s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", true,
1412                 arvadostest.ActiveUserUUID, "", arvadostest.FooCollectionPDH, "foo")
1413 }
1414
1415 func (s *IntegrationSuite) TestUploadLoggingPermission(c *check.C) {
1416         for _, adminperm := range []bool{true, false} {
1417                 for _, userperm := range []bool{true, false} {
1418
1419                         arv := arvados.NewClientFromEnv()
1420                         arv.AuthToken = arvadostest.ActiveToken
1421
1422                         var coll arvados.Collection
1423                         err := arv.RequestAndDecode(&coll,
1424                                 "POST",
1425                                 "/arvados/v1/collections",
1426                                 nil,
1427                                 map[string]interface{}{
1428                                         "ensure_unique_name": true,
1429                                         "collection": map[string]interface{}{
1430                                                 "name": "test collection",
1431                                         },
1432                                 })
1433                         c.Assert(err, check.Equals, nil)
1434
1435                         u := mustParseURL("http://" + coll.UUID + ".keep-web.example/bar")
1436
1437                         s.handler.Cluster.Collections.WebDAVPermission.Admin.Upload = adminperm
1438                         s.handler.Cluster.Collections.WebDAVPermission.User.Upload = userperm
1439
1440                         // Test admin permission
1441                         req := &http.Request{
1442                                 Method:     "PUT",
1443                                 Host:       u.Host,
1444                                 URL:        u,
1445                                 RequestURI: u.RequestURI(),
1446                                 Header: http.Header{
1447                                         "Authorization": {"Bearer " + arvadostest.AdminToken},
1448                                 },
1449                                 Body: io.NopCloser(bytes.NewReader([]byte("bar"))),
1450                         }
1451                         s.checkUploadDownloadRequest(c, req, http.StatusCreated, "upload", adminperm,
1452                                 arvadostest.AdminUserUUID, coll.UUID, "", "bar")
1453
1454                         // Test user permission
1455                         req = &http.Request{
1456                                 Method:     "PUT",
1457                                 Host:       u.Host,
1458                                 URL:        u,
1459                                 RequestURI: u.RequestURI(),
1460                                 Header: http.Header{
1461                                         "Authorization": {"Bearer " + arvadostest.ActiveToken},
1462                                 },
1463                                 Body: io.NopCloser(bytes.NewReader([]byte("bar"))),
1464                         }
1465                         s.checkUploadDownloadRequest(c, req, http.StatusCreated, "upload", userperm,
1466                                 arvadostest.ActiveUserUUID, coll.UUID, "", "bar")
1467                 }
1468         }
1469 }