executor_test.go 29 KB

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