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