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