sshpool_test.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. package adapters
  2. import (
  3. "crypto/ed25519"
  4. "crypto/rand"
  5. "errors"
  6. "net"
  7. "os"
  8. "strings"
  9. "sync"
  10. "sync/atomic"
  11. "testing"
  12. "time"
  13. "golang.org/x/crypto/ssh"
  14. "golang.org/x/crypto/ssh/knownhosts"
  15. )
  16. func newTestPool(t *testing.T) *SSHPool {
  17. t.Helper()
  18. kh, err := os.CreateTemp(t.TempDir(), "known_hosts")
  19. if err != nil {
  20. t.Fatal(err)
  21. }
  22. kh.Close()
  23. return &SSHPool{
  24. khPath: kh.Name(),
  25. conns: map[string]*sshConn{},
  26. dialTCP: ssh.Dial,
  27. }
  28. }
  29. func TestSSHPoolClosedRejectsDial(t *testing.T) {
  30. pool := newTestPool(t)
  31. pool.Close()
  32. _, err := pool.dial("1.2.3.4")
  33. if err == nil || err.Error() != "ssh pool closed" {
  34. t.Fatalf("esperaba 'ssh pool closed', obtuve: %v", err)
  35. }
  36. }
  37. func TestSSHPoolSingleFlight_LeaderSuccess(t *testing.T) {
  38. pool := newTestPool(t)
  39. var dials atomic.Int32
  40. ready := make(chan struct{})
  41. pool.dialTCP = func(network, addr string, cfg *ssh.ClientConfig) (*ssh.Client, error) {
  42. dials.Add(1)
  43. <-ready
  44. return &ssh.Client{}, nil
  45. }
  46. const N = 2
  47. results := make([]*ssh.Client, N)
  48. errs := make([]error, N)
  49. var wg sync.WaitGroup
  50. for i := 0; i < N; i++ {
  51. wg.Add(1)
  52. go func(i int) {
  53. defer wg.Done()
  54. time.Sleep(30 * time.Millisecond)
  55. results[i], errs[i] = pool.dial("10.0.0.1")
  56. }(i)
  57. }
  58. time.Sleep(100 * time.Millisecond)
  59. close(ready)
  60. wg.Wait()
  61. if n := dials.Load(); n != 1 {
  62. t.Fatalf("dialTCP llamado %d veces, esperaba 1 (single-flight)", n)
  63. }
  64. for i := 0; i < N; i++ {
  65. if errs[i] != nil {
  66. t.Errorf("goroutine %d: %v", i, errs[i])
  67. }
  68. if results[i] == nil {
  69. t.Errorf("goroutine %d: result nil", i)
  70. }
  71. }
  72. }
  73. func TestSSHPoolSingleFlight_LeaderFails(t *testing.T) {
  74. pool := newTestPool(t)
  75. var dials atomic.Int32
  76. ready := make(chan struct{})
  77. pool.dialTCP = func(network, addr string, cfg *ssh.ClientConfig) (*ssh.Client, error) {
  78. dials.Add(1)
  79. <-ready
  80. return nil, &net.OpError{Op: "dial", Err: errors.New("timeout")}
  81. }
  82. const N = 2
  83. var wg sync.WaitGroup
  84. errCh := make(chan error, N)
  85. for i := 0; i < N; i++ {
  86. wg.Add(1)
  87. go func() {
  88. defer wg.Done()
  89. time.Sleep(30 * time.Millisecond)
  90. _, err := pool.dial("10.0.0.2")
  91. errCh <- err
  92. }()
  93. }
  94. time.Sleep(100 * time.Millisecond)
  95. close(ready)
  96. wg.Wait()
  97. close(errCh)
  98. if n := dials.Load(); n != 1 {
  99. t.Fatalf("dialTCP llamado %d veces, esperaba 1", n)
  100. }
  101. failures := 0
  102. for err := range errCh {
  103. if err == nil {
  104. t.Error("esperaba error del follower")
  105. continue
  106. }
  107. if err.Error() == "ssh dial failed" || err.Error()[:3] == "ssh" {
  108. failures++
  109. }
  110. }
  111. if failures != N {
  112. t.Errorf("%d errores, esperaba %d", failures, N)
  113. }
  114. }
  115. func genTestKey(t *testing.T) (ssh.Signer, ssh.PublicKey) {
  116. t.Helper()
  117. _, priv, err := ed25519.GenerateKey(rand.Reader)
  118. if err != nil {
  119. t.Fatal(err)
  120. }
  121. signer, err := ssh.NewSignerFromKey(priv)
  122. if err != nil {
  123. t.Fatal(err)
  124. }
  125. pub, err := ssh.NewPublicKey(priv.Public())
  126. if err != nil {
  127. t.Fatal(err)
  128. }
  129. return signer, pub
  130. }
  131. // TestRemoveHostKeyEliminaEntrada: RemoveHostKey quita la línea del host,
  132. // conserva los demás hosts y deja el fichero sin esa entrada (#603).
  133. func TestRemoveHostKeyEliminaEntrada(t *testing.T) {
  134. pool := newTestPool(t)
  135. host := "host.example"
  136. other := "other.example"
  137. _, oldPub := genTestKey(t)
  138. _, otherPub := genTestKey(t)
  139. oldLine := knownhosts.Line([]string{knownhosts.Normalize(host)}, oldPub) + "\n"
  140. otherLine := knownhosts.Line([]string{knownhosts.Normalize(other)}, otherPub) + "\n"
  141. if err := os.WriteFile(pool.khPath, []byte(oldLine+otherLine), 0o600); err != nil {
  142. t.Fatal(err)
  143. }
  144. if err := pool.RemoveHostKey(host); err != nil {
  145. t.Fatal(err)
  146. }
  147. data, _ := os.ReadFile(pool.khPath)
  148. s := string(data)
  149. if strings.Contains(s, knownhosts.Normalize(host)) {
  150. t.Fatal("la entrada del host no se eliminó")
  151. }
  152. if !strings.Contains(s, otherLine) {
  153. t.Fatal("se perdió un host no relacionado")
  154. }
  155. }
  156. // TestHostKeyCallbackRejectsChangedKey: una clave conocida pero distinta NO se
  157. // acepta en silencio: el callback devuelve HostKeyChangedError y no toca el
  158. // known_hosts (#603). El re-onboard es una confirmación explícita del admin.
  159. func TestHostKeyCallbackRejectsChangedKey(t *testing.T) {
  160. pool := newTestPool(t)
  161. host := "host.example"
  162. _, oldPub := genTestKey(t)
  163. oldLine := knownhosts.Line([]string{knownhosts.Normalize(host)}, oldPub) + "\n"
  164. if err := os.WriteFile(pool.khPath, []byte(oldLine), 0o600); err != nil {
  165. t.Fatal(err)
  166. }
  167. cb, err := pool.hostKeyCallback()
  168. if err != nil {
  169. t.Fatal(err)
  170. }
  171. _, newPub := genTestKey(t)
  172. err = cb(host+":22", &net.TCPAddr{IP: net.ParseIP("1.2.3.4"), Port: 22}, newPub)
  173. var hk *HostKeyChangedError
  174. if !errors.As(err, &hk) {
  175. t.Fatalf("clave cambiada debería devolver HostKeyChangedError, obtuve: %v", err)
  176. }
  177. data, _ := os.ReadFile(pool.khPath)
  178. if !strings.Contains(string(data), oldLine) {
  179. t.Fatal("el known_hosts no debería tocarse al rechazar la clave cambiada")
  180. }
  181. }
  182. func TestAddrOf(t *testing.T) {
  183. if got := addrOf("192.168.1.2"); got != "192.168.1.2:22" {
  184. t.Fatalf("addrOf(sin puerto) = %q, esperaba 192.168.1.2:22", got)
  185. }
  186. if got := addrOf("192.168.1.2:2222"); got != "192.168.1.2:2222" {
  187. t.Fatalf("addrOf(con puerto) = %q, esperaba 192.168.1.2:2222", got)
  188. }
  189. }
  190. func TestRouterConfigSSHAddr(t *testing.T) {
  191. if got := (RouterConfig{Host: "192.168.1.2"}).SSHAddr(); got != "192.168.1.2:22" {
  192. t.Fatalf("SSHAddr sin puerto = %q", got)
  193. }
  194. if got := (RouterConfig{Host: "192.168.1.2", SSHPort: 2222}).SSHAddr(); got != "192.168.1.2:2222" {
  195. t.Fatalf("SSHAddr con puerto = %q", got)
  196. }
  197. if got := (RouterConfig{Host: "10.0.0.5", SSHPort: -1}).SSHAddr(); got != "10.0.0.5:22" {
  198. t.Fatalf("SSHAddr con puerto inválido = %q", got)
  199. }
  200. }
  201. // TestRemoveHostKeyCustomPort (#1524): la entrada de un router con SSH en
  202. // puerto no estándar vive como [host]:puerto (knownhosts.Normalize), así que
  203. // el borrado solo por el host pelado no encontraba nada y el re-onboard
  204. // (#603) nunca ocurría. Se aceptan candidatos: la dirección SSH completa y el
  205. // host pelado (por entradas viejas de cuando el router no tenía puerto).
  206. func TestRemoveHostKeyCustomPort(t *testing.T) {
  207. pool := newTestPool(t)
  208. content := strings.Join([]string{
  209. "[host-a]:2222 ssh-ed25519 AAAA old-port",
  210. "host-a ssh-ed25519 AAAA old-bare",
  211. "host-b ssh-ed25519 AAAA keep",
  212. "",
  213. }, "\n")
  214. if err := os.WriteFile(pool.khPath, []byte(content), 0o600); err != nil {
  215. t.Fatal(err)
  216. }
  217. if err := pool.RemoveHostKey("host-a:2222", "host-a"); err != nil {
  218. t.Fatal(err)
  219. }
  220. data, err := os.ReadFile(pool.khPath)
  221. if err != nil {
  222. t.Fatal(err)
  223. }
  224. if strings.Contains(string(data), "host-a") {
  225. t.Fatalf("quedan entradas de host-a: %s", data)
  226. }
  227. if !strings.Contains(string(data), "host-b ssh-ed25519 AAAA keep") {
  228. t.Fatalf("la entrada de host-b se perdió: %s", data)
  229. }
  230. }
  231. func TestSSHPoolCloseDuringDialReleasesClient(t *testing.T) {
  232. pool := newTestPool(t)
  233. started := make(chan struct{})
  234. ready := make(chan struct{})
  235. closed := make(chan struct{}, 1)
  236. pool.closeClient = func(c *ssh.Client) error {
  237. closed <- struct{}{}
  238. return nil
  239. }
  240. pool.dialTCP = func(network, addr string, cfg *ssh.ClientConfig) (*ssh.Client, error) {
  241. close(started)
  242. <-ready
  243. return &ssh.Client{}, nil
  244. }
  245. errCh := make(chan error, 1)
  246. go func() {
  247. _, err := pool.dial("10.0.0.3")
  248. errCh <- err
  249. }()
  250. select {
  251. case <-started:
  252. case <-time.After(2 * time.Second):
  253. t.Fatal("dialTCP no arrancó")
  254. }
  255. pool.Close()
  256. close(ready)
  257. select {
  258. case err := <-errCh:
  259. if err == nil || err.Error() != "ssh pool closed" {
  260. t.Fatalf("esperaba 'ssh pool closed', obtuve: %v", err)
  261. }
  262. case <-time.After(2 * time.Second):
  263. t.Fatal("dial no terminó tras Close")
  264. }
  265. select {
  266. case <-closed:
  267. case <-time.After(time.Second):
  268. t.Fatal("el cliente SSH no se cerró al detectar el pool cerrado")
  269. }
  270. }