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