14262: Move the context deadline to the top of the handler stack
[arvados.git] / lib / controller / federation_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package controller
6
7 import (
8         "bytes"
9         "encoding/json"
10         "fmt"
11         "io"
12         "io/ioutil"
13         "net/http"
14         "net/http/httptest"
15         "net/url"
16         "os"
17         "strings"
18         "time"
19
20         "git.curoverse.com/arvados.git/sdk/go/arvados"
21         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
22         "git.curoverse.com/arvados.git/sdk/go/httpserver"
23         "git.curoverse.com/arvados.git/sdk/go/keepclient"
24         "github.com/Sirupsen/logrus"
25         check "gopkg.in/check.v1"
26 )
27
28 // Gocheck boilerplate
29 var _ = check.Suite(&FederationSuite{})
30
31 type FederationSuite struct {
32         log *logrus.Logger
33         // testServer and testHandler are the controller being tested,
34         // "zhome".
35         testServer  *httpserver.Server
36         testHandler *Handler
37         // remoteServer ("zzzzz") forwards requests to the Rails API
38         // provided by the integration test environment.
39         remoteServer *httpserver.Server
40         // remoteMock ("zmock") appends each incoming request to
41         // remoteMockRequests, and returns an empty 200 response.
42         remoteMock         *httpserver.Server
43         remoteMockRequests []http.Request
44 }
45
46 func (s *FederationSuite) SetUpTest(c *check.C) {
47         s.log = logrus.New()
48         s.log.Formatter = &logrus.JSONFormatter{}
49         s.log.Out = &logWriter{c.Log}
50
51         s.remoteServer = newServerFromIntegrationTestEnv(c)
52         c.Assert(s.remoteServer.Start(), check.IsNil)
53
54         s.remoteMock = newServerFromIntegrationTestEnv(c)
55         s.remoteMock.Server.Handler = http.HandlerFunc(s.remoteMockHandler)
56         c.Assert(s.remoteMock.Start(), check.IsNil)
57
58         nodeProfile := arvados.NodeProfile{
59                 Controller: arvados.SystemServiceInstance{Listen: ":"},
60                 RailsAPI:   arvados.SystemServiceInstance{Listen: ":1"}, // local reqs will error "connection refused"
61         }
62         s.testHandler = &Handler{Cluster: &arvados.Cluster{
63                 ClusterID:  "zhome",
64                 PostgreSQL: integrationTestCluster().PostgreSQL,
65                 NodeProfiles: map[string]arvados.NodeProfile{
66                         "*": nodeProfile,
67                 },
68                 RequestLimits: arvados.RequestLimits{
69                         MaxItemsPerResponse:            1000,
70                         MultiClusterRequestConcurrency: 4,
71                 },
72         }, NodeProfile: &nodeProfile}
73         s.testServer = newServerFromIntegrationTestEnv(c)
74         s.testServer.Server.Handler = httpserver.AddRequestIDs(httpserver.LogRequests(s.log, s.testHandler))
75
76         s.testHandler.Cluster.RemoteClusters = map[string]arvados.RemoteCluster{
77                 "zzzzz": {
78                         Host:   s.remoteServer.Addr,
79                         Proxy:  true,
80                         Scheme: "http",
81                 },
82                 "zmock": {
83                         Host:   s.remoteMock.Addr,
84                         Proxy:  true,
85                         Scheme: "http",
86                 },
87         }
88
89         c.Assert(s.testServer.Start(), check.IsNil)
90
91         s.remoteMockRequests = nil
92 }
93
94 func (s *FederationSuite) remoteMockHandler(w http.ResponseWriter, req *http.Request) {
95         b := &bytes.Buffer{}
96         io.Copy(b, req.Body)
97         req.Body.Close()
98         req.Body = ioutil.NopCloser(b)
99         s.remoteMockRequests = append(s.remoteMockRequests, *req)
100 }
101
102 func (s *FederationSuite) TearDownTest(c *check.C) {
103         if s.remoteServer != nil {
104                 s.remoteServer.Close()
105         }
106         if s.testServer != nil {
107                 s.testServer.Close()
108         }
109 }
110
111 func (s *FederationSuite) testRequest(req *http.Request) *http.Response {
112         resp := httptest.NewRecorder()
113         s.testServer.Server.Handler.ServeHTTP(resp, req)
114         return resp.Result()
115 }
116
117 func (s *FederationSuite) TestLocalRequest(c *check.C) {
118         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+strings.Replace(arvadostest.WorkflowWithDefinitionYAMLUUID, "zzzzz-", "zhome-", 1), nil)
119         resp := s.testRequest(req)
120         s.checkHandledLocally(c, resp)
121 }
122
123 func (s *FederationSuite) checkHandledLocally(c *check.C, resp *http.Response) {
124         // Our "home" controller can't handle local requests because
125         // it doesn't have its own stub/test Rails API, so we rely on
126         // "connection refused" to indicate the controller tried to
127         // proxy the request to its local Rails API.
128         c.Check(resp.StatusCode, check.Equals, http.StatusBadGateway)
129         s.checkJSONErrorMatches(c, resp, `.*connection refused`)
130 }
131
132 func (s *FederationSuite) TestNoAuth(c *check.C) {
133         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
134         resp := s.testRequest(req)
135         c.Check(resp.StatusCode, check.Equals, http.StatusUnauthorized)
136         s.checkJSONErrorMatches(c, resp, `Not logged in`)
137 }
138
139 func (s *FederationSuite) TestBadAuth(c *check.C) {
140         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
141         req.Header.Set("Authorization", "Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
142         resp := s.testRequest(req)
143         c.Check(resp.StatusCode, check.Equals, http.StatusUnauthorized)
144         s.checkJSONErrorMatches(c, resp, `Not logged in`)
145 }
146
147 func (s *FederationSuite) TestNoAccess(c *check.C) {
148         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
149         req.Header.Set("Authorization", "Bearer "+arvadostest.SpectatorToken)
150         resp := s.testRequest(req)
151         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
152         s.checkJSONErrorMatches(c, resp, `.*not found`)
153 }
154
155 func (s *FederationSuite) TestGetUnknownRemote(c *check.C) {
156         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+strings.Replace(arvadostest.WorkflowWithDefinitionYAMLUUID, "zzzzz-", "zz404-", 1), nil)
157         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
158         resp := s.testRequest(req)
159         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
160         s.checkJSONErrorMatches(c, resp, `.*no proxy available for cluster zz404`)
161 }
162
163 func (s *FederationSuite) TestRemoteError(c *check.C) {
164         rc := s.testHandler.Cluster.RemoteClusters["zzzzz"]
165         rc.Scheme = "https"
166         s.testHandler.Cluster.RemoteClusters["zzzzz"] = rc
167
168         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
169         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
170         resp := s.testRequest(req)
171         c.Check(resp.StatusCode, check.Equals, http.StatusBadGateway)
172         s.checkJSONErrorMatches(c, resp, `.*HTTP response to HTTPS client`)
173 }
174
175 func (s *FederationSuite) TestGetRemoteWorkflow(c *check.C) {
176         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
177         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
178         resp := s.testRequest(req)
179         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
180         var wf arvados.Workflow
181         c.Check(json.NewDecoder(resp.Body).Decode(&wf), check.IsNil)
182         c.Check(wf.UUID, check.Equals, arvadostest.WorkflowWithDefinitionYAMLUUID)
183         c.Check(wf.OwnerUUID, check.Equals, arvadostest.ActiveUserUUID)
184 }
185
186 func (s *FederationSuite) TestOptionsMethod(c *check.C) {
187         req := httptest.NewRequest("OPTIONS", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
188         req.Header.Set("Origin", "https://example.com")
189         resp := s.testRequest(req)
190         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
191         body, err := ioutil.ReadAll(resp.Body)
192         c.Check(err, check.IsNil)
193         c.Check(string(body), check.Equals, "")
194         c.Check(resp.Header.Get("Access-Control-Allow-Origin"), check.Equals, "*")
195         for _, hdr := range []string{"Authorization", "Content-Type"} {
196                 c.Check(resp.Header.Get("Access-Control-Allow-Headers"), check.Matches, ".*"+hdr+".*")
197         }
198         for _, method := range []string{"GET", "HEAD", "PUT", "POST", "DELETE"} {
199                 c.Check(resp.Header.Get("Access-Control-Allow-Methods"), check.Matches, ".*"+method+".*")
200         }
201 }
202
203 func (s *FederationSuite) TestRemoteWithTokenInQuery(c *check.C) {
204         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+strings.Replace(arvadostest.WorkflowWithDefinitionYAMLUUID, "zzzzz-", "zmock-", 1)+"?api_token="+arvadostest.ActiveToken, nil)
205         s.testRequest(req)
206         c.Assert(s.remoteMockRequests, check.HasLen, 1)
207         pr := s.remoteMockRequests[0]
208         // Token is salted and moved from query to Authorization header.
209         c.Check(pr.URL.String(), check.Not(check.Matches), `.*api_token=.*`)
210         c.Check(pr.Header.Get("Authorization"), check.Equals, "Bearer v2/zzzzz-gj3su-077z32aux8dg2s1/7fd31b61f39c0e82a4155592163218272cedacdc")
211 }
212
213 func (s *FederationSuite) TestLocalTokenSalted(c *check.C) {
214         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+strings.Replace(arvadostest.WorkflowWithDefinitionYAMLUUID, "zzzzz-", "zmock-", 1), nil)
215         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
216         s.testRequest(req)
217         c.Assert(s.remoteMockRequests, check.HasLen, 1)
218         pr := s.remoteMockRequests[0]
219         // The salted token here has a "zzzzz-" UUID instead of a
220         // "ztest-" UUID because ztest's local database has the
221         // "zzzzz-" test fixtures. The "secret" part is HMAC(sha1,
222         // arvadostest.ActiveToken, "zmock") = "7fd3...".
223         c.Check(pr.Header.Get("Authorization"), check.Equals, "Bearer v2/zzzzz-gj3su-077z32aux8dg2s1/7fd31b61f39c0e82a4155592163218272cedacdc")
224 }
225
226 func (s *FederationSuite) TestRemoteTokenNotSalted(c *check.C) {
227         // remoteToken can be any v1 token that doesn't appear in
228         // ztest's local db.
229         remoteToken := "abcdef00000000000000000000000000000000000000000000"
230         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+strings.Replace(arvadostest.WorkflowWithDefinitionYAMLUUID, "zzzzz-", "zmock-", 1), nil)
231         req.Header.Set("Authorization", "Bearer "+remoteToken)
232         s.testRequest(req)
233         c.Assert(s.remoteMockRequests, check.HasLen, 1)
234         pr := s.remoteMockRequests[0]
235         c.Check(pr.Header.Get("Authorization"), check.Equals, "Bearer "+remoteToken)
236 }
237
238 func (s *FederationSuite) TestWorkflowCRUD(c *check.C) {
239         wf := arvados.Workflow{
240                 Description: "TestCRUD",
241         }
242         {
243                 body := &strings.Builder{}
244                 json.NewEncoder(body).Encode(&wf)
245                 req := httptest.NewRequest("POST", "/arvados/v1/workflows", strings.NewReader(url.Values{
246                         "workflow": {body.String()},
247                 }.Encode()))
248                 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
249                 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
250                 rec := httptest.NewRecorder()
251                 s.remoteServer.Server.Handler.ServeHTTP(rec, req) // direct to remote -- can't proxy a create req because no uuid
252                 resp := rec.Result()
253                 s.checkResponseOK(c, resp)
254                 json.NewDecoder(resp.Body).Decode(&wf)
255
256                 defer func() {
257                         req := httptest.NewRequest("DELETE", "/arvados/v1/workflows/"+wf.UUID, nil)
258                         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
259                         s.remoteServer.Server.Handler.ServeHTTP(httptest.NewRecorder(), req)
260                 }()
261                 c.Check(wf.UUID, check.Not(check.Equals), "")
262
263                 c.Assert(wf.ModifiedAt, check.NotNil)
264                 c.Logf("wf.ModifiedAt: %v", wf.ModifiedAt)
265                 c.Check(time.Since(*wf.ModifiedAt) < time.Minute, check.Equals, true)
266         }
267         for _, method := range []string{"PATCH", "PUT", "POST"} {
268                 form := url.Values{
269                         "workflow": {`{"description": "Updated with ` + method + `"}`},
270                 }
271                 if method == "POST" {
272                         form["_method"] = []string{"PATCH"}
273                 }
274                 req := httptest.NewRequest(method, "/arvados/v1/workflows/"+wf.UUID, strings.NewReader(form.Encode()))
275                 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
276                 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
277                 resp := s.testRequest(req)
278                 s.checkResponseOK(c, resp)
279                 err := json.NewDecoder(resp.Body).Decode(&wf)
280                 c.Check(err, check.IsNil)
281
282                 c.Check(wf.Description, check.Equals, "Updated with "+method)
283         }
284         {
285                 req := httptest.NewRequest("DELETE", "/arvados/v1/workflows/"+wf.UUID, nil)
286                 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
287                 resp := s.testRequest(req)
288                 s.checkResponseOK(c, resp)
289                 err := json.NewDecoder(resp.Body).Decode(&wf)
290                 c.Check(err, check.IsNil)
291         }
292         {
293                 req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+wf.UUID, nil)
294                 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
295                 resp := s.testRequest(req)
296                 c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
297         }
298 }
299
300 func (s *FederationSuite) checkResponseOK(c *check.C, resp *http.Response) {
301         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
302         if resp.StatusCode != http.StatusOK {
303                 body, err := ioutil.ReadAll(resp.Body)
304                 c.Logf("... response body = %q, %v\n", body, err)
305         }
306 }
307
308 func (s *FederationSuite) checkJSONErrorMatches(c *check.C, resp *http.Response, re string) {
309         var jresp httpserver.ErrorResponse
310         err := json.NewDecoder(resp.Body).Decode(&jresp)
311         c.Check(err, check.IsNil)
312         c.Assert(jresp.Errors, check.HasLen, 1)
313         c.Check(jresp.Errors[0], check.Matches, re)
314 }
315
316 func (s *FederationSuite) localServiceHandler(c *check.C, h http.Handler) *httpserver.Server {
317         srv := &httpserver.Server{
318                 Server: http.Server{
319                         Handler: h,
320                 },
321         }
322
323         c.Assert(srv.Start(), check.IsNil)
324
325         np := arvados.NodeProfile{
326                 Controller: arvados.SystemServiceInstance{Listen: ":"},
327                 RailsAPI: arvados.SystemServiceInstance{Listen: srv.Addr,
328                         TLS: false, Insecure: true}}
329         s.testHandler.Cluster.NodeProfiles["*"] = np
330         s.testHandler.NodeProfile = &np
331
332         return srv
333 }
334
335 func (s *FederationSuite) localServiceReturns404(c *check.C) *httpserver.Server {
336         return s.localServiceHandler(c, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
337                 w.WriteHeader(404)
338         }))
339 }
340
341 func (s *FederationSuite) TestGetLocalCollection(c *check.C) {
342         np := arvados.NodeProfile{
343                 Controller: arvados.SystemServiceInstance{Listen: ":"},
344                 RailsAPI: arvados.SystemServiceInstance{Listen: os.Getenv("ARVADOS_TEST_API_HOST"),
345                         TLS: true, Insecure: true}}
346         s.testHandler.Cluster.ClusterID = "zzzzz"
347         s.testHandler.Cluster.NodeProfiles["*"] = np
348         s.testHandler.NodeProfile = &np
349
350         req := httptest.NewRequest("GET", "/arvados/v1/collections/"+arvadostest.UserAgreementCollection, nil)
351         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
352         resp := s.testRequest(req)
353
354         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
355         var col arvados.Collection
356         c.Check(json.NewDecoder(resp.Body).Decode(&col), check.IsNil)
357         c.Check(col.UUID, check.Equals, arvadostest.UserAgreementCollection)
358         c.Check(col.ManifestText, check.Matches,
359                 `\. 6a4ff0499484c6c79c95cd8c566bd25f\+249025\+A[0-9a-f]{40}@[0-9a-f]{8} 0:249025:GNU_General_Public_License,_version_3.pdf
360 `)
361 }
362
363 func (s *FederationSuite) TestGetRemoteCollection(c *check.C) {
364         defer s.localServiceReturns404(c).Close()
365
366         req := httptest.NewRequest("GET", "/arvados/v1/collections/"+arvadostest.UserAgreementCollection, nil)
367         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
368         resp := s.testRequest(req)
369         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
370         var col arvados.Collection
371         c.Check(json.NewDecoder(resp.Body).Decode(&col), check.IsNil)
372         c.Check(col.UUID, check.Equals, arvadostest.UserAgreementCollection)
373         c.Check(col.ManifestText, check.Matches,
374                 `\. 6a4ff0499484c6c79c95cd8c566bd25f\+249025\+Rzzzzz-[0-9a-f]{40}@[0-9a-f]{8} 0:249025:GNU_General_Public_License,_version_3.pdf
375 `)
376 }
377
378 func (s *FederationSuite) TestGetRemoteCollectionError(c *check.C) {
379         defer s.localServiceReturns404(c).Close()
380
381         req := httptest.NewRequest("GET", "/arvados/v1/collections/zzzzz-4zz18-fakefakefakefak", nil)
382         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
383         resp := s.testRequest(req)
384         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
385 }
386
387 func (s *FederationSuite) TestSignedLocatorPattern(c *check.C) {
388         // Confirm the regular expression identifies other groups of hints correctly
389         c.Check(keepclient.SignedLocatorRe.FindStringSubmatch(`6a4ff0499484c6c79c95cd8c566bd25f+249025+B1+C2+A05227438989d04712ea9ca1c91b556cef01d5cc7@5ba5405b+D3+E4`),
390                 check.DeepEquals,
391                 []string{"6a4ff0499484c6c79c95cd8c566bd25f+249025+B1+C2+A05227438989d04712ea9ca1c91b556cef01d5cc7@5ba5405b+D3+E4",
392                         "6a4ff0499484c6c79c95cd8c566bd25f",
393                         "+249025",
394                         "+B1+C2", "+C2",
395                         "+A05227438989d04712ea9ca1c91b556cef01d5cc7@5ba5405b",
396                         "05227438989d04712ea9ca1c91b556cef01d5cc7", "5ba5405b",
397                         "+D3+E4", "+E4"})
398 }
399
400 func (s *FederationSuite) TestGetLocalCollectionByPDH(c *check.C) {
401         np := arvados.NodeProfile{
402                 Controller: arvados.SystemServiceInstance{Listen: ":"},
403                 RailsAPI: arvados.SystemServiceInstance{Listen: os.Getenv("ARVADOS_TEST_API_HOST"),
404                         TLS: true, Insecure: true}}
405         s.testHandler.Cluster.NodeProfiles["*"] = np
406         s.testHandler.NodeProfile = &np
407
408         req := httptest.NewRequest("GET", "/arvados/v1/collections/"+arvadostest.UserAgreementPDH, nil)
409         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
410         resp := s.testRequest(req)
411
412         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
413         var col arvados.Collection
414         c.Check(json.NewDecoder(resp.Body).Decode(&col), check.IsNil)
415         c.Check(col.PortableDataHash, check.Equals, arvadostest.UserAgreementPDH)
416         c.Check(col.ManifestText, check.Matches,
417                 `\. 6a4ff0499484c6c79c95cd8c566bd25f\+249025\+A[0-9a-f]{40}@[0-9a-f]{8} 0:249025:GNU_General_Public_License,_version_3.pdf
418 `)
419 }
420
421 func (s *FederationSuite) TestGetRemoteCollectionByPDH(c *check.C) {
422         defer s.localServiceReturns404(c).Close()
423
424         req := httptest.NewRequest("GET", "/arvados/v1/collections/"+arvadostest.UserAgreementPDH, nil)
425         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
426         resp := s.testRequest(req)
427
428         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
429
430         var col arvados.Collection
431         c.Check(json.NewDecoder(resp.Body).Decode(&col), check.IsNil)
432         c.Check(col.PortableDataHash, check.Equals, arvadostest.UserAgreementPDH)
433         c.Check(col.ManifestText, check.Matches,
434                 `\. 6a4ff0499484c6c79c95cd8c566bd25f\+249025\+Rzzzzz-[0-9a-f]{40}@[0-9a-f]{8} 0:249025:GNU_General_Public_License,_version_3.pdf
435 `)
436 }
437
438 func (s *FederationSuite) TestGetCollectionByPDHError(c *check.C) {
439         defer s.localServiceReturns404(c).Close()
440
441         req := httptest.NewRequest("GET", "/arvados/v1/collections/99999999999999999999999999999999+99", nil)
442         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
443
444         resp := s.testRequest(req)
445         defer resp.Body.Close()
446
447         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
448 }
449
450 func (s *FederationSuite) TestGetCollectionByPDHErrorBadHash(c *check.C) {
451         defer s.localServiceReturns404(c).Close()
452
453         srv2 := &httpserver.Server{
454                 Server: http.Server{
455                         Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
456                                 w.WriteHeader(200)
457                                 // Return a collection where the hash
458                                 // of the manifest text doesn't match
459                                 // PDH that was requested.
460                                 var col arvados.Collection
461                                 col.PortableDataHash = "99999999999999999999999999999999+99"
462                                 col.ManifestText = `. 6a4ff0499484c6c79c95cd8c566bd25f\+249025 0:249025:GNU_General_Public_License,_version_3.pdf
463 `
464                                 enc := json.NewEncoder(w)
465                                 enc.Encode(col)
466                         }),
467                 },
468         }
469
470         c.Assert(srv2.Start(), check.IsNil)
471         defer srv2.Close()
472
473         // Direct zzzzz to service that returns a 200 result with a bogus manifest_text
474         s.testHandler.Cluster.RemoteClusters["zzzzz"] = arvados.RemoteCluster{
475                 Host:   srv2.Addr,
476                 Proxy:  true,
477                 Scheme: "http",
478         }
479
480         req := httptest.NewRequest("GET", "/arvados/v1/collections/99999999999999999999999999999999+99", nil)
481         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
482
483         resp := s.testRequest(req)
484         defer resp.Body.Close()
485
486         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
487 }
488
489 func (s *FederationSuite) TestSaltedTokenGetCollectionByPDH(c *check.C) {
490         np := arvados.NodeProfile{
491                 Controller: arvados.SystemServiceInstance{Listen: ":"},
492                 RailsAPI: arvados.SystemServiceInstance{Listen: os.Getenv("ARVADOS_TEST_API_HOST"),
493                         TLS: true, Insecure: true}}
494         s.testHandler.Cluster.NodeProfiles["*"] = np
495         s.testHandler.NodeProfile = &np
496
497         req := httptest.NewRequest("GET", "/arvados/v1/collections/"+arvadostest.UserAgreementPDH, nil)
498         req.Header.Set("Authorization", "Bearer v2/zzzzz-gj3su-077z32aux8dg2s1/282d7d172b6cfdce364c5ed12ddf7417b2d00065")
499         resp := s.testRequest(req)
500
501         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
502         var col arvados.Collection
503         c.Check(json.NewDecoder(resp.Body).Decode(&col), check.IsNil)
504         c.Check(col.PortableDataHash, check.Equals, arvadostest.UserAgreementPDH)
505         c.Check(col.ManifestText, check.Matches,
506                 `\. 6a4ff0499484c6c79c95cd8c566bd25f\+249025\+A[0-9a-f]{40}@[0-9a-f]{8} 0:249025:GNU_General_Public_License,_version_3.pdf
507 `)
508 }
509
510 func (s *FederationSuite) TestSaltedTokenGetCollectionByPDHError(c *check.C) {
511         np := arvados.NodeProfile{
512                 Controller: arvados.SystemServiceInstance{Listen: ":"},
513                 RailsAPI: arvados.SystemServiceInstance{Listen: os.Getenv("ARVADOS_TEST_API_HOST"),
514                         TLS: true, Insecure: true}}
515         s.testHandler.Cluster.NodeProfiles["*"] = np
516         s.testHandler.NodeProfile = &np
517
518         req := httptest.NewRequest("GET", "/arvados/v1/collections/99999999999999999999999999999999+99", nil)
519         req.Header.Set("Authorization", "Bearer v2/zzzzz-gj3su-077z32aux8dg2s1/282d7d172b6cfdce364c5ed12ddf7417b2d00065")
520         resp := s.testRequest(req)
521
522         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
523 }
524
525 func (s *FederationSuite) TestGetRemoteContainerRequest(c *check.C) {
526         defer s.localServiceReturns404(c).Close()
527         req := httptest.NewRequest("GET", "/arvados/v1/container_requests/"+arvadostest.QueuedContainerRequestUUID, nil)
528         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
529         resp := s.testRequest(req)
530         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
531         var cr arvados.ContainerRequest
532         c.Check(json.NewDecoder(resp.Body).Decode(&cr), check.IsNil)
533         c.Check(cr.UUID, check.Equals, arvadostest.QueuedContainerRequestUUID)
534         c.Check(cr.Priority, check.Equals, 1)
535 }
536
537 func (s *FederationSuite) TestUpdateRemoteContainerRequest(c *check.C) {
538         defer s.localServiceReturns404(c).Close()
539         req := httptest.NewRequest("PATCH", "/arvados/v1/container_requests/"+arvadostest.QueuedContainerRequestUUID,
540                 strings.NewReader(`{"container_request": {"priority": 696}}`))
541         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
542         req.Header.Set("Content-type", "application/json")
543         resp := s.testRequest(req)
544         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
545         var cr arvados.ContainerRequest
546         c.Check(json.NewDecoder(resp.Body).Decode(&cr), check.IsNil)
547         c.Check(cr.UUID, check.Equals, arvadostest.QueuedContainerRequestUUID)
548         c.Check(cr.Priority, check.Equals, 696)
549 }
550
551 func (s *FederationSuite) TestCreateRemoteContainerRequest(c *check.C) {
552         defer s.localServiceReturns404(c).Close()
553         // pass cluster_id via query parameter, this allows arvados-controller
554         // to avoid parsing the body
555         req := httptest.NewRequest("POST", "/arvados/v1/container_requests?cluster_id=zzzzz",
556                 strings.NewReader(`{
557   "container_request": {
558     "name": "hello world",
559     "state": "Uncommitted",
560     "output_path": "/",
561     "container_image": "123",
562     "command": ["abc"]
563   }
564 }
565 `))
566         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
567         req.Header.Set("Content-type", "application/json")
568         resp := s.testRequest(req)
569         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
570         var cr arvados.ContainerRequest
571         c.Check(json.NewDecoder(resp.Body).Decode(&cr), check.IsNil)
572         c.Check(cr.Name, check.Equals, "hello world")
573         c.Check(strings.HasPrefix(cr.UUID, "zzzzz-"), check.Equals, true)
574 }
575
576 func (s *FederationSuite) TestCreateRemoteContainerRequestCheckRuntimeToken(c *check.C) {
577         // Send request to zmock and check that outgoing request has
578         // runtime_token sent (because runtime_token isn't returned in
579         // the response).
580
581         defer s.localServiceReturns404(c).Close()
582         // pass cluster_id via query parameter, this allows arvados-controller
583         // to avoid parsing the body
584         req := httptest.NewRequest("POST", "/arvados/v1/container_requests?cluster_id=zmock",
585                 strings.NewReader(`{
586   "container_request": {
587     "name": "hello world",
588     "state": "Uncommitted",
589     "output_path": "/",
590     "container_image": "123",
591     "command": ["abc"]
592   }
593 }
594 `))
595         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
596         req.Header.Set("Content-type", "application/json")
597
598         np := arvados.NodeProfile{
599                 Controller: arvados.SystemServiceInstance{Listen: ":"},
600                 RailsAPI: arvados.SystemServiceInstance{Listen: os.Getenv("ARVADOS_TEST_API_HOST"),
601                         TLS: true, Insecure: true}}
602         s.testHandler.Cluster.ClusterID = "zzzzz"
603         s.testHandler.Cluster.NodeProfiles["*"] = np
604         s.testHandler.NodeProfile = &np
605
606         resp := s.testRequest(req)
607         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
608         var cr struct {
609                 arvados.ContainerRequest `json:"container_request"`
610         }
611         c.Check(json.NewDecoder(s.remoteMockRequests[0].Body).Decode(&cr), check.IsNil)
612         c.Check(strings.HasPrefix(cr.ContainerRequest.RuntimeToken, "v2/"), check.Equals, true)
613 }
614
615 func (s *FederationSuite) TestCreateRemoteContainerRequestCheckSetRuntimeToken(c *check.C) {
616         // Send request to zmock and check that outgoing request has
617         // runtime_token sent (because runtime_token isn't returned in
618         // the response).
619
620         defer s.localServiceReturns404(c).Close()
621         // pass cluster_id via query parameter, this allows arvados-controller
622         // to avoid parsing the body
623         req := httptest.NewRequest("POST", "/arvados/v1/container_requests?cluster_id=zmock",
624                 strings.NewReader(`{
625   "container_request": {
626     "name": "hello world",
627     "state": "Uncommitted",
628     "output_path": "/",
629     "container_image": "123",
630     "command": ["abc"],
631     "runtime_token": "xyz"
632   }
633 }
634 `))
635         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
636         req.Header.Set("Content-type", "application/json")
637         resp := s.testRequest(req)
638         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
639         var cr struct {
640                 arvados.ContainerRequest `json:"container_request"`
641         }
642         c.Check(json.NewDecoder(s.remoteMockRequests[0].Body).Decode(&cr), check.IsNil)
643         c.Check(cr.ContainerRequest.RuntimeToken, check.Equals, "xyz")
644 }
645
646 func (s *FederationSuite) TestCreateRemoteContainerRequestError(c *check.C) {
647         defer s.localServiceReturns404(c).Close()
648         // pass cluster_id via query parameter, this allows arvados-controller
649         // to avoid parsing the body
650         req := httptest.NewRequest("POST", "/arvados/v1/container_requests?cluster_id=zz404",
651                 strings.NewReader(`{
652   "container_request": {
653     "name": "hello world",
654     "state": "Uncommitted",
655     "output_path": "/",
656     "container_image": "123",
657     "command": ["abc"]
658   }
659 }
660 `))
661         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
662         req.Header.Set("Content-type", "application/json")
663         resp := s.testRequest(req)
664         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
665 }
666
667 func (s *FederationSuite) TestGetRemoteContainer(c *check.C) {
668         defer s.localServiceReturns404(c).Close()
669         req := httptest.NewRequest("GET", "/arvados/v1/containers/"+arvadostest.QueuedContainerUUID, nil)
670         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
671         resp := s.testRequest(req)
672         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
673         var cn arvados.Container
674         c.Check(json.NewDecoder(resp.Body).Decode(&cn), check.IsNil)
675         c.Check(cn.UUID, check.Equals, arvadostest.QueuedContainerUUID)
676 }
677
678 func (s *FederationSuite) TestListRemoteContainer(c *check.C) {
679         defer s.localServiceReturns404(c).Close()
680         req := httptest.NewRequest("GET", "/arvados/v1/containers?count=none&filters="+
681                 url.QueryEscape(fmt.Sprintf(`[["uuid", "in", ["%v"]]]`, arvadostest.QueuedContainerUUID)), nil)
682         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
683         resp := s.testRequest(req)
684         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
685         var cn arvados.ContainerList
686         c.Check(json.NewDecoder(resp.Body).Decode(&cn), check.IsNil)
687         c.Check(cn.Items[0].UUID, check.Equals, arvadostest.QueuedContainerUUID)
688 }
689
690 func (s *FederationSuite) TestListMultiRemoteContainers(c *check.C) {
691         defer s.localServiceHandler(c, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
692                 bd, _ := ioutil.ReadAll(req.Body)
693                 c.Check(string(bd), check.Equals, `_method=GET&count=none&filters=%5B%5B%22uuid%22%2C+%22in%22%2C+%5B%22zhome-xvhdp-cr5queuedcontnr%22%5D%5D%5D&select=%5B%22uuid%22%2C+%22command%22%5D`)
694                 w.WriteHeader(200)
695                 w.Write([]byte(`{"kind": "arvados#containerList", "items": [{"uuid": "zhome-xvhdp-cr5queuedcontnr", "command": ["abc"]}]}`))
696         })).Close()
697         req := httptest.NewRequest("GET", fmt.Sprintf("/arvados/v1/containers?count=none&filters=%s&select=%s",
698                 url.QueryEscape(fmt.Sprintf(`[["uuid", "in", ["%v", "zhome-xvhdp-cr5queuedcontnr"]]]`,
699                         arvadostest.QueuedContainerUUID)),
700                 url.QueryEscape(`["uuid", "command"]`)),
701                 nil)
702         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
703         resp := s.testRequest(req)
704         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
705         var cn arvados.ContainerList
706         c.Check(json.NewDecoder(resp.Body).Decode(&cn), check.IsNil)
707         c.Check(cn.Items, check.HasLen, 2)
708         mp := make(map[string]arvados.Container)
709         for _, cr := range cn.Items {
710                 mp[cr.UUID] = cr
711         }
712         c.Check(mp[arvadostest.QueuedContainerUUID].Command, check.DeepEquals, []string{"echo", "hello"})
713         c.Check(mp[arvadostest.QueuedContainerUUID].ContainerImage, check.Equals, "")
714         c.Check(mp["zhome-xvhdp-cr5queuedcontnr"].Command, check.DeepEquals, []string{"abc"})
715         c.Check(mp["zhome-xvhdp-cr5queuedcontnr"].ContainerImage, check.Equals, "")
716 }
717
718 func (s *FederationSuite) TestListMultiRemoteContainerError(c *check.C) {
719         defer s.localServiceReturns404(c).Close()
720         req := httptest.NewRequest("GET", fmt.Sprintf("/arvados/v1/containers?count=none&filters=%s&select=%s",
721                 url.QueryEscape(fmt.Sprintf(`[["uuid", "in", ["%v", "zhome-xvhdp-cr5queuedcontnr"]]]`,
722                         arvadostest.QueuedContainerUUID)),
723                 url.QueryEscape(`["uuid", "command"]`)),
724                 nil)
725         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
726         resp := s.testRequest(req)
727         c.Check(resp.StatusCode, check.Equals, http.StatusBadGateway)
728         s.checkJSONErrorMatches(c, resp, `error fetching from zhome \(404 Not Found\): EOF`)
729 }
730
731 func (s *FederationSuite) TestListMultiRemoteContainersPaged(c *check.C) {
732
733         callCount := 0
734         defer s.localServiceHandler(c, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
735                 bd, _ := ioutil.ReadAll(req.Body)
736                 if callCount == 0 {
737                         c.Check(string(bd), check.Equals, `_method=GET&count=none&filters=%5B%5B%22uuid%22%2C+%22in%22%2C+%5B%22zhome-xvhdp-cr5queuedcontnr%22%2C%22zhome-xvhdp-cr6queuedcontnr%22%5D%5D%5D`)
738                         w.WriteHeader(200)
739                         w.Write([]byte(`{"kind": "arvados#containerList", "items": [{"uuid": "zhome-xvhdp-cr5queuedcontnr", "command": ["abc"]}]}`))
740                 } else if callCount == 1 {
741                         c.Check(string(bd), check.Equals, `_method=GET&count=none&filters=%5B%5B%22uuid%22%2C+%22in%22%2C+%5B%22zhome-xvhdp-cr6queuedcontnr%22%5D%5D%5D`)
742                         w.WriteHeader(200)
743                         w.Write([]byte(`{"kind": "arvados#containerList", "items": [{"uuid": "zhome-xvhdp-cr6queuedcontnr", "command": ["efg"]}]}`))
744                 }
745                 callCount += 1
746         })).Close()
747         req := httptest.NewRequest("GET", fmt.Sprintf("/arvados/v1/containers?count=none&filters=%s",
748                 url.QueryEscape(fmt.Sprintf(`[["uuid", "in", ["%v", "zhome-xvhdp-cr5queuedcontnr", "zhome-xvhdp-cr6queuedcontnr"]]]`,
749                         arvadostest.QueuedContainerUUID))),
750                 nil)
751         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
752         resp := s.testRequest(req)
753         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
754         c.Check(callCount, check.Equals, 2)
755         var cn arvados.ContainerList
756         c.Check(json.NewDecoder(resp.Body).Decode(&cn), check.IsNil)
757         c.Check(cn.Items, check.HasLen, 3)
758         mp := make(map[string]arvados.Container)
759         for _, cr := range cn.Items {
760                 mp[cr.UUID] = cr
761         }
762         c.Check(mp[arvadostest.QueuedContainerUUID].Command, check.DeepEquals, []string{"echo", "hello"})
763         c.Check(mp["zhome-xvhdp-cr5queuedcontnr"].Command, check.DeepEquals, []string{"abc"})
764         c.Check(mp["zhome-xvhdp-cr6queuedcontnr"].Command, check.DeepEquals, []string{"efg"})
765 }
766
767 func (s *FederationSuite) TestListMultiRemoteContainersMissing(c *check.C) {
768
769         callCount := 0
770         defer s.localServiceHandler(c, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
771                 bd, _ := ioutil.ReadAll(req.Body)
772                 if callCount == 0 {
773                         c.Check(string(bd), check.Equals, `_method=GET&count=none&filters=%5B%5B%22uuid%22%2C+%22in%22%2C+%5B%22zhome-xvhdp-cr5queuedcontnr%22%2C%22zhome-xvhdp-cr6queuedcontnr%22%5D%5D%5D`)
774                         w.WriteHeader(200)
775                         w.Write([]byte(`{"kind": "arvados#containerList", "items": [{"uuid": "zhome-xvhdp-cr6queuedcontnr", "command": ["efg"]}]}`))
776                 } else if callCount == 1 {
777                         c.Check(string(bd), check.Equals, `_method=GET&count=none&filters=%5B%5B%22uuid%22%2C+%22in%22%2C+%5B%22zhome-xvhdp-cr5queuedcontnr%22%5D%5D%5D`)
778                         w.WriteHeader(200)
779                         w.Write([]byte(`{"kind": "arvados#containerList", "items": []}`))
780                 }
781                 callCount += 1
782         })).Close()
783         req := httptest.NewRequest("GET", fmt.Sprintf("/arvados/v1/containers?count=none&filters=%s",
784                 url.QueryEscape(fmt.Sprintf(`[["uuid", "in", ["%v", "zhome-xvhdp-cr5queuedcontnr", "zhome-xvhdp-cr6queuedcontnr"]]]`,
785                         arvadostest.QueuedContainerUUID))),
786                 nil)
787         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
788         resp := s.testRequest(req)
789         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
790         c.Check(callCount, check.Equals, 2)
791         var cn arvados.ContainerList
792         c.Check(json.NewDecoder(resp.Body).Decode(&cn), check.IsNil)
793         c.Check(cn.Items, check.HasLen, 2)
794         mp := make(map[string]arvados.Container)
795         for _, cr := range cn.Items {
796                 mp[cr.UUID] = cr
797         }
798         c.Check(mp[arvadostest.QueuedContainerUUID].Command, check.DeepEquals, []string{"echo", "hello"})
799         c.Check(mp["zhome-xvhdp-cr6queuedcontnr"].Command, check.DeepEquals, []string{"efg"})
800 }
801
802 func (s *FederationSuite) TestListMultiRemoteContainerPageSizeError(c *check.C) {
803         s.testHandler.Cluster.RequestLimits.MaxItemsPerResponse = 1
804         req := httptest.NewRequest("GET", fmt.Sprintf("/arvados/v1/containers?count=none&filters=%s",
805                 url.QueryEscape(fmt.Sprintf(`[["uuid", "in", ["%v", "zhome-xvhdp-cr5queuedcontnr"]]]`,
806                         arvadostest.QueuedContainerUUID))),
807                 nil)
808         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
809         resp := s.testRequest(req)
810         c.Check(resp.StatusCode, check.Equals, http.StatusBadRequest)
811         s.checkJSONErrorMatches(c, resp, `Federated multi-object request for 2 objects which is more than max page size 1.`)
812 }
813
814 func (s *FederationSuite) TestListMultiRemoteContainerLimitError(c *check.C) {
815         req := httptest.NewRequest("GET", fmt.Sprintf("/arvados/v1/containers?count=none&filters=%s&limit=1",
816                 url.QueryEscape(fmt.Sprintf(`[["uuid", "in", ["%v", "zhome-xvhdp-cr5queuedcontnr"]]]`,
817                         arvadostest.QueuedContainerUUID))),
818                 nil)
819         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
820         resp := s.testRequest(req)
821         c.Check(resp.StatusCode, check.Equals, http.StatusBadRequest)
822         s.checkJSONErrorMatches(c, resp, `Federated multi-object may not provide 'limit', 'offset' or 'order'.`)
823 }
824
825 func (s *FederationSuite) TestListMultiRemoteContainerOffsetError(c *check.C) {
826         req := httptest.NewRequest("GET", fmt.Sprintf("/arvados/v1/containers?count=none&filters=%s&offset=1",
827                 url.QueryEscape(fmt.Sprintf(`[["uuid", "in", ["%v", "zhome-xvhdp-cr5queuedcontnr"]]]`,
828                         arvadostest.QueuedContainerUUID))),
829                 nil)
830         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
831         resp := s.testRequest(req)
832         c.Check(resp.StatusCode, check.Equals, http.StatusBadRequest)
833         s.checkJSONErrorMatches(c, resp, `Federated multi-object may not provide 'limit', 'offset' or 'order'.`)
834 }
835
836 func (s *FederationSuite) TestListMultiRemoteContainerOrderError(c *check.C) {
837         req := httptest.NewRequest("GET", fmt.Sprintf("/arvados/v1/containers?count=none&filters=%s&order=uuid",
838                 url.QueryEscape(fmt.Sprintf(`[["uuid", "in", ["%v", "zhome-xvhdp-cr5queuedcontnr"]]]`,
839                         arvadostest.QueuedContainerUUID))),
840                 nil)
841         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
842         resp := s.testRequest(req)
843         c.Check(resp.StatusCode, check.Equals, http.StatusBadRequest)
844         s.checkJSONErrorMatches(c, resp, `Federated multi-object may not provide 'limit', 'offset' or 'order'.`)
845 }
846
847 func (s *FederationSuite) TestListMultiRemoteContainerSelectError(c *check.C) {
848         req := httptest.NewRequest("GET", fmt.Sprintf("/arvados/v1/containers?count=none&filters=%s&select=%s",
849                 url.QueryEscape(fmt.Sprintf(`[["uuid", "in", ["%v", "zhome-xvhdp-cr5queuedcontnr"]]]`,
850                         arvadostest.QueuedContainerUUID)),
851                 url.QueryEscape(`["command"]`)),
852                 nil)
853         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
854         resp := s.testRequest(req)
855         c.Check(resp.StatusCode, check.Equals, http.StatusBadRequest)
856         s.checkJSONErrorMatches(c, resp, `Federated multi-object request must include 'uuid' in 'select'`)
857 }