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