sshpool_key_1893_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package adapters
  2. import (
  3. "errors"
  4. "os"
  5. "path/filepath"
  6. "testing"
  7. "golang.org/x/crypto/ssh"
  8. )
  9. // #1893: el mismo router llega como "test-gw.lan" (host de la config) y como
  10. // "test-gw.lan:22" (SSHAddr). El puerto por defecto no distingue hosts.
  11. func TestPoolKeyCollapsesTheDefaultPort(t *testing.T) {
  12. cases := []struct{ in, want string }{
  13. {"test-gw.lan", "test-gw.lan"},
  14. {"test-gw.lan:22", "test-gw.lan"},
  15. {"192.168.1.172:22", "192.168.1.172"},
  16. {"test-gw.lan:2222", "test-gw.lan:2222"},
  17. {"[2001:db8::1]:22", "2001:db8::1"},
  18. {"[2001:db8::1]:2222", "[2001:db8::1]:2222"},
  19. }
  20. for _, c := range cases {
  21. if got := poolKey(c.in); got != c.want {
  22. t.Errorf("poolKey(%q) = %q, want %q", c.in, got, c.want)
  23. }
  24. }
  25. }
  26. // Una credencial por unidad, aunque llegue con las dos formas.
  27. func TestSetPasswordUsesOneEntryPerHost(t *testing.T) {
  28. p := &SSHPool{conns: map[string]*sshConn{}, creds: map[string]sshCred{}}
  29. p.SetPassword("test-gw.lan:22", "root", "s3cret")
  30. p.SetPassword("test-gw.lan", "root", "s3cret")
  31. if len(p.creds) != 1 {
  32. t.Fatalf("creds = %d entradas, esperaba 1 (%v)", len(p.creds), p.creds)
  33. }
  34. if _, ok := p.creds["test-gw.lan"]; !ok {
  35. t.Fatalf("la credencial no quedo bajo la clave normalizada: %v", p.creds)
  36. }
  37. }
  38. // Y una sola conexión: el segundo dial reutiliza la entrada (o su backoff) en
  39. // vez de abrir un handshake nuevo al mismo equipo.
  40. func TestDialCollapsesHostAndDefaultPort(t *testing.T) {
  41. kh := filepath.Join(t.TempDir(), "known_hosts")
  42. if err := os.WriteFile(kh, nil, 0o600); err != nil {
  43. t.Fatalf("known_hosts: %v", err)
  44. }
  45. dials := 0
  46. p := &SSHPool{
  47. khPath: kh,
  48. conns: map[string]*sshConn{},
  49. creds: map[string]sshCred{},
  50. dialTCP: func(_, _ string, _ *ssh.ClientConfig) (*ssh.Client, error) {
  51. dials++
  52. return nil, errors.New("unreachable")
  53. },
  54. }
  55. if _, err := p.dial("test-gw.lan:22"); err == nil {
  56. t.Fatal("el primer dial debia fallar")
  57. }
  58. if _, err := p.dial("test-gw.lan"); err == nil {
  59. t.Fatal("el segundo dial debia caer en el backoff")
  60. }
  61. if dials != 1 {
  62. t.Fatalf("diales = %d, esperaba 1: host y host:22 son el mismo equipo", dials)
  63. }
  64. if len(p.conns) != 1 {
  65. t.Fatalf("conns = %d entradas, esperaba 1", len(p.conns))
  66. }
  67. }