Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/pr-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -757,7 +757,7 @@ jobs:
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ runner.temp }}/podman-linux-amd64.tar.gz
key: ${{ runner.os }}-${{ runner.arch }}-podman-static-v5.8.2
key: ${{ runner.os }}-${{ runner.arch }}-podman-static-v5.8.4

- name: install podman (Linux)
if: (matrix.install-podman == 'rootless' || matrix.install-podman == 'rootful') && runner.os == 'Linux'
Expand All @@ -766,10 +766,10 @@ jobs:
archive="${{ runner.temp }}/podman-linux-amd64.tar.gz"
if [ "${{ steps.podman-cache-linux.outputs.cache-hit }}" != "true" ]; then
curl -fsSL -o "$archive" \
https://github.com/mgoltzsche/podman-static/releases/download/v5.8.2/podman-linux-amd64.tar.gz
https://github.com/mgoltzsche/podman-static/releases/download/v5.8.4/podman-linux-amd64.tar.gz
fi

expectedHash="228b9adf1ba3585d1d72f0a4bb9a669de5ea806d13884b2c43b5e65601a1a580"
expectedHash="a58765fe8be6ab3fb79f892f1a027b4ce4a7e8eb589df1ef960c167cbde08d69"
actualHash=$(sha256sum "$archive" | cut -d' ' -f1)
if [ "$actualHash" != "$expectedHash" ]; then
echo "::error::SHA256 mismatch for podman-static archive! Expected: $expectedHash, Got: $actualHash"
Expand Down
22 changes: 19 additions & 3 deletions cmd/workspace/ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package workspace

