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