Przeglądaj źródła

fix(sshpool): single-flight per host + closed check in dial (#71)

Two concurrent dialers for the same host could leak an SSH connection:
both saw entry.client == nil after releasing the mutex for ssh.Dial,
and the second overwrote the first. Added a dialing channel per host
for single-flight and a p.closed guard in the mutex section.

Closes #68

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 miesięcy temu
rodzic
commit
0d055d2d2b

+ 32 - 2
server-go/internal/adapters/sshpool.go

@@ -39,10 +39,13 @@ type SSHPool struct {
 	mu     sync.Mutex
 	conns  map[string]*sshConn
 	closed bool
+
+	dialTCP func(network, addr string, config *ssh.ClientConfig) (*ssh.Client, error)
 }
 
 type sshConn struct {
 	client   *ssh.Client
+	dialing  chan struct{}
 	failures int
 	notUntil time.Time
 }
@@ -62,6 +65,7 @@ func NewSSHPool(keyPath string) (*SSHPool, error) {
 		signer:  signer,
 		khPath:  sshkey.KnownHostsPath(keyPath),
 		conns:   map[string]*sshConn{},
+		dialTCP: ssh.Dial,
 	}, nil
 }
 
@@ -98,8 +102,13 @@ func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
 }
 
 // dial abre (o reabre) la conexión a un host respetando el backoff.
