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