executor_test.go 29 KB

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