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