1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "git.arvados.org/arvados.git/sdk/go/arvados"
23 "git.arvados.org/arvados.git/sdk/go/arvadostest"
24 "git.arvados.org/arvados.git/sdk/go/auth"
25 "git.arvados.org/arvados.git/sdk/go/ctxlog"
26 "git.arvados.org/arvados.git/sdk/go/httpserver"
27 "github.com/prometheus/client_golang/prometheus"
28 check "gopkg.in/check.v1"
31 // Gocheck boilerplate
32 func Test(t *testing.T) {
36 var _ = check.Suite(&HandlerSuite{})
38 type HandlerSuite struct {
39 cluster *arvados.Cluster
43 cancel context.CancelFunc
46 func (s *HandlerSuite) SetUpTest(c *check.C) {
47 s.logbuf = &bytes.Buffer{}
48 s.ctx, s.cancel = context.WithCancel(context.Background())
49 s.ctx = ctxlog.Context(s.ctx, ctxlog.New(io.MultiWriter(os.Stderr, s.logbuf), "json", "debug"))
50 s.cluster = &arvados.Cluster{
52 PostgreSQL: integrationTestCluster().PostgreSQL,
54 s.cluster.API.RequestTimeout = arvados.Duration(5 * time.Minute)
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()).(*Handler)
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.Log(resp.Body.String())
75 if !c.Check(resp.Code, check.Equals, http.StatusOK) {
78 c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, `*`)
79 c.Check(resp.Header().Get("Access-Control-Allow-Methods"), check.Matches, `.*\bGET\b.*`)
80 c.Check(resp.Header().Get("Access-Control-Allow-Headers"), check.Matches, `.+`)
81 if method == "OPTIONS" {
82 c.Check(resp.Body.String(), check.HasLen, 0)
85 var cluster arvados.Cluster
86 err := json.Unmarshal(resp.Body.Bytes(), &cluster)
87 c.Check(err, check.IsNil)
88 c.Check(cluster.ManagementToken, check.Equals, "")
89 c.Check(cluster.SystemRootToken, check.Equals, "")
90 c.Check(cluster.Collections.BlobSigning, check.Equals, true)
91 c.Check(cluster.Collections.BlobSigningTTL, check.Equals, arvados.Duration(23*time.Second))
95 func (s *HandlerSuite) TestVocabularyExport(c *check.C) {
101 "labels": [{"label": "Importance"}],
104 "labels": [{"label": "High"}]
107 "labels": [{"label": "Low"}]
113 f, err := os.CreateTemp("", "test-vocabulary-*.json")
114 c.Assert(err, check.IsNil)
115 defer os.Remove(f.Name())
116 _, err = f.WriteString(voc)
117 c.Assert(err, check.IsNil)
119 s.cluster.API.VocabularyPath = f.Name()
120 for _, method := range []string{"GET", "OPTIONS"} {
121 c.Log(c.TestName()+" ", method)
122 req := httptest.NewRequest(method, "/arvados/v1/vocabulary", nil)
123 resp := httptest.NewRecorder()
124 s.handler.ServeHTTP(resp, req)
125 c.Log(resp.Body.String())
126 if !c.Check(resp.Code, check.Equals, http.StatusOK) {
129 c.Check(resp.Header().Get("Access-Control-Allow-Origin"), check.Equals, `*`)
130 c.Check(resp.Header().Get("Access-Control-Allow-Methods"), check.Matches, `.*\bGET\b.*`)
131 c.Check(resp.Header().Get("Access-Control-Allow-Headers"), check.Matches, `.+`)
132 if method == "OPTIONS" {
133 c.Check(resp.Body.String(), check.HasLen, 0)
136 var expectedVoc, receivedVoc *arvados.Vocabulary
137 err := json.Unmarshal([]byte(voc), &expectedVoc)
138 c.Check(err, check.IsNil)
139 err = json.Unmarshal(resp.Body.Bytes(), &receivedVoc)
140 c.Check(err, check.IsNil)
141 c.Check(receivedVoc, check.DeepEquals, expectedVoc)
145 func (s *HandlerSuite) TestVocabularyFailedCheckStatus(c *check.C) {
147 "strict_tags": false,
151 "labels": [{"label": "Importance"}],
154 "labels": [{"label": "High"}]
157 "labels": [{"label": "Low"}]
163 f, err := os.CreateTemp("", "test-vocabulary-*.json")
164 c.Assert(err, check.IsNil)
165 defer os.Remove(f.Name())
166 _, err = f.WriteString(voc)
167 c.Assert(err, check.IsNil)
169 s.cluster.API.VocabularyPath = f.Name()
171 req := httptest.NewRequest("POST", "/arvados/v1/collections",
175 "IDTAGIMPORTANCE": "Critical"
179 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
180 req.Header.Set("Content-type", "application/json")
182 resp := httptest.NewRecorder()
183 s.handler.ServeHTTP(resp, req)
184 c.Log(resp.Body.String())
185 c.Assert(resp.Code, check.Equals, http.StatusBadRequest)
186 var jresp httpserver.ErrorResponse
187 err = json.Unmarshal(resp.Body.Bytes(), &jresp)
188 c.Check(err, check.IsNil)
189 c.Assert(len(jresp.Errors), check.Equals, 1)
190 c.Check(jresp.Errors[0], check.Matches, `.*tag value.*is not valid for key.*`)
193 func (s *HandlerSuite) TestProxyDiscoveryDoc(c *check.C) {
194 req := httptest.NewRequest("GET", "/discovery/v1/apis/arvados/v1/rest", nil)
195 resp := httptest.NewRecorder()
196 s.handler.ServeHTTP(resp, req)
197 c.Check(resp.Code, check.Equals, http.StatusOK)
198 var dd arvados.DiscoveryDocument
199 err := json.Unmarshal(resp.Body.Bytes(), &dd)
200 c.Check(err, check.IsNil)
201 c.Check(dd.BlobSignatureTTL, check.Not(check.Equals), int64(0))
202 c.Check(dd.BlobSignatureTTL > 0, check.Equals, true)
203 c.Check(len(dd.Resources), check.Not(check.Equals), 0)
204 c.Check(len(dd.Schemas), check.Not(check.Equals), 0)
207 // Handler should give up and exit early if request context is
208 // cancelled due to client hangup, httpserver.HandlerWithDeadline,
210 func (s *HandlerSuite) TestRequestCancel(c *check.C) {
211 ctx, cancel := context.WithCancel(context.Background())
212 req := httptest.NewRequest("GET", "/discovery/v1/apis/arvados/v1/rest", nil).WithContext(ctx)
213 resp := httptest.NewRecorder()
215 s.handler.ServeHTTP(resp, req)
216 c.Check(resp.Code, check.Equals, http.StatusBadGateway)
217 var jresp httpserver.ErrorResponse
218 err := json.Unmarshal(resp.Body.Bytes(), &jresp)
219 c.Check(err, check.IsNil)
220 c.Assert(len(jresp.Errors), check.Equals, 1)
221 c.Check(jresp.Errors[0], check.Matches, `.*context canceled`)
224 func (s *HandlerSuite) TestProxyWithoutToken(c *check.C) {
225 req := httptest.NewRequest("GET", "/arvados/v1/users/current", nil)
226 resp := httptest.NewRecorder()
227 s.handler.ServeHTTP(resp, req)
228 c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
229 jresp := map[string]interface{}{}
230 err := json.Unmarshal(resp.Body.Bytes(), &jresp)
231 c.Check(err, check.IsNil)
232 c.Check(jresp["errors"], check.FitsTypeOf, []interface{}{})
235 func (s *HandlerSuite) TestProxyWithToken(c *check.C) {
236 req := httptest.NewRequest("GET", "/arvados/v1/users/current", nil)
237 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
238 resp := httptest.NewRecorder()
239 s.handler.ServeHTTP(resp, req)
240 c.Check(resp.Code, check.Equals, http.StatusOK)
242 err := json.Unmarshal(resp.Body.Bytes(), &u)
243 c.Check(err, check.IsNil)
244 c.Check(u.UUID, check.Equals, arvadostest.ActiveUserUUID)
247 func (s *HandlerSuite) TestProxyWithTokenInRequestBody(c *check.C) {
248 req := httptest.NewRequest("POST", "/arvados/v1/users/current", strings.NewReader(url.Values{
250 "api_token": {arvadostest.ActiveToken},
252 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
253 resp := httptest.NewRecorder()
254 s.handler.ServeHTTP(resp, req)
255 c.Check(resp.Code, check.Equals, http.StatusOK)
257 err := json.Unmarshal(resp.Body.Bytes(), &u)
258 c.Check(err, check.IsNil)
259 c.Check(u.UUID, check.Equals, arvadostest.ActiveUserUUID)
262 func (s *HandlerSuite) TestProxyNotFound(c *check.C) {
263 req := httptest.NewRequest("GET", "/arvados/v1/xyzzy", nil)
264 resp := httptest.NewRecorder()
265 s.handler.ServeHTTP(resp, req)
266 c.Check(resp.Code, check.Equals, http.StatusNotFound)
267 jresp := map[string]interface{}{}
268 err := json.Unmarshal(resp.Body.Bytes(), &jresp)
269 c.Check(err, check.IsNil)
270 c.Check(jresp["errors"], check.FitsTypeOf, []interface{}{})
273 func (s *HandlerSuite) TestLogoutGoogle(c *check.C) {
274 s.cluster.Login.Google.Enable = true
275 s.cluster.Login.Google.ClientID = "test"
276 req := httptest.NewRequest("GET", "https://0.0.0.0:1/logout?return_to=https://example.com/foo", nil)
277 resp := httptest.NewRecorder()
278 s.handler.ServeHTTP(resp, req)
279 if !c.Check(resp.Code, check.Equals, http.StatusFound) {
280 c.Log(resp.Body.String())
282 c.Check(resp.Header().Get("Location"), check.Equals, "https://example.com/foo")
285 func (s *HandlerSuite) TestValidateV1APIToken(c *check.C) {
286 req := httptest.NewRequest("GET", "/arvados/v1/users/current", nil)
287 user, ok, err := s.handler.validateAPItoken(req, arvadostest.ActiveToken)
288 c.Assert(err, check.IsNil)
289 c.Check(ok, check.Equals, true)
290 c.Check(user.Authorization.UUID, check.Equals, arvadostest.ActiveTokenUUID)
291 c.Check(user.Authorization.APIToken, check.Equals, arvadostest.ActiveToken)
292 c.Check(user.Authorization.Scopes, check.DeepEquals, []string{"all"})
293 c.Check(user.UUID, check.Equals, arvadostest.ActiveUserUUID)
296 func (s *HandlerSuite) TestValidateV2APIToken(c *check.C) {
297 req := httptest.NewRequest("GET", "/arvados/v1/users/current", nil)
298 user, ok, err := s.handler.validateAPItoken(req, arvadostest.ActiveTokenV2)
299 c.Assert(err, check.IsNil)
300 c.Check(ok, check.Equals, true)
301 c.Check(user.Authorization.UUID, check.Equals, arvadostest.ActiveTokenUUID)
302 c.Check(user.Authorization.APIToken, check.Equals, arvadostest.ActiveToken)
303 c.Check(user.Authorization.Scopes, check.DeepEquals, []string{"all"})
304 c.Check(user.UUID, check.Equals, arvadostest.ActiveUserUUID)
305 c.Check(user.Authorization.TokenV2(), check.Equals, arvadostest.ActiveTokenV2)
308 func (s *HandlerSuite) TestValidateRemoteToken(c *check.C) {
309 saltedToken, err := auth.SaltToken(arvadostest.ActiveTokenV2, "abcde")
310 c.Assert(err, check.IsNil)
311 for _, trial := range []struct {
315 {http.StatusOK, saltedToken},
316 {http.StatusUnauthorized, "bogus"},
318 req := httptest.NewRequest("GET", "https://0.0.0.0:1/arvados/v1/users/current?remote=abcde", nil)
319 req.Header.Set("Authorization", "Bearer "+trial.token)
320 resp := httptest.NewRecorder()
321 s.handler.ServeHTTP(resp, req)
322 if !c.Check(resp.Code, check.Equals, trial.code) {
323 c.Logf("HTTP %d: %s", resp.Code, resp.Body.String())
328 func (s *HandlerSuite) TestLogTokenUUID(c *check.C) {
329 req := httptest.NewRequest("GET", "https://0.0.0.0/arvados/v1/users/current", nil)
330 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveTokenV2)
331 req = req.WithContext(s.ctx)
332 resp := httptest.NewRecorder()
333 httpserver.LogRequests(s.handler).ServeHTTP(resp, req)
334 c.Check(resp.Code, check.Equals, http.StatusOK)
335 c.Check(s.logbuf.String(), check.Matches, `(?ms).*"tokenUUIDs":\["`+strings.Split(arvadostest.ActiveTokenV2, "/")[1]+`"\].*`)
338 func (s *HandlerSuite) TestCreateAPIToken(c *check.C) {
339 req := httptest.NewRequest("GET", "/arvados/v1/users/current", nil)
340 auth, err := s.handler.createAPItoken(req, arvadostest.ActiveUserUUID, nil)
341 c.Assert(err, check.IsNil)
342 c.Check(auth.Scopes, check.DeepEquals, []string{"all"})
344 user, ok, err := s.handler.validateAPItoken(req, auth.TokenV2())
345 c.Assert(err, check.IsNil)
346 c.Check(ok, check.Equals, true)
347 c.Check(user.Authorization.UUID, check.Equals, auth.UUID)
348 c.Check(user.Authorization.APIToken, check.Equals, auth.APIToken)
349 c.Check(user.Authorization.Scopes, check.DeepEquals, []string{"all"})
350 c.Check(user.UUID, check.Equals, arvadostest.ActiveUserUUID)
351 c.Check(user.Authorization.TokenV2(), check.Equals, auth.TokenV2())
354 func (s *HandlerSuite) CheckObjectType(c *check.C, url string, token string, skippedFields map[string]bool) {
355 var proxied, direct map[string]interface{}
358 // Get collection from controller
359 req := httptest.NewRequest("GET", url, nil)
360 req.Header.Set("Authorization", "Bearer "+token)
361 resp := httptest.NewRecorder()
362 s.handler.ServeHTTP(resp, req)
363 c.Assert(resp.Code, check.Equals, http.StatusOK,
364 check.Commentf("Wasn't able to get data from the controller at %q: %q", url, resp.Body.String()))
365 err = json.Unmarshal(resp.Body.Bytes(), &proxied)
366 c.Check(err, check.Equals, nil)
368 // Get collection directly from RailsAPI
369 client := &http.Client{
370 Transport: &http.Transport{
371 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
374 resp2, err := client.Get(s.cluster.Services.RailsAPI.ExternalURL.String() + url + "/?api_token=" + token)
375 c.Check(err, check.Equals, nil)
376 c.Assert(resp2.StatusCode, check.Equals, http.StatusOK,
377 check.Commentf("Wasn't able to get data from the RailsAPI at %q", url))
378 defer resp2.Body.Close()
379 db, err := ioutil.ReadAll(resp2.Body)
380 c.Check(err, check.Equals, nil)
381 err = json.Unmarshal(db, &direct)
382 c.Check(err, check.Equals, nil)
384 // Check that all RailsAPI provided keys exist on the controller response.
385 for k := range direct {
386 if _, ok := skippedFields[k]; ok {
388 } else if val, ok := proxied[k]; !ok {
389 c.Errorf("%s's key %q missing on controller's response.", direct["kind"], k)
390 } else if direct["kind"] == "arvados#collection" && k == "manifest_text" {
391 // Tokens differ from request to request
392 c.Check(strings.Split(val.(string), "+A")[0], check.Equals, strings.Split(direct[k].(string), "+A")[0])
394 c.Check(val, check.DeepEquals, direct[k],
395 check.Commentf("RailsAPI %s key %q's value %q differs from controller's %q.", direct["kind"], k, direct[k], val))
400 func (s *HandlerSuite) TestGetObjects(c *check.C) {
401 // Get the 1st keep service's uuid from the running test server.
402 req := httptest.NewRequest("GET", "/arvados/v1/keep_services/", nil)
403 req.Header.Set("Authorization", "Bearer "+arvadostest.AdminToken)
404 resp := httptest.NewRecorder()
405 s.handler.ServeHTTP(resp, req)
406 c.Assert(resp.Code, check.Equals, http.StatusOK)
407 var ksList arvados.KeepServiceList
408 json.Unmarshal(resp.Body.Bytes(), &ksList)
409 c.Assert(len(ksList.Items), check.Not(check.Equals), 0)
410 ksUUID := ksList.Items[0].UUID
411 // Create a new token for the test user so that we're not comparing
412 // the ones from the fixtures.
413 req = httptest.NewRequest("POST", "/arvados/v1/api_client_authorizations",
415 "api_client_authorization": {
416 "owner_uuid": "`+arvadostest.AdminUserUUID+`",
417 "created_by_ip_address": "::1",
418 "last_used_by_ip_address": "::1",
419 "default_owner_uuid": "`+arvadostest.AdminUserUUID+`"
422 req.Header.Set("Authorization", "Bearer "+arvadostest.SystemRootToken)
423 req.Header.Set("Content-type", "application/json")
424 resp = httptest.NewRecorder()
425 s.handler.ServeHTTP(resp, req)
426 c.Assert(resp.Code, check.Equals, http.StatusOK,
427 check.Commentf("%s", resp.Body.String()))
428 var auth arvados.APIClientAuthorization
429 json.Unmarshal(resp.Body.Bytes(), &auth)
430 c.Assert(auth.UUID, check.Not(check.Equals), "")
432 testCases := map[string]map[string]bool{
433 "api_clients/" + arvadostest.TrustedWorkbenchAPIClientUUID: nil,
434 "api_client_authorizations/" + auth.UUID: {"href": true, "modified_by_client_uuid": true, "modified_by_user_uuid": true},
435 "authorized_keys/" + arvadostest.AdminAuthorizedKeysUUID: nil,
436 "collections/" + arvadostest.CollectionWithUniqueWordsUUID: {"href": true},
437 "containers/" + arvadostest.RunningContainerUUID: nil,
438 "container_requests/" + arvadostest.QueuedContainerRequestUUID: nil,
439 "groups/" + arvadostest.AProjectUUID: nil,
440 "keep_services/" + ksUUID: nil,
441 "links/" + arvadostest.ActiveUserCanReadAllUsersLinkUUID: nil,
442 "logs/" + arvadostest.CrunchstatForRunningJobLogUUID: nil,
443 "nodes/" + arvadostest.IdleNodeUUID: nil,
444 "repositories/" + arvadostest.ArvadosRepoUUID: nil,
445 "users/" + arvadostest.ActiveUserUUID: {"href": true},
446 "virtual_machines/" + arvadostest.TestVMUUID: nil,
447 "workflows/" + arvadostest.WorkflowWithDefinitionYAMLUUID: nil,
449 for url, skippedFields := range testCases {
450 c.Logf("Testing %q", url)
451 s.CheckObjectType(c, "/arvados/v1/"+url, auth.TokenV2(), skippedFields)
455 func (s *HandlerSuite) TestRedactRailsAPIHostFromErrors(c *check.C) {
456 req := httptest.NewRequest("GET", "https://0.0.0.0:1/arvados/v1/collections/zzzzz-4zz18-abcdefghijklmno", nil)
457 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
458 resp := httptest.NewRecorder()
459 s.handler.ServeHTTP(resp, req)
460 c.Check(resp.Code, check.Equals, http.StatusNotFound)
464 c.Log(resp.Body.String())
465 c.Assert(json.NewDecoder(resp.Body).Decode(&jresp), check.IsNil)
466 c.Assert(jresp.Errors, check.HasLen, 1)
467 c.Check(jresp.Errors[0], check.Matches, `.*//railsapi\.internal/arvados/v1/collections/.*: 404 Not Found.*`)
468 c.Check(jresp.Errors[0], check.Not(check.Matches), `(?ms).*127.0.0.1.*`)
471 func (s *HandlerSuite) TestTrashSweep(c *check.C) {
472 s.cluster.SystemRootToken = arvadostest.SystemRootToken
473 s.cluster.Collections.TrashSweepInterval = arvados.Duration(time.Second / 10)
474 s.handler.CheckHealth()
475 ctx := auth.NewContext(s.ctx, &auth.Credentials{Tokens: []string{arvadostest.ActiveTokenV2}})
476 coll, err := s.handler.federation.CollectionCreate(ctx, arvados.CreateOptions{Attrs: map[string]interface{}{"name": "test trash sweep"}, EnsureUniqueName: true})
477 c.Assert(err, check.IsNil)
478 defer s.handler.federation.CollectionDelete(ctx, arvados.DeleteOptions{UUID: coll.UUID})
479 db, err := s.handler.db(s.ctx)
480 c.Assert(err, check.IsNil)
481 _, err = db.ExecContext(s.ctx, `update collections set trash_at = $1, delete_at = $2 where uuid = $3`, time.Now().UTC().Add(time.Second/10), time.Now().UTC().Add(time.Hour), coll.UUID)
482 c.Assert(err, check.IsNil)
483 deadline := time.Now().Add(5 * time.Second)
485 if time.Now().After(deadline) {
489 updated, err := s.handler.federation.CollectionGet(ctx, arvados.GetOptions{UUID: coll.UUID, IncludeTrash: true})
490 c.Assert(err, check.IsNil)
491 if updated.IsTrashed {
494 time.Sleep(time.Second / 10)