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", "OAuth2 "+tok)
332 return http.StatusUnauthorized
335 func (s *IntegrationSuite) TestVhostViaAuthzHeaderBearer(c *check.C) {
336 s.doVhostRequests(c, authzViaAuthzHeaderBearer)
338 func authzViaAuthzHeaderBearer(r *http.Request, tok string) int {
339 r.Header.Add("Authorization", "Bearer "+tok)
340 return http.StatusUnauthorized
343 func (s *IntegrationSuite) TestVhostViaCookieValue(c *check.C) {
344 s.doVhostRequests(c, authzViaCookieValue)
346 func authzViaCookieValue(r *http.Request, tok string) int {
347 r.AddCookie(&http.Cookie{
348 Name: "arvados_api_token",
349 Value: auth.EncodeTokenCookie([]byte(tok)),
351 return http.StatusUnauthorized
354 func (s *IntegrationSuite) TestVhostViaHTTPBasicAuth(c *check.C) {
355 s.doVhostRequests(c, authzViaHTTPBasicAuth)
357 func authzViaHTTPBasicAuth(r *http.Request, tok string) int {
358 r.AddCookie(&http.Cookie{
359 Name: "arvados_api_token",
360 Value: auth.EncodeTokenCookie([]byte(tok)),
362 return http.StatusUnauthorized
365 func (s *IntegrationSuite) TestVhostViaHTTPBasicAuthWithExtraSpaceChars(c *check.C) {
366 s.doVhostRequests(c, func(r *http.Request, tok string) int {
367 r.AddCookie(&http.Cookie{
368 Name: "arvados_api_token",
369 Value: auth.EncodeTokenCookie([]byte(" " + tok + "\n")),
371 return http.StatusUnauthorized
375 func (s *IntegrationSuite) TestVhostViaPath(c *check.C) {
376 s.doVhostRequests(c, authzViaPath)
378 func authzViaPath(r *http.Request, tok string) int {
379 r.URL.Path = "/t=" + tok + r.URL.Path
380 return http.StatusNotFound
383 func (s *IntegrationSuite) TestVhostViaQueryString(c *check.C) {
384 s.doVhostRequests(c, authzViaQueryString)
386 func authzViaQueryString(r *http.Request, tok string) int {
387 r.URL.RawQuery = "api_token=" + tok
388 return http.StatusUnauthorized
391 func (s *IntegrationSuite) TestVhostViaPOST(c *check.C) {
392 s.doVhostRequests(c, authzViaPOST)
394 func authzViaPOST(r *http.Request, tok string) int {
396 r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
397 r.Body = ioutil.NopCloser(strings.NewReader(
398 url.Values{"api_token": {tok}}.Encode()))
399 return http.StatusUnauthorized
402 func (s *IntegrationSuite) TestVhostViaXHRPOST(c *check.C) {
403 s.doVhostRequests(c, authzViaPOST)
405 func authzViaXHRPOST(r *http.Request, tok string) int {
407 r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
408 r.Header.Add("Origin", "https://origin.example")
409 r.Body = ioutil.NopCloser(strings.NewReader(
412 "disposition": {"attachment"},
414 return http.StatusUnauthorized
417 // Try some combinations of {url, token} using the given authorization
418 // mechanism, and verify the result is correct.
419 func (s *IntegrationSuite) doVhostRequests(c *check.C, authz authorizer) {
420 for _, hostPath := range []string{
421 arvadostest.FooCollection + ".example.com/foo",
422 arvadostest.FooCollection + "--collections.example.com/foo",
423 arvadostest.FooCollection + "--collections.example.com/_/foo",
424 arvadostest.FooCollectionPDH + ".example.com/foo",
425 strings.Replace(arvadostest.FooCollectionPDH, "+", "-", -1) + "--collections.example.com/foo",
426 arvadostest.FooBarDirCollection + ".example.com/dir1/foo",
428 c.Log("doRequests: ", hostPath)
429 s.doVhostRequestsWithHostPath(c, authz, hostPath)
433 func (s *IntegrationSuite) doVhostRequestsWithHostPath(c *check.C, authz authorizer, hostPath string) {
434 for _, tok := range []string{
435 arvadostest.ActiveToken,
436 arvadostest.ActiveToken[:15],
437 arvadostest.SpectatorToken,
441 u := mustParseURL("http://" + hostPath)
442 req := &http.Request{
446 RequestURI: u.RequestURI(),
447 Header: http.Header{},
449 failCode := authz(req, tok)
450 req, resp := s.doReq(req)
451 code, body := resp.Code, resp.Body.String()
453 // If the initial request had a (non-empty) token
454 // showing in the query string, we should have been
455 // redirected in order to hide it in a cookie.
456 c.Check(req.URL.String(), check.Not(check.Matches), `.*api_token=.+`)
458 if tok == arvadostest.ActiveToken {
459 c.Check(code, check.Equals, http.StatusOK)
460 c.Check(body, check.Equals, "foo")
462 c.Check(code >= 400, check.Equals, true)
463 c.Check(code < 500, check.Equals, true)
464 if tok == arvadostest.SpectatorToken {
465 // Valid token never offers to retry
466 // with different credentials.
467 c.Check(code, check.Equals, http.StatusNotFound)
469 // Invalid token can ask to retry
470 // depending on the authz method.
471 c.Check(code, check.Equals, failCode)
474 c.Check(body, check.Equals, notFoundMessage+"\n")
476 c.Check(body, check.Equals, unauthorizedMessage+"\n")
482 func (s *IntegrationSuite) TestVhostPortMatch(c *check.C) {
483 for _, host := range []string{"download.example.com", "DOWNLOAD.EXAMPLE.COM"} {
484 for _, port := range []string{"80", "443", "8000"} {
485 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = fmt.Sprintf("download.example.com:%v", port)
486 u := mustParseURL(fmt.Sprintf("http://%v/by_id/%v/foo", host, arvadostest.FooCollection))
487 req := &http.Request{
491 RequestURI: u.RequestURI(),
492 Header: http.Header{"Authorization": []string{"Bearer " + arvadostest.ActiveToken}},
494 req, resp := s.doReq(req)
495 code, _ := resp.Code, resp.Body.String()
498 c.Check(code, check.Equals, 401)
500 c.Check(code, check.Equals, 200)
506 func (s *IntegrationSuite) do(method string, urlstring string, token string, hdr http.Header) (*http.Request, *httptest.ResponseRecorder) {
507 u := mustParseURL(urlstring)
508 if hdr == nil && token != "" {
509 hdr = http.Header{"Authorization": {"Bearer " + token}}
510 } else if hdr == nil {
512 } else if token != "" {
513 panic("must not pass both token and hdr")
515 return s.doReq(&http.Request{
519 RequestURI: u.RequestURI(),
524 func (s *IntegrationSuite) doReq(req *http.Request) (*http.Request, *httptest.ResponseRecorder) {
525 resp := httptest.NewRecorder()
526 s.handler.ServeHTTP(resp, req)
527 if resp.Code != http.StatusSeeOther {
530 cookies := (&http.Response{Header: resp.Header()}).Cookies()
531 u, _ := req.URL.Parse(resp.Header().Get("Location"))
536 RequestURI: u.RequestURI(),
537 Header: http.Header{},
539 for _, c := range cookies {
545 func (s *IntegrationSuite) TestVhostRedirectQueryTokenToCookie(c *check.C) {
546 s.testVhostRedirectTokenToCookie(c, "GET",
547 arvadostest.FooCollection+".example.com/foo",
548 "?api_token="+arvadostest.ActiveToken,
556 func (s *IntegrationSuite) TestSingleOriginSecretLink(c *check.C) {
557 s.testVhostRedirectTokenToCookie(c, "GET",
558 "example.com/c="+arvadostest.FooCollection+"/t="+arvadostest.ActiveToken+"/foo",
567 func (s *IntegrationSuite) TestCollectionSharingToken(c *check.C) {
568 s.testVhostRedirectTokenToCookie(c, "GET",
569 "example.com/c="+arvadostest.FooFileCollectionUUID+"/t="+arvadostest.FooFileCollectionSharingToken+"/foo",
576 // Same valid sharing token, but requesting a different collection
577 s.testVhostRedirectTokenToCookie(c, "GET",
578 "example.com/c="+arvadostest.FooCollection+"/t="+arvadostest.FooFileCollectionSharingToken+"/foo",
583 regexp.QuoteMeta(notFoundMessage+"\n"),
587 // Bad token in URL is 404 Not Found because it doesn't make sense to
588 // retry the same URL with different authorization.
589 func (s *IntegrationSuite) TestSingleOriginSecretLinkBadToken(c *check.C) {
590 s.testVhostRedirectTokenToCookie(c, "GET",
591 "example.com/c="+arvadostest.FooCollection+"/t=bogus/foo",
596 regexp.QuoteMeta(notFoundMessage+"\n"),
600 // Bad token in a cookie (even if it got there via our own
601 // query-string-to-cookie redirect) is, in principle, retryable via
602 // wb2-login-and-redirect flow.
603 func (s *IntegrationSuite) TestVhostRedirectQueryTokenToBogusCookie(c *check.C) {
605 resp := s.testVhostRedirectTokenToCookie(c, "GET",
606 arvadostest.FooCollection+".example.com/foo",
607 "?api_token=thisisabogustoken",
608 http.Header{"Sec-Fetch-Mode": {"navigate"}},
613 u, err := url.Parse(resp.Header().Get("Location"))
614 c.Assert(err, check.IsNil)
615 c.Logf("redirected to %s", u)
616 c.Check(u.Host, check.Equals, s.handler.Cluster.Services.Workbench2.ExternalURL.Host)
617 c.Check(u.Query().Get("redirectToPreview"), check.Equals, "/c="+arvadostest.FooCollection+"/foo")
618 c.Check(u.Query().Get("redirectToDownload"), check.Equals, "")
620 // Download/attachment indicated by ?disposition=attachment
621 resp = s.testVhostRedirectTokenToCookie(c, "GET",
622 arvadostest.FooCollection+".example.com/foo",
623 "?api_token=thisisabogustoken&disposition=attachment",
624 http.Header{"Sec-Fetch-Mode": {"navigate"}},
629 u, err = url.Parse(resp.Header().Get("Location"))
630 c.Assert(err, check.IsNil)
631 c.Logf("redirected to %s", u)
632 c.Check(u.Host, check.Equals, s.handler.Cluster.Services.Workbench2.ExternalURL.Host)
633 c.Check(u.Query().Get("redirectToPreview"), check.Equals, "")
634 c.Check(u.Query().Get("redirectToDownload"), check.Equals, "/c="+arvadostest.FooCollection+"/foo")
636 // Download/attachment indicated by vhost
637 resp = s.testVhostRedirectTokenToCookie(c, "GET",
638 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host+"/c="+arvadostest.FooCollection+"/foo",
639 "?api_token=thisisabogustoken",
640 http.Header{"Sec-Fetch-Mode": {"navigate"}},
645 u, err = url.Parse(resp.Header().Get("Location"))
646 c.Assert(err, check.IsNil)
647 c.Logf("redirected to %s", u)
648 c.Check(u.Host, check.Equals, s.handler.Cluster.Services.Workbench2.ExternalURL.Host)
649 c.Check(u.Query().Get("redirectToPreview"), check.Equals, "")
650 c.Check(u.Query().Get("redirectToDownload"), check.Equals, "/c="+arvadostest.FooCollection+"/foo")
652 // Without "Sec-Fetch-Mode: navigate" header, just 401.
653 s.testVhostRedirectTokenToCookie(c, "GET",
654 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host+"/c="+arvadostest.FooCollection+"/foo",
655 "?api_token=thisisabogustoken",
656 http.Header{"Sec-Fetch-Mode": {"cors"}},
658 http.StatusUnauthorized,
659 regexp.QuoteMeta(unauthorizedMessage+"\n"),
661 s.testVhostRedirectTokenToCookie(c, "GET",
662 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host+"/c="+arvadostest.FooCollection+"/foo",
663 "?api_token=thisisabogustoken",
666 http.StatusUnauthorized,
667 regexp.QuoteMeta(unauthorizedMessage+"\n"),
671 func (s *IntegrationSuite) TestVhostRedirectWithNoCache(c *check.C) {
672 resp := s.testVhostRedirectTokenToCookie(c, "GET",
673 arvadostest.FooCollection+".example.com/foo",
674 "?api_token=thisisabogustoken",
676 "Sec-Fetch-Mode": {"navigate"},
677 "Cache-Control": {"no-cache"},
683 u, err := url.Parse(resp.Header().Get("Location"))
684 c.Assert(err, check.IsNil)
685 c.Logf("redirected to %s", u)
686 c.Check(u.Host, check.Equals, s.handler.Cluster.Services.Workbench2.ExternalURL.Host)
687 c.Check(u.Query().Get("redirectToPreview"), check.Equals, "/c="+arvadostest.FooCollection+"/foo")
688 c.Check(u.Query().Get("redirectToDownload"), check.Equals, "")
691 func (s *IntegrationSuite) TestNoTokenWorkbench2LoginFlow(c *check.C) {
692 for _, trial := range []struct {
697 {cacheControl: "no-cache"},
699 {anonToken: true, cacheControl: "no-cache"},
701 c.Logf("trial: %+v", trial)
704 s.handler.Cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
706 s.handler.Cluster.Users.AnonymousUserToken = ""
708 req, err := http.NewRequest("GET", "http://"+arvadostest.FooCollection+".example.com/foo", nil)
709 c.Assert(err, check.IsNil)
710 req.Header.Set("Sec-Fetch-Mode", "navigate")
711 if trial.cacheControl != "" {
712 req.Header.Set("Cache-Control", trial.cacheControl)
714 resp := httptest.NewRecorder()
715 s.handler.ServeHTTP(resp, req)
716 c.Check(resp.Code, check.Equals, http.StatusSeeOther)
717 u, err := url.Parse(resp.Header().Get("Location"))
718 c.Assert(err, check.IsNil)
719 c.Logf("redirected to %q", u)
720 c.Check(u.Host, check.Equals, s.handler.Cluster.Services.Workbench2.ExternalURL.Host)
721 c.Check(u.Query().Get("redirectToPreview"), check.Equals, "/c="+arvadostest.FooCollection+"/foo")
722 c.Check(u.Query().Get("redirectToDownload"), check.Equals, "")
726 func (s *IntegrationSuite) TestVhostRedirectQueryTokenSingleOriginError(c *check.C) {
727 s.testVhostRedirectTokenToCookie(c, "GET",
728 "example.com/c="+arvadostest.FooCollection+"/foo",
729 "?api_token="+arvadostest.ActiveToken,
732 http.StatusBadRequest,
733 regexp.QuoteMeta("cannot serve inline content at this URL (possible configuration error; see https://doc.arvados.org/install/install-keep-web.html#dns)\n"),
737 // If client requests an attachment by putting ?disposition=attachment
738 // in the query string, and gets redirected, the redirect target
739 // should respond with an attachment.
740 func (s *IntegrationSuite) TestVhostRedirectQueryTokenRequestAttachment(c *check.C) {
741 resp := s.testVhostRedirectTokenToCookie(c, "GET",
742 arvadostest.FooCollection+".example.com/foo",
743 "?disposition=attachment&api_token="+arvadostest.ActiveToken,
749 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
752 func (s *IntegrationSuite) TestVhostRedirectQueryTokenSiteFS(c *check.C) {
753 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
754 resp := s.testVhostRedirectTokenToCookie(c, "GET",
755 "download.example.com/by_id/"+arvadostest.FooCollection+"/foo",
756 "?api_token="+arvadostest.ActiveToken,
762 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
765 func (s *IntegrationSuite) TestPastCollectionVersionFileAccess(c *check.C) {
766 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
767 resp := s.testVhostRedirectTokenToCookie(c, "GET",
768 "download.example.com/c="+arvadostest.WazVersion1Collection+"/waz",
769 "?api_token="+arvadostest.ActiveToken,
775 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
776 resp = s.testVhostRedirectTokenToCookie(c, "GET",
777 "download.example.com/by_id/"+arvadostest.WazVersion1Collection+"/waz",
778 "?api_token="+arvadostest.ActiveToken,
784 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
787 func (s *IntegrationSuite) TestVhostRedirectQueryTokenTrustAllContent(c *check.C) {
788 s.handler.Cluster.Collections.TrustAllContent = true
789 s.testVhostRedirectTokenToCookie(c, "GET",
790 "example.com/c="+arvadostest.FooCollection+"/foo",
791 "?api_token="+arvadostest.ActiveToken,
799 func (s *IntegrationSuite) TestVhostRedirectQueryTokenAttachmentOnlyHost(c *check.C) {
800 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "example.com:1234"
802 s.testVhostRedirectTokenToCookie(c, "GET",
803 "example.com/c="+arvadostest.FooCollection+"/foo",
804 "?api_token="+arvadostest.ActiveToken,
807 http.StatusBadRequest,
808 regexp.QuoteMeta("cannot serve inline content at this URL (possible configuration error; see https://doc.arvados.org/install/install-keep-web.html#dns)\n"),
811 resp := s.testVhostRedirectTokenToCookie(c, "GET",
812 "example.com:1234/c="+arvadostest.FooCollection+"/foo",
813 "?api_token="+arvadostest.ActiveToken,
819 c.Check(resp.Header().Get("Content-Disposition"), check.Equals, "attachment")
822 func (s *IntegrationSuite) TestVhostRedirectMultipleTokens(c *check.C) {
823 baseUrl := arvadostest.FooCollection + ".example.com/foo"
824 query := url.Values{}
826 // The intent of these tests is to check that requests are redirected
827 // correctly in the presence of multiple API tokens. The exact response
828 // codes and content are not closely considered: they're just how
829 // keep-web responded when we made the smallest possible fix. Changing
830 // those responses may be okay, but you should still test all these
831 // different cases and the associated redirect logic.
832 query["api_token"] = []string{arvadostest.ActiveToken, arvadostest.AnonymousToken}
833 s.testVhostRedirectTokenToCookie(c, "GET", baseUrl, "?"+query.Encode(), nil, "", http.StatusOK, "foo")
834 query["api_token"] = []string{arvadostest.ActiveToken, arvadostest.AnonymousToken, ""}
835 s.testVhostRedirectTokenToCookie(c, "GET", baseUrl, "?"+query.Encode(), nil, "", http.StatusOK, "foo")
836 query["api_token"] = []string{arvadostest.ActiveToken, "", arvadostest.AnonymousToken}
837 s.testVhostRedirectTokenToCookie(c, "GET", baseUrl, "?"+query.Encode(), nil, "", http.StatusOK, "foo")
838 query["api_token"] = []string{"", arvadostest.ActiveToken}
839 s.testVhostRedirectTokenToCookie(c, "GET", baseUrl, "?"+query.Encode(), nil, "", http.StatusOK, "foo")
841 expectContent := regexp.QuoteMeta(unauthorizedMessage + "\n")
842 query["api_token"] = []string{arvadostest.AnonymousToken, "invalidtoo"}
843 s.testVhostRedirectTokenToCookie(c, "GET", baseUrl, "?"+query.Encode(), nil, "", http.StatusUnauthorized, expectContent)
844 query["api_token"] = []string{arvadostest.AnonymousToken, ""}
845 s.testVhostRedirectTokenToCookie(c, "GET", baseUrl, "?"+query.Encode(), nil, "", http.StatusUnauthorized, expectContent)
846 query["api_token"] = []string{"", arvadostest.AnonymousToken}
847 s.testVhostRedirectTokenToCookie(c, "GET", baseUrl, "?"+query.Encode(), nil, "", http.StatusUnauthorized, expectContent)
850 func (s *IntegrationSuite) TestVhostRedirectPOSTFormTokenToCookie(c *check.C) {
851 s.testVhostRedirectTokenToCookie(c, "POST",
852 arvadostest.FooCollection+".example.com/foo",
854 http.Header{"Content-Type": {"application/x-www-form-urlencoded"}},
855 url.Values{"api_token": {arvadostest.ActiveToken}}.Encode(),
861 func (s *IntegrationSuite) TestVhostRedirectPOSTFormTokenToCookie404(c *check.C) {
862 s.testVhostRedirectTokenToCookie(c, "POST",
863 arvadostest.FooCollection+".example.com/foo",
865 http.Header{"Content-Type": {"application/x-www-form-urlencoded"}},
866 url.Values{"api_token": {arvadostest.SpectatorToken}}.Encode(),
868 regexp.QuoteMeta(notFoundMessage+"\n"),
872 func (s *IntegrationSuite) TestAnonymousTokenOK(c *check.C) {
873 s.handler.Cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
874 s.testVhostRedirectTokenToCookie(c, "GET",
875 "example.com/c="+arvadostest.HelloWorldCollection+"/Hello%20world.txt",
884 func (s *IntegrationSuite) TestAnonymousTokenError(c *check.C) {
885 s.handler.Cluster.Users.AnonymousUserToken = "anonymousTokenConfiguredButInvalid"
886 s.testVhostRedirectTokenToCookie(c, "GET",
887 "example.com/c="+arvadostest.HelloWorldCollection+"/Hello%20world.txt",
891 http.StatusUnauthorized,
892 "Authorization tokens are not accepted here: .*\n",
896 func (s *IntegrationSuite) TestSpecialCharsInPath(c *check.C) {
897 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
899 client := arvados.NewClientFromEnv()
900 client.AuthToken = arvadostest.ActiveToken
901 fs, err := (&arvados.Collection{}).FileSystem(client, nil)
902 c.Assert(err, check.IsNil)
903 f, err := fs.OpenFile("https:\\\"odd' path chars", os.O_CREATE, 0777)
904 c.Assert(err, check.IsNil)
906 mtxt, err := fs.MarshalManifest(".")
907 c.Assert(err, check.IsNil)
908 var coll arvados.Collection
909 err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
910 "collection": map[string]string{
911 "manifest_text": mtxt,
914 c.Assert(err, check.IsNil)
916 u, _ := url.Parse("http://download.example.com/c=" + coll.UUID + "/")
917 req := &http.Request{
921 RequestURI: u.RequestURI(),
923 "Authorization": {"Bearer " + client.AuthToken},
926 resp := httptest.NewRecorder()
927 s.handler.ServeHTTP(resp, req)
928 c.Check(resp.Code, check.Equals, http.StatusOK)
929 c.Check(resp.Body.String(), check.Matches, `(?ms).*href="./https:%5c%22odd%27%20path%20chars"\S+https:\\"odd' path chars.*`)
932 func (s *IntegrationSuite) TestForwardSlashSubstitution(c *check.C) {
933 arv := arvados.NewClientFromEnv()
934 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
935 s.handler.Cluster.Collections.ForwardSlashNameSubstitution = "{SOLIDUS}"
936 name := "foo/bar/baz"
937 nameShown := strings.Replace(name, "/", "{SOLIDUS}", -1)
938 nameShownEscaped := strings.Replace(name, "/", "%7bSOLIDUS%7d", -1)
940 client := arvados.NewClientFromEnv()
941 client.AuthToken = arvadostest.ActiveToken
942 fs, err := (&arvados.Collection{}).FileSystem(client, nil)
943 c.Assert(err, check.IsNil)
944 f, err := fs.OpenFile("filename", os.O_CREATE, 0777)
945 c.Assert(err, check.IsNil)
947 mtxt, err := fs.MarshalManifest(".")
948 c.Assert(err, check.IsNil)
949 var coll arvados.Collection
950 err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
951 "collection": map[string]string{
952 "manifest_text": mtxt,
954 "owner_uuid": arvadostest.AProjectUUID,
957 c.Assert(err, check.IsNil)
958 defer arv.RequestAndDecode(&coll, "DELETE", "arvados/v1/collections/"+coll.UUID, nil, nil)
960 base := "http://download.example.com/by_id/" + coll.OwnerUUID + "/"
961 for tryURL, expectRegexp := range map[string]string{
962 base: `(?ms).*href="./` + nameShownEscaped + `/"\S+` + nameShown + `.*`,
963 base + nameShownEscaped + "/": `(?ms).*href="./filename"\S+filename.*`,
965 u, _ := url.Parse(tryURL)
966 req := &http.Request{
970 RequestURI: u.RequestURI(),
972 "Authorization": {"Bearer " + client.AuthToken},
975 resp := httptest.NewRecorder()
976 s.handler.ServeHTTP(resp, req)
977 c.Check(resp.Code, check.Equals, http.StatusOK)
978 c.Check(resp.Body.String(), check.Matches, expectRegexp)
982 // XHRs can't follow redirect-with-cookie so they rely on method=POST
983 // and disposition=attachment (telling us it's acceptable to respond
984 // with content instead of a redirect) and an Origin header that gets
985 // added automatically by the browser (telling us it's desirable to do
987 func (s *IntegrationSuite) TestXHRNoRedirect(c *check.C) {
988 u, _ := url.Parse("http://example.com/c=" + arvadostest.FooCollection + "/foo")
989 req := &http.Request{
993 RequestURI: u.RequestURI(),
995 "Origin": {"https://origin.example"},
996 "Content-Type": {"application/x-www-form-urlencoded"},
998 Body: ioutil.NopCloser(strings.NewReader(url.Values{
999 "api_token": {arvadostest.ActiveToken},
1000 "disposition": {"attachment"},
1003 resp := httptest.NewRecorder()
1004 s.handler.ServeHTTP(resp, req)
1005 c.Check(resp.Code, check.Equals, http.StatusOK)
1006 c.Check(resp.Body.String(), check.Equals, "foo")
1007 c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, "*")
1009 // GET + Origin header is representative of both AJAX GET
1010 // requests and inline images via <IMG crossorigin="anonymous"
1012 u.RawQuery = "api_token=" + url.QueryEscape(arvadostest.ActiveTokenV2)
1013 req = &http.Request{
1017 RequestURI: u.RequestURI(),
1018 Header: http.Header{
1019 "Origin": {"https://origin.example"},
1022 resp = httptest.NewRecorder()
1023 s.handler.ServeHTTP(resp, req)
1024 c.Check(resp.Code, check.Equals, http.StatusOK)
1025 c.Check(resp.Body.String(), check.Equals, "foo")
1026 c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, "*")
1029 func (s *IntegrationSuite) testVhostRedirectTokenToCookie(c *check.C, method, hostPath, queryString string, reqHeader http.Header, reqBody string, expectStatus int, matchRespBody string) *httptest.ResponseRecorder {
1030 if reqHeader == nil {
1031 reqHeader = http.Header{}
1033 u, _ := url.Parse(`http://` + hostPath + queryString)
1034 c.Logf("requesting %s", u)
1035 req := &http.Request{
1039 RequestURI: u.RequestURI(),
1041 Body: ioutil.NopCloser(strings.NewReader(reqBody)),
1044 resp := httptest.NewRecorder()
1046 c.Check(resp.Code, check.Equals, expectStatus)
1047 c.Check(resp.Body.String(), check.Matches, matchRespBody)
1050 s.handler.ServeHTTP(resp, req)
1051 if resp.Code != http.StatusSeeOther {
1052 attachment, _ := regexp.MatchString(`^attachment(;|$)`, resp.Header().Get("Content-Disposition"))
1053 // Since we're not redirecting, check that any api_token in the URL is
1055 // If there is no token in the URL, then we're good.
1056 // Otherwise, if the response code is an error, the body is expected to
1057 // be static content, and nothing that might maliciously introspect the
1058 // URL. It's considered safe and allowed.
1059 // Otherwise, if the response content has attachment disposition,
1060 // that's considered safe for all the reasons explained in the
1061 // safeAttachment comment in handler.go.
1062 c.Check(!u.Query().Has("api_token") || resp.Code >= 400 || attachment, check.Equals, true)
1066 loc, err := url.Parse(resp.Header().Get("Location"))
1067 c.Assert(err, check.IsNil)
1068 c.Check(loc.Scheme, check.Equals, u.Scheme)
1069 c.Check(loc.Host, check.Equals, u.Host)
1070 c.Check(loc.RawPath, check.Equals, u.RawPath)
1071 // If the response was a redirect, it should never include an API token.
1072 c.Check(loc.Query().Has("api_token"), check.Equals, false)
1073 c.Check(resp.Body.String(), check.Matches, `.*href="http://`+regexp.QuoteMeta(html.EscapeString(hostPath))+`(\?[^"]*)?".*`)
1074 cookies := (&http.Response{Header: resp.Header()}).Cookies()
1076 c.Logf("following redirect to %s", u)
1077 req = &http.Request{
1081 RequestURI: loc.RequestURI(),
1084 for _, c := range cookies {
1088 resp = httptest.NewRecorder()
1089 s.handler.ServeHTTP(resp, req)
1091 if resp.Code != http.StatusSeeOther {
1092 c.Check(resp.Header().Get("Location"), check.Equals, "")
1097 func (s *IntegrationSuite) TestDirectoryListingWithAnonymousToken(c *check.C) {
1098 s.handler.Cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
1099 s.testDirectoryListing(c)
1102 func (s *IntegrationSuite) TestDirectoryListingWithNoAnonymousToken(c *check.C) {
1103 s.handler.Cluster.Users.AnonymousUserToken = ""
1104 s.testDirectoryListing(c)
1107 func (s *IntegrationSuite) testDirectoryListing(c *check.C) {
1108 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
1109 authHeader := http.Header{
1110 "Authorization": {"OAuth2 " + arvadostest.ActiveToken},
1112 for _, trial := range []struct {
1120 uri: strings.Replace(arvadostest.FooAndBarFilesInDirPDH, "+", "-", -1) + ".example.com/",
1122 expect: []string{"dir1/foo", "dir1/bar"},
1126 uri: strings.Replace(arvadostest.FooAndBarFilesInDirPDH, "+", "-", -1) + ".example.com/dir1/",
1128 expect: []string{"foo", "bar"},
1132 // URLs of this form ignore authHeader, and
1133 // FooAndBarFilesInDirUUID isn't public, so
1134 // this returns 401.
1135 uri: "download.example.com/collections/" + arvadostest.FooAndBarFilesInDirUUID + "/",
1140 uri: "download.example.com/users/active/foo_file_in_dir/",
1142 expect: []string{"dir1/"},
1146 uri: "download.example.com/users/active/foo_file_in_dir/dir1/",
1148 expect: []string{"bar"},
1152 uri: "download.example.com/",
1154 expect: []string{"users/"},
1158 uri: "download.example.com/users",
1160 redirect: "/users/",
1161 expect: []string{"active/"},
1165 uri: "download.example.com/users/",
1167 expect: []string{"active/"},
1171 uri: "download.example.com/users/active",
1173 redirect: "/users/active/",
1174 expect: []string{"foo_file_in_dir/"},
1178 uri: "download.example.com/users/active/",
1180 expect: []string{"foo_file_in_dir/"},
1184 uri: "collections.example.com/collections/download/" + arvadostest.FooAndBarFilesInDirUUID + "/" + arvadostest.ActiveToken + "/",
1186 expect: []string{"dir1/foo", "dir1/bar"},
1190 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/t=" + arvadostest.ActiveToken + "/",
1192 expect: []string{"dir1/foo", "dir1/bar"},
1196 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/t=" + arvadostest.ActiveToken,
1198 expect: []string{"dir1/foo", "dir1/bar"},
1202 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID,
1204 expect: []string{"dir1/foo", "dir1/bar"},
1208 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/dir1",
1210 redirect: "/c=" + arvadostest.FooAndBarFilesInDirUUID + "/dir1/",
1211 expect: []string{"foo", "bar"},
1215 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/_/dir1/",
1217 expect: []string{"foo", "bar"},
1221 uri: arvadostest.FooAndBarFilesInDirUUID + ".example.com/dir1?api_token=" + arvadostest.ActiveToken,
1224 expect: []string{"foo", "bar"},
1228 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/theperthcountyconspiracydoesnotexist/",
1233 uri: "download.example.com/c=" + arvadostest.WazVersion1Collection,
1235 expect: []string{"waz"},
1239 uri: "download.example.com/by_id/" + arvadostest.WazVersion1Collection,
1241 expect: []string{"waz"},
1245 comment := check.Commentf("HTML: %q => %q", trial.uri, trial.expect)
1246 resp := httptest.NewRecorder()
1247 u := mustParseURL("//" + trial.uri)
1248 req := &http.Request{
1252 RequestURI: u.RequestURI(),
1253 Header: copyHeader(trial.header),
1255 s.handler.ServeHTTP(resp, req)
1256 var cookies []*http.Cookie
1257 for resp.Code == http.StatusSeeOther {
1258 u, _ := req.URL.Parse(resp.Header().Get("Location"))
1259 req = &http.Request{
1263 RequestURI: u.RequestURI(),
1264 Header: copyHeader(trial.header),
1266 cookies = append(cookies, (&http.Response{Header: resp.Header()}).Cookies()...)
1267 for _, c := range cookies {
1270 resp = httptest.NewRecorder()
1271 s.handler.ServeHTTP(resp, req)
1273 if trial.redirect != "" {
1274 c.Check(req.URL.Path, check.Equals, trial.redirect, comment)
1276 if trial.expect == nil {
1277 c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
1279 c.Check(resp.Code, check.Equals, http.StatusOK, comment)
1280 for _, e := range trial.expect {
1281 c.Check(resp.Body.String(), check.Matches, `(?ms).*href="./`+e+`".*`, comment)
1283 c.Check(resp.Body.String(), check.Matches, `(?ms).*--cut-dirs=`+fmt.Sprintf("%d", trial.cutDirs)+` .*`, comment)
1286 comment = check.Commentf("WebDAV: %q => %q", trial.uri, trial.expect)
1287 req = &http.Request{
1291 RequestURI: u.RequestURI(),
1292 Header: copyHeader(trial.header),
1293 Body: ioutil.NopCloser(&bytes.Buffer{}),
1295 resp = httptest.NewRecorder()
1296 s.handler.ServeHTTP(resp, req)
1297 if trial.expect == nil {
1298 c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
1300 c.Check(resp.Code, check.Equals, http.StatusOK, comment)
1303 req = &http.Request{
1307 RequestURI: u.RequestURI(),
1308 Header: copyHeader(trial.header),
1309 Body: ioutil.NopCloser(&bytes.Buffer{}),
1311 resp = httptest.NewRecorder()
1312 s.handler.ServeHTTP(resp, req)
1313 if trial.expect == nil {
1314 c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
1316 c.Check(resp.Code, check.Equals, http.StatusMultiStatus, comment)
1317 for _, e := range trial.expect {
1318 if strings.HasSuffix(e, "/") {
1319 e = filepath.Join(u.Path, e) + "/"
1321 e = filepath.Join(u.Path, e)
1323 c.Check(resp.Body.String(), check.Matches, `(?ms).*<D:href>`+e+`</D:href>.*`, comment)
1329 func (s *IntegrationSuite) TestDeleteLastFile(c *check.C) {
1330 arv := arvados.NewClientFromEnv()
1331 var newCollection arvados.Collection
1332 err := arv.RequestAndDecode(&newCollection, "POST", "arvados/v1/collections", nil, map[string]interface{}{
1333 "collection": map[string]string{
1334 "owner_uuid": arvadostest.ActiveUserUUID,
1335 "manifest_text": ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo.txt 0:3:bar.txt\n",
1336 "name": "keep-web test collection",
1338 "ensure_unique_name": true,
1340 c.Assert(err, check.IsNil)
1341 defer arv.RequestAndDecode(&newCollection, "DELETE", "arvados/v1/collections/"+newCollection.UUID, nil, nil)
1343 var updated arvados.Collection
1344 for _, fnm := range []string{"foo.txt", "bar.txt"} {
1345 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "example.com"
1346 u, _ := url.Parse("http://example.com/c=" + newCollection.UUID + "/" + fnm)
1347 req := &http.Request{
1351 RequestURI: u.RequestURI(),
1352 Header: http.Header{
1353 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1356 resp := httptest.NewRecorder()
1357 s.handler.ServeHTTP(resp, req)
1358 c.Check(resp.Code, check.Equals, http.StatusNoContent)
1360 updated = arvados.Collection{}
1361 err = arv.RequestAndDecode(&updated, "GET", "arvados/v1/collections/"+newCollection.UUID, nil, nil)
1362 c.Check(err, check.IsNil)
1363 c.Check(updated.ManifestText, check.Not(check.Matches), `(?ms).*\Q`+fnm+`\E.*`)
1364 c.Logf("updated manifest_text %q", updated.ManifestText)
1366 c.Check(updated.ManifestText, check.Equals, "")
1369 func (s *IntegrationSuite) TestFileContentType(c *check.C) {
1370 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
1372 client := arvados.NewClientFromEnv()
1373 client.AuthToken = arvadostest.ActiveToken
1374 arv, err := arvadosclient.New(client)
1375 c.Assert(err, check.Equals, nil)
1376 kc, err := keepclient.MakeKeepClient(arv)
1377 c.Assert(err, check.Equals, nil)
1379 fs, err := (&arvados.Collection{}).FileSystem(client, kc)
1380 c.Assert(err, check.IsNil)
1382 trials := []struct {
1387 {"picture.txt", "BMX bikes are small this year\n", "text/plain; charset=utf-8"},
1388 {"picture.bmp", "BMX bikes are small this year\n", "image/(x-ms-)?bmp"},
1389 {"picture.jpg", "BMX bikes are small this year\n", "image/jpeg"},
1390 {"picture1", "BMX bikes are small this year\n", "image/bmp"}, // content sniff; "BM" is the magic signature for .bmp
1391 {"picture2", "Cars are small this year\n", "text/plain; charset=utf-8"}, // content sniff
1393 for _, trial := range trials {
1394 f, err := fs.OpenFile(trial.filename, os.O_CREATE|os.O_WRONLY, 0777)
1395 c.Assert(err, check.IsNil)
1396 _, err = f.Write([]byte(trial.content))
1397 c.Assert(err, check.IsNil)
1398 c.Assert(f.Close(), check.IsNil)
1400 mtxt, err := fs.MarshalManifest(".")
1401 c.Assert(err, check.IsNil)
1402 var coll arvados.Collection
1403 err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
1404 "collection": map[string]string{
1405 "manifest_text": mtxt,
1408 c.Assert(err, check.IsNil)
1410 for _, trial := range trials {
1411 u, _ := url.Parse("http://download.example.com/by_id/" + coll.UUID + "/" + trial.filename)
1412 req := &http.Request{
1416 RequestURI: u.RequestURI(),
1417 Header: http.Header{
1418 "Authorization": {"Bearer " + client.AuthToken},
1421 resp := httptest.NewRecorder()
1422 s.handler.ServeHTTP(resp, req)
1423 c.Check(resp.Code, check.Equals, http.StatusOK)
1424 c.Check(resp.Header().Get("Content-Type"), check.Matches, trial.contentType)
1425 c.Check(resp.Body.String(), check.Equals, trial.content)
1429 func (s *IntegrationSuite) TestKeepClientBlockCache(c *check.C) {
1430 s.handler.Cluster.Collections.WebDAVCache.MaxBlockEntries = 42
1431 c.Check(keepclient.DefaultBlockCache.MaxBlocks, check.Not(check.Equals), 42)
1432 u := mustParseURL("http://keep-web.example/c=" + arvadostest.FooCollection + "/t=" + arvadostest.ActiveToken + "/foo")
1433 req := &http.Request{
1437 RequestURI: u.RequestURI(),
1439 resp := httptest.NewRecorder()
1440 s.handler.ServeHTTP(resp, req)
1441 c.Check(resp.Code, check.Equals, http.StatusOK)
1442 c.Check(keepclient.DefaultBlockCache.MaxBlocks, check.Equals, 42)
1445 // Writing to a collection shouldn't affect its entry in the
1446 // PDH-to-manifest cache.
1447 func (s *IntegrationSuite) TestCacheWriteCollectionSamePDH(c *check.C) {
1448 arv, err := arvadosclient.MakeArvadosClient()
1449 c.Assert(err, check.Equals, nil)
1450 arv.ApiToken = arvadostest.ActiveToken
1452 u := mustParseURL("http://x.example/testfile")
1453 req := &http.Request{
1457 RequestURI: u.RequestURI(),
1458 Header: http.Header{"Authorization": {"Bearer " + arv.ApiToken}},
1461 checkWithID := func(id string, status int) {
1462 req.URL.Host = strings.Replace(id, "+", "-", -1) + ".example"
1463 req.Host = req.URL.Host
1464 resp := httptest.NewRecorder()
1465 s.handler.ServeHTTP(resp, req)
1466 c.Check(resp.Code, check.Equals, status)
1469 var colls [2]arvados.Collection
1470 for i := range colls {
1471 err := arv.Create("collections",
1472 map[string]interface{}{
1473 "ensure_unique_name": true,
1474 "collection": map[string]interface{}{
1475 "name": "test collection",
1478 c.Assert(err, check.Equals, nil)
1481 // Populate cache with empty collection
1482 checkWithID(colls[0].PortableDataHash, http.StatusNotFound)
1484 // write a file to colls[0]
1486 reqPut.Method = "PUT"
1487 reqPut.URL.Host = colls[0].UUID + ".example"
1488 reqPut.Host = req.URL.Host
1489 reqPut.Body = ioutil.NopCloser(bytes.NewBufferString("testdata"))
1490 resp := httptest.NewRecorder()
1491 s.handler.ServeHTTP(resp, &reqPut)
1492 c.Check(resp.Code, check.Equals, http.StatusCreated)
1494 // new file should not appear in colls[1]
1495 checkWithID(colls[1].PortableDataHash, http.StatusNotFound)
1496 checkWithID(colls[1].UUID, http.StatusNotFound)
1498 checkWithID(colls[0].UUID, http.StatusOK)
1501 func copyHeader(h http.Header) http.Header {
1503 for k, v := range h {
1504 hc[k] = append([]string(nil), v...)
1509 func (s *IntegrationSuite) checkUploadDownloadRequest(c *check.C, req *http.Request,
1510 successCode int, direction string, perm bool, userUuid, collectionUuid, collectionPDH, filepath string) {
1512 client := arvados.NewClientFromEnv()
1513 client.AuthToken = arvadostest.AdminToken
1514 var logentries arvados.LogList
1516 err := client.RequestAndDecode(&logentries, "GET", "arvados/v1/logs", nil,
1517 arvados.ResourceListParams{
1519 Order: "created_at desc"})
1520 c.Check(err, check.IsNil)
1521 c.Check(logentries.Items, check.HasLen, 1)
1522 lastLogId := logentries.Items[0].ID
1523 c.Logf("lastLogId: %d", lastLogId)
1525 var logbuf bytes.Buffer
1526 logger := logrus.New()
1527 logger.Out = &logbuf
1528 resp := httptest.NewRecorder()
1529 req = req.WithContext(ctxlog.Context(context.Background(), logger))
1530 s.handler.ServeHTTP(resp, req)
1533 c.Check(resp.Result().StatusCode, check.Equals, successCode)
1534 c.Check(logbuf.String(), check.Matches, `(?ms).*msg="File `+direction+`".*`)
1535 c.Check(logbuf.String(), check.Not(check.Matches), `(?ms).*level=error.*`)
1537 deadline := time.Now().Add(time.Second)
1539 c.Assert(time.Now().After(deadline), check.Equals, false, check.Commentf("timed out waiting for log entry"))
1540 logentries = arvados.LogList{}
1541 err = client.RequestAndDecode(&logentries, "GET", "arvados/v1/logs", nil,
1542 arvados.ResourceListParams{
1543 Filters: []arvados.Filter{
1544 {Attr: "event_type", Operator: "=", Operand: "file_" + direction},
1545 {Attr: "object_uuid", Operator: "=", Operand: userUuid},
1548 Order: "created_at desc",
1550 c.Assert(err, check.IsNil)
1551 if len(logentries.Items) > 0 &&
1552 logentries.Items[0].ID > lastLogId &&
1553 logentries.Items[0].ObjectUUID == userUuid &&
1554 logentries.Items[0].Properties["collection_uuid"] == collectionUuid &&
1555 (collectionPDH == "" || logentries.Items[0].Properties["portable_data_hash"] == collectionPDH) &&
1556 logentries.Items[0].Properties["collection_file_path"] == filepath {
1559 c.Logf("logentries.Items: %+v", logentries.Items)
1560 time.Sleep(50 * time.Millisecond)
1563 c.Check(resp.Result().StatusCode, check.Equals, http.StatusForbidden)
1564 c.Check(logbuf.String(), check.Equals, "")
1568 func (s *IntegrationSuite) TestDownloadLoggingPermission(c *check.C) {
1569 u := mustParseURL("http://" + arvadostest.FooCollection + ".keep-web.example/foo")
1571 s.handler.Cluster.Collections.TrustAllContent = true
1573 for _, adminperm := range []bool{true, false} {
1574 for _, userperm := range []bool{true, false} {
1575 s.handler.Cluster.Collections.WebDAVPermission.Admin.Download = adminperm
1576 s.handler.Cluster.Collections.WebDAVPermission.User.Download = userperm
1578 // Test admin permission
1579 req := &http.Request{
1583 RequestURI: u.RequestURI(),
1584 Header: http.Header{
1585 "Authorization": {"Bearer " + arvadostest.AdminToken},
1588 s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", adminperm,
1589 arvadostest.AdminUserUUID, arvadostest.FooCollection, arvadostest.FooCollectionPDH, "foo")
1591 // Test user permission
1592 req = &http.Request{
1596 RequestURI: u.RequestURI(),
1597 Header: http.Header{
1598 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1601 s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", userperm,
1602 arvadostest.ActiveUserUUID, arvadostest.FooCollection, arvadostest.FooCollectionPDH, "foo")
1606 s.handler.Cluster.Collections.WebDAVPermission.User.Download = true
1608 for _, tryurl := range []string{"http://" + arvadostest.MultilevelCollection1 + ".keep-web.example/dir1/subdir/file1",
1609 "http://keep-web/users/active/multilevel_collection_1/dir1/subdir/file1"} {
1611 u = mustParseURL(tryurl)
1612 req := &http.Request{
1616 RequestURI: u.RequestURI(),
1617 Header: http.Header{
1618 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1621 s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", true,
1622 arvadostest.ActiveUserUUID, arvadostest.MultilevelCollection1, arvadostest.MultilevelCollection1PDH, "dir1/subdir/file1")
1625 u = mustParseURL("http://" + strings.Replace(arvadostest.FooCollectionPDH, "+", "-", 1) + ".keep-web.example/foo")
1626 req := &http.Request{
1630 RequestURI: u.RequestURI(),
1631 Header: http.Header{
1632 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1635 s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", true,
1636 arvadostest.ActiveUserUUID, "", arvadostest.FooCollectionPDH, "foo")
1639 func (s *IntegrationSuite) TestUploadLoggingPermission(c *check.C) {
1640 for _, adminperm := range []bool{true, false} {
1641 for _, userperm := range []bool{true, false} {
1643 arv := arvados.NewClientFromEnv()
1644 arv.AuthToken = arvadostest.ActiveToken
1646 var coll arvados.Collection
1647 err := arv.RequestAndDecode(&coll,
1649 "/arvados/v1/collections",
1651 map[string]interface{}{
1652 "ensure_unique_name": true,
1653 "collection": map[string]interface{}{
1654 "name": "test collection",
1657 c.Assert(err, check.Equals, nil)
1659 u := mustParseURL("http://" + coll.UUID + ".keep-web.example/bar")
1661 s.handler.Cluster.Collections.WebDAVPermission.Admin.Upload = adminperm
1662 s.handler.Cluster.Collections.WebDAVPermission.User.Upload = userperm
1664 // Test admin permission
1665 req := &http.Request{
1669 RequestURI: u.RequestURI(),
1670 Header: http.Header{
1671 "Authorization": {"Bearer " + arvadostest.AdminToken},
1673 Body: io.NopCloser(bytes.NewReader([]byte("bar"))),
1675 s.checkUploadDownloadRequest(c, req, http.StatusCreated, "upload", adminperm,
1676 arvadostest.AdminUserUUID, coll.UUID, "", "bar")
1678 // Test user permission
1679 req = &http.Request{
1683 RequestURI: u.RequestURI(),
1684 Header: http.Header{
1685 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1687 Body: io.NopCloser(bytes.NewReader([]byte("bar"))),
1689 s.checkUploadDownloadRequest(c, req, http.StatusCreated, "upload", userperm,
1690 arvadostest.ActiveUserUUID, coll.UUID, "", "bar")
1695 func (s *IntegrationSuite) TestConcurrentWrites(c *check.C) {
1696 s.handler.Cluster.Collections.WebDAVCache.TTL = arvados.Duration(time.Second * 2)
1697 lockTidyInterval = time.Second
1698 client := arvados.NewClientFromEnv()
1699 client.AuthToken = arvadostest.ActiveTokenV2
1700 // Start small, and increase concurrency (2^2, 4^2, ...)
1701 // only until hitting failure. Avoids unnecessarily long
1703 for n := 2; n < 16 && !c.Failed(); n = n * 2 {
1704 c.Logf("%s: n=%d", c.TestName(), n)
1706 var coll arvados.Collection
1707 err := client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, nil)
1708 c.Assert(err, check.IsNil)
1709 defer client.RequestAndDecode(&coll, "DELETE", "arvados/v1/collections/"+coll.UUID, nil, nil)
1711 var wg sync.WaitGroup
1712 for i := 0; i < n && !c.Failed(); i++ {
1717 u := mustParseURL(fmt.Sprintf("http://%s.collections.example.com/i=%d", coll.UUID, i))
1718 resp := httptest.NewRecorder()
1719 req, err := http.NewRequest("MKCOL", u.String(), nil)
1720 c.Assert(err, check.IsNil)
1721 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
1722 s.handler.ServeHTTP(resp, req)
1723 c.Assert(resp.Code, check.Equals, http.StatusCreated)
1724 for j := 0; j < n && !c.Failed(); j++ {
1729 content := fmt.Sprintf("i=%d/j=%d", i, j)
1730 u := mustParseURL("http://" + coll.UUID + ".collections.example.com/" + content)
1732 resp := httptest.NewRecorder()
1733 req, err := http.NewRequest("PUT", u.String(), strings.NewReader(content))
1734 c.Assert(err, check.IsNil)
1735 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
1736 s.handler.ServeHTTP(resp, req)
1737 c.Check(resp.Code, check.Equals, http.StatusCreated)
1739 time.Sleep(time.Second)
1740 resp = httptest.NewRecorder()
1741 req, err = http.NewRequest("GET", u.String(), nil)
1742 c.Assert(err, check.IsNil)
1743 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
1744 s.handler.ServeHTTP(resp, req)
1745 c.Check(resp.Code, check.Equals, http.StatusOK)
1746 c.Check(resp.Body.String(), check.Equals, content)
1752 for i := 0; i < n; i++ {
1753 u := mustParseURL(fmt.Sprintf("http://%s.collections.example.com/i=%d", coll.UUID, i))
1754 resp := httptest.NewRecorder()
1755 req, err := http.NewRequest("PROPFIND", u.String(), &bytes.Buffer{})
1756 c.Assert(err, check.IsNil)
1757 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
1758 s.handler.ServeHTTP(resp, req)
1759 c.Assert(resp.Code, check.Equals, http.StatusMultiStatus)