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 // The "ownership cycle" test fixtures are reachable from the
1109 // "filter group without filters" group, causing webdav's
1110 // walkfs to recurse indefinitely. Avoid that by deleting one
1111 // of the bogus fixtures.
1112 arv := arvados.NewClientFromEnv()
1113 err := arv.RequestAndDecode(nil, "DELETE", "arvados/v1/groups/zzzzz-j7d0g-cx2al9cqkmsf1hs", nil, nil)
1115 c.Assert(err, check.FitsTypeOf, &arvados.TransactionError{})
1116 c.Check(err.(*arvados.TransactionError).StatusCode, check.Equals, 404)
1119 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
1120 authHeader := http.Header{
1121 "Authorization": {"OAuth2 " + arvadostest.ActiveToken},
1123 for _, trial := range []struct {
1131 uri: strings.Replace(arvadostest.FooAndBarFilesInDirPDH, "+", "-", -1) + ".example.com/",
1133 expect: []string{"dir1/foo", "dir1/bar"},
1137 uri: strings.Replace(arvadostest.FooAndBarFilesInDirPDH, "+", "-", -1) + ".example.com/dir1/",
1139 expect: []string{"foo", "bar"},
1143 // URLs of this form ignore authHeader, and
1144 // FooAndBarFilesInDirUUID isn't public, so
1145 // this returns 401.
1146 uri: "download.example.com/collections/" + arvadostest.FooAndBarFilesInDirUUID + "/",
1151 uri: "download.example.com/users/active/foo_file_in_dir/",
1153 expect: []string{"dir1/"},
1157 uri: "download.example.com/users/active/foo_file_in_dir/dir1/",
1159 expect: []string{"bar"},
1163 uri: "download.example.com/",
1165 expect: []string{"users/"},
1169 uri: "download.example.com/users",
1171 redirect: "/users/",
1172 expect: []string{"active/"},
1176 uri: "download.example.com/users/",
1178 expect: []string{"active/"},
1182 uri: "download.example.com/users/active",
1184 redirect: "/users/active/",
1185 expect: []string{"foo_file_in_dir/"},
1189 uri: "download.example.com/users/active/",
1191 expect: []string{"foo_file_in_dir/"},
1195 uri: "collections.example.com/collections/download/" + arvadostest.FooAndBarFilesInDirUUID + "/" + arvadostest.ActiveToken + "/",
1197 expect: []string{"dir1/foo", "dir1/bar"},
1201 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/t=" + arvadostest.ActiveToken + "/",
1203 expect: []string{"dir1/foo", "dir1/bar"},
1207 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/t=" + arvadostest.ActiveToken,
1209 expect: []string{"dir1/foo", "dir1/bar"},
1213 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID,
1215 expect: []string{"dir1/foo", "dir1/bar"},
1219 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/dir1",
1221 redirect: "/c=" + arvadostest.FooAndBarFilesInDirUUID + "/dir1/",
1222 expect: []string{"foo", "bar"},
1226 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/_/dir1/",
1228 expect: []string{"foo", "bar"},
1232 uri: arvadostest.FooAndBarFilesInDirUUID + ".example.com/dir1?api_token=" + arvadostest.ActiveToken,
1235 expect: []string{"foo", "bar"},
1239 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/theperthcountyconspiracydoesnotexist/",
1244 uri: "download.example.com/c=" + arvadostest.WazVersion1Collection,
1246 expect: []string{"waz"},
1250 uri: "download.example.com/by_id/" + arvadostest.WazVersion1Collection,
1252 expect: []string{"waz"},
1256 uri: "download.example.com/users/active/This filter group/",
1258 expect: []string{"A Subproject/"},
1262 uri: "download.example.com/users/active/This filter group/A Subproject",
1264 expect: []string{"baz_file/"},
1268 uri: "download.example.com/by_id/" + arvadostest.AFilterGroupUUID,
1270 expect: []string{"A Subproject/"},
1274 uri: "download.example.com/by_id/" + arvadostest.AFilterGroupUUID + "/A Subproject",
1276 expect: []string{"baz_file/"},
1280 comment := check.Commentf("HTML: %q redir %q => %q", trial.uri, trial.redirect, trial.expect)
1281 resp := httptest.NewRecorder()
1282 u := mustParseURL("//" + trial.uri)
1283 req := &http.Request{
1287 RequestURI: u.RequestURI(),
1288 Header: copyHeader(trial.header),
1290 s.handler.ServeHTTP(resp, req)
1291 var cookies []*http.Cookie
1292 for resp.Code == http.StatusSeeOther {
1293 u, _ := req.URL.Parse(resp.Header().Get("Location"))
1294 req = &http.Request{
1298 RequestURI: u.RequestURI(),
1299 Header: copyHeader(trial.header),
1301 cookies = append(cookies, (&http.Response{Header: resp.Header()}).Cookies()...)
1302 for _, c := range cookies {
1305 resp = httptest.NewRecorder()
1306 s.handler.ServeHTTP(resp, req)
1308 if trial.redirect != "" {
1309 c.Check(req.URL.Path, check.Equals, trial.redirect, comment)
1311 if trial.expect == nil {
1312 c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
1314 c.Check(resp.Code, check.Equals, http.StatusOK, comment)
1315 for _, e := range trial.expect {
1316 e = strings.Replace(e, " ", "%20", -1)
1317 c.Check(resp.Body.String(), check.Matches, `(?ms).*href="./`+e+`".*`, comment)
1319 c.Check(resp.Body.String(), check.Matches, `(?ms).*--cut-dirs=`+fmt.Sprintf("%d", trial.cutDirs)+` .*`, comment)
1322 comment = check.Commentf("WebDAV: %q => %q", trial.uri, trial.expect)
1323 req = &http.Request{
1327 RequestURI: u.RequestURI(),
1328 Header: copyHeader(trial.header),
1329 Body: ioutil.NopCloser(&bytes.Buffer{}),
1331 resp = httptest.NewRecorder()
1332 s.handler.ServeHTTP(resp, req)
1333 if trial.expect == nil {
1334 c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
1336 c.Check(resp.Code, check.Equals, http.StatusOK, comment)
1339 req = &http.Request{
1343 RequestURI: u.RequestURI(),
1344 Header: copyHeader(trial.header),
1345 Body: ioutil.NopCloser(&bytes.Buffer{}),
1347 resp = httptest.NewRecorder()
1348 s.handler.ServeHTTP(resp, req)
1349 // This check avoids logging a big XML document in the
1350 // event webdav throws a 500 error after sending
1351 // headers for a 207.
1352 if !c.Check(strings.HasSuffix(resp.Body.String(), "Internal Server Error"), check.Equals, false) {
1355 if trial.expect == nil {
1356 c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
1358 c.Check(resp.Code, check.Equals, http.StatusMultiStatus, comment)
1359 for _, e := range trial.expect {
1360 if strings.HasSuffix(e, "/") {
1361 e = filepath.Join(u.Path, e) + "/"
1363 e = filepath.Join(u.Path, e)
1365 e = strings.Replace(e, " ", "%20", -1)
1366 c.Check(resp.Body.String(), check.Matches, `(?ms).*<D:href>`+e+`</D:href>.*`, comment)
1372 func (s *IntegrationSuite) TestDeleteLastFile(c *check.C) {
1373 arv := arvados.NewClientFromEnv()
1374 var newCollection arvados.Collection
1375 err := arv.RequestAndDecode(&newCollection, "POST", "arvados/v1/collections", nil, map[string]interface{}{
1376 "collection": map[string]string{
1377 "owner_uuid": arvadostest.ActiveUserUUID,
1378 "manifest_text": ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo.txt 0:3:bar.txt\n",
1379 "name": "keep-web test collection",
1381 "ensure_unique_name": true,
1383 c.Assert(err, check.IsNil)
1384 defer arv.RequestAndDecode(&newCollection, "DELETE", "arvados/v1/collections/"+newCollection.UUID, nil, nil)
1386 var updated arvados.Collection
1387 for _, fnm := range []string{"foo.txt", "bar.txt"} {
1388 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "example.com"
1389 u, _ := url.Parse("http://example.com/c=" + newCollection.UUID + "/" + fnm)
1390 req := &http.Request{
1394 RequestURI: u.RequestURI(),
1395 Header: http.Header{
1396 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1399 resp := httptest.NewRecorder()
1400 s.handler.ServeHTTP(resp, req)
1401 c.Check(resp.Code, check.Equals, http.StatusNoContent)
1403 updated = arvados.Collection{}
1404 err = arv.RequestAndDecode(&updated, "GET", "arvados/v1/collections/"+newCollection.UUID, nil, nil)
1405 c.Check(err, check.IsNil)
1406 c.Check(updated.ManifestText, check.Not(check.Matches), `(?ms).*\Q`+fnm+`\E.*`)
1407 c.Logf("updated manifest_text %q", updated.ManifestText)
1409 c.Check(updated.ManifestText, check.Equals, "")
1412 func (s *IntegrationSuite) TestFileContentType(c *check.C) {
1413 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
1415 client := arvados.NewClientFromEnv()
1416 client.AuthToken = arvadostest.ActiveToken
1417 arv, err := arvadosclient.New(client)
1418 c.Assert(err, check.Equals, nil)
1419 kc, err := keepclient.MakeKeepClient(arv)
1420 c.Assert(err, check.Equals, nil)
1422 fs, err := (&arvados.Collection{}).FileSystem(client, kc)
1423 c.Assert(err, check.IsNil)
1425 trials := []struct {
1430 {"picture.txt", "BMX bikes are small this year\n", "text/plain; charset=utf-8"},
1431 {"picture.bmp", "BMX bikes are small this year\n", "image/(x-ms-)?bmp"},
1432 {"picture.jpg", "BMX bikes are small this year\n", "image/jpeg"},
1433 {"picture1", "BMX bikes are small this year\n", "image/bmp"}, // content sniff; "BM" is the magic signature for .bmp
1434 {"picture2", "Cars are small this year\n", "text/plain; charset=utf-8"}, // content sniff
1436 for _, trial := range trials {
1437 f, err := fs.OpenFile(trial.filename, os.O_CREATE|os.O_WRONLY, 0777)
1438 c.Assert(err, check.IsNil)
1439 _, err = f.Write([]byte(trial.content))
1440 c.Assert(err, check.IsNil)
1441 c.Assert(f.Close(), check.IsNil)
1443 mtxt, err := fs.MarshalManifest(".")
1444 c.Assert(err, check.IsNil)
1445 var coll arvados.Collection
1446 err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
1447 "collection": map[string]string{
1448 "manifest_text": mtxt,
1451 c.Assert(err, check.IsNil)
1453 for _, trial := range trials {
1454 u, _ := url.Parse("http://download.example.com/by_id/" + coll.UUID + "/" + trial.filename)
1455 req := &http.Request{
1459 RequestURI: u.RequestURI(),
1460 Header: http.Header{
1461 "Authorization": {"Bearer " + client.AuthToken},
1464 resp := httptest.NewRecorder()
1465 s.handler.ServeHTTP(resp, req)
1466 c.Check(resp.Code, check.Equals, http.StatusOK)
1467 c.Check(resp.Header().Get("Content-Type"), check.Matches, trial.contentType)
1468 c.Check(resp.Body.String(), check.Equals, trial.content)
1472 func (s *IntegrationSuite) TestKeepClientBlockCache(c *check.C) {
1473 s.handler.Cluster.Collections.WebDAVCache.MaxBlockEntries = 42
1474 c.Check(keepclient.DefaultBlockCache.MaxBlocks, check.Not(check.Equals), 42)
1475 u := mustParseURL("http://keep-web.example/c=" + arvadostest.FooCollection + "/t=" + arvadostest.ActiveToken + "/foo")
1476 req := &http.Request{
1480 RequestURI: u.RequestURI(),
1482 resp := httptest.NewRecorder()
1483 s.handler.ServeHTTP(resp, req)
1484 c.Check(resp.Code, check.Equals, http.StatusOK)
1485 c.Check(keepclient.DefaultBlockCache.MaxBlocks, check.Equals, 42)
1488 // Writing to a collection shouldn't affect its entry in the
1489 // PDH-to-manifest cache.
1490 func (s *IntegrationSuite) TestCacheWriteCollectionSamePDH(c *check.C) {
1491 arv, err := arvadosclient.MakeArvadosClient()
1492 c.Assert(err, check.Equals, nil)
1493 arv.ApiToken = arvadostest.ActiveToken
1495 u := mustParseURL("http://x.example/testfile")
1496 req := &http.Request{
1500 RequestURI: u.RequestURI(),
1501 Header: http.Header{"Authorization": {"Bearer " + arv.ApiToken}},
1504 checkWithID := func(id string, status int) {
1505 req.URL.Host = strings.Replace(id, "+", "-", -1) + ".example"
1506 req.Host = req.URL.Host
1507 resp := httptest.NewRecorder()
1508 s.handler.ServeHTTP(resp, req)
1509 c.Check(resp.Code, check.Equals, status)
1512 var colls [2]arvados.Collection
1513 for i := range colls {
1514 err := arv.Create("collections",
1515 map[string]interface{}{
1516 "ensure_unique_name": true,
1517 "collection": map[string]interface{}{
1518 "name": "test collection",
1521 c.Assert(err, check.Equals, nil)
1524 // Populate cache with empty collection
1525 checkWithID(colls[0].PortableDataHash, http.StatusNotFound)
1527 // write a file to colls[0]
1529 reqPut.Method = "PUT"
1530 reqPut.URL.Host = colls[0].UUID + ".example"
1531 reqPut.Host = req.URL.Host
1532 reqPut.Body = ioutil.NopCloser(bytes.NewBufferString("testdata"))
1533 resp := httptest.NewRecorder()
1534 s.handler.ServeHTTP(resp, &reqPut)
1535 c.Check(resp.Code, check.Equals, http.StatusCreated)
1537 // new file should not appear in colls[1]
1538 checkWithID(colls[1].PortableDataHash, http.StatusNotFound)
1539 checkWithID(colls[1].UUID, http.StatusNotFound)
1541 checkWithID(colls[0].UUID, http.StatusOK)
1544 func copyHeader(h http.Header) http.Header {
1546 for k, v := range h {
1547 hc[k] = append([]string(nil), v...)
1552 func (s *IntegrationSuite) checkUploadDownloadRequest(c *check.C, req *http.Request,
1553 successCode int, direction string, perm bool, userUuid, collectionUuid, collectionPDH, filepath string) {
1555 client := arvados.NewClientFromEnv()
1556 client.AuthToken = arvadostest.AdminToken
1557 var logentries arvados.LogList
1559 err := client.RequestAndDecode(&logentries, "GET", "arvados/v1/logs", nil,
1560 arvados.ResourceListParams{
1562 Order: "created_at desc"})
1563 c.Check(err, check.IsNil)
1564 c.Check(logentries.Items, check.HasLen, 1)
1565 lastLogId := logentries.Items[0].ID
1566 c.Logf("lastLogId: %d", lastLogId)
1568 var logbuf bytes.Buffer
1569 logger := logrus.New()
1570 logger.Out = &logbuf
1571 resp := httptest.NewRecorder()
1572 req = req.WithContext(ctxlog.Context(context.Background(), logger))
1573 s.handler.ServeHTTP(resp, req)
1576 c.Check(resp.Result().StatusCode, check.Equals, successCode)
1577 c.Check(logbuf.String(), check.Matches, `(?ms).*msg="File `+direction+`".*`)
1578 c.Check(logbuf.String(), check.Not(check.Matches), `(?ms).*level=error.*`)
1580 deadline := time.Now().Add(time.Second)
1582 c.Assert(time.Now().After(deadline), check.Equals, false, check.Commentf("timed out waiting for log entry"))
1583 logentries = arvados.LogList{}
1584 err = client.RequestAndDecode(&logentries, "GET", "arvados/v1/logs", nil,
1585 arvados.ResourceListParams{
1586 Filters: []arvados.Filter{
1587 {Attr: "event_type", Operator: "=", Operand: "file_" + direction},
1588 {Attr: "object_uuid", Operator: "=", Operand: userUuid},
1591 Order: "created_at desc",
1593 c.Assert(err, check.IsNil)
1594 if len(logentries.Items) > 0 &&
1595 logentries.Items[0].ID > lastLogId &&
1596 logentries.Items[0].ObjectUUID == userUuid &&
1597 logentries.Items[0].Properties["collection_uuid"] == collectionUuid &&
1598 (collectionPDH == "" || logentries.Items[0].Properties["portable_data_hash"] == collectionPDH) &&
1599 logentries.Items[0].Properties["collection_file_path"] == filepath {
1602 c.Logf("logentries.Items: %+v", logentries.Items)
1603 time.Sleep(50 * time.Millisecond)
1606 c.Check(resp.Result().StatusCode, check.Equals, http.StatusForbidden)
1607 c.Check(logbuf.String(), check.Equals, "")
1611 func (s *IntegrationSuite) TestDownloadLoggingPermission(c *check.C) {
1612 u := mustParseURL("http://" + arvadostest.FooCollection + ".keep-web.example/foo")
1614 s.handler.Cluster.Collections.TrustAllContent = true
1616 for _, adminperm := range []bool{true, false} {
1617 for _, userperm := range []bool{true, false} {
1618 s.handler.Cluster.Collections.WebDAVPermission.Admin.Download = adminperm
1619 s.handler.Cluster.Collections.WebDAVPermission.User.Download = userperm
1621 // Test admin permission
1622 req := &http.Request{
1626 RequestURI: u.RequestURI(),
1627 Header: http.Header{
1628 "Authorization": {"Bearer " + arvadostest.AdminToken},
1631 s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", adminperm,
1632 arvadostest.AdminUserUUID, arvadostest.FooCollection, arvadostest.FooCollectionPDH, "foo")
1634 // Test user permission
1635 req = &http.Request{
1639 RequestURI: u.RequestURI(),
1640 Header: http.Header{
1641 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1644 s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", userperm,
1645 arvadostest.ActiveUserUUID, arvadostest.FooCollection, arvadostest.FooCollectionPDH, "foo")
1649 s.handler.Cluster.Collections.WebDAVPermission.User.Download = true
1651 for _, tryurl := range []string{"http://" + arvadostest.MultilevelCollection1 + ".keep-web.example/dir1/subdir/file1",
1652 "http://keep-web/users/active/multilevel_collection_1/dir1/subdir/file1"} {
1654 u = mustParseURL(tryurl)
1655 req := &http.Request{
1659 RequestURI: u.RequestURI(),
1660 Header: http.Header{
1661 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1664 s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", true,
1665 arvadostest.ActiveUserUUID, arvadostest.MultilevelCollection1, arvadostest.MultilevelCollection1PDH, "dir1/subdir/file1")
1668 u = mustParseURL("http://" + strings.Replace(arvadostest.FooCollectionPDH, "+", "-", 1) + ".keep-web.example/foo")
1669 req := &http.Request{
1673 RequestURI: u.RequestURI(),
1674 Header: http.Header{
1675 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1678 s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", true,
1679 arvadostest.ActiveUserUUID, "", arvadostest.FooCollectionPDH, "foo")
1682 func (s *IntegrationSuite) TestUploadLoggingPermission(c *check.C) {
1683 for _, adminperm := range []bool{true, false} {
1684 for _, userperm := range []bool{true, false} {
1686 arv := arvados.NewClientFromEnv()
1687 arv.AuthToken = arvadostest.ActiveToken
1689 var coll arvados.Collection
1690 err := arv.RequestAndDecode(&coll,
1692 "/arvados/v1/collections",
1694 map[string]interface{}{
1695 "ensure_unique_name": true,
1696 "collection": map[string]interface{}{
1697 "name": "test collection",
1700 c.Assert(err, check.Equals, nil)
1702 u := mustParseURL("http://" + coll.UUID + ".keep-web.example/bar")
1704 s.handler.Cluster.Collections.WebDAVPermission.Admin.Upload = adminperm
1705 s.handler.Cluster.Collections.WebDAVPermission.User.Upload = userperm
1707 // Test admin permission
1708 req := &http.Request{
1712 RequestURI: u.RequestURI(),
1713 Header: http.Header{
1714 "Authorization": {"Bearer " + arvadostest.AdminToken},
1716 Body: io.NopCloser(bytes.NewReader([]byte("bar"))),
1718 s.checkUploadDownloadRequest(c, req, http.StatusCreated, "upload", adminperm,
1719 arvadostest.AdminUserUUID, coll.UUID, "", "bar")
1721 // Test user permission
1722 req = &http.Request{
1726 RequestURI: u.RequestURI(),
1727 Header: http.Header{
1728 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1730 Body: io.NopCloser(bytes.NewReader([]byte("bar"))),
1732 s.checkUploadDownloadRequest(c, req, http.StatusCreated, "upload", userperm,
1733 arvadostest.ActiveUserUUID, coll.UUID, "", "bar")
1738 func (s *IntegrationSuite) TestConcurrentWrites(c *check.C) {
1739 s.handler.Cluster.Collections.WebDAVCache.TTL = arvados.Duration(time.Second * 2)
1740 lockTidyInterval = time.Second
1741 client := arvados.NewClientFromEnv()
1742 client.AuthToken = arvadostest.ActiveTokenV2
1743 // Start small, and increase concurrency (2^2, 4^2, ...)
1744 // only until hitting failure. Avoids unnecessarily long
1746 for n := 2; n < 16 && !c.Failed(); n = n * 2 {
1747 c.Logf("%s: n=%d", c.TestName(), n)
1749 var coll arvados.Collection
1750 err := client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, nil)
1751 c.Assert(err, check.IsNil)
1752 defer client.RequestAndDecode(&coll, "DELETE", "arvados/v1/collections/"+coll.UUID, nil, nil)
1754 var wg sync.WaitGroup
1755 for i := 0; i < n && !c.Failed(); i++ {
1760 u := mustParseURL(fmt.Sprintf("http://%s.collections.example.com/i=%d", coll.UUID, i))
1761 resp := httptest.NewRecorder()
1762 req, err := http.NewRequest("MKCOL", u.String(), nil)
1763 c.Assert(err, check.IsNil)
1764 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
1765 s.handler.ServeHTTP(resp, req)
1766 c.Assert(resp.Code, check.Equals, http.StatusCreated)
1767 for j := 0; j < n && !c.Failed(); j++ {
1772 content := fmt.Sprintf("i=%d/j=%d", i, j)
1773 u := mustParseURL("http://" + coll.UUID + ".collections.example.com/" + content)
1775 resp := httptest.NewRecorder()
1776 req, err := http.NewRequest("PUT", u.String(), strings.NewReader(content))
1777 c.Assert(err, check.IsNil)
1778 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
1779 s.handler.ServeHTTP(resp, req)
1780 c.Check(resp.Code, check.Equals, http.StatusCreated)
1782 time.Sleep(time.Second)
1783 resp = httptest.NewRecorder()
1784 req, err = http.NewRequest("GET", u.String(), nil)
1785 c.Assert(err, check.IsNil)
1786 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
1787 s.handler.ServeHTTP(resp, req)
1788 c.Check(resp.Code, check.Equals, http.StatusOK)
1789 c.Check(resp.Body.String(), check.Equals, content)
1795 for i := 0; i < n; i++ {
1796 u := mustParseURL(fmt.Sprintf("http://%s.collections.example.com/i=%d", coll.UUID, i))
1797 resp := httptest.NewRecorder()
1798 req, err := http.NewRequest("PROPFIND", u.String(), &bytes.Buffer{})
1799 c.Assert(err, check.IsNil)
1800 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
1801 s.handler.ServeHTTP(resp, req)
1802 c.Assert(resp.Code, check.Equals, http.StatusMultiStatus)