addressing https://dev.arvados.org/issues/17014#note-41
[arvados.git] / lib / controller / integration_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package controller
6
7 import (
8         "bytes"
9         "context"
10         "database/sql"
11         "encoding/json"
12         "fmt"
13         "io"
14         "io/ioutil"
15         "math"
16         "net"
17         "net/http"
18         "net/url"
19         "os"
20         "os/exec"
21         "path/filepath"
22         "strconv"
23         "strings"
24
25         "git.arvados.org/arvados.git/lib/boot"
26         "git.arvados.org/arvados.git/lib/config"
27         "git.arvados.org/arvados.git/lib/controller/rpc"
28         "git.arvados.org/arvados.git/lib/service"
29         "git.arvados.org/arvados.git/sdk/go/arvados"
30         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
31         "git.arvados.org/arvados.git/sdk/go/arvadostest"
32         "git.arvados.org/arvados.git/sdk/go/auth"
33         "git.arvados.org/arvados.git/sdk/go/ctxlog"
34         "git.arvados.org/arvados.git/sdk/go/keepclient"
35         check "gopkg.in/check.v1"
36 )
37
38 var _ = check.Suite(&IntegrationSuite{})
39
40 type testCluster struct {
41         super         boot.Supervisor
42         config        arvados.Config
43         controllerURL *url.URL
44 }
45
46 type IntegrationSuite struct {
47         testClusters map[string]*testCluster
48         oidcprovider *arvadostest.OIDCProvider
49 }
50
51 func (s *IntegrationSuite) SetUpSuite(c *check.C) {
52         if forceLegacyAPI14 {
53                 c.Skip("heavy integration tests don't run with forceLegacyAPI14")
54                 return
55         }
56
57         cwd, _ := os.Getwd()
58
59         s.oidcprovider = arvadostest.NewOIDCProvider(c)
60         s.oidcprovider.AuthEmail = "user@example.com"
61         s.oidcprovider.AuthEmailVerified = true
62         s.oidcprovider.AuthName = "Example User"
63         s.oidcprovider.ValidClientID = "clientid"
64         s.oidcprovider.ValidClientSecret = "clientsecret"
65
66         s.testClusters = map[string]*testCluster{
67                 "z1111": nil,
68                 "z2222": nil,
69                 "z3333": nil,
70         }
71         hostport := map[string]string{}
72         for id := range s.testClusters {
73                 hostport[id] = func() string {
74                         // TODO: Instead of expecting random ports on
75                         // 127.0.0.11, 22, 33 to be race-safe, try
76                         // different 127.x.y.z until finding one that
77                         // isn't in use.
78                         ln, err := net.Listen("tcp", ":0")
79                         c.Assert(err, check.IsNil)
80                         ln.Close()
81                         _, port, err := net.SplitHostPort(ln.Addr().String())
82                         c.Assert(err, check.IsNil)
83                         return "127.0.0." + id[3:] + ":" + port
84                 }()
85         }
86         for id := range s.testClusters {
87                 yaml := `Clusters:
88   ` + id + `:
89     Services:
90       Controller:
91         ExternalURL: https://` + hostport[id] + `
92     TLS:
93       Insecure: true
94     Login:
95       LoginCluster: z1111
96     SystemLogs:
97       Format: text
98     RemoteClusters:
99       z1111:
100         Host: ` + hostport["z1111"] + `
101         Scheme: https
102         Insecure: true
103         Proxy: true
104         ActivateUsers: true
105 `
106                 if id != "z2222" {
107                         yaml += `      z2222:
108         Host: ` + hostport["z2222"] + `
109         Scheme: https
110         Insecure: true
111         Proxy: true
112         ActivateUsers: true
113 `
114                 }
115                 if id != "z3333" {
116                         yaml += `      z3333:
117         Host: ` + hostport["z3333"] + `
118         Scheme: https
119         Insecure: true
120         Proxy: true
121         ActivateUsers: true
122 `
123                 }
124                 if id == "z1111" {
125                         yaml += `
126     Login:
127       LoginCluster: z1111
128       OpenIDConnect:
129         Enable: true
130         Issuer: ` + s.oidcprovider.Issuer.URL + `
131         ClientID: ` + s.oidcprovider.ValidClientID + `
132         ClientSecret: ` + s.oidcprovider.ValidClientSecret + `
133         EmailClaim: email
134         EmailVerifiedClaim: email_verified
135 `
136                 } else {
137                         yaml += `
138     Login:
139       LoginCluster: z1111
140 `
141                 }
142
143                 loader := config.NewLoader(bytes.NewBufferString(yaml), ctxlog.TestLogger(c))
144                 loader.Path = "-"
145                 loader.SkipLegacy = true
146                 loader.SkipAPICalls = true
147                 cfg, err := loader.Load()
148                 c.Assert(err, check.IsNil)
149                 s.testClusters[id] = &testCluster{
150                         super: boot.Supervisor{
151                                 SourcePath:           filepath.Join(cwd, "..", ".."),
152                                 ClusterType:          "test",
153                                 ListenHost:           "127.0.0." + id[3:],
154                                 ControllerAddr:       ":0",
155                                 OwnTemporaryDatabase: true,
156                                 Stderr:               &service.LogPrefixer{Writer: ctxlog.LogWriter(c.Log), Prefix: []byte("[" + id + "] ")},
157                         },
158                         config: *cfg,
159                 }
160                 s.testClusters[id].super.Start(context.Background(), &s.testClusters[id].config, "-")
161         }
162         for _, tc := range s.testClusters {
163                 au, ok := tc.super.WaitReady()
164                 c.Assert(ok, check.Equals, true)
165                 u := url.URL(*au)
166                 tc.controllerURL = &u
167         }
168 }
169
170 func (s *IntegrationSuite) TearDownSuite(c *check.C) {
171         for _, c := range s.testClusters {
172                 c.super.Stop()
173         }
174 }
175
176 // Get rpc connection struct initialized to communicate with the
177 // specified cluster.
178 func (s *IntegrationSuite) conn(clusterID string) *rpc.Conn {
179         return rpc.NewConn(clusterID, s.testClusters[clusterID].controllerURL, true, rpc.PassthroughTokenProvider)
180 }
181
182 // Return Context, Arvados.Client and keepclient structs initialized
183 // to connect to the specified cluster (by clusterID) using with the supplied
184 // Arvados token.
185 func (s *IntegrationSuite) clientsWithToken(clusterID string, token string) (context.Context, *arvados.Client, *keepclient.KeepClient) {
186         cl := s.testClusters[clusterID].config.Clusters[clusterID]
187         ctx := auth.NewContext(context.Background(), auth.NewCredentials(token))
188         ac, err := arvados.NewClientFromConfig(&cl)
189         if err != nil {
190                 panic(err)
191         }
192         ac.AuthToken = token
193         arv, err := arvadosclient.New(ac)
194         if err != nil {
195                 panic(err)
196         }
197         kc := keepclient.New(arv)
198         return ctx, ac, kc
199 }
200
201 // Log in as a user called "example", get the user's API token,
202 // initialize clients with the API token, set up the user and
203 // optionally activate the user.  Return client structs for
204 // communicating with the cluster on behalf of the 'example' user.
205 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) {
206         login, err := conn.UserSessionCreate(rootctx, rpc.UserSessionCreateOptions{
207                 ReturnTo: ",https://example.com",
208                 AuthInfo: rpc.UserSessionAuthInfo{
209                         Email:     "user@example.com",
210                         FirstName: "Example",
211                         LastName:  "User",
212                         Username:  "example",
213                 },
214         })
215         c.Assert(err, check.IsNil)
216         redirURL, err := url.Parse(login.RedirectLocation)
217         c.Assert(err, check.IsNil)
218         userToken := redirURL.Query().Get("api_token")
219         c.Logf("user token: %q", userToken)
220         ctx, ac, kc := s.clientsWithToken(clusterID, userToken)
221         user, err := conn.UserGetCurrent(ctx, arvados.GetOptions{})
222         c.Assert(err, check.IsNil)
223         _, err = conn.UserSetup(rootctx, arvados.UserSetupOptions{UUID: user.UUID})
224         c.Assert(err, check.IsNil)
225         if activate {
226                 _, err = conn.UserActivate(rootctx, arvados.UserActivateOptions{UUID: user.UUID})
227                 c.Assert(err, check.IsNil)
228                 user, err = conn.UserGetCurrent(ctx, arvados.GetOptions{})
229                 c.Assert(err, check.IsNil)
230                 c.Logf("user UUID: %q", user.UUID)
231                 if !user.IsActive {
232                         c.Fatalf("failed to activate user -- %#v", user)
233                 }
234         }
235         return ctx, ac, kc, user
236 }
237
238 // Return Context, arvados.Client and keepclient structs initialized
239 // to communicate with the cluster as the system root user.
240 func (s *IntegrationSuite) rootClients(clusterID string) (context.Context, *arvados.Client, *keepclient.KeepClient) {
241         return s.clientsWithToken(clusterID, s.testClusters[clusterID].config.Clusters[clusterID].SystemRootToken)
242 }
243
244 // Return Context, arvados.Client and keepclient structs initialized
245 // to communicate with the cluster as the anonymous user.
246 func (s *IntegrationSuite) anonymousClients(clusterID string) (context.Context, *arvados.Client, *keepclient.KeepClient) {
247         return s.clientsWithToken(clusterID, s.testClusters[clusterID].config.Clusters[clusterID].Users.AnonymousUserToken)
248 }
249
250 func (s *IntegrationSuite) TestGetCollectionByPDH(c *check.C) {
251         conn1 := s.conn("z1111")
252         rootctx1, _, _ := s.rootClients("z1111")
253         conn3 := s.conn("z3333")
254         userctx1, ac1, kc1, _ := s.userClients(rootctx1, c, conn1, "z1111", true)
255
256         // Create the collection to find its PDH (but don't save it
257         // anywhere yet)
258         var coll1 arvados.Collection
259         fs1, err := coll1.FileSystem(ac1, kc1)
260         c.Assert(err, check.IsNil)
261         f, err := fs1.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
262         c.Assert(err, check.IsNil)
263         _, err = io.WriteString(f, "IntegrationSuite.TestGetCollectionByPDH")
264         c.Assert(err, check.IsNil)
265         err = f.Close()
266         c.Assert(err, check.IsNil)
267         mtxt, err := fs1.MarshalManifest(".")
268         c.Assert(err, check.IsNil)
269         pdh := arvados.PortableDataHash(mtxt)
270
271         // Looking up the PDH before saving returns 404 if cycle
272         // detection is working.
273         _, err = conn1.CollectionGet(userctx1, arvados.GetOptions{UUID: pdh})
274         c.Assert(err, check.ErrorMatches, `.*404 Not Found.*`)
275
276         // Save the collection on cluster z1111.
277         coll1, err = conn1.CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
278                 "manifest_text": mtxt,
279         }})
280         c.Assert(err, check.IsNil)
281
282         // Retrieve the collection from cluster z3333.
283         coll, err := conn3.CollectionGet(userctx1, arvados.GetOptions{UUID: pdh})
284         c.Check(err, check.IsNil)
285         c.Check(coll.PortableDataHash, check.Equals, pdh)
286 }
287
288 func (s *IntegrationSuite) TestS3WithFederatedToken(c *check.C) {
289         if _, err := exec.LookPath("s3cmd"); err != nil {
290                 c.Skip("s3cmd not in PATH")
291                 return
292         }
293
294         testText := "IntegrationSuite.TestS3WithFederatedToken"
295
296         conn1 := s.conn("z1111")
297         rootctx1, _, _ := s.rootClients("z1111")
298         userctx1, ac1, _, _ := s.userClients(rootctx1, c, conn1, "z1111", true)
299         conn3 := s.conn("z3333")
300
301         createColl := func(clusterID string) arvados.Collection {
302                 _, ac, kc := s.clientsWithToken(clusterID, ac1.AuthToken)
303                 var coll arvados.Collection
304                 fs, err := coll.FileSystem(ac, kc)
305                 c.Assert(err, check.IsNil)
306                 f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
307                 c.Assert(err, check.IsNil)
308                 _, err = io.WriteString(f, testText)
309                 c.Assert(err, check.IsNil)
310                 err = f.Close()
311                 c.Assert(err, check.IsNil)
312                 mtxt, err := fs.MarshalManifest(".")
313                 c.Assert(err, check.IsNil)
314                 coll, err = s.conn(clusterID).CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
315                         "manifest_text": mtxt,
316                 }})
317                 c.Assert(err, check.IsNil)
318                 return coll
319         }
320
321         for _, trial := range []struct {
322                 clusterID string // create the collection on this cluster (then use z3333 to access it)
323                 token     string
324         }{
325                 // Try the hardest test first: z3333 hasn't seen
326                 // z1111's token yet, and we're just passing the
327                 // opaque secret part, so z3333 has to guess that it
328                 // belongs to z1111.
329                 {"z1111", strings.Split(ac1.AuthToken, "/")[2]},
330                 {"z3333", strings.Split(ac1.AuthToken, "/")[2]},
331                 {"z1111", strings.Replace(ac1.AuthToken, "/", "_", -1)},
332                 {"z3333", strings.Replace(ac1.AuthToken, "/", "_", -1)},
333         } {
334                 c.Logf("================ %v", trial)
335                 coll := createColl(trial.clusterID)
336
337                 cfgjson, err := conn3.ConfigGet(userctx1)
338                 c.Assert(err, check.IsNil)
339                 var cluster arvados.Cluster
340                 err = json.Unmarshal(cfgjson, &cluster)
341                 c.Assert(err, check.IsNil)
342
343                 c.Logf("TokenV2 is %s", ac1.AuthToken)
344                 host := cluster.Services.WebDAV.ExternalURL.Host
345                 s3args := []string{
346                         "--ssl", "--no-check-certificate",
347                         "--host=" + host, "--host-bucket=" + host,
348                         "--access_key=" + trial.token, "--secret_key=" + trial.token,
349                 }
350                 buf, err := exec.Command("s3cmd", append(s3args, "ls", "s3://"+coll.UUID)...).CombinedOutput()
351                 c.Check(err, check.IsNil)
352                 c.Check(string(buf), check.Matches, `.* `+fmt.Sprintf("%d", len(testText))+` +s3://`+coll.UUID+`/test.txt\n`)
353
354                 buf, _ = exec.Command("s3cmd", append(s3args, "get", "s3://"+coll.UUID+"/test.txt", c.MkDir()+"/tmpfile")...).CombinedOutput()
355                 // Command fails because we don't return Etag header.
356                 flen := strconv.Itoa(len(testText))
357                 c.Check(string(buf), check.Matches, `(?ms).*`+flen+` (bytes in|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.Assert(err, check.IsNil)
465         c.Logf("err == %#v", err)
466
467         c.Log("...get user with good token")
468         u = arvados.User{}
469         req, err = http.NewRequest("GET", "https://"+ac2.APIHost+"/arvados/v1/users/current", nil)
470         c.Assert(err, check.IsNil)
471         err = ac2.DoAndDecode(&u, req)
472         c.Check(err, check.IsNil)
473         c.Check(u.UUID, check.Matches, "z1111-tpzed-.*")
474
475         c.Log("...post CR with good cached token")
476         cr = arvados.ContainerRequest{}
477         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
478         c.Assert(err, check.IsNil)
479         req.Header.Set("Content-Type", "application/json")
480         err = ac2.DoAndDecode(&cr, req)
481         c.Check(err, check.IsNil)
482         c.Check(cr.UUID, check.Matches, "z2222-.*")
483
484         c.Log("...post with good cached token ('OAuth2 ...')")
485         cr = arvados.ContainerRequest{}
486         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
487         c.Assert(err, check.IsNil)
488         req.Header.Set("Content-Type", "application/json")
489         req.Header.Set("Authorization", "OAuth2 "+ac2.AuthToken)
490         resp, err = arvados.InsecureHTTPClient.Do(req)
491         c.Assert(err, check.IsNil)
492         err = json.NewDecoder(resp.Body).Decode(&cr)
493         c.Check(err, check.IsNil)
494         c.Check(cr.UUID, check.Matches, "z2222-.*")
495 }
496
497 func (s *IntegrationSuite) TestCreateContainerRequestWithBadToken(c *check.C) {
498         conn1 := s.conn("z1111")
499         rootctx1, _, _ := s.rootClients("z1111")
500         _, ac1, _, au := s.userClients(rootctx1, c, conn1, "z1111", true)
501
502         tests := []struct {
503                 name         string
504                 token        string
505                 expectedCode int
506         }{
507                 {"Good token", ac1.AuthToken, http.StatusOK},
508                 {"Bogus token", "abcdef", http.StatusUnauthorized},
509                 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", http.StatusUnauthorized},
510                 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", http.StatusUnauthorized},
511         }
512
513         body, _ := json.Marshal(map[string]interface{}{
514                 "container_request": map[string]interface{}{
515                         "command":         []string{"echo"},
516                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
517                         "cwd":             "/",
518                         "output_path":     "/",
519                 },
520         })
521
522         for _, tt := range tests {
523                 c.Log(c.TestName() + " " + tt.name)
524                 ac1.AuthToken = tt.token
525                 req, err := http.NewRequest("POST", "https://"+ac1.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body))
526                 c.Assert(err, check.IsNil)
527                 req.Header.Set("Content-Type", "application/json")
528                 resp, err := ac1.Do(req)
529                 c.Assert(err, check.IsNil)
530                 c.Assert(resp.StatusCode, check.Equals, tt.expectedCode)
531         }
532 }
533
534 // We test the direct access to the database
535 // normally an integration test would not have a database access, but  in this case we need
536 // to test tokens that are secret, so there is no API response that will give them back
537 func (s *IntegrationSuite) dbConn(c *check.C, clusterID string) (*sql.DB, *sql.Conn) {
538         ctx := context.Background()
539         db, err := sql.Open("postgres", s.testClusters[clusterID].super.Cluster().PostgreSQL.Connection.String())
540         c.Assert(err, check.IsNil)
541
542         conn, err := db.Conn(ctx)
543         c.Assert(err, check.IsNil)
544
545         rows, err := conn.ExecContext(ctx, `SELECT 1`)
546         c.Assert(err, check.IsNil)
547         n, err := rows.RowsAffected()
548         c.Assert(err, check.IsNil)
549         c.Assert(n, check.Equals, int64(1))
550         return db, conn
551 }
552
553 // TestRuntimeTokenInCR will test several different tokens in the runtime attribute
554 // and check the expected results accessing directly to the database if needed.
555 func (s *IntegrationSuite) TestRuntimeTokenInCR(c *check.C) {
556         db, dbconn := s.dbConn(c, "z1111")
557         defer db.Close()
558         defer dbconn.Close()
559         conn1 := s.conn("z1111")
560         rootctx1, _, _ := s.rootClients("z1111")
561         userctx1, ac1, _, au := s.userClients(rootctx1, c, conn1, "z1111", true)
562
563         tests := []struct {
564                 name                 string
565                 token                string
566                 expectAToGetAValidCR bool
567                 expectedToken        *string
568         }{
569                 {"Good token z1111 user", ac1.AuthToken, true, &ac1.AuthToken},
570                 {"Bogus token", "abcdef", false, nil},
571                 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", false, nil},
572                 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", false, nil},
573         }
574
575         for _, tt := range tests {
576                 c.Log(c.TestName() + " " + tt.name)
577
578                 rq := map[string]interface{}{
579                         "command":         []string{"echo"},
580                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
581                         "cwd":             "/",
582                         "output_path":     "/",
583                         "runtime_token":   tt.token,
584                 }
585                 cr, err := conn1.ContainerRequestCreate(userctx1, arvados.CreateOptions{Attrs: rq})
586                 if tt.expectAToGetAValidCR {
587                         c.Check(err, check.IsNil)
588                         c.Check(cr, check.NotNil)
589                         c.Check(cr.UUID, check.Not(check.Equals), "")
590                 }
591
592                 if tt.expectedToken == nil {
593                         continue
594                 }
595
596                 c.Logf("cr.UUID: %s", cr.UUID)
597                 row := dbconn.QueryRowContext(rootctx1, `SELECT runtime_token from container_requests where uuid=$1`, cr.UUID)
598                 c.Check(row, check.NotNil)
599                 var token sql.NullString
600                 row.Scan(&token)
601                 if c.Check(token.Valid, check.Equals, true) {
602                         c.Check(token.String, check.Equals, *tt.expectedToken)
603                 }
604         }
605 }
606
607 // TestIntermediateCluster will send a container request to
608 // one cluster with another cluster as the destination
609 // and check the tokens are being handled properly
610 func (s *IntegrationSuite) TestIntermediateCluster(c *check.C) {
611         conn1 := s.conn("z1111")
612         rootctx1, _, _ := s.rootClients("z1111")
613         uctx1, ac1, _, _ := s.userClients(rootctx1, c, conn1, "z1111", true)
614
615         tests := []struct {
616                 name                 string
617                 token                string
618                 expectedRuntimeToken string
619                 expectedUUIDprefix   string
620         }{
621                 {"Good token z1111 user sending a CR to z2222", ac1.AuthToken, "", "z2222-xvhdp-"},
622         }
623
624         for _, tt := range tests {
625                 c.Log(c.TestName() + " " + tt.name)
626                 rq := map[string]interface{}{
627                         "command":         []string{"echo"},
628                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
629                         "cwd":             "/",
630                         "output_path":     "/",
631                         "runtime_token":   tt.token,
632                 }
633                 cr, err := conn1.ContainerRequestCreate(uctx1, arvados.CreateOptions{ClusterID: "z2222", Attrs: rq})
634
635                 c.Check(err, check.IsNil)
636                 c.Check(strings.HasPrefix(cr.UUID, tt.expectedUUIDprefix), check.Equals, true)
637                 c.Check(cr.RuntimeToken, check.Equals, tt.expectedRuntimeToken)
638         }
639 }
640
641 // Test for bug #16263
642 func (s *IntegrationSuite) TestListUsers(c *check.C) {
643         rootctx1, _, _ := s.rootClients("z1111")
644         conn1 := s.conn("z1111")
645         conn3 := s.conn("z3333")
646         userctx1, _, _, _ := s.userClients(rootctx1, c, conn1, "z1111", true)
647
648         // Make sure LoginCluster is properly configured
649         for cls := range s.testClusters {
650                 c.Check(
651                         s.testClusters[cls].config.Clusters[cls].Login.LoginCluster,
652                         check.Equals, "z1111",
653                         check.Commentf("incorrect LoginCluster config on cluster %q", cls))
654         }
655         // Make sure z1111 has users with NULL usernames
656         lst, err := conn1.UserList(rootctx1, arvados.ListOptions{
657                 Limit: math.MaxInt64, // check that large limit works (see #16263)
658         })
659         nullUsername := false
660         c.Assert(err, check.IsNil)
661         c.Assert(len(lst.Items), check.Not(check.Equals), 0)
662         for _, user := range lst.Items {
663                 if user.Username == "" {
664                         nullUsername = true
665                 }
666         }
667         c.Assert(nullUsername, check.Equals, true)
668
669         user1, err := conn1.UserGetCurrent(userctx1, arvados.GetOptions{})
670         c.Assert(err, check.IsNil)
671         c.Check(user1.IsActive, check.Equals, true)
672
673         // Ask for the user list on z3333 using z1111's system root token
674         lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
675         c.Assert(err, check.IsNil)
676         found := false
677         for _, user := range lst.Items {
678                 if user.UUID == user1.UUID {
679                         c.Check(user.IsActive, check.Equals, true)
680                         found = true
681                         break
682                 }
683         }
684         c.Check(found, check.Equals, true)
685
686         // Deactivate user acct on z1111
687         _, err = conn1.UserUnsetup(rootctx1, arvados.GetOptions{UUID: user1.UUID})
688         c.Assert(err, check.IsNil)
689
690         // Get user list from z3333, check the returned z1111 user is
691         // deactivated
692         lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
693         c.Assert(err, check.IsNil)
694         found = false
695         for _, user := range lst.Items {
696                 if user.UUID == user1.UUID {
697                         c.Check(user.IsActive, check.Equals, false)
698                         found = true
699                         break
700                 }
701         }
702         c.Check(found, check.Equals, true)
703
704         // Deactivated user can see is_active==false via "get current
705         // user" API
706         user1, err = conn3.UserGetCurrent(userctx1, arvados.GetOptions{})
707         c.Assert(err, check.IsNil)
708         c.Check(user1.IsActive, check.Equals, false)
709 }
710
711 func (s *IntegrationSuite) TestSetupUserWithVM(c *check.C) {
712         conn1 := s.conn("z1111")
713         conn3 := s.conn("z3333")
714         rootctx1, rootac1, _ := s.rootClients("z1111")
715
716         // Create user on LoginCluster z1111
717         _, _, _, user := s.userClients(rootctx1, c, conn1, "z1111", false)
718
719         // Make a new root token (because rootClients() uses SystemRootToken)
720         var outAuth arvados.APIClientAuthorization
721         err := rootac1.RequestAndDecode(&outAuth, "POST", "/arvados/v1/api_client_authorizations", nil, nil)
722         c.Check(err, check.IsNil)
723
724         // Make a v2 root token to communicate with z3333
725         rootctx3, rootac3, _ := s.clientsWithToken("z3333", outAuth.TokenV2())
726
727         // Create VM on z3333
728         var outVM arvados.VirtualMachine
729         err = rootac3.RequestAndDecode(&outVM, "POST", "/arvados/v1/virtual_machines", nil,
730                 map[string]interface{}{"virtual_machine": map[string]interface{}{
731                         "hostname": "example",
732                 },
733                 })
734         c.Check(outVM.UUID[0:5], check.Equals, "z3333")
735         c.Check(err, check.IsNil)
736
737         // Make sure z3333 user list is up to date
738         _, err = conn3.UserList(rootctx3, arvados.ListOptions{Limit: 1000})
739         c.Check(err, check.IsNil)
740
741         // Try to set up user on z3333 with the VM
742         _, err = conn3.UserSetup(rootctx3, arvados.UserSetupOptions{UUID: user.UUID, VMUUID: outVM.UUID})
743         c.Check(err, check.IsNil)
744
745         var outLinks arvados.LinkList
746         err = rootac3.RequestAndDecode(&outLinks, "GET", "/arvados/v1/links", nil,
747                 arvados.ListOptions{
748                         Limit: 1000,
749                         Filters: []arvados.Filter{
750                                 {
751                                         Attr:     "tail_uuid",
752                                         Operator: "=",
753                                         Operand:  user.UUID,
754                                 },
755                                 {
756                                         Attr:     "head_uuid",
757                                         Operator: "=",
758                                         Operand:  outVM.UUID,
759                                 },
760                                 {
761                                         Attr:     "name",
762                                         Operator: "=",
763                                         Operand:  "can_login",
764                                 },
765                                 {
766                                         Attr:     "link_class",
767                                         Operator: "=",
768                                         Operand:  "permission",
769                                 }}})
770         c.Check(err, check.IsNil)
771
772         c.Check(len(outLinks.Items), check.Equals, 1)
773 }
774
775 func (s *IntegrationSuite) TestOIDCAccessTokenAuth(c *check.C) {
776         conn1 := s.conn("z1111")
777         rootctx1, _, _ := s.rootClients("z1111")
778         s.userClients(rootctx1, c, conn1, "z1111", true)
779
780         accesstoken := s.oidcprovider.ValidAccessToken()
781
782         for _, clusterid := range []string{"z1111", "z2222"} {
783                 c.Logf("trying clusterid %s", clusterid)
784
785                 conn := s.conn(clusterid)
786                 ctx, ac, kc := s.clientsWithToken(clusterid, accesstoken)
787
788                 var coll arvados.Collection
789
790                 // Write some file data and create a collection
791                 {
792                         fs, err := coll.FileSystem(ac, kc)
793                         c.Assert(err, check.IsNil)
794                         f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
795                         c.Assert(err, check.IsNil)
796                         _, err = io.WriteString(f, "IntegrationSuite.TestOIDCAccessTokenAuth")
797                         c.Assert(err, check.IsNil)
798                         err = f.Close()
799                         c.Assert(err, check.IsNil)
800                         mtxt, err := fs.MarshalManifest(".")
801                         c.Assert(err, check.IsNil)
802                         coll, err = conn.CollectionCreate(ctx, arvados.CreateOptions{Attrs: map[string]interface{}{
803                                 "manifest_text": mtxt,
804                         }})
805                         c.Assert(err, check.IsNil)
806                 }
807
808                 // Read the collection & file data
809                 {
810                         user, err := conn.UserGetCurrent(ctx, arvados.GetOptions{})
811                         c.Assert(err, check.IsNil)
812                         c.Check(user.FullName, check.Equals, "Example User")
813                         coll, err = conn.CollectionGet(ctx, arvados.GetOptions{UUID: coll.UUID})
814                         c.Assert(err, check.IsNil)
815                         c.Check(coll.ManifestText, check.Not(check.Equals), "")
816                         fs, err := coll.FileSystem(ac, kc)
817                         c.Assert(err, check.IsNil)
818                         f, err := fs.Open("test.txt")
819                         c.Assert(err, check.IsNil)
820                         buf, err := ioutil.ReadAll(f)
821                         c.Assert(err, check.IsNil)
822                         c.Check(buf, check.DeepEquals, []byte("IntegrationSuite.TestOIDCAccessTokenAuth"))
823                 }
824         }
825 }