19963: Enable login flow without anonymous token configured.
[arvados.git] / services / keep-web / handler_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package keepweb
6
7 import (
8         "bytes"
9         "context"
10         "fmt"
11         "html"
12         "io"
13         "io/ioutil"
14         "net/http"
15         "net/http/httptest"
16         "net/url"
17         "os"
18         "path/filepath"
19         "regexp"
20         "strings"
21         "time"
22
23         "git.arvados.org/arvados.git/lib/config"
24         "git.arvados.org/arvados.git/sdk/go/arvados"
25         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
26         "git.arvados.org/arvados.git/sdk/go/arvadostest"
27         "git.arvados.org/arvados.git/sdk/go/auth"
28         "git.arvados.org/arvados.git/sdk/go/ctxlog"
29         "git.arvados.org/arvados.git/sdk/go/keepclient"
30         "github.com/prometheus/client_golang/prometheus"
31         "github.com/sirupsen/logrus"
32         check "gopkg.in/check.v1"
33 )
34
35 var _ = check.Suite(&UnitSuite{})
36
37 func init() {
38         arvados.DebugLocksPanicMode = true
39 }
40
41 type UnitSuite struct {
42         cluster *arvados.Cluster
43         handler *handler
44 }
45
46 func (s *UnitSuite) SetUpTest(c *check.C) {
47         logger := ctxlog.TestLogger(c)
48         ldr := config.NewLoader(bytes.NewBufferString("Clusters: {zzzzz: {}}"), logger)
49         ldr.Path = "-"
50         cfg, err := ldr.Load()
51         c.Assert(err, check.IsNil)
52         cc, err := cfg.GetCluster("")
53         c.Assert(err, check.IsNil)
54         s.cluster = cc
55         s.handler = &handler{
56                 Cluster: cc,
57                 Cache: cache{
58                         cluster:  cc,
59                         logger:   logger,
60                         registry: prometheus.NewRegistry(),
61                 },
62         }
63 }
64
65 func (s *UnitSuite) TestCORSPreflight(c *check.C) {
66         h := s.handler
67         u := mustParseURL("http://keep-web.example/c=" + arvadostest.FooCollection + "/foo")
68         req := &http.Request{
69                 Method:     "OPTIONS",
70                 Host:       u.Host,
71                 URL:        u,
72                 RequestURI: u.RequestURI(),
73                 Header: http.Header{
74                         "Origin":                        {"https://workbench.example"},
75                         "Access-Control-Request-Method": {"POST"},
76                 },
77         }
78
79         // Check preflight for an allowed request
80         resp := httptest.NewRecorder()
81         h.ServeHTTP(resp, req)
82         c.Check(resp.Code, check.Equals, http.StatusOK)
83         c.Check(resp.Body.String(), check.Equals, "")
84         c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, "*")
85         c.Check(resp.Header().Get("Access-Control-Allow-Methods"), check.Equals, "COPY, DELETE, GET, LOCK, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, RMCOL, UNLOCK")
86         c.Check(resp.Header().Get("Access-Control-Allow-Headers"), check.Equals, "Authorization, Content-Type, Range, Depth, Destination, If, Lock-Token, Overwrite, Timeout")
87
88         // Check preflight for a disallowed request
89         resp = httptest.NewRecorder()
90         req.Header.Set("Access-Control-Request-Method", "MAKE-COFFEE")
91         h.ServeHTTP(resp, req)
92         c.Check(resp.Body.String(), check.Equals, "")
93         c.Check(resp.Code, check.Equals, http.StatusMethodNotAllowed)
94 }
95
96 func (s *UnitSuite) TestEmptyResponse(c *check.C) {
97         for _, trial := range []struct {
98                 dataExists    bool
99                 sendIMSHeader bool
100                 expectStatus  int
101                 logRegexp     string
102         }{
103                 // If we return no content due to a Keep read error,
104                 // we should emit a log message.
105                 {false, false, http.StatusOK, `(?ms).*only wrote 0 bytes.*`},
106
107                 // If we return no content because the client sent an
108                 // If-Modified-Since header, our response should be
109                 // 304.  We still expect a "File download" log since it
110                 // counts as a file access for auditing.
111                 {true, true, http.StatusNotModified, `(?ms).*msg="File download".*`},
112         } {
113                 c.Logf("trial: %+v", trial)
114                 arvadostest.StartKeep(2, true)
115                 if trial.dataExists {
116                         arv, err := arvadosclient.MakeArvadosClient()
117                         c.Assert(err, check.IsNil)
118                         arv.ApiToken = arvadostest.ActiveToken
119                         kc, err := keepclient.MakeKeepClient(arv)
120                         c.Assert(err, check.IsNil)
121                         _, _, err = kc.PutB([]byte("foo"))
122                         c.Assert(err, check.IsNil)
123                 }
124
125                 u := mustParseURL("http://" + arvadostest.FooCollection + ".keep-web.example/foo")
126                 req := &http.Request{
127                         Method:     "GET",
128                         Host:       u.Host,
129                         URL:        u,
130                         RequestURI: u.RequestURI(),
131                         Header: http.Header{
132                                 "Authorization": {"Bearer " + arvadostest.ActiveToken},
133                         },
134                 }
135                 if trial.sendIMSHeader {
136                         req.Header.Set("If-Modified-Since", strings.Replace(time.Now().UTC().Format(time.RFC1123), "UTC", "GMT", -1))
137                 }
138
139                 var logbuf bytes.Buffer
140                 logger := logrus.New()
141                 logger.Out = &logbuf
142                 req = req.WithContext(ctxlog.Context(context.Background(), logger))
143
144                 resp := httptest.NewRecorder()
145                 s.handler.ServeHTTP(resp, req)
146                 c.Check(resp.Code, check.Equals, trial.expectStatus)
147                 c.Check(resp.Body.String(), check.Equals, "")
148
149                 c.Log(logbuf.String())
150                 c.Check(logbuf.String(), check.Matches, trial.logRegexp)
151         }
152 }
153
154 func (s *UnitSuite) TestInvalidUUID(c *check.C) {
155         bogusID := strings.Replace(arvadostest.FooCollectionPDH, "+", "-", 1) + "-"
156         token := arvadostest.ActiveToken
157         for _, trial := range []string{
158                 "http://keep-web/c=" + bogusID + "/foo",
159                 "http://keep-web/c=" + bogusID + "/t=" + token + "/foo",
160                 "http://keep-web/collections/download/" + bogusID + "/" + token + "/foo",
161                 "http://keep-web/collections/" + bogusID + "/foo",
162                 "http://" + bogusID + ".keep-web/" + bogusID + "/foo",
163                 "http://" + bogusID + ".keep-web/t=" + token + "/" + bogusID + "/foo",
164         } {
165                 c.Log(trial)
166                 u := mustParseURL(trial)
167                 req := &http.Request{
168                         Method:     "GET",
169                         Host:       u.Host,
170                         URL:        u,
171                         RequestURI: u.RequestURI(),
172                 }
173                 resp := httptest.NewRecorder()
174                 s.cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
175                 s.handler.ServeHTTP(resp, req)
176                 c.Check(resp.Code, check.Equals, http.StatusNotFound)
177         }
178 }
179
180 func mustParseURL(s string) *url.URL {
181         r, err := url.Parse(s)
182         if err != nil {
183                 panic("parse URL: " + s)
184         }
185         return r
186 }
187
188 func (s *IntegrationSuite) TestVhost404(c *check.C) {
189         for _, testURL := range []string{
190                 arvadostest.NonexistentCollection + ".example.com/theperthcountyconspiracy",
191                 arvadostest.NonexistentCollection + ".example.com/t=" + arvadostest.ActiveToken + "/theperthcountyconspiracy",
192         } {
193                 resp := httptest.NewRecorder()
194                 u := mustParseURL(testURL)
195                 req := &http.Request{
196                         Method:     "GET",
197                         URL:        u,
198                         RequestURI: u.RequestURI(),
199                 }
200                 s.handler.ServeHTTP(resp, req)
201                 c.Check(resp.Code, check.Equals, http.StatusNotFound)
202                 c.Check(resp.Body.String(), check.Equals, notFoundMessage+"\n")
203         }
204 }
205
206 // An authorizer modifies an HTTP request to make use of the given
207 // token -- by adding it to a header, cookie, query param, or whatever
208 // -- and returns the HTTP status code we should expect from keep-web if
209 // the token is invalid.
210 type authorizer func(*http.Request, string) int
211
212 func (s *IntegrationSuite) TestVhostViaAuthzHeaderOAuth2(c *check.C) {
213         s.doVhostRequests(c, authzViaAuthzHeaderOAuth2)
214 }
215 func authzViaAuthzHeaderOAuth2(r *http.Request, tok string) int {
216         r.Header.Add("Authorization", "Bearer "+tok)
217         return http.StatusUnauthorized
218 }
219 func (s *IntegrationSuite) TestVhostViaAuthzHeaderBearer(c *check.C) {
220         s.doVhostRequests(c, authzViaAuthzHeaderBearer)
221 }
222 func authzViaAuthzHeaderBearer(r *http.Request, tok string) int {
223         r.Header.Add("Authorization", "Bearer "+tok)
224         return http.StatusUnauthorized
225 }
226
227 func (s *IntegrationSuite) TestVhostViaCookieValue(c *check.C) {
228         s.doVhostRequests(c, authzViaCookieValue)
229 }
230 func authzViaCookieValue(r *http.Request, tok string) int {
231         r.AddCookie(&http.Cookie{
232                 Name:  "arvados_api_token",
233                 Value: auth.EncodeTokenCookie([]byte(tok)),
234         })
235         return http.StatusUnauthorized
236 }
237
238 func (s *IntegrationSuite) TestVhostViaPath(c *check.C) {
239         s.doVhostRequests(c, authzViaPath)
240 }
241 func authzViaPath(r *http.Request, tok string) int {
242         r.URL.Path = "/t=" + tok + r.URL.Path
243         return http.StatusNotFound
244 }
245
246 func (s *IntegrationSuite) TestVhostViaQueryString(c *check.C) {
247         s.doVhostRequests(c, authzViaQueryString)
248 }
249 func authzViaQueryString(r *http.Request, tok string) int {
250         r.URL.RawQuery = "api_token=" + tok
251         return http.StatusUnauthorized
252 }
253
254 func (s *IntegrationSuite) TestVhostViaPOST(c *check.C) {
255         s.doVhostRequests(c, authzViaPOST)
256 }
257 func authzViaPOST(r *http.Request, tok string) int {
258         r.Method = "POST"
259         r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
260         r.Body = ioutil.NopCloser(strings.NewReader(
261                 url.Values{"api_token": {tok}}.Encode()))
262         return http.StatusUnauthorized
263 }
264
265 func (s *IntegrationSuite) TestVhostViaXHRPOST(c *check.C) {
266         s.doVhostRequests(c, authzViaPOST)
267 }
268 func authzViaXHRPOST(r *http.Request, tok string) int {
269         r.Method = "POST"
270         r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
271         r.Header.Add("Origin", "https://origin.example")
272         r.Body = ioutil.NopCloser(strings.NewReader(
273                 url.Values{
274                         "api_token":   {tok},
275                         "disposition": {"attachment"},
276                 }.Encode()))
277         return http.StatusUnauthorized
278 }
279
280 // Try some combinations of {url, token} using the given authorization
281 // mechanism, and verify the result is correct.
282 func (s *IntegrationSuite) doVhostRequests(c *check.C, authz authorizer) {
283         for _, hostPath := range []string{
284                 arvadostest.FooCollection + ".example.com/foo",
285                 arvadostest.FooCollection + "--collections.example.com/foo",
286                 arvadostest.FooCollection + "--collections.example.com/_/foo",
287                 arvadostest.FooCollectionPDH + ".example.com/foo",
288                 strings.Replace(arvadostest.FooCollectionPDH, "+", "-", -1) + "--collections.example.com/foo",
289                 arvadostest.FooBarDirCollection + ".example.com/dir1/foo",
290         } {
291                 c.Log("doRequests: ", hostPath)
292                 s.doVhostRequestsWithHostPath(c, authz, hostPath)
293         }
294 }
295
296 func (s *IntegrationSuite) doVhostRequestsWithHostPath(c *check.C, authz authorizer, hostPath string) {
297         for _, tok := range []string{
298                 arvadostest.ActiveToken,
299                 arvadostest.ActiveToken[:15],
300                 arvadostest.SpectatorToken,
301                 "bogus",
302                 "",
303         } {
304                 u := mustParseURL("http://" + hostPath)
305                 req := &http.Request{
306                         Method:     "GET",
307                         Host:       u.Host,
308                         URL:        u,
309                         RequestURI: u.RequestURI(),
310                         Header:     http.Header{},
311                 }
312                 failCode := authz(req, tok)
313                 req, resp := s.doReq(req)
314                 code, body := resp.Code, resp.Body.String()
315
316                 // If the initial request had a (non-empty) token
317                 // showing in the query string, we should have been
318                 // redirected in order to hide it in a cookie.
319                 c.Check(req.URL.String(), check.Not(check.Matches), `.*api_token=.+`)
320
321                 if tok == arvadostest.ActiveToken {
322                         c.Check(code, check.Equals, http.StatusOK)
323                         c.Check(body, check.Equals, "foo")
324                 } else {
325                         c.Check(code >= 400, check.Equals, true)
326                         c.Check(code < 500, check.Equals, true)
327                         if tok == arvadostest.SpectatorToken {
328                                 // Valid token never offers to retry
329                                 // with different credentials.
330                                 c.Check(code, check.Equals, http.StatusNotFound)
331                         } else {
332                                 // Invalid token can ask to retry
333                                 // depending on the authz method.
334                                 c.Check(code, check.Equals, failCode)
335                         }
336                         if code == 404 {
337                                 c.Check(body, check.Equals, notFoundMessage+"\n")
338                         } else {
339                                 c.Check(body, check.Equals, unauthorizedMessage+"\n")
340                         }
341                 }
342         }
343 }
344
345 func (s *IntegrationSuite) TestVhostPortMatch(c *check.C) {
346         for _, host := range []string{"download.example.com", "DOWNLOAD.EXAMPLE.COM"} {
347                 for _, port := range []string{"80", "443", "8000"} {
348                         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = fmt.Sprintf("download.example.com:%v", port)
349                         u := mustParseURL(fmt.Sprintf("http://%v/by_id/%v/foo", host, arvadostest.FooCollection))
350                         req := &http.Request{
351                                 Method:     "GET",
352                                 Host:       u.Host,
353                                 URL:        u,
354                                 RequestURI: u.RequestURI(),
355                                 Header:     http.Header{"Authorization": []string{"Bearer " + arvadostest.ActiveToken}},
356                         }
357                         req, resp := s.doReq(req)
358                         code, _ := resp.Code, resp.Body.String()
359
360                         if port == "8000" {
361                                 c.Check(code, check.Equals, 401)
362                         } else {
363                                 c.Check(code, check.Equals, 200)
364                         }
365                 }
366         }
367 }
368
369 func (s *IntegrationSuite) do(method string, urlstring string, token string, hdr http.Header) (*http.Request, *httptest.ResponseRecorder) {
370         u := mustParseURL(urlstring)
371         if hdr == nil && token != "" {
372                 hdr = http.Header{"Authorization": {"Bearer " + token}}
373         } else if hdr == nil {
374                 hdr = http.Header{}
375         } else if token != "" {
376                 panic("must not pass both token and hdr")
377         }
378         return s.doReq(&http.Request{
379                 Method:     method,
380                 Host:       u.Host,
381                 URL:        u,
382                 RequestURI: u.RequestURI(),
383                 Header:     hdr,
384         })
385 }
386
387 func (s *IntegrationSuite) doReq(req *http.Request) (*http.Request, *httptest.ResponseRecorder) {
388         resp := httptest.NewRecorder()
389         s.handler.ServeHTTP(resp, req)
390         if resp.Code != http.StatusSeeOther {
391                 return req, resp
392         }
393         cookies := (&http.Response{Header: resp.Header()}).Cookies()
394         u, _ := req.URL.Parse(resp.Header().Get("Location"))
395         req = &http.Request{
396                 Method:     "GET",
397                 Host:       u.Host,
398                 URL:        u,
399                 RequestURI: u.RequestURI(),
400                 Header:     http.Header{},
401         }
402         for _, c := range cookies {
403                 req.AddCookie(c)
404         }
405         return s.doReq(req)
406 }
407
408 func (s *IntegrationSuite) TestVhostRedirectQueryTokenToCookie(c *check.C) {
409         s.testVhostRedirectTokenToCookie(c, "GET",
410                 arvadostest.FooCollection+".example.com/foo",
411                 "?api_token="+arvadostest.ActiveToken,
412                 nil,
413                 "",
414                 http.StatusOK,
415                 "foo",
416         )
417 }
418
419 func (s *IntegrationSuite) TestSingleOriginSecretLink(c *check.C) {
420         s.testVhostRedirectTokenToCookie(c, "GET",
421                 "example.com/c="+arvadostest.FooCollection+"/t="+arvadostest.ActiveToken+"/foo",
422                 "",
423                 nil,
424                 "",
425                 http.StatusOK,
426                 "foo",
427         )
428 }
429
430 func (s *IntegrationSuite) TestCollectionSharingToken(c *check.C) {
431         s.testVhostRedirectTokenToCookie(c, "GET",
432                 "example.com/c="+arvadostest.FooFileCollectionUUID+"/t="+arvadostest.FooFileCollectionSharingToken+"/foo",
433                 "",
434                 nil,
435                 "",
436                 http.StatusOK,
437                 "foo",
438         )
439         // Same valid sharing token, but requesting a different collection
440         s.testVhostRedirectTokenToCookie(c, "GET",
441                 "example.com/c="+arvadostest.FooCollection+"/t="+arvadostest.FooFileCollectionSharingToken+"/foo",
442                 "",
443                 nil,
444                 "",
445                 http.StatusNotFound,
446                 regexp.QuoteMeta(notFoundMessage+"\n"),
447         )
448 }
449
450 // Bad token in URL is 404 Not Found because it doesn't make sense to
451 // retry the same URL with different authorization.
452 func (s *IntegrationSuite) TestSingleOriginSecretLinkBadToken(c *check.C) {
453         s.testVhostRedirectTokenToCookie(c, "GET",
454                 "example.com/c="+arvadostest.FooCollection+"/t=bogus/foo",
455                 "",
456                 nil,
457                 "",
458                 http.StatusNotFound,
459                 regexp.QuoteMeta(notFoundMessage+"\n"),
460         )
461 }
462
463 // Bad token in a cookie (even if it got there via our own
464 // query-string-to-cookie redirect) is, in principle, retryable via
465 // wb2-login-and-redirect flow.
466 func (s *IntegrationSuite) TestVhostRedirectQueryTokenToBogusCookie(c *check.C) {
467         // Inline
468         resp := s.testVhostRedirectTokenToCookie(c, "GET",
469                 arvadostest.FooCollection+".example.com/foo",
470                 "?api_token=thisisabogustoken",
471                 http.Header{"Sec-Fetch-Mode": {"navigate"}},
472                 "",
473                 http.StatusSeeOther,
474                 "",
475         )
476         u, err := url.Parse(resp.Header().Get("Location"))
477         c.Assert(err, check.IsNil)
478         c.Logf("redirected to %s", u)
479         c.Check(u.Host, check.Equals, s.handler.Cluster.Services.Workbench2.ExternalURL.Host)
480         c.Check(u.Query().Get("redirectToPreview"), check.Equals, "/c="+arvadostest.FooCollection+"/foo")
481         c.Check(u.Query().Get("redirectToDownload"), check.Equals, "")
482
483         // Download/attachment indicated by ?disposition=attachment
484         resp = s.testVhostRedirectTokenToCookie(c, "GET",
485                 arvadostest.FooCollection+".example.com/foo",
486                 "?api_token=thisisabogustoken&disposition=attachment",
487                 http.Header{"Sec-Fetch-Mode": {"navigate"}},
488                 "",
489                 http.StatusSeeOther,
490                 "",
491         )
492         u, err = url.Parse(resp.Header().Get("Location"))
493         c.Assert(err, check.IsNil)
494         c.Logf("redirected to %s", u)
495         c.Check(u.Host, check.Equals, s.handler.Cluster.Services.Workbench2.ExternalURL.Host)
496         c.Check(u.Query().Get("redirectToPreview"), check.Equals, "")
497         c.Check(u.Query().Get("redirectToDownload"), check.Equals, "/c="+arvadostest.FooCollection+"/foo")
498
499         // Download/attachment indicated by vhost
500         resp = s.testVhostRedirectTokenToCookie(c, "GET",
501                 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host+"/c="+arvadostest.FooCollection+"/foo",
502                 "?api_token=thisisabogustoken",
503                 http.Header{"Sec-Fetch-Mode": {"navigate"}},
504                 "",
505                 http.StatusSeeOther,
506                 "",
507         )
508         u, err = url.Parse(resp.Header().Get("Location"))
509         c.Assert(err, check.IsNil)
510         c.Logf("redirected to %s", u)
511         c.Check(u.Host, check.Equals, s.handler.Cluster.Services.Workbench2.ExternalURL.Host)
512         c.Check(u.Query().Get("redirectToPreview"), check.Equals, "")
513         c.Check(u.Query().Get("redirectToDownload"), check.Equals, "/c="+arvadostest.FooCollection+"/foo")
514
515         // Without "Sec-Fetch-Mode: navigate" header, just 401.
516         s.testVhostRedirectTokenToCookie(c, "GET",
517                 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host+"/c="+arvadostest.FooCollection+"/foo",
518                 "?api_token=thisisabogustoken",
519                 http.Header{"Sec-Fetch-Mode": {"cors"}},
520                 "",
521                 http.StatusUnauthorized,
522                 regexp.QuoteMeta(unauthorizedMessage+"\n"),
523         )
524         s.testVhostRedirectTokenToCookie(c, "GET",
525                 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host+"/c="+arvadostest.FooCollection+"/foo",
526                 "?api_token=thisisabogustoken",
527                 nil,
528                 "",
529                 http.StatusUnauthorized,
530                 regexp.QuoteMeta(unauthorizedMessage+"\n"),
531         )
532 }
533
534 func (s *IntegrationSuite) TestVhostRedirectWithNoCache(c *check.C) {
535         resp := s.testVhostRedirectTokenToCookie(c, "GET",
536                 arvadostest.FooCollection+".example.com/foo",
537                 "?api_token=thisisabogustoken",
538                 http.Header{
539                         "Sec-Fetch-Mode": {"navigate"},
540                         "Cache-Control":  {"no-cache"},
541                 },
542                 "",
543                 http.StatusSeeOther,
544                 "",
545         )
546         u, err := url.Parse(resp.Header().Get("Location"))
547         c.Assert(err, check.IsNil)
548         c.Logf("redirected to %s", u)
549         c.Check(u.Host, check.Equals, s.handler.Cluster.Services.Workbench2.ExternalURL.Host)
550         c.Check(u.Query().Get("redirectToPreview"), check.Equals, "/c="+arvadostest.FooCollection+"/foo")
551         c.Check(u.Query().Get("redirectToDownload"), check.Equals, "")
552 }
553
554 func (s *IntegrationSuite) TestVhostRedirectQueryTokenSingleOriginError(c *check.C) {
555         s.testVhostRedirectTokenToCookie(c, "GET",
556                 "example.com/c="+arvadostest.FooCollection+"/foo",
557                 "?api_token="+arvadostest.ActiveToken,
558                 nil,
559                 "",
560                 http.StatusBadRequest,
561                 regexp.QuoteMeta("cannot serve inline content at this URL (possible configuration error; see https://doc.arvados.org/install/install-keep-web.html#dns)\n"),
562         )
563 }
564
565 // If client requests an attachment by putting ?disposition=attachment
566 // in the query string, and gets redirected, the redirect target
567 // should respond with an attachment.
568 func (s *IntegrationSuite) TestVhostRedirectQueryTokenRequestAttachment(c *check.C) {
569         resp := s.testVhostRedirectTokenToCookie(c, "GET",
570                 arvadostest.FooCollection+".example.com/foo",
571                 "?disposition=attachment&api_token="+arvadostest.ActiveToken,
572                 nil,
573                 "",
574                 http.StatusOK,
575                 "foo",
576         )
577         c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
578 }
579
580 func (s *IntegrationSuite) TestVhostRedirectQueryTokenSiteFS(c *check.C) {
581         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
582         resp := s.testVhostRedirectTokenToCookie(c, "GET",
583                 "download.example.com/by_id/"+arvadostest.FooCollection+"/foo",
584                 "?api_token="+arvadostest.ActiveToken,
585                 nil,
586                 "",
587                 http.StatusOK,
588                 "foo",
589         )
590         c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
591 }
592
593 func (s *IntegrationSuite) TestPastCollectionVersionFileAccess(c *check.C) {
594         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
595         resp := s.testVhostRedirectTokenToCookie(c, "GET",
596                 "download.example.com/c="+arvadostest.WazVersion1Collection+"/waz",
597                 "?api_token="+arvadostest.ActiveToken,
598                 nil,
599                 "",
600                 http.StatusOK,
601                 "waz",
602         )
603         c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
604         resp = s.testVhostRedirectTokenToCookie(c, "GET",
605                 "download.example.com/by_id/"+arvadostest.WazVersion1Collection+"/waz",
606                 "?api_token="+arvadostest.ActiveToken,
607                 nil,
608                 "",
609                 http.StatusOK,
610                 "waz",
611         )
612         c.Check(resp.Header().Get("Content-Disposition"), check.Matches, "attachment(;.*)?")
613 }
614
615 func (s *IntegrationSuite) TestVhostRedirectQueryTokenTrustAllContent(c *check.C) {
616         s.handler.Cluster.Collections.TrustAllContent = true
617         s.testVhostRedirectTokenToCookie(c, "GET",
618                 "example.com/c="+arvadostest.FooCollection+"/foo",
619                 "?api_token="+arvadostest.ActiveToken,
620                 nil,
621                 "",
622                 http.StatusOK,
623                 "foo",
624         )
625 }
626
627 func (s *IntegrationSuite) TestVhostRedirectQueryTokenAttachmentOnlyHost(c *check.C) {
628         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "example.com:1234"
629
630         s.testVhostRedirectTokenToCookie(c, "GET",
631                 "example.com/c="+arvadostest.FooCollection+"/foo",
632                 "?api_token="+arvadostest.ActiveToken,
633                 nil,
634                 "",
635                 http.StatusBadRequest,
636                 regexp.QuoteMeta("cannot serve inline content at this URL (possible configuration error; see https://doc.arvados.org/install/install-keep-web.html#dns)\n"),
637         )
638
639         resp := s.testVhostRedirectTokenToCookie(c, "GET",
640                 "example.com:1234/c="+arvadostest.FooCollection+"/foo",
641                 "?api_token="+arvadostest.ActiveToken,
642                 nil,
643                 "",
644                 http.StatusOK,
645                 "foo",
646         )
647         c.Check(resp.Header().Get("Content-Disposition"), check.Equals, "attachment")
648 }
649
650 func (s *IntegrationSuite) TestVhostRedirectPOSTFormTokenToCookie(c *check.C) {
651         s.testVhostRedirectTokenToCookie(c, "POST",
652                 arvadostest.FooCollection+".example.com/foo",
653                 "",
654                 http.Header{"Content-Type": {"application/x-www-form-urlencoded"}},
655                 url.Values{"api_token": {arvadostest.ActiveToken}}.Encode(),
656                 http.StatusOK,
657                 "foo",
658         )
659 }
660
661 func (s *IntegrationSuite) TestVhostRedirectPOSTFormTokenToCookie404(c *check.C) {
662         s.testVhostRedirectTokenToCookie(c, "POST",
663                 arvadostest.FooCollection+".example.com/foo",
664                 "",
665                 http.Header{"Content-Type": {"application/x-www-form-urlencoded"}},
666                 url.Values{"api_token": {arvadostest.SpectatorToken}}.Encode(),
667                 http.StatusNotFound,
668                 regexp.QuoteMeta(notFoundMessage+"\n"),
669         )
670 }
671
672 func (s *IntegrationSuite) TestAnonymousTokenOK(c *check.C) {
673         s.handler.Cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
674         s.testVhostRedirectTokenToCookie(c, "GET",
675                 "example.com/c="+arvadostest.HelloWorldCollection+"/Hello%20world.txt",
676                 "",
677                 nil,
678                 "",
679                 http.StatusOK,
680                 "Hello world\n",
681         )
682 }
683
684 func (s *IntegrationSuite) TestAnonymousTokenError(c *check.C) {
685         s.handler.Cluster.Users.AnonymousUserToken = "anonymousTokenConfiguredButInvalid"
686         s.testVhostRedirectTokenToCookie(c, "GET",
687                 "example.com/c="+arvadostest.HelloWorldCollection+"/Hello%20world.txt",
688                 "",
689                 nil,
690                 "",
691                 http.StatusUnauthorized,
692                 "Authorization tokens are not accepted here: .*\n",
693         )
694 }
695
696 func (s *IntegrationSuite) TestSpecialCharsInPath(c *check.C) {
697         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
698
699         client := arvados.NewClientFromEnv()
700         client.AuthToken = arvadostest.ActiveToken
701         fs, err := (&arvados.Collection{}).FileSystem(client, nil)
702         c.Assert(err, check.IsNil)
703         f, err := fs.OpenFile("https:\\\"odd' path chars", os.O_CREATE, 0777)
704         c.Assert(err, check.IsNil)
705         f.Close()
706         mtxt, err := fs.MarshalManifest(".")
707         c.Assert(err, check.IsNil)
708         var coll arvados.Collection
709         err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
710                 "collection": map[string]string{
711                         "manifest_text": mtxt,
712                 },
713         })
714         c.Assert(err, check.IsNil)
715
716         u, _ := url.Parse("http://download.example.com/c=" + coll.UUID + "/")
717         req := &http.Request{
718                 Method:     "GET",
719                 Host:       u.Host,
720                 URL:        u,
721                 RequestURI: u.RequestURI(),
722                 Header: http.Header{
723                         "Authorization": {"Bearer " + client.AuthToken},
724                 },
725         }
726         resp := httptest.NewRecorder()
727         s.handler.ServeHTTP(resp, req)
728         c.Check(resp.Code, check.Equals, http.StatusOK)
729         c.Check(resp.Body.String(), check.Matches, `(?ms).*href="./https:%5c%22odd%27%20path%20chars"\S+https:\\&#34;odd&#39; path chars.*`)
730 }
731
732 func (s *IntegrationSuite) TestForwardSlashSubstitution(c *check.C) {
733         arv := arvados.NewClientFromEnv()
734         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
735         s.handler.Cluster.Collections.ForwardSlashNameSubstitution = "{SOLIDUS}"
736         name := "foo/bar/baz"
737         nameShown := strings.Replace(name, "/", "{SOLIDUS}", -1)
738         nameShownEscaped := strings.Replace(name, "/", "%7bSOLIDUS%7d", -1)
739
740         client := arvados.NewClientFromEnv()
741         client.AuthToken = arvadostest.ActiveToken
742         fs, err := (&arvados.Collection{}).FileSystem(client, nil)
743         c.Assert(err, check.IsNil)
744         f, err := fs.OpenFile("filename", os.O_CREATE, 0777)
745         c.Assert(err, check.IsNil)
746         f.Close()
747         mtxt, err := fs.MarshalManifest(".")
748         c.Assert(err, check.IsNil)
749         var coll arvados.Collection
750         err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
751                 "collection": map[string]string{
752                         "manifest_text": mtxt,
753                         "name":          name,
754                         "owner_uuid":    arvadostest.AProjectUUID,
755                 },
756         })
757         c.Assert(err, check.IsNil)
758         defer arv.RequestAndDecode(&coll, "DELETE", "arvados/v1/collections/"+coll.UUID, nil, nil)
759
760         base := "http://download.example.com/by_id/" + coll.OwnerUUID + "/"
761         for tryURL, expectRegexp := range map[string]string{
762                 base:                          `(?ms).*href="./` + nameShownEscaped + `/"\S+` + nameShown + `.*`,
763                 base + nameShownEscaped + "/": `(?ms).*href="./filename"\S+filename.*`,
764         } {
765                 u, _ := url.Parse(tryURL)
766                 req := &http.Request{
767                         Method:     "GET",
768                         Host:       u.Host,
769                         URL:        u,
770                         RequestURI: u.RequestURI(),
771                         Header: http.Header{
772                                 "Authorization": {"Bearer " + client.AuthToken},
773                         },
774                 }
775                 resp := httptest.NewRecorder()
776                 s.handler.ServeHTTP(resp, req)
777                 c.Check(resp.Code, check.Equals, http.StatusOK)
778                 c.Check(resp.Body.String(), check.Matches, expectRegexp)
779         }
780 }
781
782 // XHRs can't follow redirect-with-cookie so they rely on method=POST
783 // and disposition=attachment (telling us it's acceptable to respond
784 // with content instead of a redirect) and an Origin header that gets
785 // added automatically by the browser (telling us it's desirable to do
786 // so).
787 func (s *IntegrationSuite) TestXHRNoRedirect(c *check.C) {
788         u, _ := url.Parse("http://example.com/c=" + arvadostest.FooCollection + "/foo")
789         req := &http.Request{
790                 Method:     "POST",
791                 Host:       u.Host,
792                 URL:        u,
793                 RequestURI: u.RequestURI(),
794                 Header: http.Header{
795                         "Origin":       {"https://origin.example"},
796                         "Content-Type": {"application/x-www-form-urlencoded"},
797                 },
798                 Body: ioutil.NopCloser(strings.NewReader(url.Values{
799                         "api_token":   {arvadostest.ActiveToken},
800                         "disposition": {"attachment"},
801                 }.Encode())),
802         }
803         resp := httptest.NewRecorder()
804         s.handler.ServeHTTP(resp, req)
805         c.Check(resp.Code, check.Equals, http.StatusOK)
806         c.Check(resp.Body.String(), check.Equals, "foo")
807         c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, "*")
808
809         // GET + Origin header is representative of both AJAX GET
810         // requests and inline images via <IMG crossorigin="anonymous"
811         // src="...">.
812         u.RawQuery = "api_token=" + url.QueryEscape(arvadostest.ActiveTokenV2)
813         req = &http.Request{
814                 Method:     "GET",
815                 Host:       u.Host,
816                 URL:        u,
817                 RequestURI: u.RequestURI(),
818                 Header: http.Header{
819                         "Origin": {"https://origin.example"},
820                 },
821         }
822         resp = httptest.NewRecorder()
823         s.handler.ServeHTTP(resp, req)
824         c.Check(resp.Code, check.Equals, http.StatusOK)
825         c.Check(resp.Body.String(), check.Equals, "foo")
826         c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, "*")
827 }
828
829 func (s *IntegrationSuite) testVhostRedirectTokenToCookie(c *check.C, method, hostPath, queryString string, reqHeader http.Header, reqBody string, expectStatus int, matchRespBody string) *httptest.ResponseRecorder {
830         if reqHeader == nil {
831                 reqHeader = http.Header{}
832         }
833         u, _ := url.Parse(`http://` + hostPath + queryString)
834         c.Logf("requesting %s", u)
835         req := &http.Request{
836                 Method:     method,
837                 Host:       u.Host,
838                 URL:        u,
839                 RequestURI: u.RequestURI(),
840                 Header:     reqHeader,
841                 Body:       ioutil.NopCloser(strings.NewReader(reqBody)),
842         }
843
844         resp := httptest.NewRecorder()
845         defer func() {
846                 c.Check(resp.Code, check.Equals, expectStatus)
847                 c.Check(resp.Body.String(), check.Matches, matchRespBody)
848         }()
849
850         s.handler.ServeHTTP(resp, req)
851         if resp.Code != http.StatusSeeOther {
852                 return resp
853         }
854         c.Check(resp.Body.String(), check.Matches, `.*href="http://`+regexp.QuoteMeta(html.EscapeString(hostPath))+`(\?[^"]*)?".*`)
855         c.Check(strings.Split(resp.Header().Get("Location"), "?")[0], check.Equals, "http://"+hostPath)
856         cookies := (&http.Response{Header: resp.Header()}).Cookies()
857
858         u, err := u.Parse(resp.Header().Get("Location"))
859         c.Assert(err, check.IsNil)
860         c.Logf("following redirect to %s", u)
861         req = &http.Request{
862                 Method:     "GET",
863                 Host:       u.Host,
864                 URL:        u,
865                 RequestURI: u.RequestURI(),
866                 Header:     reqHeader,
867         }
868         for _, c := range cookies {
869                 req.AddCookie(c)
870         }
871
872         resp = httptest.NewRecorder()
873         s.handler.ServeHTTP(resp, req)
874
875         if resp.Code != http.StatusSeeOther {
876                 c.Check(resp.Header().Get("Location"), check.Equals, "")
877         }
878         return resp
879 }
880
881 func (s *IntegrationSuite) TestDirectoryListingWithAnonymousToken(c *check.C) {
882         s.handler.Cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
883         s.testDirectoryListing(c)
884 }
885
886 func (s *IntegrationSuite) TestDirectoryListingWithNoAnonymousToken(c *check.C) {
887         s.handler.Cluster.Users.AnonymousUserToken = ""
888         s.testDirectoryListing(c)
889 }
890
891 func (s *IntegrationSuite) testDirectoryListing(c *check.C) {
892         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
893         authHeader := http.Header{
894                 "Authorization": {"OAuth2 " + arvadostest.ActiveToken},
895         }
896         for _, trial := range []struct {
897                 uri      string
898                 header   http.Header
899                 expect   []string
900                 redirect string
901                 cutDirs  int
902         }{
903                 {
904                         uri:     strings.Replace(arvadostest.FooAndBarFilesInDirPDH, "+", "-", -1) + ".example.com/",
905                         header:  authHeader,
906                         expect:  []string{"dir1/foo", "dir1/bar"},
907                         cutDirs: 0,
908                 },
909                 {
910                         uri:     strings.Replace(arvadostest.FooAndBarFilesInDirPDH, "+", "-", -1) + ".example.com/dir1/",
911                         header:  authHeader,
912                         expect:  []string{"foo", "bar"},
913                         cutDirs: 1,
914                 },
915                 {
916                         // URLs of this form ignore authHeader, and
917                         // FooAndBarFilesInDirUUID isn't public, so
918                         // this returns 401.
919                         uri:    "download.example.com/collections/" + arvadostest.FooAndBarFilesInDirUUID + "/",
920                         header: authHeader,
921                         expect: nil,
922                 },
923                 {
924                         uri:     "download.example.com/users/active/foo_file_in_dir/",
925                         header:  authHeader,
926                         expect:  []string{"dir1/"},
927                         cutDirs: 3,
928                 },
929                 {
930                         uri:     "download.example.com/users/active/foo_file_in_dir/dir1/",
931                         header:  authHeader,
932                         expect:  []string{"bar"},
933                         cutDirs: 4,
934                 },
935                 {
936                         uri:     "download.example.com/",
937                         header:  authHeader,
938                         expect:  []string{"users/"},
939                         cutDirs: 0,
940                 },
941                 {
942                         uri:      "download.example.com/users",
943                         header:   authHeader,
944                         redirect: "/users/",
945                         expect:   []string{"active/"},
946                         cutDirs:  1,
947                 },
948                 {
949                         uri:     "download.example.com/users/",
950                         header:  authHeader,
951                         expect:  []string{"active/"},
952                         cutDirs: 1,
953                 },
954                 {
955                         uri:      "download.example.com/users/active",
956                         header:   authHeader,
957                         redirect: "/users/active/",
958                         expect:   []string{"foo_file_in_dir/"},
959                         cutDirs:  2,
960                 },
961                 {
962                         uri:     "download.example.com/users/active/",
963                         header:  authHeader,
964                         expect:  []string{"foo_file_in_dir/"},
965                         cutDirs: 2,
966                 },
967                 {
968                         uri:     "collections.example.com/collections/download/" + arvadostest.FooAndBarFilesInDirUUID + "/" + arvadostest.ActiveToken + "/",
969                         header:  nil,
970                         expect:  []string{"dir1/foo", "dir1/bar"},
971                         cutDirs: 4,
972                 },
973                 {
974                         uri:     "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/t=" + arvadostest.ActiveToken + "/",
975                         header:  nil,
976                         expect:  []string{"dir1/foo", "dir1/bar"},
977                         cutDirs: 2,
978                 },
979                 {
980                         uri:     "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/t=" + arvadostest.ActiveToken,
981                         header:  nil,
982                         expect:  []string{"dir1/foo", "dir1/bar"},
983                         cutDirs: 2,
984                 },
985                 {
986                         uri:     "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID,
987                         header:  authHeader,
988                         expect:  []string{"dir1/foo", "dir1/bar"},
989                         cutDirs: 1,
990                 },
991                 {
992                         uri:      "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/dir1",
993                         header:   authHeader,
994                         redirect: "/c=" + arvadostest.FooAndBarFilesInDirUUID + "/dir1/",
995                         expect:   []string{"foo", "bar"},
996                         cutDirs:  2,
997                 },
998                 {
999                         uri:     "download.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/_/dir1/",
1000                         header:  authHeader,
1001                         expect:  []string{"foo", "bar"},
1002                         cutDirs: 3,
1003                 },
1004                 {
1005                         uri:      arvadostest.FooAndBarFilesInDirUUID + ".example.com/dir1?api_token=" + arvadostest.ActiveToken,
1006                         header:   authHeader,
1007                         redirect: "/dir1/",
1008                         expect:   []string{"foo", "bar"},
1009                         cutDirs:  1,
1010                 },
1011                 {
1012                         uri:    "collections.example.com/c=" + arvadostest.FooAndBarFilesInDirUUID + "/theperthcountyconspiracydoesnotexist/",
1013                         header: authHeader,
1014                         expect: nil,
1015                 },
1016                 {
1017                         uri:     "download.example.com/c=" + arvadostest.WazVersion1Collection,
1018                         header:  authHeader,
1019                         expect:  []string{"waz"},
1020                         cutDirs: 1,
1021                 },
1022                 {
1023                         uri:     "download.example.com/by_id/" + arvadostest.WazVersion1Collection,
1024                         header:  authHeader,
1025                         expect:  []string{"waz"},
1026                         cutDirs: 2,
1027                 },
1028         } {
1029                 comment := check.Commentf("HTML: %q => %q", trial.uri, trial.expect)
1030                 resp := httptest.NewRecorder()
1031                 u := mustParseURL("//" + trial.uri)
1032                 req := &http.Request{
1033                         Method:     "GET",
1034                         Host:       u.Host,
1035                         URL:        u,
1036                         RequestURI: u.RequestURI(),
1037                         Header:     copyHeader(trial.header),
1038                 }
1039                 s.handler.ServeHTTP(resp, req)
1040                 var cookies []*http.Cookie
1041                 for resp.Code == http.StatusSeeOther {
1042                         u, _ := req.URL.Parse(resp.Header().Get("Location"))
1043                         req = &http.Request{
1044                                 Method:     "GET",
1045                                 Host:       u.Host,
1046                                 URL:        u,
1047                                 RequestURI: u.RequestURI(),
1048                                 Header:     copyHeader(trial.header),
1049                         }
1050                         cookies = append(cookies, (&http.Response{Header: resp.Header()}).Cookies()...)
1051                         for _, c := range cookies {
1052                                 req.AddCookie(c)
1053                         }
1054                         resp = httptest.NewRecorder()
1055                         s.handler.ServeHTTP(resp, req)
1056                 }
1057                 if trial.redirect != "" {
1058                         c.Check(req.URL.Path, check.Equals, trial.redirect, comment)
1059                 }
1060                 if trial.expect == nil {
1061                         c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
1062                 } else {
1063                         c.Check(resp.Code, check.Equals, http.StatusOK, comment)
1064                         for _, e := range trial.expect {
1065                                 c.Check(resp.Body.String(), check.Matches, `(?ms).*href="./`+e+`".*`, comment)
1066                         }
1067                         c.Check(resp.Body.String(), check.Matches, `(?ms).*--cut-dirs=`+fmt.Sprintf("%d", trial.cutDirs)+` .*`, comment)
1068                 }
1069
1070                 comment = check.Commentf("WebDAV: %q => %q", trial.uri, trial.expect)
1071                 req = &http.Request{
1072                         Method:     "OPTIONS",
1073                         Host:       u.Host,
1074                         URL:        u,
1075                         RequestURI: u.RequestURI(),
1076                         Header:     copyHeader(trial.header),
1077                         Body:       ioutil.NopCloser(&bytes.Buffer{}),
1078                 }
1079                 resp = httptest.NewRecorder()
1080                 s.handler.ServeHTTP(resp, req)
1081                 if trial.expect == nil {
1082                         c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
1083                 } else {
1084                         c.Check(resp.Code, check.Equals, http.StatusOK, comment)
1085                 }
1086
1087                 req = &http.Request{
1088                         Method:     "PROPFIND",
1089                         Host:       u.Host,
1090                         URL:        u,
1091                         RequestURI: u.RequestURI(),
1092                         Header:     copyHeader(trial.header),
1093                         Body:       ioutil.NopCloser(&bytes.Buffer{}),
1094                 }
1095                 resp = httptest.NewRecorder()
1096                 s.handler.ServeHTTP(resp, req)
1097                 if trial.expect == nil {
1098                         c.Check(resp.Code, check.Equals, http.StatusUnauthorized, comment)
1099                 } else {
1100                         c.Check(resp.Code, check.Equals, http.StatusMultiStatus, comment)
1101                         for _, e := range trial.expect {
1102                                 if strings.HasSuffix(e, "/") {
1103                                         e = filepath.Join(u.Path, e) + "/"
1104                                 } else {
1105                                         e = filepath.Join(u.Path, e)
1106                                 }
1107                                 c.Check(resp.Body.String(), check.Matches, `(?ms).*<D:href>`+e+`</D:href>.*`, comment)
1108                         }
1109                 }
1110         }
1111 }
1112
1113 func (s *IntegrationSuite) TestDeleteLastFile(c *check.C) {
1114         arv := arvados.NewClientFromEnv()
1115         var newCollection arvados.Collection
1116         err := arv.RequestAndDecode(&newCollection, "POST", "arvados/v1/collections", nil, map[string]interface{}{
1117                 "collection": map[string]string{
1118                         "owner_uuid":    arvadostest.ActiveUserUUID,
1119                         "manifest_text": ". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo.txt 0:3:bar.txt\n",
1120                         "name":          "keep-web test collection",
1121                 },
1122                 "ensure_unique_name": true,
1123         })
1124         c.Assert(err, check.IsNil)
1125         defer arv.RequestAndDecode(&newCollection, "DELETE", "arvados/v1/collections/"+newCollection.UUID, nil, nil)
1126
1127         var updated arvados.Collection
1128         for _, fnm := range []string{"foo.txt", "bar.txt"} {
1129                 s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "example.com"
1130                 u, _ := url.Parse("http://example.com/c=" + newCollection.UUID + "/" + fnm)
1131                 req := &http.Request{
1132                         Method:     "DELETE",
1133                         Host:       u.Host,
1134                         URL:        u,
1135                         RequestURI: u.RequestURI(),
1136                         Header: http.Header{
1137                                 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1138                         },
1139                 }
1140                 resp := httptest.NewRecorder()
1141                 s.handler.ServeHTTP(resp, req)
1142                 c.Check(resp.Code, check.Equals, http.StatusNoContent)
1143
1144                 updated = arvados.Collection{}
1145                 err = arv.RequestAndDecode(&updated, "GET", "arvados/v1/collections/"+newCollection.UUID, nil, nil)
1146                 c.Check(err, check.IsNil)
1147                 c.Check(updated.ManifestText, check.Not(check.Matches), `(?ms).*\Q`+fnm+`\E.*`)
1148                 c.Logf("updated manifest_text %q", updated.ManifestText)
1149         }
1150         c.Check(updated.ManifestText, check.Equals, "")
1151 }
1152
1153 func (s *IntegrationSuite) TestFileContentType(c *check.C) {
1154         s.handler.Cluster.Services.WebDAVDownload.ExternalURL.Host = "download.example.com"
1155
1156         client := arvados.NewClientFromEnv()
1157         client.AuthToken = arvadostest.ActiveToken
1158         arv, err := arvadosclient.New(client)
1159         c.Assert(err, check.Equals, nil)
1160         kc, err := keepclient.MakeKeepClient(arv)
1161         c.Assert(err, check.Equals, nil)
1162
1163         fs, err := (&arvados.Collection{}).FileSystem(client, kc)
1164         c.Assert(err, check.IsNil)
1165
1166         trials := []struct {
1167                 filename    string
1168                 content     string
1169                 contentType string
1170         }{
1171                 {"picture.txt", "BMX bikes are small this year\n", "text/plain; charset=utf-8"},
1172                 {"picture.bmp", "BMX bikes are small this year\n", "image/(x-ms-)?bmp"},
1173                 {"picture.jpg", "BMX bikes are small this year\n", "image/jpeg"},
1174                 {"picture1", "BMX bikes are small this year\n", "image/bmp"},            // content sniff; "BM" is the magic signature for .bmp
1175                 {"picture2", "Cars are small this year\n", "text/plain; charset=utf-8"}, // content sniff
1176         }
1177         for _, trial := range trials {
1178                 f, err := fs.OpenFile(trial.filename, os.O_CREATE|os.O_WRONLY, 0777)
1179                 c.Assert(err, check.IsNil)
1180                 _, err = f.Write([]byte(trial.content))
1181                 c.Assert(err, check.IsNil)
1182                 c.Assert(f.Close(), check.IsNil)
1183         }
1184         mtxt, err := fs.MarshalManifest(".")
1185         c.Assert(err, check.IsNil)
1186         var coll arvados.Collection
1187         err = client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
1188                 "collection": map[string]string{
1189                         "manifest_text": mtxt,
1190                 },
1191         })
1192         c.Assert(err, check.IsNil)
1193
1194         for _, trial := range trials {
1195                 u, _ := url.Parse("http://download.example.com/by_id/" + coll.UUID + "/" + trial.filename)
1196                 req := &http.Request{
1197                         Method:     "GET",
1198                         Host:       u.Host,
1199                         URL:        u,
1200                         RequestURI: u.RequestURI(),
1201                         Header: http.Header{
1202                                 "Authorization": {"Bearer " + client.AuthToken},
1203                         },
1204                 }
1205                 resp := httptest.NewRecorder()
1206                 s.handler.ServeHTTP(resp, req)
1207                 c.Check(resp.Code, check.Equals, http.StatusOK)
1208                 c.Check(resp.Header().Get("Content-Type"), check.Matches, trial.contentType)
1209                 c.Check(resp.Body.String(), check.Equals, trial.content)
1210         }
1211 }
1212
1213 func (s *IntegrationSuite) TestKeepClientBlockCache(c *check.C) {
1214         s.handler.Cluster.Collections.WebDAVCache.MaxBlockEntries = 42
1215         c.Check(keepclient.DefaultBlockCache.MaxBlocks, check.Not(check.Equals), 42)
1216         u := mustParseURL("http://keep-web.example/c=" + arvadostest.FooCollection + "/t=" + arvadostest.ActiveToken + "/foo")
1217         req := &http.Request{
1218                 Method:     "GET",
1219                 Host:       u.Host,
1220                 URL:        u,
1221                 RequestURI: u.RequestURI(),
1222         }
1223         resp := httptest.NewRecorder()
1224         s.handler.ServeHTTP(resp, req)
1225         c.Check(resp.Code, check.Equals, http.StatusOK)
1226         c.Check(keepclient.DefaultBlockCache.MaxBlocks, check.Equals, 42)
1227 }
1228
1229 // Writing to a collection shouldn't affect its entry in the
1230 // PDH-to-manifest cache.
1231 func (s *IntegrationSuite) TestCacheWriteCollectionSamePDH(c *check.C) {
1232         arv, err := arvadosclient.MakeArvadosClient()
1233         c.Assert(err, check.Equals, nil)
1234         arv.ApiToken = arvadostest.ActiveToken
1235
1236         u := mustParseURL("http://x.example/testfile")
1237         req := &http.Request{
1238                 Method:     "GET",
1239                 Host:       u.Host,
1240                 URL:        u,
1241                 RequestURI: u.RequestURI(),
1242                 Header:     http.Header{"Authorization": {"Bearer " + arv.ApiToken}},
1243         }
1244
1245         checkWithID := func(id string, status int) {
1246                 req.URL.Host = strings.Replace(id, "+", "-", -1) + ".example"
1247                 req.Host = req.URL.Host
1248                 resp := httptest.NewRecorder()
1249                 s.handler.ServeHTTP(resp, req)
1250                 c.Check(resp.Code, check.Equals, status)
1251         }
1252
1253         var colls [2]arvados.Collection
1254         for i := range colls {
1255                 err := arv.Create("collections",
1256                         map[string]interface{}{
1257                                 "ensure_unique_name": true,
1258                                 "collection": map[string]interface{}{
1259                                         "name": "test collection",
1260                                 },
1261                         }, &colls[i])
1262                 c.Assert(err, check.Equals, nil)
1263         }
1264
1265         // Populate cache with empty collection
1266         checkWithID(colls[0].PortableDataHash, http.StatusNotFound)
1267
1268         // write a file to colls[0]
1269         reqPut := *req
1270         reqPut.Method = "PUT"
1271         reqPut.URL.Host = colls[0].UUID + ".example"
1272         reqPut.Host = req.URL.Host
1273         reqPut.Body = ioutil.NopCloser(bytes.NewBufferString("testdata"))
1274         resp := httptest.NewRecorder()
1275         s.handler.ServeHTTP(resp, &reqPut)
1276         c.Check(resp.Code, check.Equals, http.StatusCreated)
1277
1278         // new file should not appear in colls[1]
1279         checkWithID(colls[1].PortableDataHash, http.StatusNotFound)
1280         checkWithID(colls[1].UUID, http.StatusNotFound)
1281
1282         checkWithID(colls[0].UUID, http.StatusOK)
1283 }
1284
1285 func copyHeader(h http.Header) http.Header {
1286         hc := http.Header{}
1287         for k, v := range h {
1288                 hc[k] = append([]string(nil), v...)
1289         }
1290         return hc
1291 }
1292
1293 func (s *IntegrationSuite) checkUploadDownloadRequest(c *check.C, req *http.Request,
1294         successCode int, direction string, perm bool, userUuid, collectionUuid, collectionPDH, filepath string) {
1295
1296         client := arvados.NewClientFromEnv()
1297         client.AuthToken = arvadostest.AdminToken
1298         var logentries arvados.LogList
1299         limit1 := 1
1300         err := client.RequestAndDecode(&logentries, "GET", "arvados/v1/logs", nil,
1301                 arvados.ResourceListParams{
1302                         Limit: &limit1,
1303                         Order: "created_at desc"})
1304         c.Check(err, check.IsNil)
1305         c.Check(logentries.Items, check.HasLen, 1)
1306         lastLogId := logentries.Items[0].ID
1307         c.Logf("lastLogId: %d", lastLogId)
1308
1309         var logbuf bytes.Buffer
1310         logger := logrus.New()
1311         logger.Out = &logbuf
1312         resp := httptest.NewRecorder()
1313         req = req.WithContext(ctxlog.Context(context.Background(), logger))
1314         s.handler.ServeHTTP(resp, req)
1315
1316         if perm {
1317                 c.Check(resp.Result().StatusCode, check.Equals, successCode)
1318                 c.Check(logbuf.String(), check.Matches, `(?ms).*msg="File `+direction+`".*`)
1319                 c.Check(logbuf.String(), check.Not(check.Matches), `(?ms).*level=error.*`)
1320
1321                 deadline := time.Now().Add(time.Second)
1322                 for {
1323                         c.Assert(time.Now().After(deadline), check.Equals, false, check.Commentf("timed out waiting for log entry"))
1324                         logentries = arvados.LogList{}
1325                         err = client.RequestAndDecode(&logentries, "GET", "arvados/v1/logs", nil,
1326                                 arvados.ResourceListParams{
1327                                         Filters: []arvados.Filter{
1328                                                 {Attr: "event_type", Operator: "=", Operand: "file_" + direction},
1329                                                 {Attr: "object_uuid", Operator: "=", Operand: userUuid},
1330                                         },
1331                                         Limit: &limit1,
1332                                         Order: "created_at desc",
1333                                 })
1334                         c.Assert(err, check.IsNil)
1335                         if len(logentries.Items) > 0 &&
1336                                 logentries.Items[0].ID > lastLogId &&
1337                                 logentries.Items[0].ObjectUUID == userUuid &&
1338                                 logentries.Items[0].Properties["collection_uuid"] == collectionUuid &&
1339                                 (collectionPDH == "" || logentries.Items[0].Properties["portable_data_hash"] == collectionPDH) &&
1340                                 logentries.Items[0].Properties["collection_file_path"] == filepath {
1341                                 break
1342                         }
1343                         c.Logf("logentries.Items: %+v", logentries.Items)
1344                         time.Sleep(50 * time.Millisecond)
1345                 }
1346         } else {
1347                 c.Check(resp.Result().StatusCode, check.Equals, http.StatusForbidden)
1348                 c.Check(logbuf.String(), check.Equals, "")
1349         }
1350 }
1351
1352 func (s *IntegrationSuite) TestDownloadLoggingPermission(c *check.C) {
1353         u := mustParseURL("http://" + arvadostest.FooCollection + ".keep-web.example/foo")
1354
1355         s.handler.Cluster.Collections.TrustAllContent = true
1356
1357         for _, adminperm := range []bool{true, false} {
1358                 for _, userperm := range []bool{true, false} {
1359                         s.handler.Cluster.Collections.WebDAVPermission.Admin.Download = adminperm
1360                         s.handler.Cluster.Collections.WebDAVPermission.User.Download = userperm
1361
1362                         // Test admin permission
1363                         req := &http.Request{
1364                                 Method:     "GET",
1365                                 Host:       u.Host,
1366                                 URL:        u,
1367                                 RequestURI: u.RequestURI(),
1368                                 Header: http.Header{
1369                                         "Authorization": {"Bearer " + arvadostest.AdminToken},
1370                                 },
1371                         }
1372                         s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", adminperm,
1373                                 arvadostest.AdminUserUUID, arvadostest.FooCollection, arvadostest.FooCollectionPDH, "foo")
1374
1375                         // Test user permission
1376                         req = &http.Request{
1377                                 Method:     "GET",
1378                                 Host:       u.Host,
1379                                 URL:        u,
1380                                 RequestURI: u.RequestURI(),
1381                                 Header: http.Header{
1382                                         "Authorization": {"Bearer " + arvadostest.ActiveToken},
1383                                 },
1384                         }
1385                         s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", userperm,
1386                                 arvadostest.ActiveUserUUID, arvadostest.FooCollection, arvadostest.FooCollectionPDH, "foo")
1387                 }
1388         }
1389
1390         s.handler.Cluster.Collections.WebDAVPermission.User.Download = true
1391
1392         for _, tryurl := range []string{"http://" + arvadostest.MultilevelCollection1 + ".keep-web.example/dir1/subdir/file1",
1393                 "http://keep-web/users/active/multilevel_collection_1/dir1/subdir/file1"} {
1394
1395                 u = mustParseURL(tryurl)
1396                 req := &http.Request{
1397                         Method:     "GET",
1398                         Host:       u.Host,
1399                         URL:        u,
1400                         RequestURI: u.RequestURI(),
1401                         Header: http.Header{
1402                                 "Authorization": {"Bearer " + arvadostest.ActiveToken},
1403                         },
1404                 }
1405                 s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", true,
1406                         arvadostest.ActiveUserUUID, arvadostest.MultilevelCollection1, arvadostest.MultilevelCollection1PDH, "dir1/subdir/file1")
1407         }
1408
1409         u = mustParseURL("http://" + strings.Replace(arvadostest.FooCollectionPDH, "+", "-", 1) + ".keep-web.example/foo")
1410         req := &http.Request{
1411                 Method:     "GET",
1412                 Host:       u.Host,
1413                 URL:        u,
1414                 RequestURI: u.RequestURI(),
1415                 Header: http.Header{
1416                         "Authorization": {"Bearer " + arvadostest.ActiveToken},
1417                 },
1418         }
1419         s.checkUploadDownloadRequest(c, req, http.StatusOK, "download", true,
1420                 arvadostest.ActiveUserUUID, "", arvadostest.FooCollectionPDH, "foo")
1421 }
1422
1423 func (s *IntegrationSuite) TestUploadLoggingPermission(c *check.C) {
1424         for _, adminperm := range []bool{true, false} {
1425                 for _, userperm := range []bool{true, false} {
1426
1427                         arv := arvados.NewClientFromEnv()
1428                         arv.AuthToken = arvadostest.ActiveToken
1429
1430                         var coll arvados.Collection
1431                         err := arv.RequestAndDecode(&coll,
1432                                 "POST",
1433                                 "/arvados/v1/collections",
1434                                 nil,
1435                                 map[string]interface{}{
1436                                         "ensure_unique_name": true,
1437                                         "collection": map[string]interface{}{
1438                                                 "name": "test collection",
1439                                         },
1440                                 })
1441                         c.Assert(err, check.Equals, nil)
1442
1443                         u := mustParseURL("http://" + coll.UUID + ".keep-web.example/bar")
1444
1445                         s.handler.Cluster.Collections.WebDAVPermission.Admin.Upload = adminperm
1446                         s.handler.Cluster.Collections.WebDAVPermission.User.Upload = userperm
1447
1448                         // Test admin permission
1449                         req := &http.Request{
1450                                 Method:     "PUT",
1451                                 Host:       u.Host,
1452                                 URL:        u,
1453                                 RequestURI: u.RequestURI(),
1454                                 Header: http.Header{
1455                                         "Authorization": {"Bearer " + arvadostest.AdminToken},
1456                                 },
1457                                 Body: io.NopCloser(bytes.NewReader([]byte("bar"))),
1458                         }
1459                         s.checkUploadDownloadRequest(c, req, http.StatusCreated, "upload", adminperm,
1460                                 arvadostest.AdminUserUUID, coll.UUID, "", "bar")
1461
1462                         // Test user permission
1463                         req = &http.Request{
1464                                 Method:     "PUT",
1465                                 Host:       u.Host,
1466                                 URL:        u,
1467                                 RequestURI: u.RequestURI(),
1468                                 Header: http.Header{
1469                                         "Authorization": {"Bearer " + arvadostest.ActiveToken},
1470                                 },
1471                                 Body: io.NopCloser(bytes.NewReader([]byte("bar"))),
1472                         }
1473                         s.checkUploadDownloadRequest(c, req, http.StatusCreated, "upload", userperm,
1474                                 arvadostest.ActiveUserUUID, coll.UUID, "", "bar")
1475                 }
1476         }
1477 }