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