1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.arvados.org/arvados.git/sdk/go/arvados"
21 "git.arvados.org/arvados.git/sdk/go/arvadostest"
22 "git.arvados.org/arvados.git/sdk/go/auth"
23 "git.arvados.org/arvados.git/sdk/go/ctxlog"
24 "git.arvados.org/arvados.git/sdk/go/httpserver"
25 "github.com/prometheus/client_golang/prometheus"
26 check "gopkg.in/check.v1"
29 var forceLegacyAPI14 bool
31 // Gocheck boilerplate
32 func Test(t *testing.T) {
33 for _, forceLegacyAPI14 = range []bool{false, true} {
38 var _ = check.Suite(&HandlerSuite{})
40 type HandlerSuite struct {
41 cluster *arvados.Cluster
44 cancel context.CancelFunc
47 func (s *HandlerSuite) SetUpTest(c *check.C) {
48 s.ctx, s.cancel = context.WithCancel(context.Background())
49 s.ctx = ctxlog.Context(s.ctx, ctxlog.New(os.Stderr, "json", "debug"))
50 s.cluster = &arvados.Cluster{
52 PostgreSQL: integrationTestCluster().PostgreSQL,
53 ForceLegacyAPI14: forceLegacyAPI14,
55 s.cluster.TLS.Insecure = true
56 arvadostest.SetServiceURL(&s.cluster.Services.RailsAPI, "https://"+os.Getenv("ARVADOS_TEST_API_HOST"))
57 arvadostest.SetServiceURL(&s.cluster.Services.Controller, "http://localhost:/")
58 s.handler = newHandler(s.ctx, s.cluster, "", prometheus.NewRegistry())
61 func (s *HandlerSuite) TearDownTest(c *check.C) {
65 func (s *HandlerSuite) TestConfigExport(c *check.C) {
66 s.cluster.ManagementToken = "secret"
67 s.cluster.SystemRootToken = "secret"
68 s.cluster.Collections.BlobSigning = true
69 s.cluster.Collections.BlobSigningTTL = arvados.Duration(23 * time.Second)
70 for _, method := range []string{"GET", "OPTIONS"} {
71 req := httptest.NewRequest(method, "/arvados/v1/config", nil)
72 resp := httptest.NewRecorder()
73 s.handler.ServeHTTP(resp, req)
74 c.Check(resp.Code, check.Equals, http.StatusOK)
75 c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, `*`)
76 c.Check(resp.Header().Get("Access-Control-Allow-Methods"), check.Matches, `.*\bGET\b.*`)
77 c.Check(resp.Header().Get("Access-Control-Allow-Headers"), check.Matches, `.+`)
78 if method == "OPTIONS" {
79 c.Check(resp.Body.String(), check.HasLen, 0)
82 var cluster arvados.Cluster
83 c.Log(resp.Body.String())
84 err := json.Unmarshal(resp.Body.Bytes(), &cluster)
85 c.Check(err, check.IsNil)
86 c.Check(cluster.ManagementToken, check.Equals, "")
87 c.Check(cluster.SystemRootToken, check.Equals, "")
88 c.Check(cluster.Collections.BlobSigning, check.DeepEquals, true)
89 c.Check(cluster.Collections.BlobSigningTTL, check.Equals, arvados.Duration(23*time.Second))
93 func (s *HandlerSuite) TestProxyDiscoveryDoc(c *check.C) {
94 req := httptest.NewRequest("GET", "/discovery/v1/apis/arvados/v1/rest", nil)
95 resp := httptest.NewRecorder()
96 s.handler.ServeHTTP(resp, req)
97 c.Check(resp.Code, check.Equals, http.StatusOK)
98 var dd arvados.DiscoveryDocument
99 err := json.Unmarshal(resp.Body.Bytes(), &dd)
100 c.Check(err, check.IsNil)
101 c.Check(dd.BlobSignatureTTL, check.Not(check.Equals), int64(0))
102 c.Check(dd.BlobSignatureTTL > 0, check.Equals, true)
103 c.Check(len(dd.Resources), check.Not(check.Equals), 0)
104 c.Check(len(dd.Schemas), check.Not(check.Equals), 0)
107 func (s *HandlerSuite) TestRequestTimeout(c *check.C) {
108 s.cluster.API.RequestTimeout = arvados.Duration(time.Nanosecond)
109 req := httptest.NewRequest("GET", "/discovery/v1/apis/arvados/v1/rest", nil)
110 resp := httptest.NewRecorder()
111 s.handler.ServeHTTP(resp, req)
112 c.Check(resp.Code, check.Equals, http.StatusBadGateway)
113 var jresp httpserver.ErrorResponse
114 err := json.Unmarshal(resp.Body.Bytes(), &jresp)
115 c.Check(err, check.IsNil)
116 c.Assert(len(jresp.Errors), check.Equals, 1)
117 c.Check(jresp.Errors[0], check.Matches, `.*context deadline exceeded.*`)
120 func (s *HandlerSuite) TestProxyWithoutToken(c *check.C) {
121 req := httptest.NewRequest("GET", "/arvados/v1/users/current", nil)
122 resp := httptest.NewRecorder()
123 s.handler.ServeHTTP(resp, req)
124 c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
125 jresp := map[string]interface{}{}
126 err := json.Unmarshal(resp.Body.Bytes(), &jresp)
127 c.Check(err, check.IsNil)
128 c.Check(jresp["errors"], check.FitsTypeOf, []interface{}{})
131 func (s *HandlerSuite) TestProxyWithToken(c *check.C) {
132 req := httptest.NewRequest("GET", "/arvados/v1/users/current", nil)
133 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
134 resp := httptest.NewRecorder()
135 s.handler.ServeHTTP(resp, req)
136 c.Check(resp.Code, check.Equals, http.StatusOK)
138 err := json.Unmarshal(resp.Body.Bytes(), &u)
139 c.Check(err, check.IsNil)
140 c.Check(u.UUID, check.Equals, arvadostest.ActiveUserUUID)
143 func (s *HandlerSuite) TestProxyWithTokenInRequestBody(c *check.C) {
144 req := httptest.NewRequest("POST", "/arvados/v1/users/current", strings.NewReader(url.Values{
146 "api_token": {arvadostest.ActiveToken},
148 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
149 resp := httptest.NewRecorder()
150 s.handler.ServeHTTP(resp, req)
151 c.Check(resp.Code, check.Equals, http.StatusOK)
153 err := json.Unmarshal(resp.Body.Bytes(), &u)
154 c.Check(err, check.IsNil)
155 c.Check(u.UUID, check.Equals, arvadostest.ActiveUserUUID)
158 func (s *HandlerSuite) TestProxyNotFound(c *check.C) {
159 req := httptest.NewRequest("GET", "/arvados/v1/xyzzy", nil)
160 resp := httptest.NewRecorder()
161 s.handler.ServeHTTP(resp, req)
162 c.Check(resp.Code, check.Equals, http.StatusNotFound)
163 jresp := map[string]interface{}{}
164 err := json.Unmarshal(resp.Body.Bytes(), &jresp)
165 c.Check(err, check.IsNil)
166 c.Check(jresp["errors"], check.FitsTypeOf, []interface{}{})
169 func (s *HandlerSuite) TestProxyRedirect(c *check.C) {
170 s.cluster.Login.SSO.Enable = true
171 s.cluster.Login.SSO.ProviderAppID = "test"
172 s.cluster.Login.SSO.ProviderAppSecret = "test"
173 req := httptest.NewRequest("GET", "https://0.0.0.0:1/login?return_to=foo", nil)
174 resp := httptest.NewRecorder()
175 s.handler.ServeHTTP(resp, req)
176 if !c.Check(resp.Code, check.Equals, http.StatusFound) {
177 c.Log(resp.Body.String())
179 // Old "proxy entire request" code path returns an absolute
180 // URL. New lib/controller/federation code path returns a
182 c.Check(resp.Header().Get("Location"), check.Matches, `(https://0.0.0.0:1)?/auth/joshid\?return_to=%2Cfoo&?`)
185 func (s *HandlerSuite) TestLogoutSSO(c *check.C) {
186 s.cluster.Login.SSO.Enable = true
187 s.cluster.Login.SSO.ProviderAppID = "test"
188 req := httptest.NewRequest("GET", "https://0.0.0.0:1/logout?return_to=https://example.com/foo", nil)
189 resp := httptest.NewRecorder()
190 s.handler.ServeHTTP(resp, req)
191 if !c.Check(resp.Code, check.Equals, http.StatusFound) {
192 c.Log(resp.Body.String())
194 c.Check(resp.Header().Get("Location"), check.Equals, "http://localhost:3002/users/sign_out?"+url.Values{"redirect_uri": {"https://example.com/foo"}}.Encode())
197 func (s *HandlerSuite) TestLogoutGoogle(c *check.C) {
198 if s.cluster.ForceLegacyAPI14 {
202 s.cluster.Login.Google.Enable = true
203 s.cluster.Login.Google.ClientID = "test"
204 req := httptest.NewRequest("GET", "https://0.0.0.0:1/logout?return_to=https://example.com/foo", nil)
205 resp := httptest.NewRecorder()
206 s.handler.ServeHTTP(resp, req)
207 if !c.Check(resp.Code, check.Equals, http.StatusFound) {
208 c.Log(resp.Body.String())
210 c.Check(resp.Header().Get("Location"), check.Equals, "https://example.com/foo")
213 func (s *HandlerSuite) TestValidateV1APIToken(c *check.C) {
214 req := httptest.NewRequest("GET", "/arvados/v1/users/current", nil)
215 user, ok, err := s.handler.(*Handler).validateAPItoken(req, arvadostest.ActiveToken)
216 c.Assert(err, check.IsNil)
217 c.Check(ok, check.Equals, true)
218 c.Check(user.Authorization.UUID, check.Equals, arvadostest.ActiveTokenUUID)
219 c.Check(user.Authorization.APIToken, check.Equals, arvadostest.ActiveToken)
220 c.Check(user.Authorization.Scopes, check.DeepEquals, []string{"all"})
221 c.Check(user.UUID, check.Equals, arvadostest.ActiveUserUUID)
224 func (s *HandlerSuite) TestValidateV2APIToken(c *check.C) {
225 req := httptest.NewRequest("GET", "/arvados/v1/users/current", nil)
226 user, ok, err := s.handler.(*Handler).validateAPItoken(req, arvadostest.ActiveTokenV2)
227 c.Assert(err, check.IsNil)
228 c.Check(ok, check.Equals, true)
229 c.Check(user.Authorization.UUID, check.Equals, arvadostest.ActiveTokenUUID)
230 c.Check(user.Authorization.APIToken, check.Equals, arvadostest.ActiveToken)
231 c.Check(user.Authorization.Scopes, check.DeepEquals, []string{"all"})
232 c.Check(user.UUID, check.Equals, arvadostest.ActiveUserUUID)
233 c.Check(user.Authorization.TokenV2(), check.Equals, arvadostest.ActiveTokenV2)
236 func (s *HandlerSuite) TestValidateRemoteToken(c *check.C) {
237 saltedToken, err := auth.SaltToken(arvadostest.ActiveTokenV2, "abcde")
238 c.Assert(err, check.IsNil)
239 for _, trial := range []struct {
243 {http.StatusOK, saltedToken},
244 {http.StatusUnauthorized, "bogus"},
246 req := httptest.NewRequest("GET", "https://0.0.0.0:1/arvados/v1/users/current?remote=abcde", nil)
247 req.Header.Set("Authorization", "Bearer "+trial.token)
248 resp := httptest.NewRecorder()
249 s.handler.ServeHTTP(resp, req)
250 if !c.Check(resp.Code, check.Equals, trial.code) {
251 c.Logf("HTTP %d: %s", resp.Code, resp.Body.String())
256 func (s *HandlerSuite) TestCreateAPIToken(c *check.C) {
257 req := httptest.NewRequest("GET", "/arvados/v1/users/current", nil)
258 auth, err := s.handler.(*Handler).createAPItoken(req, arvadostest.ActiveUserUUID, nil)
259 c.Assert(err, check.IsNil)
260 c.Check(auth.Scopes, check.DeepEquals, []string{"all"})
262 user, ok, err := s.handler.(*Handler).validateAPItoken(req, auth.TokenV2())
263 c.Assert(err, check.IsNil)
264 c.Check(ok, check.Equals, true)
265 c.Check(user.Authorization.UUID, check.Equals, auth.UUID)
266 c.Check(user.Authorization.APIToken, check.Equals, auth.APIToken)
267 c.Check(user.Authorization.Scopes, check.DeepEquals, []string{"all"})
268 c.Check(user.UUID, check.Equals, arvadostest.ActiveUserUUID)
269 c.Check(user.Authorization.TokenV2(), check.Equals, auth.TokenV2())
272 func (s *HandlerSuite) CheckObjectType(c *check.C, url string, token string, skippedFields map[string]bool) {
273 var proxied, direct map[string]interface{}
276 // Get collection from controller
277 req := httptest.NewRequest("GET", url, nil)
278 req.Header.Set("Authorization", "Bearer "+token)
279 resp := httptest.NewRecorder()
280 s.handler.ServeHTTP(resp, req)
281 c.Assert(resp.Code, check.Equals, http.StatusOK,
282 check.Commentf("Wasn't able to get data from the controller at %q", url))
283 err = json.Unmarshal(resp.Body.Bytes(), &proxied)
284 c.Check(err, check.Equals, nil)
286 // Get collection directly from RailsAPI
287 client := &http.Client{
288 Transport: &http.Transport{
289 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
292 resp2, err := client.Get(s.cluster.Services.RailsAPI.ExternalURL.String() + url + "/?api_token=" + token)
293 c.Check(err, check.Equals, nil)
294 defer resp2.Body.Close()
295 db, err := ioutil.ReadAll(resp2.Body)
296 c.Check(err, check.Equals, nil)
297 err = json.Unmarshal(db, &direct)
298 c.Check(err, check.Equals, nil)
300 // Check that all RailsAPI provided keys exist on the controller response.
301 for k := range direct {
302 if _, ok := skippedFields[k]; ok {
304 } else if val, ok := proxied[k]; ok {
305 if direct["kind"] == "arvados#collection" && k == "manifest_text" {
306 // Tokens differ from request to request
307 c.Check(strings.Split(val.(string), "+A")[0], check.Equals, strings.Split(direct[k].(string), "+A")[0])
309 c.Check(val, check.DeepEquals, direct[k],
310 check.Commentf("RailsAPI %s key %q's value %q differs from controller's %q.", direct["kind"], k, direct[k], val))
313 c.Errorf("%s's key %q missing on controller's response.", direct["kind"], k)
318 func (s *HandlerSuite) TestGetObjects(c *check.C) {
319 // Get the 1st keep service's uuid from the running test server.
320 req := httptest.NewRequest("GET", "/arvados/v1/keep_services/", nil)
321 req.Header.Set("Authorization", "Bearer "+arvadostest.AdminToken)
322 resp := httptest.NewRecorder()
323 s.handler.ServeHTTP(resp, req)
324 c.Assert(resp.Code, check.Equals, http.StatusOK)
325 var ksList arvados.KeepServiceList
326 json.Unmarshal(resp.Body.Bytes(), &ksList)
327 c.Assert(len(ksList.Items), check.Not(check.Equals), 0)
328 ksUUID := ksList.Items[0].UUID
330 testCases := map[string]map[string]bool{
331 "api_clients/" + arvadostest.TrustedWorkbenchAPIClientUUID: nil,
332 "api_client_authorizations/" + arvadostest.AdminTokenUUID: nil,
333 "authorized_keys/" + arvadostest.AdminAuthorizedKeysUUID: nil,
334 "collections/" + arvadostest.CollectionWithUniqueWordsUUID: map[string]bool{"href": true},
335 "containers/" + arvadostest.RunningContainerUUID: nil,
336 "container_requests/" + arvadostest.QueuedContainerRequestUUID: nil,
337 "groups/" + arvadostest.AProjectUUID: nil,
338 "keep_services/" + ksUUID: nil,
339 "links/" + arvadostest.ActiveUserCanReadAllUsersLinkUUID: nil,
340 "logs/" + arvadostest.CrunchstatForRunningJobLogUUID: nil,
341 "nodes/" + arvadostest.IdleNodeUUID: nil,
342 "repositories/" + arvadostest.ArvadosRepoUUID: nil,
343 "users/" + arvadostest.ActiveUserUUID: map[string]bool{"href": true},
344 "virtual_machines/" + arvadostest.TestVMUUID: nil,
345 "workflows/" + arvadostest.WorkflowWithDefinitionYAMLUUID: nil,
347 for url, skippedFields := range testCases {
348 s.CheckObjectType(c, "/arvados/v1/"+url, arvadostest.AdminToken, skippedFields)