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