1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.arvados.org/arvados.git/lib/boot"
21 "git.arvados.org/arvados.git/lib/config"
22 "git.arvados.org/arvados.git/lib/controller/rpc"
23 "git.arvados.org/arvados.git/lib/service"
24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
26 "git.arvados.org/arvados.git/sdk/go/arvadostest"
27 "git.arvados.org/arvados.git/sdk/go/auth"
28 "git.arvados.org/arvados.git/sdk/go/ctxlog"
29 "git.arvados.org/arvados.git/sdk/go/keepclient"
30 check "gopkg.in/check.v1"
33 var _ = check.Suite(&IntegrationSuite{})
35 type testCluster struct {
38 controllerURL *url.URL
41 type IntegrationSuite struct {
42 testClusters map[string]*testCluster
43 oidcprovider *arvadostest.OIDCProvider
46 func (s *IntegrationSuite) SetUpSuite(c *check.C) {
48 c.Skip("heavy integration tests don't run with forceLegacyAPI14")
54 s.oidcprovider = arvadostest.NewOIDCProvider(c)
55 s.oidcprovider.AuthEmail = "user@example.com"
56 s.oidcprovider.AuthEmailVerified = true
57 s.oidcprovider.AuthName = "Example User"
58 s.oidcprovider.ValidClientID = "clientid"
59 s.oidcprovider.ValidClientSecret = "clientsecret"
61 s.testClusters = map[string]*testCluster{
66 hostport := map[string]string{}
67 for id := range s.testClusters {
68 hostport[id] = func() string {
69 // TODO: Instead of expecting random ports on
70 // 127.0.0.11, 22, 33 to be race-safe, try
71 // different 127.x.y.z until finding one that
73 ln, err := net.Listen("tcp", ":0")
74 c.Assert(err, check.IsNil)
76 _, port, err := net.SplitHostPort(ln.Addr().String())
77 c.Assert(err, check.IsNil)
78 return "127.0.0." + id[3:] + ":" + port
81 for id := range s.testClusters {
86 ExternalURL: https://` + hostport[id] + `
95 Host: ` + hostport["z1111"] + `
103 Host: ` + hostport["z2222"] + `
112 Host: ` + hostport["z3333"] + `
125 Issuer: ` + s.oidcprovider.Issuer.URL + `
126 ClientID: ` + s.oidcprovider.ValidClientID + `
127 ClientSecret: ` + s.oidcprovider.ValidClientSecret + `
129 EmailVerifiedClaim: email_verified
138 loader := config.NewLoader(bytes.NewBufferString(yaml), ctxlog.TestLogger(c))
140 loader.SkipLegacy = true
141 loader.SkipAPICalls = true
142 cfg, err := loader.Load()
143 c.Assert(err, check.IsNil)
144 s.testClusters[id] = &testCluster{
145 super: boot.Supervisor{
146 SourcePath: filepath.Join(cwd, "..", ".."),
148 ListenHost: "127.0.0." + id[3:],
149 ControllerAddr: ":0",
150 OwnTemporaryDatabase: true,
151 Stderr: &service.LogPrefixer{Writer: ctxlog.LogWriter(c.Log), Prefix: []byte("[" + id + "] ")},
155 s.testClusters[id].super.Start(context.Background(), &s.testClusters[id].config, "-")
157 for _, tc := range s.testClusters {
158 au, ok := tc.super.WaitReady()
159 c.Assert(ok, check.Equals, true)
161 tc.controllerURL = &u
165 func (s *IntegrationSuite) TearDownSuite(c *check.C) {
166 for _, c := range s.testClusters {
171 // Get rpc connection struct initialized to communicate with the
172 // specified cluster.
173 func (s *IntegrationSuite) conn(clusterID string) *rpc.Conn {
174 return rpc.NewConn(clusterID, s.testClusters[clusterID].controllerURL, true, rpc.PassthroughTokenProvider)
177 // Return Context, Arvados.Client and keepclient structs initialized
178 // to connect to the specified cluster (by clusterID) using with the supplied
180 func (s *IntegrationSuite) clientsWithToken(clusterID string, token string) (context.Context, *arvados.Client, *keepclient.KeepClient) {
181 cl := s.testClusters[clusterID].config.Clusters[clusterID]
182 ctx := auth.NewContext(context.Background(), auth.NewCredentials(token))
183 ac, err := arvados.NewClientFromConfig(&cl)
188 arv, err := arvadosclient.New(ac)
192 kc := keepclient.New(arv)
196 // Log in as a user called "example", get the user's API token,
197 // initialize clients with the API token, set up the user and
198 // optionally activate the user. Return client structs for
199 // communicating with the cluster on behalf of the 'example' user.
200 func (s *IntegrationSuite) userClients(rootctx context.Context, c *check.C, conn *rpc.Conn, clusterID string, activate bool) (context.Context, *arvados.Client, *keepclient.KeepClient, arvados.User) {
201 login, err := conn.UserSessionCreate(rootctx, rpc.UserSessionCreateOptions{
202 ReturnTo: ",https://example.com",
203 AuthInfo: rpc.UserSessionAuthInfo{
204 Email: "user@example.com",
205 FirstName: "Example",
210 c.Assert(err, check.IsNil)
211 redirURL, err := url.Parse(login.RedirectLocation)
212 c.Assert(err, check.IsNil)
213 userToken := redirURL.Query().Get("api_token")
214 c.Logf("user token: %q", userToken)
215 ctx, ac, kc := s.clientsWithToken(clusterID, userToken)
216 user, err := conn.UserGetCurrent(ctx, arvados.GetOptions{})
217 c.Assert(err, check.IsNil)
218 _, err = conn.UserSetup(rootctx, arvados.UserSetupOptions{UUID: user.UUID})
219 c.Assert(err, check.IsNil)
221 _, err = conn.UserActivate(rootctx, arvados.UserActivateOptions{UUID: user.UUID})
222 c.Assert(err, check.IsNil)
223 user, err = conn.UserGetCurrent(ctx, arvados.GetOptions{})
224 c.Assert(err, check.IsNil)
225 c.Logf("user UUID: %q", user.UUID)
227 c.Fatalf("failed to activate user -- %#v", user)
230 return ctx, ac, kc, user
233 // Return Context, arvados.Client and keepclient structs initialized
234 // to communicate with the cluster as the system root user.
235 func (s *IntegrationSuite) rootClients(clusterID string) (context.Context, *arvados.Client, *keepclient.KeepClient) {
236 return s.clientsWithToken(clusterID, s.testClusters[clusterID].config.Clusters[clusterID].SystemRootToken)
239 // Return Context, arvados.Client and keepclient structs initialized
240 // to communicate with the cluster as the anonymous user.
241 func (s *IntegrationSuite) anonymousClients(clusterID string) (context.Context, *arvados.Client, *keepclient.KeepClient) {
242 return s.clientsWithToken(clusterID, s.testClusters[clusterID].config.Clusters[clusterID].Users.AnonymousUserToken)
245 func (s *IntegrationSuite) TestGetCollectionByPDH(c *check.C) {
246 conn1 := s.conn("z1111")
247 rootctx1, _, _ := s.rootClients("z1111")
248 conn3 := s.conn("z3333")
249 userctx1, ac1, kc1, _ := s.userClients(rootctx1, c, conn1, "z1111", true)
251 // Create the collection to find its PDH (but don't save it
253 var coll1 arvados.Collection
254 fs1, err := coll1.FileSystem(ac1, kc1)
255 c.Assert(err, check.IsNil)
256 f, err := fs1.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
257 c.Assert(err, check.IsNil)
258 _, err = io.WriteString(f, "IntegrationSuite.TestGetCollectionByPDH")
259 c.Assert(err, check.IsNil)
261 c.Assert(err, check.IsNil)
262 mtxt, err := fs1.MarshalManifest(".")
263 c.Assert(err, check.IsNil)
264 pdh := arvados.PortableDataHash(mtxt)
266 // Looking up the PDH before saving returns 404 if cycle
267 // detection is working.
268 _, err = conn1.CollectionGet(userctx1, arvados.GetOptions{UUID: pdh})
269 c.Assert(err, check.ErrorMatches, `.*404 Not Found.*`)
271 // Save the collection on cluster z1111.
272 coll1, err = conn1.CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
273 "manifest_text": mtxt,
275 c.Assert(err, check.IsNil)
277 // Retrieve the collection from cluster z3333.
278 coll, err := conn3.CollectionGet(userctx1, arvados.GetOptions{UUID: pdh})
279 c.Check(err, check.IsNil)
280 c.Check(coll.PortableDataHash, check.Equals, pdh)
283 func (s *IntegrationSuite) TestGetCollectionAsAnonymous(c *check.C) {
284 conn1 := s.conn("z1111")
285 conn3 := s.conn("z3333")
286 rootctx1, rootac1, rootkc1 := s.rootClients("z1111")
287 anonctx3, anonac3, _ := s.anonymousClients("z3333")
289 // Make sure anonymous token was set
290 c.Assert(anonac3.AuthToken, check.Not(check.Equals), "")
292 // Create the collection to find its PDH (but don't save it
294 var coll1 arvados.Collection
295 fs1, err := coll1.FileSystem(rootac1, rootkc1)
296 c.Assert(err, check.IsNil)
297 f, err := fs1.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
298 c.Assert(err, check.IsNil)
299 _, err = io.WriteString(f, "IntegrationSuite.TestGetCollectionAsAnonymous")
300 c.Assert(err, check.IsNil)
302 c.Assert(err, check.IsNil)
303 mtxt, err := fs1.MarshalManifest(".")
304 c.Assert(err, check.IsNil)
305 pdh := arvados.PortableDataHash(mtxt)
307 // Save the collection on cluster z1111.
308 coll1, err = conn1.CollectionCreate(rootctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
309 "manifest_text": mtxt,
311 c.Assert(err, check.IsNil)
313 // Share it with the anonymous users group.
314 var outLink arvados.Link
315 err = rootac1.RequestAndDecode(&outLink, "POST", "/arvados/v1/links", nil,
316 map[string]interface{}{"link": map[string]interface{}{
317 "link_class": "permission",
319 "tail_uuid": "z1111-j7d0g-anonymouspublic",
320 "head_uuid": coll1.UUID,
323 c.Check(err, check.IsNil)
325 // Current user should be z3 anonymous user
326 outUser, err := anonac3.CurrentUser()
327 c.Check(err, check.IsNil)
328 c.Check(outUser.UUID, check.Equals, "z3333-tpzed-anonymouspublic")
330 // Get the token uuid
331 var outAuth arvados.APIClientAuthorization
332 err = anonac3.RequestAndDecode(&outAuth, "GET", "/arvados/v1/api_client_authorizations/current", nil, nil)
333 c.Check(err, check.IsNil)
335 // Make a v2 token of the z3 anonymous user, and use it on z1
336 _, anonac1, _ := s.clientsWithToken("z1111", outAuth.TokenV2())
337 outUser2, err := anonac1.CurrentUser()
338 c.Check(err, check.IsNil)
339 // z3 anonymous user will be mapped to the z1 anonymous user
340 c.Check(outUser2.UUID, check.Equals, "z1111-tpzed-anonymouspublic")
342 // Retrieve the collection (which is on z1) using anonymous from cluster z3333.
343 coll, err := conn3.CollectionGet(anonctx3, arvados.GetOptions{UUID: coll1.UUID})
344 c.Check(err, check.IsNil)
345 c.Check(coll.PortableDataHash, check.Equals, pdh)
348 // Get a token from the login cluster (z1111), use it to submit a
349 // container request on z2222.
350 func (s *IntegrationSuite) TestCreateContainerRequestWithFedToken(c *check.C) {
351 conn1 := s.conn("z1111")
352 rootctx1, _, _ := s.rootClients("z1111")
353 _, ac1, _, _ := s.userClients(rootctx1, c, conn1, "z1111", true)
355 // Use ac2 to get the discovery doc with a blank token, so the
356 // SDK doesn't magically pass the z1111 token to z2222 before
357 // we're ready to start our test.
358 _, ac2, _ := s.clientsWithToken("z2222", "")
359 var dd map[string]interface{}
360 err := ac2.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
361 c.Assert(err, check.IsNil)
368 cr arvados.ContainerRequest
370 json.NewEncoder(&body).Encode(map[string]interface{}{
371 "container_request": map[string]interface{}{
372 "command": []string{"echo"},
373 "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
378 ac2.AuthToken = ac1.AuthToken
380 c.Log("...post CR with good (but not yet cached) token")
381 cr = arvados.ContainerRequest{}
382 req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
383 c.Assert(err, check.IsNil)
384 req.Header.Set("Content-Type", "application/json")
385 err = ac2.DoAndDecode(&cr, req)
386 c.Logf("err == %#v", err)
388 c.Log("...get user with good token")
390 req, err = http.NewRequest("GET", "https://"+ac2.APIHost+"/arvados/v1/users/current", nil)
391 c.Assert(err, check.IsNil)
392 err = ac2.DoAndDecode(&u, req)
393 c.Check(err, check.IsNil)
394 c.Check(u.UUID, check.Matches, "z1111-tpzed-.*")
396 c.Log("...post CR with good cached token")
397 cr = arvados.ContainerRequest{}
398 req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
399 c.Assert(err, check.IsNil)
400 req.Header.Set("Content-Type", "application/json")
401 err = ac2.DoAndDecode(&cr, req)
402 c.Check(err, check.IsNil)
403 c.Check(cr.UUID, check.Matches, "z2222-.*")
405 c.Log("...post with good cached token ('OAuth2 ...')")
406 cr = arvados.ContainerRequest{}
407 req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
408 c.Assert(err, check.IsNil)
409 req.Header.Set("Content-Type", "application/json")
410 req.Header.Set("Authorization", "OAuth2 "+ac2.AuthToken)
411 resp, err = arvados.InsecureHTTPClient.Do(req)
412 if c.Check(err, check.IsNil) {
413 err = json.NewDecoder(resp.Body).Decode(&cr)
414 c.Check(err, check.IsNil)
415 c.Check(cr.UUID, check.Matches, "z2222-.*")
419 // Test for bug #16263
420 func (s *IntegrationSuite) TestListUsers(c *check.C) {
421 rootctx1, _, _ := s.rootClients("z1111")
422 conn1 := s.conn("z1111")
423 conn3 := s.conn("z3333")
424 userctx1, _, _, _ := s.userClients(rootctx1, c, conn1, "z1111", true)
426 // Make sure LoginCluster is properly configured
427 for cls := range s.testClusters {
429 s.testClusters[cls].config.Clusters[cls].Login.LoginCluster,
430 check.Equals, "z1111",
431 check.Commentf("incorrect LoginCluster config on cluster %q", cls))
433 // Make sure z1111 has users with NULL usernames
434 lst, err := conn1.UserList(rootctx1, arvados.ListOptions{
435 Limit: math.MaxInt64, // check that large limit works (see #16263)
437 nullUsername := false
438 c.Assert(err, check.IsNil)
439 c.Assert(len(lst.Items), check.Not(check.Equals), 0)
440 for _, user := range lst.Items {
441 if user.Username == "" {
445 c.Assert(nullUsername, check.Equals, true)
447 user1, err := conn1.UserGetCurrent(userctx1, arvados.GetOptions{})
448 c.Assert(err, check.IsNil)
449 c.Check(user1.IsActive, check.Equals, true)
451 // Ask for the user list on z3333 using z1111's system root token
452 lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
453 c.Assert(err, check.IsNil)
455 for _, user := range lst.Items {
456 if user.UUID == user1.UUID {
457 c.Check(user.IsActive, check.Equals, true)
462 c.Check(found, check.Equals, true)
464 // Deactivate user acct on z1111
465 _, err = conn1.UserUnsetup(rootctx1, arvados.GetOptions{UUID: user1.UUID})
466 c.Assert(err, check.IsNil)
468 // Get user list from z3333, check the returned z1111 user is
470 lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
471 c.Assert(err, check.IsNil)
473 for _, user := range lst.Items {
474 if user.UUID == user1.UUID {
475 c.Check(user.IsActive, check.Equals, false)
480 c.Check(found, check.Equals, true)
482 // Deactivated user can see is_active==false via "get current
484 user1, err = conn3.UserGetCurrent(userctx1, arvados.GetOptions{})
485 c.Assert(err, check.IsNil)
486 c.Check(user1.IsActive, check.Equals, false)
489 func (s *IntegrationSuite) TestSetupUserWithVM(c *check.C) {
490 conn1 := s.conn("z1111")
491 conn3 := s.conn("z3333")
492 rootctx1, rootac1, _ := s.rootClients("z1111")
494 // Create user on LoginCluster z1111
495 _, _, _, user := s.userClients(rootctx1, c, conn1, "z1111", false)
497 // Make a new root token (because rootClients() uses SystemRootToken)
498 var outAuth arvados.APIClientAuthorization
499 err := rootac1.RequestAndDecode(&outAuth, "POST", "/arvados/v1/api_client_authorizations", nil, nil)
500 c.Check(err, check.IsNil)
502 // Make a v2 root token to communicate with z3333
503 rootctx3, rootac3, _ := s.clientsWithToken("z3333", outAuth.TokenV2())
505 // Create VM on z3333
506 var outVM arvados.VirtualMachine
507 err = rootac3.RequestAndDecode(&outVM, "POST", "/arvados/v1/virtual_machines", nil,
508 map[string]interface{}{"virtual_machine": map[string]interface{}{
509 "hostname": "example",
512 c.Check(outVM.UUID[0:5], check.Equals, "z3333")
513 c.Check(err, check.IsNil)
515 // Make sure z3333 user list is up to date
516 _, err = conn3.UserList(rootctx3, arvados.ListOptions{Limit: 1000})
517 c.Check(err, check.IsNil)
519 // Try to set up user on z3333 with the VM
520 _, err = conn3.UserSetup(rootctx3, arvados.UserSetupOptions{UUID: user.UUID, VMUUID: outVM.UUID})
521 c.Check(err, check.IsNil)
523 var outLinks arvados.LinkList
524 err = rootac3.RequestAndDecode(&outLinks, "GET", "/arvados/v1/links", nil,
527 Filters: []arvados.Filter{
541 Operand: "can_login",
546 Operand: "permission",
548 c.Check(err, check.IsNil)
550 c.Check(len(outLinks.Items), check.Equals, 1)
553 func (s *IntegrationSuite) TestOIDCAccessTokenAuth(c *check.C) {
554 conn1 := s.conn("z1111")
555 rootctx1, _, _ := s.rootClients("z1111")
556 s.userClients(rootctx1, c, conn1, "z1111", true)
558 accesstoken := s.oidcprovider.ValidAccessToken()
560 for _, clusterid := range []string{"z1111", "z2222"} {
561 c.Logf("trying clusterid %s", clusterid)
563 conn := s.conn(clusterid)
564 ctx, ac, kc := s.clientsWithToken(clusterid, accesstoken)
566 var coll arvados.Collection
568 // Write some file data and create a collection
570 fs, err := coll.FileSystem(ac, kc)
571 c.Assert(err, check.IsNil)
572 f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
573 c.Assert(err, check.IsNil)
574 _, err = io.WriteString(f, "IntegrationSuite.TestOIDCAccessTokenAuth")
575 c.Assert(err, check.IsNil)
577 c.Assert(err, check.IsNil)
578 mtxt, err := fs.MarshalManifest(".")
579 c.Assert(err, check.IsNil)
580 coll, err = conn.CollectionCreate(ctx, arvados.CreateOptions{Attrs: map[string]interface{}{
581 "manifest_text": mtxt,
583 c.Assert(err, check.IsNil)
586 // Read the collection & file data
588 user, err := conn.UserGetCurrent(ctx, arvados.GetOptions{})
589 c.Assert(err, check.IsNil)
590 c.Check(user.FullName, check.Equals, "Example User")
591 coll, err = conn.CollectionGet(ctx, arvados.GetOptions{UUID: coll.UUID})
592 c.Assert(err, check.IsNil)
593 c.Check(coll.ManifestText, check.Not(check.Equals), "")
594 fs, err := coll.FileSystem(ac, kc)
595 c.Assert(err, check.IsNil)
596 f, err := fs.Open("test.txt")
597 c.Assert(err, check.IsNil)
598 buf, err := ioutil.ReadAll(f)
599 c.Assert(err, check.IsNil)
600 c.Check(buf, check.DeepEquals, []byte("IntegrationSuite.TestOIDCAccessTokenAuth"))