17717: Merge branch 'master' into 17717-costanalyzer-date-mode
[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         "fmt"
13         "io"
14         "io/ioutil"
15         "math"
16         "net"
17         "net/http"
18         "os"
19         "os/exec"
20         "path/filepath"
21         "strconv"
22         "strings"
23
24         "git.arvados.org/arvados.git/lib/boot"
25         "git.arvados.org/arvados.git/lib/config"
26         "git.arvados.org/arvados.git/sdk/go/arvados"
27         "git.arvados.org/arvados.git/sdk/go/arvadostest"
28         "git.arvados.org/arvados.git/sdk/go/ctxlog"
29         check "gopkg.in/check.v1"
30 )
31
32 var _ = check.Suite(&IntegrationSuite{})
33
34 type IntegrationSuite struct {
35         testClusters map[string]*boot.TestCluster
36         oidcprovider *arvadostest.OIDCProvider
37 }
38
39 func (s *IntegrationSuite) SetUpSuite(c *check.C) {
40         cwd, _ := os.Getwd()
41
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"
48
49         s.testClusters = map[string]*boot.TestCluster{
50                 "z1111": nil,
51                 "z2222": nil,
52                 "z3333": nil,
53         }
54         hostport := map[string]string{}
55         for id := range s.testClusters {
56                 hostport[id] = func() string {
57                         // TODO: Instead of expecting random ports on
58                         // 127.0.0.11, 22, 33 to be race-safe, try
59                         // different 127.x.y.z until finding one that
60                         // isn't in use.
61                         ln, err := net.Listen("tcp", ":0")
62                         c.Assert(err, check.IsNil)
63                         ln.Close()
64                         _, port, err := net.SplitHostPort(ln.Addr().String())
65                         c.Assert(err, check.IsNil)
66                         return "127.0.0." + id[3:] + ":" + port
67                 }()
68         }
69         for id := range s.testClusters {
70                 yaml := `Clusters:
71   ` + id + `:
72     Services:
73       Controller:
74         ExternalURL: https://` + hostport[id] + `
75     TLS:
76       Insecure: true
77     SystemLogs:
78       Format: text
79     RemoteClusters:
80       z1111:
81         Host: ` + hostport["z1111"] + `
82         Scheme: https
83         Insecure: true
84         Proxy: true
85         ActivateUsers: true
86 `
87                 if id != "z2222" {
88                         yaml += `      z2222:
89         Host: ` + hostport["z2222"] + `
90         Scheme: https
91         Insecure: true
92         Proxy: true
93         ActivateUsers: true
94 `
95                 }
96                 if id != "z3333" {
97                         yaml += `      z3333:
98         Host: ` + hostport["z3333"] + `
99         Scheme: https
100         Insecure: true
101         Proxy: true
102         ActivateUsers: true
103 `
104                 }
105                 if id == "z1111" {
106                         yaml += `
107     Login:
108       LoginCluster: z1111
109       OpenIDConnect:
110         Enable: true
111         Issuer: ` + s.oidcprovider.Issuer.URL + `
112         ClientID: ` + s.oidcprovider.ValidClientID + `
113         ClientSecret: ` + s.oidcprovider.ValidClientSecret + `
114         EmailClaim: email
115         EmailVerifiedClaim: email_verified
116         AcceptAccessToken: true
117         AcceptAccessTokenScope: ""
118 `
119                 } else {
120                         yaml += `
121     Login:
122       LoginCluster: z1111
123 `
124                 }
125
126                 loader := config.NewLoader(bytes.NewBufferString(yaml), ctxlog.TestLogger(c))
127                 loader.Path = "-"
128                 loader.SkipLegacy = true
129                 loader.SkipAPICalls = true
130                 cfg, err := loader.Load()
131                 c.Assert(err, check.IsNil)
132                 tc := boot.NewTestCluster(
133                         filepath.Join(cwd, "..", ".."),
134                         id, cfg, "127.0.0."+id[3:], c.Log)
135                 tc.Super.NoWorkbench1 = true
136                 tc.Start()
137                 s.testClusters[id] = tc
138         }
139         for _, tc := range s.testClusters {
140                 ok := tc.WaitReady()
141                 c.Assert(ok, check.Equals, true)
142         }
143 }
144
145 func (s *IntegrationSuite) TearDownSuite(c *check.C) {
146         for _, c := range s.testClusters {
147                 c.Super.Stop()
148         }
149 }
150
151 func (s *IntegrationSuite) TestGetCollectionByPDH(c *check.C) {
152         conn1 := s.testClusters["z1111"].Conn()
153         rootctx1, _, _ := s.testClusters["z1111"].RootClients()
154         conn3 := s.testClusters["z3333"].Conn()
155         userctx1, ac1, kc1, _ := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
156
157         // Create the collection to find its PDH (but don't save it
158         // anywhere yet)
159         var coll1 arvados.Collection
160         fs1, err := coll1.FileSystem(ac1, kc1)
161         c.Assert(err, check.IsNil)
162         f, err := fs1.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
163         c.Assert(err, check.IsNil)
164         _, err = io.WriteString(f, "IntegrationSuite.TestGetCollectionByPDH")
165         c.Assert(err, check.IsNil)
166         err = f.Close()
167         c.Assert(err, check.IsNil)
168         mtxt, err := fs1.MarshalManifest(".")
169         c.Assert(err, check.IsNil)
170         pdh := arvados.PortableDataHash(mtxt)
171
172         // Looking up the PDH before saving returns 404 if cycle
173         // detection is working.
174         _, err = conn1.CollectionGet(userctx1, arvados.GetOptions{UUID: pdh})
175         c.Assert(err, check.ErrorMatches, `.*404 Not Found.*`)
176
177         // Save the collection on cluster z1111.
178         coll1, err = conn1.CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
179                 "manifest_text": mtxt,
180         }})
181         c.Assert(err, check.IsNil)
182
183         // Retrieve the collection from cluster z3333.
184         coll, err := conn3.CollectionGet(userctx1, arvados.GetOptions{UUID: pdh})
185         c.Check(err, check.IsNil)
186         c.Check(coll.PortableDataHash, check.Equals, pdh)
187 }
188
189 func (s *IntegrationSuite) TestS3WithFederatedToken(c *check.C) {
190         if _, err := exec.LookPath("s3cmd"); err != nil {
191                 c.Skip("s3cmd not in PATH")
192                 return
193         }
194
195         testText := "IntegrationSuite.TestS3WithFederatedToken"
196
197         conn1 := s.testClusters["z1111"].Conn()
198         rootctx1, _, _ := s.testClusters["z1111"].RootClients()
199         userctx1, ac1, _, _ := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
200         conn3 := s.testClusters["z3333"].Conn()
201
202         createColl := func(clusterID string) arvados.Collection {
203                 _, ac, kc := s.testClusters[clusterID].ClientsWithToken(ac1.AuthToken)
204                 var coll arvados.Collection
205                 fs, err := coll.FileSystem(ac, kc)
206                 c.Assert(err, check.IsNil)
207                 f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
208                 c.Assert(err, check.IsNil)
209                 _, err = io.WriteString(f, testText)
210                 c.Assert(err, check.IsNil)
211                 err = f.Close()
212                 c.Assert(err, check.IsNil)
213                 mtxt, err := fs.MarshalManifest(".")
214                 c.Assert(err, check.IsNil)
215                 coll, err = s.testClusters[clusterID].Conn().CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
216                         "manifest_text": mtxt,
217                 }})
218                 c.Assert(err, check.IsNil)
219                 return coll
220         }
221
222         for _, trial := range []struct {
223                 clusterID string // create the collection on this cluster (then use z3333 to access it)
224                 token     string
225         }{
226                 // Try the hardest test first: z3333 hasn't seen
227                 // z1111's token yet, and we're just passing the
228                 // opaque secret part, so z3333 has to guess that it
229                 // belongs to z1111.
230                 {"z1111", strings.Split(ac1.AuthToken, "/")[2]},
231                 {"z3333", strings.Split(ac1.AuthToken, "/")[2]},
232                 {"z1111", strings.Replace(ac1.AuthToken, "/", "_", -1)},
233                 {"z3333", strings.Replace(ac1.AuthToken, "/", "_", -1)},
234         } {
235                 c.Logf("================ %v", trial)
236                 coll := createColl(trial.clusterID)
237
238                 cfgjson, err := conn3.ConfigGet(userctx1)
239                 c.Assert(err, check.IsNil)
240                 var cluster arvados.Cluster
241                 err = json.Unmarshal(cfgjson, &cluster)
242                 c.Assert(err, check.IsNil)
243
244                 c.Logf("TokenV2 is %s", ac1.AuthToken)
245                 host := cluster.Services.WebDAV.ExternalURL.Host
246                 s3args := []string{
247                         "--ssl", "--no-check-certificate",
248                         "--host=" + host, "--host-bucket=" + host,
249                         "--access_key=" + trial.token, "--secret_key=" + trial.token,
250                 }
251                 buf, err := exec.Command("s3cmd", append(s3args, "ls", "s3://"+coll.UUID)...).CombinedOutput()
252                 c.Check(err, check.IsNil)
253                 c.Check(string(buf), check.Matches, `.* `+fmt.Sprintf("%d", len(testText))+` +s3://`+coll.UUID+`/test.txt\n`)
254
255                 buf, _ = exec.Command("s3cmd", append(s3args, "get", "s3://"+coll.UUID+"/test.txt", c.MkDir()+"/tmpfile")...).CombinedOutput()
256                 // Command fails because we don't return Etag header.
257                 flen := strconv.Itoa(len(testText))
258                 c.Check(string(buf), check.Matches, `(?ms).*`+flen+` (bytes in|of `+flen+`).*`)
259         }
260 }
261
262 func (s *IntegrationSuite) TestGetCollectionAsAnonymous(c *check.C) {
263         conn1 := s.testClusters["z1111"].Conn()
264         conn3 := s.testClusters["z3333"].Conn()
265         rootctx1, rootac1, rootkc1 := s.testClusters["z1111"].RootClients()
266         anonctx3, anonac3, _ := s.testClusters["z3333"].AnonymousClients()
267
268         // Make sure anonymous token was set
269         c.Assert(anonac3.AuthToken, check.Not(check.Equals), "")
270
271         // Create the collection to find its PDH (but don't save it
272         // anywhere yet)
273         var coll1 arvados.Collection
274         fs1, err := coll1.FileSystem(rootac1, rootkc1)
275         c.Assert(err, check.IsNil)
276         f, err := fs1.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
277         c.Assert(err, check.IsNil)
278         _, err = io.WriteString(f, "IntegrationSuite.TestGetCollectionAsAnonymous")
279         c.Assert(err, check.IsNil)
280         err = f.Close()
281         c.Assert(err, check.IsNil)
282         mtxt, err := fs1.MarshalManifest(".")
283         c.Assert(err, check.IsNil)
284         pdh := arvados.PortableDataHash(mtxt)
285
286         // Save the collection on cluster z1111.
287         coll1, err = conn1.CollectionCreate(rootctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
288                 "manifest_text": mtxt,
289         }})
290         c.Assert(err, check.IsNil)
291
292         // Share it with the anonymous users group.
293         var outLink arvados.Link
294         err = rootac1.RequestAndDecode(&outLink, "POST", "/arvados/v1/links", nil,
295                 map[string]interface{}{"link": map[string]interface{}{
296                         "link_class": "permission",
297                         "name":       "can_read",
298                         "tail_uuid":  "z1111-j7d0g-anonymouspublic",
299                         "head_uuid":  coll1.UUID,
300                 },
301                 })
302         c.Check(err, check.IsNil)
303
304         // Current user should be z3 anonymous user
305         outUser, err := anonac3.CurrentUser()
306         c.Check(err, check.IsNil)
307         c.Check(outUser.UUID, check.Equals, "z3333-tpzed-anonymouspublic")
308
309         // Get the token uuid
310         var outAuth arvados.APIClientAuthorization
311         err = anonac3.RequestAndDecode(&outAuth, "GET", "/arvados/v1/api_client_authorizations/current", nil, nil)
312         c.Check(err, check.IsNil)
313
314         // Make a v2 token of the z3 anonymous user, and use it on z1
315         _, anonac1, _ := s.testClusters["z1111"].ClientsWithToken(outAuth.TokenV2())
316         outUser2, err := anonac1.CurrentUser()
317         c.Check(err, check.IsNil)
318         // z3 anonymous user will be mapped to the z1 anonymous user
319         c.Check(outUser2.UUID, check.Equals, "z1111-tpzed-anonymouspublic")
320
321         // Retrieve the collection (which is on z1) using anonymous from cluster z3333.
322         coll, err := conn3.CollectionGet(anonctx3, arvados.GetOptions{UUID: coll1.UUID})
323         c.Check(err, check.IsNil)
324         c.Check(coll.PortableDataHash, check.Equals, pdh)
325 }
326
327 // Get a token from the login cluster (z1111), use it to submit a
328 // container request on z2222.
329 func (s *IntegrationSuite) TestCreateContainerRequestWithFedToken(c *check.C) {
330         conn1 := s.testClusters["z1111"].Conn()
331         rootctx1, _, _ := s.testClusters["z1111"].RootClients()
332         _, ac1, _, _ := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
333
334         // Use ac2 to get the discovery doc with a blank token, so the
335         // SDK doesn't magically pass the z1111 token to z2222 before
336         // we're ready to start our test.
337         _, ac2, _ := s.testClusters["z2222"].ClientsWithToken("")
338         var dd map[string]interface{}
339         err := ac2.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
340         c.Assert(err, check.IsNil)
341
342         var (
343                 body bytes.Buffer
344                 req  *http.Request
345                 resp *http.Response
346                 u    arvados.User
347                 cr   arvados.ContainerRequest
348         )
349         json.NewEncoder(&body).Encode(map[string]interface{}{
350                 "container_request": map[string]interface{}{
351                         "command":         []string{"echo"},
352                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
353                         "cwd":             "/",
354                         "output_path":     "/",
355                 },
356         })
357         ac2.AuthToken = ac1.AuthToken
358
359         c.Log("...post CR with good (but not yet cached) token")
360         cr = arvados.ContainerRequest{}
361         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
362         c.Assert(err, check.IsNil)
363         req.Header.Set("Content-Type", "application/json")
364         err = ac2.DoAndDecode(&cr, req)
365         c.Assert(err, check.IsNil)
366         c.Logf("err == %#v", err)
367
368         c.Log("...get user with good token")
369         u = arvados.User{}
370         req, err = http.NewRequest("GET", "https://"+ac2.APIHost+"/arvados/v1/users/current", nil)
371         c.Assert(err, check.IsNil)
372         err = ac2.DoAndDecode(&u, req)
373         c.Check(err, check.IsNil)
374         c.Check(u.UUID, check.Matches, "z1111-tpzed-.*")
375
376         c.Log("...post CR with good cached token")
377         cr = arvados.ContainerRequest{}
378         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
379         c.Assert(err, check.IsNil)
380         req.Header.Set("Content-Type", "application/json")
381         err = ac2.DoAndDecode(&cr, req)
382         c.Check(err, check.IsNil)
383         c.Check(cr.UUID, check.Matches, "z2222-.*")
384
385         c.Log("...post with good cached token ('OAuth2 ...')")
386         cr = arvados.ContainerRequest{}
387         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
388         c.Assert(err, check.IsNil)
389         req.Header.Set("Content-Type", "application/json")
390         req.Header.Set("Authorization", "OAuth2 "+ac2.AuthToken)
391         resp, err = arvados.InsecureHTTPClient.Do(req)
392         c.Assert(err, check.IsNil)
393         err = json.NewDecoder(resp.Body).Decode(&cr)
394         c.Check(err, check.IsNil)
395         c.Check(cr.UUID, check.Matches, "z2222-.*")
396 }
397
398 func (s *IntegrationSuite) TestCreateContainerRequestWithBadToken(c *check.C) {
399         conn1 := s.testClusters["z1111"].Conn()
400         rootctx1, _, _ := s.testClusters["z1111"].RootClients()
401         _, ac1, _, au := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, "user@example.com", true)
402
403         tests := []struct {
404                 name         string
405                 token        string
406                 expectedCode int
407         }{
408                 {"Good token", ac1.AuthToken, http.StatusOK},
409                 {"Bogus token", "abcdef", http.StatusUnauthorized},
410                 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", http.StatusUnauthorized},
411                 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", http.StatusUnauthorized},
412         }
413
414         body, _ := json.Marshal(map[string]interface{}{
415                 "container_request": map[string]interface{}{
416                         "command":         []string{"echo"},
417                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
418                         "cwd":             "/",
419                         "output_path":     "/",
420                 },
421         })
422
423         for _, tt := range tests {
424                 c.Log(c.TestName() + " " + tt.name)
425                 ac1.AuthToken = tt.token
426                 req, err := http.NewRequest("POST", "https://"+ac1.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body))
427                 c.Assert(err, check.IsNil)
428                 req.Header.Set("Content-Type", "application/json")
429                 resp, err := ac1.Do(req)
430                 c.Assert(err, check.IsNil)
431                 c.Assert(resp.StatusCode, check.Equals, tt.expectedCode)
432         }
433 }
434
435 // We test the direct access to the database
436 // normally an integration test would not have a database access, but  in this case we need
437 // to test tokens that are secret, so there is no API response that will give them back
438 func (s *IntegrationSuite) dbConn(c *check.C, clusterID string) (*sql.DB, *sql.Conn) {
439         ctx := context.Background()
440         db, err := sql.Open("postgres", s.testClusters[clusterID].Super.Cluster().PostgreSQL.Connection.String())
441         c.Assert(err, check.IsNil)
442
443         conn, err := db.Conn(ctx)
444         c.Assert(err, check.IsNil)
445
446         rows, err := conn.ExecContext(ctx, `SELECT 1`)
447         c.Assert(err, check.IsNil)
448         n, err := rows.RowsAffected()
449         c.Assert(err, check.IsNil)
450         c.Assert(n, check.Equals, int64(1))
451         return db, conn
452 }
453
454 // TestRuntimeTokenInCR will test several different tokens in the runtime attribute
455 // and check the expected results accessing directly to the database if needed.
456 func (s *IntegrationSuite) TestRuntimeTokenInCR(c *check.C) {
457         db, dbconn := s.dbConn(c, "z1111")
458         defer db.Close()
459         defer dbconn.Close()
460         conn1 := s.testClusters["z1111"].Conn()
461         rootctx1, _, _ := s.testClusters["z1111"].RootClients()
462         userctx1, ac1, _, au := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, "user@example.com", true)
463
464         tests := []struct {
465                 name                 string
466                 token                string
467                 expectAToGetAValidCR bool
468                 expectedToken        *string
469         }{
470                 {"Good token z1111 user", ac1.AuthToken, true, &ac1.AuthToken},
471                 {"Bogus token", "abcdef", false, nil},
472                 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", false, nil},
473                 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", false, nil},
474         }
475
476         for _, tt := range tests {
477                 c.Log(c.TestName() + " " + tt.name)
478
479                 rq := map[string]interface{}{
480                         "command":         []string{"echo"},
481                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
482                         "cwd":             "/",
483                         "output_path":     "/",
484                         "runtime_token":   tt.token,
485                 }
486                 cr, err := conn1.ContainerRequestCreate(userctx1, arvados.CreateOptions{Attrs: rq})
487                 if tt.expectAToGetAValidCR {
488                         c.Check(err, check.IsNil)
489                         c.Check(cr, check.NotNil)
490                         c.Check(cr.UUID, check.Not(check.Equals), "")
491                 }
492
493                 if tt.expectedToken == nil {
494                         continue
495                 }
496
497                 c.Logf("cr.UUID: %s", cr.UUID)
498                 row := dbconn.QueryRowContext(rootctx1, `SELECT runtime_token from container_requests where uuid=$1`, cr.UUID)
499                 c.Check(row, check.NotNil)
500                 var token sql.NullString
501                 row.Scan(&token)
502                 if c.Check(token.Valid, check.Equals, true) {
503                         c.Check(token.String, check.Equals, *tt.expectedToken)
504                 }
505         }
506 }
507
508 // TestIntermediateCluster will send a container request to
509 // one cluster with another cluster as the destination
510 // and check the tokens are being handled properly
511 func (s *IntegrationSuite) TestIntermediateCluster(c *check.C) {
512         conn1 := s.testClusters["z1111"].Conn()
513         rootctx1, _, _ := s.testClusters["z1111"].RootClients()
514         uctx1, ac1, _, _ := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, "user@example.com", true)
515
516         tests := []struct {
517                 name                 string
518                 token                string
519                 expectedRuntimeToken string
520                 expectedUUIDprefix   string
521         }{
522                 {"Good token z1111 user sending a CR to z2222", ac1.AuthToken, "", "z2222-xvhdp-"},
523         }
524
525         for _, tt := range tests {
526                 c.Log(c.TestName() + " " + tt.name)
527                 rq := map[string]interface{}{
528                         "command":         []string{"echo"},
529                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
530                         "cwd":             "/",
531                         "output_path":     "/",
532                         "runtime_token":   tt.token,
533                 }
534                 cr, err := conn1.ContainerRequestCreate(uctx1, arvados.CreateOptions{ClusterID: "z2222", Attrs: rq})
535
536                 c.Check(err, check.IsNil)
537                 c.Check(strings.HasPrefix(cr.UUID, tt.expectedUUIDprefix), check.Equals, true)
538                 c.Check(cr.RuntimeToken, check.Equals, tt.expectedRuntimeToken)
539         }
540 }
541
542 // Test for bug #16263
543 func (s *IntegrationSuite) TestListUsers(c *check.C) {
544         rootctx1, _, _ := s.testClusters["z1111"].RootClients()
545         conn1 := s.testClusters["z1111"].Conn()
546         conn3 := s.testClusters["z3333"].Conn()
547         userctx1, _, _, _ := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, s.oidcprovider.AuthEmail, 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.testClusters["z1111"].Conn()
614         conn3 := s.testClusters["z3333"].Conn()
615         rootctx1, rootac1, _ := s.testClusters["z1111"].RootClients()
616
617         // Create user on LoginCluster z1111
618         _, _, _, user := s.testClusters["z1111"].UserClients(rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
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.testClusters["z3333"].ClientsWithToken(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.testClusters["z1111"].Conn()
678         rootctx1, _, _ := s.testClusters["z1111"].RootClients()
679         s.testClusters["z1111"].UserClients(rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
680
681         accesstoken := s.oidcprovider.ValidAccessToken()
682
683         for _, clusterID := range []string{"z1111", "z2222"} {
684
685                 var coll arvados.Collection
686
687                 // Write some file data and create a collection
688                 {
689                         c.Logf("save collection to %s", clusterID)
690
691                         conn := s.testClusters[clusterID].Conn()
692                         ctx, ac, kc := s.testClusters[clusterID].ClientsWithToken(accesstoken)
693
694                         fs, err := coll.FileSystem(ac, kc)
695                         c.Assert(err, check.IsNil)
696                         f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
697                         c.Assert(err, check.IsNil)
698                         _, err = io.WriteString(f, "IntegrationSuite.TestOIDCAccessTokenAuth")
699                         c.Assert(err, check.IsNil)
700                         err = f.Close()
701                         c.Assert(err, check.IsNil)
702                         mtxt, err := fs.MarshalManifest(".")
703                         c.Assert(err, check.IsNil)
704                         coll, err = conn.CollectionCreate(ctx, arvados.CreateOptions{Attrs: map[string]interface{}{
705                                 "manifest_text": mtxt,
706                         }})
707                         c.Assert(err, check.IsNil)
708                 }
709
710                 // Read the collection & file data -- both from the
711                 // cluster where it was created, and from the other
712                 // cluster.
713                 for _, readClusterID := range []string{"z1111", "z2222", "z3333"} {
714                         c.Logf("retrieve %s from %s", coll.UUID, readClusterID)
715
716                         conn := s.testClusters[readClusterID].Conn()
717                         ctx, ac, kc := s.testClusters[readClusterID].ClientsWithToken(accesstoken)
718
719                         user, err := conn.UserGetCurrent(ctx, arvados.GetOptions{})
720                         c.Assert(err, check.IsNil)
721                         c.Check(user.FullName, check.Equals, "Example User")
722                         readcoll, err := conn.CollectionGet(ctx, arvados.GetOptions{UUID: coll.UUID})
723                         c.Assert(err, check.IsNil)
724                         c.Check(readcoll.ManifestText, check.Not(check.Equals), "")
725                         fs, err := readcoll.FileSystem(ac, kc)
726                         c.Assert(err, check.IsNil)
727                         f, err := fs.Open("test.txt")
728                         c.Assert(err, check.IsNil)
729                         buf, err := ioutil.ReadAll(f)
730                         c.Assert(err, check.IsNil)
731                         c.Check(buf, check.DeepEquals, []byte("IntegrationSuite.TestOIDCAccessTokenAuth"))
732                 }
733         }
734 }