import (
"context"
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -354,7 +355,7 @@ func (cmd *SSHCmd) startProxyTunnel(
client client2.ProxyClient,
) error {
log.Debugf("start proxy tunnel")
return tunnel.NewTunnel(
return tunnel.NewTunnelWithMetadata(
ctx,
func(ctx context.Context, stdin io.Reader, stdout io.Writer) error {
return client.Ssh(ctx, client2.SshOptions{
Expand All @@ -366,6 +367,11 @@ func (cmd *SSHCmd) startProxyTunnel(
func(ctx context.Context, containerClient *ssh.Client) error {
return cmd.startTunnel(ctx, devsyConfig, containerClient, client)
},
tunnel.TransportLogMetadata{
Provider: client.Provider(),
Mode: "proxy",
Workspace: client.Workspace(),
},
)
}

Expand Down Expand Up @@ -689,10 +695,20 @@ func startSSHKeepAlive(
case <-ctx.Done():
return
case <-ticker.C:
_, _, err := client.SendRequest("keepalive@openssh.com", true, nil)
if err != nil {
ok, _, err := client.SendRequest("keepalive@openssh.com", true, nil)
if err := checkKeepAliveResponse(ok, err); err != nil {
log.Errorf("failed to send keepalive: %v", err)
}
}
}
}

func checkKeepAliveResponse(ok bool, err error) error {
if err != nil {
return err
}
if !ok {
return errors.New("keepalive request rejected")
}
return nil
}
37 changes: 37 additions & 0 deletions cmd/workspace/ssh_keepalive_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package workspace

import (
"errors"
"testing"
)

func TestCheckKeepAliveResponse(t *testing.T) {
t.Parallel()

transportErr := errors.New("connection closed")
tests := []struct {
name string
ok bool
err error
want error
}{
{name: "positive reply", ok: true},
{name: "negative reply", ok: false, want: errors.New("keepalive request rejected")},
{name: "transport error", ok: true, err: transportErr, want: transportErr},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := checkKeepAliveResponse(tt.ok, tt.err)
if tt.want == nil {
if got != nil {
t.Fatalf("checkKeepAliveResponse() = %v, want nil", got)
}
return
}
if got == nil || got.Error() != tt.want.Error() {
t.Fatalf("checkKeepAliveResponse() = %v, want %v", got, tt.want)
}
})
}
}
249 changes: 249 additions & 0 deletions pkg/ssh/direct_tcpip_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,249 @@
package ssh

import (
"crypto/ed25519"
"fmt"
"io"
"net"
"strconv"
"sync"
"testing"
"time"

"golang.org/x/crypto/ssh"
)

type directTCPIPChannelData struct {
DestAddr string
DestPort uint32
OriginAddr string
OriginPort uint32
}

func startDirectTCPIPSSHServer(t *testing.T) (*ssh.Client, string) {
t.Helper()

signer := newTestSSHSigner(t)
backend, backendAddr := startEchoBackend(t)
serverListener := startDirectTCPIPServer(t)
serverConnDone := serveDirectTCPIPConnection(serverListener, signer)

client, err := ssh.Dial("tcp", serverListener.Addr().String(), &ssh.ClientConfig{
User: "test",
HostKeyCallback: ssh.FixedHostKey(signer.PublicKey()),
Timeout: 2 * time.Second,
})
if err != nil {
_ = serverListener.Close()
_ = backend.Close()
t.Fatalf("dial SSH server: %v", err)
}

t.Cleanup(func() {
_ = client.Close()
_ = serverListener.Close()
_ = backend.Close()
<-serverConnDone
})
return client, backendAddr
}

func newTestSSHSigner(t *testing.T) ssh.Signer {
t.Helper()

_, privateKey, err := ed25519.GenerateKey(nil)
if err != nil {
t.Fatalf("generate host key: %v", err)
}
signer, err := ssh.NewSignerFromKey(privateKey)
if err != nil {
t.Fatalf("create host signer: %v", err)
}
return signer
}

func startEchoBackend(t *testing.T) (net.Listener, string) {
t.Helper()

backend, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen for backend: %v", err)
}
go serveEchoBackend(backend)
return backend, backend.Addr().String()
}

func serveEchoBackend(listener net.Listener) {
for {
conn, err := listener.Accept()
if err != nil {
return
}
go func() {
defer func() { _ = conn.Close() }()
_, _ = io.Copy(conn, conn)
}()
}
}

func startDirectTCPIPServer(t *testing.T) net.Listener {
t.Helper()

serverListener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen for SSH server: %v", err)
}
return serverListener
}

func serveDirectTCPIPConnection(listener net.Listener, signer ssh.Signer) <-chan struct{} {
serverConfig := &ssh.ServerConfig{NoClientAuth: true}
serverConfig.AddHostKey(signer)
serverConnDone := make(chan struct{})
go func() {
defer close(serverConnDone)
conn, acceptErr := listener.Accept()
if acceptErr != nil {
return
}
serverConn, channels, requests, handshakeErr := ssh.NewServerConn(conn, serverConfig)
if handshakeErr != nil {
return
}
go ssh.DiscardRequests(requests)
for newChannel := range channels {
handleDirectTCPIPChannel(newChannel)
}
_ = serverConn.Close()
}()
return serverConnDone
}

func handleDirectTCPIPChannel(newChannel ssh.NewChannel) {
if newChannel.ChannelType() != "direct-tcpip" {
_ = newChannel.Reject(ssh.UnknownChannelType, "only direct-tcpip is supported")
return
}
var data directTCPIPChannelData
if err := ssh.Unmarshal(newChannel.ExtraData(), &data); err != nil {
_ = newChannel.Reject(ssh.ConnectionFailed, err.Error())
return
}
channel, channelRequests, err := newChannel.Accept()
if err != nil {
return
}
go ssh.DiscardRequests(channelRequests)
backendAddr := net.JoinHostPort(data.DestAddr, strconv.FormatUint(uint64(data.DestPort), 10))
backendConn, err := net.Dial("tcp", backendAddr)
if err != nil {
_ = channel.Close()
return
}
go bridgeDirectTCPIPChannel(channel, backendConn)
}

func bridgeDirectTCPIPChannel(channel ssh.Channel, backendConn net.Conn) {
defer func() { _ = channel.Close() }()
defer func() { _ = backendConn.Close() }()
go func() { _, _ = io.Copy(backendConn, channel) }()
_, _ = io.Copy(channel, backendConn)
}

func openDirectTCPIP(t *testing.T, client *ssh.Client, backendAddr string) ssh.Channel {
t.Helper()
host, portString, err := net.SplitHostPort(backendAddr)
if err != nil {
t.Fatal(err)
}
port, err := strconv.ParseUint(portString, 10, 32)
if err != nil {
t.Fatal(err)
}
channel, _, err := client.OpenChannel("direct-tcpip", ssh.Marshal(&directTCPIPChannelData{
DestAddr: host,
DestPort: uint32(port),
OriginAddr: "127.0.0.1",
OriginPort: 0,
}))
if err != nil {
t.Fatalf("open direct-tcpip channel: %v", err)
}
return channel
}

func TestDirectTCPIPRepeatedChannelsKeepParentAlive(t *testing.T) {
client, backendAddr := startDirectTCPIPSSHServer(t)

for range 10 {
channel := openDirectTCPIP(t, client, backendAddr)
message := []byte("ping")
if _, err := channel.Write(message); err != nil {
t.Fatalf("write: %v", err)
}
response := make([]byte, len(message))
if _, err := io.ReadFull(channel, response); err != nil {
t.Fatalf("read: %v", err)
}
if string(response) != string(message) {
t.Fatalf("response = %q, want %q", response, message)
}
_ = channel.Close()
}
}

func TestDirectTCPIPConcurrentChannelsAreIndependent(t *testing.T) {
client, backendAddr := startDirectTCPIPSSHServer(t)
channels := make([]ssh.Channel, 5)
for i := range channels {
channels[i] = openDirectTCPIP(t, client, backendAddr)
}

var wg sync.WaitGroup
for i, channel := range channels {
wg.Go(func() {
message := fmt.Appendf(nil, "channel-%d", i)
if err := exchangeDirectTCPIP(channel, message); err != nil {
t.Errorf("channel %d exchange: %v", i, err)
}
})
}
wg.Wait()

// Closing channels in non-FIFO order exercises parent/channel ownership.
for _, index := range []int{4, 1, 3, 0, 2} {
_ = channels[index].Close()
}

channel := openDirectTCPIP(t, client, backendAddr)
defer func() { _ = channel.Close() }()
message := []byte("still-alive")
if err := exchangeDirectTCPIP(channel, message); err != nil {
t.Fatalf("parent transport unusable after channel churn: %v", err)
}
}

func TestDirectTCPIPIdleParentAcceptsNewChannel(t *testing.T) {
client, backendAddr := startDirectTCPIPSSHServer(t)
time.Sleep(25 * time.Millisecond)
channel := openDirectTCPIP(t, client, backendAddr)
defer func() { _ = channel.Close() }()
message := []byte("after-idle")
if err := exchangeDirectTCPIP(channel, message); err != nil {
t.Fatalf("exchange after idle: %v", err)
}
}

func exchangeDirectTCPIP(channel ssh.Channel, message []byte) error {
if _, err := channel.Write(message); err != nil {
return fmt.Errorf("write: %w", err)
}
response := make([]byte, len(message))
if _, err := io.ReadFull(channel, response); err != nil {
return fmt.Errorf("read: %w", err)
}
if string(response) != string(message) {
return fmt.Errorf("response = %q, want %q", response, message)
}
return nil
}
10 changes: 9 additions & 1 deletion pkg/tunnel/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ func (c *ContainerTunnel) Run(
}
defer pb.Close()

return pb.RunPair(ctx,
info, err := runPersistentPair(
ctx,
pb,
func(ctx context.Context, stdin, stdout *os.File) error {
return c.runHostTunnel(ctx, stdin, stdout, timeout)
},
Expand All @@ -82,6 +84,12 @@ func (c *ContainerTunnel) Run(
return nil
},
)
LogTransportClose(info, TransportLogMetadata{
Provider: c.client.Provider(),
Mode: workspaceSubcommand,
Workspace: c.client.Workspace(),
})
return err
}

// runHostTunnel injects the devsy agent onto the host and starts the SSH server,
Expand Down
Loading
Loading