Use "systemctl disable" instead of "service docker stop" refs #19439
[arvados.git] / lib / controller / localdb / container_gateway_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package localdb
6
7 import (
8         "context"
9         "crypto/hmac"
10         "crypto/sha256"
11         "fmt"
12         "io"
13         "io/ioutil"
14         "net"
15         "time"
16
17         "git.arvados.org/arvados.git/lib/config"
18         "git.arvados.org/arvados.git/lib/crunchrun"
19         "git.arvados.org/arvados.git/sdk/go/arvados"
20         "git.arvados.org/arvados.git/sdk/go/arvadostest"
21         "git.arvados.org/arvados.git/sdk/go/auth"
22         "git.arvados.org/arvados.git/sdk/go/ctxlog"
23         "golang.org/x/crypto/ssh"
24         check "gopkg.in/check.v1"
25 )
26
27 var _ = check.Suite(&ContainerGatewaySuite{})
28
29 type ContainerGatewaySuite struct {
30         cluster *arvados.Cluster
31         localdb *Conn
32         ctx     context.Context
33         ctrUUID string
34         gw      *crunchrun.Gateway
35 }
36
37 func (s *ContainerGatewaySuite) TearDownSuite(c *check.C) {
38         // Undo any changes/additions to the user database so they
39         // don't affect subsequent tests.
40         arvadostest.ResetEnv()
41         c.Check(arvados.NewClientFromEnv().RequestAndDecode(nil, "POST", "database/reset", nil, nil), check.IsNil)
42 }
43
44 func (s *ContainerGatewaySuite) SetUpSuite(c *check.C) {
45         cfg, err := config.NewLoader(nil, ctxlog.TestLogger(c)).Load()
46         c.Assert(err, check.IsNil)
47         s.cluster, err = cfg.GetCluster("")
48         c.Assert(err, check.IsNil)
49         s.localdb = NewConn(s.cluster)
50         s.ctx = auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{arvadostest.ActiveTokenV2}})
51
52         s.ctrUUID = arvadostest.QueuedContainerUUID
53
54         h := hmac.New(sha256.New, []byte(s.cluster.SystemRootToken))
55         fmt.Fprint(h, s.ctrUUID)
56         authKey := fmt.Sprintf("%x", h.Sum(nil))
57
58         s.gw = &crunchrun.Gateway{
59                 ContainerUUID: s.ctrUUID,
60                 AuthSecret:    authKey,
61                 Address:       "localhost:0",
62                 Log:           ctxlog.TestLogger(c),
63                 Target:        crunchrun.GatewayTargetStub{},
64         }
65         c.Assert(s.gw.Start(), check.IsNil)
66         rootctx := auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{s.cluster.SystemRootToken}})
67         _, err = s.localdb.ContainerUpdate(rootctx, arvados.UpdateOptions{
68                 UUID: s.ctrUUID,
69                 Attrs: map[string]interface{}{
70                         "state": arvados.ContainerStateLocked}})
71         c.Assert(err, check.IsNil)
72         _, err = s.localdb.ContainerUpdate(rootctx, arvados.UpdateOptions{
73                 UUID: s.ctrUUID,
74                 Attrs: map[string]interface{}{
75                         "state":           arvados.ContainerStateRunning,
76                         "gateway_address": s.gw.Address}})
77         c.Assert(err, check.IsNil)
78 }
79
80 func (s *ContainerGatewaySuite) SetUpTest(c *check.C) {
81         s.cluster.Containers.ShellAccess.Admin = true
82         s.cluster.Containers.ShellAccess.User = true
83         _, err := arvadostest.DB(c, s.cluster).Exec(`update containers set interactive_session_started=$1 where uuid=$2`, false, s.ctrUUID)
84         c.Check(err, check.IsNil)
85 }
86
87 func (s *ContainerGatewaySuite) TestConfig(c *check.C) {
88         for _, trial := range []struct {
89                 configAdmin bool
90                 configUser  bool
91                 sendToken   string
92                 errorCode   int
93         }{
94                 {true, true, arvadostest.ActiveTokenV2, 0},
95                 {true, false, arvadostest.ActiveTokenV2, 503},
96                 {false, true, arvadostest.ActiveTokenV2, 0},
97                 {false, false, arvadostest.ActiveTokenV2, 503},
98                 {true, true, arvadostest.AdminToken, 0},
99                 {true, false, arvadostest.AdminToken, 0},
100                 {false, true, arvadostest.AdminToken, 403},
101                 {false, false, arvadostest.AdminToken, 503},
102         } {
103                 c.Logf("trial %#v", trial)
104                 s.cluster.Containers.ShellAccess.Admin = trial.configAdmin
105                 s.cluster.Containers.ShellAccess.User = trial.configUser
106                 ctx := auth.NewContext(s.ctx, &auth.Credentials{Tokens: []string{trial.sendToken}})
107                 sshconn, err := s.localdb.ContainerSSH(ctx, arvados.ContainerSSHOptions{UUID: s.ctrUUID})
108                 if trial.errorCode == 0 {
109                         if !c.Check(err, check.IsNil) {
110                                 continue
111                         }
112                         if !c.Check(sshconn.Conn, check.NotNil) {
113                                 continue
114                         }
115                         sshconn.Conn.Close()
116                 } else {
117                         c.Check(err, check.NotNil)
118                         err, ok := err.(interface{ HTTPStatus() int })
119                         if c.Check(ok, check.Equals, true) {
120                                 c.Check(err.HTTPStatus(), check.Equals, trial.errorCode)
121                         }
122                 }
123         }
124 }
125
126 func (s *ContainerGatewaySuite) TestDirectTCP(c *check.C) {
127         // Set up servers on a few TCP ports
128         var addrs []string
129         for i := 0; i < 3; i++ {
130                 ln, err := net.Listen("tcp", ":0")
131                 c.Assert(err, check.IsNil)
132                 defer ln.Close()
133                 addrs = append(addrs, ln.Addr().String())
134                 go func() {
135                         for {
136                                 conn, err := ln.Accept()
137                                 if err != nil {
138                                         return
139                                 }
140                                 var gotAddr string
141                                 fmt.Fscanf(conn, "%s\n", &gotAddr)
142                                 c.Logf("stub server listening at %s received string %q from remote %s", ln.Addr().String(), gotAddr, conn.RemoteAddr())
143                                 if gotAddr == ln.Addr().String() {
144                                         fmt.Fprintf(conn, "%s\n", ln.Addr().String())
145                                 }
146                                 conn.Close()
147                         }
148                 }()
149         }
150
151         c.Logf("connecting to %s", s.gw.Address)
152         sshconn, err := s.localdb.ContainerSSH(s.ctx, arvados.ContainerSSHOptions{UUID: s.ctrUUID})
153         c.Assert(err, check.IsNil)
154         c.Assert(sshconn.Conn, check.NotNil)
155         defer sshconn.Conn.Close()
156         conn, chans, reqs, err := ssh.NewClientConn(sshconn.Conn, "zzzz-dz642-abcdeabcdeabcde", &ssh.ClientConfig{
157                 HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil },
158         })
159         c.Assert(err, check.IsNil)
160         client := ssh.NewClient(conn, chans, reqs)
161         for _, expectAddr := range addrs {
162                 _, port, err := net.SplitHostPort(expectAddr)
163                 c.Assert(err, check.IsNil)
164
165                 c.Logf("trying foo:%s", port)
166                 {
167                         conn, err := client.Dial("tcp", "foo:"+port)
168                         c.Assert(err, check.IsNil)
169                         conn.SetDeadline(time.Now().Add(time.Second))
170                         buf, err := ioutil.ReadAll(conn)
171                         c.Check(err, check.IsNil)
172                         c.Check(string(buf), check.Equals, "")
173                 }
174
175                 c.Logf("trying localhost:%s", port)
176                 {
177                         conn, err := client.Dial("tcp", "localhost:"+port)
178                         c.Assert(err, check.IsNil)
179                         conn.SetDeadline(time.Now().Add(time.Second))
180                         conn.Write([]byte(expectAddr + "\n"))
181                         var gotAddr string
182                         fmt.Fscanf(conn, "%s\n", &gotAddr)
183                         c.Check(gotAddr, check.Equals, expectAddr)
184                 }
185         }
186 }
187
188 func (s *ContainerGatewaySuite) TestConnect(c *check.C) {
189         c.Logf("connecting to %s", s.gw.Address)
190         sshconn, err := s.localdb.ContainerSSH(s.ctx, arvados.ContainerSSHOptions{UUID: s.ctrUUID})
191         c.Assert(err, check.IsNil)
192         c.Assert(sshconn.Conn, check.NotNil)
193         defer sshconn.Conn.Close()
194
195         done := make(chan struct{})
196         go func() {
197                 defer close(done)
198
199                 // Receive text banner
200                 buf := make([]byte, 12)
201                 _, err := io.ReadFull(sshconn.Conn, buf)
202                 c.Check(err, check.IsNil)
203                 c.Check(string(buf), check.Equals, "SSH-2.0-Go\r\n")
204
205                 // Send text banner
206                 _, err = sshconn.Conn.Write([]byte("SSH-2.0-Fake\r\n"))
207                 c.Check(err, check.IsNil)
208
209                 // Receive binary
210                 _, err = io.ReadFull(sshconn.Conn, buf[:4])
211                 c.Check(err, check.IsNil)
212
213                 // If we can get this far into an SSH handshake...
214                 c.Logf("was able to read %x -- success, tunnel is working", buf[:4])
215         }()
216         select {
217         case <-done:
218         case <-time.After(time.Second):
219                 c.Fail()
220         }
221         ctr, err := s.localdb.ContainerGet(s.ctx, arvados.GetOptions{UUID: s.ctrUUID})
222         c.Check(err, check.IsNil)
223         c.Check(ctr.InteractiveSessionStarted, check.Equals, true)
224 }
225
226 func (s *ContainerGatewaySuite) TestConnectFail(c *check.C) {
227         c.Log("trying with no token")
228         ctx := auth.NewContext(context.Background(), &auth.Credentials{})
229         _, err := s.localdb.ContainerSSH(ctx, arvados.ContainerSSHOptions{UUID: s.ctrUUID})
230         c.Check(err, check.ErrorMatches, `.* 401 .*`)
231
232         c.Log("trying with anonymous token")
233         ctx = auth.NewContext(context.Background(), &auth.Credentials{Tokens: []string{arvadostest.AnonymousToken}})
234         _, err = s.localdb.ContainerSSH(ctx, arvados.ContainerSSHOptions{UUID: s.ctrUUID})
235         c.Check(err, check.ErrorMatches, `.* 404 .*`)
236 }