d50bc14537ce149b45b0ed7b6a3945eacf1e4de8
[arvados.git] / lib / controller / integration_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package controller
6
7 import (
8         "bytes"
9         "context"
10         "database/sql"
11         "encoding/json"
12         "io"
13         "io/ioutil"
14         "math"
15         "net"
16         "net/http"
17         "net/url"
18         "os"
19         "path/filepath"
20
21         "git.arvados.org/arvados.git/lib/boot"
22         "git.arvados.org/arvados.git/lib/config"
23         "git.arvados.org/arvados.git/lib/controller/rpc"
24         "git.arvados.org/arvados.git/lib/service"
25         "git.arvados.org/arvados.git/sdk/go/arvados"
26         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
27         "git.arvados.org/arvados.git/sdk/go/arvadostest"
28         "git.arvados.org/arvados.git/sdk/go/auth"
29         "git.arvados.org/arvados.git/sdk/go/ctxlog"
30         "git.arvados.org/arvados.git/sdk/go/keepclient"
31         check "gopkg.in/check.v1"
32 )
33
34 var _ = check.Suite(&IntegrationSuite{})
35
36 type testCluster struct {
37         super         boot.Supervisor
38         config        arvados.Config
39         controllerURL *url.URL
40 }
41
42 type IntegrationSuite struct {
43         testClusters map[string]*testCluster
44         oidcprovider *arvadostest.OIDCProvider
45 }
46
47 func (s *IntegrationSuite) SetUpSuite(c *check.C) {
48         if forceLegacyAPI14 {
49                 c.Skip("heavy integration tests don't run with forceLegacyAPI14")
50                 return
51         }
52
53         cwd, _ := os.Getwd()
54
55         s.oidcprovider = arvadostest.NewOIDCProvider(c)
56         s.oidcprovider.AuthEmail = "user@example.com"
57         s.oidcprovider.AuthEmailVerified = true
58         s.oidcprovider.AuthName = "Example User"
59         s.oidcprovider.ValidClientID = "clientid"
60         s.oidcprovider.ValidClientSecret = "clientsecret"
61
62         s.testClusters = map[string]*testCluster{
63                 "z1111": nil,
64                 "z2222": nil,
65                 "z3333": nil,
66         }
67         hostport := map[string]string{}
68         for id := range s.testClusters {
69                 hostport[id] = func() string {
70                         // TODO: Instead of expecting random ports on
71                         // 127.0.0.11, 22, 33 to be race-safe, try
72                         // different 127.x.y.z until finding one that
73                         // isn't in use.
74                         ln, err := net.Listen("tcp", ":0")
75                         c.Assert(err, check.IsNil)
76                         ln.Close()
77                         _, port, err := net.SplitHostPort(ln.Addr().String())
78                         c.Assert(err, check.IsNil)
79                         return "127.0.0." + id[3:] + ":" + port
80                 }()
81         }
82         for id := range s.testClusters {
83                 yaml := `Clusters:
84   ` + id + `:
85     Services:
86       Controller:
87         ExternalURL: https://` + hostport[id] + `
88     TLS:
89       Insecure: true
90     Login:
91       LoginCluster: z1111
92     SystemLogs:
93       Format: text
94     RemoteClusters:
95       z1111:
96         Host: ` + hostport["z1111"] + `
97         Scheme: https
98         Insecure: true
99         Proxy: true
100         ActivateUsers: true
101 `
102                 if id != "z2222" {
103                         yaml += `      z2222:
104         Host: ` + hostport["z2222"] + `
105         Scheme: https
106         Insecure: true
107         Proxy: true
108         ActivateUsers: true
109 `
110                 }
111                 if id != "z3333" {
112                         yaml += `      z3333:
113         Host: ` + hostport["z3333"] + `
114         Scheme: https
115         Insecure: true
116         Proxy: true
117         ActivateUsers: true
118 `
119                 }
120                 if id == "z1111" {
121                         yaml += `
122     Login:
123       LoginCluster: z1111
124       OpenIDConnect:
125         Enable: true
126         Issuer: ` + s.oidcprovider.Issuer.URL + `
127         ClientID: ` + s.oidcprovider.ValidClientID + `
128         ClientSecret: ` + s.oidcprovider.ValidClientSecret + `
129         EmailClaim: email
130         EmailVerifiedClaim: email_verified
131 `
132                 } else {
133                         yaml += `
134     Login:
135       LoginCluster: z1111
136 `
137                 }
138
139                 loader := config.NewLoader(bytes.NewBufferString(yaml), ctxlog.TestLogger(c))
140                 loader.Path = "-"
141                 loader.SkipLegacy = true
142                 loader.SkipAPICalls = true
143                 cfg, err := loader.Load()
144                 c.Assert(err, check.IsNil)
145                 s.testClusters[id] = &testCluster{
146                         super: boot.Supervisor{
147                                 SourcePath:           filepath.Join(cwd, "..", ".."),
148                                 ClusterType:          "test",
149                                 ListenHost:           "127.0.0." + id[3:],
150                                 ControllerAddr:       ":0",
151                                 OwnTemporaryDatabase: true,
152                                 Stderr:               &service.LogPrefixer{Writer: ctxlog.LogWriter(c.Log), Prefix: []byte("[" + id + "] ")},
153                         },
154                         config: *cfg,
155                 }
156                 s.testClusters[id].super.Start(context.Background(), &s.testClusters[id].config, "-")
157         }
158         for _, tc := range s.testClusters {
159                 au, ok := tc.super.WaitReady()
160                 c.Assert(ok, check.Equals, true)
161                 u := url.URL(*au)
162                 tc.controllerURL = &u
163         }
164 }
165
166 func (s *IntegrationSuite) TearDownSuite(c *check.C) {
167         for _, c := range s.testClusters {
168                 c.super.Stop()
169         }
170 }
171
172 // Get rpc connection struct initialized to communicate with the
173 // specified cluster.
174 func (s *IntegrationSuite) conn(clusterID string) *rpc.Conn {
175         return rpc.NewConn(clusterID, s.testClusters[clusterID].controllerURL, true, rpc.PassthroughTokenProvider)
176 }
177
178 // Return Context, Arvados.Client and keepclient structs initialized
179 // to connect to the specified cluster (by clusterID) using with the supplied
180 // Arvados token.
181 func (s *IntegrationSuite) clientsWithToken(clusterID string, token string) (context.Context, *arvados.Client, *keepclient.KeepClient) {
182         cl := s.testClusters[clusterID].config.Clusters[clusterID]
183         ctx := auth.NewContext(context.Background(), auth.NewCredentials(token))
184         ac, err := arvados.NewClientFromConfig(&cl)
185         if err != nil {
186                 panic(err)
187         }
188         ac.AuthToken = token
189         arv, err := arvadosclient.New(ac)
190         if err != nil {
191                 panic(err)
192         }
193         kc := keepclient.New(arv)
194         return ctx, ac, kc
195 }
196
197 // Log in as a user called "example", get the user's API token,
198 // initialize clients with the API token, set up the user and
199 // optionally activate the user.  Return client structs for
200 // communicating with the cluster on behalf of the 'example' user.
201 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) {
202         login, err := conn.UserSessionCreate(rootctx, rpc.UserSessionCreateOptions{
203                 ReturnTo: ",https://example.com",
204                 AuthInfo: rpc.UserSessionAuthInfo{
205                         Email:     "user@example.com",
206                         FirstName: "Example",
207                         LastName:  "User",
208                         Username:  "example",
209                 },
210         })
211         c.Assert(err, check.IsNil)
212         redirURL, err := url.Parse(login.RedirectLocation)
213         c.Assert(err, check.IsNil)
214         userToken := redirURL.Query().Get("api_token")
215         c.Logf("user token: %q", userToken)
216         ctx, ac, kc := s.clientsWithToken(clusterID, userToken)
217         user, err := conn.UserGetCurrent(ctx, arvados.GetOptions{})
218         c.Assert(err, check.IsNil)
219         _, err = conn.UserSetup(rootctx, arvados.UserSetupOptions{UUID: user.UUID})
220         c.Assert(err, check.IsNil)
221         if activate {
222                 _, err = conn.UserActivate(rootctx, arvados.UserActivateOptions{UUID: user.UUID})
223                 c.Assert(err, check.IsNil)
224                 user, err = conn.UserGetCurrent(ctx, arvados.GetOptions{})
225                 c.Assert(err, check.IsNil)
226                 c.Logf("user UUID: %q", user.UUID)
227                 if !user.IsActive {
228                         c.Fatalf("failed to activate user -- %#v", user)
229                 }
230         }
231         return ctx, ac, kc, user
232 }
233
234 // Return Context, arvados.Client and keepclient structs initialized
235 // to communicate with the cluster as the system root user.
236 func (s *IntegrationSuite) rootClients(clusterID string) (context.Context, *arvados.Client, *keepclient.KeepClient) {
237         return s.clientsWithToken(clusterID, s.testClusters[clusterID].config.Clusters[clusterID].SystemRootToken)
238 }
239
240 // Return Context, arvados.Client and keepclient structs initialized
241 // to communicate with the cluster as the anonymous user.
242 func (s *IntegrationSuite) anonymousClients(clusterID string) (context.Context, *arvados.Client, *keepclient.KeepClient) {
243         return s.clientsWithToken(clusterID, s.testClusters[clusterID].config.Clusters[clusterID].Users.AnonymousUserToken)
244 }
245
246 func (s *IntegrationSuite) TestGetCollectionByPDH(c *check.C) {
247         conn1 := s.conn("z1111")
248         rootctx1, _, _ := s.rootClients("z1111")
249         conn3 := s.conn("z3333")
250         userctx1, ac1, kc1, _ := s.userClients(rootctx1, c, conn1, "z1111", true)
251
252         // Create the collection to find its PDH (but don't save it
253         // anywhere yet)
254         var coll1 arvados.Collection
255         fs1, err := coll1.FileSystem(ac1, kc1)
256         c.Assert(err, check.IsNil)
257         f, err := fs1.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
258         c.Assert(err, check.IsNil)
259         _, err = io.WriteString(f, "IntegrationSuite.TestGetCollectionByPDH")
260         c.Assert(err, check.IsNil)
261         err = f.Close()
262         c.Assert(err, check.IsNil)
263         mtxt, err := fs1.MarshalManifest(".")
264         c.Assert(err, check.IsNil)
265         pdh := arvados.PortableDataHash(mtxt)
266
267         // Looking up the PDH before saving returns 404 if cycle
268         // detection is working.
269         _, err = conn1.CollectionGet(userctx1, arvados.GetOptions{UUID: pdh})
270         c.Assert(err, check.ErrorMatches, `.*404 Not Found.*`)
271
272         // Save the collection on cluster z1111.
273         coll1, err = conn1.CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
274                 "manifest_text": mtxt,
275         }})
276         c.Assert(err, check.IsNil)
277
278         // Retrieve the collection from cluster z3333.
279         coll, err := conn3.CollectionGet(userctx1, arvados.GetOptions{UUID: pdh})
280         c.Check(err, check.IsNil)
281         c.Check(coll.PortableDataHash, check.Equals, pdh)
282 }
283
284 func (s *IntegrationSuite) TestGetCollectionAsAnonymous(c *check.C) {
285         conn1 := s.conn("z1111")
286         conn3 := s.conn("z3333")
287         rootctx1, rootac1, rootkc1 := s.rootClients("z1111")
288         anonctx3, anonac3, _ := s.anonymousClients("z3333")
289
290         // Make sure anonymous token was set
291         c.Assert(anonac3.AuthToken, check.Not(check.Equals), "")
292
293         // Create the collection to find its PDH (but don't save it
294         // anywhere yet)
295         var coll1 arvados.Collection
296         fs1, err := coll1.FileSystem(rootac1, rootkc1)
297         c.Assert(err, check.IsNil)
298         f, err := fs1.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
299         c.Assert(err, check.IsNil)
300         _, err = io.WriteString(f, "IntegrationSuite.TestGetCollectionAsAnonymous")
301         c.Assert(err, check.IsNil)
302         err = f.Close()
303         c.Assert(err, check.IsNil)
304         mtxt, err := fs1.MarshalManifest(".")
305         c.Assert(err, check.IsNil)
306         pdh := arvados.PortableDataHash(mtxt)
307
308         // Save the collection on cluster z1111.
309         coll1, err = conn1.CollectionCreate(rootctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
310                 "manifest_text": mtxt,
311         }})
312         c.Assert(err, check.IsNil)
313
314         // Share it with the anonymous users group.
315         var outLink arvados.Link
316         err = rootac1.RequestAndDecode(&outLink, "POST", "/arvados/v1/links", nil,
317                 map[string]interface{}{"link": map[string]interface{}{
318                         "link_class": "permission",
319                         "name":       "can_read",
320                         "tail_uuid":  "z1111-j7d0g-anonymouspublic",
321                         "head_uuid":  coll1.UUID,
322                 },
323                 })
324         c.Check(err, check.IsNil)
325
326         // Current user should be z3 anonymous user
327         outUser, err := anonac3.CurrentUser()
328         c.Check(err, check.IsNil)
329         c.Check(outUser.UUID, check.Equals, "z3333-tpzed-anonymouspublic")
330
331         // Get the token uuid
332         var outAuth arvados.APIClientAuthorization
333         err = anonac3.RequestAndDecode(&outAuth, "GET", "/arvados/v1/api_client_authorizations/current", nil, nil)
334         c.Check(err, check.IsNil)
335
336         // Make a v2 token of the z3 anonymous user, and use it on z1
337         _, anonac1, _ := s.clientsWithToken("z1111", outAuth.TokenV2())
338         outUser2, err := anonac1.CurrentUser()
339         c.Check(err, check.IsNil)
340         // z3 anonymous user will be mapped to the z1 anonymous user
341         c.Check(outUser2.UUID, check.Equals, "z1111-tpzed-anonymouspublic")
342
343         // Retrieve the collection (which is on z1) using anonymous from cluster z3333.
344         coll, err := conn3.CollectionGet(anonctx3, arvados.GetOptions{UUID: coll1.UUID})
345         c.Check(err, check.IsNil)
346         c.Check(coll.PortableDataHash, check.Equals, pdh)
347 }
348
349 // Get a token from the login cluster (z1111), use it to submit a
350 // container request on z2222.
351 func (s *IntegrationSuite) TestCreateContainerRequestWithFedToken(c *check.C) {
352         conn1 := s.conn("z1111")
353         rootctx1, _, _ := s.rootClients("z1111")
354         _, ac1, _, _ := s.userClients(rootctx1, c, conn1, "z1111", true)
355
356         // Use ac2 to get the discovery doc with a blank token, so the
357         // SDK doesn't magically pass the z1111 token to z2222 before
358         // we're ready to start our test.
359         _, ac2, _ := s.clientsWithToken("z2222", "")
360         var dd map[string]interface{}
361         err := ac2.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
362         c.Assert(err, check.IsNil)
363
364         var (
365                 body bytes.Buffer
366                 req  *http.Request
367                 resp *http.Response
368                 u    arvados.User
369                 cr   arvados.ContainerRequest
370         )
371         json.NewEncoder(&body).Encode(map[string]interface{}{
372                 "container_request": map[string]interface{}{
373                         "command":         []string{"echo"},
374                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
375                         "cwd":             "/",
376                         "output_path":     "/",
377                 },
378         })
379         ac2.AuthToken = ac1.AuthToken
380
381         c.Log("...post CR with good (but not yet cached) token")
382         cr = arvados.ContainerRequest{}
383         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
384         c.Assert(err, check.IsNil)
385         req.Header.Set("Content-Type", "application/json")
386         err = ac2.DoAndDecode(&cr, req)
387         c.Assert(err, check.IsNil)
388         c.Logf("err == %#v", err)
389
390         c.Log("...get user with good token")
391         u = arvados.User{}
392         req, err = http.NewRequest("GET", "https://"+ac2.APIHost+"/arvados/v1/users/current", nil)
393         c.Assert(err, check.IsNil)
394         err = ac2.DoAndDecode(&u, req)
395         c.Check(err, check.IsNil)
396         c.Check(u.UUID, check.Matches, "z1111-tpzed-.*")
397
398         c.Log("...post CR with good cached token")
399         cr = arvados.ContainerRequest{}
400         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
401         c.Assert(err, check.IsNil)
402         req.Header.Set("Content-Type", "application/json")
403         err = ac2.DoAndDecode(&cr, req)
404         c.Check(err, check.IsNil)
405         c.Check(cr.UUID, check.Matches, "z2222-.*")
406
407         c.Log("...post with good cached token ('OAuth2 ...')")
408         cr = arvados.ContainerRequest{}
409         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
410         c.Assert(err, check.IsNil)
411         req.Header.Set("Content-Type", "application/json")
412         req.Header.Set("Authorization", "OAuth2 "+ac2.AuthToken)
413         resp, err = arvados.InsecureHTTPClient.Do(req)
414         c.Assert(err, check.IsNil)
415         err = json.NewDecoder(resp.Body).Decode(&cr)
416         c.Check(err, check.IsNil)
417         c.Check(cr.UUID, check.Matches, "z2222-.*")
418 }
419
420 func (s *IntegrationSuite) TestCreateContainerRequestWithBadToken(c *check.C) {
421         var (
422                 body bytes.Buffer
423                 resp *http.Response
424         )
425
426         conn1 := s.conn("z1111")
427         rootctx1, _, _ := s.rootClients("z1111")
428         _, ac1, _, au := s.userClients(rootctx1, c, conn1, "z1111", true)
429
430         tests := []struct {
431                 name         string
432                 token        string
433                 expectedCode int
434         }{
435                 {"Good token", ac1.AuthToken, http.StatusOK},
436                 {"Bogus token", "abcdef", http.StatusUnauthorized},
437                 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", http.StatusUnauthorized},
438                 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", http.StatusUnauthorized},
439         }
440
441         json.NewEncoder(&body).Encode(map[string]interface{}{
442                 "container_request": map[string]interface{}{
443                         "command":         []string{"echo"},
444                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
445                         "cwd":             "/",
446                         "output_path":     "/",
447                 },
448         })
449
450         for _, tt := range tests {
451                 c.Log(c.TestName() + " " + tt.name)
452                 ac1.AuthToken = tt.token
453                 req, err := http.NewRequest("POST", "https://"+ac1.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
454                 c.Assert(err, check.IsNil)
455                 req.Header.Set("Content-Type", "application/json")
456                 resp, err = ac1.Do(req)
457                 c.Assert(err, check.IsNil)
458                 c.Assert(resp.StatusCode, check.Equals, tt.expectedCode)
459         }
460 }
461
462 // We test the direct access to the database
463 // normally an integration test would not have a database access, but  in this case we need
464 // to test tokens that are secret, so there is no API response that will give them back
465 func (s *IntegrationSuite) dbConn(c *check.C, clusterID string) (*sql.DB, *sql.Conn) {
466         ctx := context.Background()
467         db, err := sql.Open("postgres", s.testClusters[clusterID].super.Cluster().PostgreSQL.Connection.String())
468         c.Assert(err, check.IsNil)
469
470         conn, err := db.Conn(ctx)
471         c.Assert(err, check.IsNil)
472
473         rows, err := conn.ExecContext(ctx, `SELECT 1`)
474         c.Assert(err, check.IsNil)
475         n, err := rows.RowsAffected()
476         c.Assert(err, check.IsNil)
477         c.Assert(n, check.Equals, int64(1))
478         return db, conn
479 }
480
481 func (s *IntegrationSuite) TestRuntimeTokenInCR(c *check.C) {
482         db, dbconn := s.dbConn(c, "z1111")
483         defer db.Close()
484         defer dbconn.Close()
485         conn1 := s.conn("z1111")
486         rootctx1, _, _ := s.rootClients("z1111")
487         _, ac1, _, au := s.userClients(rootctx1, c, conn1, "z1111", true)
488
489         tests := []struct {
490                 name                 string
491                 token                string
492                 expectAToGetAValidCR bool
493                 expectedToken        *string
494         }{
495                 {"Good token z1111 user", ac1.AuthToken, true, &ac1.AuthToken},
496                 {"Bogus token", "abcdef", false, nil},
497                 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", false, nil},
498                 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", false, nil},
499         }
500
501         for _, tt := range tests {
502                 c.Log(c.TestName() + " " + tt.name)
503
504                 rq := map[string]interface{}{
505                         "command":         []string{"echo"},
506                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
507                         "cwd":             "/",
508                         "output_path":     "/",
509                         "runtime_token":   tt.token,
510                 }
511                 cr, err := conn1.ContainerRequestCreate(rootctx1, arvados.CreateOptions{Attrs: rq})
512                 if tt.expectAToGetAValidCR {
513                         c.Assert(err, check.IsNil)
514                         c.Assert(cr, check.NotNil)
515                         c.Assert(cr.UUID, check.Not(check.Equals), "")
516                 }
517
518                 if tt.expectedToken == nil {
519                         break
520                 }
521
522                 c.Logf("cr.UUID: %s", cr.UUID)
523                 row := dbconn.QueryRowContext(rootctx1, `SELECT runtime_token from container_requests where uuid=$1`, cr.UUID)
524                 c.Assert(row, check.NotNil)
525                 // runtimeToken is *string and not a string because the database has a NULL column for this
526                 var runtimeToken *string
527                 err = row.Scan(&runtimeToken)
528                 c.Assert(err, check.IsNil)
529                 c.Assert(runtimeToken, check.NotNil)
530                 c.Assert(*runtimeToken, check.DeepEquals, *tt.expectedToken)
531         }
532 }
533
534 // Test for bug #16263
535 func (s *IntegrationSuite) TestListUsers(c *check.C) {
536         rootctx1, _, _ := s.rootClients("z1111")
537         conn1 := s.conn("z1111")
538         conn3 := s.conn("z3333")
539         userctx1, _, _, _ := s.userClients(rootctx1, c, conn1, "z1111", true)
540
541         // Make sure LoginCluster is properly configured
542         for cls := range s.testClusters {
543                 c.Check(
544                         s.testClusters[cls].config.Clusters[cls].Login.LoginCluster,
545                         check.Equals, "z1111",
546                         check.Commentf("incorrect LoginCluster config on cluster %q", cls))
547         }
548         // Make sure z1111 has users with NULL usernames
549         lst, err := conn1.UserList(rootctx1, arvados.ListOptions{
550                 Limit: math.MaxInt64, // check that large limit works (see #16263)
551         })
552         nullUsername := false
553         c.Assert(err, check.IsNil)
554         c.Assert(len(lst.Items), check.Not(check.Equals), 0)
555         for _, user := range lst.Items {
556                 if user.Username == "" {
557                         nullUsername = true
558                 }
559         }
560         c.Assert(nullUsername, check.Equals, true)
561
562         user1, err := conn1.UserGetCurrent(userctx1, arvados.GetOptions{})
563         c.Assert(err, check.IsNil)
564         c.Check(user1.IsActive, check.Equals, true)
565
566         // Ask for the user list on z3333 using z1111's system root token
567         lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
568         c.Assert(err, check.IsNil)
569         found := false
570         for _, user := range lst.Items {
571                 if user.UUID == user1.UUID {
572                         c.Check(user.IsActive, check.Equals, true)
573                         found = true
574                         break
575                 }
576         }
577         c.Check(found, check.Equals, true)
578
579         // Deactivate user acct on z1111
580         _, err = conn1.UserUnsetup(rootctx1, arvados.GetOptions{UUID: user1.UUID})
581         c.Assert(err, check.IsNil)
582
583         // Get user list from z3333, check the returned z1111 user is
584         // deactivated
585         lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
586         c.Assert(err, check.IsNil)
587         found = false
588         for _, user := range lst.Items {
589                 if user.UUID == user1.UUID {
590                         c.Check(user.IsActive, check.Equals, false)
591                         found = true
592                         break
593                 }
594         }
595         c.Check(found, check.Equals, true)
596
597         // Deactivated user can see is_active==false via "get current
598         // user" API
599         user1, err = conn3.UserGetCurrent(userctx1, arvados.GetOptions{})
600         c.Assert(err, check.IsNil)
601         c.Check(user1.IsActive, check.Equals, false)
602 }
603
604 func (s *IntegrationSuite) TestSetupUserWithVM(c *check.C) {
605         conn1 := s.conn("z1111")
606         conn3 := s.conn("z3333")
607         rootctx1, rootac1, _ := s.rootClients("z1111")
608
609         // Create user on LoginCluster z1111
610         _, _, _, user := s.userClients(rootctx1, c, conn1, "z1111", false)
611
612         // Make a new root token (because rootClients() uses SystemRootToken)
613         var outAuth arvados.APIClientAuthorization
614         err := rootac1.RequestAndDecode(&outAuth, "POST", "/arvados/v1/api_client_authorizations", nil, nil)
615         c.Check(err, check.IsNil)
616
617         // Make a v2 root token to communicate with z3333
618         rootctx3, rootac3, _ := s.clientsWithToken("z3333", outAuth.TokenV2())
619
620         // Create VM on z3333
621         var outVM arvados.VirtualMachine
622         err = rootac3.RequestAndDecode(&outVM, "POST", "/arvados/v1/virtual_machines", nil,
623                 map[string]interface{}{"virtual_machine": map[string]interface{}{
624                         "hostname": "example",
625                 },
626                 })
627         c.Check(outVM.UUID[0:5], check.Equals, "z3333")
628         c.Check(err, check.IsNil)
629
630         // Make sure z3333 user list is up to date
631         _, err = conn3.UserList(rootctx3, arvados.ListOptions{Limit: 1000})
632         c.Check(err, check.IsNil)
633
634         // Try to set up user on z3333 with the VM
635         _, err = conn3.UserSetup(rootctx3, arvados.UserSetupOptions{UUID: user.UUID, VMUUID: outVM.UUID})
636         c.Check(err, check.IsNil)
637
638         var outLinks arvados.LinkList
639         err = rootac3.RequestAndDecode(&outLinks, "GET", "/arvados/v1/links", nil,
640                 arvados.ListOptions{
641                         Limit: 1000,
642                         Filters: []arvados.Filter{
643                                 {
644                                         Attr:     "tail_uuid",
645                                         Operator: "=",
646                                         Operand:  user.UUID,
647                                 },
648                                 {
649                                         Attr:     "head_uuid",
650                                         Operator: "=",
651                                         Operand:  outVM.UUID,
652                                 },
653                                 {
654                                         Attr:     "name",
655                                         Operator: "=",
656                                         Operand:  "can_login",
657                                 },
658                                 {
659                                         Attr:     "link_class",
660                                         Operator: "=",
661                                         Operand:  "permission",
662                                 }}})
663         c.Check(err, check.IsNil)
664
665         c.Check(len(outLinks.Items), check.Equals, 1)
666 }
667
668 func (s *IntegrationSuite) TestOIDCAccessTokenAuth(c *check.C) {
669         conn1 := s.conn("z1111")
670         rootctx1, _, _ := s.rootClients("z1111")
671         s.userClients(rootctx1, c, conn1, "z1111", true)
672
673         accesstoken := s.oidcprovider.ValidAccessToken()
674
675         for _, clusterid := range []string{"z1111", "z2222"} {
676                 c.Logf("trying clusterid %s", clusterid)
677
678                 conn := s.conn(clusterid)
679                 ctx, ac, kc := s.clientsWithToken(clusterid, accesstoken)
680
681                 var coll arvados.Collection
682
683                 // Write some file data and create a collection
684                 {
685                         fs, err := coll.FileSystem(ac, kc)
686                         c.Assert(err, check.IsNil)
687                         f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
688                         c.Assert(err, check.IsNil)
689                         _, err = io.WriteString(f, "IntegrationSuite.TestOIDCAccessTokenAuth")
690                         c.Assert(err, check.IsNil)
691                         err = f.Close()
692                         c.Assert(err, check.IsNil)
693                         mtxt, err := fs.MarshalManifest(".")
694                         c.Assert(err, check.IsNil)
695                         coll, err = conn.CollectionCreate(ctx, arvados.CreateOptions{Attrs: map[string]interface{}{
696                                 "manifest_text": mtxt,
697                         }})
698                         c.Assert(err, check.IsNil)
699                 }
700
701                 // Read the collection & file data
702                 {
703                         user, err := conn.UserGetCurrent(ctx, arvados.GetOptions{})
704                         c.Assert(err, check.IsNil)
705                         c.Check(user.FullName, check.Equals, "Example User")
706                         coll, err = conn.CollectionGet(ctx, arvados.GetOptions{UUID: coll.UUID})
707                         c.Assert(err, check.IsNil)
708                         c.Check(coll.ManifestText, check.Not(check.Equals), "")
709                         fs, err := coll.FileSystem(ac, kc)
710                         c.Assert(err, check.IsNil)
711                         f, err := fs.Open("test.txt")
712                         c.Assert(err, check.IsNil)
713                         buf, err := ioutil.ReadAll(f)
714                         c.Assert(err, check.IsNil)
715                         c.Check(buf, check.DeepEquals, []byte("IntegrationSuite.TestOIDCAccessTokenAuth"))
716                 }
717         }
718 }