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