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