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) TestVhostViaAuthzHeaderOAuth2(c *check.C) {
197 s.doVhostRequests(c, authzViaAuthzHeaderOAuth2)
199 func authzViaAuthzHeaderOAuth2(r *http.Request, tok string) int {
200 r.Header.Add("Authorization", "Bearer "+tok)
201 return http.StatusUnauthorized
203 func (s *IntegrationSuite) TestVhostViaAuthzHeaderBearer(c *check.C) {
204 s.doVhostRequests(c, authzViaAuthzHeaderBearer)
206 func authzViaAuthzHeaderBearer(r *http.Request, tok string) int {
207 r.Header.Add("Authorization", "Bearer "+tok)
208 return http.StatusUnauthorized
211 func (s *IntegrationSuite) TestVhostViaCookieValue(c *check.C) {
212 s.doVhostRequests(c, authzViaCookieValue)
214 func authzViaCookieValue(r *http.Request, tok string) int {
215 r.AddCookie(&http.Cookie{
216 Name: "arvados_api_token",
217 Value: auth.EncodeTokenCookie([]byte(tok)),
219 return http.StatusUnauthorized
222 func (s *IntegrationSuite) TestVhostViaPath(c *check.C) {
223 s.doVhostRequests(c, authzViaPath)
225 func authzViaPath(r *http.Request, tok string) int {
226 r.URL.Path = "/t=" + tok + r.URL.Path
227 return http.StatusNotFound
230 func (s *IntegrationSuite) TestVhostViaQueryString(c *check.C) {
231 s.doVhostRequests(c, authzViaQueryString)
233 func authzViaQueryString(r *http.Request, tok string) int {
234 r.URL.RawQuery = "api_token=" + tok
235 return http.StatusUnauthorized
238 func (s *IntegrationSuite) TestVhostViaPOST(c *check.C) {
239 s.doVhostRequests(c, authzViaPOST)
241 func authzViaPOST(r *http.Request, tok string) int {
243 r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
244 r.Body = ioutil.NopCloser(strings.NewReader(
245 url.Values{"api_token": {tok}}.Encode()))
246 return http.StatusUnauthorized
249 func (s *IntegrationSuite) TestVhostViaXHRPOST(c *check.C) {
250 s.doVhostRequests(c, authzViaPOST)
252 func authzViaXHRPOST(r *http.Request, tok string) int {
254 r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
255 r.Header.Add("Origin", "https://origin.example")
256 r.Body = ioutil.NopCloser(strings.NewReader(
259 "disposition": {"attachment"},
261 return http.StatusUnauthorized
264 // Try some combinations of {url, token} using the given authorization
265 // mechanism, and verify the result is correct.
266 func (s *IntegrationSuite) doVhostRequests(c *check.C, authz authorizer) {
267 for _, hostPath := range []string{
268 arvadostest.FooCollection + ".example.com/foo",
269 arvadostest.FooCollection + "--collections.example.com/foo",
270 arvadostest.FooCollection + "--collections.example.com/_/foo",
271 arvadostest.FooCollectionPDH + ".example.com/foo",
272 strings.Replace(arvadostest.FooCollectionPDH, "+", "-", -1) + "--collections.example.com/foo",
273 arvadostest.FooBarDirCollection + ".example.com/dir1/foo",
275 c.Log("doRequests: ", hostPath)
276 s.doVhostRequestsWithHostPath(c, authz, hostPath)
280 func (s *IntegrationSuite) doVhostRequestsWithHostPath(c *check.C, authz authorizer, hostPath string) {
281 for _, tok := range []string{
282 arvadostest.ActiveToken,
283 arvadostest.ActiveToken[:15],
284 arvadostest.SpectatorToken,
288 u := mustParseURL("http://" + hostPath)
289 req := &http.Request{
293 RequestURI: u.RequestURI(),
294 Header: http.Header{},
296 failCode := authz(req, tok)
297 req, resp := s.doReq(req)
298 code, body := resp.Code, resp.Body.String()
300 // If the initial request had a (non-empty) token
301 // showing in the query string, we should have been
302 // redirected in order to hide it in a cookie.
303 c.Check(req.URL.String(), check.Not(check.Matches), `.*api_token=.+`)
305 if tok == arvadostest.ActiveToken {
306 c.Check(code, check.Equals, http.StatusOK)
307 c.Check(body, check.Equals, "foo")
309 c.Check(code >= 400, check.Equals, true)
310 c.Check(code < 500, check.Equals, true)
311 if tok == arvadostest.SpectatorToken {
312 // Valid token never offers to retry
313 // with different credentials.
314 c.Check(code, check.Equals, http.StatusNotFound)
316 // Invalid token can ask to retry
317 // depending on the authz method.
318 c.Check(code, check.Equals, failCode)
321 c.Check(body, check.Equals, notFoundMessage+"\n")
323 c.Check(body, check.Equals, unauthorizedMessage+"\n")
329 func (s *IntegrationSuite) TestVhostPortMatch(c *check.C) {
330 for _, port := range []string{"80", "443", "8000"} {
331 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = fmt.Sprintf("download.example.com:%v", port)
332 u := mustParseURL(fmt.Sprintf("http://download.example.com/by_id/%v/foo", arvadostest.FooCollection))
333 req := &http.Request{
337 RequestURI: u.RequestURI(),
338 Header: http.Header{"Authorization": []string{"Bearer " + arvadostest.ActiveToken}},
340 req, resp := s.doReq(req)
341 code, _ := resp.Code, resp.Body.String()
344 c.Check(code, check.Equals, 401)
346 c.Check(code, check.Equals, 200)
351 func (s *IntegrationSuite) doReq(req *http.Request) (*http.Request, *httptest.ResponseRecorder) {
352 resp := httptest.NewRecorder()
353 s.testServer.Handler.ServeHTTP(resp, req)
354 if resp.Code != http.StatusSeeOther {
357 cookies := (&http.Response{Header: resp.Header()}).Cookies()
358 u, _ := req.URL.Parse(resp.Header().Get("Location"))
363 RequestURI: u.RequestURI(),
364 Header: http.Header{},
366 for _, c := range cookies {
372 func (s *IntegrationSuite) TestVhostRedirectQueryTokenToCookie(c *check.C) {
373 s.testVhostRedirectTokenToCookie(c, "GET",
374 arvadostest.FooCollection+".example.com/foo",
375 "?api_token="+arvadostest.ActiveToken,
383 func (s *IntegrationSuite) TestSingleOriginSecretLink(c *check.C) {
384 s.testVhostRedirectTokenToCookie(c, "GET",
385 "example.com/c="+arvadostest.FooCollection+"/t="+arvadostest.ActiveToken+"/foo",
394 // Bad token in URL is 404 Not Found because it doesn't make sense to
395 // retry the same URL with different authorization.
396 func (s *IntegrationSuite) TestSingleOriginSecretLinkBadToken(c *check.C) {
397 s.testVhostRedirectTokenToCookie(c, "GET",
398 "example.com/c="+arvadostest.FooCollection+"/t=bogus/foo",
403 notFoundMessage+"\n",
407 // Bad token in a cookie (even if it got there via our own
408 // query-string-to-cookie redirect) is, in principle, retryable at the
409 // same URL so it's 401 Unauthorized.
410 func (s *IntegrationSuite) TestVhostRedirectQueryTokenToBogusCookie(c *check.C) {
411 s.testVhostRedirectTokenToCookie(c, "GET",
412 arvadostest.FooCollection+".example.com/foo",
413 "?api_token=thisisabogustoken",
416 http.StatusUnauthorized,
417 unauthorizedMessage+"\n",
421 func (s *IntegrationSuite) TestVhostRedirectQueryTokenSingleOriginError(c *check.C) {
422 s.testVhostRedirectTokenToCookie(c, "GET",
423 "example.com/c="+arvadostest.FooCollection+"/foo",
424 "?api_token="+arvadostest.ActiveToken,
427 http.StatusBadRequest,
428 "cannot serve inline content at this URL (possible configuration error; see https://doc.arvados.org/install/install-keep-web.html#dns)\n",
432 // If client requests an attachment by putting ?disposition=attachment
433 // in the query string, and gets redirected, the redirect target
434 // should respond with an attachment.
435 func (s *IntegrationSuite) TestVhostRedirectQueryTokenRequestAttachment(c *check.C) {
436 resp := s.testVhostRedirectTokenToCookie(c, "GET",
437 arvadostest.FooCollection+".example.com/foo",
438 "?disposition=attachment&api_token="+arvadostest.ActiveToken,
444 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
447 func (s *IntegrationSuite) TestVhostRedirectQueryTokenSiteFS(c *check.C) {
448 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
449 resp := s.testVhostRedirectTokenToCookie(c, "GET",
450 "download.example.com/by_id/"+arvadostest.FooCollection+"/foo",
451 "?api_token="+arvadostest.ActiveToken,
457 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
460 func (s *IntegrationSuite) TestPastCollectionVersionFileAccess(c *check.C) {
461 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
462 resp := s.testVhostRedirectTokenToCookie(c, "GET",
463 "download.example.com/c="+arvadostest.WazVersion1Collection+"/waz",
464 "?api_token="+arvadostest.ActiveToken,
470 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
471 resp = s.testVhostRedirectTokenToCookie(c, "GET",
472 "download.example.com/by_id/"+arvadostest.WazVersion1Collection+"/waz",
473 "?api_token="+arvadostest.ActiveToken,
479 c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
482 func (s *IntegrationSuite) TestVhostRedirectQueryTokenTrustAllContent(c *check.C) {
483 s.testServer.Config.cluster.Collections.TrustAllContent = true
484 s.testVhostRedirectTokenToCookie(c, "GET",
485 "example.com/c="+arvadostest.FooCollection+"/foo",
486 "?api_token="+arvadostest.ActiveToken,
494 func (s *IntegrationSuite) TestVhostRedirectQueryTokenAttachmentOnlyHost(c *check.C) {
495 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "example.com:1234"
497 s.testVhostRedirectTokenToCookie(c, "GET",
498 "example.com/c="+arvadostest.FooCollection+"/foo",
499 "?api_token="+arvadostest.ActiveToken,
502 http.StatusBadRequest,
503 "cannot serve inline content at this URL (possible configuration error; see https://doc.arvados.org/install/install-keep-web.html#dns)\n",
506 resp := s.testVhostRedirectTokenToCookie(c, "GET",
507 "example.com:1234/c="+arvadostest.FooCollection+"/foo",
508 "?api_token="+arvadostest.ActiveToken,
514 c.Check(resp.Header().Get("Content-Disposition"), check.Equals, "attachment")
517 func (s *IntegrationSuite) TestVhostRedirectPOSTFormTokenToCookie(c *check.C) {
518 s.testVhostRedirectTokenToCookie(c, "POST",
519 arvadostest.FooCollection+".example.com/foo",
521 "application/x-www-form-urlencoded",
522 url.Values{"api_token": {arvadostest.ActiveToken}}.Encode(),
528 func (s *IntegrationSuite) TestVhostRedirectPOSTFormTokenToCookie404(c *check.C) {
529 s.testVhostRedirectTokenToCookie(c, "POST",
530 arvadostest.FooCollection+".example.com/foo",
532 "application/x-www-form-urlencoded",
533 url.Values{"api_token": {arvadostest.SpectatorToken}}.Encode(),
535 notFoundMessage+"\n",
539 func (s *IntegrationSuite) TestAnonymousTokenOK(c *check.C) {
540 s.testServer.Config.cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
541 s.testVhostRedirectTokenToCookie(c, "GET",
542 "example.com/c="+arvadostest.HelloWorldCollection+"/Hello%20world.txt",
551 func (s *IntegrationSuite) TestAnonymousTokenError(c *check.C) {
552 s.testServer.Config.cluster.Users.AnonymousUserToken = "anonymousTokenConfiguredButInvalid"
553 s.testVhostRedirectTokenToCookie(c, "GET",
554 "example.com/c="+arvadostest.HelloWorldCollection+"/Hello%20world.txt",
559 notFoundMessage+"\n",
563 func (s *IntegrationSuite) TestSpecialCharsInPath(c *check.C) {
564 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
566 client := s.testServer.Config.Client
567 client.AuthToken = arvadostest.ActiveToken
568 fs, err := (&arvados.Collection{}).FileSystem(&client, nil)
569 c.Assert(err, check.IsNil)
570 f, err := fs.OpenFile("https:\\\"odd' path chars", os.O_CREATE, 0777)
571 c.Assert(err, check.IsNil)
573 mtxt, err := fs.MarshalManifest(".")
574 c.Assert(err, check.IsNil)
575 var coll arvados.Collection
576 err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
577 "collection": map[string]string{
578 "manifest_text": mtxt,
581 c.Assert(err, check.IsNil)
583 u, _ := url.Parse("http://download.example.com/c=" + coll.UUID + "/")
584 req := &http.Request{
588 RequestURI: u.RequestURI(),
590 "Authorization": {"Bearer " + client.AuthToken},
593 resp := httptest.NewRecorder()
594 s.testServer.Handler.ServeHTTP(resp, req)
595 c.Check(resp.Code, check.Equals, http.StatusOK)
596 c.Check(resp.Body.String(), check.Matches, `(?ms).*href="./https:%5c%22odd%27%20path%20chars"\S+https:\\"odd' path chars.*`)
599 func (s *IntegrationSuite) TestForwardSlashSubstitution(c *check.C) {
600 arv := arvados.NewClientFromEnv()
601 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
602 s.testServer.Config.cluster.Collections.ForwardSlashNameSubstitution = "{SOLIDUS}"
603 name := "foo/bar/baz"
604 nameShown := strings.Replace(name, "/", "{SOLIDUS}", -1)
605 nameShownEscaped := strings.Replace(name, "/", "%7bSOLIDUS%7d", -1)
607 client := s.testServer.Config.Client
608 client.AuthToken = arvadostest.ActiveToken
609 fs, err := (&arvados.Collection{}).FileSystem(&client, nil)
610 c.Assert(err, check.IsNil)
611 f, err := fs.OpenFile("filename", os.O_CREATE, 0777)
612 c.Assert(err, check.IsNil)
614 mtxt, err := fs.MarshalManifest(".")
615 c.Assert(err, check.IsNil)
616 var coll arvados.Collection
617 err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
618 "collection": map[string]string{
619 "manifest_text": mtxt,
621 "owner_uuid": arvadostest.AProjectUUID,
624 c.Assert(err, check.IsNil)
625 defer arv.RequestAndDecode(&coll, "DELETE", "arvados/v1/collections/"+coll.UUID, nil, nil)
627 base := "http://download.example.com/by_id/" + coll.OwnerUUID + "/"
628 for tryURL, expectRegexp := range map[string]string{
629 base: `(?ms).*href="./` + nameShownEscaped + `/"\S+` + nameShown + `.*`,
630 base + nameShownEscaped + "/": `(?ms).*href="./filename"\S+filename.*`,
632 u, _ := url.Parse(tryURL)
633 req := &http.Request{
637 RequestURI: u.RequestURI(),
639 "Authorization": {"Bearer " + client.AuthToken},
642 resp := httptest.NewRecorder()
643 s.testServer.Handler.ServeHTTP(resp, req)
644 c.Check(resp.Code, check.Equals, http.StatusOK)
645 c.Check(resp.Body.String(), check.Matches, expectRegexp)
649 // XHRs can't follow redirect-with-cookie so they rely on method=POST
650 // and disposition=attachment (telling us it's acceptable to respond
651 // with content instead of a redirect) and an Origin header that gets
652 // added automatically by the browser (telling us it's desirable to do
654 func (s *IntegrationSuite) TestXHRNoRedirect(c *check.C) {
655 u, _ := url.Parse("http://example.com/c=" + arvadostest.FooCollection + "/foo")
656 req := &http.Request{
660 RequestURI: u.RequestURI(),
662 "Origin": {"https://origin.example"},
663 "Content-Type": {"application/x-www-form-urlencoded"},
665 Body: ioutil.NopCloser(strings.NewReader(url.Values{
666 "api_token": {arvadostest.ActiveToken},
667 "disposition": {"attachment"},
670 resp := httptest.NewRecorder()
671 s.testServer.Handler.ServeHTTP(resp, req)
672 c.Check(resp.Code, check.Equals, http.StatusOK)
673 c.Check(resp.Body.String(), check.Equals, "foo")
674 c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, "*")
676 // GET + Origin header is representative of both AJAX GET
677 // requests and inline images via <IMG crossorigin="anonymous"
679 u.RawQuery = "api_token=" + url.QueryEscape(arvadostest.ActiveTokenV2)
684 RequestURI: u.RequestURI(),
686 "Origin": {"https://origin.example"},
689 resp = httptest.NewRecorder()
690 s.testServer.Handler.ServeHTTP(resp, req)
691 c.Check(resp.Code, check.Equals, http.StatusOK)
692 c.Check(resp.Body.String(), check.Equals, "foo")
693 c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, "*")
696 func (s *IntegrationSuite) testVhostRedirectTokenToCookie(c *check.C, method, hostPath, queryString, contentType, reqBody string, expectStatus int, expectRespBody string) *httptest.ResponseRecorder {
697 u, _ := url.Parse(`http://` + hostPath + queryString)
698 req := &http.Request{
702 RequestURI: u.RequestURI(),
703 Header: http.Header{"Content-Type": {contentType}},
704 Body: ioutil.NopCloser(strings.NewReader(reqBody)),
707 resp := httptest.NewRecorder()
709 c.Check(resp.Code, check.Equals, expectStatus)
710 c.Check(resp.Body.String(), check.Equals, expectRespBody)
713 s.testServer.Handler.ServeHTTP(resp, req)
714 if resp.Code != http.StatusSeeOther {
717 c.Check(resp.Body.String(), check.Matches, `.*href="http://`+regexp.QuoteMeta(html.EscapeString(hostPath))+`(\?[^"]*)?".*`)
718 cookies := (&http.Response{Header: resp.Header()}).Cookies()
720 u, _ = u.Parse(resp.Header().Get("Location"))
725 RequestURI: u.RequestURI(),
726 Header: http.Header{},
728 for _, c := range cookies {
732 resp = httptest.NewRecorder()
733 s.testServer.Handler.ServeHTTP(resp, req)
734 c.Check(resp.Header().Get("Location"), check.Equals, "")
738 func (s *IntegrationSuite) TestDirectoryListingWithAnonymousToken(c *check.C) {
739 s.testServer.Config.cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
740 s.testDirectoryListing(c)
743 func (s *IntegrationSuite) TestDirectoryListingWithNoAnonymousToken(c *check.C) {
744 s.testServer.Config.cluster.Users.AnonymousUserToken = ""
745 s.testDirectoryListing(c)
748 func (s *IntegrationSuite) testDirectoryListing(c *check.C) {
749 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
750 authHeader := http.Header{
751 "Authorization": {"OAuth2 " + arvadostest.ActiveToken},
753 for _, trial := range []struct {
761 uri: strings.Replace(arvadostest.FooAndBarFilesInDirPDH, "+", "-", -1) + ".example.com/",
763 expect: []string{"dir1/foo", "dir1/bar"},
767 uri: strings.Replace(arvadostest.FooAndBarFilesInDirPDH, "+", "-", -1) + ".example.com/dir1/",
769 expect: []string{"foo", "bar"},
773 // URLs of this form ignore authHeader, and
774 // FooAndBarFilesInDirUUID isn't public, so
776 uri: "download.example.com/collections/" + arvadostest.FooAndBarFilesInDirUUID + "/",
781 uri: "download.example.com/users/active/foo_file_in_dir/",
783 expect: []string{"dir1/"},
787 uri: "download.example.com/users/active/foo_file_in_dir/dir1/",
789 expect: []string{"bar"},
793 uri: "download.example.com/",
795 expect: []string{"users/"},
799 uri: "download.example.com/users",
802 expect: []string{"active/"},
806 uri: "download.example.com/users/",
808 expect: []string{"active/"},
812 uri: "download.example.com/users/active",
814 redirect: "/users/active/",
815 expect: []string{"foo_file_in_dir/"},
819 uri: "download.example.com/users/active/",
821 expect: []string{"foo_file_in_dir/"},
825 uri: "collections.example.com/collections/download/" + arvadostest.FooAndBarFilesInDirUUID + "/" + arvadostest.ActiveToken + "/",
827 expect: []string{"dir1/foo", "dir1/bar"},
831 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/t=" + arvadostest.ActiveToken + "/",
833 expect: []string{"dir1/foo", "dir1/bar"},
837 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/t=" + arvadostest.ActiveToken,
839 expect: []string{"dir1/foo", "dir1/bar"},
843 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID,
845 expect: []string{"dir1/foo", "dir1/bar"},
849 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/dir1",
851 redirect: "/c=" + arvadostest.FooAndBarFilesInDirUUID + "/dir1/",
852 expect: []string{"foo", "bar"},
856 uri: "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/_/dir1/",
858 expect: []string{"foo", "bar"},
862 uri: arvadostest.FooAndBarFilesInDirUUID + ".example.com/dir1?api_token=" + arvadostest.ActiveToken,
865 expect: []string{"foo", "bar"},
869 uri: "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/theperthcountyconspiracydoesnotexist/",
874 uri: "download.example.com/c=" + arvadostest.WazVersion1Collection,
876 expect: []string{"waz"},
880 uri: "download.example.com/by_id/" + arvadostest.WazVersion1Collection,
882 expect: []string{"waz"},
886 comment := check.Commentf("HTML: %q => %q", trial.uri, trial.expect)
887 resp := httptest.NewRecorder()
888 u := mustParseURL("//" + trial.uri)
889 req := &http.Request{
893 RequestURI: u.RequestURI(),
894 Header: copyHeader(trial.header),
896 s.testServer.Handler.ServeHTTP(resp, req)
897 var cookies []*http.Cookie
898 for resp.Code == http.StatusSeeOther {
899 u, _ := req.URL.Parse(resp.Header().Get("Location"))
904 RequestURI: u.RequestURI(),
905 Header: copyHeader(trial.header),
907 cookies = append(cookies, (&http.Response{Header: resp.Header()}).Cookies()...)
908 for _, c := range cookies {
911 resp = httptest.NewRecorder()
912 s.testServer.Handler.ServeHTTP(resp, req)
914 if trial.redirect != "" {
915 c.Check(req.URL.Path, check.Equals, trial.redirect, comment)
917 if trial.expect == nil {
918 if s.testServer.Config.cluster.Users.AnonymousUserToken == "" {
919 c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
921 c.Check(resp.Code, check.Equals, http.StatusNotFound, comment)
924 c.Check(resp.Code, check.Equals, http.StatusOK, comment)
925 for _, e := range trial.expect {
926 c.Check(resp.Body.String(), check.Matches, `(?ms).*href="./`+e+`".*`, comment)
928 c.Check(resp.Body.String(), check.Matches, `(?ms).*--cut-dirs=`+fmt.Sprintf("%d", trial.cutDirs)+` .*`, comment)
931 comment = check.Commentf("WebDAV: %q => %q", trial.uri, trial.expect)
936 RequestURI: u.RequestURI(),
937 Header: copyHeader(trial.header),
938 Body: ioutil.NopCloser(&bytes.Buffer{}),
940 resp = httptest.NewRecorder()
941 s.testServer.Handler.ServeHTTP(resp, req)
942 if trial.expect == nil {
943 if s.testServer.Config.cluster.Users.AnonymousUserToken == "" {
944 c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
946 c.Check(resp.Code, check.Equals, http.StatusNotFound, comment)
949 c.Check(resp.Code, check.Equals, http.StatusOK, comment)
956 RequestURI: u.RequestURI(),
957 Header: copyHeader(trial.header),
958 Body: ioutil.NopCloser(&bytes.Buffer{}),
960 resp = httptest.NewRecorder()
961 s.testServer.Handler.ServeHTTP(resp, req)
962 if trial.expect == nil {
963 if s.testServer.Config.cluster.Users.AnonymousUserToken == "" {
964 c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
966 c.Check(resp.Code, check.Equals, http.StatusNotFound, comment)
969 c.Check(resp.Code, check.Equals, http.StatusMultiStatus, comment)
970 for _, e := range trial.expect {
971 if strings.HasSuffix(e, "/") {
972 e = filepath.Join(u.Path, e) + "/"
974 e = filepath.Join(u.Path, e)
976 c.Check(resp.Body.String(), check.Matches, `(?ms).*<D:href>`+e+`</D:href>.*`, comment)
982 func (s *IntegrationSuite) TestDeleteLastFile(c *check.C) {
983 arv := arvados.NewClientFromEnv()
984 var newCollection arvados.Collection
985 err := arv.RequestAndDecode(&newCollection, "POST", "arvados/v1/collections", nil, map[string]interface{}{
986 "collection": map[string]string{
987 "owner_uuid": arvadostest.ActiveUserUUID,
988 "manifest_text": ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo.txt 0:3:bar.txt\n",
989 "name": "keep-web test collection",
991 "ensure_unique_name": true,
993 c.Assert(err, check.IsNil)
994 defer arv.RequestAndDecode(&newCollection, "DELETE", "arvados/v1/collections/"+newCollection.UUID, nil, nil)
996 var updated arvados.Collection
997 for _, fnm := range []string{"foo.txt", "bar.txt"} {
998 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "example.com"
999 u, _ := url.Parse("http://example.com/c=" + newCollection.UUID + "/" + fnm)
1000 req := &http.Request{
1004 RequestURI: u.RequestURI(),
1005 Header: http.Header{
1006 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1009 resp := httptest.NewRecorder()
1010 s.testServer.Handler.ServeHTTP(resp, req)
1011 c.Check(resp.Code, check.Equals, http.StatusNoContent)
1013 updated = arvados.Collection{}
1014 err = arv.RequestAndDecode(&updated, "GET", "arvados/v1/collections/"+newCollection.UUID, nil, nil)
1015 c.Check(err, check.IsNil)
1016 c.Check(updated.ManifestText, check.Not(check.Matches), `(?ms).*\Q`+fnm+`\E.*`)
1017 c.Logf("updated manifest_text %q", updated.ManifestText)
1019 c.Check(updated.ManifestText, check.Equals, "")
1022 func (s *IntegrationSuite) TestHealthCheckPing(c *check.C) {
1023 s.testServer.Config.cluster.ManagementToken = arvadostest.ManagementToken
1024 authHeader := http.Header{
1025 "Authorization": {"Bearer " + arvadostest.ManagementToken},
1028 resp := httptest.NewRecorder()
1029 u := mustParseURL("http://download.example.com/_health/ping")
1030 req := &http.Request{
1034 RequestURI: u.RequestURI(),
1037 s.testServer.Handler.ServeHTTP(resp, req)
1039 c.Check(resp.Code, check.Equals, http.StatusOK)
1040 c.Check(resp.Body.String(), check.Matches, `{"health":"OK"}\n`)
1043 func (s *IntegrationSuite) TestFileContentType(c *check.C) {
1044 s.testServer.Config.cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
1046 client := s.testServer.Config.Client
1047 client.AuthToken = arvadostest.ActiveToken
1048 arv, err := arvadosclient.New(&client)
1049 c.Assert(err, check.Equals, nil)
1050 kc, err := keepclient.MakeKeepClient(arv)
1051 c.Assert(err, check.Equals, nil)
1053 fs, err := (&arvados.Collection{}).FileSystem(&client, kc)
1054 c.Assert(err, check.IsNil)
1056 trials := []struct {
1061 {"picture.txt", "BMX bikes are small this year\n", "text/plain; charset=utf-8"},
1062 {"picture.bmp", "BMX bikes are small this year\n", "image/x-ms-bmp"},
1063 {"picture.jpg", "BMX bikes are small this year\n", "image/jpeg"},
1064 {"picture1", "BMX bikes are small this year\n", "image/bmp"}, // content sniff; "BM" is the magic signature for .bmp
1065 {"picture2", "Cars are small this year\n", "text/plain; charset=utf-8"}, // content sniff
1067 for _, trial := range trials {
1068 f, err := fs.OpenFile(trial.filename, os.O_CREATE|os.O_WRONLY, 0777)
1069 c.Assert(err, check.IsNil)
1070 _, err = f.Write([]byte(trial.content))
1071 c.Assert(err, check.IsNil)
1072 c.Assert(f.Close(), check.IsNil)
1074 mtxt, err := fs.MarshalManifest(".")
1075 c.Assert(err, check.IsNil)
1076 var coll arvados.Collection
1077 err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
1078 "collection": map[string]string{
1079 "manifest_text": mtxt,
1082 c.Assert(err, check.IsNil)
1084 for _, trial := range trials {
1085 u, _ := url.Parse("http://download.example.com/by_id/" + coll.UUID + "/" + trial.filename)
1086 req := &http.Request{
1090 RequestURI: u.RequestURI(),
1091 Header: http.Header{
1092 "Authorization": {"Bearer " + client.AuthToken},
1095 resp := httptest.NewRecorder()
1096 s.testServer.Handler.ServeHTTP(resp, req)
1097 c.Check(resp.Code, check.Equals, http.StatusOK)
1098 c.Check(resp.Header().Get("Content-Type"), check.Equals, trial.contentType)
1099 c.Check(resp.Body.String(), check.Equals, trial.content)
1103 func (s *IntegrationSuite) TestKeepClientBlockCache(c *check.C) {
1104 s.testServer.Config.cluster.Collections.WebDAVCache.MaxBlockEntries = 42
1105 c.Check(keepclient.DefaultBlockCache.MaxBlocks, check.Not(check.Equals), 42)
1106 u := mustParseURL("http://keep-web.example/c=" + arvadostest.FooCollection + "/t=" + arvadostest.ActiveToken + "/foo")
1107 req := &http.Request{
1111 RequestURI: u.RequestURI(),
1113 resp := httptest.NewRecorder()
1114 s.testServer.Handler.ServeHTTP(resp, req)
1115 c.Check(resp.Code, check.Equals, http.StatusOK)
1116 c.Check(keepclient.DefaultBlockCache.MaxBlocks, check.Equals, 42)
1119 func copyHeader(h http.Header) http.Header {
1121 for k, v := range h {
1122 hc[k] = append([]string(nil), v...)