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