13493: Comment+cleanup tests.
[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         "io/ioutil"
10         "net/http"
11         "net/http/httptest"
12         "net/url"
13         "strings"
14         "time"
15
16         "git.curoverse.com/arvados.git/sdk/go/arvados"
17         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
18         "git.curoverse.com/arvados.git/sdk/go/httpserver"
19         "github.com/Sirupsen/logrus"
20         check "gopkg.in/check.v1"
21 )
22
23 // Gocheck boilerplate
24 var _ = check.Suite(&FederationSuite{})
25
26 type FederationSuite struct {
27         log *logrus.Logger
28         // testServer and testHandler are the controller being tested,
29         // "zhome".
30         testServer  *httpserver.Server
31         testHandler *Handler
32         // remoteServer ("zzzzz") forwards requests to the Rails API
33         // provided by the integration test environment.
34         remoteServer *httpserver.Server
35         // remoteMock ("zmock") appends each incoming request to
36         // remoteMockRequests, and returns an empty 200 response.
37         remoteMock         *httpserver.Server
38         remoteMockRequests []http.Request
39 }
40
41 func (s *FederationSuite) SetUpTest(c *check.C) {
42         s.log = logrus.New()
43         s.log.Formatter = &logrus.JSONFormatter{}
44         s.log.Out = &logWriter{c.Log}
45
46         s.remoteServer = newServerFromIntegrationTestEnv(c)
47         c.Assert(s.remoteServer.Start(), check.IsNil)
48
49         s.remoteMock = newServerFromIntegrationTestEnv(c)
50         s.remoteMock.Server.Handler = http.HandlerFunc(s.remoteMockHandler)
51         c.Assert(s.remoteMock.Start(), check.IsNil)
52
53         nodeProfile := arvados.NodeProfile{
54                 Controller: arvados.SystemServiceInstance{Listen: ":"},
55                 RailsAPI:   arvados.SystemServiceInstance{Listen: ":1"}, // local reqs will error "connection refused"
56         }
57         s.testHandler = &Handler{Cluster: &arvados.Cluster{
58                 ClusterID: "zhome",
59                 NodeProfiles: map[string]arvados.NodeProfile{
60                         "*": nodeProfile,
61                 },
62         }, NodeProfile: &nodeProfile}
63         s.testServer = newServerFromIntegrationTestEnv(c)
64         s.testServer.Server.Handler = httpserver.AddRequestIDs(httpserver.LogRequests(s.log, s.testHandler))
65
66         s.testHandler.Cluster.RemoteClusters = map[string]arvados.RemoteCluster{
67                 "zzzzz": {
68                         Host:   s.remoteServer.Addr,
69                         Proxy:  true,
70                         Scheme: "http",
71                 },
72                 "zmock": {
73                         Host:   s.remoteMock.Addr,
74                         Proxy:  true,
75                         Scheme: "http",
76                 },
77         }
78
79         c.Assert(s.testServer.Start(), check.IsNil)
80 }
81
82 func (s *FederationSuite) remoteMockHandler(w http.ResponseWriter, req *http.Request) {
83         s.remoteMockRequests = append(s.remoteMockRequests, *req)
84 }
85
86 func (s *FederationSuite) TearDownTest(c *check.C) {
87         if s.remoteServer != nil {
88                 s.remoteServer.Close()
89         }
90         if s.testServer != nil {
91                 s.testServer.Close()
92         }
93 }
94
95 func (s *FederationSuite) testRequest(req *http.Request) *http.Response {
96         resp := httptest.NewRecorder()
97         s.testServer.Server.Handler.ServeHTTP(resp, req)
98         return resp.Result()
99 }
100
101 func (s *FederationSuite) TestLocalRequest(c *check.C) {
102         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+strings.Replace(arvadostest.WorkflowWithDefinitionYAMLUUID, "zzzzz-", "zhome-", 1), nil)
103         resp := s.testRequest(req)
104         s.checkHandledLocally(c, resp)
105 }
106
107 func (s *FederationSuite) checkHandledLocally(c *check.C, resp *http.Response) {
108         // Our "home" controller can't handle local requests because
109         // it doesn't have its own stub/test Rails API, so we rely on
110         // "connection refused" to indicate the controller tried to
111         // proxy the request to its local Rails API.
112         c.Check(resp.StatusCode, check.Equals, http.StatusInternalServerError)
113         s.checkJSONErrorMatches(c, resp, `.*connection refused`)
114 }
115
116 func (s *FederationSuite) TestNoAuth(c *check.C) {
117         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
118         resp := s.testRequest(req)
119         c.Check(resp.StatusCode, check.Equals, http.StatusUnauthorized)
120         s.checkJSONErrorMatches(c, resp, `Not logged in`)
121 }
122
123 func (s *FederationSuite) TestBadAuth(c *check.C) {
124         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
125         req.Header.Set("Authorization", "Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
126         resp := s.testRequest(req)
127         c.Check(resp.StatusCode, check.Equals, http.StatusUnauthorized)
128         s.checkJSONErrorMatches(c, resp, `Not logged in`)
129 }
130
131 func (s *FederationSuite) TestNoAccess(c *check.C) {
132         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
133         req.Header.Set("Authorization", "Bearer "+arvadostest.SpectatorToken)
134         resp := s.testRequest(req)
135         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
136         s.checkJSONErrorMatches(c, resp, `.*not found`)
137 }
138
139 func (s *FederationSuite) TestGetUnknownRemote(c *check.C) {
140         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+strings.Replace(arvadostest.WorkflowWithDefinitionYAMLUUID, "zzzzz-", "zz404-", 1), nil)
141         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
142         resp := s.testRequest(req)
143         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
144         s.checkJSONErrorMatches(c, resp, `.*no proxy available for cluster zz404`)
145 }
146
147 func (s *FederationSuite) TestRemoteError(c *check.C) {
148         rc := s.testHandler.Cluster.RemoteClusters["zzzzz"]
149         rc.Scheme = "https"
150         s.testHandler.Cluster.RemoteClusters["zzzzz"] = rc
151
152         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
153         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
154         resp := s.testRequest(req)
155         c.Check(resp.StatusCode, check.Equals, http.StatusInternalServerError)
156         s.checkJSONErrorMatches(c, resp, `.*HTTP response to HTTPS client`)
157 }
158
159 func (s *FederationSuite) TestGetRemoteWorkflow(c *check.C) {
160         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, nil)
161         req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
162         resp := s.testRequest(req)
163         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
164         var wf arvados.Workflow
165         c.Check(json.NewDecoder(resp.Body).Decode(&wf), check.IsNil)
166         c.Check(wf.UUID, check.Equals, arvadostest.WorkflowWithDefinitionYAMLUUID)
167         c.Check(wf.OwnerUUID, check.Equals, arvadostest.ActiveUserUUID)
168 }
169
170 func (s *FederationSuite) TestRemoteWithTokenInQuery(c *check.C) {
171         req := httptest.NewRequest("GET", "/arvados/v1/workflows/"+strings.Replace(arvadostest.WorkflowWithDefinitionYAMLUUID, "zzzzz-", "zmock-", 1)+"?api_token="+arvadostest.ActiveToken, nil)
172         s.testRequest(req)
173         c.Assert(len(s.remoteMockRequests), check.Equals, 1)
174         c.Check(s.remoteMockRequests[0].URL.String(), check.Not(check.Matches), `.*api_token=.*`)
175 }
176
177 func (s *FederationSuite) TestUpdateRemoteWorkflow(c *check.C) {
178         updateDescription := func(descr string) *http.Response {
179                 req := httptest.NewRequest("PATCH", "/arvados/v1/workflows/"+arvadostest.WorkflowWithDefinitionYAMLUUID, strings.NewReader(url.Values{
180                         "workflow": {`{"description":"` + descr + `"}`},
181                 }.Encode()))
182                 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
183                 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
184                 resp := s.testRequest(req)
185                 s.checkResponseOK(c, resp)
186                 return resp
187         }
188
189         // Update description twice so running this test twice in a
190         // row still causes ModifiedAt to change
191         updateDescription("updated once by TestUpdateRemoteWorkflow")
192         resp := updateDescription("updated twice by TestUpdateRemoteWorkflow")
193
194         var wf arvados.Workflow
195         c.Check(json.NewDecoder(resp.Body).Decode(&wf), check.IsNil)
196         c.Check(wf.UUID, check.Equals, arvadostest.WorkflowWithDefinitionYAMLUUID)
197         c.Assert(wf.ModifiedAt, check.NotNil)
198         c.Logf("%s", *wf.ModifiedAt)
199         c.Check(time.Since(*wf.ModifiedAt) < time.Minute, check.Equals, true)
200 }
201
202 func (s *FederationSuite) checkResponseOK(c *check.C, resp *http.Response) {
203         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
204         if resp.StatusCode != http.StatusOK {
205                 body, err := ioutil.ReadAll(resp.Body)
206                 c.Logf("... response body = %q, %v\n", body, err)
207         }
208 }
209
210 func (s *FederationSuite) checkJSONErrorMatches(c *check.C, resp *http.Response, re string) {
211         var jresp httpserver.ErrorResponse
212         err := json.NewDecoder(resp.Body).Decode(&jresp)
213         c.Check(err, check.IsNil)
214         c.Assert(len(jresp.Errors), check.Equals, 1)
215         c.Check(jresp.Errors[0], check.Matches, re)
216 }