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