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