Fix more golint warnings.
[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, err = 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                 // c.Check(err, check.IsNil)
356                 flen := strconv.Itoa(len(testText))
357                 c.Check(string(buf), check.Matches, `(?ms).*`+flen+` of `+flen+`.*`)
358         }
359 }
360
361 func (s *IntegrationSuite) TestGetCollectionAsAnonymous(c *check.C) {
362         conn1 := s.conn("z1111")
363         conn3 := s.conn("z3333")
364         rootctx1, rootac1, rootkc1 := s.rootClients("z1111")
365         anonctx3, anonac3, _ := s.anonymousClients("z3333")
366
367         // Make sure anonymous token was set
368         c.Assert(anonac3.AuthToken, check.Not(check.Equals), "")
369
370         // Create the collection to find its PDH (but don't save it
371         // anywhere yet)
372         var coll1 arvados.Collection
373         fs1, err := coll1.FileSystem(rootac1, rootkc1)
374         c.Assert(err, check.IsNil)
375         f, err := fs1.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
376         c.Assert(err, check.IsNil)
377         _, err = io.WriteString(f, "IntegrationSuite.TestGetCollectionAsAnonymous")
378         c.Assert(err, check.IsNil)
379         err = f.Close()
380         c.Assert(err, check.IsNil)
381         mtxt, err := fs1.MarshalManifest(".")
382         c.Assert(err, check.IsNil)
383         pdh := arvados.PortableDataHash(mtxt)
384
385         // Save the collection on cluster z1111.
386         coll1, err = conn1.CollectionCreate(rootctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
387                 "manifest_text": mtxt,
388         }})
389         c.Assert(err, check.IsNil)
390
391         // Share it with the anonymous users group.
392         var outLink arvados.Link
393         err = rootac1.RequestAndDecode(&outLink, "POST", "/arvados/v1/links", nil,
394                 map[string]interface{}{"link": map[string]interface{}{
395                         "link_class": "permission",
396                         "name":       "can_read",
397                         "tail_uuid":  "z1111-j7d0g-anonymouspublic",
398                         "head_uuid":  coll1.UUID,
399                 },
400                 })
401         c.Check(err, check.IsNil)
402
403         // Current user should be z3 anonymous user
404         outUser, err := anonac3.CurrentUser()
405         c.Check(err, check.IsNil)
406         c.Check(outUser.UUID, check.Equals, "z3333-tpzed-anonymouspublic")
407
408         // Get the token uuid
409         var outAuth arvados.APIClientAuthorization
410         err = anonac3.RequestAndDecode(&outAuth, "GET", "/arvados/v1/api_client_authorizations/current", nil, nil)
411         c.Check(err, check.IsNil)
412
413         // Make a v2 token of the z3 anonymous user, and use it on z1
414         _, anonac1, _ := s.clientsWithToken("z1111", outAuth.TokenV2())
415         outUser2, err := anonac1.CurrentUser()
416         c.Check(err, check.IsNil)
417         // z3 anonymous user will be mapped to the z1 anonymous user
418         c.Check(outUser2.UUID, check.Equals, "z1111-tpzed-anonymouspublic")
419
420         // Retrieve the collection (which is on z1) using anonymous from cluster z3333.
421         coll, err := conn3.CollectionGet(anonctx3, arvados.GetOptions{UUID: coll1.UUID})
422         c.Check(err, check.IsNil)
423         c.Check(coll.PortableDataHash, check.Equals, pdh)
424 }
425
426 // Get a token from the login cluster (z1111), use it to submit a
427 // container request on z2222.
428 func (s *IntegrationSuite) TestCreateContainerRequestWithFedToken(c *check.C) {
429         conn1 := s.conn("z1111")
430         rootctx1, _, _ := s.rootClients("z1111")
431         _, ac1, _, _ := s.userClients(rootctx1, c, conn1, "z1111", true)
432
433         // Use ac2 to get the discovery doc with a blank token, so the
434         // SDK doesn't magically pass the z1111 token to z2222 before
435         // we're ready to start our test.
436         _, ac2, _ := s.clientsWithToken("z2222", "")
437         var dd map[string]interface{}
438         err := ac2.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
439         c.Assert(err, check.IsNil)
440
441         var (
442                 body bytes.Buffer
443                 req  *http.Request
444                 resp *http.Response
445                 u    arvados.User
446                 cr   arvados.ContainerRequest
447         )
448         json.NewEncoder(&body).Encode(map[string]interface{}{
449                 "container_request": map[string]interface{}{
450                         "command":         []string{"echo"},
451                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
452                         "cwd":             "/",
453                         "output_path":     "/",
454                 },
455         })
456         ac2.AuthToken = ac1.AuthToken
457
458         c.Log("...post CR with good (but not yet cached) token")
459         cr = arvados.ContainerRequest{}
460         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
461         c.Assert(err, check.IsNil)
462         req.Header.Set("Content-Type", "application/json")
463         err = ac2.DoAndDecode(&cr, req)
464         c.Logf("err == %#v", err)
465
466         c.Log("...get user with good token")
467         u = arvados.User{}
468         req, err = http.NewRequest("GET", "https://"+ac2.APIHost+"/arvados/v1/users/current", nil)
469         c.Assert(err, check.IsNil)
470         err = ac2.DoAndDecode(&u, req)
471         c.Check(err, check.IsNil)
472         c.Check(u.UUID, check.Matches, "z1111-tpzed-.*")
473
474         c.Log("...post CR with good cached token")
475         cr = arvados.ContainerRequest{}
476         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
477         c.Assert(err, check.IsNil)
478         req.Header.Set("Content-Type", "application/json")
479         err = ac2.DoAndDecode(&cr, req)
480         c.Check(err, check.IsNil)
481         c.Check(cr.UUID, check.Matches, "z2222-.*")
482
483         c.Log("...post with good cached token ('OAuth2 ...')")
484         cr = arvados.ContainerRequest{}
485         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
486         c.Assert(err, check.IsNil)
487         req.Header.Set("Content-Type", "application/json")
488         req.Header.Set("Authorization", "OAuth2 "+ac2.AuthToken)
489         resp, err = arvados.InsecureHTTPClient.Do(req)
490         if c.Check(err, check.IsNil) {
491                 err = json.NewDecoder(resp.Body).Decode(&cr)
492                 c.Check(err, check.IsNil)
493                 c.Check(cr.UUID, check.Matches, "z2222-.*")
494         }
495 }
496
497 // Test for bug #16263
498 func (s *IntegrationSuite) TestListUsers(c *check.C) {
499         rootctx1, _, _ := s.rootClients("z1111")
500         conn1 := s.conn("z1111")
501         conn3 := s.conn("z3333")
502         userctx1, _, _, _ := s.userClients(rootctx1, c, conn1, "z1111", true)
503
504         // Make sure LoginCluster is properly configured
505         for cls := range s.testClusters {
506                 c.Check(
507                         s.testClusters[cls].config.Clusters[cls].Login.LoginCluster,
508                         check.Equals, "z1111",
509                         check.Commentf("incorrect LoginCluster config on cluster %q", cls))
510         }
511         // Make sure z1111 has users with NULL usernames
512         lst, err := conn1.UserList(rootctx1, arvados.ListOptions{
513                 Limit: math.MaxInt64, // check that large limit works (see #16263)
514         })
515         nullUsername := false
516         c.Assert(err, check.IsNil)
517         c.Assert(len(lst.Items), check.Not(check.Equals), 0)
518         for _, user := range lst.Items {
519                 if user.Username == "" {
520                         nullUsername = true
521                 }
522         }
523         c.Assert(nullUsername, check.Equals, true)
524
525         user1, err := conn1.UserGetCurrent(userctx1, arvados.GetOptions{})
526         c.Assert(err, check.IsNil)
527         c.Check(user1.IsActive, check.Equals, true)
528
529         // Ask for the user list on z3333 using z1111's system root token
530         lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
531         c.Assert(err, check.IsNil)
532         found := false
533         for _, user := range lst.Items {
534                 if user.UUID == user1.UUID {
535                         c.Check(user.IsActive, check.Equals, true)
536                         found = true
537                         break
538                 }
539         }
540         c.Check(found, check.Equals, true)
541
542         // Deactivate user acct on z1111
543         _, err = conn1.UserUnsetup(rootctx1, arvados.GetOptions{UUID: user1.UUID})
544         c.Assert(err, check.IsNil)
545
546         // Get user list from z3333, check the returned z1111 user is
547         // deactivated
548         lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
549         c.Assert(err, check.IsNil)
550         found = false
551         for _, user := range lst.Items {
552                 if user.UUID == user1.UUID {
553                         c.Check(user.IsActive, check.Equals, false)
554                         found = true
555                         break
556                 }
557         }
558         c.Check(found, check.Equals, true)
559
560         // Deactivated user can see is_active==false via "get current
561         // user" API
562         user1, err = conn3.UserGetCurrent(userctx1, arvados.GetOptions{})
563         c.Assert(err, check.IsNil)
564         c.Check(user1.IsActive, check.Equals, false)
565 }
566
567 func (s *IntegrationSuite) TestSetupUserWithVM(c *check.C) {
568         conn1 := s.conn("z1111")
569         conn3 := s.conn("z3333")
570         rootctx1, rootac1, _ := s.rootClients("z1111")
571
572         // Create user on LoginCluster z1111
573         _, _, _, user := s.userClients(rootctx1, c, conn1, "z1111", false)
574
575         // Make a new root token (because rootClients() uses SystemRootToken)
576         var outAuth arvados.APIClientAuthorization
577         err := rootac1.RequestAndDecode(&outAuth, "POST", "/arvados/v1/api_client_authorizations", nil, nil)
578         c.Check(err, check.IsNil)
579
580         // Make a v2 root token to communicate with z3333
581         rootctx3, rootac3, _ := s.clientsWithToken("z3333", outAuth.TokenV2())
582
583         // Create VM on z3333
584         var outVM arvados.VirtualMachine
585         err = rootac3.RequestAndDecode(&outVM, "POST", "/arvados/v1/virtual_machines", nil,
586                 map[string]interface{}{"virtual_machine": map[string]interface{}{
587                         "hostname": "example",
588                 },
589                 })
590         c.Check(outVM.UUID[0:5], check.Equals, "z3333")
591         c.Check(err, check.IsNil)
592
593         // Make sure z3333 user list is up to date
594         _, err = conn3.UserList(rootctx3, arvados.ListOptions{Limit: 1000})
595         c.Check(err, check.IsNil)
596
597         // Try to set up user on z3333 with the VM
598         _, err = conn3.UserSetup(rootctx3, arvados.UserSetupOptions{UUID: user.UUID, VMUUID: outVM.UUID})
599         c.Check(err, check.IsNil)
600
601         var outLinks arvados.LinkList
602         err = rootac3.RequestAndDecode(&outLinks, "GET", "/arvados/v1/links", nil,
603                 arvados.ListOptions{
604                         Limit: 1000,
605                         Filters: []arvados.Filter{
606                                 {
607                                         Attr:     "tail_uuid",
608                                         Operator: "=",
609                                         Operand:  user.UUID,
610                                 },
611                                 {
612                                         Attr:     "head_uuid",
613                                         Operator: "=",
614                                         Operand:  outVM.UUID,
615                                 },
616                                 {
617                                         Attr:     "name",
618                                         Operator: "=",
619                                         Operand:  "can_login",
620                                 },
621                                 {
622                                         Attr:     "link_class",
623                                         Operator: "=",
624                                         Operand:  "permission",
625                                 }}})
626         c.Check(err, check.IsNil)
627
628         c.Check(len(outLinks.Items), check.Equals, 1)
629 }
630
631 func (s *IntegrationSuite) TestOIDCAccessTokenAuth(c *check.C) {
632         conn1 := s.conn("z1111")
633         rootctx1, _, _ := s.rootClients("z1111")
634         s.userClients(rootctx1, c, conn1, "z1111", true)
635
636         accesstoken := s.oidcprovider.ValidAccessToken()
637
638         for _, clusterid := range []string{"z1111", "z2222"} {
639                 c.Logf("trying clusterid %s", clusterid)
640
641                 conn := s.conn(clusterid)
642                 ctx, ac, kc := s.clientsWithToken(clusterid, accesstoken)
643
644                 var coll arvados.Collection
645
646                 // Write some file data and create a collection
647                 {
648                         fs, err := coll.FileSystem(ac, kc)
649                         c.Assert(err, check.IsNil)
650                         f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
651                         c.Assert(err, check.IsNil)
652                         _, err = io.WriteString(f, "IntegrationSuite.TestOIDCAccessTokenAuth")
653                         c.Assert(err, check.IsNil)
654                         err = f.Close()
655                         c.Assert(err, check.IsNil)
656                         mtxt, err := fs.MarshalManifest(".")
657                         c.Assert(err, check.IsNil)
658                         coll, err = conn.CollectionCreate(ctx, arvados.CreateOptions{Attrs: map[string]interface{}{
659                                 "manifest_text": mtxt,
660                         }})
661                         c.Assert(err, check.IsNil)
662                 }
663
664                 // Read the collection & file data
665                 {
666                         user, err := conn.UserGetCurrent(ctx, arvados.GetOptions{})
667                         c.Assert(err, check.IsNil)
668                         c.Check(user.FullName, check.Equals, "Example User")
669                         coll, err = conn.CollectionGet(ctx, arvados.GetOptions{UUID: coll.UUID})
670                         c.Assert(err, check.IsNil)
671                         c.Check(coll.ManifestText, check.Not(check.Equals), "")
672                         fs, err := coll.FileSystem(ac, kc)
673                         c.Assert(err, check.IsNil)
674                         f, err := fs.Open("test.txt")
675                         c.Assert(err, check.IsNil)
676                         buf, err := ioutil.ReadAll(f)
677                         c.Assert(err, check.IsNil)
678                         c.Check(buf, check.DeepEquals, []byte("IntegrationSuite.TestOIDCAccessTokenAuth"))
679                 }
680         }
681 }