1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
25 "git.arvados.org/arvados.git/lib/boot"
26 "git.arvados.org/arvados.git/lib/config"
27 "git.arvados.org/arvados.git/sdk/go/arvados"
28 "git.arvados.org/arvados.git/sdk/go/arvadostest"
29 "git.arvados.org/arvados.git/sdk/go/ctxlog"
30 "git.arvados.org/arvados.git/sdk/go/httpserver"
31 check "gopkg.in/check.v1"
34 var _ = check.Suite(&IntegrationSuite{})
36 type IntegrationSuite struct {
37 testClusters map[string]*boot.TestCluster
38 oidcprovider *arvadostest.OIDCProvider
41 func (s *IntegrationSuite) SetUpSuite(c *check.C) {
44 s.oidcprovider = arvadostest.NewOIDCProvider(c)
45 s.oidcprovider.AuthEmail = "user@example.com"
46 s.oidcprovider.AuthEmailVerified = true
47 s.oidcprovider.AuthName = "Example User"
48 s.oidcprovider.ValidClientID = "clientid"
49 s.oidcprovider.ValidClientSecret = "clientsecret"
51 s.testClusters = map[string]*boot.TestCluster{
56 hostport := map[string]string{}
57 for id := range s.testClusters {
58 hostport[id] = func() string {
59 // TODO: Instead of expecting random ports on
60 // 127.0.0.11, 22, 33 to be race-safe, try
61 // different 127.x.y.z until finding one that
63 ln, err := net.Listen("tcp", ":0")
64 c.Assert(err, check.IsNil)
66 _, port, err := net.SplitHostPort(ln.Addr().String())
67 c.Assert(err, check.IsNil)
68 return "127.0.0." + id[3:] + ":" + port
71 for id := range s.testClusters {
76 ExternalURL: https://` + hostport[id] + `
83 Host: ` + hostport["z1111"] + `
91 Host: ` + hostport["z2222"] + `
100 Host: ` + hostport["z3333"] + `
113 Issuer: ` + s.oidcprovider.Issuer.URL + `
114 ClientID: ` + s.oidcprovider.ValidClientID + `
115 ClientSecret: ` + s.oidcprovider.ValidClientSecret + `
117 EmailVerifiedClaim: email_verified
118 AcceptAccessToken: true
119 AcceptAccessTokenScope: ""
128 loader := config.NewLoader(bytes.NewBufferString(yaml), ctxlog.TestLogger(c))
130 loader.SkipLegacy = true
131 loader.SkipAPICalls = true
132 cfg, err := loader.Load()
133 c.Assert(err, check.IsNil)
134 tc := boot.NewTestCluster(
135 filepath.Join(cwd, "..", ".."),
136 id, cfg, "127.0.0."+id[3:], c.Log)
137 tc.Super.NoWorkbench1 = true
138 tc.Super.NoWorkbench2 = true
140 s.testClusters[id] = tc
142 for _, tc := range s.testClusters {
144 c.Assert(ok, check.Equals, true)
148 func (s *IntegrationSuite) TearDownSuite(c *check.C) {
149 for _, c := range s.testClusters {
154 func (s *IntegrationSuite) TestDefaultStorageClassesOnCollections(c *check.C) {
155 conn := s.testClusters["z1111"].Conn()
156 rootctx, _, _ := s.testClusters["z1111"].RootClients()
157 userctx, _, kc, _ := s.testClusters["z1111"].UserClients(rootctx, c, conn, s.oidcprovider.AuthEmail, true)
158 c.Assert(len(kc.DefaultStorageClasses) > 0, check.Equals, true)
159 coll, err := conn.CollectionCreate(userctx, arvados.CreateOptions{})
160 c.Assert(err, check.IsNil)
161 c.Assert(coll.StorageClassesDesired, check.DeepEquals, kc.DefaultStorageClasses)
164 func (s *IntegrationSuite) TestGetCollectionByPDH(c *check.C) {
165 conn1 := s.testClusters["z1111"].Conn()
166 rootctx1, _, _ := s.testClusters["z1111"].RootClients()
167 conn3 := s.testClusters["z3333"].Conn()
168 userctx1, ac1, kc1, _ := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
170 // Create the collection to find its PDH (but don't save it
172 var coll1 arvados.Collection
173 fs1, err := coll1.FileSystem(ac1, kc1)
174 c.Assert(err, check.IsNil)
175 f, err := fs1.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
176 c.Assert(err, check.IsNil)
177 _, err = io.WriteString(f, "IntegrationSuite.TestGetCollectionByPDH")
178 c.Assert(err, check.IsNil)
180 c.Assert(err, check.IsNil)
181 mtxt, err := fs1.MarshalManifest(".")
182 c.Assert(err, check.IsNil)
183 pdh := arvados.PortableDataHash(mtxt)
185 // Looking up the PDH before saving returns 404 if cycle
186 // detection is working.
187 _, err = conn1.CollectionGet(userctx1, arvados.GetOptions{UUID: pdh})
188 c.Assert(err, check.ErrorMatches, `.*404 Not Found.*`)
190 // Save the collection on cluster z1111.
191 coll1, err = conn1.CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
192 "manifest_text": mtxt,
194 c.Assert(err, check.IsNil)
196 // Retrieve the collection from cluster z3333.
197 coll, err := conn3.CollectionGet(userctx1, arvados.GetOptions{UUID: pdh})
198 c.Check(err, check.IsNil)
199 c.Check(coll.PortableDataHash, check.Equals, pdh)
203 func (s *IntegrationSuite) TestRemoteUserAndTokenCacheRace(c *check.C) {
204 conn1 := s.testClusters["z1111"].Conn()
205 rootctx1, _, _ := s.testClusters["z1111"].RootClients()
206 rootctx2, _, _ := s.testClusters["z2222"].RootClients()
207 conn2 := s.testClusters["z2222"].Conn()
208 userctx1, _, _, _ := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, "user2@example.com", true)
210 var wg1, wg2 sync.WaitGroup
213 // Make concurrent requests to z2222 with a local token to make sure more
214 // than one worker is listening.
216 for i := 0; i < creqs; i++ {
221 _, err := conn2.UserGetCurrent(rootctx2, arvados.GetOptions{})
222 c.Check(err, check.IsNil, check.Commentf("warm up phase failed"))
228 // Real test pass -- use a new remote token than the one used in the warm-up
231 for i := 0; i < creqs; i++ {
236 // Retrieve the remote collection from cluster z2222.
237 _, err := conn2.UserGetCurrent(userctx1, arvados.GetOptions{})
238 c.Check(err, check.IsNil, check.Commentf("testing phase failed"))
245 func (s *IntegrationSuite) TestS3WithFederatedToken(c *check.C) {
246 if _, err := exec.LookPath("s3cmd"); err != nil {
247 c.Skip("s3cmd not in PATH")
251 testText := "IntegrationSuite.TestS3WithFederatedToken"
253 conn1 := s.testClusters["z1111"].Conn()
254 rootctx1, _, _ := s.testClusters["z1111"].RootClients()
255 userctx1, ac1, _, _ := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
256 conn3 := s.testClusters["z3333"].Conn()
258 createColl := func(clusterID string) arvados.Collection {
259 _, ac, kc := s.testClusters[clusterID].ClientsWithToken(ac1.AuthToken)
260 var coll arvados.Collection
261 fs, err := coll.FileSystem(ac, kc)
262 c.Assert(err, check.IsNil)
263 f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
264 c.Assert(err, check.IsNil)
265 _, err = io.WriteString(f, testText)
266 c.Assert(err, check.IsNil)
268 c.Assert(err, check.IsNil)
269 mtxt, err := fs.MarshalManifest(".")
270 c.Assert(err, check.IsNil)
271 coll, err = s.testClusters[clusterID].Conn().CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
272 "manifest_text": mtxt,
274 c.Assert(err, check.IsNil)
278 for _, trial := range []struct {
279 clusterID string // create the collection on this cluster (then use z3333 to access it)
282 // Try the hardest test first: z3333 hasn't seen
283 // z1111's token yet, and we're just passing the
284 // opaque secret part, so z3333 has to guess that it
286 {"z1111", strings.Split(ac1.AuthToken, "/")[2]},
287 {"z3333", strings.Split(ac1.AuthToken, "/")[2]},
288 {"z1111", strings.Replace(ac1.AuthToken, "/", "_", -1)},
289 {"z3333", strings.Replace(ac1.AuthToken, "/", "_", -1)},
291 c.Logf("================ %v", trial)
292 coll := createColl(trial.clusterID)
294 cfgjson, err := conn3.ConfigGet(userctx1)
295 c.Assert(err, check.IsNil)
296 var cluster arvados.Cluster
297 err = json.Unmarshal(cfgjson, &cluster)
298 c.Assert(err, check.IsNil)
300 c.Logf("TokenV2 is %s", ac1.AuthToken)
301 host := cluster.Services.WebDAV.ExternalURL.Host
303 "--ssl", "--no-check-certificate",
304 "--host=" + host, "--host-bucket=" + host,
305 "--access_key=" + trial.token, "--secret_key=" + trial.token,
307 buf, err := exec.Command("s3cmd", append(s3args, "ls", "s3://"+coll.UUID)...).CombinedOutput()
308 c.Check(err, check.IsNil)
309 c.Check(string(buf), check.Matches, `.* `+fmt.Sprintf("%d", len(testText))+` +s3://`+coll.UUID+`/test.txt\n`)
311 buf, _ = exec.Command("s3cmd", append(s3args, "get", "s3://"+coll.UUID+"/test.txt", c.MkDir()+"/tmpfile")...).CombinedOutput()
312 // Command fails because we don't return Etag header.
313 flen := strconv.Itoa(len(testText))
314 c.Check(string(buf), check.Matches, `(?ms).*`+flen+` (bytes in|of `+flen+`).*`)
318 func (s *IntegrationSuite) TestGetCollectionAsAnonymous(c *check.C) {
319 conn1 := s.testClusters["z1111"].Conn()
320 conn3 := s.testClusters["z3333"].Conn()
321 rootctx1, rootac1, rootkc1 := s.testClusters["z1111"].RootClients()
322 anonctx3, anonac3, _ := s.testClusters["z3333"].AnonymousClients()
324 // Make sure anonymous token was set
325 c.Assert(anonac3.AuthToken, check.Not(check.Equals), "")
327 // Create the collection to find its PDH (but don't save it
329 var coll1 arvados.Collection
330 fs1, err := coll1.FileSystem(rootac1, rootkc1)
331 c.Assert(err, check.IsNil)
332 f, err := fs1.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
333 c.Assert(err, check.IsNil)
334 _, err = io.WriteString(f, "IntegrationSuite.TestGetCollectionAsAnonymous")
335 c.Assert(err, check.IsNil)
337 c.Assert(err, check.IsNil)
338 mtxt, err := fs1.MarshalManifest(".")
339 c.Assert(err, check.IsNil)
340 pdh := arvados.PortableDataHash(mtxt)
342 // Save the collection on cluster z1111.
343 coll1, err = conn1.CollectionCreate(rootctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
344 "manifest_text": mtxt,
346 c.Assert(err, check.IsNil)
348 // Share it with the anonymous users group.
349 var outLink arvados.Link
350 err = rootac1.RequestAndDecode(&outLink, "POST", "/arvados/v1/links", nil,
351 map[string]interface{}{"link": map[string]interface{}{
352 "link_class": "permission",
354 "tail_uuid": "z1111-j7d0g-anonymouspublic",
355 "head_uuid": coll1.UUID,
358 c.Check(err, check.IsNil)
360 // Current user should be z3 anonymous user
361 outUser, err := anonac3.CurrentUser()
362 c.Check(err, check.IsNil)
363 c.Check(outUser.UUID, check.Equals, "z3333-tpzed-anonymouspublic")
365 // Get the token uuid
366 var outAuth arvados.APIClientAuthorization
367 err = anonac3.RequestAndDecode(&outAuth, "GET", "/arvados/v1/api_client_authorizations/current", nil, nil)
368 c.Check(err, check.IsNil)
370 // Make a v2 token of the z3 anonymous user, and use it on z1
371 _, anonac1, _ := s.testClusters["z1111"].ClientsWithToken(outAuth.TokenV2())
372 outUser2, err := anonac1.CurrentUser()
373 c.Check(err, check.IsNil)
374 // z3 anonymous user will be mapped to the z1 anonymous user
375 c.Check(outUser2.UUID, check.Equals, "z1111-tpzed-anonymouspublic")
377 // Retrieve the collection (which is on z1) using anonymous from cluster z3333.
378 coll, err := conn3.CollectionGet(anonctx3, arvados.GetOptions{UUID: coll1.UUID})
379 c.Check(err, check.IsNil)
380 c.Check(coll.PortableDataHash, check.Equals, pdh)
383 // Get a token from the login cluster (z1111), use it to submit a
384 // container request on z2222.
385 func (s *IntegrationSuite) TestCreateContainerRequestWithFedToken(c *check.C) {
386 conn1 := s.testClusters["z1111"].Conn()
387 rootctx1, _, _ := s.testClusters["z1111"].RootClients()
388 _, ac1, _, _ := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
390 // Use ac2 to get the discovery doc with a blank token, so the
391 // SDK doesn't magically pass the z1111 token to z2222 before
392 // we're ready to start our test.
393 _, ac2, _ := s.testClusters["z2222"].ClientsWithToken("")
394 var dd map[string]interface{}
395 err := ac2.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
396 c.Assert(err, check.IsNil)
403 cr arvados.ContainerRequest
405 json.NewEncoder(&body).Encode(map[string]interface{}{
406 "container_request": map[string]interface{}{
407 "command": []string{"echo"},
408 "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
413 ac2.AuthToken = ac1.AuthToken
415 c.Log("...post CR with good (but not yet cached) token")
416 cr = arvados.ContainerRequest{}
417 req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
418 c.Assert(err, check.IsNil)
419 req.Header.Set("Content-Type", "application/json")
420 err = ac2.DoAndDecode(&cr, req)
421 c.Assert(err, check.IsNil)
422 c.Logf("err == %#v", err)
424 c.Log("...get user with good token")
426 req, err = http.NewRequest("GET", "https://"+ac2.APIHost+"/arvados/v1/users/current", nil)
427 c.Assert(err, check.IsNil)
428 err = ac2.DoAndDecode(&u, req)
429 c.Check(err, check.IsNil)
430 c.Check(u.UUID, check.Matches, "z1111-tpzed-.*")
432 c.Log("...post CR with good cached token")
433 cr = arvados.ContainerRequest{}
434 req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
435 c.Assert(err, check.IsNil)
436 req.Header.Set("Content-Type", "application/json")
437 err = ac2.DoAndDecode(&cr, req)
438 c.Check(err, check.IsNil)
439 c.Check(cr.UUID, check.Matches, "z2222-.*")
441 c.Log("...post with good cached token ('OAuth2 ...')")
442 cr = arvados.ContainerRequest{}
443 req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
444 c.Assert(err, check.IsNil)
445 req.Header.Set("Content-Type", "application/json")
446 req.Header.Set("Authorization", "OAuth2 "+ac2.AuthToken)
447 resp, err = arvados.InsecureHTTPClient.Do(req)
448 c.Assert(err, check.IsNil)
449 err = json.NewDecoder(resp.Body).Decode(&cr)
450 c.Check(err, check.IsNil)
451 c.Check(cr.UUID, check.Matches, "z2222-.*")
454 func (s *IntegrationSuite) TestCreateContainerRequestWithBadToken(c *check.C) {
455 conn1 := s.testClusters["z1111"].Conn()
456 rootctx1, _, _ := s.testClusters["z1111"].RootClients()
457 _, ac1, _, au := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, "user@example.com", true)
464 {"Good token", ac1.AuthToken, http.StatusOK},
465 {"Bogus token", "abcdef", http.StatusUnauthorized},
466 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", http.StatusUnauthorized},
467 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", http.StatusUnauthorized},
470 body, _ := json.Marshal(map[string]interface{}{
471 "container_request": map[string]interface{}{
472 "command": []string{"echo"},
473 "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
479 for _, tt := range tests {
480 c.Log(c.TestName() + " " + tt.name)
481 ac1.AuthToken = tt.token
482 req, err := http.NewRequest("POST", "https://"+ac1.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body))
483 c.Assert(err, check.IsNil)
484 req.Header.Set("Content-Type", "application/json")
485 resp, err := ac1.Do(req)
486 c.Assert(err, check.IsNil)
487 c.Assert(resp.StatusCode, check.Equals, tt.expectedCode)
491 func (s *IntegrationSuite) TestRequestIDHeader(c *check.C) {
492 conn1 := s.testClusters["z1111"].Conn()
493 rootctx1, _, _ := s.testClusters["z1111"].RootClients()
494 userctx1, ac1, _, _ := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, "user@example.com", true)
496 coll, err := conn1.CollectionCreate(userctx1, arvados.CreateOptions{})
497 c.Check(err, check.IsNil)
498 specimen, err := conn1.SpecimenCreate(userctx1, arvados.CreateOptions{})
499 c.Check(err, check.IsNil)
506 {"/arvados/v1/collections", false, false},
507 {"/arvados/v1/collections", true, false},
508 {"/arvados/v1/nonexistant", false, true},
509 {"/arvados/v1/nonexistant", true, true},
510 {"/arvados/v1/collections/" + coll.UUID, false, false},
511 {"/arvados/v1/collections/" + coll.UUID, true, false},
512 {"/arvados/v1/specimens/" + specimen.UUID, false, false},
513 {"/arvados/v1/specimens/" + specimen.UUID, true, false},
514 // new code path (lib/controller/router etc) - single-cluster request
515 {"/arvados/v1/collections/z1111-4zz18-0123456789abcde", false, true},
516 {"/arvados/v1/collections/z1111-4zz18-0123456789abcde", true, true},
517 // new code path (lib/controller/router etc) - federated request
518 {"/arvados/v1/collections/z2222-4zz18-0123456789abcde", false, true},
519 {"/arvados/v1/collections/z2222-4zz18-0123456789abcde", true, true},
520 // old code path (proxyRailsAPI) - single-cluster request
521 {"/arvados/v1/specimens/z1111-j58dm-0123456789abcde", false, true},
522 {"/arvados/v1/specimens/z1111-j58dm-0123456789abcde", true, true},
523 // old code path (setupProxyRemoteCluster) - federated request
524 {"/arvados/v1/workflows/z2222-7fd4e-0123456789abcde", false, true},
525 {"/arvados/v1/workflows/z2222-7fd4e-0123456789abcde", true, true},
528 for _, tt := range tests {
529 c.Log(c.TestName() + " " + tt.path)
530 req, err := http.NewRequest("GET", "https://"+ac1.APIHost+tt.path, nil)
531 c.Assert(err, check.IsNil)
532 customReqId := "abcdeG"
533 if !tt.reqIdProvided {
534 c.Assert(req.Header.Get("X-Request-Id"), check.Equals, "")
536 req.Header.Set("X-Request-Id", customReqId)
538 resp, err := ac1.Do(req)
539 c.Assert(err, check.IsNil)
540 if tt.notFoundRequest {
541 c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
543 c.Check(resp.StatusCode, check.Equals, http.StatusOK)
545 respHdr := resp.Header.Get("X-Request-Id")
546 if tt.reqIdProvided {
547 c.Check(respHdr, check.Equals, customReqId)
549 c.Check(respHdr, check.Matches, `req-[0-9a-zA-Z]{20}`)
551 if tt.notFoundRequest {
552 var jresp httpserver.ErrorResponse
553 err := json.NewDecoder(resp.Body).Decode(&jresp)
554 c.Check(err, check.IsNil)
555 c.Assert(jresp.Errors, check.HasLen, 1)
556 c.Check(jresp.Errors[0], check.Matches, `.*\(`+respHdr+`\).*`)
561 // We test the direct access to the database
562 // normally an integration test would not have a database access, but in this case we need
563 // to test tokens that are secret, so there is no API response that will give them back
564 func (s *IntegrationSuite) dbConn(c *check.C, clusterID string) (*sql.DB, *sql.Conn) {
565 ctx := context.Background()
566 db, err := sql.Open("postgres", s.testClusters[clusterID].Super.Cluster().PostgreSQL.Connection.String())
567 c.Assert(err, check.IsNil)
569 conn, err := db.Conn(ctx)
570 c.Assert(err, check.IsNil)
572 rows, err := conn.ExecContext(ctx, `SELECT 1`)
573 c.Assert(err, check.IsNil)
574 n, err := rows.RowsAffected()
575 c.Assert(err, check.IsNil)
576 c.Assert(n, check.Equals, int64(1))
580 // TestRuntimeTokenInCR will test several different tokens in the runtime attribute
581 // and check the expected results accessing directly to the database if needed.
582 func (s *IntegrationSuite) TestRuntimeTokenInCR(c *check.C) {
583 db, dbconn := s.dbConn(c, "z1111")
586 conn1 := s.testClusters["z1111"].Conn()
587 rootctx1, _, _ := s.testClusters["z1111"].RootClients()
588 userctx1, ac1, _, au := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, "user@example.com", true)
593 expectAToGetAValidCR bool
594 expectedToken *string
596 {"Good token z1111 user", ac1.AuthToken, true, &ac1.AuthToken},
597 {"Bogus token", "abcdef", false, nil},
598 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", false, nil},
599 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", false, nil},
602 for _, tt := range tests {
603 c.Log(c.TestName() + " " + tt.name)
605 rq := map[string]interface{}{
606 "command": []string{"echo"},
607 "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
610 "runtime_token": tt.token,
612 cr, err := conn1.ContainerRequestCreate(userctx1, arvados.CreateOptions{Attrs: rq})
613 if tt.expectAToGetAValidCR {
614 c.Check(err, check.IsNil)
615 c.Check(cr, check.NotNil)
616 c.Check(cr.UUID, check.Not(check.Equals), "")
619 if tt.expectedToken == nil {
623 c.Logf("cr.UUID: %s", cr.UUID)
624 row := dbconn.QueryRowContext(rootctx1, `SELECT runtime_token from container_requests where uuid=$1`, cr.UUID)
625 c.Check(row, check.NotNil)
626 var token sql.NullString
628 if c.Check(token.Valid, check.Equals, true) {
629 c.Check(token.String, check.Equals, *tt.expectedToken)
634 // TestIntermediateCluster will send a container request to
635 // one cluster with another cluster as the destination
636 // and check the tokens are being handled properly
637 func (s *IntegrationSuite) TestIntermediateCluster(c *check.C) {
638 conn1 := s.testClusters["z1111"].Conn()
639 rootctx1, _, _ := s.testClusters["z1111"].RootClients()
640 uctx1, ac1, _, _ := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, "user@example.com", true)
645 expectedRuntimeToken string
646 expectedUUIDprefix string
648 {"Good token z1111 user sending a CR to z2222", ac1.AuthToken, "", "z2222-xvhdp-"},
651 for _, tt := range tests {
652 c.Log(c.TestName() + " " + tt.name)
653 rq := map[string]interface{}{
654 "command": []string{"echo"},
655 "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
658 "runtime_token": tt.token,
660 cr, err := conn1.ContainerRequestCreate(uctx1, arvados.CreateOptions{ClusterID: "z2222", Attrs: rq})
662 c.Check(err, check.IsNil)
663 c.Check(strings.HasPrefix(cr.UUID, tt.expectedUUIDprefix), check.Equals, true)
664 c.Check(cr.RuntimeToken, check.Equals, tt.expectedRuntimeToken)
669 func (s *IntegrationSuite) TestFederatedApiClientAuthHandling(c *check.C) {
670 rootctx1, rootclnt1, _ := s.testClusters["z1111"].RootClients()
671 conn1 := s.testClusters["z1111"].Conn()
673 // Make sure LoginCluster is properly configured
674 for _, cls := range []string{"z1111", "z3333"} {
676 s.testClusters[cls].Config.Clusters[cls].Login.LoginCluster,
677 check.Equals, "z1111",
678 check.Commentf("incorrect LoginCluster config on cluster %q", cls))
680 // Get user's UUID & attempt to create a token for it on the remote cluster
681 _, _, _, user := s.testClusters["z1111"].UserClients(rootctx1, c, conn1,
682 "user@example.com", true)
683 _, rootclnt3, _ := s.testClusters["z3333"].ClientsWithToken(rootclnt1.AuthToken)
684 var resp arvados.APIClientAuthorization
685 err := rootclnt3.RequestAndDecode(
686 &resp, "POST", "arvados/v1/api_client_authorizations", nil,
687 map[string]interface{}{
688 "api_client_authorization": map[string]string{
689 "owner_uuid": user.UUID,
693 c.Assert(err, check.IsNil)
694 c.Assert(resp.APIClientID, check.Not(check.Equals), 0)
695 newTok := resp.TokenV2()
696 c.Assert(newTok, check.Not(check.Equals), "")
698 // Confirm the token is from z1111
699 c.Assert(strings.HasPrefix(newTok, "v2/z1111-gj3su-"), check.Equals, true)
701 // Confirm the token works and is from the correct user
702 _, rootclnt3bis, _ := s.testClusters["z3333"].ClientsWithToken(newTok)
703 var curUser arvados.User
704 err = rootclnt3bis.RequestAndDecode(
705 &curUser, "GET", "arvados/v1/users/current", nil, nil,
707 c.Assert(err, check.IsNil)
708 c.Assert(curUser.UUID, check.Equals, user.UUID)
710 // Request the ApiClientAuthorization list using the new token
711 _, userClient, _ := s.testClusters["z3333"].ClientsWithToken(newTok)
712 var acaLst arvados.APIClientAuthorizationList
713 err = userClient.RequestAndDecode(
714 &acaLst, "GET", "arvados/v1/api_client_authorizations", nil, nil,
716 c.Assert(err, check.IsNil)
719 // Test for bug #18076
720 func (s *IntegrationSuite) TestStaleCachedUserRecord(c *check.C) {
721 rootctx1, _, _ := s.testClusters["z1111"].RootClients()
722 _, rootclnt3, _ := s.testClusters["z3333"].RootClients()
723 conn1 := s.testClusters["z1111"].Conn()
724 conn3 := s.testClusters["z3333"].Conn()
726 // Make sure LoginCluster is properly configured
727 for _, cls := range []string{"z1111", "z3333"} {
729 s.testClusters[cls].Config.Clusters[cls].Login.LoginCluster,
730 check.Equals, "z1111",
731 check.Commentf("incorrect LoginCluster config on cluster %q", cls))
734 for testCaseNr, testCase := range []struct {
738 {"User without local repository", false},
739 {"User with local repository", true},
741 c.Log(c.TestName() + " " + testCase.name)
742 // Create some users, request them on the federated cluster so they're cached.
743 var users []arvados.User
744 for userNr := 0; userNr < 2; userNr++ {
745 _, _, _, user := s.testClusters["z1111"].UserClients(
749 fmt.Sprintf("user%d%d@example.com", testCaseNr, userNr),
751 c.Assert(user.Username, check.Not(check.Equals), "")
752 users = append(users, user)
754 lst, err := conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
755 c.Assert(err, check.Equals, nil)
757 for _, fedUser := range lst.Items {
758 if fedUser.UUID == user.UUID {
759 c.Assert(fedUser.Username, check.Equals, user.Username)
764 c.Assert(userFound, check.Equals, true)
766 if testCase.withRepository {
768 err = rootclnt3.RequestAndDecode(
769 &repo, "POST", "arvados/v1/repositories", nil,
770 map[string]interface{}{
771 "repository": map[string]string{
772 "name": fmt.Sprintf("%s/test", user.Username),
773 "owner_uuid": user.UUID,
777 c.Assert(err, check.IsNil)
781 // Swap the usernames
782 _, err := conn1.UserUpdate(rootctx1, arvados.UpdateOptions{
784 Attrs: map[string]interface{}{
788 c.Assert(err, check.Equals, nil)
789 _, err = conn1.UserUpdate(rootctx1, arvados.UpdateOptions{
791 Attrs: map[string]interface{}{
792 "username": users[0].Username,
795 c.Assert(err, check.Equals, nil)
796 _, err = conn1.UserUpdate(rootctx1, arvados.UpdateOptions{
798 Attrs: map[string]interface{}{
799 "username": users[1].Username,
802 c.Assert(err, check.Equals, nil)
804 // Re-request the list on the federated cluster & check for updates
805 lst, err := conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
806 c.Assert(err, check.Equals, nil)
807 var user0Found, user1Found bool
808 for _, user := range lst.Items {
809 if user.UUID == users[0].UUID {
811 c.Assert(user.Username, check.Equals, users[1].Username)
812 } else if user.UUID == users[1].UUID {
814 c.Assert(user.Username, check.Equals, users[0].Username)
817 c.Assert(user0Found, check.Equals, true)
818 c.Assert(user1Found, check.Equals, true)
822 // Test for bug #16263
823 func (s *IntegrationSuite) TestListUsers(c *check.C) {
824 rootctx1, _, _ := s.testClusters["z1111"].RootClients()
825 conn1 := s.testClusters["z1111"].Conn()
826 conn3 := s.testClusters["z3333"].Conn()
827 userctx1, _, _, _ := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
829 // Make sure LoginCluster is properly configured
830 for cls := range s.testClusters {
832 s.testClusters[cls].Config.Clusters[cls].Login.LoginCluster,
833 check.Equals, "z1111",
834 check.Commentf("incorrect LoginCluster config on cluster %q", cls))
836 // Make sure z1111 has users with NULL usernames
837 lst, err := conn1.UserList(rootctx1, arvados.ListOptions{
838 Limit: math.MaxInt64, // check that large limit works (see #16263)
840 nullUsername := false
841 c.Assert(err, check.IsNil)
842 c.Assert(len(lst.Items), check.Not(check.Equals), 0)
843 for _, user := range lst.Items {
844 if user.Username == "" {
849 c.Assert(nullUsername, check.Equals, true)
851 user1, err := conn1.UserGetCurrent(userctx1, arvados.GetOptions{})
852 c.Assert(err, check.IsNil)
853 c.Check(user1.IsActive, check.Equals, true)
855 // Ask for the user list on z3333 using z1111's system root token
856 lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
857 c.Assert(err, check.IsNil)
859 for _, user := range lst.Items {
860 if user.UUID == user1.UUID {
861 c.Check(user.IsActive, check.Equals, true)
866 c.Check(found, check.Equals, true)
868 // Deactivate user acct on z1111
869 _, err = conn1.UserUnsetup(rootctx1, arvados.GetOptions{UUID: user1.UUID})
870 c.Assert(err, check.IsNil)
872 // Get user list from z3333, check the returned z1111 user is
874 lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
875 c.Assert(err, check.IsNil)
877 for _, user := range lst.Items {
878 if user.UUID == user1.UUID {
879 c.Check(user.IsActive, check.Equals, false)
884 c.Check(found, check.Equals, true)
886 // Deactivated user no longer has working token
887 user1, err = conn3.UserGetCurrent(userctx1, arvados.GetOptions{})
888 c.Assert(err, check.ErrorMatches, `.*401 Unauthorized.*`)
891 func (s *IntegrationSuite) TestSetupUserWithVM(c *check.C) {
892 conn1 := s.testClusters["z1111"].Conn()
893 conn3 := s.testClusters["z3333"].Conn()
894 rootctx1, rootac1, _ := s.testClusters["z1111"].RootClients()
896 // Create user on LoginCluster z1111
897 _, _, _, user := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
899 // Make a new root token (because rootClients() uses SystemRootToken)
900 var outAuth arvados.APIClientAuthorization
901 err := rootac1.RequestAndDecode(&outAuth, "POST", "/arvados/v1/api_client_authorizations", nil, nil)
902 c.Check(err, check.IsNil)
904 // Make a v2 root token to communicate with z3333
905 rootctx3, rootac3, _ := s.testClusters["z3333"].ClientsWithToken(outAuth.TokenV2())
907 // Create VM on z3333
908 var outVM arvados.VirtualMachine
909 err = rootac3.RequestAndDecode(&outVM, "POST", "/arvados/v1/virtual_machines", nil,
910 map[string]interface{}{"virtual_machine": map[string]interface{}{
911 "hostname": "example",
914 c.Check(outVM.UUID[0:5], check.Equals, "z3333")
915 c.Check(err, check.IsNil)
917 // Make sure z3333 user list is up to date
918 _, err = conn3.UserList(rootctx3, arvados.ListOptions{Limit: 1000})
919 c.Check(err, check.IsNil)
921 // Try to set up user on z3333 with the VM
922 _, err = conn3.UserSetup(rootctx3, arvados.UserSetupOptions{UUID: user.UUID, VMUUID: outVM.UUID})
923 c.Check(err, check.IsNil)
925 var outLinks arvados.LinkList
926 err = rootac3.RequestAndDecode(&outLinks, "GET", "/arvados/v1/links", nil,
929 Filters: []arvados.Filter{
943 Operand: "can_login",
948 Operand: "permission",
950 c.Check(err, check.IsNil)
952 c.Check(len(outLinks.Items), check.Equals, 1)
955 func (s *IntegrationSuite) TestOIDCAccessTokenAuth(c *check.C) {
956 conn1 := s.testClusters["z1111"].Conn()
957 rootctx1, _, _ := s.testClusters["z1111"].RootClients()
958 s.testClusters["z1111"].UserClients(rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
960 accesstoken := s.oidcprovider.ValidAccessToken()
962 for _, clusterID := range []string{"z1111", "z2222"} {
964 var coll arvados.Collection
966 // Write some file data and create a collection
968 c.Logf("save collection to %s", clusterID)
970 conn := s.testClusters[clusterID].Conn()
971 ctx, ac, kc := s.testClusters[clusterID].ClientsWithToken(accesstoken)
973 fs, err := coll.FileSystem(ac, kc)
974 c.Assert(err, check.IsNil)
975 f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
976 c.Assert(err, check.IsNil)
977 _, err = io.WriteString(f, "IntegrationSuite.TestOIDCAccessTokenAuth")
978 c.Assert(err, check.IsNil)
980 c.Assert(err, check.IsNil)
981 mtxt, err := fs.MarshalManifest(".")
982 c.Assert(err, check.IsNil)
983 coll, err = conn.CollectionCreate(ctx, arvados.CreateOptions{Attrs: map[string]interface{}{
984 "manifest_text": mtxt,
986 c.Assert(err, check.IsNil)
989 // Read the collection & file data -- both from the
990 // cluster where it was created, and from the other
992 for _, readClusterID := range []string{"z1111", "z2222", "z3333"} {
993 c.Logf("retrieve %s from %s", coll.UUID, readClusterID)
995 conn := s.testClusters[readClusterID].Conn()
996 ctx, ac, kc := s.testClusters[readClusterID].ClientsWithToken(accesstoken)
998 user, err := conn.UserGetCurrent(ctx, arvados.GetOptions{})
999 c.Assert(err, check.IsNil)
1000 c.Check(user.FullName, check.Equals, "Example User")
1001 readcoll, err := conn.CollectionGet(ctx, arvados.GetOptions{UUID: coll.UUID})
1002 c.Assert(err, check.IsNil)
1003 c.Check(readcoll.ManifestText, check.Not(check.Equals), "")
1004 fs, err := readcoll.FileSystem(ac, kc)
1005 c.Assert(err, check.IsNil)
1006 f, err := fs.Open("test.txt")
1007 c.Assert(err, check.IsNil)
1008 buf, err := ioutil.ReadAll(f)
1009 c.Assert(err, check.IsNil)
1010 c.Check(buf, check.DeepEquals, []byte("IntegrationSuite.TestOIDCAccessTokenAuth"))
1015 // z3333 should not forward a locally-issued container runtime token,
1016 // associated with a z1111 user, to its login cluster z1111. z1111
1017 // would only call back to z3333 and then reject the response because
1018 // the user ID does not match the token prefix. See
1019 // dev.arvados.org/issues/18346
1020 func (s *IntegrationSuite) TestForwardRuntimeTokenToLoginCluster(c *check.C) {
1021 db3, db3conn := s.dbConn(c, "z3333")
1023 defer db3conn.Close()
1024 rootctx1, _, _ := s.testClusters["z1111"].RootClients()
1025 rootctx3, _, _ := s.testClusters["z3333"].RootClients()
1026 conn1 := s.testClusters["z1111"].Conn()
1027 conn3 := s.testClusters["z3333"].Conn()
1028 userctx1, _, _, _ := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, "user@example.com", true)
1030 user1, err := conn1.UserGetCurrent(userctx1, arvados.GetOptions{})
1031 c.Assert(err, check.IsNil)
1032 c.Logf("user1 %+v", user1)
1034 imageColl, err := conn3.CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
1035 "manifest_text": ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.tar\n",
1037 c.Assert(err, check.IsNil)
1038 c.Logf("imageColl %+v", imageColl)
1040 cr, err := conn3.ContainerRequestCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
1041 "state": "Committed",
1042 "command": []string{"echo"},
1043 "container_image": imageColl.PortableDataHash,
1047 "runtime_constraints": arvados.RuntimeConstraints{
1052 c.Assert(err, check.IsNil)
1053 c.Logf("container request %+v", cr)
1054 ctr, err := conn3.ContainerLock(rootctx3, arvados.GetOptions{UUID: cr.ContainerUUID})
1055 c.Assert(err, check.IsNil)
1056 c.Logf("container %+v", ctr)
1058 // We could use conn3.ContainerAuth() here, but that API
1059 // hasn't been added to sdk/go/arvados/api.go yet.
1060 row := db3conn.QueryRowContext(context.Background(), `SELECT api_token from api_client_authorizations where uuid=$1`, ctr.AuthUUID)
1061 c.Check(row, check.NotNil)
1062 var val sql.NullString
1064 c.Assert(val.Valid, check.Equals, true)
1065 runtimeToken := "v2/" + ctr.AuthUUID + "/" + val.String
1066 ctrctx, _, _ := s.testClusters["z3333"].ClientsWithToken(runtimeToken)
1067 c.Logf("container runtime token %+v", runtimeToken)
1069 _, err = conn3.UserGet(ctrctx, arvados.GetOptions{UUID: user1.UUID})
1070 c.Assert(err, check.NotNil)
1071 c.Check(err, check.ErrorMatches, `request failed: .* 401 Unauthorized: cannot use a locally issued token to forward a request to our login cluster \(z1111\)`)
1072 c.Check(err, check.Not(check.ErrorMatches), `(?ms).*127\.0\.0\.11.*`)