13619: Test that "select" is passed through multi-object query
[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         "encoding/json"
9         "fmt"
10         "io/ioutil"
11         "net/http"
12         "net/http/httptest"
13         "net/url"
14         "os"
15         "strings"
16         "time"
17
18         "git.curoverse.com/arvados.git/sdk/go/arvados"
19         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
20         "git.curoverse.com/arvados.git/sdk/go/httpserver"
21         "git.curoverse.com/arvados.git/sdk/go/keepclient"
22         "github.com/Sirupsen/logrus"
23         check "gopkg.in/check.v1"
24 )
25
26 // Gocheck boilerplate
27 var _ = check.Suite(&FederationSuite{})
28
29 type FederationSuite struct {
30         log *logrus.Logger
31         // testServer and testHandler are the controller being tested,
32         // "zhome".
33         testServer  *httpserver.Server
34         testHandler *Handler
35         // remoteServer ("zzzzz") forwards requests to the Rails API
36         // provided by the integration test environment.
37         remoteServer *httpserver.Server
38         // remoteMock ("zmock") appends each incoming request to
39         // remoteMockRequests, and returns an empty 200 response.
40         remoteMock         *httpserver.Server
41         remoteMockRequests []http.Request
42 }
43
44 func (s *FederationSuite) SetUpTest(c *check.C) {
45         s.log = logrus.New()
46         s.log.Formatter = &logrus.JSONFormatter{}
47         s.log.Out = &logWriter{c.Log}
48
49         s.remoteServer = newServerFromIntegrationTestEnv(c)
50         c.Assert(s.remoteServer.Start(), check.IsNil)
51
52         s.remoteMock = newServerFromIntegrationTestEnv(c)
53         s.remoteMock.Server.Handler = http.HandlerFunc(s.remoteMockHandler)
54         c.Assert(s.remoteMock.Start(), check.IsNil)
55
56         nodeProfile := arvados.NodeProfile{
57                 Controller: arvados.SystemServiceInstance{Listen: ":"},
58                 RailsAPI:   arvados.SystemServiceInstance{Listen: ":1"}, // local reqs will error "connection refused"
59         }
60         s.testHandler = &Handler{Cluster: &arvados.Cluster{
61                 ClusterID:  "zhome",
62                 PostgreSQL: integrationTestCluster().PostgreSQL,
63                 NodeProfiles: map[string]arvados.NodeProfile{
64                         "*": nodeProfile,
65                 },
66         }, NodeProfile: &nodeProfile}
67         s.testServer = newServerFromIntegrationTestEnv(c)
68         s.testServer.Server.Handler = httpserver.AddRequestIDs(httpserver.LogRequests(s.log, s.testHandler))
69
70         s.testHandler.Cluster.RemoteClusters = map[string]arvados.RemoteCluster{
71                 "zzzzz": {
72                         Host:   s.remoteServer.Addr,
73                         Proxy:  true,
74                         Scheme: "http",
75                 },
76                 "zmock": {
77                         Host:   s.remoteMock.Addr,
78                         Proxy:  true,
79                         Scheme: "http",
80                 },
81         }
82
83         c.Assert(s.testServer.Start(), check.IsNil)
84
85         s.remoteMockRequests = nil
86 }
87
88 func (s *FederationSuite) remoteMockHandler(w http.ResponseWriter, req *http.Request) {
89         s.remoteMockRequests = append(s.remoteMockRequests, *req)
90 }
91
92 func (s *FederationSuite) TearDownTest(c *check.C) {
93         if s.remoteServer != nil {
94                 s.remoteServer.Close()
95         }
96         if s.testServer != nil {
97                 s.testServer.Close()
98         }
99 }
100
101 func (s *FederationSuite) testRequest(req *http.Request) *http.Response {
102         resp := httptest.NewRecorder()
103         s.testServer.Server.Handler.ServeHTTP(resp, req)
104         return resp.Result()
105 }
106
107 func (s *FederationSuite) TestLocalRequest(c *check.C) {
108         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+strings.Replace(arvadostest.WorkflowWithDefinitionYAMLUUID, "zzzzz-", "zhome-", 1), nil)
109         resp := s.testRequest(req)
110         s.checkHandledLocally(c, resp)
111 }
112
113 func (s *FederationSuite) checkHandledLocally(c *check.C, resp *http.Response) {
114         // Our "home" controller can't handle local requests because
115         // it doesn't have its own stub/test Rails API, so we rely on
116         // "connection refused" to indicate the controller tried to
117         // proxy the request to its local Rails API.
118         c.Check(resp.StatusCode, check.Equals, http.StatusBadGateway)
119         s.checkJSONErrorMatches(c, resp, `.*connection refused`)
120 }
121
122 func (s *FederationSuite) TestNoAuth(c *check.C) {
123         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
124         resp := s.testRequest(req)
125         c.Check(resp.StatusCode, check.Equals, http.StatusUnauthorized)
126         s.checkJSONErrorMatches(c, resp, `Not logged in`)
127 }
128
129 func (s *FederationSuite) TestBadAuth(c *check.C) {
130         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
131         req.Header.Set("Authorization", "Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
132         resp := s.testRequest(req)
133         c.Check(resp.StatusCode, check.Equals, http.StatusUnauthorized)
134         s.checkJSONErrorMatches(c, resp, `Not logged in`)
135 }
136
137 func (s *FederationSuite) TestNoAccess(c *check.C) {
138         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
139         req.Header.Set("Authorization", "Bearer "+arvadostest.SpectatorToken)
140         resp := s.testRequest(req)
141         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
142         s.checkJSONErrorMatches(c, resp, `.*not found`)
143 }
144
145 func (s *FederationSuite) TestGetUnknownRemote(c *check.C) {
146         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+strings.Replace(arvadostest.WorkflowWithDefinitionYAMLUUID, "zzzzz-", "zz404-", 1), nil)
147         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
148         resp := s.testRequest(req)
149         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
150         s.checkJSONErrorMatches(c, resp, `.*no proxy available for cluster zz404`)
151 }
152
153 func (s *FederationSuite) TestRemoteError(c *check.C) {
154         rc := s.testHandler.Cluster.RemoteClusters["zzzzz"]
155         rc.Scheme = "https"
156         s.testHandler.Cluster.RemoteClusters["zzzzz"] = rc
157
158         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
159         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
160         resp := s.testRequest(req)
161         c.Check(resp.StatusCode, check.Equals, http.StatusBadGateway)
162         s.checkJSONErrorMatches(c, resp, `.*HTTP response to HTTPS client`)
163 }
164
165 func (s *FederationSuite) TestGetRemoteWorkflow(c *check.C) {
166         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
167         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
168         resp := s.testRequest(req)
169         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
170         var wf arvados.Workflow
171         c.Check(json.NewDecoder(resp.Body).Decode(&wf), check.IsNil)
172         c.Check(wf.UUID, check.Equals, arvadostest.WorkflowWithDefinitionYAMLUUID)
173         c.Check(wf.OwnerUUID, check.Equals, arvadostest.ActiveUserUUID)
174 }
175
176 func (s *FederationSuite) TestOptionsMethod(c *check.C) {
177         req := httptest.NewRequest("OPTIONS", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
178         req.Header.Set("Origin", "https://example.com")
179         resp := s.testRequest(req)
180         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
181         body, err := ioutil.ReadAll(resp.Body)
182         c.Check(err, check.IsNil)
183         c.Check(string(body), check.Equals, "")
184         c.Check(resp.Header.Get("Access-Control-Allow-Origin"), check.Equals, "*")
185         for _, hdr := range []string{"Authorization", "Content-Type"} {
186                 c.Check(resp.Header.Get("Access-Control-Allow-Headers"), check.Matches, ".*"+hdr+".*")
187         }
188         for _, method := range []string{"GET", "HEAD", "PUT", "POST", "DELETE"} {
189                 c.Check(resp.Header.Get("Access-Control-Allow-Methods"), check.Matches, ".*"+method+".*")
190         }
191 }
192
193 func (s *FederationSuite) TestRemoteWithTokenInQuery(c *check.C) {
194         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+strings.Replace(arvadostest.WorkflowWithDefinitionYAMLUUID, "zzzzz-", "zmock-", 1)+"?api_token="+arvadostest.ActiveToken, nil)
195         s.testRequest(req)
196         c.Assert(len(s.remoteMockRequests), check.Equals, 1)
197         pr := s.remoteMockRequests[0]
198         // Token is salted and moved from query to Authorization header.
199         c.Check(pr.URL.String(), check.Not(check.Matches), `.*api_token=.*`)
200         c.Check(pr.Header.Get("Authorization"), check.Equals, "Bearer v2/zzzzz-gj3su-077z32aux8dg2s1/7fd31b61f39c0e82a4155592163218272cedacdc")
201 }
202
203 func (s *FederationSuite) TestLocalTokenSalted(c *check.C) {
204         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+strings.Replace(arvadostest.WorkflowWithDefinitionYAMLUUID, "zzzzz-", "zmock-", 1), nil)
205         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
206         s.testRequest(req)
207         c.Assert(len(s.remoteMockRequests), check.Equals, 1)
208         pr := s.remoteMockRequests[0]
209         // The salted token here has a "zzzzz-" UUID instead of a
210         // "ztest-" UUID because ztest's local database has the
211         // "zzzzz-" test fixtures. The "secret" part is HMAC(sha1,
212         // arvadostest.ActiveToken, "zmock") = "7fd3...".
213         c.Check(pr.Header.Get("Authorization"), check.Equals, "Bearer v2/zzzzz-gj3su-077z32aux8dg2s1/7fd31b61f39c0e82a4155592163218272cedacdc")
214 }
215
216 func (s *FederationSuite) TestRemoteTokenNotSalted(c *check.C) {
217         // remoteToken can be any v1 token that doesn't appear in
218         // ztest's local db.
219         remoteToken := "abcdef00000000000000000000000000000000000000000000"
220         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+strings.Replace(arvadostest.WorkflowWithDefinitionYAMLUUID, "zzzzz-", "zmock-", 1), nil)
221         req.Header.Set("Authorization", "Bearer "+remoteToken)
222         s.testRequest(req)
223         c.Assert(len(s.remoteMockRequests), check.Equals, 1)
224         pr := s.remoteMockRequests[0]
225         c.Check(pr.Header.Get("Authorization"), check.Equals, "Bearer "+remoteToken)
226 }
227
228 func (s *FederationSuite) TestWorkflowCRUD(c *check.C) {
229         wf := arvados.Workflow{
230                 Description: "TestCRUD",
231         }
232         {
233                 body := &strings.Builder{}
234                 json.NewEncoder(body).Encode(&wf)
235                 req := httptest.NewRequest("POST", "/arvados/v1/workflows", strings.NewReader(url.Values{
236                         "workflow": {body.String()},
237                 }.Encode()))
238                 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
239                 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
240                 rec := httptest.NewRecorder()
241                 s.remoteServer.Server.Handler.ServeHTTP(rec, req) // direct to remote -- can't proxy a create req because no uuid
242                 resp := rec.Result()
243                 s.checkResponseOK(c, resp)
244                 json.NewDecoder(resp.Body).Decode(&wf)
245
246                 defer func() {
247                         req := httptest.NewRequest("DELETE", "/arvados/v1/workflows/"+wf.UUID, nil)
248                         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
249                         s.remoteServer.Server.Handler.ServeHTTP(httptest.NewRecorder(), req)
250                 }()
251                 c.Check(wf.UUID, check.Not(check.Equals), "")
252
253                 c.Assert(wf.ModifiedAt, check.NotNil)
254                 c.Logf("wf.ModifiedAt: %v", wf.ModifiedAt)
255                 c.Check(time.Since(*wf.ModifiedAt) < time.Minute, check.Equals, true)
256         }
257         for _, method := range []string{"PATCH", "PUT", "POST"} {
258                 form := url.Values{
259                         "workflow": {`{"description": "Updated with ` + method + `"}`},
260                 }
261                 if method == "POST" {
262                         form["_method"] = []string{"PATCH"}
263                 }
264                 req := httptest.NewRequest(method, "/arvados/v1/workflows/"+wf.UUID, strings.NewReader(form.Encode()))
265                 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
266                 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
267                 resp := s.testRequest(req)
268                 s.checkResponseOK(c, resp)
269                 err := json.NewDecoder(resp.Body).Decode(&wf)
270                 c.Check(err, check.IsNil)
271
272                 c.Check(wf.Description, check.Equals, "Updated with "+method)
273         }
274         {
275                 req := httptest.NewRequest("DELETE", "/arvados/v1/workflows/"+wf.UUID, nil)
276                 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
277                 resp := s.testRequest(req)
278                 s.checkResponseOK(c, resp)
279                 err := json.NewDecoder(resp.Body).Decode(&wf)
280                 c.Check(err, check.IsNil)
281         }
282         {
283                 req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+wf.UUID, nil)
284                 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
285                 resp := s.testRequest(req)
286                 c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
287         }
288 }
289
290 func (s *FederationSuite) checkResponseOK(c *check.C, resp *http.Response) {
291         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
292         if resp.StatusCode != http.StatusOK {
293                 body, err := ioutil.ReadAll(resp.Body)
294                 c.Logf("... response body = %q, %v\n", body, err)
295         }
296 }
297
298 func (s *FederationSuite) checkJSONErrorMatches(c *check.C, resp *http.Response, re string) {
299         var jresp httpserver.ErrorResponse
300         err := json.NewDecoder(resp.Body).Decode(&jresp)
301         c.Check(err, check.IsNil)
302         c.Assert(len(jresp.Errors), check.Equals, 1)
303         c.Check(jresp.Errors[0], check.Matches, re)
304 }
305
306 func (s *FederationSuite) localServiceHandler(c *check.C, h http.Handler) *httpserver.Server {
307         srv := &httpserver.Server{
308                 Server: http.Server{
309                         Handler: h,
310                 },
311         }
312
313         c.Assert(srv.Start(), check.IsNil)
314
315         np := arvados.NodeProfile{
316                 Controller: arvados.SystemServiceInstance{Listen: ":"},
317                 RailsAPI: arvados.SystemServiceInstance{Listen: srv.Addr,
318                         TLS: false, Insecure: true}}
319         s.testHandler.Cluster.NodeProfiles["*"] = np
320         s.testHandler.NodeProfile = &np
321
322         return srv
323 }
324
325 func (s *FederationSuite) localServiceReturns404(c *check.C) *httpserver.Server {
326         return s.localServiceHandler(c, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
327                 w.WriteHeader(404)
328         }))
329 }
330
331 func (s *FederationSuite) TestGetLocalCollection(c *check.C) {
332         np := arvados.NodeProfile{
333                 Controller: arvados.SystemServiceInstance{Listen: ":"},
334                 RailsAPI: arvados.SystemServiceInstance{Listen: os.Getenv("ARVADOS_TEST_API_HOST"),
335                         TLS: true, Insecure: true}}
336         s.testHandler.Cluster.ClusterID = "zzzzz"
337         s.testHandler.Cluster.NodeProfiles["*"] = np
338         s.testHandler.NodeProfile = &np
339
340         req := httptest.NewRequest("GET", "/arvados/v1/collections/"+arvadostest.UserAgreementCollection, nil)
341         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
342         resp := s.testRequest(req)
343
344         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
345         var col arvados.Collection
346         c.Check(json.NewDecoder(resp.Body).Decode(&col), check.IsNil)
347         c.Check(col.UUID, check.Equals, arvadostest.UserAgreementCollection)
348         c.Check(col.ManifestText, check.Matches,
349                 `\. 6a4ff0499484c6c79c95cd8c566bd25f\+249025\+A[0-9a-f]{40}@[0-9a-f]{8} 0:249025:GNU_General_Public_License,_version_3.pdf
350 `)
351 }
352
353 func (s *FederationSuite) TestGetRemoteCollection(c *check.C) {
354         defer s.localServiceReturns404(c).Close()
355
356         req := httptest.NewRequest("GET", "/arvados/v1/collections/"+arvadostest.UserAgreementCollection, nil)
357         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
358         resp := s.testRequest(req)
359         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
360         var col arvados.Collection
361         c.Check(json.NewDecoder(resp.Body).Decode(&col), check.IsNil)
362         c.Check(col.UUID, check.Equals, arvadostest.UserAgreementCollection)
363         c.Check(col.ManifestText, check.Matches,
364                 `\. 6a4ff0499484c6c79c95cd8c566bd25f\+249025\+Rzzzzz-[0-9a-f]{40}@[0-9a-f]{8} 0:249025:GNU_General_Public_License,_version_3.pdf
365 `)
366 }
367
368 func (s *FederationSuite) TestGetRemoteCollectionError(c *check.C) {
369         defer s.localServiceReturns404(c).Close()
370
371         req := httptest.NewRequest("GET", "/arvados/v1/collections/zzzzz-4zz18-fakefakefakefak", nil)
372         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
373         resp := s.testRequest(req)
374         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
375 }
376
377 func (s *FederationSuite) TestSignedLocatorPattern(c *check.C) {
378         // Confirm the regular expression identifies other groups of hints correctly
379         c.Check(keepclient.SignedLocatorRe.FindStringSubmatch(`6a4ff0499484c6c79c95cd8c566bd25f+249025+B1+C2+A05227438989d04712ea9ca1c91b556cef01d5cc7@5ba5405b+D3+E4`),
380                 check.DeepEquals,
381                 []string{"6a4ff0499484c6c79c95cd8c566bd25f+249025+B1+C2+A05227438989d04712ea9ca1c91b556cef01d5cc7@5ba5405b+D3+E4",
382                         "6a4ff0499484c6c79c95cd8c566bd25f",
383                         "+249025",
384                         "+B1+C2", "+C2",
385                         "+A05227438989d04712ea9ca1c91b556cef01d5cc7@5ba5405b",
386                         "05227438989d04712ea9ca1c91b556cef01d5cc7", "5ba5405b",
387                         "+D3+E4", "+E4"})
388 }
389
390 func (s *FederationSuite) TestGetLocalCollectionByPDH(c *check.C) {
391         np := arvados.NodeProfile{
392                 Controller: arvados.SystemServiceInstance{Listen: ":"},
393                 RailsAPI: arvados.SystemServiceInstance{Listen: os.Getenv("ARVADOS_TEST_API_HOST"),
394                         TLS: true, Insecure: true}}
395         s.testHandler.Cluster.NodeProfiles["*"] = np
396         s.testHandler.NodeProfile = &np
397
398         req := httptest.NewRequest("GET", "/arvados/v1/collections/"+arvadostest.UserAgreementPDH, nil)
399         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
400         resp := s.testRequest(req)
401
402         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
403         var col arvados.Collection
404         c.Check(json.NewDecoder(resp.Body).Decode(&col), check.IsNil)
405         c.Check(col.PortableDataHash, check.Equals, arvadostest.UserAgreementPDH)
406         c.Check(col.ManifestText, check.Matches,
407                 `\. 6a4ff0499484c6c79c95cd8c566bd25f\+249025\+A[0-9a-f]{40}@[0-9a-f]{8} 0:249025:GNU_General_Public_License,_version_3.pdf
408 `)
409 }
410
411 func (s *FederationSuite) TestGetRemoteCollectionByPDH(c *check.C) {
412         defer s.localServiceReturns404(c).Close()
413
414         req := httptest.NewRequest("GET", "/arvados/v1/collections/"+arvadostest.UserAgreementPDH, nil)
415         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
416         resp := s.testRequest(req)
417
418         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
419
420         var col arvados.Collection
421         c.Check(json.NewDecoder(resp.Body).Decode(&col), check.IsNil)
422         c.Check(col.PortableDataHash, check.Equals, arvadostest.UserAgreementPDH)
423         c.Check(col.ManifestText, check.Matches,
424                 `\. 6a4ff0499484c6c79c95cd8c566bd25f\+249025\+Rzzzzz-[0-9a-f]{40}@[0-9a-f]{8} 0:249025:GNU_General_Public_License,_version_3.pdf
425 `)
426 }
427
428 func (s *FederationSuite) TestGetCollectionByPDHError(c *check.C) {
429         defer s.localServiceReturns404(c).Close()
430
431         req := httptest.NewRequest("GET", "/arvados/v1/collections/99999999999999999999999999999999+99", nil)
432         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
433
434         resp := s.testRequest(req)
435         defer resp.Body.Close()
436
437         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
438 }
439
440 func (s *FederationSuite) TestGetCollectionByPDHErrorBadHash(c *check.C) {
441         defer s.localServiceReturns404(c).Close()
442
443         srv2 := &httpserver.Server{
444                 Server: http.Server{
445                         Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
446                                 w.WriteHeader(200)
447                                 // Return a collection where the hash
448                                 // of the manifest text doesn't match
449                                 // PDH that was requested.
450                                 var col arvados.Collection
451                                 col.PortableDataHash = "99999999999999999999999999999999+99"
452                                 col.ManifestText = `. 6a4ff0499484c6c79c95cd8c566bd25f\+249025 0:249025:GNU_General_Public_License,_version_3.pdf
453 `
454                                 enc := json.NewEncoder(w)
455                                 enc.Encode(col)
456                         }),
457                 },
458         }
459
460         c.Assert(srv2.Start(), check.IsNil)
461         defer srv2.Close()
462
463         // Direct zzzzz to service that returns a 200 result with a bogus manifest_text
464         s.testHandler.Cluster.RemoteClusters["zzzzz"] = arvados.RemoteCluster{
465                 Host:   srv2.Addr,
466                 Proxy:  true,
467                 Scheme: "http",
468         }
469
470         req := httptest.NewRequest("GET", "/arvados/v1/collections/99999999999999999999999999999999+99", nil)
471         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
472
473         resp := s.testRequest(req)
474         defer resp.Body.Close()
475
476         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
477 }
478
479 func (s *FederationSuite) TestSaltedTokenGetCollectionByPDH(c *check.C) {
480         np := arvados.NodeProfile{
481                 Controller: arvados.SystemServiceInstance{Listen: ":"},
482                 RailsAPI: arvados.SystemServiceInstance{Listen: os.Getenv("ARVADOS_TEST_API_HOST"),
483                         TLS: true, Insecure: true}}
484         s.testHandler.Cluster.NodeProfiles["*"] = np
485         s.testHandler.NodeProfile = &np
486
487         req := httptest.NewRequest("GET", "/arvados/v1/collections/"+arvadostest.UserAgreementPDH, nil)
488         req.Header.Set("Authorization", "Bearer v2/zzzzz-gj3su-077z32aux8dg2s1/282d7d172b6cfdce364c5ed12ddf7417b2d00065")
489         resp := s.testRequest(req)
490
491         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
492         var col arvados.Collection
493         c.Check(json.NewDecoder(resp.Body).Decode(&col), check.IsNil)
494         c.Check(col.PortableDataHash, check.Equals, arvadostest.UserAgreementPDH)
495         c.Check(col.ManifestText, check.Matches,
496                 `\. 6a4ff0499484c6c79c95cd8c566bd25f\+249025\+A[0-9a-f]{40}@[0-9a-f]{8} 0:249025:GNU_General_Public_License,_version_3.pdf
497 `)
498 }
499
500 func (s *FederationSuite) TestSaltedTokenGetCollectionByPDHError(c *check.C) {
501         np := arvados.NodeProfile{
502                 Controller: arvados.SystemServiceInstance{Listen: ":"},
503                 RailsAPI: arvados.SystemServiceInstance{Listen: os.Getenv("ARVADOS_TEST_API_HOST"),
504                         TLS: true, Insecure: true}}
505         s.testHandler.Cluster.NodeProfiles["*"] = np
506         s.testHandler.NodeProfile = &np
507
508         req := httptest.NewRequest("GET", "/arvados/v1/collections/99999999999999999999999999999999+99", nil)
509         req.Header.Set("Authorization", "Bearer v2/zzzzz-gj3su-077z32aux8dg2s1/282d7d172b6cfdce364c5ed12ddf7417b2d00065")
510         resp := s.testRequest(req)
511
512         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
513 }
514
515 func (s *FederationSuite) TestGetRemoteContainerRequest(c *check.C) {
516         defer s.localServiceReturns404(c).Close()
517         req := httptest.NewRequest("GET", "/arvados/v1/container_requests/"+arvadostest.QueuedContainerRequestUUID, nil)
518         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
519         resp := s.testRequest(req)
520         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
521         var cr arvados.ContainerRequest
522         c.Check(json.NewDecoder(resp.Body).Decode(&cr), check.IsNil)
523         c.Check(cr.UUID, check.Equals, arvadostest.QueuedContainerRequestUUID)
524         c.Check(cr.Priority, check.Equals, 1)
525 }
526
527 func (s *FederationSuite) TestUpdateRemoteContainerRequest(c *check.C) {
528         defer s.localServiceReturns404(c).Close()
529         req := httptest.NewRequest("PATCH", "/arvados/v1/container_requests/"+arvadostest.QueuedContainerRequestUUID,
530                 strings.NewReader(`{"container_request": {"priority": 696}}`))
531         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
532         req.Header.Set("Content-type", "application/json")
533         resp := s.testRequest(req)
534         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
535         var cr arvados.ContainerRequest
536         c.Check(json.NewDecoder(resp.Body).Decode(&cr), check.IsNil)
537         c.Check(cr.UUID, check.Equals, arvadostest.QueuedContainerRequestUUID)
538         c.Check(cr.Priority, check.Equals, 696)
539 }
540
541 func (s *FederationSuite) TestCreateRemoteContainerRequest(c *check.C) {
542         defer s.localServiceReturns404(c).Close()
543         // pass cluster_id via query parameter, this allows arvados-controller
544         // to avoid parsing the body
545         req := httptest.NewRequest("POST", "/arvados/v1/container_requests?cluster_id=zzzzz",
546                 strings.NewReader(`{
547   "container_request": {
548     "name": "hello world",
549     "state": "Uncommitted",
550     "output_path": "/",
551     "container_image": "123",
552     "command": ["abc"]
553   }
554 }
555 `))
556         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
557         req.Header.Set("Content-type", "application/json")
558         resp := s.testRequest(req)
559         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
560         var cr arvados.ContainerRequest
561         c.Check(json.NewDecoder(resp.Body).Decode(&cr), check.IsNil)
562         c.Check(cr.Name, check.Equals, "hello world")
563         c.Check(strings.HasPrefix(cr.UUID, "zzzzz-"), check.Equals, true)
564 }
565
566 func (s *FederationSuite) TestCreateRemoteContainerRequestError(c *check.C) {
567         defer s.localServiceReturns404(c).Close()
568         // pass cluster_id via query parameter, this allows arvados-controller
569         // to avoid parsing the body
570         req := httptest.NewRequest("POST", "/arvados/v1/container_requests?cluster_id=zz404",
571                 strings.NewReader(`{
572   "container_request": {
573     "name": "hello world",
574     "state": "Uncommitted",
575     "output_path": "/",
576     "container_image": "123",
577     "command": ["abc"]
578   }
579 }
580 `))
581         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
582         req.Header.Set("Content-type", "application/json")
583         resp := s.testRequest(req)
584         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
585 }
586
587 func (s *FederationSuite) TestGetRemoteContainer(c *check.C) {
588         defer s.localServiceReturns404(c).Close()
589         req := httptest.NewRequest("GET", "/arvados/v1/containers/"+arvadostest.QueuedContainerUUID, nil)
590         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
591         resp := s.testRequest(req)
592         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
593         var cn arvados.Container
594         c.Check(json.NewDecoder(resp.Body).Decode(&cn), check.IsNil)
595         c.Check(cn.UUID, check.Equals, arvadostest.QueuedContainerUUID)
596 }
597
598 func (s *FederationSuite) TestListRemoteContainer(c *check.C) {
599         defer s.localServiceReturns404(c).Close()
600         req := httptest.NewRequest("GET", "/arvados/v1/containers?count=none&filters="+
601                 url.QueryEscape(fmt.Sprintf(`[["uuid", "in", ["%v"]]]`, arvadostest.QueuedContainerUUID)), nil)
602         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
603         resp := s.testRequest(req)
604         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
605         var cn arvados.ContainerList
606         c.Check(json.NewDecoder(resp.Body).Decode(&cn), check.IsNil)
607         c.Check(cn.Items[0].UUID, check.Equals, arvadostest.QueuedContainerUUID)
608 }
609
610 func (s *FederationSuite) TestListMultiRemoteContainers(c *check.C) {
611         defer s.localServiceHandler(c, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
612                 bd, _ := ioutil.ReadAll(req.Body)
613                 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`)
614                 w.WriteHeader(200)
615                 w.Write([]byte(`{"kind": "arvados#containerList", "items": [{"uuid": "zhome-xvhdp-cr5queuedcontnr", "command": ["abc"]}]}`))
616         })).Close()
617         req := httptest.NewRequest("GET", fmt.Sprintf("/arvados/v1/containers?count=none&filters=%s&select=%s",
618                 url.QueryEscape(fmt.Sprintf(`[["uuid", "in", ["%v", "zhome-xvhdp-cr5queuedcontnr"]]]`,
619                         arvadostest.QueuedContainerUUID)),
620                 url.QueryEscape(`["uuid", "command"]`)),
621                 nil)
622         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
623         resp := s.testRequest(req)
624         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
625         var cn arvados.ContainerList
626         c.Check(json.NewDecoder(resp.Body).Decode(&cn), check.IsNil)
627         if cn.Items[0].UUID == arvadostest.QueuedContainerUUID {
628                 c.Check(cn.Items[0].Command, check.DeepEquals, []string{"echo", "hello"})
629                 c.Check(cn.Items[0].ContainerImage, check.Equals, "")
630
631                 c.Check(cn.Items[1].UUID, check.Equals, "zhome-xvhdp-cr5queuedcontnr")
632                 c.Check(cn.Items[1].Command, check.DeepEquals, []string{"abc"})
633                 c.Check(cn.Items[1].ContainerImage, check.Equals, "")
634         } else {
635                 c.Check(cn.Items[0].UUID, check.Equals, "zhome-xvhdp-cr5queuedcontnr")
636                 c.Check(cn.Items[0].Command, check.DeepEquals, []string{"abc"})
637                 c.Check(cn.Items[0].ContainerImage, check.Equals, "")
638
639                 c.Check(cn.Items[1].UUID, check.Equals, arvadostest.QueuedContainerUUID)
640                 c.Check(cn.Items[1].Command, check.DeepEquals, []string{"echo", "hello"})
641                 c.Check(cn.Items[1].ContainerImage, check.Equals, "")
642         }
643 }