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