sshpool_2014_test.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. package adapters
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "sync"
  8. "testing"
  9. "github.com/gnacho/netpulse/server-go/internal/sshkey"
  10. "golang.org/x/crypto/ssh/knownhosts"
  11. )
  12. // TestHostKeyCallbackRecoversFromCorruptKnownHosts: una línea corrupta en el
  13. // known_hosts deja hoy sin SSH a TODAS las unidades, porque knownhosts.New
  14. // rechaza el fichero entero (#2014). El callback debe sanear antes de cargar.
  15. func TestHostKeyCallbackRecoversFromCorruptKnownHosts(t *testing.T) {
  16. pool := newTestPool(t)
  17. _, pub := genTestKey(t)
  18. good := knownhosts.Line([]string{knownhosts.Normalize("host-a")}, pub)
  19. content := good + "\nhost-corrupt ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAbc\n"
  20. if err := os.WriteFile(pool.khPath, []byte(content), 0o600); err != nil {
  21. t.Fatal(err)
  22. }
  23. // Premisa: la línea corrupta sigue siendo inválida. Desde x/crypto 0.59
  24. // knownhosts.New salta las líneas malas de un fichero mixto y solo falla
  25. // cuando no queda ninguna válida, así que se comprueba aparte.
  26. onlyBad := filepath.Join(t.TempDir(), "known_hosts")
  27. if err := os.WriteFile(onlyBad, []byte("host-corrupt ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAbc\n"), 0o600); err != nil {
  28. t.Fatal(err)
  29. }
  30. if _, err := knownhosts.New(onlyBad); err == nil {
  31. t.Fatal("premisa rota: un known_hosts solo con la línea corrupta debería fallar")
  32. }
  33. cb, err := pool.hostKeyCallback()
  34. if err != nil {
  35. t.Fatalf("el callback debería recuperarse de una línea corrupta, obtuve: %v", err)
  36. }
  37. if cb == nil {
  38. t.Fatal("callback nil")
  39. }
  40. data, _ := os.ReadFile(pool.khPath)
  41. if strings.Contains(string(data), "host-corrupt") {
  42. t.Fatal("la línea corrupta sigue en el fichero")
  43. }
  44. if !strings.Contains(string(data), good) {
  45. t.Fatal("el saneado se comió la entrada válida")
  46. }
  47. }
  48. // TestRemoveHostKeyConcurrentWithAppends: la carrera del issue consistía en
  49. // reescribir el fichero (truncate en sitio) mientras otro escritor hacía
  50. // append. Con la reescritura atómica el fichero siempre queda legible.
  51. func TestRemoveHostKeyConcurrentWithAppends(t *testing.T) {
  52. pool := newTestPool(t)
  53. const n = 40
  54. lines := make([]string, n)
  55. for i := 0; i < n; i++ {
  56. _, pub := genTestKey(t)
  57. lines[i] = knownhosts.Line([]string{knownhosts.Normalize(fmt.Sprintf("host-%d", i))}, pub)
  58. }
  59. if err := os.WriteFile(pool.khPath, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
  60. t.Fatal(err)
  61. }
  62. var wg sync.WaitGroup
  63. for i := 0; i < n; i++ {
  64. wg.Add(2)
  65. go func(i int) {
  66. defer wg.Done()
  67. if err := sshkey.AppendKnownHosts(pool.khPath, []string{lines[i]}); err != nil {
  68. t.Errorf("append %d: %v", i, err)
  69. }
  70. }(i)
  71. go func(i int) {
  72. defer wg.Done()
  73. if err := pool.RemoveHostKey(fmt.Sprintf("host-%d", i)); err != nil {
  74. t.Errorf("remove %d: %v", i, err)
  75. }
  76. }(i)
  77. }
  78. wg.Wait()
  79. if _, err := knownhosts.New(pool.khPath); err != nil {
  80. t.Fatalf("known_hosts ilegible tras la concurrencia: %v", err)
  81. }
  82. }
  83. // TestRemoveHostKeyKeepsOtherHostsAndSkipsNoop: sin coincidencias no se
  84. // reescribe; con coincidencias se quita solo ese host.
  85. func TestRemoveHostKeyKeepsOtherHostsAndSkipsNoop(t *testing.T) {
  86. pool := newTestPool(t)
  87. _, pubA := genTestKey(t)
  88. _, pubB := genTestKey(t)
  89. a := knownhosts.Line([]string{knownhosts.Normalize("host-a")}, pubA)
  90. b := knownhosts.Line([]string{knownhosts.Normalize("host-b")}, pubB)
  91. if err := os.WriteFile(pool.khPath, []byte(a+"\n"+b+"\n"), 0o600); err != nil {
  92. t.Fatal(err)
  93. }
  94. before, _ := os.Stat(pool.khPath)
  95. if err := pool.RemoveHostKey("host-inexistente"); err != nil {
  96. t.Fatal(err)
  97. }
  98. after, _ := os.Stat(pool.khPath)
  99. if !os.SameFile(before, after) {
  100. t.Fatal("un RemoveHostKey sin coincidencias no debería reescribir el fichero")
  101. }
  102. if err := pool.RemoveHostKey("host-a"); err != nil {
  103. t.Fatal(err)
  104. }
  105. data, _ := os.ReadFile(pool.khPath)
  106. s := string(data)
  107. if strings.Contains(s, "host-a") {
  108. t.Fatal("no se quitó host-a")
  109. }
  110. if !strings.Contains(s, b) {
  111. t.Fatal("se perdió host-b")
  112. }
  113. }