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.ProviderAppID = "test"
171 s.cluster.Login.ProviderAppSecret = "test"
172 req := httptest.NewRequest("GET", "https://0.0.0.0:1/login?return_to=foo", nil)
173 resp := httptest.NewRecorder()
174 s.handler.ServeHTTP(resp, req)
175 if !c.Check(resp.Code, check.Equals, http.StatusFound) {
176 c.Log(resp.Body.String())
178 // Old "proxy entire request" code path returns an absolute
179 // URL. New lib/controller/federation code path returns a
181 c.Check(resp.Header().Get("Location"), check.Matches, `(https://0.0.0.0:1)?/auth/joshid\?return_to=%2Cfoo&?`)
184 func (s *HandlerSuite) TestLogoutSSO(c *check.C) {
185 s.cluster.Login.ProviderAppID = "test"
186 req := httptest.NewRequest("GET", "https://0.0.0.0:1/logout?return_to=https://example.com/foo", nil)
187 resp := httptest.NewRecorder()
188 s.handler.ServeHTTP(resp, req)
189 if !c.Check(resp.Code, check.Equals, http.StatusFound) {
190 c.Log(resp.Body.String())
192 c.Check(resp.Header().Get("Location"), check.Equals, "http://localhost:3002/users/sign_out?"+url.Values{"redirect_uri": {"https://example.com/foo"}}.Encode())
195 func (s *HandlerSuite) TestLogoutGoogle(c *check.C) {
196 if s.cluster.ForceLegacyAPI14 {
200 s.cluster.Login.GoogleClientID = "test"
201 req := httptest.NewRequest("GET", "https://0.0.0.0:1/logout?return_to=https://example.com/foo", nil)
202 resp := httptest.NewRecorder()
203 s.handler.ServeHTTP(resp, req)
204 if !c.Check(resp.Code, check.Equals, http.StatusFound) {
205 c.Log(resp.Body.String())
207 c.Check(resp.Header().Get("Location"), check.Equals, "https://example.com/foo")
210 func (s *HandlerSuite) TestValidateV1APIToken(c *check.C) {
211 req := httptest.NewRequest("GET", "/arvados/v1/users/current", nil)
212 user, ok, err := s.handler.(*Handler).validateAPItoken(req, arvadostest.ActiveToken)
213 c.Assert(err, check.IsNil)
214 c.Check(ok, check.Equals, true)
215 c.Check(user.Authorization.UUID, check.Equals, arvadostest.ActiveTokenUUID)
216 c.Check(user.Authorization.APIToken, check.Equals, arvadostest.ActiveToken)
217 c.Check(user.Authorization.Scopes, check.DeepEquals, []string{"all"})
218 c.Check(user.UUID, check.Equals, arvadostest.ActiveUserUUID)
221 func (s *HandlerSuite) TestValidateV2APIToken(c *check.C) {
222 req := httptest.NewRequest("GET", "/arvados/v1/users/current", nil)
223 user, ok, err := s.handler.(*Handler).validateAPItoken(req, arvadostest.ActiveTokenV2)
224 c.Assert(err, check.IsNil)
225 c.Check(ok, check.Equals, true)
226 c.Check(user.Authorization.UUID, check.Equals, arvadostest.ActiveTokenUUID)
227 c.Check(user.Authorization.APIToken, check.Equals, arvadostest.ActiveToken)
228 c.Check(user.Authorization.Scopes, check.DeepEquals, []string{"all"})
229 c.Check(user.UUID, check.Equals, arvadostest.ActiveUserUUID)
230 c.Check(user.Authorization.TokenV2(), check.Equals, arvadostest.ActiveTokenV2)
233 func (s *HandlerSuite) TestValidateRemoteToken(c *check.C) {
234 saltedToken, err := auth.SaltToken(arvadostest.ActiveTokenV2, "abcde")
235 c.Assert(err, check.IsNil)
236 for _, trial := range []struct {
240 {http.StatusOK, saltedToken},
241 {http.StatusUnauthorized, "bogus"},
243 req := httptest.NewRequest("GET", "https://0.0.0.0:1/arvados/v1/users/current?remote=abcde", nil)
244 req.Header.Set("Authorization", "Bearer "+trial.token)
245 resp := httptest.NewRecorder()
246 s.handler.ServeHTTP(resp, req)
247 if !c.Check(resp.Code, check.Equals, trial.code) {
248 c.Logf("HTTP %d: %s", resp.Code, resp.Body.String())
253 func (s *HandlerSuite) TestCreateAPIToken(c *check.C) {
254 req := httptest.NewRequest("GET", "/arvados/v1/users/current", nil)
255 auth, err := s.handler.(*Handler).createAPItoken(req, arvadostest.ActiveUserUUID, nil)
256 c.Assert(err, check.IsNil)
257 c.Check(auth.Scopes, check.DeepEquals, []string{"all"})
259 user, ok, err := s.handler.(*Handler).validateAPItoken(req, auth.TokenV2())
260 c.Assert(err, check.IsNil)
261 c.Check(ok, check.Equals, true)
262 c.Check(user.Authorization.UUID, check.Equals, auth.UUID)
263 c.Check(user.Authorization.APIToken, check.Equals, auth.APIToken)
264 c.Check(user.Authorization.Scopes, check.DeepEquals, []string{"all"})
265 c.Check(user.UUID, check.Equals, arvadostest.ActiveUserUUID)
266 c.Check(user.Authorization.TokenV2(), check.Equals, auth.TokenV2())
269 func (s *HandlerSuite) CheckObjectType(c *check.C, url string, token string, skippedFields map[string]bool) {
270 var proxied, direct map[string]interface{}
273 // Get collection from controller
274 req := httptest.NewRequest("GET", url, nil)
275 req.Header.Set("Authorization", "Bearer "+token)
276 resp := httptest.NewRecorder()
277 s.handler.ServeHTTP(resp, req)
278 c.Assert(resp.Code, check.Equals, http.StatusOK,
279 check.Commentf("Wasn't able to get data from the controller at %q", url))
280 err = json.Unmarshal(resp.Body.Bytes(), &proxied)
281 c.Check(err, check.Equals, nil)
283 // Get collection directly from RailsAPI
284 client := &http.Client{
285 Transport: &http.Transport{
286 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
289 resp2, err := client.Get(s.cluster.Services.RailsAPI.ExternalURL.String() + url + "/?api_token=" + token)
290 c.Check(err, check.Equals, nil)
291 defer resp2.Body.Close()
292 db, err := ioutil.ReadAll(resp2.Body)
293 c.Check(err, check.Equals, nil)
294 err = json.Unmarshal(db, &direct)
295 c.Check(err, check.Equals, nil)
297 // Check that all RailsAPI provided keys exist on the controller response.
298 for k := range direct {
299 if _, ok := skippedFields[k]; ok {
301 } else if val, ok := proxied[k]; ok {
302 if direct["kind"] == "arvados#collection" && k == "manifest_text" {
303 // Tokens differ from request to request
304 c.Check(strings.Split(val.(string), "+A")[0], check.Equals, strings.Split(direct[k].(string), "+A")[0])
306 c.Check(val, check.DeepEquals, direct[k],
307 check.Commentf("RailsAPI %s key %q's value %q differs from controller's %q.", direct["kind"], k, direct[k], val))
310 c.Errorf("%s's key %q missing on controller's response.", direct["kind"], k)
315 func (s *HandlerSuite) TestGetObjects(c *check.C) {
316 // Get the 1st keep service's uuid from the running test server.
317 req := httptest.NewRequest("GET", "/arvados/v1/keep_services/", nil)
318 req.Header.Set("Authorization", "Bearer "+arvadostest.AdminToken)
319 resp := httptest.NewRecorder()
320 s.handler.ServeHTTP(resp, req)
321 c.Assert(resp.Code, check.Equals, http.StatusOK)
322 var ksList arvados.KeepServiceList
323 json.Unmarshal(resp.Body.Bytes(), &ksList)
324 c.Assert(len(ksList.Items), check.Not(check.Equals), 0)
325 ksUUID := ksList.Items[0].UUID
327 testCases := map[string]map[string]bool{
328 "api_clients/" + arvadostest.TrustedWorkbenchAPIClientUUID: nil,
329 "api_client_authorizations/" + arvadostest.AdminTokenUUID: nil,
330 "authorized_keys/" + arvadostest.AdminAuthorizedKeysUUID: nil,
331 "collections/" + arvadostest.CollectionWithUniqueWordsUUID: map[string]bool{"href": true},
332 "containers/" + arvadostest.RunningContainerUUID: nil,
333 "container_requests/" + arvadostest.QueuedContainerRequestUUID: nil,
334 "groups/" + arvadostest.AProjectUUID: nil,
335 "keep_services/" + ksUUID: nil,
336 "links/" + arvadostest.ActiveUserCanReadAllUsersLinkUUID: nil,
337 "logs/" + arvadostest.CrunchstatForRunningJobLogUUID: nil,
338 "nodes/" + arvadostest.IdleNodeUUID: nil,
339 "repositories/" + arvadostest.ArvadosRepoUUID: nil,
340 "users/" + arvadostest.ActiveUserUUID: map[string]bool{"href": true},
341 "virtual_machines/" + arvadostest.TestVMUUID: nil,
342 "workflows/" + arvadostest.WorkflowWithDefinitionYAMLUUID: nil,
344 for url, skippedFields := range testCases {
345 s.CheckObjectType(c, "/arvados/v1/"+url, arvadostest.AdminToken, skippedFields)