Explorar el Código

feat(ssh): log every dial, discard and failure with its reason (#1893) (#1907)

* feat(ssh): log every dial, discard and failure with its reason (#1893)

* docs(changelog): cover ssh dial logging (#1893)
Nacho hace 4 semanas
padre
commit
0143a2eb26

+ 4 - 0
CHANGELOG.md

@@ -7,6 +7,10 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 
 ## [Unreleased]
 ## [Unreleased]
 
 
+### Added
+
+- The SSH pool writes what it does to the system log (#1893). A unit showed bursts of "Exit before auth" in dropbear and there was nothing on the server side to correlate them with: no host, no reason, no rhythm. Every new connection is now logged with its host and user, every discarded connection is logged before the redial that follows, and every dial failure is logged with the real cause, whether that is a host key problem, an authentication rejection, a timeout or a network error, together with the consecutive failure count and the backoff. Failures are rate limited to the first and every tenth so a dead unit cannot fill the journal, and a recovery line closes the episode.
+
 ### Fixed
 ### Fixed
 
 
 - Discovery no longer offers a unit that is already in the fleet (#1895). A candidate was marked as already added only when its IP was byte-identical to the host string in the configuration, so a unit added by DNS name, by a name with different case or a trailing dot, or by an IP with a port showed up with an Add button while the gateway, added by plain IP, was the only one recognised. The comparison now normalises case, port and the trailing dot, resolves configured names to their addresses, and also matches the reverse DNS name of the candidate, with name resolution bounded so a stale name cannot slow the scan down.
 - Discovery no longer offers a unit that is already in the fleet (#1895). A candidate was marked as already added only when its IP was byte-identical to the host string in the configuration, so a unit added by DNS name, by a name with different case or a trailing dot, or by an IP with a port showed up with an Add button while the gateway, added by plain IP, was the only one recognised. The comparison now normalises case, port and the trailing dot, resolves configured names to their addresses, and also matches the reverse DNS name of the candidate, with name resolution bounded so a stale name cannot slow the scan down.

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

@@ -333,6 +333,14 @@ func (p *SSHPool) dial(host string) (*ssh.Client, error) {
 			backoff = sshBackoffMax
 			backoff = sshBackoffMax
 		}
 		}
 		entry.notUntil = time.Now().Add(backoff)
 		entry.notUntil = time.Now().Add(backoff)
+		// #1893: un "Exit before auth" en dropbear no se podía cruzar con nada,
+		// porque el server no decía a qué host llamaba ni por qué fallaba. El
+		// motivo real (host key, auth, timeout, red) va al log del sistema con
+		// el host y el número de fallos; se registra el primero y cada diez
+		// para que una unidad apagada no sature el journal.
+		if entry.failures == 1 || entry.failures%10 == 0 {
+			log.Printf("[netpulse:ssh] dial %s (user=%s): %v (fallo %d, backoff %s)", host, cfg.User, err, entry.failures, backoff)
+		}
 		p.mu.Unlock()
 		p.mu.Unlock()
 		if isSSHAuthError(err) {
 		if isSSHAuthError(err) {
 			return nil, &SSHAuthError{Host: host, Err: err}
 			return nil, &SSHAuthError{Host: host, Err: err}
@@ -344,6 +352,13 @@ func (p *SSHPool) dial(host string) (*ssh.Client, error) {
 		_ = p.closeSSHClient(client)
 		_ = p.closeSSHClient(client)
 		return nil, errors.New("ssh pool closed")
 		return nil, errors.New("ssh pool closed")
 	}
 	}
+	// #1893: toda conexión NUEVA queda registrada. Si algo está marcando el
+	// ciclo de sondeo con conexiones que mueren antes de autenticar, aquí se
+	// ve el ritmo real de dials por host en vez de suponerlo.
+	if entry.failures > 0 {
+		log.Printf("[netpulse:ssh] %s: conexión recuperada tras %d fallos de dial", host, entry.failures)
+	}
+	log.Printf("[netpulse:ssh] %s: nueva conexión establecida (user=%s)", host, cfg.User)
 	entry.client = client
 	entry.client = client
 	entry.failures = 0
 	entry.failures = 0
 	entry.notUntil = time.Time{}
 	entry.notUntil = time.Time{}
@@ -356,6 +371,9 @@ func (p *SSHPool) drop(host string) {
 	p.mu.Lock()
 	p.mu.Lock()
 	defer p.mu.Unlock()
 	defer p.mu.Unlock()
 	if e := p.conns[host]; e != nil && e.client != nil {
 	if e := p.conns[host]; e != nil && e.client != nil {
+		// #1893: el descarte explica la reconexión siguiente; sin esta línea un
+		// dial nuevo no se puede distinguir de una fuga de conexiones.
+		log.Printf("[netpulse:ssh] %s: conexión descartada, el próximo comando rediala", host)
 		_ = p.closeSSHClient(e.client)
 		_ = p.closeSSHClient(e.client)
 		e.client = nil
 		e.client = nil
 	}
 	}

+ 107 - 0
server-go/internal/adapters/sshpool_dial_log_1893_test.go

@@ -0,0 +1,107 @@
+package adapters
+
+// #1893: una unidad solo-SSH mostraba en dropbear ráfagas de "Exit before
+// auth" y el server no registraba nada con lo que cruzarlas. Estos tests fijan
+// que el pool deja en el log del sistema cada dial nuevo, cada descarte y
+// cada fallo con su motivo, y que cierra el episodio al recuperar.
+
+import (
+	"bytes"
+	"errors"
+	"log"
+	"strings"
+	"sync/atomic"
+	"testing"
+	"time"
+
+	"golang.org/x/crypto/ssh"
+)
+
+func captureSSHPoolLog(t *testing.T) *bytes.Buffer {
+	t.Helper()
+	var buf bytes.Buffer
+	prev := log.Writer()
+	flags := log.Flags()
+	log.SetOutput(&buf)
+	log.SetFlags(0)
+	t.Cleanup(func() {
+		log.SetOutput(prev)
+		log.SetFlags(flags)
+	})
+	return &buf
+}
+
+func TestSSHPoolDialLogsFailureAndRecovery(t *testing.T) {
+	buf := captureSSHPoolLog(t)
+	pool := newTestPool(t)
+	const host = "192.168.1.50"
+
+	pool.dialTCP = func(_ string, _ string, _ *ssh.ClientConfig) (*ssh.Client, error) {
+		return nil, errors.New("i/o timeout")
+	}
+	if _, err := pool.dial(host); err == nil {
+		t.Fatal("el dial debía fallar")
+	}
+	out := buf.String()
+	if !strings.Contains(out, host) || !strings.Contains(out, "i/o timeout") {
+		t.Fatalf("el fallo de dial no quedó registrado con host y motivo: %q", out)
+	}
+	if !strings.Contains(out, "fallo 1") {
+		t.Fatalf("el log debería numerar el fallo: %q", out)
+	}
+
+	// Recuperación: se limpia el backoff a mano para no esperar al enfriamiento.
+	pool.conns[host].notUntil = time.Time{}
+	pool.dialTCP = func(_ string, _ string, _ *ssh.ClientConfig) (*ssh.Client, error) {
+		return &ssh.Client{}, nil
+	}
+	if _, err := pool.dial(host); err != nil {
+		t.Fatalf("redial: %v", err)
+	}
+	out = buf.String()
+	if !strings.Contains(out, "nueva conexión establecida") {
+		t.Fatalf("la conexión nueva no quedó registrada: %q", out)
+	}
+	if !strings.Contains(out, "recuperada tras 1 fallos") {
+		t.Fatalf("la recuperación no cerró el episodio: %q", out)
+	}
+
+}
+
+func TestSSHPoolDropLogsDiscard(t *testing.T) {
+	buf := captureSSHPoolLog(t)
+	var seenUser atomic.Value
+	addr := startPasswordOnlySSHServer(t, "admin", "s3cret", &seenUser)
+	host := addr.String()
+
+	pool := newTestPool(t)
+	pool.SetPassword(host, "admin", "s3cret")
+	if _, err := pool.dial(host); err != nil {
+		t.Fatalf("dial real: %v", err)
+	}
+	pool.drop(host)
+	if !strings.Contains(buf.String(), "conexión descartada") {
+		t.Fatalf("el descarte no quedó registrado: %q", buf.String())
+	}
+}
+
+func TestSSHPoolDialFailureLogIsRateLimited(t *testing.T) {
+	buf := captureSSHPoolLog(t)
+	pool := newTestPool(t)
+	const host = "192.168.1.51"
+
+	pool.dialTCP = func(_ string, _ string, _ *ssh.ClientConfig) (*ssh.Client, error) {
+		return nil, errors.New("connection refused")
+	}
+	for i := 0; i < 3; i++ {
+		if e := pool.conns[host]; e != nil {
+			e.notUntil = time.Time{}
+		}
+		_, _ = pool.dial(host)
+	}
+	// Tres fallos seguidos: solo el primero se registra (luego cada diez), para
+	// que una unidad apagada no escriba en el journal cada ciclo de sondeo.
+	if got := strings.Count(buf.String(), "connection refused"); got != 1 {
+		t.Fatalf("líneas de fallo = %d, quiero 1 (rate limit): %q", got, buf.String())
+	}
+}