4
0

modules_test.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package orchestr
  2. import (
  3. "encoding/base64"
  4. "errors"
  5. "strings"
  6. "testing"
  7. "github.com/gnacho/netpulse/agent/executor"
  8. )
  9. // validateAll ejecuta executor.Validate sobre cada op y falla el test si
  10. // alguna no pasa el allowlist del agente. Garantiza que el plan generado por
  11. // orchestr es ejecutable (contrato orchestr→executor).
  12. func validateAll(t *testing.T, ops []executor.Op) {
  13. t.Helper()
  14. for i, op := range ops {
  15. if err := executor.Validate(op); err != nil {
  16. t.Errorf("op[%d] kind=%s NO pasa Validate: %v\n args=%v", i, op.Kind, err, op.Args)
  17. }
  18. }
  19. }
  20. func TestAdGuardOpsAbortaSiForkFabricante(t *testing.T) {
  21. sc := AdGuardScenario{ManagedByFirmware: true}
  22. _, err := AdGuardOps(AdGuardDesired{Enabled: true}, sc)
  23. if !errors.Is(err, ErrManagedByFirmware) {
  24. t.Fatalf("esperaba ErrManagedByFirmware, got %v", err)
  25. }
  26. }
  27. func TestAdGuardOpsDisable(t *testing.T) {
  28. ops, err := AdGuardOps(AdGuardDesired{Enabled: false}, AdGuardScenario{})
  29. if err != nil {
  30. t.Fatalf("disable inesperado error: %v", err)
  31. }
  32. // Sin ops de install/download (solo limpia DNS + para servicio).
  33. for _, op := range ops {
  34. if op.Kind == "install" || op.Kind == "apk_install" || op.Kind == "download" {
  35. t.Errorf("disable no debe instalar: encontró %s", op.Kind)
  36. }
  37. }
  38. // Debe tener uci_delete server + service stop.
  39. hasDel, hasStop := false, false
  40. for _, op := range ops {
  41. if op.Kind == "uci_delete" && op.Args["option"] == "server" {
  42. hasDel = true
  43. }
  44. if op.Kind == "service" && op.Args["action"] == "stop" {
  45. hasStop = true
  46. }
  47. }
  48. if !hasDel || !hasStop {
  49. t.Errorf("disable incompleto: hasDel=%v hasStop=%v", hasDel, hasStop)
  50. }
  51. validateAll(t, ops)
  52. }
  53. func TestAdGuardOpsEscenarioApk(t *testing.T) {
  54. sc := AdGuardScenario{ApkAvailable: true, Arch: "x86_64", AdguardSuffix: "amd64"}
  55. ops, err := AdGuardOps(AdGuardDesired{Enabled: true, Port: "5300", UpstreamDNS: "9.9.9.9"}, sc)
  56. if err != nil {
  57. t.Fatalf("apk inesperado error: %v", err)
  58. }
  59. if ops[0].Kind != "apk_install" || ops[0].Args["package"] != "adguard-home" {
  60. t.Errorf("primera op debe ser apk_install adguard-home, got %+v", ops[0])
  61. }
  62. // Sin download (usa gestor de paquetes).
  63. for _, op := range ops {
  64. if op.Kind == "download" || op.Kind == "extract_tarball" || op.Kind == "mv" {
  65. t.Errorf("apk no debe descargar binario: encontró %s", op.Kind)
  66. }
  67. }
  68. // El reenvío DNS va al puerto DNS fijo (adGuardDNSPort), NO al puerto de la UI.
  69. // El puerto deseado (5300) solo afecta a la UI (bind_port/tcp_check).
  70. hasForward := false
  71. for _, op := range ops {
  72. if op.Kind == "uci_set" && op.Args["option"] == "server" && op.Args["value"] == "127.0.0.1#"+adGuardDNSPort {
  73. hasForward = true
  74. }
  75. }
  76. if !hasForward {
  77. t.Errorf("apk debe forwardear DNS al puerto DNS fijo %s, no al de la UI", adGuardDNSPort)
  78. }
  79. // El tcp_check de la UI usa el puerto deseado, no el del DNS.
  80. hasTCP := false
  81. for _, op := range ops {
  82. if op.Kind == "tcp_check" && op.Args["port"] == "5300" {
  83. hasTCP = true
  84. }
  85. }
  86. if !hasTCP {
  87. t.Error("tcp_check de la UI debe apuntar al puerto 5300 (bind_port)")
  88. }
  89. validateAll(t, ops)
  90. }
  91. func TestAdGuardOpsEscenarioOpkg(t *testing.T) {
  92. sc := AdGuardScenario{OpkgAvailable: true, Arch: "mips", AdguardSuffix: "mips"}
  93. ops, err := AdGuardOps(AdGuardDesired{Enabled: true}, sc)
  94. if err != nil {
  95. t.Fatalf("opkg inesperado error: %v", err)
  96. }
  97. if ops[0].Kind != "install" || ops[0].Args["package"] != "adguard-home" {
  98. t.Errorf("primera op debe ser install (opkg) adguard-home, got %+v", ops[0])
  99. }
  100. validateAll(t, ops)
  101. }
  102. func TestAdGuardOpsEscenarioNoneBinarioYaPresente(t *testing.T) {
  103. sc := AdGuardScenario{BinaryPresent: true, Arch: "aarch64", AdguardSuffix: "arm64"}
  104. ops, err := AdGuardOps(AdGuardDesired{Enabled: true}, sc)
  105. if err != nil {
  106. t.Fatalf("none inesperado error: %v", err)
  107. }
  108. // Sin install ni download (binario ya está).
  109. for _, op := range ops {
  110. if op.Kind == "install" || op.Kind == "apk_install" || op.Kind == "download" {
  111. t.Errorf("none no debe instalar/descargar: encontró %s", op.Kind)
  112. }
  113. }
  114. validateAll(t, ops)
  115. }
  116. func TestAdGuardOpsEscenarioBinary(t *testing.T) {
  117. sc := AdGuardScenario{Arch: "aarch64", AdguardSuffix: "arm64"}
  118. ops, err := AdGuardOps(AdGuardDesired{Enabled: true, Port: "3000", UpstreamDNS: "1.1.1.1"}, sc)
  119. if err != nil {
  120. t.Fatalf("binary inesperado error: %v", err)
  121. }
  122. // Secuencia esperada: download → extract → mv → chmod → write_file config
  123. // → write_file init.d → chmod init.d → enable → start → tcp_check UI →
  124. // uci_set ×2 → commit → dnsmasq restart.
  125. kinds := make([]string, len(ops))
  126. for i, op := range ops {
  127. kinds[i] = op.Kind
  128. }
  129. wantSeq := []string{"download", "extract_tarball", "mv", "chmod", "write_file", "write_file", "chmod", "service", "service", "tcp_check", "uci_set", "uci_set", "uci_commit", "service"}
  130. if len(kinds) != len(wantSeq) {
  131. t.Fatalf("binary plan length: got %d want %d\nkinds: %v", len(kinds), len(wantSeq), kinds)
  132. }
  133. for i, want := range wantSeq {
  134. if kinds[i] != want {
  135. t.Errorf("binary step %d: got %s want %s\nfull: %v", i, kinds[i], want, kinds)
  136. }
  137. }
  138. validateAll(t, ops)
  139. }
  140. func TestAdGuardOpsBinaryURLContieneVersionYSuffix(t *testing.T) {
  141. sc := AdGuardScenario{Arch: "aarch64", AdguardSuffix: "arm64"}
  142. ops, err := AdGuardOps(AdGuardDesired{Enabled: true}, sc)
  143. if err != nil {
  144. t.Fatalf("binary inesperado error: %v", err)
  145. }
  146. if len(ops) == 0 || ops[0].Kind != "download" {
  147. t.Fatal("primera op debe ser download")
  148. }
  149. url := ops[0].Args["url"]
  150. if !strings.Contains(url, adguardVersion) {
  151. t.Errorf("URL no contiene versión %s: %s", adguardVersion, url)
  152. }
  153. if !strings.Contains(url, "_arm64.tar.gz") {
  154. t.Errorf("URL no contiene suffix arm64: %s", url)
  155. }
  156. // Validate pasa (allowlist de URL).
  157. if err := executor.Validate(ops[0]); err != nil {
  158. t.Errorf("download op no valida: %v", err)
  159. }
  160. }
  161. func TestAdGuardOpsBinaryFallbackSuffix(t *testing.T) {
  162. // Arch desconocida → fallback "arm64" en la URL (no rompe, el plan sigue
  163. // siendo válido; fallaría en apply-time si la arch real no es arm64).
  164. sc := AdGuardScenario{Arch: "exotic", AdguardSuffix: ""}
  165. ops, err := AdGuardOps(AdGuardDesired{Enabled: true}, sc)
  166. if err != nil {
  167. t.Fatalf("binary fallback inesperado error: %v", err)
  168. }
  169. if !strings.Contains(ops[0].Args["url"], "_arm64.tar.gz") {
  170. t.Errorf("fallback URL debe usar arm64: %s", ops[0].Args["url"])
  171. }
  172. validateAll(t, ops)
  173. }
  174. func TestAdGuardOpsDNSForwardMatchConfigBinary(t *testing.T) {
  175. // Regresión issue #269: el puerto que dnsmasq reenvía (127.0.0.1#X) debe
  176. // coincidir con el dns.port de la config de AdGuard, y el DNS no debe
  177. // chocar con la UI (bind_port). Antes reenviaba al puerto de la UI.
  178. sc := AdGuardScenario{Arch: "aarch64", AdguardSuffix: "arm64"}
  179. ops, err := AdGuardOps(AdGuardDesired{Enabled: true, Port: "3000", UpstreamDNS: "1.1.1.1"}, sc)
  180. if err != nil {
  181. t.Fatalf("binary inesperado error: %v", err)
  182. }
  183. // puerto de reenvío dnsmasq
  184. var fwdPort string
  185. for _, op := range ops {
  186. if op.Kind == "uci_set" && op.Args["option"] == "server" {
  187. fwdPort = strings.TrimPrefix(op.Args["value"], "127.0.0.1#")
  188. }
  189. }
  190. if fwdPort == "" {
  191. t.Fatal("no se encontró op uci_set server de reenvío")
  192. }
  193. if fwdPort != adGuardDNSPort {
  194. t.Errorf("dnsmasq reenvía a %q, esperado %q", fwdPort, adGuardDNSPort)
  195. }
  196. // puerto de la UI (bind_port / tcp_check) debe ser distinto del DNS
  197. var uiPort string
  198. for _, op := range ops {
  199. if op.Kind == "tcp_check" {
  200. uiPort = op.Args["port"]
  201. }
  202. }
  203. if uiPort == fwdPort {
  204. t.Errorf("UI y DNS comparten puerto %q: colisión", uiPort)
  205. }
  206. // la config embebida debe tener dns.port == fwdPort
  207. for _, op := range ops {
  208. if op.Kind == "write_file" && strings.Contains(op.Args["path"], "AdGuardHome.yaml") {
  209. raw, err := base64.StdEncoding.DecodeString(op.Args["content_b64"])
  210. if err != nil {
  211. t.Fatalf("config no es base64 válido: %v", err)
  212. }
  213. if !strings.Contains(string(raw), " port: "+fwdPort) {
  214. t.Errorf("config dns.port no coincide con reenvío %q\nconfig:\n%s", fwdPort, raw)
  215. }
  216. if !strings.Contains(string(raw), " port: 53") {
  217. t.Errorf("config no debe usar el puerto fijo 53 (mal):\n%s", raw)
  218. }
  219. }
  220. }
  221. validateAll(t, ops)
  222. }