integrations_sshpass_test.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. // integrations_sshpass_test.go - #1708: el fichero compañero de contraseña
  2. // SSH (<slug>.sshpass) del modo ssh: se escribe al editar con contraseña,
  3. // se conserva al editar sin ella, muere con la integración y su fallo de
  4. // autenticación sale con código propio (ssh_auth_failed).
  5. package httpapi_test
  6. import (
  7. "errors"
  8. "fmt"
  9. "net/http"
  10. "sync"
  11. "testing"
  12. "time"
  13. "github.com/gnacho/netpulse/server-go/internal/adapters"
  14. "github.com/gnacho/netpulse/server-go/internal/db"
  15. "github.com/gnacho/netpulse/server-go/internal/rintegration"
  16. )
  17. // sshPassFakePool registra la secuencia de eventos (set/run) para poder
  18. // afirmar el orden: la credencial se aplica ANTES de cada comando SSH.
  19. type sshPassFakePool struct {
  20. mu sync.Mutex
  21. events []string
  22. runs int
  23. fail bool
  24. }
  25. func (f *sshPassFakePool) Run(host, cmd string, _ time.Duration) (string, error) {
  26. f.mu.Lock()
  27. defer f.mu.Unlock()
  28. f.runs++
  29. if f.runs == 1 {
  30. f.events = append(f.events, "run:read")
  31. } else {
  32. f.events = append(f.events, fmt.Sprintf("run:call-%d", f.runs))
  33. }
  34. if f.fail {
  35. return "", &adapters.SSHAuthError{
  36. Host: host,
  37. Err: errors.New("ssh: handshake failed: ssh: unable to authenticate, attempted methods [none password], no supported methods remain"),
  38. }
  39. }
  40. if f.runs == 1 {
  41. return "ASUSWRT_HOST=127.0.0.1\nASUSWRT_USER=admin\nASUSWRT_PASS=old\nNETPULSE_INTERVAL=45s\n", nil
  42. }
  43. return "", nil
  44. }
  45. func (f *sshPassFakePool) SetPassword(host, user, password string) {
  46. f.mu.Lock()
  47. defer f.mu.Unlock()
  48. f.events = append(f.events, fmt.Sprintf("set:%s:%s", user, password))
  49. }
  50. func (f *sshPassFakePool) recorded() []string {
  51. f.mu.Lock()
  52. defer f.mu.Unlock()
  53. return append([]string{}, f.events...)
  54. }
  55. func seedSSHIntegration(t *testing.T, d *db.DB, mgr *rintegration.Manager) {
  56. t.Helper()
  57. store := rintegration.NewStore(d.DB)
  58. row := bootIntegrationRow("wrt-pass", "asuswrt", "ssh", true, "running")
  59. if err := store.Upsert(row); err != nil {
  60. t.Fatal(err)
  61. }
  62. }
  63. // TestIntegrationEditWritesSSHPassFile: editar con contraseña reescribe el
  64. // fichero compañero y aplica la credencial al pool antes de conectar.
  65. func TestIntegrationEditWritesSSHPassFile(t *testing.T) {
  66. pool := &sshPassFakePool{}
  67. ts, mgr := makeIntegrationsTestServerFull(t, func(d *db.DB, mgr *rintegration.Manager) {
  68. seedSSHIntegration(t, d, mgr)
  69. if err := mgr.WriteSSHPassword("wrt-pass", "old"); err != nil {
  70. t.Fatal(err)
  71. }
  72. }, nil, pool)
  73. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  74. res := putJSONPath(t, ts.URL, "/api/integrations/wrt-pass", `{"password":"nueva","intervalS":45}`, cookie)
  75. body := readJSON(t, res)
  76. if res.StatusCode != http.StatusOK {
  77. t.Fatalf("PUT con password: status %d (%v)", res.StatusCode, body)
  78. }
  79. pass, err := mgr.ReadSSHPassword("wrt-pass")
  80. if err != nil || pass != "nueva" {
  81. t.Fatalf("fichero tras editar = %q (err %v), quiero \"nueva\"", pass, err)
  82. }
  83. events := pool.recorded()
  84. if len(events) < 3 {
  85. t.Fatalf("secuencia corta: %v", events)
  86. }
  87. if events[0] != "set:admin:nueva" {
  88. t.Fatalf("la credencial debe aplicarse antes de conectar: %v", events)
  89. }
  90. if events[1] != "run:read" {
  91. t.Fatalf("la edición debe leer el env remoto tras aplicar la credencial: %v", events)
  92. }
  93. if events[len(events)-1] != "run:call-2" {
  94. t.Fatalf("la edición debe reescribir el env en una segunda llamada: %v", events)
  95. }
  96. }
  97. // TestIntegrationEditKeepsSSHPassWhenEmpty: editar sin contraseña conserva
  98. // la guardada y la sigue aplicando al pool (la conexión sigue siendo por
  99. // contraseña).
  100. func TestIntegrationEditKeepsSSHPassWhenEmpty(t *testing.T) {
  101. pool := &sshPassFakePool{}
  102. ts, mgr := makeIntegrationsTestServerFull(t, func(d *db.DB, mgr *rintegration.Manager) {
  103. seedSSHIntegration(t, d, mgr)
  104. if err := mgr.WriteSSHPassword("wrt-pass", "guardada"); err != nil {
  105. t.Fatal(err)
  106. }
  107. }, nil, pool)
  108. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  109. res := putJSONPath(t, ts.URL, "/api/integrations/wrt-pass", `{"intervalS":60}`, cookie)
  110. if res.StatusCode != http.StatusOK {
  111. t.Fatalf("PUT sin password: status %d", res.StatusCode)
  112. }
  113. pass, err := mgr.ReadSSHPassword("wrt-pass")
  114. if err != nil || pass != "guardada" {
  115. t.Fatalf("el fichero debe conservarse: %q (err %v)", pass, err)
  116. }
  117. for _, ev := range pool.recorded() {
  118. if ev == "set:admin:guardada" {
  119. return
  120. }
  121. }
  122. t.Fatalf("el pool debe recibir la credencial conservada: %v", pool.recorded())
  123. }
  124. // TestIntegrationDeleteRemovesSSHPassFile: borrar la integración quita el
  125. // fichero compañero y limpia la credencial del pool.
  126. func TestIntegrationDeleteRemovesSSHPassFile(t *testing.T) {
  127. pool := &sshPassFakePool{}
  128. ts, mgr := makeIntegrationsTestServerFull(t, func(d *db.DB, mgr *rintegration.Manager) {
  129. seedSSHIntegration(t, d, mgr)
  130. if err := mgr.WriteSSHPassword("wrt-pass", "old"); err != nil {
  131. t.Fatal(err)
  132. }
  133. }, nil, pool)
  134. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  135. res := deleteJSONPath(t, ts.URL, "/api/integrations/wrt-pass", cookie)
  136. if res.StatusCode != http.StatusNoContent {
  137. t.Fatalf("DELETE: status %d", res.StatusCode)
  138. }
  139. if pass, err := mgr.ReadSSHPassword("wrt-pass"); err != nil || pass != "" {
  140. t.Fatalf("el fichero debe desaparecer con la integración: %q (err %v)", pass, err)
  141. }
  142. for _, ev := range pool.recorded() {
  143. if ev == "set::" {
  144. return
  145. }
  146. }
  147. t.Fatalf("la credencial del pool debe limpiarse al borrar: %v", pool.recorded())
  148. }
  149. // TestIntegrationSSHAuthErrorIsItsOwnCode: el rechazo de autenticación
  150. // reporta ssh_auth_failed, no ssh_failed, para que la UI pida revisar la
  151. // contraseña.
  152. func TestIntegrationSSHAuthErrorIsItsOwnCode(t *testing.T) {
  153. pool := &sshPassFakePool{fail: true}
  154. ts, _ := makeIntegrationsTestServerFull(t, func(d *db.DB, mgr *rintegration.Manager) {
  155. seedSSHIntegration(t, d, mgr)
  156. if err := mgr.WriteSSHPassword("wrt-pass", "mala"); err != nil {
  157. t.Fatal(err)
  158. }
  159. }, nil, pool)
  160. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  161. res := putJSONPath(t, ts.URL, "/api/integrations/wrt-pass", `{"intervalS":60}`, cookie)
  162. body := readJSON(t, res)
  163. if res.StatusCode != http.StatusBadGateway {
  164. t.Fatalf("status = %d, quiero 502 (%v)", res.StatusCode, body)
  165. }
  166. if body["error"] != "ssh_auth_failed" {
  167. t.Fatalf("código de error = %v, quiero ssh_auth_failed", body["error"])
  168. }
  169. }