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