1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
36 var _ = check.Suite(&UnitSuite{})
39 arvados.DebugLocksPanicMode = true
42 type UnitSuite struct {
43 cluster *arvados.Cluster
47 func (s *UnitSuite) SetUpTest(c *check.C) {
48 logger := ctxlog.TestLogger(c)
49 ldr := config.NewLoader(bytes.NewBufferString("Clusters: {zzzzz: {}}"), logger)
51 cfg, err := ldr.Load()
52 c.Assert(err, check.IsNil)
53 cc, err := cfg.GetCluster("")
54 c.Assert(err, check.IsNil)
61 registry: prometheus.NewRegistry(),
66 func (s *UnitSuite) TestCORSPreflight(c *check.C) {
68 u := mustParseURL("http://keep-web.example/c=" + arvadostest.FooCollection + "/foo")
73 RequestURI: u.RequestURI(),
75 "Origin": {"https://workbench.example"},
76 "Access-Control-Request-Method": {"POST"},
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")
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)
97 func (s *UnitSuite) TestWebdavPrefixAndSource(c *check.C) {
98 for _, trial := range []struct {
126 path: "/prefix/dir1/foo",
132 path: "/prefix/dir1/foo",
138 path: "/prefix/dir1/foo",
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,
187 RequestURI: u.RequestURI(),
189 "Authorization": {"Bearer " + arvadostest.ActiveTokenV2},
190 "X-Webdav-Prefix": {trial.prefix},
191 "X-Webdav-Source": {trial.source},
193 Body: ioutil.NopCloser(bytes.NewReader(nil)),
196 resp := httptest.NewRecorder()
197 s.handler.ServeHTTP(resp, req)
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)
206 c.Check(resp.Code, check.Equals, http.StatusOK)
211 func (s *UnitSuite) TestEmptyResponse(c *check.C) {
212 for _, trial := range []struct {
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.*`},
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".*`},
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)
240 u := mustParseURL("http://" + arvadostest.FooCollection + ".keep-web.example/foo")
241 req := &http.Request{
245 RequestURI: u.RequestURI(),
247 "Authorization": {"Bearer " + arvadostest.ActiveToken},
250 if trial.sendIMSHeader {
251 req.Header.Set("If-Modified-Since", strings.Replace(time.Now().UTC().Format(time.RFC1123), "UTC", "GMT", -1))
254 var logbuf bytes.Buffer
255 logger := logrus.New()
257 req = req.WithContext(ctxlog.Context(context.Background(), logger))
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, "")
264 c.Log(logbuf.String())
265 c.Check(logbuf.String(), check.Matches, trial.logRegexp)
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",
281 u := mustParseURL(trial)
282 req := &http.Request{
286 RequestURI: u.RequestURI(),
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)
295 func mustParseURL(s string) *url.URL {
296 r, err := url.Parse(s)
298 panic("parse URL: " + s)
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",
308 resp := httptest.NewRecorder()
309 u := mustParseURL(testURL)
310 req := &http.Request{
313 RequestURI: u.RequestURI(),
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")
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
327 func (s *IntegrationSuite) TestVhostViaAuthzHeaderOAuth2(c *check.C) {
328 s.doVhostRequests(c, authzViaAuthzHeaderOAuth2)
330 func authzViaAuthzHeaderOAuth2(r *http.Request, tok string) int {
331 r.Header.Add("Authorization", "Bearer "+tok)
332 return http.StatusUnauthorized
334 func (s *IntegrationSuite) TestVhostViaAuthzHeaderBearer(c *check.C) {
335 s.doVhostRequests(c, authzViaAuthzHeaderBearer)
337 func authzViaAuthzHeaderBearer(r *http.Request, tok string) int {
338 r.Header.Add("Authorization", "Bearer "+tok)
339 return http.StatusUnauthorized
342 func (s *IntegrationSuite) TestVhostViaCookieValue(c *check.C) {
343 s.doVhostRequests(c, authzViaCookieValue)
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)),
350 return http.StatusUnauthorized
353 func (s *IntegrationSuite) TestVhostViaPath(c *check.C) {
354 s.doVhostRequests(c, authzViaPath)
356 func authzViaPath(r *http.Request, tok string) int {
357 r.URL.Path = "/t=" + tok + r.URL.Path
358 return http.StatusNotFound
361 func (s *IntegrationSuite) TestVhostViaQueryString(c *check.C) {
362 s.doVhostRequests(c, authzViaQueryString)
364 func authzViaQueryString(r *http.Request, tok string) int {
365 r.URL.RawQuery = "api_token=" + tok
366 return http.StatusUnauthorized
369 func (s *IntegrationSuite) TestVhostViaPOST(c *check.C) {
370 s.doVhostRequests(c, authzViaPOST)
372 func authzViaPOST(r *http.Request, tok string) int {
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
380 func (s *IntegrationSuite) TestVhostViaXHRPOST(c *check.C) {
381 s.doVhostRequests(c, authzViaPOST)
383 func authzViaXHRPOST(r *http.Request, tok string) int {
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(
390 "disposition": {"attachment"},
392 return http.StatusUnauthorized
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",
406 c.Log("doRequests: ", hostPath)
407 s.doVhostRequestsWithHostPath(c, authz, hostPath)
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,
419 u := mustParseURL("http://" + hostPath)
420 req := &http.Request{
424 RequestURI: u.RequestURI(),
425 Header: http.Header{},
427 failCode := authz(req, tok)
428 req, resp := s.doReq(req)
429 code, body := resp.Code, resp.Body.String()
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=.+`)
436 if tok == arvadostest.ActiveToken {
437 c.Check(code, check.Equals, http.StatusOK)
438 c.Check(body, check.Equals, "foo")
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)
447 // Invalid token can ask to retry
448 // depending on the authz method.
449 c.Check(code, check.Equals, failCode)
452 c.Check(body, check.Equals, notFoundMessage+"\n")
454 c.Check(body, check.Equals, unauthorizedMessage+"\n")
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{
469 RequestURI: u.RequestURI(),
470 Header: http.Header{"Authorization": []string{"Bearer " + arvadostest.ActiveToken}},
472 req, resp := s.doReq(req)
473 code, _ := resp.Code, resp.Body.String()
476 c.Check(code, check.Equals, 401)
478 c.Check(code, check.Equals, 200)
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 {
490 } else if token != "" {
491 panic("must not pass both token and hdr")
493 return s.doReq(&http.Request{
497 RequestURI: u.RequestURI(),
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 {
508 cookies := (&http.Response{Header: resp.Header()}).Cookies()
509 u, _ := req.URL.Parse(resp.Header().Get("Location"))
514 RequestURI: u.RequestURI(),
515 Header: http.Header{},
517 for _, c := range cookies {
523 func (s *IntegrationSuite) TestVhostRedirectQueryTokenToCookie(c *check.C) {
524 s.testVhostRedirectTokenToCookie(c, "GET",
525 arvadostest.FooCollection+".example.com/foo",
526 "?api_token="+arvadostest.ActiveToken,
534 func (s *IntegrationSuite) TestSingleOriginSecretLink(c *check.C) {
535 s.testVhostRedirectTokenToCookie(c, "GET",
536 "example.com/c="+arvadostest.FooCollection+"/t="+arvadostest.ActiveToken+"/foo",
545 func (s *IntegrationSuite) TestCollectionSharingToken(c *check.C) {
546 s.testVhostRedirectTokenToCookie(c, "GET",
547 "example.com/c="+arvadostest.FooFileCollectionUUID+"/t="+arvadostest.FooFileCollectionSharingToken+"/foo",
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",
561 regexp.QuoteMeta(notFoundMessage+"\n"),
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",
574 regexp.QuoteMeta(notFoundMessage+"\n"),
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) {
583 resp := s.testVhostRedirectTokenToCookie(c, "GET",
584 arvadostest.FooCollection+".example.com/foo",
585 "?api_token=thisisabogustoken",
586 http.Header{"Sec-Fetch-Mode": {"navigate"}},
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, "")
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"}},
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")
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"}},
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")
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"}},
636 http.StatusUnauthorized,
637 regexp.QuoteMeta(unauthorizedMessage+"\n"),
639 s.testVhostRedirectTokenToCookie(c, "GET",
640 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host+"/c="+arvadostest.FooCollection+"/foo",
641 "?api_token=thisisabogustoken",
644 http.StatusUnauthorized,
645 regexp.QuoteMeta(unauthorizedMessage+"\n"),
649 func (s *IntegrationSuite) TestVhostRedirectWithNoCache(c *check.C) {
650 resp := s.testVhostRedirectTokenToCookie(c, "GET",
651 arvadostest.FooCollection+".example.com/foo",
652 "?api_token=thisisabogustoken",
654 "Sec-Fetch-Mode": {"navigate"},
655 "Cache-Control": {"no-cache"},
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, "")
669 func (s *IntegrationSuite) TestNoTokenWorkbench2LoginFlow(c *check.C) {
670 for _, trial := range []struct {
675 {cacheControl: "no-cache"},
677 {anonToken: true, cacheControl: "no-cache"},
679 c.Logf("trial: %+v", trial)
682 s.handler.Cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
684 s.handler.Cluster.Users.AnonymousUserToken = ""
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)
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, "")
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,
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"),
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,
727 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
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,
740 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
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,
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,
762 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
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,
777 func (s *IntegrationSuite) TestVhostRedirectQueryTokenAttachmentOnlyHost(c *check.C) {
778 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "example.com:1234"
780 s.testVhostRedirectTokenToCookie(c, "GET",
781 "example.com/c="+arvadostest.FooCollection+"/foo",
782 "?api_token="+arvadostest.ActiveToken,
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"),
789 resp := s.testVhostRedirectTokenToCookie(c, "GET",
790 "example.com:1234/c="+arvadostest.FooCollection+"/foo",
791 "?api_token="+arvadostest.ActiveToken,
797 c.Check(resp.Header().Get("Content-Disposition"), check.Equals, "attachment")
800 func (s *IntegrationSuite) TestVhostRedirectPOSTFormTokenToCookie(c *check.C) {
801 s.testVhostRedirectTokenToCookie(c, "POST",
802 arvadostest.FooCollection+".example.com/foo",
804 http.Header{"Content-Type": {"application/x-www-form-urlencoded"}},
805 url.Values{"api_token": {arvadostest.ActiveToken}}.Encode(),
811 func (s *IntegrationSuite) TestVhostRedirectPOSTFormTokenToCookie404(c *check.C) {
812 s.testVhostRedirectTokenToCookie(c, "POST",
813 arvadostest.FooCollection+".example.com/foo",
815 http.Header{"Content-Type": {"application/x-www-form-urlencoded"}},
816 url.Values{"api_token": {arvadostest.SpectatorToken}}.Encode(),
818 regexp.QuoteMeta(notFoundMessage+"\n"),
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",
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",
841 http.StatusUnauthorized,
842 "Authorization tokens are not accepted here: .*\n",
846 func (s *IntegrationSuite) TestSpecialCharsInPath(c *check.C) {
847 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
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)
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,
864 c.Assert(err, check.IsNil)
866 u, _ := url.Parse("http://download.example.com/c=" + coll.UUID + "/")
867 req := &http.Request{
871 RequestURI: u.RequestURI(),
873 "Authorization": {"Bearer " + client.AuthToken},
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:\\"odd' path chars.*`)
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)
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)
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,
904 "owner_uuid": arvadostest.AProjectUUID,
907 c.Assert(err, check.IsNil)
908 defer arv.RequestAndDecode(&coll, "DELETE", "arvados/v1/collections/"+coll.UUID, nil, nil)
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.*`,
915 u, _ := url.Parse(tryURL)
916 req := &http.Request{
920 RequestURI: u.RequestURI(),
922 "Authorization": {"Bearer " + client.AuthToken},
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)
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
937 func (s *IntegrationSuite) TestXHRNoRedirect(c *check.C) {
938 u, _ := url.Parse("http://example.com/c=" + arvadostest.FooCollection + "/foo")
939 req := &http.Request{
943 RequestURI: u.RequestURI(),
945 "Origin": {"https://origin.example"},
946 "Content-Type": {"application/x-www-form-urlencoded"},
948 Body: ioutil.NopCloser(strings.NewReader(url.Values{
949 "api_token": {arvadostest.ActiveToken},
950 "disposition": {"attachment"},
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, "*")
959 // GET + Origin header is representative of both AJAX GET
960 // requests and inline images via <IMG crossorigin="anonymous"
962 u.RawQuery = "api_token=" + url.QueryEscape(arvadostest.ActiveTokenV2)
967 RequestURI: u.RequestURI(),
969 "Origin": {"https://origin.example"},
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, "*")
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{}
983 u, _ := url.Parse(`http://` + hostPath + queryString)
984 c.Logf("requesting %s", u)
985 req := &http.Request{
989 RequestURI: u.RequestURI(),
991 Body: ioutil.NopCloser(strings.NewReader(reqBody)),
994 resp := httptest.NewRecorder()
996 c.Check(resp.Code, check.Equals, expectStatus)
997 c.Check(resp.Body.String(), check.Matches, matchRespBody)
1000 s.handler.ServeHTTP(resp, req)
1001 if resp.Code != http.StatusSeeOther {
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()
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{
1015 RequestURI: u.RequestURI(),
1018 for _, c := range cookies {
1022 resp = httptest.NewRecorder()
1023 s.handler.ServeHTTP(resp, req)
1025 if resp.Code != http.StatusSeeOther {
1026 c.Check(resp.Header().Get("Location"), check.Equals, "")
1031 func (s *IntegrationSuite) TestDirectoryListingWithAnonymousToken(c *check.C) {
1032 s.handler.Cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
1033 s.testDirectoryListing(c)
1036 func (s *IntegrationSuite) TestDirectoryListingWithNoAnonymousToken(c *check.C) {
1037 s.handler.Cluster.Users.AnonymousUserToken = ""
1038 s.testDirectoryListing(c)
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},
1046 for _, trial := range []struct {
1054 uri: strings.Replace(arvadostest.FooAndBarFilesInDirPDH, "+", "-", -1) + ".example.com/",
1056 expect: []string{"dir1/foo", "dir1/bar"},
1060 uri: strings.Replace(arvadostest.FooAndBarFilesInDirPDH, "+", "-", -1) + ".example.com/dir1/",
1062 expect: []string{"foo", "bar"},
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 + "/",
1074 uri: "download.example.com/users/active/foo_file_in_dir/",
1076 expect: []string{"dir1/"},
1080 uri: "download.example.com/users/active/foo_file_in_dir/dir1/",
1082 expect: []string{"bar"},
1086 uri: "download.example.com/",
1088 expect: []string{"users/"},
1092 uri: "download.example.com/users",
1094 redirect: "/users/",
1095 expect: []string{"active/"},
1099 uri: "download.example.com/users/",
1101 expect: []string{"active/"},
1105 uri: "download.example.com/users/active",
1107 redirect: "/users/active/",
1108 expect: []string{"foo_file_in_dir/"},
1112 uri: "download.example.com/users/active/",
1114 expect: []string{"foo_file_in_dir/"},
1118 uri: "collections.example.com/collections/download/" + arvadostest.FooAndBarFilesInDirUUID + "/" + arvadostest.ActiveToken + "/",
1120 expect: []string{"dir1/foo", "dir1/bar"},
1124 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/t=" + arvadostest.ActiveToken + "/",
1126 expect: []string{"dir1/foo", "dir1/bar"},
1130 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/t=" + arvadostest.ActiveToken,
1132 expect: []string{"dir1/foo", "dir1/bar"},
1136 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID,
1138 expect: []string{"dir1/foo", "dir1/bar"},
1142 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/dir1",
1144 redirect: "/c=" + arvadostest.FooAndBarFilesInDirUUID + "/dir1/",
1145 expect: []string{"foo", "bar"},
1149 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/_/dir1/",
1151 expect: []string{"foo", "bar"},
1155 uri: arvadostest.FooAndBarFilesInDirUUID + ".example.com/dir1?api_token=" + arvadostest.ActiveToken,
1158 expect: []string{"foo", "bar"},
1162 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/theperthcountyconspiracydoesnotexist/",
1167 uri: "download.example.com/c=" + arvadostest.WazVersion1Collection,
1169 expect: []string{"waz"},
1173 uri: "download.example.com/by_id/" + arvadostest.WazVersion1Collection,
1175 expect: []string{"waz"},
1179 comment := check.Commentf("HTML: %q => %q", trial.uri, trial.expect)
1180 resp := httptest.NewRecorder()
1181 u := mustParseURL("//" + trial.uri)
1182 req := &http.Request{
1186 RequestURI: u.RequestURI(),
1187 Header: copyHeader(trial.header),
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{
1197 RequestURI: u.RequestURI(),
1198 Header: copyHeader(trial.header),
1200 cookies = append(cookies, (&http.Response{Header: resp.Header()}).Cookies()...)
1201 for _, c := range cookies {
1204 resp = httptest.NewRecorder()
1205 s.handler.ServeHTTP(resp, req)
1207 if trial.redirect != "" {
1208 c.Check(req.URL.Path, check.Equals, trial.redirect, comment)
1210 if trial.expect == nil {
1211 c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
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)
1217 c.Check(resp.Body.String(), check.Matches, `(?ms).*--cut-dirs=`+fmt.Sprintf("%d", trial.cutDirs)+` .*`, comment)
1220 comment = check.Commentf("WebDAV: %q => %q", trial.uri, trial.expect)
1221 req = &http.Request{
1225 RequestURI: u.RequestURI(),
1226 Header: copyHeader(trial.header),
1227 Body: ioutil.NopCloser(&bytes.Buffer{}),
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)
1234 c.Check(resp.Code, check.Equals, http.StatusOK, comment)
1237 req = &http.Request{
1241 RequestURI: u.RequestURI(),
1242 Header: copyHeader(trial.header),
1243 Body: ioutil.NopCloser(&bytes.Buffer{}),
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)
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) + "/"
1255 e = filepath.Join(u.Path, e)
1257 c.Check(resp.Body.String(), check.Matches, `(?ms).*<D:href>`+e+`</D:href>.*`, comment)
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",
1272 "ensure_unique_name": true,
1274 c.Assert(err, check.IsNil)
1275 defer arv.RequestAndDecode(&newCollection, "DELETE", "arvados/v1/collections/"+newCollection.UUID, nil, nil)
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{
1285 RequestURI: u.RequestURI(),
1286 Header: http.Header{
1287 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1290 resp := httptest.NewRecorder()
1291 s.handler.ServeHTTP(resp, req)
1292 c.Check(resp.Code, check.Equals, http.StatusNoContent)
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)
1300 c.Check(updated.ManifestText, check.Equals, "")
1303 func (s *IntegrationSuite) TestFileContentType(c *check.C) {
1304 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
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)
1313 fs, err := (&arvados.Collection{}).FileSystem(client, kc)
1314 c.Assert(err, check.IsNil)
1316 trials := []struct {
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
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)
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,
1342 c.Assert(err, check.IsNil)
1344 for _, trial := range trials {
1345 u, _ := url.Parse("http://download.example.com/by_id/" + coll.UUID + "/" + trial.filename)
1346 req := &http.Request{
1350 RequestURI: u.RequestURI(),
1351 Header: http.Header{
1352 "Authorization": {"Bearer " + client.AuthToken},
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)
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{
1371 RequestURI: u.RequestURI(),
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)
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
1386 u := mustParseURL("http://x.example/testfile")
1387 req := &http.Request{
1391 RequestURI: u.RequestURI(),
1392 Header: http.Header{"Authorization": {"Bearer " + arv.ApiToken}},
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)
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",
1412 c.Assert(err, check.Equals, nil)
1415 // Populate cache with empty collection
1416 checkWithID(colls[0].PortableDataHash, http.StatusNotFound)
1418 // write a file to colls[0]
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)
1428 // new file should not appear in colls[1]
1429 checkWithID(colls[1].PortableDataHash, http.StatusNotFound)
1430 checkWithID(colls[1].UUID, http.StatusNotFound)
1432 checkWithID(colls[0].UUID, http.StatusOK)
1435 func copyHeader(h http.Header) http.Header {
1437 for k, v := range h {
1438 hc[k] = append([]string(nil), v...)
1443 func (s *IntegrationSuite) checkUploadDownloadRequest(c *check.C, req *http.Request,
1444 successCode int, direction string, perm bool, userUuid, collectionUuid, collectionPDH, filepath string) {
1446 client := arvados.NewClientFromEnv()
1447 client.AuthToken = arvadostest.AdminToken
1448 var logentries arvados.LogList
1450 err := client.RequestAndDecode(&logentries, "GET", "arvados/v1/logs", nil,
1451 arvados.ResourceListParams{
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)
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)
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.*`)
1471 deadline := time.Now().Add(time.Second)
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},
1482 Order: "created_at desc",
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 {
1493 c.Logf("logentries.Items: %+v", logentries.Items)
1494 time.Sleep(50 * time.Millisecond)
1497 c.Check(resp.Result().StatusCode, check.Equals, http.StatusForbidden)
1498 c.Check(logbuf.String(), check.Equals, "")
1502 func (s *IntegrationSuite) TestDownloadLoggingPermission(c *check.C) {
1503 u := mustParseURL("http://" + arvadostest.FooCollection + ".keep-web.example/foo")
1505 s.handler.Cluster.Collections.TrustAllContent = true
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
1512 // Test admin permission
1513 req := &http.Request{
1517 RequestURI: u.RequestURI(),
1518 Header: http.Header{
1519 "Authorization": {"Bearer " + arvadostest.AdminToken},
1522 s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", adminperm,
1523 arvadostest.AdminUserUUID, arvadostest.FooCollection, arvadostest.FooCollectionPDH, "foo")
1525 // Test user permission
1526 req = &http.Request{
1530 RequestURI: u.RequestURI(),
1531 Header: http.Header{
1532 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1535 s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", userperm,
1536 arvadostest.ActiveUserUUID, arvadostest.FooCollection, arvadostest.FooCollectionPDH, "foo")
1540 s.handler.Cluster.Collections.WebDAVPermission.User.Download = true
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"} {
1545 u = mustParseURL(tryurl)
1546 req := &http.Request{
1550 RequestURI: u.RequestURI(),
1551 Header: http.Header{
1552 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1555 s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", true,
1556 arvadostest.ActiveUserUUID, arvadostest.MultilevelCollection1, arvadostest.MultilevelCollection1PDH, "dir1/subdir/file1")
1559 u = mustParseURL("http://" + strings.Replace(arvadostest.FooCollectionPDH, "+", "-", 1) + ".keep-web.example/foo")
1560 req := &http.Request{
1564 RequestURI: u.RequestURI(),
1565 Header: http.Header{
1566 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1569 s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", true,
1570 arvadostest.ActiveUserUUID, "", arvadostest.FooCollectionPDH, "foo")
1573 func (s *IntegrationSuite) TestUploadLoggingPermission(c *check.C) {
1574 for _, adminperm := range []bool{true, false} {
1575 for _, userperm := range []bool{true, false} {
1577 arv := arvados.NewClientFromEnv()
1578 arv.AuthToken = arvadostest.ActiveToken
1580 var coll arvados.Collection
1581 err := arv.RequestAndDecode(&coll,
1583 "/arvados/v1/collections",
1585 map[string]interface{}{
1586 "ensure_unique_name": true,
1587 "collection": map[string]interface{}{
1588 "name": "test collection",
1591 c.Assert(err, check.Equals, nil)
1593 u := mustParseURL("http://" + coll.UUID + ".keep-web.example/bar")
1595 s.handler.Cluster.Collections.WebDAVPermission.Admin.Upload = adminperm
1596 s.handler.Cluster.Collections.WebDAVPermission.User.Upload = userperm
1598 // Test admin permission
1599 req := &http.Request{
1603 RequestURI: u.RequestURI(),
1604 Header: http.Header{
1605 "Authorization": {"Bearer " + arvadostest.AdminToken},
1607 Body: io.NopCloser(bytes.NewReader([]byte("bar"))),
1609 s.checkUploadDownloadRequest(c, req, http.StatusCreated, "upload", adminperm,
1610 arvadostest.AdminUserUUID, coll.UUID, "", "bar")
1612 // Test user permission
1613 req = &http.Request{
1617 RequestURI: u.RequestURI(),
1618 Header: http.Header{
1619 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1621 Body: io.NopCloser(bytes.NewReader([]byte("bar"))),
1623 s.checkUploadDownloadRequest(c, req, http.StatusCreated, "upload", userperm,
1624 arvadostest.ActiveUserUUID, coll.UUID, "", "bar")
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
1637 for n := 2; n < 16 && !c.Failed(); n = n * 2 {
1638 c.Logf("%s: n=%d", c.TestName(), n)
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)
1645 var wg sync.WaitGroup
1646 for i := 0; i < n && !c.Failed(); i++ {
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++ {
1663 content := fmt.Sprintf("i=%d/j=%d", i, j)
1664 u := mustParseURL("http://" + coll.UUID + ".collections.example.com/" + content)
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)
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)
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)