proxmox_detect_internal_test.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. // proxmox_detect_internal_test.go - POST /api/config/proxmox/detect (#967):
  2. // barrido en dos fases (TCP masivo + confirmacion TLS EN SERIE) sobre la /24
  3. // de los hosts de `routers`, y validacion de la sonda TLS real.
  4. package httpapi
  5. import (
  6. "encoding/json"
  7. "net/http"
  8. "net/http/httptest"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "testing"
  14. "time"
  15. "github.com/gnacho/netpulse/server-go/internal/db"
  16. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  17. )
  18. // TestDetectProxmoxTwoPhase: fase 1 barre la /24 entera en TCP; fase 2
  19. // confirma TLS EN SERIE (concurrencia maxima 1, causa raiz del bug en vivo:
  20. // pveproxy limita conexiones simultaneas por IP).
  21. func TestDetectProxmoxTwoPhase(t *testing.T) {
  22. d, err := db.Open(t.TempDir())
  23. if err != nil {
  24. t.Fatalf("db.Open: %v", err)
  25. }
  26. t.Cleanup(func() { _ = d.Close() })
  27. if _, err := routerstore.AddRouter(d.DB, routerstore.AddInput{Name: "gw", Host: "192.0.2.1", IsGateway: true}); err != nil {
  28. t.Fatalf("AddRouter: %v", err)
  29. }
  30. var tcpCalls atomic.Int64
  31. oldTCP := pveTCPProbe
  32. t.Cleanup(func() { pveTCPProbe = oldTCP })
  33. pveTCPProbe = func(host string, _ int, _ time.Duration) bool {
  34. tcpCalls.Add(1)
  35. // Dos candidatos abiertos en la /24: .100 (confirma) y .200 (no).
  36. return host == "192.0.2.100" || host == "192.0.2.200"
  37. }
  38. var concurrent, maxConcurrent atomic.Int64
  39. confirmed := []string{}
  40. var mu sync.Mutex
  41. oldTLS := pveTLSConfirm
  42. t.Cleanup(func() { pveTLSConfirm = oldTLS })
  43. pveTLSConfirm = func(host string, _ int, _ time.Duration) bool {
  44. n := concurrent.Add(1)
  45. for {
  46. m := maxConcurrent.Load()
  47. if n <= m || maxConcurrent.CompareAndSwap(m, n) {
  48. break
  49. }
  50. }
  51. defer concurrent.Add(-1)
  52. time.Sleep(5 * time.Millisecond) // solape visible si hubiera paralelismo
  53. mu.Lock()
  54. confirmed = append(confirmed, host)
  55. mu.Unlock()
  56. return host == "192.0.2.100"
  57. }
  58. s := &server{db: d}
  59. rec := httptest.NewRecorder()
  60. req := httptest.NewRequest("POST", "/api/config/proxmox/detect", nil)
  61. s.handleDetectProxmox(rec, req)
  62. if rec.Code != 200 {
  63. t.Fatalf("detect: status %d", rec.Code)
  64. }
  65. var out proxmoxDetectResponse
  66. if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
  67. t.Fatalf("detect json: %v", err)
  68. }
  69. if !out.Found || len(out.Hosts) != 1 || out.Hosts[0] != "192.0.2.100" {
  70. t.Fatalf("respuesta: %+v", out)
  71. }
  72. if n := tcpCalls.Load(); n != 254 {
  73. t.Fatalf("fase 1: %d sondeos TCP, esperado 254 (/24 completa)", n)
  74. }
  75. if m := maxConcurrent.Load(); m != 1 {
  76. t.Fatalf("fase 2: concurrencia maxima %d, esperado 1 (serie estricta)", m)
  77. }
  78. if len(confirmed) != 2 {
  79. t.Fatalf("fase 2: %d confirmaciones, esperado 2 candidatos", len(confirmed))
  80. }
  81. }
  82. // TestConfirmPVEHost: la sonda TLS real acepta header Server pve-api-daemon
  83. // o un body con "pve", y rechaza cualquier otro servicio TLS en :8006.
  84. func TestConfirmPVEHost(t *testing.T) {
  85. hostPort := func(t *testing.T, h http.Handler) (string, int) {
  86. t.Helper()
  87. srv := httptest.NewTLSServer(h)
  88. t.Cleanup(srv.Close)
  89. parts := strings.Split(strings.TrimPrefix(srv.URL, "https://"), ":")
  90. port, err := strconv.Atoi(parts[1])
  91. if err != nil {
  92. t.Fatalf("port: %v", err)
  93. }
  94. return parts[0], port
  95. }
  96. // Body con "pve" (version API real).
  97. h, p := hostPort(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  98. _, _ = w.Write([]byte(`{"data":{"version":"8.2.4","release":"pve","repoid":"2"}}`))
  99. }))
  100. if !confirmPVEHost(h, p, 3*time.Second) {
  101. t.Fatal("body pve: no confirmado")
  102. }
  103. // Sin body pve pero con header Server pve-api-daemon.
  104. h, p = hostPort(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  105. w.Header().Set("Server", "pve-api-daemon/3.10.8")
  106. _, _ = w.Write([]byte(`{"data":null}`))
  107. }))
  108. if !confirmPVEHost(h, p, 3*time.Second) {
  109. t.Fatal("header pve-api-daemon: no confirmado")
  110. }
  111. // Otro servicio TLS cualquiera: no es PVE.
  112. h, p = hostPort(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  113. _, _ = w.Write([]byte(`<html>router admin</html>`))
  114. }))
  115. if confirmPVEHost(h, p, 3*time.Second) {
  116. t.Fatal("servicio ajeno: confirmado como PVE")
  117. }
  118. }
  119. // TestDetectProxmoxNoRouters: sin hosts IPv4 configurados, found=false.
  120. func TestDetectProxmoxNoRouters(t *testing.T) {
  121. d, err := db.Open(t.TempDir())
  122. if err != nil {
  123. t.Fatalf("db.Open: %v", err)
  124. }
  125. t.Cleanup(func() { _ = d.Close() })
  126. s := &server{db: d}
  127. rec := httptest.NewRecorder()
  128. req := httptest.NewRequest("POST", "/api/config/proxmox/detect", nil)
  129. s.handleDetectProxmox(rec, req)
  130. var out proxmoxDetectResponse
  131. if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
  132. t.Fatalf("detect json: %v", err)
  133. }
  134. if out.Found || len(out.Hosts) != 0 {
  135. t.Fatalf("respuesta: %+v, esperado found=false", out)
  136. }
  137. }