21700: Install Bundler system-wide in Rails postinst
[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 func (s *IntegrationSuite) TestS3WithFederatedToken(c *check.C) {
303         if _, err := exec.LookPath("s3cmd"); err != nil {
304                 c.Skip("s3cmd not in PATH")
305                 return
306         }
307
308         testText := "IntegrationSuite.TestS3WithFederatedToken"
309
310         conn1 := s.super.Conn("z1111")
311         rootctx1, _, _ := s.super.RootClients("z1111")
312         userctx1, ac1, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
313         conn3 := s.super.Conn("z3333")
314
315         createColl := func(clusterID string) arvados.Collection {
316                 _, ac, kc := s.super.ClientsWithToken(clusterID, ac1.AuthToken)
317                 var coll arvados.Collection
318                 fs, err := coll.FileSystem(ac, kc)
319                 c.Assert(err, check.IsNil)
320                 f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
321                 c.Assert(err, check.IsNil)
322                 _, err = io.WriteString(f, testText)
323                 c.Assert(err, check.IsNil)
324                 err = f.Close()
325                 c.Assert(err, check.IsNil)
326                 mtxt, err := fs.MarshalManifest(".")
327                 c.Assert(err, check.IsNil)
328                 coll, err = s.super.Conn(clusterID).CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
329                         "manifest_text": mtxt,
330                 }})
331                 c.Assert(err, check.IsNil)
332                 return coll
333         }
334
335         for _, trial := range []struct {
336                 clusterID string // create the collection on this cluster (then use z3333 to access it)
337                 token     string
338         }{
339                 // Try the hardest test first: z3333 hasn't seen
340                 // z1111's token yet, and we're just passing the
341                 // opaque secret part, so z3333 has to guess that it
342                 // belongs to z1111.
343                 {"z1111", strings.Split(ac1.AuthToken, "/")[2]},
344                 {"z3333", strings.Split(ac1.AuthToken, "/")[2]},
345                 {"z1111", strings.Replace(ac1.AuthToken, "/", "_", -1)},
346                 {"z3333", strings.Replace(ac1.AuthToken, "/", "_", -1)},
347         } {
348                 c.Logf("================ %v", trial)
349                 coll := createColl(trial.clusterID)
350
351                 cfgjson, err := conn3.ConfigGet(userctx1)
352                 c.Assert(err, check.IsNil)
353                 var cluster arvados.Cluster
354                 err = json.Unmarshal(cfgjson, &cluster)
355                 c.Assert(err, check.IsNil)
356
357                 c.Logf("TokenV2 is %s", ac1.AuthToken)
358                 host := cluster.Services.WebDAV.ExternalURL.Host
359                 s3args := []string{
360                         "--ssl", "--no-check-certificate",
361                         "--host=" + host, "--host-bucket=" + host,
362                         "--access_key=" + trial.token, "--secret_key=" + trial.token,
363                 }
364                 buf, err := exec.Command("s3cmd", append(s3args, "ls", "s3://"+coll.UUID)...).CombinedOutput()
365                 c.Check(err, check.IsNil)
366                 c.Check(string(buf), check.Matches, `.* `+fmt.Sprintf("%d", len(testText))+` +s3://`+coll.UUID+`/test.txt\n`)
367
368                 buf, _ = exec.Command("s3cmd", append(s3args, "get", "s3://"+coll.UUID+"/test.txt", c.MkDir()+"/tmpfile")...).CombinedOutput()
369                 // Command fails because we don't return Etag header.
370                 flen := strconv.Itoa(len(testText))
371                 c.Check(string(buf), check.Matches, `(?ms).*`+flen+` (bytes in|of `+flen+`).*`)
372         }
373 }
374
375 func (s *IntegrationSuite) TestGetCollectionAsAnonymous(c *check.C) {
376         conn1 := s.super.Conn("z1111")
377         conn3 := s.super.Conn("z3333")
378         rootctx1, rootac1, rootkc1 := s.super.RootClients("z1111")
379         anonctx3, anonac3, _ := s.super.AnonymousClients("z3333")
380
381         // Make sure anonymous token was set
382         c.Assert(anonac3.AuthToken, check.Not(check.Equals), "")
383
384         // Create the collection to find its PDH (but don't save it
385         // anywhere yet)
386         var coll1 arvados.Collection
387         fs1, err := coll1.FileSystem(rootac1, rootkc1)
388         c.Assert(err, check.IsNil)
389         f, err := fs1.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
390         c.Assert(err, check.IsNil)
391         _, err = io.WriteString(f, "IntegrationSuite.TestGetCollectionAsAnonymous")
392         c.Assert(err, check.IsNil)
393         err = f.Close()
394         c.Assert(err, check.IsNil)
395         mtxt, err := fs1.MarshalManifest(".")
396         c.Assert(err, check.IsNil)
397         pdh := arvados.PortableDataHash(mtxt)
398
399         // Save the collection on cluster z1111.
400         coll1, err = conn1.CollectionCreate(rootctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
401                 "manifest_text": mtxt,
402         }})
403         c.Assert(err, check.IsNil)
404
405         // Share it with the anonymous users group.
406         var outLink arvados.Link
407         err = rootac1.RequestAndDecode(&outLink, "POST", "/arvados/v1/links", nil,
408                 map[string]interface{}{"link": map[string]interface{}{
409                         "link_class": "permission",
410                         "name":       "can_read",
411                         "tail_uuid":  "z1111-j7d0g-anonymouspublic",
412                         "head_uuid":  coll1.UUID,
413                 },
414                 })
415         c.Check(err, check.IsNil)
416
417         // Current user should be z3 anonymous user
418         outUser, err := anonac3.CurrentUser()
419         c.Check(err, check.IsNil)
420         c.Check(outUser.UUID, check.Equals, "z3333-tpzed-anonymouspublic")
421
422         // Get the token uuid
423         var outAuth arvados.APIClientAuthorization
424         err = anonac3.RequestAndDecode(&outAuth, "GET", "/arvados/v1/api_client_authorizations/current", nil, nil)
425         c.Check(err, check.IsNil)
426
427         // Make a v2 token of the z3 anonymous user, and use it on z1
428         _, anonac1, _ := s.super.ClientsWithToken("z1111", outAuth.TokenV2())
429         outUser2, err := anonac1.CurrentUser()
430         c.Check(err, check.IsNil)
431         // z3 anonymous user will be mapped to the z1 anonymous user
432         c.Check(outUser2.UUID, check.Equals, "z1111-tpzed-anonymouspublic")
433
434         // Retrieve the collection (which is on z1) using anonymous from cluster z3333.
435         coll, err := conn3.CollectionGet(anonctx3, arvados.GetOptions{UUID: coll1.UUID})
436         c.Check(err, check.IsNil)
437         c.Check(coll.PortableDataHash, check.Equals, pdh)
438 }
439
440 // z3333 should forward the locally-issued anonymous user token to its login
441 // cluster z1111. That is no problem because the login cluster controller will
442 // map any anonymous user token to its local anonymous user.
443 //
444 // This needs to work because wb1 has a tendency to slap the local anonymous
445 // user token on every request as a reader_token, which gets folded into the
446 // request token list controller.
447 //
448 // Use a z1111 user token and the anonymous token from z3333 passed in as a
449 // reader_token to do a request on z3333, asking for the z1111 anonymous user
450 // object. The request will be forwarded to the z1111 cluster. The presence of
451 // the z3333 anonymous user token should not prohibit the request from being
452 // forwarded.
453 func (s *IntegrationSuite) TestForwardAnonymousTokenToLoginCluster(c *check.C) {
454         conn1 := s.super.Conn("z1111")
455
456         rootctx1, _, _ := s.super.RootClients("z1111")
457         _, anonac3, _ := s.super.AnonymousClients("z3333")
458
459         // Make a user connection to z3333 (using a z1111 user, because that's the login cluster)
460         _, userac1, _, _ := s.super.UserClients("z3333", rootctx1, c, conn1, "user@example.com", true)
461
462         // Get the anonymous user token for z3333
463         var anon3Auth arvados.APIClientAuthorization
464         err := anonac3.RequestAndDecode(&anon3Auth, "GET", "/arvados/v1/api_client_authorizations/current", nil, nil)
465         c.Check(err, check.IsNil)
466
467         var userList arvados.UserList
468         where := make(map[string]string)
469         where["uuid"] = "z1111-tpzed-anonymouspublic"
470         err = userac1.RequestAndDecode(&userList, "GET", "/arvados/v1/users", nil,
471                 map[string]interface{}{
472                         "reader_tokens": []string{anon3Auth.TokenV2()},
473                         "where":         where,
474                 },
475         )
476         // The local z3333 anonymous token must be allowed to be forwarded to the login cluster
477         c.Check(err, check.IsNil)
478
479         userac1.AuthToken = "v2/z1111-gj3su-asdfasdfasdfasd/this-token-does-not-validate-so-anonymous-token-will-be-used-instead"
480         err = userac1.RequestAndDecode(&userList, "GET", "/arvados/v1/users", nil,
481                 map[string]interface{}{
482                         "reader_tokens": []string{anon3Auth.TokenV2()},
483                         "where":         where,
484                 },
485         )
486         c.Check(err, check.IsNil)
487 }
488
489 // Get a token from the login cluster (z1111), use it to submit a
490 // container request on z2222.
491 func (s *IntegrationSuite) TestCreateContainerRequestWithFedToken(c *check.C) {
492         conn1 := s.super.Conn("z1111")
493         rootctx1, _, _ := s.super.RootClients("z1111")
494         _, ac1, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
495
496         // Use ac2 to get the discovery doc with a blank token, so the
497         // SDK doesn't magically pass the z1111 token to z2222 before
498         // we're ready to start our test.
499         _, ac2, _ := s.super.ClientsWithToken("z2222", "")
500         var dd map[string]interface{}
501         err := ac2.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
502         c.Assert(err, check.IsNil)
503
504         var (
505                 body bytes.Buffer
506                 req  *http.Request
507                 resp *http.Response
508                 u    arvados.User
509                 cr   arvados.ContainerRequest
510         )
511         json.NewEncoder(&body).Encode(map[string]interface{}{
512                 "container_request": map[string]interface{}{
513                         "command":         []string{"echo"},
514                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
515                         "cwd":             "/",
516                         "output_path":     "/",
517                 },
518         })
519         ac2.AuthToken = ac1.AuthToken
520
521         c.Log("...post CR with good (but not yet cached) token")
522         cr = arvados.ContainerRequest{}
523         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
524         c.Assert(err, check.IsNil)
525         req.Header.Set("Content-Type", "application/json")
526         err = ac2.DoAndDecode(&cr, req)
527         c.Assert(err, check.IsNil)
528         c.Logf("err == %#v", err)
529
530         c.Log("...get user with good token")
531         u = arvados.User{}
532         req, err = http.NewRequest("GET", "https://"+ac2.APIHost+"/arvados/v1/users/current", nil)
533         c.Assert(err, check.IsNil)
534         err = ac2.DoAndDecode(&u, req)
535         c.Check(err, check.IsNil)
536         c.Check(u.UUID, check.Matches, "z1111-tpzed-.*")
537
538         c.Log("...post CR with good cached token")
539         cr = arvados.ContainerRequest{}
540         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
541         c.Assert(err, check.IsNil)
542         req.Header.Set("Content-Type", "application/json")
543         err = ac2.DoAndDecode(&cr, req)
544         c.Check(err, check.IsNil)
545         c.Check(cr.UUID, check.Matches, "z2222-.*")
546
547         c.Log("...post with good cached token ('OAuth2 ...')")
548         cr = arvados.ContainerRequest{}
549         req, err = http.NewRequest("POST", "https://"+ac2.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body.Bytes()))
550         c.Assert(err, check.IsNil)
551         req.Header.Set("Content-Type", "application/json")
552         req.Header.Set("Authorization", "OAuth2 "+ac2.AuthToken)
553         resp, err = arvados.InsecureHTTPClient.Do(req)
554         c.Assert(err, check.IsNil)
555         defer resp.Body.Close()
556         err = json.NewDecoder(resp.Body).Decode(&cr)
557         c.Check(err, check.IsNil)
558         c.Check(cr.UUID, check.Matches, "z2222-.*")
559 }
560
561 func (s *IntegrationSuite) TestCreateContainerRequestWithBadToken(c *check.C) {
562         conn1 := s.super.Conn("z1111")
563         rootctx1, _, _ := s.super.RootClients("z1111")
564         _, ac1, _, au := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
565
566         tests := []struct {
567                 name         string
568                 token        string
569                 expectedCode int
570         }{
571                 {"Good token", ac1.AuthToken, http.StatusOK},
572                 {"Bogus token", "abcdef", http.StatusUnauthorized},
573                 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", http.StatusUnauthorized},
574                 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", http.StatusUnauthorized},
575         }
576
577         body, _ := json.Marshal(map[string]interface{}{
578                 "container_request": map[string]interface{}{
579                         "command":         []string{"echo"},
580                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
581                         "cwd":             "/",
582                         "output_path":     "/",
583                 },
584         })
585
586         for _, tt := range tests {
587                 c.Log(c.TestName() + " " + tt.name)
588                 ac1.AuthToken = tt.token
589                 req, err := http.NewRequest("POST", "https://"+ac1.APIHost+"/arvados/v1/container_requests", bytes.NewReader(body))
590                 c.Assert(err, check.IsNil)
591                 req.Header.Set("Content-Type", "application/json")
592                 resp, err := ac1.Do(req)
593                 if c.Check(err, check.IsNil) {
594                         c.Assert(resp.StatusCode, check.Equals, tt.expectedCode)
595                         resp.Body.Close()
596                 }
597         }
598 }
599
600 func (s *IntegrationSuite) TestRequestIDHeader(c *check.C) {
601         conn1 := s.super.Conn("z1111")
602         rootctx1, _, _ := s.super.RootClients("z1111")
603         userctx1, ac1, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
604
605         coll, err := conn1.CollectionCreate(userctx1, arvados.CreateOptions{})
606         c.Check(err, check.IsNil)
607         specimen, err := conn1.SpecimenCreate(userctx1, arvados.CreateOptions{})
608         c.Check(err, check.IsNil)
609
610         tests := []struct {
611                 path            string
612                 reqIdProvided   bool
613                 notFoundRequest bool
614         }{
615                 {"/arvados/v1/collections", false, false},
616                 {"/arvados/v1/collections", true, false},
617                 {"/arvados/v1/nonexistant", false, true},
618                 {"/arvados/v1/nonexistant", true, true},
619                 {"/arvados/v1/collections/" + coll.UUID, false, false},
620                 {"/arvados/v1/collections/" + coll.UUID, true, false},
621                 {"/arvados/v1/specimens/" + specimen.UUID, false, false},
622                 {"/arvados/v1/specimens/" + specimen.UUID, true, false},
623                 // new code path (lib/controller/router etc) - single-cluster request
624                 {"/arvados/v1/collections/z1111-4zz18-0123456789abcde", false, true},
625                 {"/arvados/v1/collections/z1111-4zz18-0123456789abcde", true, true},
626                 // new code path (lib/controller/router etc) - federated request
627                 {"/arvados/v1/collections/z2222-4zz18-0123456789abcde", false, true},
628                 {"/arvados/v1/collections/z2222-4zz18-0123456789abcde", true, true},
629                 // old code path (proxyRailsAPI) - single-cluster request
630                 {"/arvados/v1/specimens/z1111-j58dm-0123456789abcde", false, true},
631                 {"/arvados/v1/specimens/z1111-j58dm-0123456789abcde", true, true},
632                 // old code path (setupProxyRemoteCluster) - federated request
633                 {"/arvados/v1/workflows/z2222-7fd4e-0123456789abcde", false, true},
634                 {"/arvados/v1/workflows/z2222-7fd4e-0123456789abcde", true, true},
635         }
636
637         for _, tt := range tests {
638                 c.Log(c.TestName() + " " + tt.path)
639                 req, err := http.NewRequest("GET", "https://"+ac1.APIHost+tt.path, nil)
640                 c.Assert(err, check.IsNil)
641                 customReqId := "abcdeG"
642                 if !tt.reqIdProvided {
643                         c.Assert(req.Header.Get("X-Request-Id"), check.Equals, "")
644                 } else {
645                         req.Header.Set("X-Request-Id", customReqId)
646                 }
647                 resp, err := ac1.Do(req)
648                 c.Assert(err, check.IsNil)
649                 if tt.notFoundRequest {
650                         c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
651                 } else {
652                         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
653                 }
654                 respHdr := resp.Header.Get("X-Request-Id")
655                 if tt.reqIdProvided {
656                         c.Check(respHdr, check.Equals, customReqId)
657                 } else {
658                         c.Check(respHdr, check.Matches, `req-[0-9a-zA-Z]{20}`)
659                 }
660                 if tt.notFoundRequest {
661                         var jresp httpserver.ErrorResponse
662                         err := json.NewDecoder(resp.Body).Decode(&jresp)
663                         c.Check(err, check.IsNil)
664                         if c.Check(jresp.Errors, check.HasLen, 1) {
665                                 c.Check(jresp.Errors[0], check.Matches, `.*\(`+respHdr+`\).*`)
666                         }
667                 }
668                 resp.Body.Close()
669         }
670 }
671
672 // We test the direct access to the database
673 // normally an integration test would not have a database access, but in this case we need
674 // to test tokens that are secret, so there is no API response that will give them back
675 func (s *IntegrationSuite) dbConn(c *check.C, clusterID string) (*sql.DB, *sql.Conn) {
676         ctx := context.Background()
677         db, err := sql.Open("postgres", s.super.Cluster(clusterID).PostgreSQL.Connection.String())
678         c.Assert(err, check.IsNil)
679
680         conn, err := db.Conn(ctx)
681         c.Assert(err, check.IsNil)
682
683         rows, err := conn.ExecContext(ctx, `SELECT 1`)
684         c.Assert(err, check.IsNil)
685         n, err := rows.RowsAffected()
686         c.Assert(err, check.IsNil)
687         c.Assert(n, check.Equals, int64(1))
688         return db, conn
689 }
690
691 // TestRuntimeTokenInCR will test several different tokens in the runtime attribute
692 // and check the expected results accessing directly to the database if needed.
693 func (s *IntegrationSuite) TestRuntimeTokenInCR(c *check.C) {
694         db, dbconn := s.dbConn(c, "z1111")
695         defer db.Close()
696         defer dbconn.Close()
697         conn1 := s.super.Conn("z1111")
698         rootctx1, _, _ := s.super.RootClients("z1111")
699         userctx1, ac1, _, au := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
700
701         tests := []struct {
702                 name                 string
703                 token                string
704                 expectAToGetAValidCR bool
705                 expectedToken        *string
706         }{
707                 {"Good token z1111 user", ac1.AuthToken, true, &ac1.AuthToken},
708                 {"Bogus token", "abcdef", false, nil},
709                 {"v1-looking token", "badtoken00badtoken00badtoken00badtoken00b", false, nil},
710                 {"v2-looking token", "v2/" + au.UUID + "/badtoken00badtoken00badtoken00badtoken00b", false, nil},
711         }
712
713         for _, tt := range tests {
714                 c.Log(c.TestName() + " " + tt.name)
715
716                 rq := map[string]interface{}{
717                         "command":         []string{"echo"},
718                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
719                         "cwd":             "/",
720                         "output_path":     "/",
721                         "runtime_token":   tt.token,
722                 }
723                 cr, err := conn1.ContainerRequestCreate(userctx1, arvados.CreateOptions{Attrs: rq})
724                 if tt.expectAToGetAValidCR {
725                         c.Check(err, check.IsNil)
726                         c.Check(cr, check.NotNil)
727                         c.Check(cr.UUID, check.Not(check.Equals), "")
728                 }
729
730                 if tt.expectedToken == nil {
731                         continue
732                 }
733
734                 c.Logf("cr.UUID: %s", cr.UUID)
735                 row := dbconn.QueryRowContext(rootctx1, `SELECT runtime_token from container_requests where uuid=$1`, cr.UUID)
736                 c.Check(row, check.NotNil)
737                 var token sql.NullString
738                 row.Scan(&token)
739                 if c.Check(token.Valid, check.Equals, true) {
740                         c.Check(token.String, check.Equals, *tt.expectedToken)
741                 }
742         }
743 }
744
745 // TestIntermediateCluster will send a container request to
746 // one cluster with another cluster as the destination
747 // and check the tokens are being handled properly
748 func (s *IntegrationSuite) TestIntermediateCluster(c *check.C) {
749         conn1 := s.super.Conn("z1111")
750         rootctx1, _, _ := s.super.RootClients("z1111")
751         uctx1, ac1, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
752
753         tests := []struct {
754                 name                 string
755                 token                string
756                 expectedRuntimeToken string
757                 expectedUUIDprefix   string
758         }{
759                 {"Good token z1111 user sending a CR to z2222", ac1.AuthToken, "", "z2222-xvhdp-"},
760         }
761
762         for _, tt := range tests {
763                 c.Log(c.TestName() + " " + tt.name)
764                 rq := map[string]interface{}{
765                         "command":         []string{"echo"},
766                         "container_image": "d41d8cd98f00b204e9800998ecf8427e+0",
767                         "cwd":             "/",
768                         "output_path":     "/",
769                         "runtime_token":   tt.token,
770                 }
771                 cr, err := conn1.ContainerRequestCreate(uctx1, arvados.CreateOptions{ClusterID: "z2222", Attrs: rq})
772
773                 c.Check(err, check.IsNil)
774                 c.Check(strings.HasPrefix(cr.UUID, tt.expectedUUIDprefix), check.Equals, true)
775                 c.Check(cr.RuntimeToken, check.Equals, tt.expectedRuntimeToken)
776         }
777 }
778
779 // Test for #17785
780 func (s *IntegrationSuite) TestFederatedApiClientAuthHandling(c *check.C) {
781         rootctx1, rootclnt1, _ := s.super.RootClients("z1111")
782         conn1 := s.super.Conn("z1111")
783
784         // Make sure LoginCluster is properly configured
785         for _, cls := range []string{"z1111", "z3333"} {
786                 c.Check(
787                         s.super.Cluster(cls).Login.LoginCluster,
788                         check.Equals, "z1111",
789                         check.Commentf("incorrect LoginCluster config on cluster %q", cls))
790         }
791         // Get user's UUID & attempt to create a token for it on the remote cluster
792         _, _, _, user := s.super.UserClients("z1111", rootctx1, c, conn1,
793                 "user@example.com", true)
794         _, rootclnt3, _ := s.super.ClientsWithToken("z3333", rootclnt1.AuthToken)
795         var resp arvados.APIClientAuthorization
796         err := rootclnt3.RequestAndDecode(
797                 &resp, "POST", "arvados/v1/api_client_authorizations", nil,
798                 map[string]interface{}{
799                         "api_client_authorization": map[string]string{
800                                 "owner_uuid": user.UUID,
801                         },
802                 },
803         )
804         c.Assert(err, check.IsNil)
805         c.Assert(resp.APIClientID, check.Not(check.Equals), 0)
806         newTok := resp.TokenV2()
807         c.Assert(newTok, check.Not(check.Equals), "")
808
809         // Confirm the token is from z1111
810         c.Assert(strings.HasPrefix(newTok, "v2/z1111-gj3su-"), check.Equals, true)
811
812         // Confirm the token works and is from the correct user
813         _, rootclnt3bis, _ := s.super.ClientsWithToken("z3333", newTok)
814         var curUser arvados.User
815         err = rootclnt3bis.RequestAndDecode(
816                 &curUser, "GET", "arvados/v1/users/current", nil, nil,
817         )
818         c.Assert(err, check.IsNil)
819         c.Assert(curUser.UUID, check.Equals, user.UUID)
820
821         // Request the ApiClientAuthorization list using the new token
822         _, userClient, _ := s.super.ClientsWithToken("z3333", newTok)
823         var acaLst arvados.APIClientAuthorizationList
824         err = userClient.RequestAndDecode(
825                 &acaLst, "GET", "arvados/v1/api_client_authorizations", nil, nil,
826         )
827         c.Assert(err, check.IsNil)
828 }
829
830 // Test for bug #18076
831 func (s *IntegrationSuite) TestStaleCachedUserRecord(c *check.C) {
832         rootctx1, _, _ := s.super.RootClients("z1111")
833         _, rootclnt3, _ := s.super.RootClients("z3333")
834         conn1 := s.super.Conn("z1111")
835         conn3 := s.super.Conn("z3333")
836
837         // Make sure LoginCluster is properly configured
838         for _, cls := range []string{"z1111", "z3333"} {
839                 c.Check(
840                         s.super.Cluster(cls).Login.LoginCluster,
841                         check.Equals, "z1111",
842                         check.Commentf("incorrect LoginCluster config on cluster %q", cls))
843         }
844
845         for testCaseNr, testCase := range []struct {
846                 name           string
847                 withRepository bool
848         }{
849                 {"User without local repository", false},
850                 {"User with local repository", true},
851         } {
852                 c.Log(c.TestName() + " " + testCase.name)
853                 // Create some users, request them on the federated cluster so they're cached.
854                 var users []arvados.User
855                 for userNr := 0; userNr < 2; userNr++ {
856                         _, _, _, user := s.super.UserClients("z1111",
857                                 rootctx1,
858                                 c,
859                                 conn1,
860                                 fmt.Sprintf("user%d%d@example.com", testCaseNr, userNr),
861                                 true)
862                         c.Assert(user.Username, check.Not(check.Equals), "")
863                         users = append(users, user)
864
865                         lst, err := conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
866                         c.Assert(err, check.Equals, nil)
867                         userFound := false
868                         for _, fedUser := range lst.Items {
869                                 if fedUser.UUID == user.UUID {
870                                         c.Assert(fedUser.Username, check.Equals, user.Username)
871                                         userFound = true
872                                         break
873                                 }
874                         }
875                         c.Assert(userFound, check.Equals, true)
876
877                         if testCase.withRepository {
878                                 var repo interface{}
879                                 err = rootclnt3.RequestAndDecode(
880                                         &repo, "POST", "arvados/v1/repositories", nil,
881                                         map[string]interface{}{
882                                                 "repository": map[string]string{
883                                                         "name":       fmt.Sprintf("%s/test", user.Username),
884                                                         "owner_uuid": user.UUID,
885                                                 },
886                                         },
887                                 )
888                                 c.Assert(err, check.IsNil)
889                         }
890                 }
891
892                 // Swap the usernames
893                 _, err := conn1.UserUpdate(rootctx1, arvados.UpdateOptions{
894                         UUID: users[0].UUID,
895                         Attrs: map[string]interface{}{
896                                 "username": "",
897                         },
898                 })
899                 c.Assert(err, check.Equals, nil)
900                 _, err = conn1.UserUpdate(rootctx1, arvados.UpdateOptions{
901                         UUID: users[1].UUID,
902                         Attrs: map[string]interface{}{
903                                 "username": users[0].Username,
904                         },
905                 })
906                 c.Assert(err, check.Equals, nil)
907                 _, err = conn1.UserUpdate(rootctx1, arvados.UpdateOptions{
908                         UUID: users[0].UUID,
909                         Attrs: map[string]interface{}{
910                                 "username": users[1].Username,
911                         },
912                 })
913                 c.Assert(err, check.Equals, nil)
914
915                 // Re-request the list on the federated cluster & check for updates
916                 lst, err := conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
917                 c.Assert(err, check.Equals, nil)
918                 var user0Found, user1Found bool
919                 for _, user := range lst.Items {
920                         if user.UUID == users[0].UUID {
921                                 user0Found = true
922                                 c.Assert(user.Username, check.Equals, users[1].Username)
923                         } else if user.UUID == users[1].UUID {
924                                 user1Found = true
925                                 c.Assert(user.Username, check.Equals, users[0].Username)
926                         }
927                 }
928                 c.Assert(user0Found, check.Equals, true)
929                 c.Assert(user1Found, check.Equals, true)
930         }
931 }
932
933 // Test for bug #16263
934 func (s *IntegrationSuite) TestListUsers(c *check.C) {
935         rootctx1, _, _ := s.super.RootClients("z1111")
936         conn1 := s.super.Conn("z1111")
937         conn3 := s.super.Conn("z3333")
938         userctx1, _, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
939
940         // Make sure LoginCluster is properly configured
941         for _, cls := range []string{"z1111", "z2222", "z3333"} {
942                 c.Check(
943                         s.super.Cluster(cls).Login.LoginCluster,
944                         check.Equals, "z1111",
945                         check.Commentf("incorrect LoginCluster config on cluster %q", cls))
946         }
947         // Make sure z1111 has users with NULL usernames
948         lst, err := conn1.UserList(rootctx1, arvados.ListOptions{
949                 Limit: math.MaxInt64, // check that large limit works (see #16263)
950         })
951         nullUsername := false
952         c.Assert(err, check.IsNil)
953         c.Assert(len(lst.Items), check.Not(check.Equals), 0)
954         for _, user := range lst.Items {
955                 if user.Username == "" {
956                         nullUsername = true
957                         break
958                 }
959         }
960         c.Assert(nullUsername, check.Equals, true)
961
962         user1, err := conn1.UserGetCurrent(userctx1, arvados.GetOptions{})
963         c.Assert(err, check.IsNil)
964         c.Check(user1.IsActive, check.Equals, true)
965
966         // Ask for the user list on z3333 using z1111's system root token
967         lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
968         c.Assert(err, check.IsNil)
969         found := false
970         for _, user := range lst.Items {
971                 if user.UUID == user1.UUID {
972                         c.Check(user.IsActive, check.Equals, true)
973                         found = true
974                         break
975                 }
976         }
977         c.Check(found, check.Equals, true)
978
979         // Deactivate user acct on z1111
980         _, err = conn1.UserUnsetup(rootctx1, arvados.GetOptions{UUID: user1.UUID})
981         c.Assert(err, check.IsNil)
982
983         // Get user list from z3333, check the returned z1111 user is
984         // deactivated
985         lst, err = conn3.UserList(rootctx1, arvados.ListOptions{Limit: -1})
986         c.Assert(err, check.IsNil)
987         found = false
988         for _, user := range lst.Items {
989                 if user.UUID == user1.UUID {
990                         c.Check(user.IsActive, check.Equals, false)
991                         found = true
992                         break
993                 }
994         }
995         c.Check(found, check.Equals, true)
996
997         // Deactivated user no longer has working token
998         user1, err = conn3.UserGetCurrent(userctx1, arvados.GetOptions{})
999         c.Assert(err, check.ErrorMatches, `.*401 Unauthorized.*`)
1000 }
1001
1002 func (s *IntegrationSuite) TestSetupUserWithVM(c *check.C) {
1003         conn1 := s.super.Conn("z1111")
1004         conn3 := s.super.Conn("z3333")
1005         rootctx1, rootac1, _ := s.super.RootClients("z1111")
1006
1007         // Create user on LoginCluster z1111
1008         _, _, _, user := s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
1009
1010         // Make a new root token (because rootClients() uses SystemRootToken)
1011         var outAuth arvados.APIClientAuthorization
1012         err := rootac1.RequestAndDecode(&outAuth, "POST", "/arvados/v1/api_client_authorizations", nil, nil)
1013         c.Check(err, check.IsNil)
1014
1015         // Make a v2 root token to communicate with z3333
1016         rootctx3, rootac3, _ := s.super.ClientsWithToken("z3333", outAuth.TokenV2())
1017
1018         // Create VM on z3333
1019         var outVM arvados.VirtualMachine
1020         err = rootac3.RequestAndDecode(&outVM, "POST", "/arvados/v1/virtual_machines", nil,
1021                 map[string]interface{}{"virtual_machine": map[string]interface{}{
1022                         "hostname": "example",
1023                 },
1024                 })
1025         c.Assert(err, check.IsNil)
1026         c.Check(outVM.UUID[0:5], check.Equals, "z3333")
1027
1028         // Make sure z3333 user list is up to date
1029         _, err = conn3.UserList(rootctx3, arvados.ListOptions{Limit: 1000})
1030         c.Check(err, check.IsNil)
1031
1032         // Try to set up user on z3333 with the VM
1033         _, err = conn3.UserSetup(rootctx3, arvados.UserSetupOptions{UUID: user.UUID, VMUUID: outVM.UUID})
1034         c.Check(err, check.IsNil)
1035
1036         var outLinks arvados.LinkList
1037         err = rootac3.RequestAndDecode(&outLinks, "GET", "/arvados/v1/links", nil,
1038                 arvados.ListOptions{
1039                         Limit: 1000,
1040                         Filters: []arvados.Filter{
1041                                 {
1042                                         Attr:     "tail_uuid",
1043                                         Operator: "=",
1044                                         Operand:  user.UUID,
1045                                 },
1046                                 {
1047                                         Attr:     "head_uuid",
1048                                         Operator: "=",
1049                                         Operand:  outVM.UUID,
1050                                 },
1051                                 {
1052                                         Attr:     "name",
1053                                         Operator: "=",
1054                                         Operand:  "can_login",
1055                                 },
1056                                 {
1057                                         Attr:     "link_class",
1058                                         Operator: "=",
1059                                         Operand:  "permission",
1060                                 }}})
1061         c.Check(err, check.IsNil)
1062
1063         c.Check(len(outLinks.Items), check.Equals, 1)
1064 }
1065
1066 func (s *IntegrationSuite) TestOIDCAccessTokenAuth(c *check.C) {
1067         conn1 := s.super.Conn("z1111")
1068         rootctx1, _, _ := s.super.RootClients("z1111")
1069         s.super.UserClients("z1111", rootctx1, c, conn1, s.oidcprovider.AuthEmail, true)
1070
1071         accesstoken := s.oidcprovider.ValidAccessToken()
1072
1073         for _, clusterID := range []string{"z1111", "z2222"} {
1074
1075                 var coll arvados.Collection
1076
1077                 // Write some file data and create a collection
1078                 {
1079                         c.Logf("save collection to %s", clusterID)
1080
1081                         conn := s.super.Conn(clusterID)
1082                         ctx, ac, kc := s.super.ClientsWithToken(clusterID, accesstoken)
1083
1084                         fs, err := coll.FileSystem(ac, kc)
1085                         c.Assert(err, check.IsNil)
1086                         f, err := fs.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0777)
1087                         c.Assert(err, check.IsNil)
1088                         _, err = io.WriteString(f, "IntegrationSuite.TestOIDCAccessTokenAuth")
1089                         c.Assert(err, check.IsNil)
1090                         err = f.Close()
1091                         c.Assert(err, check.IsNil)
1092                         mtxt, err := fs.MarshalManifest(".")
1093                         c.Assert(err, check.IsNil)
1094                         coll, err = conn.CollectionCreate(ctx, arvados.CreateOptions{Attrs: map[string]interface{}{
1095                                 "manifest_text": mtxt,
1096                         }})
1097                         c.Assert(err, check.IsNil)
1098                 }
1099
1100                 // Read the collection & file data -- both from the
1101                 // cluster where it was created, and from the other
1102                 // cluster.
1103                 for _, readClusterID := range []string{"z1111", "z2222", "z3333"} {
1104                         c.Logf("retrieve %s from %s", coll.UUID, readClusterID)
1105
1106                         conn := s.super.Conn(readClusterID)
1107                         ctx, ac, kc := s.super.ClientsWithToken(readClusterID, accesstoken)
1108
1109                         user, err := conn.UserGetCurrent(ctx, arvados.GetOptions{})
1110                         c.Assert(err, check.IsNil)
1111                         c.Check(user.FullName, check.Equals, "Example User")
1112                         readcoll, err := conn.CollectionGet(ctx, arvados.GetOptions{UUID: coll.UUID})
1113                         c.Assert(err, check.IsNil)
1114                         c.Check(readcoll.ManifestText, check.Not(check.Equals), "")
1115                         fs, err := readcoll.FileSystem(ac, kc)
1116                         c.Assert(err, check.IsNil)
1117                         f, err := fs.Open("test.txt")
1118                         c.Assert(err, check.IsNil)
1119                         buf, err := ioutil.ReadAll(f)
1120                         c.Assert(err, check.IsNil)
1121                         c.Check(buf, check.DeepEquals, []byte("IntegrationSuite.TestOIDCAccessTokenAuth"))
1122                 }
1123         }
1124 }
1125
1126 // z3333 should not forward a locally-issued container runtime token,
1127 // associated with a z1111 user, to its login cluster z1111. z1111
1128 // would only call back to z3333 and then reject the response because
1129 // the user ID does not match the token prefix. See
1130 // dev.arvados.org/issues/18346
1131 func (s *IntegrationSuite) TestForwardRuntimeTokenToLoginCluster(c *check.C) {
1132         db3, db3conn := s.dbConn(c, "z3333")
1133         defer db3.Close()
1134         defer db3conn.Close()
1135         rootctx1, _, _ := s.super.RootClients("z1111")
1136         rootctx3, _, _ := s.super.RootClients("z3333")
1137         conn1 := s.super.Conn("z1111")
1138         conn3 := s.super.Conn("z3333")
1139         userctx1, _, _, _ := s.super.UserClients("z1111", rootctx1, c, conn1, "user@example.com", true)
1140
1141         user1, err := conn1.UserGetCurrent(userctx1, arvados.GetOptions{})
1142         c.Assert(err, check.IsNil)
1143         c.Logf("user1 %+v", user1)
1144
1145         imageColl, err := conn3.CollectionCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
1146                 "manifest_text": ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.tar\n",
1147         }})
1148         c.Assert(err, check.IsNil)
1149         c.Logf("imageColl %+v", imageColl)
1150
1151         cr, err := conn3.ContainerRequestCreate(userctx1, arvados.CreateOptions{Attrs: map[string]interface{}{
1152                 "state":           "Committed",
1153                 "command":         []string{"echo"},
1154                 "container_image": imageColl.PortableDataHash,
1155                 "cwd":             "/",
1156                 "output_path":     "/",
1157                 "priority":        1,
1158                 "runtime_constraints": arvados.RuntimeConstraints{
1159                         VCPUs: 1,
1160                         RAM:   1000000000,
1161                 },
1162         }})
1163         c.Assert(err, check.IsNil)
1164         c.Logf("container request %+v", cr)
1165         ctr, err := conn3.ContainerLock(rootctx3, arvados.GetOptions{UUID: cr.ContainerUUID})
1166         c.Assert(err, check.IsNil)
1167         c.Logf("container %+v", ctr)
1168
1169         // We could use conn3.ContainerAuth() here, but that API
1170         // hasn't been added to sdk/go/arvados/api.go yet.
1171         row := db3conn.QueryRowContext(context.Background(), `SELECT api_token from api_client_authorizations where uuid=$1`, ctr.AuthUUID)
1172         c.Check(row, check.NotNil)
1173         var val sql.NullString
1174         row.Scan(&val)
1175         c.Assert(val.Valid, check.Equals, true)
1176         runtimeToken := "v2/" + ctr.AuthUUID + "/" + val.String
1177         ctrctx, _, _ := s.super.ClientsWithToken("z3333", runtimeToken)
1178         c.Logf("container runtime token %+v", runtimeToken)
1179
1180         _, err = conn3.UserGet(ctrctx, arvados.GetOptions{UUID: user1.UUID})
1181         c.Assert(err, check.NotNil)
1182         c.Check(err, check.ErrorMatches, `request failed: .* 401 Unauthorized: cannot use a locally issued token to forward a request to our login cluster \(z1111\)`)
1183         c.Check(err, check.Not(check.ErrorMatches), `(?ms).*127\.0\.0\.11.*`)
1184 }
1185
1186 func (s *IntegrationSuite) TestRunTrivialContainer(c *check.C) {
1187         outcoll, _ := s.runContainer(c, "z1111", "", map[string]interface{}{
1188                 "command":             []string{"sh", "-c", "touch \"/out/hello world\" /out/ohai"},
1189                 "container_image":     "busybox:uclibc",
1190                 "cwd":                 "/tmp",
1191                 "environment":         map[string]string{},
1192                 "mounts":              map[string]arvados.Mount{"/out": {Kind: "tmp", Capacity: 10000}},
1193                 "output_path":         "/out",
1194                 "runtime_constraints": arvados.RuntimeConstraints{RAM: 100000000, VCPUs: 1, KeepCacheRAM: 1 << 26},
1195                 "priority":            1,
1196                 "state":               arvados.ContainerRequestStateCommitted,
1197         }, 0)
1198         c.Check(outcoll.ManifestText, check.Matches, `\. d41d8.* 0:0:hello\\040world 0:0:ohai\n`)
1199         c.Check(outcoll.PortableDataHash, check.Equals, "8fa5dee9231a724d7cf377c5a2f4907c+65")
1200 }
1201
1202 func (s *IntegrationSuite) TestContainerInputOnDifferentCluster(c *check.C) {
1203         conn := s.super.Conn("z1111")
1204         rootctx, _, _ := s.super.RootClients("z1111")
1205         userctx, ac, _, _ := s.super.UserClients("z1111", rootctx, c, conn, s.oidcprovider.AuthEmail, true)
1206         z1coll, err := conn.CollectionCreate(userctx, arvados.CreateOptions{Attrs: map[string]interface{}{
1207                 "manifest_text": ". d41d8cd98f00b204e9800998ecf8427e+0 0:0:ocelot\n",
1208         }})
1209         c.Assert(err, check.IsNil)
1210
1211         outcoll, logcfs := s.runContainer(c, "z2222", ac.AuthToken, map[string]interface{}{
1212                 "command":         []string{"ls", "/in"},
1213                 "container_image": "busybox:uclibc",
1214                 "cwd":             "/tmp",
1215                 "environment":     map[string]string{},
1216                 "mounts": map[string]arvados.Mount{
1217                         "/in":  {Kind: "collection", PortableDataHash: z1coll.PortableDataHash},
1218                         "/out": {Kind: "tmp", Capacity: 10000},
1219                 },
1220                 "output_path":         "/out",
1221                 "runtime_constraints": arvados.RuntimeConstraints{RAM: 100000000, VCPUs: 1, KeepCacheRAM: 1 << 26},
1222                 "priority":            1,
1223                 "state":               arvados.ContainerRequestStateCommitted,
1224                 "container_count_max": 1,
1225         }, -1)
1226         if outcoll.UUID == "" {
1227                 arvmountlog, err := fs.ReadFile(arvados.FS(logcfs), "/arv-mount.txt")
1228                 c.Check(err, check.IsNil)
1229                 c.Check(string(arvmountlog), check.Matches, `(?ms).*cannot use a locally issued token to forward a request to our login cluster \(z1111\).*`)
1230                 c.Skip("this use case is not supported yet")
1231         }
1232         stdout, err := fs.ReadFile(arvados.FS(logcfs), "/stdout.txt")
1233         c.Check(err, check.IsNil)
1234         c.Check(string(stdout), check.Equals, "ocelot\n")
1235 }
1236
1237 func (s *IntegrationSuite) runContainer(c *check.C, clusterID string, token string, ctrSpec map[string]interface{}, expectExitCode int) (outcoll arvados.Collection, logcfs arvados.CollectionFileSystem) {
1238         conn := s.super.Conn(clusterID)
1239         rootctx, _, _ := s.super.RootClients(clusterID)
1240         if token == "" {
1241                 _, ac, _, _ := s.super.UserClients(clusterID, rootctx, c, conn, s.oidcprovider.AuthEmail, true)
1242                 token = ac.AuthToken
1243         }
1244         _, ac, kc := s.super.ClientsWithToken(clusterID, token)
1245
1246         c.Log("[docker load]")
1247         out, err := exec.Command("docker", "load", "--input", arvadostest.BusyboxDockerImage(c)).CombinedOutput()
1248         c.Logf("[docker load output] %s", out)
1249         c.Check(err, check.IsNil)
1250
1251         c.Log("[arv-keepdocker]")
1252         akd := exec.Command("arv-keepdocker", "--no-resume", "busybox:uclibc")
1253         akd.Env = append(os.Environ(), "ARVADOS_API_HOST="+ac.APIHost, "ARVADOS_API_HOST_INSECURE=1", "ARVADOS_API_TOKEN="+ac.AuthToken)
1254         out, err = akd.CombinedOutput()
1255         c.Logf("[arv-keepdocker output]\n%s", out)
1256         c.Check(err, check.IsNil)
1257
1258         var cr arvados.ContainerRequest
1259         err = ac.RequestAndDecode(&cr, "POST", "/arvados/v1/container_requests", nil, map[string]interface{}{
1260                 "container_request": ctrSpec,
1261         })
1262         c.Assert(err, check.IsNil)
1263
1264         showlogs := func(collectionID string) arvados.CollectionFileSystem {
1265                 var logcoll arvados.Collection
1266                 err = ac.RequestAndDecode(&logcoll, "GET", "/arvados/v1/collections/"+collectionID, nil, nil)
1267                 c.Assert(err, check.IsNil)
1268                 cfs, err := logcoll.FileSystem(ac, kc)
1269                 c.Assert(err, check.IsNil)
1270                 fs.WalkDir(arvados.FS(cfs), "/", func(path string, d fs.DirEntry, err error) error {
1271                         if d.IsDir() || strings.HasPrefix(path, "/log for container") {
1272                                 return nil
1273                         }
1274                         f, err := cfs.Open(path)
1275                         c.Assert(err, check.IsNil)
1276                         defer f.Close()
1277                         buf, err := ioutil.ReadAll(f)
1278                         c.Assert(err, check.IsNil)
1279                         c.Logf("=== %s\n%s\n", path, buf)
1280                         return nil
1281                 })
1282                 return cfs
1283         }
1284
1285         checkwebdavlogs := func(cr arvados.ContainerRequest) {
1286                 req, err := http.NewRequest("OPTIONS", "https://"+ac.APIHost+"/arvados/v1/container_requests/"+cr.UUID+"/log/"+cr.ContainerUUID+"/", nil)
1287                 c.Assert(err, check.IsNil)
1288                 req.Header.Set("Origin", "http://example.example")
1289                 resp, err := ac.Do(req)
1290                 c.Assert(err, check.IsNil)
1291                 c.Check(resp.StatusCode, check.Equals, http.StatusOK)
1292                 // Check for duplicate headers -- must use Header[], not Header.Get()
1293                 c.Check(resp.Header["Access-Control-Allow-Origin"], check.DeepEquals, []string{"*"})
1294         }
1295
1296         var ctr arvados.Container
1297         var lastState arvados.ContainerState
1298         var status, lastStatus arvados.ContainerStatus
1299         var allStatus string
1300         checkstatus := func() {
1301                 err := ac.RequestAndDecode(&status, "GET", "/arvados/v1/container_requests/"+cr.UUID+"/container_status", nil, nil)
1302                 c.Assert(err, check.IsNil)
1303                 if status != lastStatus {
1304                         c.Logf("container status: %s, %s", status.State, status.SchedulingStatus)
1305                         allStatus += fmt.Sprintf("%s, %s\n", status.State, status.SchedulingStatus)
1306                         lastStatus = status
1307                 }
1308         }
1309         deadline := time.Now().Add(time.Minute)
1310         for cr.State != arvados.ContainerRequestStateFinal || (lastStatus.State != arvados.ContainerStateComplete && lastStatus.State != arvados.ContainerStateCancelled) {
1311                 err = ac.RequestAndDecode(&cr, "GET", "/arvados/v1/container_requests/"+cr.UUID, nil, nil)
1312                 c.Assert(err, check.IsNil)
1313                 checkstatus()
1314                 err = ac.RequestAndDecode(&ctr, "GET", "/arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
1315                 if err != nil {
1316                         c.Logf("error getting container state: %s", err)
1317                 } else if ctr.State != lastState {
1318                         c.Logf("container state changed to %q", ctr.State)
1319                         lastState = ctr.State
1320                 } else {
1321                         if time.Now().After(deadline) {
1322                                 c.Errorf("timed out, container state is %q", cr.State)
1323                                 if ctr.Log == "" {
1324                                         c.Logf("=== NO LOG COLLECTION saved for container")
1325                                 } else {
1326                                         showlogs(ctr.Log)
1327                                 }
1328                                 c.FailNow()
1329                         }
1330                         time.Sleep(time.Second / 2)
1331                 }
1332         }
1333         checkstatus()
1334         c.Logf("cr.CumulativeCost == %f", cr.CumulativeCost)
1335         c.Check(cr.CumulativeCost, check.Not(check.Equals), 0.0)
1336         if expectExitCode >= 0 {
1337                 c.Check(ctr.State, check.Equals, arvados.ContainerStateComplete)
1338                 c.Check(ctr.ExitCode, check.Equals, expectExitCode)
1339                 err = ac.RequestAndDecode(&outcoll, "GET", "/arvados/v1/collections/"+cr.OutputUUID, nil, nil)
1340                 c.Assert(err, check.IsNil)
1341                 c.Check(allStatus, check.Matches, `Queued, waiting for dispatch\n`+
1342                         `(Queued, waiting.*\n)*`+
1343                         `(Locked, waiting for dispatch\n)?`+
1344                         `(Locked, waiting for new instance to be ready\n)?`+
1345                         `(Locked, preparing runtime environment\n)?`+
1346                         `(Running, \n)?`+
1347                         `Complete, \n`)
1348         }
1349         logcfs = showlogs(cr.LogUUID)
1350         checkwebdavlogs(cr)
1351         return outcoll, logcfs
1352 }