Merge branch '22130-logout-token'
[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/fs"
15         "io/ioutil"
16         "math"
17         "net"
18         "net/http"
19         "os"
20         "os/exec"
21         "strconv"
22         "strings"
23         "sync"
24         "time"
25
26         "git.arvados.org/arvados.git/lib/boot"
27         "git.arvados.org/arvados.git/sdk/go/arvados"
28         "git.arvados.org/arvados.git/sdk/go/arvadostest"
29         "git.arvados.org/arvados.git/sdk/go/ctxlog"
30         "git.arvados.org/arvados.git/sdk/go/httpserver"
31         "git.arvados.org/arvados.git/sdk/go/keepclient"
32         check "gopkg.in/check.v1"
33 )
34
35 var _ = check.Suite(&IntegrationSuite{})
36
37 type IntegrationSuite struct {
38         super        *boot.Supervisor
39         oidcprovider *arvadostest.OIDCProvider
40 }
41
42 func (s *IntegrationSuite) SetUpSuite(c *check.C) {
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         hostport := map[string]string{}
51         for _, id := range []string{"z1111", "z2222", "z3333"} {
52                 hostport[id] = func() string {
53                         // TODO: Instead of expecting random ports on
54                         // 127.0.0.11, 22, 33 to be race-safe, try
55                         // different 127.x.y.z until finding one that
56                         // isn't in use.
57                         ln, err := net.Listen("tcp", ":0")
58                         c.Assert(err, check.IsNil)
59                         ln.Close()
60                         _, port, err := net.SplitHostPort(ln.Addr().String())
61                         c.Assert(err, check.IsNil)
62                         return "127.0.0." + id[3:] + ":" + port
63                 }()
64         }
65         yaml := "Clusters:\n"
66         for id := range hostport {
67                 yaml += `
68   ` + id + `:
69     Services:
70       Controller:
71         ExternalURL: https://` + hostport[id] + `
72     TLS:
73       Insecure: true
74     SystemLogs:
75       Format: text
76     API:
77       MaxConcurrentRequests: 128
78     Containers:
79       CloudVMs:
80         Enable: true
81         Driver: loopback
82         BootProbeCommand: "rm -f /var/lock/crunch-run-broken"
83         ProbeInterval: 1s
84         PollInterval: 5s
85         SyncInterval: 10s
86         TimeoutIdle: 1s
87         TimeoutBooting: 2s
88       RuntimeEngine: singularity
89       CrunchRunArgumentsList: ["--broken-node-hook", "true"]
90     RemoteClusters:
91       z1111:
92         Host: ` + hostport["z1111"] + `
93         Scheme: https
94         Insecure: true
95         Proxy: true
96         ActivateUsers: true
97 `
98                 if id != "z2222" {
99                         yaml += `      z2222:
100         Host: ` + hostport["z2222"] + `
101         Scheme: https
102         Insecure: true
103         Proxy: true
104         ActivateUsers: true
105 `
106                 }
107                 if id != "z3333" {
108                         yaml += `      z3333:
109         Host: ` + hostport["z3333"] + `
110         Scheme: https
111         Insecure: true
112         Proxy: true
113         ActivateUsers: true
114 `
115                 }
116                 if id == "z1111" {
117                         yaml += `
118     Login:
119       LoginCluster: z1111
120       OpenIDConnect:
121         Enable: true
122         Issuer: ` + s.oidcprovider.Issuer.URL + `
123         ClientID: ` + s.oidcprovider.ValidClientID + `
124         ClientSecret: ` + s.oidcprovider.ValidClientSecret + `
125         EmailClaim: email
126         EmailVerifiedClaim: email_verified
127         AcceptAccessToken: true
128         AcceptAccessTokenScope: ""
129 `
130                 } else {
131                         yaml += `
132     Login:
133       LoginCluster: z1111
134 `
135                 }
136         }
137         s.super = &boot.Supervisor{
138                 ClusterType:          "test",
139                 ConfigYAML:           yaml,
140                 Stderr:               ctxlog.LogWriter(c.Log),
141                 NoWorkbench1:         true,
142                 NoWorkbench2:         true,
143                 OwnTemporaryDatabase: true,
144         }
145
146         // Give up if startup takes longer than 3m
147         timeout := time.AfterFunc(3*time.Minute, s.super.Stop)
148         defer timeout.Stop()
149         s.super.Start(context.Background())
150         ok := s.super.WaitReady()
151         c.Assert(ok, check.Equals, true)
152 }
153
154 func (s *IntegrationSuite) TearDownSuite(c *check.C) {
155         if s.super != nil {
156                 s.super.Stop()
157                 s.super.Wait()
158         }
159 }
160
161 func (s *IntegrationSuite) TestDefaultStorageClassesOnCollections(c *check.C) {
162         conn := s.super.Conn("z1111")
163         rootctx, _, _ := s.super.RootClients("z1111")
164         userctx, _, kc, _ := s.super.UserClients("z1111", rootctx, c, conn, s.oidcprovider.AuthEmail, true)
165         c.Assert(len(kc.DefaultStorageClasses) > 0, check.Equals, true)
166         coll, err := conn.CollectionCreate(userctx, arvados.CreateOptions{})
167         c.Assert(err, check.IsNil)
168         c.Assert(coll.StorageClassesDesired, check.DeepEquals, kc.DefaultStorageClasses)
169 }
170
171 func (s *IntegrationSuite) createTestCollectionManifest(c *check.C, ac *arvados.Client, kc *keepclient.KeepClient, content string) string {
172         fs, err := (&arvados.Collection{}).FileSystem(ac, kc)
173         c.Assert(err, check.IsNil)
174         f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
175         c.Assert(err, check.IsNil)
176         _, err = io.WriteString(f, content)
177         c.Assert(err, check.IsNil)
178         err = f.Close()
179         c.Assert(err, check.IsNil)
180         mtxt, err := fs.MarshalManifest(".")
181         c.Assert(err, check.IsNil)
182         return mtxt
183 }
184
185 func (s *IntegrationSuite) TestGetCollectionByPDH(c *check.C) {
186         conn1 := s.super.Conn("z1111")
187         rootctx1, _, _ := s.super.RootClients("z1111")
188         conn3 := s.super.Conn("z3333")
189         userctx1, ac1, kc1, _ := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
190
191         // Create the collection to find its PDH (but don't save it
192         // anywhere yet)
193         mtxt := s.createTestCollectionManifest(c, ac1, kc1, c.TestName())
194         pdh := arvados.PortableDataHash(mtxt)
195
196         // Looking up the PDH before saving returns 404 if cycle
197         // detection is working.
198         _, err := conn1.CollectionGet(userctx1, arvados.GetOptions{UUID: pdh})
199         c.Assert(err, check.ErrorMatches, `.*404 Not Found.*`)
200
201         // Save the collection on cluster z1111.
202         _, err = conn1.CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
203                 "manifest_text": mtxt,
204         }})
205         c.Assert(err, check.IsNil)
206
207         // Retrieve the collection from cluster z3333.
208         coll2, err := conn3.CollectionGet(userctx1, arvados.GetOptions{UUID: pdh})
209         c.Check(err, check.IsNil)
210         c.Check(coll2.PortableDataHash, check.Equals, pdh)
211 }
212
213 func (s *IntegrationSuite) TestFederation_Write1Read2(c *check.C) {
214         s.testFederationCollectionAccess(c, "z1111", "z2222")
215 }
216
217 func (s *IntegrationSuite) TestFederation_Write2Read1(c *check.C) {
218         s.testFederationCollectionAccess(c, "z2222", "z1111")
219 }
220
221 func (s *IntegrationSuite) TestFederation_Write2Read3(c *check.C) {
222         s.testFederationCollectionAccess(c, "z2222", "z3333")
223 }
224
225 func (s *IntegrationSuite) testFederationCollectionAccess(c *check.C, writeCluster, readCluster string) {
226         conn1 := s.super.Conn("z1111")
227         rootctx1, _, _ := s.super.RootClients("z1111")
228         _, ac1, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
229
230         connW := s.super.Conn(writeCluster)
231         userctxW, acW, kcW := s.super.ClientsWithToken(writeCluster, ac1.AuthToken)
232         kcW.DiskCacheSize = keepclient.DiskCacheDisabled
233         connR := s.super.Conn(readCluster)
234         userctxR, acR, kcR := s.super.ClientsWithToken(readCluster, ac1.AuthToken)
235         kcR.DiskCacheSize = keepclient.DiskCacheDisabled
236
237         filedata := fmt.Sprintf("%s: write to %s, read from %s", c.TestName(), writeCluster, readCluster)
238         mtxt := s.createTestCollectionManifest(c, acW, kcW, filedata)
239         collW, err := connW.CollectionCreate(userctxW, arvados.CreateOptions{Attrs: map[string]interface{}{
240                 "manifest_text": mtxt,
241         }})
242         c.Assert(err, check.IsNil)
243
244         collR, err := connR.CollectionGet(userctxR, arvados.GetOptions{UUID: collW.UUID})
245         if !c.Check(err, check.IsNil) {
246                 return
247         }
248         fsR, err := collR.FileSystem(acR, kcR)
249         if !c.Check(err, check.IsNil) {
250                 return
251         }
252         buf, err := fs.ReadFile(arvados.FS(fsR), "test.txt")
253         if !c.Check(err, check.IsNil) {
254                 return
255         }
256         c.Check(string(buf), check.Equals, filedata)
257 }
258
259 // Tests bug #18004
260 func (s *IntegrationSuite) TestRemoteUserAndTokenCacheRace(c *check.C) {
261         conn1 := s.super.Conn("z1111")
262         rootctx1, _, _ := s.super.RootClients("z1111")
263         rootctx2, _, _ := s.super.RootClients("z2222")
264         conn2 := s.super.Conn("z2222")
265         userctx1, _, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, "user2@example.com", true)
266
267         var wg1, wg2 sync.WaitGroup
268         creqs := 100
269
270         // Make concurrent requests to z2222 with a local token to make sure more
271         // than one worker is listening.
272         wg1.Add(1)
273         for i := 0; i < creqs; i++ {
274                 wg2.Add(1)
275                 go func() {
276                         defer wg2.Done()
277                         wg1.Wait()
278                         _, err := conn2.UserGetCurrent(rootctx2, arvados.GetOptions{})
279                         c.Check(err, check.IsNil, check.Commentf("warm up phase failed"))
280                 }()
281         }
282         wg1.Done()
283         wg2.Wait()
284
285         // Real test pass -- use a new remote token than the one used in the warm-up
286         // phase.
287         wg1.Add(1)
288         for i := 0; i < creqs; i++ {
289                 wg2.Add(1)
290                 go func() {
291                         defer wg2.Done()
292                         wg1.Wait()
293                         // Retrieve the remote collection from cluster z2222.
294                         _, err := conn2.UserGetCurrent(userctx1, arvados.GetOptions{})
295                         c.Check(err, check.IsNil, check.Commentf("testing phase failed"))
296                 }()
297         }
298         wg1.Done()
299         wg2.Wait()
300 }
301
302 // After using a token issued by z1111 to call the Logout endpoint on
303 // z2222, the token should be expired and rejected by both z1111 and
304 // z2222.
305 func (s *IntegrationSuite) TestLogoutUsingLoginCluster(c *check.C) {
306         conn1 := s.super.Conn("z1111")
307         conn2 := s.super.Conn("z2222")
308         rootctx1, _, _ := s.super.RootClients("z1111")
309         _, ac1, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, "user1@example.com", true)
310         userctx2, ac2, _ := s.super.ClientsWithToken("z2222", ac1.AuthToken)
311         c.Assert(ac2.AuthToken, check.Matches, `^v2/z1111-.*`)
312         _, err := conn1.CollectionCreate(userctx2, arvados.CreateOptions{})
313         c.Assert(err, check.IsNil)
314         _, err = conn2.CollectionCreate(userctx2, arvados.CreateOptions{})
315         c.Assert(err, check.IsNil)
316
317         _, err = conn2.Logout(userctx2, arvados.LogoutOptions{})
318         c.Assert(err, check.IsNil)
319
320         _, err = conn1.CollectionCreate(userctx2, arvados.CreateOptions{})
321         se, ok := err.(httpserver.HTTPStatusError)
322         if c.Check(ok, check.Equals, true, check.Commentf("after logging out, token should have been rejected by login cluster")) {
323                 c.Check(se.HTTPStatus(), check.Equals, 401)
324         }
325
326         _, err = conn2.CollectionCreate(userctx2, arvados.CreateOptions{})
327         se, ok = err.(httpserver.HTTPStatusError)
328         if c.Check(ok, check.Equals, true, check.Commentf("after logging out, token should have been rejected by remote cluster")) {
329                 c.Check(se.HTTPStatus(), check.Equals, 401)
330         }
331
332 }
333
334 func (s *IntegrationSuite) TestS3WithFederatedToken(c *check.C) {
335         if _, err := exec.LookPath("s3cmd"); err != nil {
336                 c.Skip("s3cmd not in PATH")
337                 return
338         }
339
340         testText := "IntegrationSuite.TestS3WithFederatedToken"
341
342         conn1 := s.super.Conn("z1111")
343         rootctx1, _, _ := s.super.RootClients("z1111")
344         userctx1, ac1, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
345         conn3 := s.super.Conn("z3333")
346
347         createColl := func(clusterID string) arvados.Collection {
348                 _, ac, kc := s.super.ClientsWithToken(clusterID, ac1.AuthToken)
349                 var coll arvados.Collection
350                 fs, err := coll.FileSystem(ac, kc)
351                 c.Assert(err, check.IsNil)
352                 f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
353                 c.Assert(err, check.IsNil)
354                 _, err = io.WriteString(f, testText)
355                 c.Assert(err, check.IsNil)
356                 err = f.Close()
357                 c.Assert(err, check.IsNil)
358                 mtxt, err := fs.MarshalManifest(".")
359                 c.Assert(err, check.IsNil)
360                 coll, err = s.super.Conn(clusterID).CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
361                         "manifest_text": mtxt,
362                 }})
363                 c.Assert(err, check.IsNil)
364                 return coll
365         }
366
367         for _, trial := range []struct {
368                 clusterID string // create the collection on this cluster (then use z3333 to access it)
369                 token     string
370         }{
371                 // Try the hardest test first: z3333 hasn't seen
372                 // z1111's token yet, and we're just passing the
373                 // opaque secret part, so z3333 has to guess that it
374                 // belongs to z1111.
375                 {"z1111", strings.Split(ac1.AuthToken, "/")[2]},
376                 {"z3333", strings.Split(ac1.AuthToken, "/")[2]},
377                 {"z1111", strings.Replace(ac1.AuthToken, "/", "_", -1)},
378                 {"z3333", strings.Replace(ac1.AuthToken, "/", "_", -1)},
379         } {
380                 c.Logf("================ %v", trial)
381                 coll := createColl(trial.clusterID)
382
383                 cfgjson, err := conn3.ConfigGet(userctx1)
384                 c.Assert(err, check.IsNil)
385                 var cluster arvados.Cluster
386                 err = json.Unmarshal(cfgjson, &cluster)
387                 c.Assert(err, check.IsNil)
388
389                 c.Logf("TokenV2 is %s", ac1.AuthToken)
390                 host := cluster.Services.WebDAV.ExternalURL.Host
391                 s3args := []string{
392                         "--ssl", "--no-check-certificate",
393                         "--host=" + host, "--host-bucket=" + host,
394                         "--access_key=" + trial.token, "--secret_key=" + trial.token,
395                 }
396                 buf, err := exec.Command("s3cmd", append(s3args, "ls", "s3://"+coll.UUID)...).CombinedOutput()
397                 c.Check(err, check.IsNil)
398                 c.Check(string(buf), check.Matches, `.* `+fmt.Sprintf("%d", len(testText))+` +s3://`+coll.UUID+`/test.txt\n`)
399
400                 buf, _ = exec.Command("s3cmd", append(s3args, "get", "s3://"+coll.UUID+"/test.txt", c.MkDir()+"/tmpfile")...).CombinedOutput()
401                 // Command fails because we don't return Etag header.
402                 flen := strconv.Itoa(len(testText))
403                 c.Check(string(buf), check.Matches, `(?ms).*`+flen+` (bytes in|of `+flen+`).*`)
404         }
405 }
406
407 func (s *IntegrationSuite) TestGetCollectionAsAnonymous(c *check.C) {
408         conn1 := s.super.Conn("z1111")
409         conn3 := s.super.Conn("z3333")
410         rootctx1, rootac1, rootkc1 := s.super.RootClients("z1111")
411         anonctx3, anonac3, _ := s.super.AnonymousClients("z3333")
412
413         // Make sure anonymous token was set
414         c.Assert(anonac3.AuthToken, check.Not(check.Equals), "")
415
416         // Create the collection to find its PDH (but don't save it
417         // anywhere yet)
418         var coll1 arvados.Collection
419         fs1, err := coll1.FileSystem(rootac1, rootkc1)
420         c.Assert(err, check.IsNil)
421         f, err := fs1.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
422         c.Assert(err, check.IsNil)
423         _, err = io.WriteString(f, "IntegrationSuite.TestGetCollectionAsAnonymous")
424         c.Assert(err, check.IsNil)
425         err = f.Close()
426         c.Assert(err, check.IsNil)
427         mtxt, err := fs1.MarshalManifest(".")
428         c.Assert(err, check.IsNil)
429         pdh := arvados.PortableDataHash(mtxt)
430
431         // Save the collection on cluster z1111.
432         coll1, err = conn1.CollectionCreate(rootctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
433                 "manifest_text": mtxt,
434         }})
435         c.Assert(err, check.IsNil)
436
437         // Share it with the anonymous users group.
438         var outLink arvados.Link
439         err = rootac1.RequestAndDecode(&outLink, "POST", "/arvados/v1/links", nil,
440                 map[string]interface{}{"link": map[string]interface{}{
441                         "link_class": "permission",
442                         "name":       "can_read",
443                         "tail_uuid":  "z1111-j7d0g-anonymouspublic",
444                         "head_uuid":  coll1.UUID,
445                 },
446                 })
447         c.Check(err, check.IsNil)
448
449         // Current user should be z3 anonymous user
450         outUser, err := anonac3.CurrentUser()
451         c.Check(err, check.IsNil)
452         c.Check(outUser.UUID, check.Equals, "z3333-tpzed-anonymouspublic")
453
454         // Get the token uuid
455         var outAuth arvados.APIClientAuthorization
456         err = anonac3.RequestAndDecode(&outAuth, "GET", "/arvados/v1/api_client_authorizations/current", nil, nil)
457         c.Check(err, check.IsNil)
458
459         // Make a v2 token of the z3 anonymous user, and use it on z1
460         _, anonac1, _ := s.super.ClientsWithToken("z1111", outAuth.TokenV2())
461         outUser2, err := anonac1.CurrentUser()
462         c.Check(err, check.IsNil)
463         // z3 anonymous user will be mapped to the z1 anonymous user
464         c.Check(outUser2.UUID, check.Equals, "z1111-tpzed-anonymouspublic")
465
466         // Retrieve the collection (which is on z1) using anonymous from cluster z3333.
467         coll, err := conn3.CollectionGet(anonctx3, arvados.GetOptions{UUID: coll1.UUID})
468         c.Check(err, check.IsNil)
469         c.Check(coll.PortableDataHash, check.Equals, pdh)
470 }
471
472 // z3333 should forward the locally-issued anonymous user token to its login
473 // cluster z1111. That is no problem because the login cluster controller will
474 // map any anonymous user token to its local anonymous user.
475 //
476 // This needs to work because wb1 has a tendency to slap the local anonymous
477 // user token on every request as a reader_token, which gets folded into the
478 // request token list controller.
479 //
480 // Use a z1111 user token and the anonymous token from z3333 passed in as a
481 // reader_token to do a request on z3333, asking for the z1111 anonymous user
482 // object. The request will be forwarded to the z1111 cluster. The presence of
483 // the z3333 anonymous user token should not prohibit the request from being
484 // forwarded.
485 func (s *IntegrationSuite) TestForwardAnonymousTokenToLoginCluster(c *check.C) {
486         conn1 := s.super.Conn("z1111")
487
488         rootctx1, _, _ := s.super.RootClients("z1111")
489         _, anonac3, _ := s.super.AnonymousClients("z3333")
490
491         // Make a user connection to z3333 (using a z1111 user, because that's the login cluster)
492         _, userac1, _, _ := s.super.UserClients("z3333", rootctx1, c, conn1, "user@example.com", true)
493
494         // Get the anonymous user token for z3333
495         var anon3Auth arvados.APIClientAuthorization
496         err := anonac3.RequestAndDecode(&anon3Auth, "GET", "/arvados/v1/api_client_authorizations/current", nil, nil)
497         c.Check(err, check.IsNil)
498
499         var userList arvados.UserList
500         where := make(map[string]string)
501         where["uuid"] = "z1111-tpzed-anonymouspublic"
502         err = userac1.RequestAndDecode(&userList, "GET", "/arvados/v1/users", nil,
503                 map[string]interface{}{
504                         "reader_tokens": []string{anon3Auth.TokenV2()},
505                         "where":         where,
506                 },
507         )
508         // The local z3333 anonymous token must be allowed to be forwarded to the login cluster
509         c.Check(err, check.IsNil)
510
511         userac1.AuthToken = "v2/z1111-gj3su-asdfasdfasdfasd/this-token-does-not-validate-so-anonymous-token-will-be-used-instead"
512         err = userac1.RequestAndDecode(&userList, "GET", "/arvados/v1/users", nil,
513                 map[string]interface{}{
514                         "reader_tokens": []string{anon3Auth.TokenV2()},
515                         "where":         where,
516                 },
517         )
518         c.Check(err, check.IsNil)
519 }
520
521 // Get a token from the login cluster (z1111), use it to submit a
522 // container request on z2222.
523 func (s *IntegrationSuite) TestCreateContainerRequestWithFedToken(c *check.C) {
524         conn1 := s.super.Conn("z1111")
525         rootctx1, _, _ := s.super.RootClients("z1111")
526         _, ac1, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
527
528         // Use ac2 to get the discovery doc with a blank token, so the
529         // SDK doesn't magically pass the z1111 token to z2222 before
530         // we're ready to start our test.
531         _, ac2, _ := s.super.ClientsWithToken("z2222", "")
532         var dd map[string]interface{}
533         err := ac2.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
534         c.Assert(err, check.IsNil)
535
536         var (
537                 body bytes.Buffer
538                 req  *http.Request
539                 resp *http.Response
540                 u    arvados.User
541                 cr   arvados.ContainerRequest
542         )
543         json.NewEncoder(&body).Encode(map[string]interface{}{
544                 "container_request": map[string]interface{}{
545                         "command":         []string{"echo"},
546                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
547                         "cwd":             "/",
548                         "output_path":     "/",
549                 },
550         })
551         ac2.AuthToken = ac1.AuthToken
552
553         c.Log("...post CR with good (but not yet cached) token")
554         cr = arvados.ContainerRequest{}
555         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
556         c.Assert(err, check.IsNil)
557         req.Header.Set("Content-Type", "application/json")
558         err = ac2.DoAndDecode(&cr, req)
559         c.Assert(err, check.IsNil)
560         c.Logf("err == %#v", err)
561
562         c.Log("...get user with good token")
563         u = arvados.User{}
564         req, err = http.NewRequest("GET", "https://"+ac2.APIHost+"/arvados/v1/users/current", nil)
565         c.Assert(err, check.IsNil)
566         err = ac2.DoAndDecode(&u, req)
567         c.Check(err, check.IsNil)
568         c.Check(u.UUID, check.Matches, "z1111-tpzed-.*")
569
570         c.Log("...post CR with good cached token")
571         cr = arvados.ContainerRequest{}
572         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
573         c.Assert(err, check.IsNil)
574         req.Header.Set("Content-Type", "application/json")
575         err = ac2.DoAndDecode(&cr, req)
576         c.Check(err, check.IsNil)
577         c.Check(cr.UUID, check.Matches, "z2222-.*")
578
579         c.Log("...post with good cached token ('Bearer ...')")
580         cr = arvados.ContainerRequest{}
581         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
582         c.Assert(err, check.IsNil)
583         req.Header.Set("Content-Type", "application/json")
584         req.Header.Set("Authorization", "Bearer "+ac2.AuthToken)
585         resp, err = arvados.InsecureHTTPClient.Do(req)
586         c.Assert(err, check.IsNil)
587         defer resp.Body.Close()
588         err = json.NewDecoder(resp.Body).Decode(&cr)
589         c.Check(err, check.IsNil)
590         c.Check(cr.UUID, check.Matches, "z2222-.*")
591 }
592
593 func (s *IntegrationSuite) TestCreateContainerRequestWithBadToken(c *check.C) {
594         conn1 := s.super.Conn("z1111")
595         rootctx1, _, _ := s.super.RootClients("z1111")
596         _, ac1, _, au := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
597
598         tests := []struct {
599                 name         string
600                 token        string
601                 expectedCode int
602         }{
603                 {"Good token", ac1.AuthToken, http.StatusOK},
604                 {"Bogus token", "abcdef", http.StatusUnauthorized},
605                 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", http.StatusUnauthorized},
606                 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", http.StatusUnauthorized},
607         }
608
609         body, _ := json.Marshal(map[string]interface{}{
610                 "container_request": map[string]interface{}{
611                         "command":         []string{"echo"},
612                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
613                         "cwd":             "/",
614                         "output_path":     "/",
615                 },
616         })
617
618         for _, tt := range tests {
619                 c.Log(c.TestName() + " " + tt.name)
620                 ac1.AuthToken = tt.token
621                 req, err := http.NewRequest("POST", "https://"+ac1.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body))
622                 c.Assert(err, check.IsNil)
623                 req.Header.Set("Content-Type", "application/json")
624                 resp, err := ac1.Do(req)
625                 if c.Check(err, check.IsNil) {
626                         c.Assert(resp.StatusCode, check.Equals, tt.expectedCode)
627                         resp.Body.Close()
628                 }
629         }
630 }
631
632 func (s *IntegrationSuite) TestRequestIDHeader(c *check.C) {
633         conn1 := s.super.Conn("z1111")
634         rootctx1, _, _ := s.super.RootClients("z1111")
635         userctx1, ac1, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
636
637         coll, err := conn1.CollectionCreate(userctx1, arvados.CreateOptions{})
638         c.Check(err, check.IsNil)
639
640         tests := []struct {
641                 path            string
642                 reqIdProvided   bool
643                 notFoundRequest bool
644         }{
645                 {"/arvados/v1/collections", false, false},
646                 {"/arvados/v1/collections", true, false},
647                 {"/arvados/v1/nonexistant", false, true},
648                 {"/arvados/v1/nonexistant", true, true},
649                 {"/arvados/v1/collections/" + coll.UUID, false, false},
650                 {"/arvados/v1/collections/" + coll.UUID, true, false},
651                 // new code path (lib/controller/router etc) - single-cluster request
652                 {"/arvados/v1/collections/z1111-4zz18-0123456789abcde", false, true},
653                 {"/arvados/v1/collections/z1111-4zz18-0123456789abcde", true, true},
654                 // new code path (lib/controller/router etc) - federated request
655                 {"/arvados/v1/collections/z2222-4zz18-0123456789abcde", false, true},
656                 {"/arvados/v1/collections/z2222-4zz18-0123456789abcde", true, true},
657                 // old code path (proxyRailsAPI) - single-cluster request
658                 {"/arvados/v1/containers/z1111-dz642-0123456789abcde", false, true},
659                 {"/arvados/v1/containers/z1111-dz642-0123456789abcde", true, true},
660                 // old code path (setupProxyRemoteCluster) - federated request
661                 {"/arvados/v1/workflows/z2222-7fd4e-0123456789abcde", false, true},
662                 {"/arvados/v1/workflows/z2222-7fd4e-0123456789abcde", true, true},
663         }
664
665         for _, tt := range tests {
666                 c.Log(c.TestName() + " " + tt.path)
667                 req, err := http.NewRequest("GET", "https://"+ac1.APIHost+tt.path, nil)
668                 c.Assert(err, check.IsNil)
669                 customReqId := "abcdeG"
670                 if !tt.reqIdProvided {
671                         c.Assert(req.Header.Get("X-Request-Id"), check.Equals, "")
672                 } else {
673                         req.Header.Set("X-Request-Id", customReqId)
674                 }
675                 resp, err := ac1.Do(req)
676                 c.Assert(err, check.IsNil)
677                 if tt.notFoundRequest {
678                         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
679                 } else {
680                         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
681                 }
682                 respHdr := resp.Header.Get("X-Request-Id")
683                 if tt.reqIdProvided {
684                         c.Check(respHdr, check.Equals, customReqId)
685                 } else {
686                         c.Check(respHdr, check.Matches, `req-[0-9a-zA-Z]{20}`)
687                 }
688                 if tt.notFoundRequest {
689                         var jresp httpserver.ErrorResponse
690                         err := json.NewDecoder(resp.Body).Decode(&jresp)
691                         c.Check(err, check.IsNil)
692                         if c.Check(jresp.Errors, check.HasLen, 1) {
693                                 c.Check(jresp.Errors[0], check.Matches, `.*\(`+respHdr+`\).*`)
694                         }
695                 }
696                 resp.Body.Close()
697         }
698 }
699
700 // We test the direct access to the database
701 // normally an integration test would not have a database access, but in this case we need
702 // to test tokens that are secret, so there is no API response that will give them back
703 func (s *IntegrationSuite) dbConn(c *check.C, clusterID string) (*sql.DB, *sql.Conn) {
704         ctx := context.Background()
705         db, err := sql.Open("postgres", s.super.Cluster(clusterID).PostgreSQL.Connection.String())
706         c.Assert(err, check.IsNil)
707
708         conn, err := db.Conn(ctx)
709         c.Assert(err, check.IsNil)
710
711         rows, err := conn.ExecContext(ctx, `SELECT 1`)
712         c.Assert(err, check.IsNil)
713         n, err := rows.RowsAffected()
714         c.Assert(err, check.IsNil)
715         c.Assert(n, check.Equals, int64(1))
716         return db, conn
717 }
718
719 // TestRuntimeTokenInCR will test several different tokens in the runtime attribute
720 // and check the expected results accessing directly to the database if needed.
721 func (s *IntegrationSuite) TestRuntimeTokenInCR(c *check.C) {
722         db, dbconn := s.dbConn(c, "z1111")
723         defer db.Close()
724         defer dbconn.Close()
725         conn1 := s.super.Conn("z1111")
726         rootctx1, _, _ := s.super.RootClients("z1111")
727         userctx1, ac1, _, au := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
728
729         tests := []struct {
730                 name                 string
731                 token                string
732                 expectAToGetAValidCR bool
733                 expectedToken        *string
734         }{
735                 {"Good token z1111 user", ac1.AuthToken, true, &ac1.AuthToken},
736                 {"Bogus token", "abcdef", false, nil},
737                 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", false, nil},
738                 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", false, nil},
739         }
740
741         for _, tt := range tests {
742                 c.Log(c.TestName() + " " + tt.name)
743
744                 rq := map[string]interface{}{
745                         "command":         []string{"echo"},
746                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
747                         "cwd":             "/",
748                         "output_path":     "/",
749                         "runtime_token":   tt.token,
750                 }
751                 cr, err := conn1.ContainerRequestCreate(userctx1, arvados.CreateOptions{Attrs: rq})
752                 if tt.expectAToGetAValidCR {
753                         c.Check(err, check.IsNil)
754                         c.Check(cr, check.NotNil)
755                         c.Check(cr.UUID, check.Not(check.Equals), "")
756                 }
757
758                 if tt.expectedToken == nil {
759                         continue
760                 }
761
762                 c.Logf("cr.UUID: %s", cr.UUID)
763                 row := dbconn.QueryRowContext(rootctx1, `SELECT runtime_token from container_requests where uuid=$1`, cr.UUID)
764                 c.Check(row, check.NotNil)
765                 var token sql.NullString
766                 row.Scan(&token)
767                 if c.Check(token.Valid, check.Equals, true) {
768                         c.Check(token.String, check.Equals, *tt.expectedToken)
769                 }
770         }
771 }
772
773 // TestIntermediateCluster will send a container request to
774 // one cluster with another cluster as the destination
775 // and check the tokens are being handled properly
776 func (s *IntegrationSuite) TestIntermediateCluster(c *check.C) {
777         conn1 := s.super.Conn("z1111")
778         rootctx1, _, _ := s.super.RootClients("z1111")
779         uctx1, ac1, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
780
781         tests := []struct {
782                 name                 string
783                 token                string
784                 expectedRuntimeToken string
785                 expectedUUIDprefix   string
786         }{
787                 {"Good token z1111 user sending a CR to z2222", ac1.AuthToken, "", "z2222-xvhdp-"},
788         }
789
790         for _, tt := range tests {
791                 c.Log(c.TestName() + " " + tt.name)
792                 rq := map[string]interface{}{
793                         "command":         []string{"echo"},
794                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
795                         "cwd":             "/",
796                         "output_path":     "/",
797                         "runtime_token":   tt.token,
798                 }
799                 cr, err := conn1.ContainerRequestCreate(uctx1, arvados.CreateOptions{ClusterID: "z2222", Attrs: rq})
800
801                 c.Check(err, check.IsNil)
802                 c.Check(strings.HasPrefix(cr.UUID, tt.expectedUUIDprefix), check.Equals, true)
803                 c.Check(cr.RuntimeToken, check.Equals, tt.expectedRuntimeToken)
804         }
805 }
806
807 // Test for #17785
808 func (s *IntegrationSuite) TestFederatedApiClientAuthHandling(c *check.C) {
809         rootctx1, rootclnt1, _ := s.super.RootClients("z1111")
810         conn1 := s.super.Conn("z1111")
811
812         // Make sure LoginCluster is properly configured
813         for _, cls := range []string{"z1111", "z3333"} {
814                 c.Check(
815                         s.super.Cluster(cls).Login.LoginCluster,
816                         check.Equals, "z1111",
817                         check.Commentf("incorrect LoginCluster config on cluster %q", cls))
818         }
819         // Get user's UUID & attempt to create a token for it on the remote cluster
820         _, _, _, user := s.super.UserClients("z1111", rootctx1, c, conn1,
821                 "user@example.com", true)
822         _, rootclnt3, _ := s.super.ClientsWithToken("z3333", rootclnt1.AuthToken)
823         var resp arvados.APIClientAuthorization
824         err := rootclnt3.RequestAndDecode(
825                 &resp, "POST", "arvados/v1/api_client_authorizations", nil,
826                 map[string]interface{}{
827                         "api_client_authorization": map[string]string{
828                                 "owner_uuid": user.UUID,
829                         },
830                 },
831         )
832         c.Assert(err, check.IsNil)
833         newTok := resp.TokenV2()
834         c.Assert(newTok, check.Not(check.Equals), "")
835
836         // Confirm the token is from z1111
837         c.Assert(strings.HasPrefix(newTok, "v2/z1111-gj3su-"), check.Equals, true)
838
839         // Confirm the token works and is from the correct user
840         _, rootclnt3bis, _ := s.super.ClientsWithToken("z3333", newTok)
841         var curUser arvados.User
842         err = rootclnt3bis.RequestAndDecode(
843                 &curUser, "GET", "arvados/v1/users/current", nil, nil,
844         )
845         c.Assert(err, check.IsNil)
846         c.Assert(curUser.UUID, check.Equals, user.UUID)
847
848         // Request the ApiClientAuthorization list using the new token
849         _, userClient, _ := s.super.ClientsWithToken("z3333", newTok)
850         var acaLst arvados.APIClientAuthorizationList
851         err = userClient.RequestAndDecode(
852                 &acaLst, "GET", "arvados/v1/api_client_authorizations", nil, nil,
853         )
854         c.Assert(err, check.IsNil)
855 }
856
857 // Test for bug #18076
858 func (s *IntegrationSuite) TestStaleCachedUserRecord(c *check.C) {
859         rootctx1, _, _ := s.super.RootClients("z1111")
860         conn1 := s.super.Conn("z1111")
861         conn3 := s.super.Conn("z3333")
862
863         // Make sure LoginCluster is properly configured
864         for _, cls := range []string{"z1111", "z3333"} {
865                 c.Check(
866                         s.super.Cluster(cls).Login.LoginCluster,
867                         check.Equals, "z1111",
868                         check.Commentf("incorrect LoginCluster config on cluster %q", cls))
869         }
870
871         // Create some users, request them on the federated cluster so they're cached.
872         var users []arvados.User
873         for userNr := 0; userNr < 2; userNr++ {
874                 _, _, _, user := s.super.UserClients("z1111",
875                         rootctx1,
876                         c,
877                         conn1,
878                         fmt.Sprintf("user0%d@example.com", userNr),
879                         true)
880                 c.Assert(user.Username, check.Not(check.Equals), "")
881                 users = append(users, user)
882
883                 lst, err := conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
884                 c.Assert(err, check.Equals, nil)
885                 userFound := false
886                 for _, fedUser := range lst.Items {
887                         if fedUser.UUID == user.UUID {
888                                 c.Assert(fedUser.Username, check.Equals, user.Username)
889                                 userFound = true
890                                 break
891                         }
892                 }
893                 c.Assert(userFound, check.Equals, true)
894         }
895
896         // Swap the usernames
897         _, err := conn1.UserUpdate(rootctx1, arvados.UpdateOptions{
898                 UUID: users[0].UUID,
899                 Attrs: map[string]interface{}{
900                         "username": "",
901                 },
902         })
903         c.Assert(err, check.Equals, nil)
904         _, err = conn1.UserUpdate(rootctx1, arvados.UpdateOptions{
905                 UUID: users[1].UUID,
906                 Attrs: map[string]interface{}{
907                         "username": users[0].Username,
908                 },
909         })
910         c.Assert(err, check.Equals, nil)
911         _, err = conn1.UserUpdate(rootctx1, arvados.UpdateOptions{
912                 UUID: users[0].UUID,
913                 Attrs: map[string]interface{}{
914                         "username": users[1].Username,
915                 },
916         })
917         c.Assert(err, check.Equals, nil)
918
919         // Re-request the list on the federated cluster & check for updates
920         lst, err := conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
921         c.Assert(err, check.Equals, nil)
922         var user0Found, user1Found bool
923         for _, user := range lst.Items {
924                 if user.UUID == users[0].UUID {
925                         user0Found = true
926                         c.Assert(user.Username, check.Equals, users[1].Username)
927                 } else if user.UUID == users[1].UUID {
928                         user1Found = true
929                         c.Assert(user.Username, check.Equals, users[0].Username)
930                 }
931         }
932         c.Assert(user0Found, check.Equals, true)
933         c.Assert(user1Found, check.Equals, true)
934 }
935
936 // Test for bug #16263
937 func (s *IntegrationSuite) TestListUsers(c *check.C) {
938         rootctx1, _, _ := s.super.RootClients("z1111")
939         conn1 := s.super.Conn("z1111")
940         conn3 := s.super.Conn("z3333")
941         userctx1, _, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
942
943         // Make sure LoginCluster is properly configured
944         for _, cls := range []string{"z1111", "z2222", "z3333"} {
945                 c.Check(
946                         s.super.Cluster(cls).Login.LoginCluster,
947                         check.Equals, "z1111",
948                         check.Commentf("incorrect LoginCluster config on cluster %q", cls))
949         }
950         // Make sure z1111 has users with NULL usernames
951         lst, err := conn1.UserList(rootctx1, arvados.ListOptions{
952                 Limit: math.MaxInt64, // check that large limit works (see #16263)
953         })
954         nullUsername := false
955         c.Assert(err, check.IsNil)
956         c.Assert(len(lst.Items), check.Not(check.Equals), 0)
957         for _, user := range lst.Items {
958                 if user.Username == "" {
959                         nullUsername = true
960                         break
961                 }
962         }
963         c.Assert(nullUsername, check.Equals, true)
964
965         user1, err := conn1.UserGetCurrent(userctx1, arvados.GetOptions{})
966         c.Assert(err, check.IsNil)
967         c.Check(user1.IsActive, check.Equals, true)
968
969         // Ask for the user list on z3333 using z1111's system root token
970         lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
971         c.Assert(err, check.IsNil)
972         found := false
973         for _, user := range lst.Items {
974                 if user.UUID == user1.UUID {
975                         c.Check(user.IsActive, check.Equals, true)
976                         found = true
977                         break
978                 }
979         }
980         c.Check(found, check.Equals, true)
981
982         // Deactivate user acct on z1111
983         _, err = conn1.UserUnsetup(rootctx1, arvados.GetOptions{UUID: user1.UUID})
984         c.Assert(err, check.IsNil)
985
986         // Get user list from z3333, check the returned z1111 user is
987         // deactivated
988         lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
989         c.Assert(err, check.IsNil)
990         found = false
991         for _, user := range lst.Items {
992                 if user.UUID == user1.UUID {
993                         c.Check(user.IsActive, check.Equals, false)
994                         found = true
995                         break
996                 }
997         }
998         c.Check(found, check.Equals, true)
999
1000         // Deactivated user no longer has working token
1001         user1, err = conn3.UserGetCurrent(userctx1, arvados.GetOptions{})
1002         c.Assert(err, check.ErrorMatches, `.*401 Unauthorized.*`)
1003 }
1004
1005 func (s *IntegrationSuite) TestSetupUserWithVM(c *check.C) {
1006         conn1 := s.super.Conn("z1111")
1007         conn3 := s.super.Conn("z3333")
1008         rootctx1, rootac1, _ := s.super.RootClients("z1111")
1009
1010         // Create user on LoginCluster z1111
1011         _, _, _, user := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
1012
1013         // Make a new root token (because rootClients() uses SystemRootToken)
1014         var outAuth arvados.APIClientAuthorization
1015         err := rootac1.RequestAndDecode(&outAuth, "POST", "/arvados/v1/api_client_authorizations", nil, nil)
1016         c.Check(err, check.IsNil)
1017
1018         // Make a v2 root token to communicate with z3333
1019         rootctx3, rootac3, _ := s.super.ClientsWithToken("z3333", outAuth.TokenV2())
1020
1021         // Create VM on z3333
1022         var outVM arvados.VirtualMachine
1023         err = rootac3.RequestAndDecode(&outVM, "POST", "/arvados/v1/virtual_machines", nil,
1024                 map[string]interface{}{"virtual_machine": map[string]interface{}{
1025                         "hostname": "example",
1026                 },
1027                 })
1028         c.Assert(err, check.IsNil)
1029         c.Check(outVM.UUID[0:5], check.Equals, "z3333")
1030
1031         // Make sure z3333 user list is up to date
1032         _, err = conn3.UserList(rootctx3, arvados.ListOptions{Limit: 1000})
1033         c.Check(err, check.IsNil)
1034
1035         // Try to set up user on z3333 with the VM
1036         _, err = conn3.UserSetup(rootctx3, arvados.UserSetupOptions{UUID: user.UUID, VMUUID: outVM.UUID})
1037         c.Check(err, check.IsNil)
1038
1039         var outLinks arvados.LinkList
1040         err = rootac3.RequestAndDecode(&outLinks, "GET", "/arvados/v1/links", nil,
1041                 arvados.ListOptions{
1042                         Limit: 1000,
1043                         Filters: []arvados.Filter{
1044                                 {
1045                                         Attr:     "tail_uuid",
1046                                         Operator: "=",
1047                                         Operand:  user.UUID,
1048                                 },
1049                                 {
1050                                         Attr:     "head_uuid",
1051                                         Operator: "=",
1052                                         Operand:  outVM.UUID,
1053                                 },
1054                                 {
1055                                         Attr:     "name",
1056                                         Operator: "=",
1057                                         Operand:  "can_login",
1058                                 },
1059                                 {
1060                                         Attr:     "link_class",
1061                                         Operator: "=",
1062                                         Operand:  "permission",
1063                                 }}})
1064         c.Check(err, check.IsNil)
1065
1066         c.Check(len(outLinks.Items), check.Equals, 1)
1067 }
1068
1069 func (s *IntegrationSuite) TestOIDCAccessTokenAuth(c *check.C) {
1070         conn1 := s.super.Conn("z1111")
1071         rootctx1, _, _ := s.super.RootClients("z1111")
1072         s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
1073
1074         accesstoken := s.oidcprovider.ValidAccessToken()
1075
1076         for _, clusterID := range []string{"z1111", "z2222"} {
1077
1078                 var coll arvados.Collection
1079
1080                 // Write some file data and create a collection
1081                 {
1082                         c.Logf("save collection to %s", clusterID)
1083
1084                         conn := s.super.Conn(clusterID)
1085                         ctx, ac, kc := s.super.ClientsWithToken(clusterID, accesstoken)
1086
1087                         fs, err := coll.FileSystem(ac, kc)
1088                         c.Assert(err, check.IsNil)
1089                         f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
1090                         c.Assert(err, check.IsNil)
1091                         _, err = io.WriteString(f, "IntegrationSuite.TestOIDCAccessTokenAuth")
1092                         c.Assert(err, check.IsNil)
1093                         err = f.Close()
1094                         c.Assert(err, check.IsNil)
1095                         mtxt, err := fs.MarshalManifest(".")
1096                         c.Assert(err, check.IsNil)
1097                         coll, err = conn.CollectionCreate(ctx, arvados.CreateOptions{Attrs: map[string]interface{}{
1098                                 "manifest_text": mtxt,
1099                         }})
1100                         c.Assert(err, check.IsNil)
1101                 }
1102
1103                 // Read the collection & file data -- both from the
1104                 // cluster where it was created, and from the other
1105                 // cluster.
1106                 for _, readClusterID := range []string{"z1111", "z2222", "z3333"} {
1107                         c.Logf("retrieve %s from %s", coll.UUID, readClusterID)
1108
1109                         conn := s.super.Conn(readClusterID)
1110                         ctx, ac, kc := s.super.ClientsWithToken(readClusterID, accesstoken)
1111
1112                         user, err := conn.UserGetCurrent(ctx, arvados.GetOptions{})
1113                         c.Assert(err, check.IsNil)
1114                         c.Check(user.FullName, check.Equals, "Example User")
1115                         readcoll, err := conn.CollectionGet(ctx, arvados.GetOptions{UUID: coll.UUID})
1116                         c.Assert(err, check.IsNil)
1117                         c.Check(readcoll.ManifestText, check.Not(check.Equals), "")
1118                         fs, err := readcoll.FileSystem(ac, kc)
1119                         c.Assert(err, check.IsNil)
1120                         f, err := fs.Open("test.txt")
1121                         c.Assert(err, check.IsNil)
1122                         buf, err := ioutil.ReadAll(f)
1123                         c.Assert(err, check.IsNil)
1124                         c.Check(buf, check.DeepEquals, []byte("IntegrationSuite.TestOIDCAccessTokenAuth"))
1125                 }
1126         }
1127 }
1128
1129 // z3333 should not forward a locally-issued container runtime token,
1130 // associated with a z1111 user, to its login cluster z1111. z1111
1131 // would only call back to z3333 and then reject the response because
1132 // the user ID does not match the token prefix. See
1133 // dev.arvados.org/issues/18346
1134 func (s *IntegrationSuite) TestForwardRuntimeTokenToLoginCluster(c *check.C) {
1135         db3, db3conn := s.dbConn(c, "z3333")
1136         defer db3.Close()
1137         defer db3conn.Close()
1138         rootctx1, _, _ := s.super.RootClients("z1111")
1139         rootctx3, _, _ := s.super.RootClients("z3333")
1140         conn1 := s.super.Conn("z1111")
1141         conn3 := s.super.Conn("z3333")
1142         userctx1, _, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
1143
1144         user1, err := conn1.UserGetCurrent(userctx1, arvados.GetOptions{})
1145         c.Assert(err, check.IsNil)
1146         c.Logf("user1 %+v", user1)
1147
1148         imageColl, err := conn3.CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
1149                 "manifest_text": ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.tar\n",
1150         }})
1151         c.Assert(err, check.IsNil)
1152         c.Logf("imageColl %+v", imageColl)
1153
1154         cr, err := conn3.ContainerRequestCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
1155                 "state":           "Committed",
1156                 "command":         []string{"echo"},
1157                 "container_image": imageColl.PortableDataHash,
1158                 "cwd":             "/",
1159                 "output_path":     "/",
1160                 "priority":        1,
1161                 "runtime_constraints": arvados.RuntimeConstraints{
1162                         VCPUs: 1,
1163                         RAM:   1000000000,
1164                 },
1165         }})
1166         c.Assert(err, check.IsNil)
1167         c.Logf("container request %+v", cr)
1168         ctr, err := conn3.ContainerLock(rootctx3, arvados.GetOptions{UUID: cr.ContainerUUID})
1169         c.Assert(err, check.IsNil)
1170         c.Logf("container %+v", ctr)
1171
1172         // We could use conn3.ContainerAuth() here, but that API
1173         // hasn't been added to sdk/go/arvados/api.go yet.
1174         row := db3conn.QueryRowContext(context.Background(), `SELECT api_token from api_client_authorizations where uuid=$1`, ctr.AuthUUID)
1175         c.Check(row, check.NotNil)
1176         var val sql.NullString
1177         row.Scan(&val)
1178         c.Assert(val.Valid, check.Equals, true)
1179         runtimeToken := "v2/" + ctr.AuthUUID + "/" + val.String
1180         ctrctx, _, _ := s.super.ClientsWithToken("z3333", runtimeToken)
1181         c.Logf("container runtime token %+v", runtimeToken)
1182
1183         _, err = conn3.UserGet(ctrctx, arvados.GetOptions{UUID: user1.UUID})
1184         c.Assert(err, check.NotNil)
1185         c.Check(err, check.ErrorMatches, `request failed: .* 401 Unauthorized: cannot use a locally issued token to forward a request to our login cluster \(z1111\)`)
1186         c.Check(err, check.Not(check.ErrorMatches), `(?ms).*127\.0\.0\.11.*`)
1187 }
1188
1189 func (s *IntegrationSuite) TestRunTrivialContainer(c *check.C) {
1190         outcoll, _ := s.runContainer(c, "z1111", "", map[string]interface{}{
1191                 "command":             []string{"sh", "-c", "touch \"/out/hello world\" /out/ohai"},
1192                 "container_image":     "busybox:uclibc",
1193                 "cwd":                 "/tmp",
1194                 "environment":         map[string]string{},
1195                 "mounts":              map[string]arvados.Mount{"/out": {Kind: "tmp", Capacity: 10000}},
1196                 "output_path":         "/out",
1197                 "runtime_constraints": arvados.RuntimeConstraints{RAM: 100000000, VCPUs: 1, KeepCacheRAM: 1 << 26},
1198                 "priority":            1,
1199                 "state":               arvados.ContainerRequestStateCommitted,
1200         }, 0)
1201         c.Check(outcoll.ManifestText, check.Matches, `\. d41d8.* 0:0:hello\\040world 0:0:ohai\n`)
1202         c.Check(outcoll.PortableDataHash, check.Equals, "8fa5dee9231a724d7cf377c5a2f4907c+65")
1203 }
1204
1205 func (s *IntegrationSuite) TestContainerInputOnDifferentCluster(c *check.C) {
1206         conn := s.super.Conn("z1111")
1207         rootctx, _, _ := s.super.RootClients("z1111")
1208         userctx, ac, _, _ := s.super.UserClients("z1111", rootctx, c, conn, s.oidcprovider.AuthEmail, true)
1209         z1coll, err := conn.CollectionCreate(userctx, arvados.CreateOptions{Attrs: map[string]interface{}{
1210                 "manifest_text": ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:ocelot\n",
1211         }})
1212         c.Assert(err, check.IsNil)
1213
1214         outcoll, logcfs := s.runContainer(c, "z2222", ac.AuthToken, map[string]interface{}{
1215                 "command":         []string{"ls", "/in"},
1216                 "container_image": "busybox:uclibc",
1217                 "cwd":             "/tmp",
1218                 "environment":     map[string]string{},
1219                 "mounts": map[string]arvados.Mount{
1220                         "/in":  {Kind: "collection", PortableDataHash: z1coll.PortableDataHash},
1221                         "/out": {Kind: "tmp", Capacity: 10000},
1222                 },
1223                 "output_path":         "/out",
1224                 "runtime_constraints": arvados.RuntimeConstraints{RAM: 100000000, VCPUs: 1, KeepCacheRAM: 1 << 26},
1225                 "priority":            1,
1226                 "state":               arvados.ContainerRequestStateCommitted,
1227                 "container_count_max": 1,
1228         }, -1)
1229         if outcoll.UUID == "" {
1230                 arvmountlog, err := fs.ReadFile(arvados.FS(logcfs), "/arv-mount.txt")
1231                 c.Check(err, check.IsNil)
1232                 c.Check(string(arvmountlog), check.Matches, `(?ms).*cannot use a locally issued token to forward a request to our login cluster \(z1111\).*`)
1233                 c.Skip("this use case is not supported yet")
1234         }
1235         stdout, err := fs.ReadFile(arvados.FS(logcfs), "/stdout.txt")
1236         c.Check(err, check.IsNil)
1237         c.Check(string(stdout), check.Equals, "ocelot\n")
1238 }
1239
1240 func (s *IntegrationSuite) runContainer(c *check.C, clusterID string, token string, ctrSpec map[string]interface{}, expectExitCode int) (outcoll arvados.Collection, logcfs arvados.CollectionFileSystem) {
1241         conn := s.super.Conn(clusterID)
1242         rootctx, _, _ := s.super.RootClients(clusterID)
1243         if token == "" {
1244                 _, ac, _, _ := s.super.UserClients(clusterID, rootctx, c, conn, s.oidcprovider.AuthEmail, true)
1245                 token = ac.AuthToken
1246         }
1247         _, ac, kc := s.super.ClientsWithToken(clusterID, token)
1248
1249         c.Log("[docker load]")
1250         out, err := exec.Command("docker", "load", "--input", arvadostest.BusyboxDockerImage(c)).CombinedOutput()
1251         c.Logf("[docker load output] %s", out)
1252         c.Check(err, check.IsNil)
1253
1254         c.Log("[arv-keepdocker]")
1255         akd := exec.Command("arv-keepdocker", "--no-resume", "busybox:uclibc")
1256         akd.Env = append(os.Environ(), "ARVADOS_API_HOST="+ac.APIHost, "ARVADOS_API_HOST_INSECURE=1", "ARVADOS_API_TOKEN="+ac.AuthToken)
1257         out, err = akd.CombinedOutput()
1258         c.Logf("[arv-keepdocker output]\n%s", out)
1259         c.Check(err, check.IsNil)
1260
1261         var cr arvados.ContainerRequest
1262         err = ac.RequestAndDecode(&cr, "POST", "/arvados/v1/container_requests", nil, map[string]interface{}{
1263                 "container_request": ctrSpec,
1264         })
1265         c.Assert(err, check.IsNil)
1266
1267         showlogs := func(collectionID string) arvados.CollectionFileSystem {
1268                 var logcoll arvados.Collection
1269                 err = ac.RequestAndDecode(&logcoll, "GET", "/arvados/v1/collections/"+collectionID, nil, nil)
1270                 c.Assert(err, check.IsNil)
1271                 cfs, err := logcoll.FileSystem(ac, kc)
1272                 c.Assert(err, check.IsNil)
1273                 fs.WalkDir(arvados.FS(cfs), "/", func(path string, d fs.DirEntry, err error) error {
1274                         if d.IsDir() || strings.HasPrefix(path, "/log for container") {
1275                                 return nil
1276                         }
1277                         f, err := cfs.Open(path)
1278                         c.Assert(err, check.IsNil)
1279                         defer f.Close()
1280                         buf, err := ioutil.ReadAll(f)
1281                         c.Assert(err, check.IsNil)
1282                         c.Logf("=== %s\n%s\n", path, buf)
1283                         return nil
1284                 })
1285                 return cfs
1286         }
1287
1288         checkwebdavlogs := func(cr arvados.ContainerRequest) {
1289                 req, err := http.NewRequest("OPTIONS", "https://"+ac.APIHost+"/arvados/v1/container_requests/"+cr.UUID+"/log/"+cr.ContainerUUID+"/", nil)
1290                 c.Assert(err, check.IsNil)
1291                 req.Header.Set("Origin", "http://example.example")
1292                 resp, err := ac.Do(req)
1293                 c.Assert(err, check.IsNil)
1294                 c.Check(resp.StatusCode, check.Equals, http.StatusOK)
1295                 // Check for duplicate headers -- must use Header[], not Header.Get()
1296                 c.Check(resp.Header["Access-Control-Allow-Origin"], check.DeepEquals, []string{"*"})
1297         }
1298
1299         var ctr arvados.Container
1300         var lastState arvados.ContainerState
1301         var status, lastStatus arvados.ContainerStatus
1302         var allStatus string
1303         checkstatus := func() {
1304                 err := ac.RequestAndDecode(&status, "GET", "/arvados/v1/container_requests/"+cr.UUID+"/container_status", nil, nil)
1305                 c.Assert(err, check.IsNil)
1306                 if status != lastStatus {
1307                         c.Logf("container status: %s, %s", status.State, status.SchedulingStatus)
1308                         allStatus += fmt.Sprintf("%s, %s\n", status.State, status.SchedulingStatus)
1309                         lastStatus = status
1310                 }
1311         }
1312         deadline := time.Now().Add(time.Minute)
1313         for cr.State != arvados.ContainerRequestStateFinal || (lastStatus.State != arvados.ContainerStateComplete && lastStatus.State != arvados.ContainerStateCancelled) {
1314                 err = ac.RequestAndDecode(&cr, "GET", "/arvados/v1/container_requests/"+cr.UUID, nil, nil)
1315                 c.Assert(err, check.IsNil)
1316                 checkstatus()
1317                 err = ac.RequestAndDecode(&ctr, "GET", "/arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
1318                 if err != nil {
1319                         c.Logf("error getting container state: %s", err)
1320                 } else if ctr.State != lastState {
1321                         c.Logf("container state changed to %q", ctr.State)
1322                         lastState = ctr.State
1323                 } else {
1324                         if time.Now().After(deadline) {
1325                                 c.Errorf("timed out, container state is %q", cr.State)
1326                                 if ctr.Log == "" {
1327                                         c.Logf("=== NO LOG COLLECTION saved for container")
1328                                 } else {
1329                                         showlogs(ctr.Log)
1330                                 }
1331                                 c.FailNow()
1332                         }
1333                         time.Sleep(time.Second / 2)
1334                 }
1335         }
1336         checkstatus()
1337         c.Logf("cr.CumulativeCost == %f", cr.CumulativeCost)
1338         c.Check(cr.CumulativeCost, check.Not(check.Equals), 0.0)
1339         if expectExitCode >= 0 {
1340                 c.Check(ctr.State, check.Equals, arvados.ContainerStateComplete)
1341                 c.Check(ctr.ExitCode, check.Equals, expectExitCode)
1342                 err = ac.RequestAndDecode(&outcoll, "GET", "/arvados/v1/collections/"+cr.OutputUUID, nil, nil)
1343                 c.Assert(err, check.IsNil)
1344                 c.Check(allStatus, check.Matches, `(Queued, Waiting in queue\.\n)?`+
1345                         // Occasionally the dispatcher will
1346                         // unlock/retry, and we get state/status from
1347                         // database/dispatcher via separate API calls,
1348                         // so we can also see "Queued, preparing
1349                         // runtime environment".
1350                         `((Queued|Locked), (Waiting .*|Container is allocated to an instance and preparing to run\.)\n)*`+
1351                         `(Running, \n)?`+
1352                         `Complete, \n`)
1353         }
1354         logcfs = showlogs(cr.LogUUID)
1355         checkwebdavlogs(cr)
1356         return outcoll, logcfs
1357 }