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