17014: rebase with master and adaptation changes
[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) TestDatabaseConnection(c *check.C) {
466         ctx, cancel := context.WithCancel(context.Background())
467         defer cancel()
468         db, err := sql.Open("postgres", s.testClusters["z1111"].super.Cluster().PostgreSQL.Connection.String())
469         c.Assert(err, check.IsNil)
470         defer db.Close()
471         conn, err := db.Conn(ctx)
472         c.Assert(err, check.IsNil)
473         defer conn.Close()
474         rows, err := conn.ExecContext(ctx, `SELECT 1`)
475         c.Assert(err, check.IsNil)
476         n, err := rows.RowsAffected()
477         c.Assert(err, check.IsNil)
478         c.Assert(n, check.Equals, int64(1))
479 }
480
481 func (s *IntegrationSuite) TestRuntimeTokenInCR(c *check.C) {
482         conn1 := s.conn("z1111")
483         rootctx1, _, _ := s.rootClients("z1111")
484         _, ac1, _, au := s.userClients(rootctx1, c, conn1, "z1111", true)
485
486         tests := []struct {
487                 name                 string
488                 token                string
489                 expectAToGetAValidCR bool
490                 expectedToken        *string
491         }{
492                 {"Good token z1111 user", ac1.AuthToken, true, &ac1.AuthToken},
493                 {"Bogus token", "abcdef", false, nil},
494                 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", false, nil},
495                 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", false, nil},
496         }
497
498         for _, tt := range tests {
499                 c.Log(c.TestName() + " " + tt.name)
500
501                 rq := map[string]interface{}{
502                         "command":         []string{"echo"},
503                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
504                         "cwd":             "/",
505                         "output_path":     "/",
506                         "runtime_token":   tt.token,
507                 }
508                 cr, err := conn1.ContainerRequestCreate(rootctx1, arvados.CreateOptions{Attrs: rq})
509                 if tt.expectAToGetAValidCR {
510                         c.Assert(err, check.IsNil)
511                         c.Assert(cr, check.NotNil)
512                         c.Assert(cr.UUID, check.Not(check.Equals), "")
513                 }
514
515                 if tt.expectedToken == nil {
516                         break
517                 }
518
519                 ctx2, cancel2 := context.WithCancel(context.Background())
520                 defer cancel2()
521
522                 db, err := sql.Open("postgres", s.testClusters["z1111"].super.Cluster().PostgreSQL.Connection.String())
523                 c.Assert(err, check.IsNil)
524                 defer db.Close()
525
526                 conn, err := db.Conn(ctx2)
527                 c.Assert(err, check.IsNil)
528                 defer conn.Close()
529
530                 c.Logf("cr.UUID: %s", cr.UUID)
531                 row := conn.QueryRowContext(ctx2, `SELECT runtime_token from container_requests where uuid=$1`, cr.UUID)
532                 c.Assert(row, check.NotNil)
533                 // runtimeToken is *string and not a string because the database has a NULL column for this
534                 var runtimeToken *string
535                 err = row.Scan(&runtimeToken)
536                 c.Assert(err, check.IsNil)
537                 c.Assert(runtimeToken, check.NotNil)
538                 c.Assert(*runtimeToken, check.DeepEquals, *tt.expectedToken)
539         }
540 }
541
542 // Test for bug #16263
543 func (s *IntegrationSuite) TestListUsers(c *check.C) {
544         rootctx1, _, _ := s.rootClients("z1111")
545         conn1 := s.conn("z1111")
546         conn3 := s.conn("z3333")
547         userctx1, _, _, _ := s.userClients(rootctx1, c, conn1, "z1111", true)
548
549         // Make sure LoginCluster is properly configured
550         for cls := range s.testClusters {
551                 c.Check(
552                         s.testClusters[cls].config.Clusters[cls].Login.LoginCluster,
553                         check.Equals, "z1111",
554                         check.Commentf("incorrect LoginCluster config on cluster %q", cls))
555         }
556         // Make sure z1111 has users with NULL usernames
557         lst, err := conn1.UserList(rootctx1, arvados.ListOptions{
558                 Limit: math.MaxInt64, // check that large limit works (see #16263)
559         })
560         nullUsername := false
561         c.Assert(err, check.IsNil)
562         c.Assert(len(lst.Items), check.Not(check.Equals), 0)
563         for _, user := range lst.Items {
564                 if user.Username == "" {
565                         nullUsername = true
566                 }
567         }
568         c.Assert(nullUsername, check.Equals, true)
569
570         user1, err := conn1.UserGetCurrent(userctx1, arvados.GetOptions{})
571         c.Assert(err, check.IsNil)
572         c.Check(user1.IsActive, check.Equals, true)
573
574         // Ask for the user list on z3333 using z1111's system root token
575         lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
576         c.Assert(err, check.IsNil)
577         found := false
578         for _, user := range lst.Items {
579                 if user.UUID == user1.UUID {
580                         c.Check(user.IsActive, check.Equals, true)
581                         found = true
582                         break
583                 }
584         }
585         c.Check(found, check.Equals, true)
586
587         // Deactivate user acct on z1111
588         _, err = conn1.UserUnsetup(rootctx1, arvados.GetOptions{UUID: user1.UUID})
589         c.Assert(err, check.IsNil)
590
591         // Get user list from z3333, check the returned z1111 user is
592         // deactivated
593         lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
594         c.Assert(err, check.IsNil)
595         found = false
596         for _, user := range lst.Items {
597                 if user.UUID == user1.UUID {
598                         c.Check(user.IsActive, check.Equals, false)
599                         found = true
600                         break
601                 }
602         }
603         c.Check(found, check.Equals, true)
604
605         // Deactivated user can see is_active==false via "get current
606         // user" API
607         user1, err = conn3.UserGetCurrent(userctx1, arvados.GetOptions{})
608         c.Assert(err, check.IsNil)
609         c.Check(user1.IsActive, check.Equals, false)
610 }
611
612 func (s *IntegrationSuite) TestSetupUserWithVM(c *check.C) {
613         conn1 := s.conn("z1111")
614         conn3 := s.conn("z3333")
615         rootctx1, rootac1, _ := s.rootClients("z1111")
616
617         // Create user on LoginCluster z1111
618         _, _, _, user := s.userClients(rootctx1, c, conn1, "z1111", false)
619
620         // Make a new root token (because rootClients() uses SystemRootToken)
621         var outAuth arvados.APIClientAuthorization
622         err := rootac1.RequestAndDecode(&outAuth, "POST", "/arvados/v1/api_client_authorizations", nil, nil)
623         c.Check(err, check.IsNil)
624
625         // Make a v2 root token to communicate with z3333
626         rootctx3, rootac3, _ := s.clientsWithToken("z3333", outAuth.TokenV2())
627
628         // Create VM on z3333
629         var outVM arvados.VirtualMachine
630         err = rootac3.RequestAndDecode(&outVM, "POST", "/arvados/v1/virtual_machines", nil,
631                 map[string]interface{}{"virtual_machine": map[string]interface{}{
632                         "hostname": "example",
633                 },
634                 })
635         c.Check(outVM.UUID[0:5], check.Equals, "z3333")
636         c.Check(err, check.IsNil)
637
638         // Make sure z3333 user list is up to date
639         _, err = conn3.UserList(rootctx3, arvados.ListOptions{Limit: 1000})
640         c.Check(err, check.IsNil)
641
642         // Try to set up user on z3333 with the VM
643         _, err = conn3.UserSetup(rootctx3, arvados.UserSetupOptions{UUID: user.UUID, VMUUID: outVM.UUID})
644         c.Check(err, check.IsNil)
645
646         var outLinks arvados.LinkList
647         err = rootac3.RequestAndDecode(&outLinks, "GET", "/arvados/v1/links", nil,
648                 arvados.ListOptions{
649                         Limit: 1000,
650                         Filters: []arvados.Filter{
651                                 {
652                                         Attr:     "tail_uuid",
653                                         Operator: "=",
654                                         Operand:  user.UUID,
655                                 },
656                                 {
657                                         Attr:     "head_uuid",
658                                         Operator: "=",
659                                         Operand:  outVM.UUID,
660                                 },
661                                 {
662                                         Attr:     "name",
663                                         Operator: "=",
664                                         Operand:  "can_login",
665                                 },
666                                 {
667                                         Attr:     "link_class",
668                                         Operator: "=",
669                                         Operand:  "permission",
670                                 }}})
671         c.Check(err, check.IsNil)
672
673         c.Check(len(outLinks.Items), check.Equals, 1)
674 }
675
676 func (s *IntegrationSuite) TestOIDCAccessTokenAuth(c *check.C) {
677         conn1 := s.conn("z1111")
678         rootctx1, _, _ := s.rootClients("z1111")
679         s.userClients(rootctx1, c, conn1, "z1111", true)
680
681         accesstoken := s.oidcprovider.ValidAccessToken()
682
683         for _, clusterid := range []string{"z1111", "z2222"} {
684                 c.Logf("trying clusterid %s", clusterid)
685
686                 conn := s.conn(clusterid)
687                 ctx, ac, kc := s.clientsWithToken(clusterid, accesstoken)
688
689                 var coll arvados.Collection
690
691                 // Write some file data and create a collection
692                 {
693                         fs, err := coll.FileSystem(ac, kc)
694                         c.Assert(err, check.IsNil)
695                         f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
696                         c.Assert(err, check.IsNil)
697                         _, err = io.WriteString(f, "IntegrationSuite.TestOIDCAccessTokenAuth")
698                         c.Assert(err, check.IsNil)
699                         err = f.Close()
700                         c.Assert(err, check.IsNil)
701                         mtxt, err := fs.MarshalManifest(".")
702                         c.Assert(err, check.IsNil)
703                         coll, err = conn.CollectionCreate(ctx, arvados.CreateOptions{Attrs: map[string]interface{}{
704                                 "manifest_text": mtxt,
705                         }})
706                         c.Assert(err, check.IsNil)
707                 }
708
709                 // Read the collection & file data
710                 {
711                         user, err := conn.UserGetCurrent(ctx, arvados.GetOptions{})
712                         c.Assert(err, check.IsNil)
713                         c.Check(user.FullName, check.Equals, "Example User")
714                         coll, err = conn.CollectionGet(ctx, arvados.GetOptions{UUID: coll.UUID})
715                         c.Assert(err, check.IsNil)
716                         c.Check(coll.ManifestText, check.Not(check.Equals), "")
717                         fs, err := coll.FileSystem(ac, kc)
718                         c.Assert(err, check.IsNil)
719                         f, err := fs.Open("test.txt")
720                         c.Assert(err, check.IsNil)
721                         buf, err := ioutil.ReadAll(f)
722                         c.Assert(err, check.IsNil)
723                         c.Check(buf, check.DeepEquals, []byte("IntegrationSuite.TestOIDCAccessTokenAuth"))
724                 }
725         }
726 }