1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
26 "git.arvados.org/arvados.git/lib/boot"
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 super *boot.Supervisor
38 oidcprovider *arvadostest.OIDCProvider
41 func (s *IntegrationSuite) SetUpSuite(c *check.C) {
42 s.oidcprovider = arvadostest.NewOIDCProvider(c)
43 s.oidcprovider.AuthEmail = "user@example.com"
44 s.oidcprovider.AuthEmailVerified = true
45 s.oidcprovider.AuthName = "Example User"
46 s.oidcprovider.ValidClientID = "clientid"
47 s.oidcprovider.ValidClientSecret = "clientsecret"
49 hostport := map[string]string{}
50 for _, id := range []string{"z1111", "z2222", "z3333"} {
51 hostport[id] = func() string {
52 // TODO: Instead of expecting random ports on
53 // 127.0.0.11, 22, 33 to be race-safe, try
54 // different 127.x.y.z until finding one that
56 ln, err := net.Listen("tcp", ":0")
57 c.Assert(err, check.IsNil)
59 _, port, err := net.SplitHostPort(ln.Addr().String())
60 c.Assert(err, check.IsNil)
61 return "127.0.0." + id[3:] + ":" + port
65 for id := range hostport {
70 ExternalURL: https://` + hostport[id] + `
85 RuntimeEngine: singularity
88 Host: ` + hostport["z1111"] + `
96 Host: ` + hostport["z2222"] + `
105 Host: ` + hostport["z3333"] + `
118 Issuer: ` + s.oidcprovider.Issuer.URL + `
119 ClientID: ` + s.oidcprovider.ValidClientID + `
120 ClientSecret: ` + s.oidcprovider.ValidClientSecret + `
122 EmailVerifiedClaim: email_verified
123 AcceptAccessToken: true
124 AcceptAccessTokenScope: ""
133 s.super = &boot.Supervisor{
136 Stderr: ctxlog.LogWriter(c.Log),
139 OwnTemporaryDatabase: true,
142 // Give up if startup takes longer than 3m
143 timeout := time.AfterFunc(3*time.Minute, s.super.Stop)
145 s.super.Start(context.Background())
146 ok := s.super.WaitReady()
147 c.Assert(ok, check.Equals, true)
150 func (s *IntegrationSuite) TearDownSuite(c *check.C) {
157 func (s *IntegrationSuite) TestDefaultStorageClassesOnCollections(c *check.C) {
158 conn := s.super.Conn("z1111")
159 rootctx, _, _ := s.super.RootClients("z1111")
160 userctx, _, kc, _ := s.super.UserClients("z1111", rootctx, c, conn, s.oidcprovider.AuthEmail, true)
161 c.Assert(len(kc.DefaultStorageClasses) > 0, check.Equals, true)
162 coll, err := conn.CollectionCreate(userctx, arvados.CreateOptions{})
163 c.Assert(err, check.IsNil)
164 c.Assert(coll.StorageClassesDesired, check.DeepEquals, kc.DefaultStorageClasses)
167 func (s *IntegrationSuite) TestGetCollectionByPDH(c *check.C) {
168 conn1 := s.super.Conn("z1111")
169 rootctx1, _, _ := s.super.RootClients("z1111")
170 conn3 := s.super.Conn("z3333")
171 userctx1, ac1, kc1, _ := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
173 // Create the collection to find its PDH (but don't save it
175 var coll1 arvados.Collection
176 fs1, err := coll1.FileSystem(ac1, kc1)
177 c.Assert(err, check.IsNil)
178 f, err := fs1.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
179 c.Assert(err, check.IsNil)
180 _, err = io.WriteString(f, "IntegrationSuite.TestGetCollectionByPDH")
181 c.Assert(err, check.IsNil)
183 c.Assert(err, check.IsNil)
184 mtxt, err := fs1.MarshalManifest(".")
185 c.Assert(err, check.IsNil)
186 pdh := arvados.PortableDataHash(mtxt)
188 // Looking up the PDH before saving returns 404 if cycle
189 // detection is working.
190 _, err = conn1.CollectionGet(userctx1, arvados.GetOptions{UUID: pdh})
191 c.Assert(err, check.ErrorMatches, `.*404 Not Found.*`)
193 // Save the collection on cluster z1111.
194 coll1, err = conn1.CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
195 "manifest_text": mtxt,
197 c.Assert(err, check.IsNil)
199 // Retrieve the collection from cluster z3333.
200 coll, err := conn3.CollectionGet(userctx1, arvados.GetOptions{UUID: pdh})
201 c.Check(err, check.IsNil)
202 c.Check(coll.PortableDataHash, check.Equals, pdh)
206 func (s *IntegrationSuite) TestRemoteUserAndTokenCacheRace(c *check.C) {
207 conn1 := s.super.Conn("z1111")
208 rootctx1, _, _ := s.super.RootClients("z1111")
209 rootctx2, _, _ := s.super.RootClients("z2222")
210 conn2 := s.super.Conn("z2222")
211 userctx1, _, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, "user2@example.com", true)
213 var wg1, wg2 sync.WaitGroup
216 // Make concurrent requests to z2222 with a local token to make sure more
217 // than one worker is listening.
219 for i := 0; i < creqs; i++ {
224 _, err := conn2.UserGetCurrent(rootctx2, arvados.GetOptions{})
225 c.Check(err, check.IsNil, check.Commentf("warm up phase failed"))
231 // Real test pass -- use a new remote token than the one used in the warm-up
234 for i := 0; i < creqs; i++ {
239 // Retrieve the remote collection from cluster z2222.
240 _, err := conn2.UserGetCurrent(userctx1, arvados.GetOptions{})
241 c.Check(err, check.IsNil, check.Commentf("testing phase failed"))
248 func (s *IntegrationSuite) TestS3WithFederatedToken(c *check.C) {
249 if _, err := exec.LookPath("s3cmd"); err != nil {
250 c.Skip("s3cmd not in PATH")
254 testText := "IntegrationSuite.TestS3WithFederatedToken"
256 conn1 := s.super.Conn("z1111")
257 rootctx1, _, _ := s.super.RootClients("z1111")
258 userctx1, ac1, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
259 conn3 := s.super.Conn("z3333")
261 createColl := func(clusterID string) arvados.Collection {
262 _, ac, kc := s.super.ClientsWithToken(clusterID, ac1.AuthToken)
263 var coll arvados.Collection
264 fs, err := coll.FileSystem(ac, kc)
265 c.Assert(err, check.IsNil)
266 f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
267 c.Assert(err, check.IsNil)
268 _, err = io.WriteString(f, testText)
269 c.Assert(err, check.IsNil)
271 c.Assert(err, check.IsNil)
272 mtxt, err := fs.MarshalManifest(".")
273 c.Assert(err, check.IsNil)
274 coll, err = s.super.Conn(clusterID).CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
275 "manifest_text": mtxt,
277 c.Assert(err, check.IsNil)
281 for _, trial := range []struct {
282 clusterID string // create the collection on this cluster (then use z3333 to access it)
285 // Try the hardest test first: z3333 hasn't seen
286 // z1111's token yet, and we're just passing the
287 // opaque secret part, so z3333 has to guess that it
289 {"z1111", strings.Split(ac1.AuthToken, "/")[2]},
290 {"z3333", strings.Split(ac1.AuthToken, "/")[2]},
291 {"z1111", strings.Replace(ac1.AuthToken, "/", "_", -1)},
292 {"z3333", strings.Replace(ac1.AuthToken, "/", "_", -1)},
294 c.Logf("================ %v", trial)
295 coll := createColl(trial.clusterID)
297 cfgjson, err := conn3.ConfigGet(userctx1)
298 c.Assert(err, check.IsNil)
299 var cluster arvados.Cluster
300 err = json.Unmarshal(cfgjson, &cluster)
301 c.Assert(err, check.IsNil)
303 c.Logf("TokenV2 is %s", ac1.AuthToken)
304 host := cluster.Services.WebDAV.ExternalURL.Host
306 "--ssl", "--no-check-certificate",
307 "--host=" + host, "--host-bucket=" + host,
308 "--access_key=" + trial.token, "--secret_key=" + trial.token,
310 buf, err := exec.Command("s3cmd", append(s3args, "ls", "s3://"+coll.UUID)...).CombinedOutput()
311 c.Check(err, check.IsNil)
312 c.Check(string(buf), check.Matches, `.* `+fmt.Sprintf("%d", len(testText))+` +s3://`+coll.UUID+`/test.txt\n`)
314 buf, _ = exec.Command("s3cmd", append(s3args, "get", "s3://"+coll.UUID+"/test.txt", c.MkDir()+"/tmpfile")...).CombinedOutput()
315 // Command fails because we don't return Etag header.
316 flen := strconv.Itoa(len(testText))
317 c.Check(string(buf), check.Matches, `(?ms).*`+flen+` (bytes in|of `+flen+`).*`)
321 func (s *IntegrationSuite) TestGetCollectionAsAnonymous(c *check.C) {
322 conn1 := s.super.Conn("z1111")
323 conn3 := s.super.Conn("z3333")
324 rootctx1, rootac1, rootkc1 := s.super.RootClients("z1111")
325 anonctx3, anonac3, _ := s.super.AnonymousClients("z3333")
327 // Make sure anonymous token was set
328 c.Assert(anonac3.AuthToken, check.Not(check.Equals), "")
330 // Create the collection to find its PDH (but don't save it
332 var coll1 arvados.Collection
333 fs1, err := coll1.FileSystem(rootac1, rootkc1)
334 c.Assert(err, check.IsNil)
335 f, err := fs1.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
336 c.Assert(err, check.IsNil)
337 _, err = io.WriteString(f, "IntegrationSuite.TestGetCollectionAsAnonymous")
338 c.Assert(err, check.IsNil)
340 c.Assert(err, check.IsNil)
341 mtxt, err := fs1.MarshalManifest(".")
342 c.Assert(err, check.IsNil)
343 pdh := arvados.PortableDataHash(mtxt)
345 // Save the collection on cluster z1111.
346 coll1, err = conn1.CollectionCreate(rootctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
347 "manifest_text": mtxt,
349 c.Assert(err, check.IsNil)
351 // Share it with the anonymous users group.
352 var outLink arvados.Link
353 err = rootac1.RequestAndDecode(&outLink, "POST", "/arvados/v1/links", nil,
354 map[string]interface{}{"link": map[string]interface{}{
355 "link_class": "permission",
357 "tail_uuid": "z1111-j7d0g-anonymouspublic",
358 "head_uuid": coll1.UUID,
361 c.Check(err, check.IsNil)
363 // Current user should be z3 anonymous user
364 outUser, err := anonac3.CurrentUser()
365 c.Check(err, check.IsNil)
366 c.Check(outUser.UUID, check.Equals, "z3333-tpzed-anonymouspublic")
368 // Get the token uuid
369 var outAuth arvados.APIClientAuthorization
370 err = anonac3.RequestAndDecode(&outAuth, "GET", "/arvados/v1/api_client_authorizations/current", nil, nil)
371 c.Check(err, check.IsNil)
373 // Make a v2 token of the z3 anonymous user, and use it on z1
374 _, anonac1, _ := s.super.ClientsWithToken("z1111", outAuth.TokenV2())
375 outUser2, err := anonac1.CurrentUser()
376 c.Check(err, check.IsNil)
377 // z3 anonymous user will be mapped to the z1 anonymous user
378 c.Check(outUser2.UUID, check.Equals, "z1111-tpzed-anonymouspublic")
380 // Retrieve the collection (which is on z1) using anonymous from cluster z3333.
381 coll, err := conn3.CollectionGet(anonctx3, arvados.GetOptions{UUID: coll1.UUID})
382 c.Check(err, check.IsNil)
383 c.Check(coll.PortableDataHash, check.Equals, pdh)
386 // z3333 should forward the locally-issued anonymous user token to its login
387 // cluster z1111. That is no problem because the login cluster controller will
388 // map any anonymous user token to its local anonymous user.
390 // This needs to work because wb1 has a tendency to slap the local anonymous
391 // user token on every request as a reader_token, which gets folded into the
392 // request token list controller.
394 // Use a z1111 user token and the anonymous token from z3333 passed in as a
395 // reader_token to do a request on z3333, asking for the z1111 anonymous user
396 // object. The request will be forwarded to the z1111 cluster. The presence of
397 // the z3333 anonymous user token should not prohibit the request from being
399 func (s *IntegrationSuite) TestForwardAnonymousTokenToLoginCluster(c *check.C) {
400 conn1 := s.super.Conn("z1111")
402 rootctx1, _, _ := s.super.RootClients("z1111")
403 _, anonac3, _ := s.super.AnonymousClients("z3333")
405 // Make a user connection to z3333 (using a z1111 user, because that's the login cluster)
406 _, userac1, _, _ := s.super.UserClients("z3333", rootctx1, c, conn1, "user@example.com", true)
408 // Get the anonymous user token for z3333
409 var anon3Auth arvados.APIClientAuthorization
410 err := anonac3.RequestAndDecode(&anon3Auth, "GET", "/arvados/v1/api_client_authorizations/current", nil, nil)
411 c.Check(err, check.IsNil)
413 var userList arvados.UserList
414 where := make(map[string]string)
415 where["uuid"] = "z1111-tpzed-anonymouspublic"
416 err = userac1.RequestAndDecode(&userList, "GET", "/arvados/v1/users", nil,
417 map[string]interface{}{
418 "reader_tokens": []string{anon3Auth.TokenV2()},
422 // The local z3333 anonymous token must be allowed to be forwarded to the login cluster
423 c.Check(err, check.IsNil)
425 userac1.AuthToken = "v2/z1111-gj3su-asdfasdfasdfasd/this-token-does-not-validate-so-anonymous-token-will-be-used-instead"
426 err = userac1.RequestAndDecode(&userList, "GET", "/arvados/v1/users", nil,
427 map[string]interface{}{
428 "reader_tokens": []string{anon3Auth.TokenV2()},
432 c.Check(err, check.IsNil)
435 // Get a token from the login cluster (z1111), use it to submit a
436 // container request on z2222.
437 func (s *IntegrationSuite) TestCreateContainerRequestWithFedToken(c *check.C) {
438 conn1 := s.super.Conn("z1111")
439 rootctx1, _, _ := s.super.RootClients("z1111")
440 _, ac1, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
442 // Use ac2 to get the discovery doc with a blank token, so the
443 // SDK doesn't magically pass the z1111 token to z2222 before
444 // we're ready to start our test.
445 _, ac2, _ := s.super.ClientsWithToken("z2222", "")
446 var dd map[string]interface{}
447 err := ac2.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
448 c.Assert(err, check.IsNil)
455 cr arvados.ContainerRequest
457 json.NewEncoder(&body).Encode(map[string]interface{}{
458 "container_request": map[string]interface{}{
459 "command": []string{"echo"},
460 "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
465 ac2.AuthToken = ac1.AuthToken
467 c.Log("...post CR with good (but not yet cached) token")
468 cr = arvados.ContainerRequest{}
469 req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
470 c.Assert(err, check.IsNil)
471 req.Header.Set("Content-Type", "application/json")
472 err = ac2.DoAndDecode(&cr, req)
473 c.Assert(err, check.IsNil)
474 c.Logf("err == %#v", err)
476 c.Log("...get user with good token")
478 req, err = http.NewRequest("GET", "https://"+ac2.APIHost+"/arvados/v1/users/current", nil)
479 c.Assert(err, check.IsNil)
480 err = ac2.DoAndDecode(&u, req)
481 c.Check(err, check.IsNil)
482 c.Check(u.UUID, check.Matches, "z1111-tpzed-.*")
484 c.Log("...post CR with good cached token")
485 cr = arvados.ContainerRequest{}
486 req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
487 c.Assert(err, check.IsNil)
488 req.Header.Set("Content-Type", "application/json")
489 err = ac2.DoAndDecode(&cr, req)
490 c.Check(err, check.IsNil)
491 c.Check(cr.UUID, check.Matches, "z2222-.*")
493 c.Log("...post with good cached token ('OAuth2 ...')")
494 cr = arvados.ContainerRequest{}
495 req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
496 c.Assert(err, check.IsNil)
497 req.Header.Set("Content-Type", "application/json")
498 req.Header.Set("Authorization", "OAuth2 "+ac2.AuthToken)
499 resp, err = arvados.InsecureHTTPClient.Do(req)
500 c.Assert(err, check.IsNil)
501 err = json.NewDecoder(resp.Body).Decode(&cr)
502 c.Check(err, check.IsNil)
503 c.Check(cr.UUID, check.Matches, "z2222-.*")
506 func (s *IntegrationSuite) TestCreateContainerRequestWithBadToken(c *check.C) {
507 conn1 := s.super.Conn("z1111")
508 rootctx1, _, _ := s.super.RootClients("z1111")
509 _, ac1, _, au := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
516 {"Good token", ac1.AuthToken, http.StatusOK},
517 {"Bogus token", "abcdef", http.StatusUnauthorized},
518 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", http.StatusUnauthorized},
519 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", http.StatusUnauthorized},
522 body, _ := json.Marshal(map[string]interface{}{
523 "container_request": map[string]interface{}{
524 "command": []string{"echo"},
525 "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
531 for _, tt := range tests {
532 c.Log(c.TestName() + " " + tt.name)
533 ac1.AuthToken = tt.token
534 req, err := http.NewRequest("POST", "https://"+ac1.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body))
535 c.Assert(err, check.IsNil)
536 req.Header.Set("Content-Type", "application/json")
537 resp, err := ac1.Do(req)
538 c.Assert(err, check.IsNil)
539 c.Assert(resp.StatusCode, check.Equals, tt.expectedCode)
543 func (s *IntegrationSuite) TestRequestIDHeader(c *check.C) {
544 conn1 := s.super.Conn("z1111")
545 rootctx1, _, _ := s.super.RootClients("z1111")
546 userctx1, ac1, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
548 coll, err := conn1.CollectionCreate(userctx1, arvados.CreateOptions{})
549 c.Check(err, check.IsNil)
550 specimen, err := conn1.SpecimenCreate(userctx1, arvados.CreateOptions{})
551 c.Check(err, check.IsNil)
558 {"/arvados/v1/collections", false, false},
559 {"/arvados/v1/collections", true, false},
560 {"/arvados/v1/nonexistant", false, true},
561 {"/arvados/v1/nonexistant", true, true},
562 {"/arvados/v1/collections/" + coll.UUID, false, false},
563 {"/arvados/v1/collections/" + coll.UUID, true, false},
564 {"/arvados/v1/specimens/" + specimen.UUID, false, false},
565 {"/arvados/v1/specimens/" + specimen.UUID, true, false},
566 // new code path (lib/controller/router etc) - single-cluster request
567 {"/arvados/v1/collections/z1111-4zz18-0123456789abcde", false, true},
568 {"/arvados/v1/collections/z1111-4zz18-0123456789abcde", true, true},
569 // new code path (lib/controller/router etc) - federated request
570 {"/arvados/v1/collections/z2222-4zz18-0123456789abcde", false, true},
571 {"/arvados/v1/collections/z2222-4zz18-0123456789abcde", true, true},
572 // old code path (proxyRailsAPI) - single-cluster request
573 {"/arvados/v1/specimens/z1111-j58dm-0123456789abcde", false, true},
574 {"/arvados/v1/specimens/z1111-j58dm-0123456789abcde", true, true},
575 // old code path (setupProxyRemoteCluster) - federated request
576 {"/arvados/v1/workflows/z2222-7fd4e-0123456789abcde", false, true},
577 {"/arvados/v1/workflows/z2222-7fd4e-0123456789abcde", true, true},
580 for _, tt := range tests {
581 c.Log(c.TestName() + " " + tt.path)
582 req, err := http.NewRequest("GET", "https://"+ac1.APIHost+tt.path, nil)
583 c.Assert(err, check.IsNil)
584 customReqId := "abcdeG"
585 if !tt.reqIdProvided {
586 c.Assert(req.Header.Get("X-Request-Id"), check.Equals, "")
588 req.Header.Set("X-Request-Id", customReqId)
590 resp, err := ac1.Do(req)
591 c.Assert(err, check.IsNil)
592 if tt.notFoundRequest {
593 c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
595 c.Check(resp.StatusCode, check.Equals, http.StatusOK)
597 respHdr := resp.Header.Get("X-Request-Id")
598 if tt.reqIdProvided {
599 c.Check(respHdr, check.Equals, customReqId)
601 c.Check(respHdr, check.Matches, `req-[0-9a-zA-Z]{20}`)
603 if tt.notFoundRequest {
604 var jresp httpserver.ErrorResponse
605 err := json.NewDecoder(resp.Body).Decode(&jresp)
606 c.Check(err, check.IsNil)
607 c.Assert(jresp.Errors, check.HasLen, 1)
608 c.Check(jresp.Errors[0], check.Matches, `.*\(`+respHdr+`\).*`)
613 // We test the direct access to the database
614 // normally an integration test would not have a database access, but in this case we need
615 // to test tokens that are secret, so there is no API response that will give them back
616 func (s *IntegrationSuite) dbConn(c *check.C, clusterID string) (*sql.DB, *sql.Conn) {
617 ctx := context.Background()
618 db, err := sql.Open("postgres", s.super.Cluster(clusterID).PostgreSQL.Connection.String())
619 c.Assert(err, check.IsNil)
621 conn, err := db.Conn(ctx)
622 c.Assert(err, check.IsNil)
624 rows, err := conn.ExecContext(ctx, `SELECT 1`)
625 c.Assert(err, check.IsNil)
626 n, err := rows.RowsAffected()
627 c.Assert(err, check.IsNil)
628 c.Assert(n, check.Equals, int64(1))
632 // TestRuntimeTokenInCR will test several different tokens in the runtime attribute
633 // and check the expected results accessing directly to the database if needed.
634 func (s *IntegrationSuite) TestRuntimeTokenInCR(c *check.C) {
635 db, dbconn := s.dbConn(c, "z1111")
638 conn1 := s.super.Conn("z1111")
639 rootctx1, _, _ := s.super.RootClients("z1111")
640 userctx1, ac1, _, au := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
645 expectAToGetAValidCR bool
646 expectedToken *string
648 {"Good token z1111 user", ac1.AuthToken, true, &ac1.AuthToken},
649 {"Bogus token", "abcdef", false, nil},
650 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", false, nil},
651 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", false, nil},
654 for _, tt := range tests {
655 c.Log(c.TestName() + " " + tt.name)
657 rq := map[string]interface{}{
658 "command": []string{"echo"},
659 "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
662 "runtime_token": tt.token,
664 cr, err := conn1.ContainerRequestCreate(userctx1, arvados.CreateOptions{Attrs: rq})
665 if tt.expectAToGetAValidCR {
666 c.Check(err, check.IsNil)
667 c.Check(cr, check.NotNil)
668 c.Check(cr.UUID, check.Not(check.Equals), "")
671 if tt.expectedToken == nil {
675 c.Logf("cr.UUID: %s", cr.UUID)
676 row := dbconn.QueryRowContext(rootctx1, `SELECT runtime_token from container_requests where uuid=$1`, cr.UUID)
677 c.Check(row, check.NotNil)
678 var token sql.NullString
680 if c.Check(token.Valid, check.Equals, true) {
681 c.Check(token.String, check.Equals, *tt.expectedToken)
686 // TestIntermediateCluster will send a container request to
687 // one cluster with another cluster as the destination
688 // and check the tokens are being handled properly
689 func (s *IntegrationSuite) TestIntermediateCluster(c *check.C) {
690 conn1 := s.super.Conn("z1111")
691 rootctx1, _, _ := s.super.RootClients("z1111")
692 uctx1, ac1, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
697 expectedRuntimeToken string
698 expectedUUIDprefix string
700 {"Good token z1111 user sending a CR to z2222", ac1.AuthToken, "", "z2222-xvhdp-"},
703 for _, tt := range tests {
704 c.Log(c.TestName() + " " + tt.name)
705 rq := map[string]interface{}{
706 "command": []string{"echo"},
707 "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
710 "runtime_token": tt.token,
712 cr, err := conn1.ContainerRequestCreate(uctx1, arvados.CreateOptions{ClusterID: "z2222", Attrs: rq})
714 c.Check(err, check.IsNil)
715 c.Check(strings.HasPrefix(cr.UUID, tt.expectedUUIDprefix), check.Equals, true)
716 c.Check(cr.RuntimeToken, check.Equals, tt.expectedRuntimeToken)
721 func (s *IntegrationSuite) TestFederatedApiClientAuthHandling(c *check.C) {
722 rootctx1, rootclnt1, _ := s.super.RootClients("z1111")
723 conn1 := s.super.Conn("z1111")
725 // Make sure LoginCluster is properly configured
726 for _, cls := range []string{"z1111", "z3333"} {
728 s.super.Cluster(cls).Login.LoginCluster,
729 check.Equals, "z1111",
730 check.Commentf("incorrect LoginCluster config on cluster %q", cls))
732 // Get user's UUID & attempt to create a token for it on the remote cluster
733 _, _, _, user := s.super.UserClients("z1111", rootctx1, c, conn1,
734 "user@example.com", true)
735 _, rootclnt3, _ := s.super.ClientsWithToken("z3333", rootclnt1.AuthToken)
736 var resp arvados.APIClientAuthorization
737 err := rootclnt3.RequestAndDecode(
738 &resp, "POST", "arvados/v1/api_client_authorizations", nil,
739 map[string]interface{}{
740 "api_client_authorization": map[string]string{
741 "owner_uuid": user.UUID,
745 c.Assert(err, check.IsNil)
746 c.Assert(resp.APIClientID, check.Not(check.Equals), 0)
747 newTok := resp.TokenV2()
748 c.Assert(newTok, check.Not(check.Equals), "")
750 // Confirm the token is from z1111
751 c.Assert(strings.HasPrefix(newTok, "v2/z1111-gj3su-"), check.Equals, true)
753 // Confirm the token works and is from the correct user
754 _, rootclnt3bis, _ := s.super.ClientsWithToken("z3333", newTok)
755 var curUser arvados.User
756 err = rootclnt3bis.RequestAndDecode(
757 &curUser, "GET", "arvados/v1/users/current", nil, nil,
759 c.Assert(err, check.IsNil)
760 c.Assert(curUser.UUID, check.Equals, user.UUID)
762 // Request the ApiClientAuthorization list using the new token
763 _, userClient, _ := s.super.ClientsWithToken("z3333", newTok)
764 var acaLst arvados.APIClientAuthorizationList
765 err = userClient.RequestAndDecode(
766 &acaLst, "GET", "arvados/v1/api_client_authorizations", nil, nil,
768 c.Assert(err, check.IsNil)
771 // Test for bug #18076
772 func (s *IntegrationSuite) TestStaleCachedUserRecord(c *check.C) {
773 rootctx1, _, _ := s.super.RootClients("z1111")
774 _, rootclnt3, _ := s.super.RootClients("z3333")
775 conn1 := s.super.Conn("z1111")
776 conn3 := s.super.Conn("z3333")
778 // Make sure LoginCluster is properly configured
779 for _, cls := range []string{"z1111", "z3333"} {
781 s.super.Cluster(cls).Login.LoginCluster,
782 check.Equals, "z1111",
783 check.Commentf("incorrect LoginCluster config on cluster %q", cls))
786 for testCaseNr, testCase := range []struct {
790 {"User without local repository", false},
791 {"User with local repository", true},
793 c.Log(c.TestName() + " " + testCase.name)
794 // Create some users, request them on the federated cluster so they're cached.
795 var users []arvados.User
796 for userNr := 0; userNr < 2; userNr++ {
797 _, _, _, user := s.super.UserClients("z1111",
801 fmt.Sprintf("user%d%d@example.com", testCaseNr, userNr),
803 c.Assert(user.Username, check.Not(check.Equals), "")
804 users = append(users, user)
806 lst, err := conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
807 c.Assert(err, check.Equals, nil)
809 for _, fedUser := range lst.Items {
810 if fedUser.UUID == user.UUID {
811 c.Assert(fedUser.Username, check.Equals, user.Username)
816 c.Assert(userFound, check.Equals, true)
818 if testCase.withRepository {
820 err = rootclnt3.RequestAndDecode(
821 &repo, "POST", "arvados/v1/repositories", nil,
822 map[string]interface{}{
823 "repository": map[string]string{
824 "name": fmt.Sprintf("%s/test", user.Username),
825 "owner_uuid": user.UUID,
829 c.Assert(err, check.IsNil)
833 // Swap the usernames
834 _, err := conn1.UserUpdate(rootctx1, arvados.UpdateOptions{
836 Attrs: map[string]interface{}{
840 c.Assert(err, check.Equals, nil)
841 _, err = conn1.UserUpdate(rootctx1, arvados.UpdateOptions{
843 Attrs: map[string]interface{}{
844 "username": users[0].Username,
847 c.Assert(err, check.Equals, nil)
848 _, err = conn1.UserUpdate(rootctx1, arvados.UpdateOptions{
850 Attrs: map[string]interface{}{
851 "username": users[1].Username,
854 c.Assert(err, check.Equals, nil)
856 // Re-request the list on the federated cluster & check for updates
857 lst, err := conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
858 c.Assert(err, check.Equals, nil)
859 var user0Found, user1Found bool
860 for _, user := range lst.Items {
861 if user.UUID == users[0].UUID {
863 c.Assert(user.Username, check.Equals, users[1].Username)
864 } else if user.UUID == users[1].UUID {
866 c.Assert(user.Username, check.Equals, users[0].Username)
869 c.Assert(user0Found, check.Equals, true)
870 c.Assert(user1Found, check.Equals, true)
874 // Test for bug #16263
875 func (s *IntegrationSuite) TestListUsers(c *check.C) {
876 rootctx1, _, _ := s.super.RootClients("z1111")
877 conn1 := s.super.Conn("z1111")
878 conn3 := s.super.Conn("z3333")
879 userctx1, _, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
881 // Make sure LoginCluster is properly configured
882 for _, cls := range []string{"z1111", "z2222", "z3333"} {
884 s.super.Cluster(cls).Login.LoginCluster,
885 check.Equals, "z1111",
886 check.Commentf("incorrect LoginCluster config on cluster %q", cls))
888 // Make sure z1111 has users with NULL usernames
889 lst, err := conn1.UserList(rootctx1, arvados.ListOptions{
890 Limit: math.MaxInt64, // check that large limit works (see #16263)
892 nullUsername := false
893 c.Assert(err, check.IsNil)
894 c.Assert(len(lst.Items), check.Not(check.Equals), 0)
895 for _, user := range lst.Items {
896 if user.Username == "" {
901 c.Assert(nullUsername, check.Equals, true)
903 user1, err := conn1.UserGetCurrent(userctx1, arvados.GetOptions{})
904 c.Assert(err, check.IsNil)
905 c.Check(user1.IsActive, check.Equals, true)
907 // Ask for the user list on z3333 using z1111's system root token
908 lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
909 c.Assert(err, check.IsNil)
911 for _, user := range lst.Items {
912 if user.UUID == user1.UUID {
913 c.Check(user.IsActive, check.Equals, true)
918 c.Check(found, check.Equals, true)
920 // Deactivate user acct on z1111
921 _, err = conn1.UserUnsetup(rootctx1, arvados.GetOptions{UUID: user1.UUID})
922 c.Assert(err, check.IsNil)
924 // Get user list from z3333, check the returned z1111 user is
926 lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
927 c.Assert(err, check.IsNil)
929 for _, user := range lst.Items {
930 if user.UUID == user1.UUID {
931 c.Check(user.IsActive, check.Equals, false)
936 c.Check(found, check.Equals, true)
938 // Deactivated user no longer has working token
939 user1, err = conn3.UserGetCurrent(userctx1, arvados.GetOptions{})
940 c.Assert(err, check.ErrorMatches, `.*401 Unauthorized.*`)
943 func (s *IntegrationSuite) TestSetupUserWithVM(c *check.C) {
944 conn1 := s.super.Conn("z1111")
945 conn3 := s.super.Conn("z3333")
946 rootctx1, rootac1, _ := s.super.RootClients("z1111")
948 // Create user on LoginCluster z1111
949 _, _, _, user := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
951 // Make a new root token (because rootClients() uses SystemRootToken)
952 var outAuth arvados.APIClientAuthorization
953 err := rootac1.RequestAndDecode(&outAuth, "POST", "/arvados/v1/api_client_authorizations", nil, nil)
954 c.Check(err, check.IsNil)
956 // Make a v2 root token to communicate with z3333
957 rootctx3, rootac3, _ := s.super.ClientsWithToken("z3333", outAuth.TokenV2())
959 // Create VM on z3333
960 var outVM arvados.VirtualMachine
961 err = rootac3.RequestAndDecode(&outVM, "POST", "/arvados/v1/virtual_machines", nil,
962 map[string]interface{}{"virtual_machine": map[string]interface{}{
963 "hostname": "example",
966 c.Check(outVM.UUID[0:5], check.Equals, "z3333")
967 c.Check(err, check.IsNil)
969 // Make sure z3333 user list is up to date
970 _, err = conn3.UserList(rootctx3, arvados.ListOptions{Limit: 1000})
971 c.Check(err, check.IsNil)
973 // Try to set up user on z3333 with the VM
974 _, err = conn3.UserSetup(rootctx3, arvados.UserSetupOptions{UUID: user.UUID, VMUUID: outVM.UUID})
975 c.Check(err, check.IsNil)
977 var outLinks arvados.LinkList
978 err = rootac3.RequestAndDecode(&outLinks, "GET", "/arvados/v1/links", nil,
981 Filters: []arvados.Filter{
995 Operand: "can_login",
1000 Operand: "permission",
1002 c.Check(err, check.IsNil)
1004 c.Check(len(outLinks.Items), check.Equals, 1)
1007 func (s *IntegrationSuite) TestOIDCAccessTokenAuth(c *check.C) {
1008 conn1 := s.super.Conn("z1111")
1009 rootctx1, _, _ := s.super.RootClients("z1111")
1010 s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
1012 accesstoken := s.oidcprovider.ValidAccessToken()
1014 for _, clusterID := range []string{"z1111", "z2222"} {
1016 var coll arvados.Collection
1018 // Write some file data and create a collection
1020 c.Logf("save collection to %s", clusterID)
1022 conn := s.super.Conn(clusterID)
1023 ctx, ac, kc := s.super.ClientsWithToken(clusterID, accesstoken)
1025 fs, err := coll.FileSystem(ac, kc)
1026 c.Assert(err, check.IsNil)
1027 f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
1028 c.Assert(err, check.IsNil)
1029 _, err = io.WriteString(f, "IntegrationSuite.TestOIDCAccessTokenAuth")
1030 c.Assert(err, check.IsNil)
1032 c.Assert(err, check.IsNil)
1033 mtxt, err := fs.MarshalManifest(".")
1034 c.Assert(err, check.IsNil)
1035 coll, err = conn.CollectionCreate(ctx, arvados.CreateOptions{Attrs: map[string]interface{}{
1036 "manifest_text": mtxt,
1038 c.Assert(err, check.IsNil)
1041 // Read the collection & file data -- both from the
1042 // cluster where it was created, and from the other
1044 for _, readClusterID := range []string{"z1111", "z2222", "z3333"} {
1045 c.Logf("retrieve %s from %s", coll.UUID, readClusterID)
1047 conn := s.super.Conn(readClusterID)
1048 ctx, ac, kc := s.super.ClientsWithToken(readClusterID, accesstoken)
1050 user, err := conn.UserGetCurrent(ctx, arvados.GetOptions{})
1051 c.Assert(err, check.IsNil)
1052 c.Check(user.FullName, check.Equals, "Example User")
1053 readcoll, err := conn.CollectionGet(ctx, arvados.GetOptions{UUID: coll.UUID})
1054 c.Assert(err, check.IsNil)
1055 c.Check(readcoll.ManifestText, check.Not(check.Equals), "")
1056 fs, err := readcoll.FileSystem(ac, kc)
1057 c.Assert(err, check.IsNil)
1058 f, err := fs.Open("test.txt")
1059 c.Assert(err, check.IsNil)
1060 buf, err := ioutil.ReadAll(f)
1061 c.Assert(err, check.IsNil)
1062 c.Check(buf, check.DeepEquals, []byte("IntegrationSuite.TestOIDCAccessTokenAuth"))
1067 // z3333 should not forward a locally-issued container runtime token,
1068 // associated with a z1111 user, to its login cluster z1111. z1111
1069 // would only call back to z3333 and then reject the response because
1070 // the user ID does not match the token prefix. See
1071 // dev.arvados.org/issues/18346
1072 func (s *IntegrationSuite) TestForwardRuntimeTokenToLoginCluster(c *check.C) {
1073 db3, db3conn := s.dbConn(c, "z3333")
1075 defer db3conn.Close()
1076 rootctx1, _, _ := s.super.RootClients("z1111")
1077 rootctx3, _, _ := s.super.RootClients("z3333")
1078 conn1 := s.super.Conn("z1111")
1079 conn3 := s.super.Conn("z3333")
1080 userctx1, _, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
1082 user1, err := conn1.UserGetCurrent(userctx1, arvados.GetOptions{})
1083 c.Assert(err, check.IsNil)
1084 c.Logf("user1 %+v", user1)
1086 imageColl, err := conn3.CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
1087 "manifest_text": ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.tar\n",
1089 c.Assert(err, check.IsNil)
1090 c.Logf("imageColl %+v", imageColl)
1092 cr, err := conn3.ContainerRequestCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
1093 "state": "Committed",
1094 "command": []string{"echo"},
1095 "container_image": imageColl.PortableDataHash,
1099 "runtime_constraints": arvados.RuntimeConstraints{
1104 c.Assert(err, check.IsNil)
1105 c.Logf("container request %+v", cr)
1106 ctr, err := conn3.ContainerLock(rootctx3, arvados.GetOptions{UUID: cr.ContainerUUID})
1107 c.Assert(err, check.IsNil)
1108 c.Logf("container %+v", ctr)
1110 // We could use conn3.ContainerAuth() here, but that API
1111 // hasn't been added to sdk/go/arvados/api.go yet.
1112 row := db3conn.QueryRowContext(context.Background(), `SELECT api_token from api_client_authorizations where uuid=$1`, ctr.AuthUUID)
1113 c.Check(row, check.NotNil)
1114 var val sql.NullString
1116 c.Assert(val.Valid, check.Equals, true)
1117 runtimeToken := "v2/" + ctr.AuthUUID + "/" + val.String
1118 ctrctx, _, _ := s.super.ClientsWithToken("z3333", runtimeToken)
1119 c.Logf("container runtime token %+v", runtimeToken)
1121 _, err = conn3.UserGet(ctrctx, arvados.GetOptions{UUID: user1.UUID})
1122 c.Assert(err, check.NotNil)
1123 c.Check(err, check.ErrorMatches, `request failed: .* 401 Unauthorized: cannot use a locally issued token to forward a request to our login cluster \(z1111\)`)
1124 c.Check(err, check.Not(check.ErrorMatches), `(?ms).*127\.0\.0\.11.*`)
1127 func (s *IntegrationSuite) TestRunTrivialContainer(c *check.C) {
1128 conn1 := s.super.Conn("z1111")
1129 rootctx1, _, _ := s.super.RootClients("z1111")
1130 _, ac1, kc1, _ := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
1132 c.Log("[docker load]")
1133 out, err := exec.Command("docker", "load", "--input", arvadostest.BusyboxDockerImage(c)).CombinedOutput()
1134 c.Logf("[docker load done] %s", out)
1135 c.Check(err, check.IsNil)
1137 c.Log("[arv-keepdocker]")
1138 akd := exec.Command("arv-keepdocker", "--no-resume", "busybox:uclibc")
1139 akd.Env = append(os.Environ(), "ARVADOS_API_HOST="+ac1.APIHost, "ARVADOS_API_HOST_INSECURE=1", "ARVADOS_API_TOKEN="+ac1.AuthToken)
1140 c.Logf("[arv-keepdocker env] %q", akd.Env)
1141 out, err = akd.CombinedOutput()
1142 c.Logf("[arv-keepdocker done] %s", out)
1143 c.Check(err, check.IsNil)
1145 var cr arvados.ContainerRequest
1146 err = ac1.RequestAndDecode(&cr, "POST", "/arvados/v1/container_requests", nil, map[string]interface{}{
1147 "container_request": map[string]interface{}{
1148 "command": []string{"touch", "/out/hello_world"},
1149 "container_image": "busybox:uclibc",
1151 "environment": map[string]string{},
1152 "mounts": map[string]arvados.Mount{"/out": {Kind: "tmp", Capacity: 10000}},
1153 "output_path": "/out",
1154 "runtime_constraints": arvados.RuntimeConstraints{RAM: 100000000, VCPUs: 1},
1156 "state": arvados.ContainerRequestStateCommitted,
1159 c.Assert(err, check.IsNil)
1161 showlogs := func(collectionID string) {
1162 var logcoll arvados.Collection
1163 err = ac1.RequestAndDecode(&logcoll, "GET", "/arvados/v1/collections/"+collectionID, nil, nil)
1164 c.Assert(err, check.IsNil)
1165 cfs, err := logcoll.FileSystem(ac1, kc1)
1166 c.Assert(err, check.IsNil)
1167 fs.WalkDir(arvados.FS(cfs), "/", func(path string, d fs.DirEntry, err error) error {
1168 if d.IsDir() || strings.HasPrefix(path, "/log for container") {
1171 f, err := cfs.Open(path)
1172 c.Assert(err, check.IsNil)
1174 buf, err := ioutil.ReadAll(f)
1175 c.Assert(err, check.IsNil)
1176 c.Logf("=== %s\n%s\n", path, buf)
1181 var ctr arvados.Container
1182 var lastState arvados.ContainerState
1183 deadline := time.Now().Add(time.Minute)
1185 for ; ; lastState = ctr.State {
1186 err = ac1.RequestAndDecode(&ctr, "GET", "/arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
1187 c.Assert(err, check.IsNil)
1190 if time.Now().After(deadline) {
1191 c.Errorf("timed out, container request state is %q", cr.State)
1195 time.Sleep(time.Second / 2)
1196 case arvados.ContainerStateComplete:
1198 case arvados.ContainerStateQueued, arvados.ContainerStateLocked, arvados.ContainerStateRunning:
1199 c.Logf("container state changed to %q", ctr.State)
1201 c.Errorf("unexpected container state %q", ctr.State)
1206 c.Check(ctr.ExitCode, check.Equals, 0)
1208 err = ac1.RequestAndDecode(&cr, "GET", "/arvados/v1/container_requests/"+cr.UUID, nil, nil)
1209 c.Assert(err, check.IsNil)
1211 showlogs(cr.LogUUID)
1213 var outcoll arvados.Collection
1214 err = ac1.RequestAndDecode(&outcoll, "GET", "/arvados/v1/collections/"+cr.OutputUUID, nil, nil)
1215 c.Assert(err, check.IsNil)
1216 c.Check(outcoll.ManifestText, check.Matches, `\. d41d8.* 0:0:hello_world\n`)
1217 c.Check(outcoll.PortableDataHash, check.Equals, "dac08d558cfb6c9536f604ca89e3c002+53")