Просмотр исходного кода

fix(ssh): keep one pool entry per unit when the port is the default (#1893) (#1971)

Nacho 3 недель назад
Родитель
Сommit
ba2a38c8c2

+ 15 - 0
server-go/internal/adapters/sshpool.go

@@ -43,6 +43,18 @@ func addrOf(host string) string {
 	return net.JoinHostPort(host, "22")
 }
 
+// poolKey es la clave del pool para un host. El mismo router llega unas veces
+// como "test-gw.lan" y otras como "test-gw.lan:22" (RouterConfig.SSHAddr), y
+// con el string tal cual el pool abría DOS conexiones al mismo equipo, una por
+// clave y cada una con su handshake (#1893). El puerto por defecto no
+// distingue hosts, así que no forma parte de la clave; uno no estándar sí.
+func poolKey(host string) string {
+	if h, port, err := net.SplitHostPort(host); err == nil && port == "22" {
+		return h
+	}
+	return host
+}
+
 // SSHPool gestiona conexiones persistentes a los routers.
 type SSHPool struct {
 	keyPath string
@@ -111,6 +123,7 @@ func NewSSHPool(keyPath string) (*SSHPool, error) {
 // backoff del host: la siguiente llamada reconecta con el valor nuevo, sin
 // esperar el enfriamiento de un fallo ya resuelto.
 func (p *SSHPool) SetPassword(host, user, password string) {
+	host = poolKey(host)
 	p.mu.Lock()
 	defer p.mu.Unlock()
 	old, had := p.creds[host]
@@ -261,6 +274,7 @@ func (p *SSHPool) RemoveHostKey(hostnames ...string) 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) {
+	host = poolKey(host)
 	p.mu.Lock()
 	if p.closed {
 		p.mu.Unlock()
@@ -368,6 +382,7 @@ func (p *SSHPool) dial(host string) (*ssh.Client, error) {
 
 // drop invalida la conexión de un host (la próxima llamada rediala).
 func (p *SSHPool) drop(host string) {
+	host = poolKey(host)
 	p.mu.Lock()
 	defer p.mu.Unlock()
 	if e := p.conns[host]; e != nil && e.client != nil {

+ 72 - 0
server-go/internal/adapters/sshpool_key_1893_test.go

@@ -0,0 +1,72 @@
+package adapters
+
+import (
+	"errors"
+	"os"
+	"path/filepath"
+	"testing"
+
+	"golang.org/x/crypto/ssh"
+)
+
+// #1893: el mismo router llega como "test-gw.lan" (host de la config) y como
+// "test-gw.lan:22" (SSHAddr). El puerto por defecto no distingue hosts.
+func TestPoolKeyCollapsesTheDefaultPort(t *testing.T) {
+	cases := []struct{ in, want string }{
+		{"test-gw.lan", "test-gw.lan"},
+		{"test-gw.lan:22", "test-gw.lan"},
+		{"192.168.1.172:22", "192.168.1.172"},
+		{"test-gw.lan:2222", "test-gw.lan:2222"},
+		{"[2001:db8::1]:22", "2001:db8::1"},
+		{"[2001:db8::1]:2222", "[2001:db8::1]:2222"},
+	}
+	for _, c := range cases {
+		if got := poolKey(c.in); got != c.want {
+			t.Errorf("poolKey(%q) = %q, want %q", c.in, got, c.want)
+		}
+	}
+}
+
+// Una credencial por unidad, aunque llegue con las dos formas.
+func TestSetPasswordUsesOneEntryPerHost(t *testing.T) {
+	p := &SSHPool{conns: map[string]*sshConn{}, creds: map[string]sshCred{}}
+	p.SetPassword("test-gw.lan:22", "root", "s3cret")
+	p.SetPassword("test-gw.lan", "root", "s3cret")
+	if len(p.creds) != 1 {
+		t.Fatalf("creds = %d entradas, esperaba 1 (%v)", len(p.creds), p.creds)
+	}
+	if _, ok := p.creds["test-gw.lan"]; !ok {
+		t.Fatalf("la credencial no quedo bajo la clave normalizada: %v", p.creds)
+	}
+}
+
+// Y una sola conexión: el segundo dial reutiliza la entrada (o su backoff) en
+// vez de abrir un handshake nuevo al mismo equipo.
+func TestDialCollapsesHostAndDefaultPort(t *testing.T) {
+	kh := filepath.Join(t.TempDir(), "known_hosts")
+	if err := os.WriteFile(kh, nil, 0o600); err != nil {
+		t.Fatalf("known_hosts: %v", err)
+	}
+	dials := 0
+	p := &SSHPool{
+		khPath: kh,
+		conns:  map[string]*sshConn{},
+		creds:  map[string]sshCred{},
+		dialTCP: func(_, _ string, _ *ssh.ClientConfig) (*ssh.Client, error) {
+			dials++
+			return nil, errors.New("unreachable")
+		},
+	}
+	if _, err := p.dial("test-gw.lan:22"); err == nil {
+		t.Fatal("el primer dial debia fallar")
+	}
+	if _, err := p.dial("test-gw.lan"); err == nil {
+		t.Fatal("el segundo dial debia caer en el backoff")
+	}
+	if dials != 1 {
+		t.Fatalf("diales = %d, esperaba 1: host y host:22 son el mismo equipo", dials)
+	}
+	if len(p.conns) != 1 {
+		t.Fatalf("conns = %d entradas, esperaba 1", len(p.conns))
+	}
+}