executor_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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 TestValidateDawnCheck(t *testing.T) {
  175. if err := Validate(Op{Kind: "dawn_check", Args: map[string]string{}}); err != nil {
  176. t.Fatalf("dawn_check debería validar: %v", err)
  177. }
  178. }
  179. func TestValidateWifiReload(t *testing.T) {
  180. if err := Validate(Op{Kind: "wifi_reload", Args: map[string]string{}}); err != nil {
  181. t.Fatalf("wifi_reload debería validar: %v", err)
  182. }
  183. }
  184. func TestValidateFilePathAllowlist(t *testing.T) {
  185. for _, p := range []string{"/etc/AdGuardHome.yaml", "/tmp/agh.tar.gz", "/usr/bin/AdGuardHome", "/usr/lib/AdGuardHome/dns"} {
  186. if err := Validate(Op{Kind: "write_file", Args: map[string]string{"path": p, "content_b64": "Zm9v"}}); err != nil {
  187. t.Errorf("path %q should be accepted: %v", p, err)
  188. }
  189. }
  190. for _, p := range []string{"/etc/passwd;rm", "/etc/../etc/shadow", "/root/.ssh/id_rsa", "/var/log/x", "/home/nacho/x"} {
  191. if err := Validate(Op{Kind: "write_file", Args: map[string]string{"path": p, "content_b64": "Zm9v"}}); err == nil {
  192. t.Errorf("path %q should be rejected", p)
  193. }
  194. }
  195. }
  196. func TestValidateChmodMode(t *testing.T) {
  197. for _, m := range []string{"755", "644", "600", "0755", "1777"} {
  198. if err := Validate(Op{Kind: "chmod", Args: map[string]string{"mode": m, "path": "/usr/bin/AdGuardHome"}}); err != nil {
  199. t.Errorf("mode %q should be accepted: %v", m, err)
  200. }
  201. }
  202. for _, m := range []string{"999", "rwxr-xr-x", "755;rm", "abc"} {
  203. if err := Validate(Op{Kind: "chmod", Args: map[string]string{"mode": m, "path": "/usr/bin/AdGuardHome"}}); err == nil {
  204. t.Errorf("mode %q should be rejected", m)
  205. }
  206. }
  207. }
  208. func TestValidateApkInstall(t *testing.T) {
  209. if err := Validate(Op{Kind: "apk_install", Args: map[string]string{"package": "adguard-home"}}); err != nil {
  210. t.Fatalf("valid apk_install rejected: %v", err)
  211. }
  212. if err := Validate(Op{Kind: "apk_install", Args: map[string]string{"package": "adguard-home;rm"}}); err == nil {
  213. t.Fatal("apk_install with shell metachars should be rejected")
  214. }
  215. }
  216. func TestValidateExtractTarball(t *testing.T) {
  217. if err := Validate(Op{Kind: "extract_tarball", Args: map[string]string{"src": "/tmp/agh.tar.gz", "dest": "/tmp/agh"}}); err != nil {
  218. t.Fatalf("valid extract_tarball rejected: %v", err)
  219. }
  220. // dest fuera de allowlist
  221. if err := Validate(Op{Kind: "extract_tarball", Args: map[string]string{"src": "/tmp/agh.tar.gz", "dest": "/home/nacho"}}); err == nil {
  222. t.Fatal("extract_tarball dest outside allowlist should be rejected")
  223. }
  224. }
  225. func TestValidateMv(t *testing.T) {
  226. if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/agh-x/AdGuardHome", "dest": "/usr/bin/AdGuardHome"}}); err != nil {
  227. t.Fatalf("valid mv rejected: %v", err)
  228. }
  229. // dest fuera de allowlist
  230. if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/x", "dest": "/etc/passwd;rm"}}); err == nil {
  231. t.Fatal("mv with malicious dest should be rejected")
  232. }
  233. // src con traversal
  234. if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/../etc/shadow", "dest": "/tmp/x"}}); err == nil {
  235. t.Fatal("mv src with traversal should be rejected")
  236. }
  237. }
  238. // TestWriteFileCreatesParentDir: write_file debe crear /etc/AdGuardHome/ si
  239. // no existe (MkdirAll del dir padre).
  240. func TestWriteFileCreatesParentDir(t *testing.T) {
  241. parent := "/tmp/netpulse-mkdir-test-" + t.Name()
  242. defer os.RemoveAll(parent)
  243. path := parent + "/AdGuardHome/AdGuardHome.yaml"
  244. spec := allowlist["write_file"]
  245. if code := spec.exec(nil, map[string]string{"path": path, "content_b64": "Zm9v"}); code != 0 {
  246. t.Fatalf("write_file exec failed: exit %d", code)
  247. }
  248. if _, err := os.ReadFile(path); err != nil {
  249. t.Fatalf("file not written (dir padre no creado?): %v", err)
  250. }
  251. }
  252. // TestWriteFileExec verifica el exec de write_file escribe el contenido real.
  253. // Usa un tmpdir (no fakeRunner) porque exec usa os.WriteFile directamente.
  254. func TestWriteFileExec(t *testing.T) {
  255. // Invoco exec directamente con un path /tmp real y limpio después.
  256. // El path debe casar con reFilePath (^/tmp/...).
  257. path := "/tmp/netpulse-exec-test-" + t.Name()
  258. defer os.Remove(path)
  259. content := "bind_port: 3000\n"
  260. b64 := "YmluZF9wb3J0OiAzMDAwCg==" // base64 de content
  261. spec := allowlist["write_file"]
  262. if spec.exec == nil {
  263. t.Fatal("write_file has no exec")
  264. }
  265. if code := spec.exec(nil, map[string]string{"path": path, "content_b64": b64}); code != 0 {
  266. t.Fatalf("write_file exec failed: exit %d", code)
  267. }
  268. data, err := os.ReadFile(path)
  269. if err != nil {
  270. t.Fatalf("file not written: %v", err)
  271. }
  272. if string(data) != content {
  273. t.Fatalf("content mismatch: got %q want %q", data, content)
  274. }
  275. }
  276. // TestWriteFileRejectsTraversal: path con .. debe ser rechazado por exec
  277. // (defense in depth: aunque el regex lo pille, exec lo revalida).
  278. func TestWriteFileRejectsTraversal(t *testing.T) {
  279. spec := allowlist["write_file"]
  280. // "/tmp/../../../etc/x" no casa el regex → Validate lo rechaza.
  281. // Pero comprobemos exec con un path que SÍ casa el regex pero tiene ..:
  282. // filepath.Clean("/tmp/a/../b") = "/tmp/b" (válido). Para forzar el
  283. // rechazo en exec, pasamos un path que Clean cambie (no debería casar
  284. // el regex, pero si alguien lo bypassa, exec lo para).
  285. // Como no podemos bypassar el regex desde Validate, este test documenta
  286. // la defensa: si path != Clean(path), exit 1.
  287. path := "/tmp/a/./b"
  288. if code := spec.exec(nil, map[string]string{"path": path, "content_b64": "Zm9v"}); code == 0 {
  289. t.Fatal("exec should reject path where Clean(path) != path")
  290. }
  291. }
  292. // TestApplyPlanConDownloadWriteChmod: plan que mezcla los nuevos Kinds con
  293. // los existentes, verificando que Apply despacha exec vs build correctamente.
  294. func TestApplyPlanConDownloadWriteChmod(t *testing.T) {
  295. fr := newFakeRunner()
  296. // download/extract/chmod via fakeRunner (build path). write_file via exec
  297. // (escribe de verdad en /tmp). service via fakeRunner.
  298. tmpFile := "/tmp/netpulse-plan-test-" + t.Name()
  299. defer os.Remove(tmpFile)
  300. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  301. ops := []Op{
  302. {Kind: "download", Args: map[string]string{
  303. "url": "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
  304. "dest": tmpFile,
  305. }, Desc: "Download AdGuard tarball"},
  306. {Kind: "write_file", Args: map[string]string{
  307. "path": "/tmp/netpulse-plan-test-cfg.yaml",
  308. "content_b64": "YmluZF9wb3J0OiAzMDAwCg==",
  309. }, Desc: "Write AdGuard config"},
  310. {Kind: "chmod", Args: map[string]string{"mode": "755", "path": tmpFile}, Desc: "Make executable"},
  311. {Kind: "service", Args: map[string]string{"name": "adguardhome", "action": "start"}, Desc: "Start AdGuard"},
  312. }
  313. defer os.Remove("/tmp/netpulse-plan-test-cfg.yaml")
  314. res := e.Apply(ops)
  315. if res.Status != "applied" {
  316. t.Fatalf("expected applied, got %s: %s", res.Status, res.Error)
  317. }
  318. // Verifica que los comandos build se ejecutaron (download, chmod, service).
  319. got := strings.Join(fr.calls, "\n")
  320. for _, want := range []string{"uclient-fetch https:", "chmod 755", "/etc/init.d/adguardhome start"} {
  321. if !strings.Contains(got, want) {
  322. t.Errorf("missing call %q in:\n%s", want, got)
  323. }
  324. }
  325. // Y que write_file escribió el fichero config.
  326. if _, err := os.ReadFile("/tmp/netpulse-plan-test-cfg.yaml"); err != nil {
  327. t.Errorf("config file not written: %v", err)
  328. }
  329. }
  330. func TestApplySuccess(t *testing.T) {
  331. fr := newFakeRunner()
  332. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  333. ops := []Op{
  334. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}, Desc: "Set DNS upstream"},
  335. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit dhcp"},
  336. }
  337. res := e.Apply(ops)
  338. if res.Status != "applied" {
  339. t.Fatalf("expected applied, got %s (error=%s)", res.Status, res.Error)
  340. }
  341. if res.Snapshot != "dhcp" {
  342. t.Fatalf("snapshot should list dhcp, got %q", res.Snapshot)
  343. }
  344. // Verificar que se hizo snapshot (uci export dhcp) antes de ejecutar
  345. foundSnap := false
  346. for _, c := range fr.calls {
  347. if strings.Contains(c, "uci export dhcp") {
  348. foundSnap = true
  349. break
  350. }
  351. }
  352. if !foundSnap {
  353. t.Fatal("should have done uci export for snapshot")
  354. }
  355. // Verificar commit
  356. foundCommit := false
  357. for _, c := range fr.calls {
  358. if c == "uci commit dhcp" {
  359. foundCommit = true
  360. break
  361. }
  362. }
  363. if !foundCommit {
  364. t.Fatal("should have committed dhcp")
  365. }
  366. }
  367. func TestApplyFailingOpReverts(t *testing.T) {
  368. fr := newFakeRunner()
  369. // Hacer que el segundo op (commit) falle
  370. fr.responses["uci commit dhcp"] = 1
  371. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  372. ops := []Op{
  373. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}, Desc: "Set DNS"},
  374. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit"},
  375. }
  376. res := e.Apply(ops)
  377. if res.Status != "failed" {
  378. t.Fatalf("expected failed, got %s", res.Status)
  379. }
  380. // Verificar que se hizo revert de los staged changes
  381. foundRevert := false
  382. for _, c := range fr.calls {
  383. if strings.Contains(c, "uci revert dhcp") {
  384. foundRevert = true
  385. break
  386. }
  387. }
  388. if !foundRevert {
  389. t.Fatal("should have reverted staged changes on failure")
  390. }
  391. }
  392. func TestApplyHealthcheckFailRollsBack(t *testing.T) {
  393. fr := newFakeRunner()
  394. // Hacer que el ping falle (healthcheck)
  395. fr.responses["ping"] = 1
  396. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  397. ops := []Op{
  398. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "8.8.8.8"}, Desc: "Change DNS"},
  399. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit"},
  400. }
  401. res := e.Apply(ops)
  402. if res.Status != "rolled_back" {
  403. t.Fatalf("expected rolled_back, got %s (error=%s)", res.Status, res.Error)
  404. }
  405. if res.Error != "healthcheck_failed" {
  406. t.Fatalf("error should be healthcheck_failed, got %s", res.Error)
  407. }
  408. // Verificar que se restauró el snapshot (uci import)
  409. foundImport := false
  410. for _, c := range fr.calls {
  411. if strings.Contains(c, "uci import") {
  412. foundImport = true
  413. break
  414. }
  415. }
  416. if !foundImport {
  417. t.Fatal("should have imported snapshot on rollback")
  418. }
  419. }
  420. // TestValidateWgCheck (10.3): el healthcheck del túnel valida interface y
  421. // rechaza metachars shell.
  422. func TestValidateWgCheck(t *testing.T) {
  423. if err := Validate(Op{Kind: "wg_check", Args: map[string]string{"interface": "wg0"}}); err != nil {
  424. t.Fatalf("valid wg_check rejected: %v", err)
  425. }
  426. if err := Validate(Op{Kind: "wg_check", Args: map[string]string{"interface": "wg0; rm -rf /"}}); err == nil {
  427. t.Fatal("wg_check with shell metachars should be rejected")
  428. }
  429. if err := Validate(Op{Kind: "wg_check", Args: map[string]string{}}); err == nil {
  430. t.Fatal("wg_check missing interface should be rejected")
  431. }
  432. }
  433. // TestApplyWgCheckFailRollsBack (10.3): si `wg show wg0` falla tras el apply,
  434. // el executor restaura los snapshots y relanza la red (rollback real), en vez
  435. // de devolver un simple "failed".
  436. func TestApplyWgCheckFailRollsBack(t *testing.T) {
  437. fr := newFakeRunner()
  438. fr.responses["wg show wg0"] = 1 // el túnel no levantó tras el reload
  439. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  440. ops := []Op{
  441. {Kind: "uci_set_named", Args: map[string]string{"config": "network", "section": "wg0", "type": "interface"}, Desc: "Create interface"},
  442. {Kind: "uci_set", Args: map[string]string{"config": "network", "section": "wg0", "option": "proto", "value": "wireguard"}, Desc: "Set proto"},
  443. {Kind: "uci_commit", Args: map[string]string{"config": "network"}, Desc: "Commit"},
  444. {Kind: "service", Args: map[string]string{"name": "network", "action": "reload"}, Desc: "Reload network"},
  445. {Kind: "wg_check", Args: map[string]string{"interface": "wg0"}, Desc: "Check tunnel up"},
  446. }
  447. res := e.Apply(ops)
  448. if res.Status != "rolled_back" {
  449. t.Fatalf("expected rolled_back, got %s (error=%s)", res.Status, res.Error)
  450. }
  451. if res.Error != "wg_check_failed" {
  452. t.Fatalf("error should be wg_check_failed, got %s", res.Error)
  453. }
  454. got := strings.Join(fr.calls, "\n")
  455. if !strings.Contains(got, "uci import") {
  456. t.Error("should have restored the snapshot (uci import) on wg_check failure")
  457. }
  458. if !strings.Contains(got, "/etc/init.d/network reload") {
  459. t.Error("should have reloaded network after restoring the snapshot")
  460. }
  461. }
  462. func TestAffectedConfigsDedup(t *testing.T) {
  463. ops := []Op{
  464. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s1", "option": "o1", "value": "v1"}},
  465. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s2", "option": "o2", "value": "v2"}},
  466. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}},
  467. {Kind: "service", Args: map[string]string{"name": "dnsmasq", "action": "restart"}},
  468. }
  469. cfgs := affectedConfigs(ops)
  470. if len(cfgs) != 1 || cfgs[0] != "dhcp" {
  471. t.Fatalf("expected [dhcp], got %v", cfgs)
  472. }
  473. }
  474. func TestMarshalUnmarshalOps(t *testing.T) {
  475. ops := []Op{
  476. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s", "option": "o", "value": "1.2.3.4"}, Desc: "test"},
  477. }
  478. data, err := MarshalOps(ops)
  479. if err != nil {
  480. t.Fatal(err)
  481. }
  482. got, err := UnmarshalOps(data)
  483. if err != nil {
  484. t.Fatal(err)
  485. }
  486. if len(got) != 1 || got[0].Kind != "uci_set" || got[0].Args["value"] != "1.2.3.4" {
  487. t.Fatalf("roundtrip failed: %+v", got)
  488. }
  489. }
  490. // TestValidateTcpCheck: args host/port validados por regex.
  491. func TestValidateTcpCheck(t *testing.T) {
  492. cases := []struct {
  493. name, host, port string
  494. ok bool
  495. }{
  496. {"ipv4", "127.0.0.1", "3000", true},
  497. {"localhost", "localhost", "53", true},
  498. {"lan-ip", "192.168.1.1", "80", true},
  499. {"port-zero", "127.0.0.1", "0", false},
  500. {"port-too-high", "127.0.0.1", "65536", false},
  501. {"port-leading-zero", "127.0.0.1", "03000", false},
  502. {"host-space", "127.0.0.1 ", "3000", false},
  503. {"host-shell-chars", "127.0.0.1; rm -rf /", "3000", false},
  504. {"missing-port", "127.0.0.1", "", false},
  505. }
  506. for _, c := range cases {
  507. op := Op{Kind: "tcp_check", Args: map[string]string{"host": c.host, "port": c.port}}
  508. err := Validate(op)
  509. if (err == nil) != c.ok {
  510. t.Errorf("%s: esperaba ok=%v, got err=%v", c.name, c.ok, err)
  511. }
  512. }
  513. }
  514. // TestTcpCheckExecOpenThenClosed: el exec de tcp_check devuelve 0 si el
  515. // puerto está abierto y 1 si está cerrado (healthcheck real de servicio).
  516. func TestTcpCheckExecOpenThenClosed(t *testing.T) {
  517. // Acortar el budget para que el caso "cerrado" no tarde 10 s en el test.
  518. prev := tcpCheckBudget
  519. tcpCheckBudget = 300 * time.Millisecond
  520. defer func() { tcpCheckBudget = prev }()
  521. ln, err := net.Listen("tcp", "127.0.0.1:0")
  522. if err != nil {
  523. t.Fatalf("no pude abrir listener: %v", err)
  524. }
  525. port := strconv.Itoa(ln.Addr().(*net.TCPAddr).Port)
  526. spec, ok := allowlist["tcp_check"]
  527. if !ok {
  528. t.Fatal("tcp_check no está en allowlist")
  529. }
  530. // Puerto abierto → 0
  531. if rc := spec.exec(nil, map[string]string{"host": "127.0.0.1", "port": port}); rc != 0 {
  532. t.Errorf("puerto abierto: esperaba 0, got %d", rc)
  533. }
  534. // Cerrar el listener → puerto cerrado → 1 (tras exhausting el budget corto)
  535. ln.Close()
  536. if rc := spec.exec(nil, map[string]string{"host": "127.0.0.1", "port": port}); rc != 1 {
  537. t.Errorf("puerto cerrado: esperaba 1, got %d", rc)
  538. }
  539. }