1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "git.arvados.org/arvados.git/lib/config"
23 "git.arvados.org/arvados.git/sdk/go/arvados"
24 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
25 "git.arvados.org/arvados.git/sdk/go/arvadostest"
26 "git.arvados.org/arvados.git/sdk/go/auth"
27 "git.arvados.org/arvados.git/sdk/go/ctxlog"
28 "git.arvados.org/arvados.git/sdk/go/keepclient"
29 "github.com/sirupsen/logrus"
30 check "gopkg.in/check.v1"
33 var _ = check.Suite(&UnitSuite{})
35 type UnitSuite struct {
36 Config *arvados.Config
39 func (s *UnitSuite) SetUpTest(c *check.C) {
40 ldr := config.NewLoader(bytes.NewBufferString("Clusters: {zzzzz: {}}"), ctxlog.TestLogger(c))
42 cfg, err := ldr.Load()
43 c.Assert(err, check.IsNil)
47 func (s *UnitSuite) TestCORSPreflight(c *check.C) {
48 h := handler{Config: newConfig(s.Config)}
49 u := mustParseURL("http://keep-web.example/c=" + arvadostest.FooCollection + "/foo")
54 RequestURI: u.RequestURI(),
56 "Origin": {"https://workbench.example"},
57 "Access-Control-Request-Method": {"POST"},
61 // Check preflight for an allowed request
62 resp := httptest.NewRecorder()
63 h.ServeHTTP(resp, req)
64 c.Check(resp.Code, check.Equals, http.StatusOK)
65 c.Check(resp.Body.String(), check.Equals, "")
66 c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, "*")
67 c.Check(resp.Header().Get("Access-Control-Allow-Methods"), check.Equals, "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
68 c.Check(resp.Header().Get("Access-Control-Allow-Headers"), check.Equals, "Authorization, Content-Type, Range, Depth, Destination, If, Lock-Token, Overwrite, Timeout")
70 // Check preflight for a disallowed request
71 resp = httptest.NewRecorder()
72 req.Header.Set("Access-Control-Request-Method", "MAKE-COFFEE")
73 h.ServeHTTP(resp, req)
74 c.Check(resp.Body.String(), check.Equals, "")
75 c.Check(resp.Code, check.Equals, http.StatusMethodNotAllowed)
78 func (s *UnitSuite) TestEmptyResponse(c *check.C) {
79 for _, trial := range []struct {
85 // If we return no content due to a Keep read error,
86 // we should emit a log message.
87 {false, false, http.StatusOK, `(?ms).*only wrote 0 bytes.*`},
89 // If we return no content because the client sent an
90 // If-Modified-Since header, our response should be
91 // 304, and we should not emit a log message.
92 {true, true, http.StatusNotModified, ``},
94 c.Logf("trial: %+v", trial)
95 arvadostest.StartKeep(2, true)
97 arv, err := arvadosclient.MakeArvadosClient()
98 c.Assert(err, check.IsNil)
99 arv.ApiToken = arvadostest.ActiveToken
100 kc, err := keepclient.MakeKeepClient(arv)
101 c.Assert(err, check.IsNil)
102 _, _, err = kc.PutB([]byte("foo"))
103 c.Assert(err, check.IsNil)
106 h := handler{Config: newConfig(s.Config)}
107 u := mustParseURL("http://" + arvadostest.FooCollection + ".keep-web.example/foo")
108 req := &http.Request{
112 RequestURI: u.RequestURI(),
114 "Authorization": {"Bearer " + arvadostest.ActiveToken},
117 if trial.sendIMSHeader {
118 req.Header.Set("If-Modified-Since", strings.Replace(time.Now().UTC().Format(time.RFC1123), "UTC", "GMT", -1))
121 var logbuf bytes.Buffer
122 logger := logrus.New()
124 req = req.WithContext(ctxlog.Context(context.Background(), logger))
126 resp := httptest.NewRecorder()
127 h.ServeHTTP(resp, req)
128 c.Check(resp.Code, check.Equals, trial.expectStatus)
129 c.Check(resp.Body.String(), check.Equals, "")
131 c.Log(logbuf.String())
132 c.Check(logbuf.String(), check.Matches, trial.logRegexp)
136 func (s *UnitSuite) TestInvalidUUID(c *check.C) {
137 bogusID := strings.Replace(arvadostest.FooCollectionPDH, "+", "-", 1) + "-"
138 token := arvadostest.ActiveToken
139 for _, trial := range []string{
140 "http://keep-web/c=" + bogusID + "/foo",
141 "http://keep-web/c=" + bogusID + "/t=" + token + "/foo",
142 "http://keep-web/collections/download/" + bogusID + "/" + token + "/foo",
143 "http://keep-web/collections/" + bogusID + "/foo",
144 "http://" + bogusID + ".keep-web/" + bogusID + "/foo",
145 "http://" + bogusID + ".keep-web/t=" + token + "/" + bogusID + "/foo",
148 u := mustParseURL(trial)
149 req := &http.Request{
153 RequestURI: u.RequestURI(),
155 resp := httptest.NewRecorder()
156 cfg := newConfig(s.Config)
157 cfg.cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
158 h := handler{Config: cfg}
159 h.ServeHTTP(resp, req)
160 c.Check(resp.Code, check.Equals, http.StatusNotFound)
164 func mustParseURL(s string) *url.URL {
165 r, err := url.Parse(s)
167 panic("parse URL: " + s)
172 func (s *IntegrationSuite) TestVhost404(c *check.C) {
173 for _, testURL := range []string{
174 arvadostest.NonexistentCollection + ".example.com/theperthcountyconspiracy",
175 arvadostest.NonexistentCollection + ".example.com/t=" + arvadostest.ActiveToken + "/theperthcountyconspiracy",
177 resp := httptest.NewRecorder()
178 u := mustParseURL(testURL)
179 req := &http.Request{
182 RequestURI: u.RequestURI(),
184 s.testServer.Handler.ServeHTTP(resp, req)
185 c.Check(resp.Code, check.Equals, http.StatusNotFound)
186 c.Check(resp.Body.String(), check.Equals, notFoundMessage+"\n")
190 // An authorizer modifies an HTTP request to make use of the given
191 // token -- by adding it to a header, cookie, query param, or whatever
192 // -- and returns the HTTP status code we should expect from keep-web if
193 // the token is invalid.
194 type authorizer func(*http.Request, string) int
196 func (s *IntegrationSuite) TestVhostViaAuthzHeader(c *check.C) {
197 s.doVhostRequests(c, authzViaAuthzHeader)
199 func authzViaAuthzHeader(r *http.Request, tok string) int {
200 r.Header.Add("Authorization", "OAuth2 "+tok)
201 return http.StatusUnauthorized
204 func (s *IntegrationSuite) TestVhostViaCookieValue(c *check.C) {
205 s.doVhostRequests(c, authzViaCookieValue)
207 func authzViaCookieValue(r *http.Request, tok string) int {
208 r.AddCookie(&http.Cookie{
209 Name: "arvados_api_token",
210 Value: auth.EncodeTokenCookie([]byte(tok)),
212 return http.StatusUnauthorized
215 func (s *IntegrationSuite) TestVhostViaPath(c *check.C) {
216 s.doVhostRequests(c, authzViaPath)
218 func authzViaPath(r *http.Request, tok string) int {
219 r.URL.Path = "/t=" + tok + r.URL.Path
220 return http.StatusNotFound
223 func (s *IntegrationSuite) TestVhostViaQueryString(c *check.C) {
224 s.doVhostRequests(c, authzViaQueryString)
226 func authzViaQueryString(r *http.Request, tok string) int {
227 r.URL.RawQuery = "api_token=" + tok
228 return http.StatusUnauthorized
231 func (s *IntegrationSuite) TestVhostViaPOST(c *check.C) {
232 s.doVhostRequests(c, authzViaPOST)
234 func authzViaPOST(r *http.Request, tok string) int {
236 r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
237 r.Body = ioutil.NopCloser(strings.NewReader(
238 url.Values{"api_token": {tok}}.Encode()))
239 return http.StatusUnauthorized
242 func (s *IntegrationSuite) TestVhostViaXHRPOST(c *check.C) {
243 s.doVhostRequests(c, authzViaPOST)
245 func authzViaXHRPOST(r *http.Request, tok string) int {
247 r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
248 r.Header.Add("Origin", "https://origin.example")
249 r.Body = ioutil.NopCloser(strings.NewReader(
252 "disposition": {"attachment"},
254 return http.StatusUnauthorized
257 // Try some combinations of {url, token} using the given authorization
258 // mechanism, and verify the result is correct.
259 func (s *IntegrationSuite) doVhostRequests(c *check.C, authz authorizer) {
260 for _, hostPath := range []string{
261 arvadostest.FooCollection + ".example.com/foo",
262 arvadostest.FooCollection + "--collections.example.com/foo",
263 arvadostest.FooCollection + "--collections.example.com/_/foo",
264 arvadostest.FooCollectionPDH + ".example.com/foo",
265 strings.Replace(arvadostest.FooCollectionPDH, "+", "-", -1) + "--collections.example.com/foo",
266 arvadostest.FooBarDirCollection + ".example.com/dir1/foo",
268 c.Log("doRequests: ", hostPath)
269 s.doVhostRequestsWithHostPath(c, authz, hostPath)
273 func (s *IntegrationSuite) doVhostRequestsWithHostPath(c *check.C, authz authorizer, hostPath string) {
274 for _, tok := range []string{
275 arvadostest.ActiveToken,
276 arvadostest.ActiveToken[:15],
277 arvadostest.SpectatorToken,
281 u := mustParseURL("http://" + hostPath)
282 req := &http.Request{
286 RequestURI: u.RequestURI(),
287 Header: http.Header{},
289 failCode := authz(req, tok)
290 req, resp := s.doReq(req)
291 code, body := resp.Code, resp.Body.String()
293 // If the initial request had a (non-empty) token
294 // showing in the query string, we should have been
295 // redirected in order to hide it in a cookie.
296 c.Check(req.URL.String(), check.Not(check.Matches), `.*api_token=.+`)
298 if tok == arvadostest.ActiveToken {
299 c.Check(code, check.Equals, http.StatusOK)
300 c.Check(body, check.Equals, "foo")
302 c.Check(code >= 400, check.Equals, true)
303 c.Check(code < 500, check.Equals, true)
304 if tok == arvadostest.SpectatorToken {
305 // Valid token never offers to retry
306 // with different credentials.
307 c.Check(code, check.Equals, http.StatusNotFound)
309 // Invalid token can ask to retry
310 // depending on the authz method.
311 c.Check(code, check.Equals, failCode)
314 c.Check(body, check.Equals, notFoundMessage+"\n")
316 c.Check(body, check.Equals, unauthorizedMessage+"\n")
322 func (s *IntegrationSuite) doReq(req *http.Request) (*http.Request, *httptest.ResponseRecorder) {
323 resp := httptest.NewRecorder()
324 s.testServer.Handler.ServeHTTP(resp, req)
325 if resp.Code != http.StatusSeeOther {
328 cookies := (&http.Response{Header: resp.Header()}).Cookies()
329 u, _ := req.URL.Parse(resp.Header().Get("Location"))
334 RequestURI: u.RequestURI(),
335 Header: http.Header{},
337 for _, c := range cookies {
343 func (s *IntegrationSuite) TestVhostRedirectQueryTokenToCookie(c *check.C) {
344 s.testVhostRedirectTokenToCookie(c, "GET",
345 arvadostest.FooCollection+".example.com/foo",
346 "?api_token="+arvadostest.ActiveToken,
354 func (s *IntegrationSuite) TestSingleOriginSecretLink(c *check.C) {
355 s.testVhostRedirectTokenToCookie(c, "GET",
356 "example.com/c="+arvadostest.FooCollection+"/t="+arvadostest.ActiveToken+"/foo",
365 // Bad token in URL is 404 Not Found because it doesn't make sense to
366 // retry the same URL with different authorization.
367 func (s *IntegrationSuite) TestSingleOriginSecretLinkBadToken(c *check.C) {
368 s.testVhostRedirectTokenToCookie(c, "GET",
369 "example.com/c="+arvadostest.FooCollection+"/t=bogus/foo",
374 notFoundMessage+"\n",
378 // Bad token in a cookie (even if it got there via our own
379 // query-string-to-cookie redirect) is, in principle, retryable at the
380 // same URL so it's 401 Unauthorized.
381 func (s *IntegrationSuite) TestVhostRedirectQueryTokenToBogusCookie(c *check.C) {
382 s.testVhostRedirectTokenToCookie(c, "GET",
383 arvadostest.FooCollection+".example.com/foo",
384 "?api_token=thisisabogustoken",
387 http.StatusUnauthorized,
388 unauthorizedMessage+"\n",
392 func (s *IntegrationSuite) TestVhostRedirectQueryTokenSingleOriginError(c *check.C) {
393 s.testVhostRedirectTokenToCookie(c, "GET",
394 "example.com/c="+arvadostest.FooCollection+"/foo",
395 "?api_token="+arvadostest.ActiveToken,
398 http.StatusBadRequest,
399 "cannot serve inline content at this URL (possible configuration error; see https://doc.arvados.org/install/install-keep-web.html#dns)\n",
403 // If client requests an attachment by putting ?disposition=attachment
404 // in the query string, and gets redirected, the redirect target
405 // should respond with an attachment.
406 func (s *IntegrationSuite) TestVhostRedirectQueryTokenRequestAttachment(c *check.C) {
407 resp := s.testVhostRedirectTokenToCookie(c, "GET",
408 arvadostest.FooCollection+".example.com/foo",
409 "?disposition=attachment&api_token="+arvadostest.ActiveToken,
415 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
418 func (s *IntegrationSuite) TestVhostRedirectQueryTokenSiteFS(c *check.C) {
419 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
420 resp := s.testVhostRedirectTokenToCookie(c, "GET",
421 "download.example.com/by_id/"+arvadostest.FooCollection+"/foo",
422 "?api_token="+arvadostest.ActiveToken,
428 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
431 func (s *IntegrationSuite) TestPastCollectionVersionFileAccess(c *check.C) {
432 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
433 resp := s.testVhostRedirectTokenToCookie(c, "GET",
434 "download.example.com/c="+arvadostest.WazVersion1Collection+"/waz",
435 "?api_token="+arvadostest.ActiveToken,
441 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
442 resp = s.testVhostRedirectTokenToCookie(c, "GET",
443 "download.example.com/by_id/"+arvadostest.WazVersion1Collection+"/waz",
444 "?api_token="+arvadostest.ActiveToken,
450 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
453 func (s *IntegrationSuite) TestVhostRedirectQueryTokenTrustAllContent(c *check.C) {
454 s.testServer.Config.cluster.Collections.TrustAllContent = true
455 s.testVhostRedirectTokenToCookie(c, "GET",
456 "example.com/c="+arvadostest.FooCollection+"/foo",
457 "?api_token="+arvadostest.ActiveToken,
465 func (s *IntegrationSuite) TestVhostRedirectQueryTokenAttachmentOnlyHost(c *check.C) {
466 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "example.com:1234"
468 s.testVhostRedirectTokenToCookie(c, "GET",
469 "example.com/c="+arvadostest.FooCollection+"/foo",
470 "?api_token="+arvadostest.ActiveToken,
473 http.StatusBadRequest,
474 "cannot serve inline content at this URL (possible configuration error; see https://doc.arvados.org/install/install-keep-web.html#dns)\n",
477 resp := s.testVhostRedirectTokenToCookie(c, "GET",
478 "example.com:1234/c="+arvadostest.FooCollection+"/foo",
479 "?api_token="+arvadostest.ActiveToken,
485 c.Check(resp.Header().Get("Content-Disposition"), check.Equals, "attachment")
488 func (s *IntegrationSuite) TestVhostRedirectPOSTFormTokenToCookie(c *check.C) {
489 s.testVhostRedirectTokenToCookie(c, "POST",
490 arvadostest.FooCollection+".example.com/foo",
492 "application/x-www-form-urlencoded",
493 url.Values{"api_token": {arvadostest.ActiveToken}}.Encode(),
499 func (s *IntegrationSuite) TestVhostRedirectPOSTFormTokenToCookie404(c *check.C) {
500 s.testVhostRedirectTokenToCookie(c, "POST",
501 arvadostest.FooCollection+".example.com/foo",
503 "application/x-www-form-urlencoded",
504 url.Values{"api_token": {arvadostest.SpectatorToken}}.Encode(),
506 notFoundMessage+"\n",
510 func (s *IntegrationSuite) TestAnonymousTokenOK(c *check.C) {
511 s.testServer.Config.cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
512 s.testVhostRedirectTokenToCookie(c, "GET",
513 "example.com/c="+arvadostest.HelloWorldCollection+"/Hello%20world.txt",
522 func (s *IntegrationSuite) TestAnonymousTokenError(c *check.C) {
523 s.testServer.Config.cluster.Users.AnonymousUserToken = "anonymousTokenConfiguredButInvalid"
524 s.testVhostRedirectTokenToCookie(c, "GET",
525 "example.com/c="+arvadostest.HelloWorldCollection+"/Hello%20world.txt",
530 notFoundMessage+"\n",
534 func (s *IntegrationSuite) TestSpecialCharsInPath(c *check.C) {
535 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
537 client := s.testServer.Config.Client
538 client.AuthToken = arvadostest.ActiveToken
539 fs, err := (&arvados.Collection{}).FileSystem(&client, nil)
540 c.Assert(err, check.IsNil)
541 f, err := fs.OpenFile("https:\\\"odd' path chars", os.O_CREATE, 0777)
542 c.Assert(err, check.IsNil)
544 mtxt, err := fs.MarshalManifest(".")
545 c.Assert(err, check.IsNil)
546 var coll arvados.Collection
547 err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
548 "collection": map[string]string{
549 "manifest_text": mtxt,
552 c.Assert(err, check.IsNil)
554 u, _ := url.Parse("http://download.example.com/c=" + coll.UUID + "/")
555 req := &http.Request{
559 RequestURI: u.RequestURI(),
561 "Authorization": {"Bearer " + client.AuthToken},
564 resp := httptest.NewRecorder()
565 s.testServer.Handler.ServeHTTP(resp, req)
566 c.Check(resp.Code, check.Equals, http.StatusOK)
567 c.Check(resp.Body.String(), check.Matches, `(?ms).*href="./https:%5c%22odd%27%20path%20chars"\S+https:\\"odd' path chars.*`)
570 func (s *IntegrationSuite) TestForwardSlashSubstitution(c *check.C) {
571 arv := arvados.NewClientFromEnv()
572 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
573 s.testServer.Config.cluster.Collections.ForwardSlashNameSubstitution = "{SOLIDUS}"
574 name := "foo/bar/baz"
575 nameShown := strings.Replace(name, "/", "{SOLIDUS}", -1)
576 nameShownEscaped := strings.Replace(name, "/", "%7bSOLIDUS%7d", -1)
578 client := s.testServer.Config.Client
579 client.AuthToken = arvadostest.ActiveToken
580 fs, err := (&arvados.Collection{}).FileSystem(&client, nil)
581 c.Assert(err, check.IsNil)
582 f, err := fs.OpenFile("filename", os.O_CREATE, 0777)
583 c.Assert(err, check.IsNil)
585 mtxt, err := fs.MarshalManifest(".")
586 c.Assert(err, check.IsNil)
587 var coll arvados.Collection
588 err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
589 "collection": map[string]string{
590 "manifest_text": mtxt,
592 "owner_uuid": arvadostest.AProjectUUID,
595 c.Assert(err, check.IsNil)
596 defer arv.RequestAndDecode(&coll, "DELETE", "arvados/v1/collections/"+coll.UUID, nil, nil)
598 base := "http://download.example.com/by_id/" + coll.OwnerUUID + "/"
599 for tryURL, expectRegexp := range map[string]string{
600 base: `(?ms).*href="./` + nameShownEscaped + `/"\S+` + nameShown + `.*`,
601 base + nameShownEscaped + "/": `(?ms).*href="./filename"\S+filename.*`,
603 u, _ := url.Parse(tryURL)
604 req := &http.Request{
608 RequestURI: u.RequestURI(),
610 "Authorization": {"Bearer " + client.AuthToken},
613 resp := httptest.NewRecorder()
614 s.testServer.Handler.ServeHTTP(resp, req)
615 c.Check(resp.Code, check.Equals, http.StatusOK)
616 c.Check(resp.Body.String(), check.Matches, expectRegexp)
620 // XHRs can't follow redirect-with-cookie so they rely on method=POST
621 // and disposition=attachment (telling us it's acceptable to respond
622 // with content instead of a redirect) and an Origin header that gets
623 // added automatically by the browser (telling us it's desirable to do
625 func (s *IntegrationSuite) TestXHRNoRedirect(c *check.C) {
626 u, _ := url.Parse("http://example.com/c=" + arvadostest.FooCollection + "/foo")
627 req := &http.Request{
631 RequestURI: u.RequestURI(),
633 "Origin": {"https://origin.example"},
634 "Content-Type": {"application/x-www-form-urlencoded"},
636 Body: ioutil.NopCloser(strings.NewReader(url.Values{
637 "api_token": {arvadostest.ActiveToken},
638 "disposition": {"attachment"},
641 resp := httptest.NewRecorder()
642 s.testServer.Handler.ServeHTTP(resp, req)
643 c.Check(resp.Code, check.Equals, http.StatusOK)
644 c.Check(resp.Body.String(), check.Equals, "foo")
645 c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, "*")
647 // GET + Origin header is representative of both AJAX GET
648 // requests and inline images via <IMG crossorigin="anonymous"
650 u.RawQuery = "api_token=" + url.QueryEscape(arvadostest.ActiveTokenV2)
655 RequestURI: u.RequestURI(),
657 "Origin": {"https://origin.example"},
660 resp = httptest.NewRecorder()
661 s.testServer.Handler.ServeHTTP(resp, req)
662 c.Check(resp.Code, check.Equals, http.StatusOK)
663 c.Check(resp.Body.String(), check.Equals, "foo")
664 c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, "*")
667 func (s *IntegrationSuite) testVhostRedirectTokenToCookie(c *check.C, method, hostPath, queryString, contentType, reqBody string, expectStatus int, expectRespBody string) *httptest.ResponseRecorder {
668 u, _ := url.Parse(`http://` + hostPath + queryString)
669 req := &http.Request{
673 RequestURI: u.RequestURI(),
674 Header: http.Header{"Content-Type": {contentType}},
675 Body: ioutil.NopCloser(strings.NewReader(reqBody)),
678 resp := httptest.NewRecorder()
680 c.Check(resp.Code, check.Equals, expectStatus)
681 c.Check(resp.Body.String(), check.Equals, expectRespBody)
684 s.testServer.Handler.ServeHTTP(resp, req)
685 if resp.Code != http.StatusSeeOther {
688 c.Check(resp.Body.String(), check.Matches, `.*href="http://`+regexp.QuoteMeta(html.EscapeString(hostPath))+`(\?[^"]*)?".*`)
689 cookies := (&http.Response{Header: resp.Header()}).Cookies()
691 u, _ = u.Parse(resp.Header().Get("Location"))
696 RequestURI: u.RequestURI(),
697 Header: http.Header{},
699 for _, c := range cookies {
703 resp = httptest.NewRecorder()
704 s.testServer.Handler.ServeHTTP(resp, req)
705 c.Check(resp.Header().Get("Location"), check.Equals, "")
709 func (s *IntegrationSuite) TestDirectoryListingWithAnonymousToken(c *check.C) {
710 s.testServer.Config.cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
711 s.testDirectoryListing(c)
714 func (s *IntegrationSuite) TestDirectoryListingWithNoAnonymousToken(c *check.C) {
715 s.testServer.Config.cluster.Users.AnonymousUserToken = ""
716 s.testDirectoryListing(c)
719 func (s *IntegrationSuite) testDirectoryListing(c *check.C) {
720 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
721 authHeader := http.Header{
722 "Authorization": {"OAuth2 " + arvadostest.ActiveToken},
724 for _, trial := range []struct {
732 uri: strings.Replace(arvadostest.FooAndBarFilesInDirPDH, "+", "-", -1) + ".example.com/",
734 expect: []string{"dir1/foo", "dir1/bar"},
738 uri: strings.Replace(arvadostest.FooAndBarFilesInDirPDH, "+", "-", -1) + ".example.com/dir1/",
740 expect: []string{"foo", "bar"},
744 // URLs of this form ignore authHeader, and
745 // FooAndBarFilesInDirUUID isn't public, so
747 uri: "download.example.com/collections/" + arvadostest.FooAndBarFilesInDirUUID + "/",
752 uri: "download.example.com/users/active/foo_file_in_dir/",
754 expect: []string{"dir1/"},
758 uri: "download.example.com/users/active/foo_file_in_dir/dir1/",
760 expect: []string{"bar"},
764 uri: "download.example.com/",
766 expect: []string{"users/"},
770 uri: "download.example.com/users",
773 expect: []string{"active/"},
777 uri: "download.example.com/users/",
779 expect: []string{"active/"},
783 uri: "download.example.com/users/active",
785 redirect: "/users/active/",
786 expect: []string{"foo_file_in_dir/"},
790 uri: "download.example.com/users/active/",
792 expect: []string{"foo_file_in_dir/"},
796 uri: "collections.example.com/collections/download/" + arvadostest.FooAndBarFilesInDirUUID + "/" + arvadostest.ActiveToken + "/",
798 expect: []string{"dir1/foo", "dir1/bar"},
802 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/t=" + arvadostest.ActiveToken + "/",
804 expect: []string{"dir1/foo", "dir1/bar"},
808 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/t=" + arvadostest.ActiveToken,
810 expect: []string{"dir1/foo", "dir1/bar"},
814 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID,
816 expect: []string{"dir1/foo", "dir1/bar"},
820 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/dir1",
822 redirect: "/c=" + arvadostest.FooAndBarFilesInDirUUID + "/dir1/",
823 expect: []string{"foo", "bar"},
827 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/_/dir1/",
829 expect: []string{"foo", "bar"},
833 uri: arvadostest.FooAndBarFilesInDirUUID + ".example.com/dir1?api_token=" + arvadostest.ActiveToken,
836 expect: []string{"foo", "bar"},
840 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/theperthcountyconspiracydoesnotexist/",
845 uri: "download.example.com/c=" + arvadostest.WazVersion1Collection,
847 expect: []string{"waz"},
851 uri: "download.example.com/by_id/" + arvadostest.WazVersion1Collection,
853 expect: []string{"waz"},
857 comment := check.Commentf("HTML: %q => %q", trial.uri, trial.expect)
858 resp := httptest.NewRecorder()
859 u := mustParseURL("//" + trial.uri)
860 req := &http.Request{
864 RequestURI: u.RequestURI(),
865 Header: copyHeader(trial.header),
867 s.testServer.Handler.ServeHTTP(resp, req)
868 var cookies []*http.Cookie
869 for resp.Code == http.StatusSeeOther {
870 u, _ := req.URL.Parse(resp.Header().Get("Location"))
875 RequestURI: u.RequestURI(),
876 Header: copyHeader(trial.header),
878 cookies = append(cookies, (&http.Response{Header: resp.Header()}).Cookies()...)
879 for _, c := range cookies {
882 resp = httptest.NewRecorder()
883 s.testServer.Handler.ServeHTTP(resp, req)
885 if trial.redirect != "" {
886 c.Check(req.URL.Path, check.Equals, trial.redirect, comment)
888 if trial.expect == nil {
889 c.Check(resp.Code, check.Equals, http.StatusNotFound, comment)
891 c.Check(resp.Code, check.Equals, http.StatusOK, comment)
892 for _, e := range trial.expect {
893 c.Check(resp.Body.String(), check.Matches, `(?ms).*href="./`+e+`".*`, comment)
895 c.Check(resp.Body.String(), check.Matches, `(?ms).*--cut-dirs=`+fmt.Sprintf("%d", trial.cutDirs)+` .*`, comment)
898 comment = check.Commentf("WebDAV: %q => %q", trial.uri, trial.expect)
903 RequestURI: u.RequestURI(),
904 Header: copyHeader(trial.header),
905 Body: ioutil.NopCloser(&bytes.Buffer{}),
907 resp = httptest.NewRecorder()
908 s.testServer.Handler.ServeHTTP(resp, req)
909 if trial.expect == nil {
910 c.Check(resp.Code, check.Equals, http.StatusNotFound, comment)
912 c.Check(resp.Code, check.Equals, http.StatusOK, comment)
919 RequestURI: u.RequestURI(),
920 Header: copyHeader(trial.header),
921 Body: ioutil.NopCloser(&bytes.Buffer{}),
923 resp = httptest.NewRecorder()
924 s.testServer.Handler.ServeHTTP(resp, req)
925 if trial.expect == nil {
926 c.Check(resp.Code, check.Equals, http.StatusNotFound, comment)
928 c.Check(resp.Code, check.Equals, http.StatusMultiStatus, comment)
929 for _, e := range trial.expect {
930 if strings.HasSuffix(e, "/") {
931 e = filepath.Join(u.Path, e) + "/"
933 e = filepath.Join(u.Path, e)
935 c.Check(resp.Body.String(), check.Matches, `(?ms).*<D:href>`+e+`</D:href>.*`, comment)
941 func (s *IntegrationSuite) TestDeleteLastFile(c *check.C) {
942 arv := arvados.NewClientFromEnv()
943 var newCollection arvados.Collection
944 err := arv.RequestAndDecode(&newCollection, "POST", "arvados/v1/collections", nil, map[string]interface{}{
945 "collection": map[string]string{
946 "owner_uuid": arvadostest.ActiveUserUUID,
947 "manifest_text": ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo.txt 0:3:bar.txt\n",
948 "name": "keep-web test collection",
950 "ensure_unique_name": true,
952 c.Assert(err, check.IsNil)
953 defer arv.RequestAndDecode(&newCollection, "DELETE", "arvados/v1/collections/"+newCollection.UUID, nil, nil)
955 var updated arvados.Collection
956 for _, fnm := range []string{"foo.txt", "bar.txt"} {
957 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "example.com"
958 u, _ := url.Parse("http://example.com/c=" + newCollection.UUID + "/" + fnm)
959 req := &http.Request{
963 RequestURI: u.RequestURI(),
965 "Authorization": {"Bearer " + arvadostest.ActiveToken},
968 resp := httptest.NewRecorder()
969 s.testServer.Handler.ServeHTTP(resp, req)
970 c.Check(resp.Code, check.Equals, http.StatusNoContent)
972 updated = arvados.Collection{}
973 err = arv.RequestAndDecode(&updated, "GET", "arvados/v1/collections/"+newCollection.UUID, nil, nil)
974 c.Check(err, check.IsNil)
975 c.Check(updated.ManifestText, check.Not(check.Matches), `(?ms).*\Q`+fnm+`\E.*`)
976 c.Logf("updated manifest_text %q", updated.ManifestText)
978 c.Check(updated.ManifestText, check.Equals, "")
981 func (s *IntegrationSuite) TestHealthCheckPing(c *check.C) {
982 s.testServer.Config.cluster.ManagementToken = arvadostest.ManagementToken
983 authHeader := http.Header{
984 "Authorization": {"Bearer " + arvadostest.ManagementToken},
987 resp := httptest.NewRecorder()
988 u := mustParseURL("http://download.example.com/_health/ping")
989 req := &http.Request{
993 RequestURI: u.RequestURI(),
996 s.testServer.Handler.ServeHTTP(resp, req)
998 c.Check(resp.Code, check.Equals, http.StatusOK)
999 c.Check(resp.Body.String(), check.Matches, `{"health":"OK"}\n`)
1002 func (s *IntegrationSuite) TestFileContentType(c *check.C) {
1003 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
1005 client := s.testServer.Config.Client
1006 client.AuthToken = arvadostest.ActiveToken
1007 arv, err := arvadosclient.New(&client)
1008 c.Assert(err, check.Equals, nil)
1009 kc, err := keepclient.MakeKeepClient(arv)
1010 c.Assert(err, check.Equals, nil)
1012 fs, err := (&arvados.Collection{}).FileSystem(&client, kc)
1013 c.Assert(err, check.IsNil)
1015 trials := []struct {
1020 {"picture.txt", "BMX bikes are small this year\n", "text/plain; charset=utf-8"},
1021 {"picture.bmp", "BMX bikes are small this year\n", "image/x-ms-bmp"},
1022 {"picture.jpg", "BMX bikes are small this year\n", "image/jpeg"},
1023 {"picture1", "BMX bikes are small this year\n", "image/bmp"}, // content sniff; "BM" is the magic signature for .bmp
1024 {"picture2", "Cars are small this year\n", "text/plain; charset=utf-8"}, // content sniff
1026 for _, trial := range trials {
1027 f, err := fs.OpenFile(trial.filename, os.O_CREATE|os.O_WRONLY, 0777)
1028 c.Assert(err, check.IsNil)
1029 _, err = f.Write([]byte(trial.content))
1030 c.Assert(err, check.IsNil)
1031 c.Assert(f.Close(), check.IsNil)
1033 mtxt, err := fs.MarshalManifest(".")
1034 c.Assert(err, check.IsNil)
1035 var coll arvados.Collection
1036 err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
1037 "collection": map[string]string{
1038 "manifest_text": mtxt,
1041 c.Assert(err, check.IsNil)
1043 for _, trial := range trials {
1044 u, _ := url.Parse("http://download.example.com/by_id/" + coll.UUID + "/" + trial.filename)
1045 req := &http.Request{
1049 RequestURI: u.RequestURI(),
1050 Header: http.Header{
1051 "Authorization": {"Bearer " + client.AuthToken},
1054 resp := httptest.NewRecorder()
1055 s.testServer.Handler.ServeHTTP(resp, req)
1056 c.Check(resp.Code, check.Equals, http.StatusOK)
1057 c.Check(resp.Header().Get("Content-Type"), check.Equals, trial.contentType)
1058 c.Check(resp.Body.String(), check.Equals, trial.content)
1062 func (s *IntegrationSuite) TestKeepClientBlockCache(c *check.C) {
1063 s.testServer.Config.cluster.Collections.WebDAVCache.MaxBlockEntries = 42
1064 c.Check(keepclient.DefaultBlockCache.MaxBlocks, check.Not(check.Equals), 42)
1065 u := mustParseURL("http://keep-web.example/c=" + arvadostest.FooCollection + "/t=" + arvadostest.ActiveToken + "/foo")
1066 req := &http.Request{
1070 RequestURI: u.RequestURI(),
1072 resp := httptest.NewRecorder()
1073 s.testServer.Handler.ServeHTTP(resp, req)
1074 c.Check(resp.Code, check.Equals, http.StatusOK)
1075 c.Check(keepclient.DefaultBlockCache.MaxBlocks, check.Equals, 42)
1078 func copyHeader(h http.Header) http.Header {
1080 for k, v := range h {
1081 hc[k] = append([]string(nil), v...)