+// Single-flight por host: dos llamantes concurrentes comparten el mismo dial.
 func (p *SSHPool) dial(host string) (*ssh.Client, error) {
 	p.mu.Lock()
+	if p.closed {
+		p.mu.Unlock()
+		return nil, errors.New("ssh pool closed")
+	}
 	entry := p.conns[host]
 	if entry == nil {
 		entry = &sshConn{}
@@ -110,14 +119,32 @@ func (p *SSHPool) dial(host string) (*ssh.Client, error) {
 		p.mu.Unlock()
 		return c, nil
 	}
+	if entry.dialing != nil {
+		ch := entry.dialing
+		p.mu.Unlock()
+		<-ch
+		p.mu.Lock()
+		if entry.client != nil {
+			c := entry.client
+			p.mu.Unlock()
+			return c, nil
+		}
+		p.mu.Unlock()
+		return nil, errors.New("ssh dial failed")
+	}
 	if time.Now().Before(entry.notUntil) {
 		p.mu.Unlock()
 		return nil, fmt.Errorf("ssh %s: en backoff tras %d fallos", host, entry.failures)
 	}
+	entry.dialing = make(chan struct{})
 	p.mu.Unlock()
 
 	cb, err := p.hostKeyCallback()
 	if err != nil {
+		p.mu.Lock()
+		close(entry.dialing)
+		entry.dialing = nil
+		p.mu.Unlock()
 		return nil, err
 	}
 	cfg := &ssh.ClientConfig{
@@ -126,10 +153,11 @@ func (p *SSHPool) dial(host string) (*ssh.Client, error) {
 		HostKeyCallback: cb,
 		Timeout:         sshDialTimeout,
 	}
-	client, err := ssh.Dial("tcp", net.JoinHostPort(host, "22"), cfg)
+	client, err := p.dialTCP("tcp", net.JoinHostPort(host, "22"), cfg)
 
 	p.mu.Lock()
-	defer p.mu.Unlock()
+	close(entry.dialing)
+	entry.dialing = nil
 	if err != nil {
 		entry.failures++
 		backoff := sshBackoffBase << min(entry.failures-1, 4)
@@ -137,11 +165,13 @@ func (p *SSHPool) dial(host string) (*ssh.Client, error) {
 			backoff = sshBackoffMax
 		}
 		entry.notUntil = time.Now().Add(backoff)
+		p.mu.Unlock()
 		return nil, fmt.Errorf("ssh %s: %w", host, err)
 	}
 	entry.client = client
 	entry.failures = 0
 	entry.notUntil = time.Time{}
+	p.mu.Unlock()
 	return client, nil
 }
 

+ 127 - 0
server-go/internal/adapters/sshpool_test.go

@@ -0,0 +1,127 @@
+package adapters
+
+import (
+	"errors"
+	"net"
+	"os"
+	"sync"
+	"sync/atomic"
+	"testing"
+	"time"
+
+	"golang.org/x/crypto/ssh"
+)
+
+func newTestPool(t *testing.T) *SSHPool {
+	t.Helper()
+	kh, err := os.CreateTemp(t.TempDir(), "known_hosts")
+	if err != nil {
+		t.Fatal(err)
+	}
+	kh.Close()
+	return &SSHPool{
+		khPath:  kh.Name(),
+		conns:   map[string]*sshConn{},
+		dialTCP: ssh.Dial,
+	}
+}
+
+func TestSSHPoolClosedRejectsDial(t *testing.T) {
+	pool := newTestPool(t)
+	pool.Close()
+	_, err := pool.dial("1.2.3.4")
+	if err == nil || err.Error() != "ssh pool closed" {
+		t.Fatalf("esperaba 'ssh pool closed', obtuve: %v", err)
+	}
+}
+
+func TestSSHPoolSingleFlight_LeaderSuccess(t *testing.T) {
+	pool := newTestPool(t)
+	var dials atomic.Int32
+	ready := make(chan struct{})
+
+	pool.dialTCP = func(network, addr string, cfg *ssh.ClientConfig) (*ssh.Client, error) {
+		dials.Add(1)
+		<-ready
+		return &ssh.Client{}, nil
+	}
+
+	const N = 2
+	results := make([]*ssh.Client, N)
+	errs := make([]error, N)
+	var wg sync.WaitGroup
+
+	for i := 0; i < N; i++ {
+		wg.Add(1)
+		go func(i int) {
+			defer wg.Done()
+			time.Sleep(30 * time.Millisecond)
+			results[i], errs[i] = pool.dial("10.0.0.1")
+		}(i)
+	}
+
+	time.Sleep(100 * time.Millisecond)
+	close(ready)
+	wg.Wait()
+
+	if n := dials.Load(); n != 1 {
+		t.Fatalf("dialTCP llamado %d veces, esperaba 1 (single-flight)", n)
+	}
+	for i := 0; i < N; i++ {
+		if errs[i] != nil {
+			t.Errorf("goroutine %d: %v", i, errs[i])
+		}
+		if results[i] == nil {
+			t.Errorf("goroutine %d: result nil", i)
+		}
+	}
+}
+
+func TestSSHPoolSingleFlight_LeaderFails(t *testing.T) {
+	pool := newTestPool(t)
+	var dials atomic.Int32
+	ready := make(chan struct{})
+
+	pool.dialTCP = func(network, addr string, cfg *ssh.ClientConfig) (*ssh.Client, error) {
+		dials.Add(1)
+		<-ready
+		return nil, &net.OpError{Op: "dial", Err: errors.New("timeout")}
+	}
+
+	const N = 2
+	var wg sync.WaitGroup
+	errCh := make(chan error, N)
+
+	for i := 0; i < N; i++ {
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+			time.Sleep(30 * time.Millisecond)
+			_, err := pool.dial("10.0.0.2")
+			errCh <- err
+		}()
+	}
+
+	time.Sleep(100 * time.Millisecond)
+	close(ready)
+	wg.Wait()
+	close(errCh)
+
+	if n := dials.Load(); n != 1 {
+		t.Fatalf("dialTCP llamado %d veces, esperaba 1", n)
+	}
+
+	failures := 0
+	for err := range errCh {
+		if err == nil {
+			t.Error("esperaba error del follower")
+			continue
+		}
+		if err.Error() == "ssh dial failed" || err.Error()[:3] == "ssh" {
+			failures++
+		}
+	}
+	if failures != N {
+		t.Errorf("%d errores, esperaba %d", failures, N)
+	}
+}