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