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