executor_test.go 22 KB

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