executor_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. package executor
  2. import (
  3. "net"
  4. "os"
  5. "strconv"
  6. "strings"
  7. "testing"
  8. "time"
  9. )
  10. // fakeRunner registra los comandos ejecutados y devuelve respuestas canned.
  11. type fakeRunner struct {
  12. calls []string
  13. responses map[string]int // prefix → exitCode (0 si no está)
  14. }
  15. func newFakeRunner() *fakeRunner {
  16. return &fakeRunner{responses: map[string]int{}}
  17. }
  18. func (f *fakeRunner) Run(name string, args ...string) (string, int) {
  19. cmd := name + " " + strings.Join(args, " ")
  20. f.calls = append(f.calls, cmd)
  21. // Buscar respuesta por prefix.
  22. for prefix, code := range f.responses {
  23. if strings.HasPrefix(cmd, prefix) {
  24. if code == 0 {
  25. return "ok", 0
  26. }
  27. return "", code
  28. }
  29. }
  30. return "ok", 0 // default success
  31. }
  32. func TestValidateRejectsUnknownKind(t *testing.T) {
  33. err := Validate(Op{Kind: "rm_rf", Args: map[string]string{}})
  34. if err == nil {
  35. t.Fatal("unknown kind should be rejected")
  36. }
  37. }
  38. func TestValidateRejectsShellMetachars(t *testing.T) {
  39. err := Validate(Op{
  40. Kind: "uci_set",
  41. Args: map[string]string{
  42. "config": "dhcp",
  43. "section": "@dnsmasq[0]",
  44. "option": "server",
  45. "value": "1.1.1.1; rm -rf /", // shell injection
  46. },
  47. })
  48. if err == nil {
  49. t.Fatal("shell metachars in value should be rejected")
  50. }
  51. }
  52. func TestValidateAcceptsValidOp(t *testing.T) {
  53. err := Validate(Op{
  54. Kind: "uci_set",
  55. Args: map[string]string{
  56. "config": "dhcp",
  57. "section": "@dnsmasq[0]",
  58. "option": "server",
  59. "value": "1.1.1.1",
  60. },
  61. })
  62. if err != nil {
  63. t.Fatalf("valid op rejected: %v", err)
  64. }
  65. }
  66. func TestValidateRejectsMissingArg(t *testing.T) {
  67. err := Validate(Op{
  68. Kind: "uci_set",
  69. Args: map[string]string{"config": "dhcp", "section": "foo", "option": "bar"},
  70. // missing "value"
  71. })
  72. if err == nil {
  73. t.Fatal("missing arg should be rejected")
  74. }
  75. }
  76. func TestValidateServiceAction(t *testing.T) {
  77. // Acciones válidas (start/stop añadidos en Fase 17.1 para módulos que
  78. // escuchan en puerto, p. ej. parar AdGuard antes de reconfigurarlo).
  79. for _, action := range []string{"restart", "reload", "enable", "disable", "start", "stop"} {
  80. if err := Validate(Op{Kind: "service", Args: map[string]string{"name": "dnsmasq", "action": action}}); err != nil {
  81. t.Fatalf("action %q should be accepted: %v", action, err)
  82. }
  83. }
  84. // Acción inválida
  85. if err := Validate(Op{Kind: "service", Args: map[string]string{"name": "dnsmasq", "action": "restart;;rm"}}); err == nil {
  86. t.Fatal("action with shell metachars should be rejected")
  87. }
  88. }
  89. // --- Fase 17.2: uci_add + secciones @[-1] ---
  90. func TestValidateUciAdd(t *testing.T) {
  91. valid := Op{Kind: "uci_add", Args: map[string]string{"config": "wireless", "type": "wifi-iface"}}
  92. if err := Validate(valid); err != nil {
  93. t.Fatalf("uci_add válido rechazado: %v", err)
  94. }
  95. // type con shell metachars → rechazado
  96. bad := Op{Kind: "uci_add", Args: map[string]string{"config": "wireless", "type": "wifi-iface; rm -rf /"}}
  97. if err := Validate(bad); err == nil {
  98. t.Fatal("uci_add type con metachars debería rechazarse")
  99. }
  100. // config inválido
  101. bad2 := Op{Kind: "uci_add", Args: map[string]string{"config": "wireless;", "type": "wifi-iface"}}
  102. if err := Validate(bad2); err == nil {
  103. t.Fatal("uci_add config inválido debería rechazarse")
  104. }
  105. // uci_delete_section válido (sección nombrada y @referencia)
  106. del := Op{Kind: "uci_delete_section", Args: map[string]string{"config": "network", "section": "guest"}}
  107. if err := Validate(del); err != nil {
  108. t.Fatalf("uci_delete_section válido rechazado: %v", err)
  109. }
  110. del2 := Op{Kind: "uci_delete_section", Args: map[string]string{"config": "firewall", "section": "@zone[2]"}}
  111. if err := Validate(del2); err != nil {
  112. t.Fatalf("uci_delete_section @referencia rechazado: %v", err)
  113. }
  114. }
  115. func TestValidateSectionLastIndex(t *testing.T) {
  116. // @wifi-iface[-1] (última sección) válido para uci_set tras uci_add
  117. op := Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "ssid", "value": "NetPulse-Guest"}}
  118. if err := Validate(op); err != nil {
  119. t.Fatalf("@wifi-iface[-1] debería aceptarse: %v", err)
  120. }
  121. // índice numérico sigue válido
  122. op2 := Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[0]", "option": "ssid", "value": "Main"}}
  123. if err := Validate(op2); err != nil {
  124. t.Fatalf("@wifi-iface[0] debería aceptarse: %v", err)
  125. }
  126. // negativo distinto de -1 → rechazado
  127. op3 := Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-2]", "option": "ssid", "value": "X"}}
  128. if err := Validate(op3); err == nil {
  129. t.Fatal("@wifi-iface[-2] debería rechazarse (solo -1)")
  130. }
  131. }
  132. // TestValidateSectionWithDigits (17.4): las secciones UCI de interfaces reales
  133. // llevan dígitos (eth1, wlan0, br-lan) — el nombre de sección debe aceptarlos.
  134. func TestValidateSectionWithDigits(t *testing.T) {
  135. for _, sec := range []string{"eth1", "wlan0", "br-lan", "wan6"} {
  136. op := Op{Kind: "uci_set", Args: map[string]string{"config": "sqm", "section": sec, "option": "enabled", "value": "1"}}
  137. if err := Validate(op); err != nil {
  138. t.Errorf("section %q debería aceptarse (interfaz UCI): %v", sec, err)
  139. }
  140. }
  141. // @tipo[-1] con tipo que lleva dígito
  142. op := Op{Kind: "uci_set", Args: map[string]string{"config": "sqm", "section": "@queue[-1]", "option": "interface", "value": "eth1"}}
  143. if err := Validate(op); err != nil {
  144. t.Errorf("@queue[-1] debería aceptarse: %v", err)
  145. }
  146. }
  147. // --- Fase 17.1: validación de los nuevos Kinds ---
  148. func TestValidateDownloadURLAllowlist(t *testing.T) {
  149. // URL oficial válida
  150. valid := Op{Kind: "download", Args: map[string]string{
  151. "url": "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
  152. "dest": "/tmp/AdGuardHome.tar.gz",
  153. }}
  154. if err := Validate(valid); err != nil {
  155. t.Fatalf("valid download URL rejected: %v", err)
  156. }
  157. // URL maliciosa (dominio distinto) → rechazo
  158. bad := Op{Kind: "download", Args: map[string]string{
  159. "url": "https://evil.example.com/AdGuardHome.tar.gz",
  160. "dest": "/tmp/x.tar.gz",
  161. }}
  162. if err := Validate(bad); err == nil {
  163. t.Fatal("non-allowlisted download URL should be rejected")
  164. }
  165. // URL oficial pero path fuera de allowlist (otro repo) → rechazo
  166. bad2 := Op{Kind: "download", Args: map[string]string{
  167. "url": "https://github.com/evil/repo/releases/download/v1.0/payload",
  168. "dest": "/tmp/x.tar.gz",
  169. }}
  170. if err := Validate(bad2); err == nil {
  171. t.Fatal("non-AdguardTeam github path should be rejected")
  172. }
  173. }
  174. func TestValidateFilePathAllowlist(t *testing.T) {
  175. for _, p := range []string{"/etc/AdGuardHome.yaml", "/tmp/agh.tar.gz", "/usr/bin/AdGuardHome", "/usr/lib/AdGuardHome/dns"} {
  176. if err := Validate(Op{Kind: "write_file", Args: map[string]string{"path": p, "content_b64": "Zm9v"}}); err != nil {
  177. t.Errorf("path %q should be accepted: %v", p, err)
  178. }
  179. }
  180. for _, p := range []string{"/etc/passwd;rm", "/etc/../etc/shadow", "/root/.ssh/id_rsa", "/var/log/x", "/home/nacho/x"} {
  181. if err := Validate(Op{Kind: "write_file", Args: map[string]string{"path": p, "content_b64": "Zm9v"}}); err == nil {
  182. t.Errorf("path %q should be rejected", p)
  183. }
  184. }
  185. }
  186. func TestValidateChmodMode(t *testing.T) {
  187. for _, m := range []string{"755", "644", "600", "0755", "1777"} {
  188. if err := Validate(Op{Kind: "chmod", Args: map[string]string{"mode": m, "path": "/usr/bin/AdGuardHome"}}); err != nil {
  189. t.Errorf("mode %q should be accepted: %v", m, err)
  190. }
  191. }
  192. for _, m := range []string{"999", "rwxr-xr-x", "755;rm", "abc"} {
  193. if err := Validate(Op{Kind: "chmod", Args: map[string]string{"mode": m, "path": "/usr/bin/AdGuardHome"}}); err == nil {
  194. t.Errorf("mode %q should be rejected", m)
  195. }
  196. }
  197. }
  198. func TestValidateApkInstall(t *testing.T) {
  199. if err := Validate(Op{Kind: "apk_install", Args: map[string]string{"package": "adguard-home"}}); err != nil {
  200. t.Fatalf("valid apk_install rejected: %v", err)
  201. }
  202. if err := Validate(Op{Kind: "apk_install", Args: map[string]string{"package": "adguard-home;rm"}}); err == nil {
  203. t.Fatal("apk_install with shell metachars should be rejected")
  204. }
  205. }
  206. func TestValidateExtractTarball(t *testing.T) {
  207. if err := Validate(Op{Kind: "extract_tarball", Args: map[string]string{"src": "/tmp/agh.tar.gz", "dest": "/tmp/agh"}}); err != nil {
  208. t.Fatalf("valid extract_tarball rejected: %v", err)
  209. }
  210. // dest fuera de allowlist
  211. if err := Validate(Op{Kind: "extract_tarball", Args: map[string]string{"src": "/tmp/agh.tar.gz", "dest": "/home/nacho"}}); err == nil {
  212. t.Fatal("extract_tarball dest outside allowlist should be rejected")
  213. }
  214. }
  215. func TestValidateMv(t *testing.T) {
  216. if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/agh-x/AdGuardHome", "dest": "/usr/bin/AdGuardHome"}}); err != nil {
  217. t.Fatalf("valid mv rejected: %v", err)
  218. }
  219. // dest fuera de allowlist
  220. if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/x", "dest": "/etc/passwd;rm"}}); err == nil {
  221. t.Fatal("mv with malicious dest should be rejected")
  222. }
  223. // src con traversal
  224. if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/../etc/shadow", "dest": "/tmp/x"}}); err == nil {
  225. t.Fatal("mv src with traversal should be rejected")
  226. }
  227. }
  228. // TestWriteFileCreatesParentDir: write_file debe crear /etc/AdGuardHome/ si
  229. // no existe (MkdirAll del dir padre).
  230. func TestWriteFileCreatesParentDir(t *testing.T) {
  231. parent := "/tmp/netpulse-mkdir-test-" + t.Name()
  232. defer os.RemoveAll(parent)
  233. path := parent + "/AdGuardHome/AdGuardHome.yaml"
  234. spec := allowlist["write_file"]
  235. if code := spec.exec(nil, map[string]string{"path": path, "content_b64": "Zm9v"}); code != 0 {
  236. t.Fatalf("write_file exec failed: exit %d", code)
  237. }
  238. if _, err := os.ReadFile(path); err != nil {
  239. t.Fatalf("file not written (dir padre no creado?): %v", err)
  240. }
  241. }
  242. // TestWriteFileExec verifica el exec de write_file escribe el contenido real.
  243. // Usa un tmpdir (no fakeRunner) porque exec usa os.WriteFile directamente.
  244. func TestWriteFileExec(t *testing.T) {
  245. // Invoco exec directamente con un path /tmp real y limpio después.
  246. // El path debe casar con reFilePath (^/tmp/...).
  247. path := "/tmp/netpulse-exec-test-" + t.Name()
  248. defer os.Remove(path)
  249. content := "bind_port: 3000\n"
  250. b64 := "YmluZF9wb3J0OiAzMDAwCg==" // base64 de content
  251. spec := allowlist["write_file"]
  252. if spec.exec == nil {
  253. t.Fatal("write_file has no exec")
  254. }
  255. if code := spec.exec(nil, map[string]string{"path": path, "content_b64": b64}); code != 0 {
  256. t.Fatalf("write_file exec failed: exit %d", code)
  257. }
  258. data, err := os.ReadFile(path)
  259. if err != nil {
  260. t.Fatalf("file not written: %v", err)
  261. }
  262. if string(data) != content {
  263. t.Fatalf("content mismatch: got %q want %q", data, content)
  264. }
  265. }
  266. // TestWriteFileRejectsTraversal: path con .. debe ser rechazado por exec
  267. // (defense in depth: aunque el regex lo pille, exec lo revalida).
  268. func TestWriteFileRejectsTraversal(t *testing.T) {
  269. spec := allowlist["write_file"]
  270. // "/tmp/../../../etc/x" no casa el regex → Validate lo rechaza.
  271. // Pero comprobemos exec con un path que SÍ casa el regex pero tiene ..:
  272. // filepath.Clean("/tmp/a/../b") = "/tmp/b" (válido). Para forzar el
  273. // rechazo en exec, pasamos un path que Clean cambie (no debería casar
  274. // el regex, pero si alguien lo bypassa, exec lo para).
  275. // Como no podemos bypassar el regex desde Validate, este test documenta
  276. // la defensa: si path != Clean(path), exit 1.
  277. path := "/tmp/a/./b"
  278. if code := spec.exec(nil, map[string]string{"path": path, "content_b64": "Zm9v"}); code == 0 {
  279. t.Fatal("exec should reject path where Clean(path) != path")
  280. }
  281. }
  282. // TestApplyPlanConDownloadWriteChmod: plan que mezcla los nuevos Kinds con
  283. // los existentes, verificando que Apply despacha exec vs build correctamente.
  284. func TestApplyPlanConDownloadWriteChmod(t *testing.T) {
  285. fr := newFakeRunner()
  286. // download/extract/chmod via fakeRunner (build path). write_file via exec
  287. // (escribe de verdad en /tmp). service via fakeRunner.
  288. tmpFile := "/tmp/netpulse-plan-test-" + t.Name()
  289. defer os.Remove(tmpFile)
  290. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  291. ops := []Op{
  292. {Kind: "download", Args: map[string]string{
  293. "url": "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
  294. "dest": tmpFile,
  295. }, Desc: "Download AdGuard tarball"},
  296. {Kind: "write_file", Args: map[string]string{
  297. "path": "/tmp/netpulse-plan-test-cfg.yaml",
  298. "content_b64": "YmluZF9wb3J0OiAzMDAwCg==",
  299. }, Desc: "Write AdGuard config"},
  300. {Kind: "chmod", Args: map[string]string{"mode": "755", "path": tmpFile}, Desc: "Make executable"},
  301. {Kind: "service", Args: map[string]string{"name": "adguardhome", "action": "start"}, Desc: "Start AdGuard"},
  302. }
  303. defer os.Remove("/tmp/netpulse-plan-test-cfg.yaml")
  304. res := e.Apply(ops)
  305. if res.Status != "applied" {
  306. t.Fatalf("expected applied, got %s: %s", res.Status, res.Error)
  307. }
  308. // Verifica que los comandos build se ejecutaron (download, chmod, service).
  309. got := strings.Join(fr.calls, "\n")
  310. for _, want := range []string{"uclient-fetch https:", "chmod 755", "/etc/init.d/adguardhome start"} {
  311. if !strings.Contains(got, want) {
  312. t.Errorf("missing call %q in:\n%s", want, got)
  313. }
  314. }
  315. // Y que write_file escribió el fichero config.
  316. if _, err := os.ReadFile("/tmp/netpulse-plan-test-cfg.yaml"); err != nil {
  317. t.Errorf("config file not written: %v", err)
  318. }
  319. }
  320. func TestApplySuccess(t *testing.T) {
  321. fr := newFakeRunner()
  322. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  323. ops := []Op{
  324. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}, Desc: "Set DNS upstream"},
  325. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit dhcp"},
  326. }
  327. res := e.Apply(ops)
  328. if res.Status != "applied" {
  329. t.Fatalf("expected applied, got %s (error=%s)", res.Status, res.Error)
  330. }
  331. if res.Snapshot != "dhcp" {
  332. t.Fatalf("snapshot should list dhcp, got %q", res.Snapshot)
  333. }
  334. // Verificar que se hizo snapshot (uci export dhcp) antes de ejecutar
  335. foundSnap := false
  336. for _, c := range fr.calls {
  337. if strings.Contains(c, "uci export dhcp") {
  338. foundSnap = true
  339. break
  340. }
  341. }
  342. if !foundSnap {
  343. t.Fatal("should have done uci export for snapshot")
  344. }
  345. // Verificar commit
  346. foundCommit := false
  347. for _, c := range fr.calls {
  348. if c == "uci commit dhcp" {
  349. foundCommit = true
  350. break
  351. }
  352. }
  353. if !foundCommit {
  354. t.Fatal("should have committed dhcp")
  355. }
  356. }
  357. func TestApplyFailingOpReverts(t *testing.T) {
  358. fr := newFakeRunner()
  359. // Hacer que el segundo op (commit) falle
  360. fr.responses["uci commit dhcp"] = 1
  361. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  362. ops := []Op{
  363. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}, Desc: "Set DNS"},
  364. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit"},
  365. }
  366. res := e.Apply(ops)
  367. if res.Status != "failed" {
  368. t.Fatalf("expected failed, got %s", res.Status)
  369. }
  370. // Verificar que se hizo revert de los staged changes
  371. foundRevert := false
  372. for _, c := range fr.calls {
  373. if strings.Contains(c, "uci revert dhcp") {
  374. foundRevert = true
  375. break
  376. }
  377. }
  378. if !foundRevert {
  379. t.Fatal("should have reverted staged changes on failure")
  380. }
  381. }
  382. func TestApplyHealthcheckFailRollsBack(t *testing.T) {
  383. fr := newFakeRunner()
  384. // Hacer que el ping falle (healthcheck)
  385. fr.responses["ping"] = 1
  386. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  387. ops := []Op{
  388. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "8.8.8.8"}, Desc: "Change DNS"},
  389. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit"},
  390. }
  391. res := e.Apply(ops)
  392. if res.Status != "rolled_back" {
  393. t.Fatalf("expected rolled_back, got %s (error=%s)", res.Status, res.Error)
  394. }
  395. if res.Error != "healthcheck_failed" {
  396. t.Fatalf("error should be healthcheck_failed, got %s", res.Error)
  397. }
  398. // Verificar que se restauró el snapshot (uci import)
  399. foundImport := false
  400. for _, c := range fr.calls {
  401. if strings.Contains(c, "uci import") {
  402. foundImport = true
  403. break
  404. }
  405. }
  406. if !foundImport {
  407. t.Fatal("should have imported snapshot on rollback")
  408. }
  409. }
  410. // TestValidateWgCheck (10.3): el healthcheck del túnel valida interface y
  411. // rechaza metachars shell.
  412. func TestValidateWgCheck(t *testing.T) {
  413. if err := Validate(Op{Kind: "wg_check", Args: map[string]string{"interface": "wg0"}}); err != nil {
  414. t.Fatalf("valid wg_check rejected: %v", err)
  415. }
  416. if err := Validate(Op{Kind: "wg_check", Args: map[string]string{"interface": "wg0; rm -rf /"}}); err == nil {
  417. t.Fatal("wg_check with shell metachars should be rejected")
  418. }
  419. if err := Validate(Op{Kind: "wg_check", Args: map[string]string{}}); err == nil {
  420. t.Fatal("wg_check missing interface should be rejected")
  421. }
  422. }
  423. // TestApplyWgCheckFailRollsBack (10.3): si `wg show wg0` falla tras el apply,
  424. // el executor restaura los snapshots y relanza la red (rollback real), en vez
  425. // de devolver un simple "failed".
  426. func TestApplyWgCheckFailRollsBack(t *testing.T) {
  427. fr := newFakeRunner()
  428. fr.responses["wg show wg0"] = 1 // el túnel no levantó tras el reload
  429. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  430. ops := []Op{
  431. {Kind: "uci_set_named", Args: map[string]string{"config": "network", "section": "wg0", "type": "interface"}, Desc: "Create interface"},
  432. {Kind: "uci_set", Args: map[string]string{"config": "network", "section": "wg0", "option": "proto", "value": "wireguard"}, Desc: "Set proto"},
  433. {Kind: "uci_commit", Args: map[string]string{"config": "network"}, Desc: "Commit"},
  434. {Kind: "service", Args: map[string]string{"name": "network", "action": "reload"}, Desc: "Reload network"},
  435. {Kind: "wg_check", Args: map[string]string{"interface": "wg0"}, Desc: "Check tunnel up"},
  436. }
  437. res := e.Apply(ops)
  438. if res.Status != "rolled_back" {
  439. t.Fatalf("expected rolled_back, got %s (error=%s)", res.Status, res.Error)
  440. }
  441. if res.Error != "wg_check_failed" {
  442. t.Fatalf("error should be wg_check_failed, got %s", res.Error)
  443. }
  444. got := strings.Join(fr.calls, "\n")
  445. if !strings.Contains(got, "uci import") {
  446. t.Error("should have restored the snapshot (uci import) on wg_check failure")
  447. }
  448. if !strings.Contains(got, "/etc/init.d/network reload") {
  449. t.Error("should have reloaded network after restoring the snapshot")
  450. }
  451. }
  452. func TestAffectedConfigsDedup(t *testing.T) {
  453. ops := []Op{
  454. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s1", "option": "o1", "value": "v1"}},
  455. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s2", "option": "o2", "value": "v2"}},
  456. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}},
  457. {Kind: "service", Args: map[string]string{"name": "dnsmasq", "action": "restart"}},
  458. }
  459. cfgs := affectedConfigs(ops)
  460. if len(cfgs) != 1 || cfgs[0] != "dhcp" {
  461. t.Fatalf("expected [dhcp], got %v", cfgs)
  462. }
  463. }
  464. func TestMarshalUnmarshalOps(t *testing.T) {
  465. ops := []Op{
  466. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s", "option": "o", "value": "1.2.3.4"}, Desc: "test"},
  467. }
  468. data, err := MarshalOps(ops)
  469. if err != nil {
  470. t.Fatal(err)
  471. }
  472. got, err := UnmarshalOps(data)
  473. if err != nil {
  474. t.Fatal(err)
  475. }
  476. if len(got) != 1 || got[0].Kind != "uci_set" || got[0].Args["value"] != "1.2.3.4" {
  477. t.Fatalf("roundtrip failed: %+v", got)
  478. }
  479. }
  480. // TestValidateTcpCheck: args host/port validados por regex.
  481. func TestValidateTcpCheck(t *testing.T) {
  482. cases := []struct {
  483. name, host, port string
  484. ok bool
  485. }{
  486. {"ipv4", "127.0.0.1", "3000", true},
  487. {"localhost", "localhost", "53", true},
  488. {"lan-ip", "192.168.1.1", "80", true},
  489. {"port-zero", "127.0.0.1", "0", false},
  490. {"port-too-high", "127.0.0.1", "65536", false},
  491. {"port-leading-zero", "127.0.0.1", "03000", false},
  492. {"host-space", "127.0.0.1 ", "3000", false},
  493. {"host-shell-chars", "127.0.0.1; rm -rf /", "3000", false},
  494. {"missing-port", "127.0.0.1", "", false},
  495. }
  496. for _, c := range cases {
  497. op := Op{Kind: "tcp_check", Args: map[string]string{"host": c.host, "port": c.port}}
  498. err := Validate(op)
  499. if (err == nil) != c.ok {
  500. t.Errorf("%s: esperaba ok=%v, got err=%v", c.name, c.ok, err)
  501. }
  502. }
  503. }
  504. // TestTcpCheckExecOpenThenClosed: el exec de tcp_check devuelve 0 si el
  505. // puerto está abierto y 1 si está cerrado (healthcheck real de servicio).
  506. func TestTcpCheckExecOpenThenClosed(t *testing.T) {
  507. // Acortar el budget para que el caso "cerrado" no tarde 10 s en el test.
  508. prev := tcpCheckBudget
  509. tcpCheckBudget = 300 * time.Millisecond
  510. defer func() { tcpCheckBudget = prev }()
  511. ln, err := net.Listen("tcp", "127.0.0.1:0")
  512. if err != nil {
  513. t.Fatalf("no pude abrir listener: %v", err)
  514. }
  515. port := strconv.Itoa(ln.Addr().(*net.TCPAddr).Port)
  516. spec, ok := allowlist["tcp_check"]
  517. if !ok {
  518. t.Fatal("tcp_check no está en allowlist")
  519. }
  520. // Puerto abierto → 0
  521. if rc := spec.exec(nil, map[string]string{"host": "127.0.0.1", "port": port}); rc != 0 {
  522. t.Errorf("puerto abierto: esperaba 0, got %d", rc)
  523. }
  524. // Cerrar el listener → puerto cerrado → 1 (tras exhausting el budget corto)
  525. ln.Close()
  526. if rc := spec.exec(nil, map[string]string{"host": "127.0.0.1", "port": port}); rc != 1 {
  527. t.Errorf("puerto cerrado: esperaba 1, got %d", rc)
  528. }
  529. }