executor_test.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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. "sha256": strings.Repeat("a", 64),
  169. }}
  170. if err := Validate(valid); err != nil {
  171. t.Fatalf("valid download URL rejected: %v", err)
  172. }
  173. missingSum := Op{Kind: "download", Args: map[string]string{
  174. "url": "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
  175. "dest": "/tmp/AdGuardHome.tar.gz",
  176. }}
  177. if err := Validate(missingSum); err == nil {
  178. t.Fatal("download without sha256 should be rejected")
  179. }
  180. badSum := Op{Kind: "download", Args: map[string]string{
  181. "url": "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
  182. "dest": "/tmp/AdGuardHome.tar.gz",
  183. "sha256": "no-es-un-sha",
  184. }}
  185. if err := Validate(badSum); err == nil {
  186. t.Fatal("download with malformed sha256 should be rejected")
  187. }
  188. // URL maliciosa (dominio distinto) → rechazo
  189. bad := Op{Kind: "download", Args: map[string]string{
  190. "url": "https://evil.example.com/AdGuardHome.tar.gz",
  191. "dest": "/tmp/x.tar.gz",
  192. }}
  193. if err := Validate(bad); err == nil {
  194. t.Fatal("non-allowlisted download URL should be rejected")
  195. }
  196. // URL oficial pero path fuera de allowlist (otro repo) → rechazo
  197. bad2 := Op{Kind: "download", Args: map[string]string{
  198. "url": "https://github.com/evil/repo/releases/download/v1.0/payload",
  199. "dest": "/tmp/x.tar.gz",
  200. }}
  201. if err := Validate(bad2); err == nil {
  202. t.Fatal("non-AdguardTeam github path should be rejected")
  203. }
  204. }
  205. func TestValidateDawnCheck(t *testing.T) {
  206. if err := Validate(Op{Kind: "dawn_check", Args: map[string]string{}}); err != nil {
  207. t.Fatalf("dawn_check debería validar: %v", err)
  208. }
  209. }
  210. func TestValidateUsteerCheck(t *testing.T) {
  211. if err := Validate(Op{Kind: "usteer_check", Args: map[string]string{}}); err != nil {
  212. t.Fatalf("usteer_check debería validar: %v", err)
  213. }
  214. }
  215. func TestValidateRemoveKinds(t *testing.T) {
  216. for _, k := range []string{"apk_remove", "opkg_remove"} {
  217. if err := Validate(Op{Kind: k, Args: map[string]string{"package": "luci-app-usteer"}}); err != nil {
  218. t.Errorf("%s con package con guion debería validar: %v", k, err)
  219. }
  220. if err := Validate(Op{Kind: k, Args: map[string]string{"package": "dawn"}}); err != nil {
  221. t.Errorf("%s debería validar: %v", k, err)
  222. }
  223. if err := Validate(Op{Kind: k, Args: map[string]string{}}); err == nil {
  224. t.Errorf("%s sin package debería fallar", k)
  225. }
  226. if err := Validate(Op{Kind: k, Args: map[string]string{"package": "bad;rm -rf /"}}); err == nil {
  227. t.Errorf("%s con package inválido debería fallar", k)
  228. }
  229. }
  230. }
  231. func TestValidateWifiReload(t *testing.T) {
  232. if err := Validate(Op{Kind: "wifi_reload", Args: map[string]string{}}); err != nil {
  233. t.Fatalf("wifi_reload debería validar: %v", err)
  234. }
  235. }
  236. func TestValidateFilePathAllowlist(t *testing.T) {
  237. for _, p := range []string{"/etc/AdGuardHome.yaml", "/tmp/agh.tar.gz", "/usr/bin/AdGuardHome", "/usr/lib/AdGuardHome/dns"} {
  238. if err := Validate(Op{Kind: "write_file", Args: map[string]string{"path": p, "content_b64": "Zm9v"}}); err != nil {
  239. t.Errorf("path %q should be accepted: %v", p, err)
  240. }
  241. }
  242. for _, p := range []string{"/etc/passwd;rm", "/etc/../etc/shadow", "/root/.ssh/id_rsa", "/var/log/x", "/home/nacho/x"} {
  243. if err := Validate(Op{Kind: "write_file", Args: map[string]string{"path": p, "content_b64": "Zm9v"}}); err == nil {
  244. t.Errorf("path %q should be rejected", p)
  245. }
  246. }
  247. }
  248. func TestValidateChmodMode(t *testing.T) {
  249. for _, m := range []string{"755", "644", "600", "0755", "1777"} {
  250. if err := Validate(Op{Kind: "chmod", Args: map[string]string{"mode": m, "path": "/usr/bin/AdGuardHome"}}); err != nil {
  251. t.Errorf("mode %q should be accepted: %v", m, err)
  252. }
  253. }
  254. for _, m := range []string{"999", "rwxr-xr-x", "755;rm", "abc"} {
  255. if err := Validate(Op{Kind: "chmod", Args: map[string]string{"mode": m, "path": "/usr/bin/AdGuardHome"}}); err == nil {
  256. t.Errorf("mode %q should be rejected", m)
  257. }
  258. }
  259. }
  260. func TestValidateApkInstall(t *testing.T) {
  261. if err := Validate(Op{Kind: "apk_install", Args: map[string]string{"package": "adguard-home"}}); err != nil {
  262. t.Fatalf("valid apk_install rejected: %v", err)
  263. }
  264. if err := Validate(Op{Kind: "apk_install", Args: map[string]string{"package": "adguard-home;rm"}}); err == nil {
  265. t.Fatal("apk_install with shell metachars should be rejected")
  266. }
  267. }
  268. func TestValidateExtractTarball(t *testing.T) {
  269. if err := Validate(Op{Kind: "extract_tarball", Args: map[string]string{"src": "/tmp/agh.tar.gz", "dest": "/tmp/agh"}}); err != nil {
  270. t.Fatalf("valid extract_tarball rejected: %v", err)
  271. }
  272. // dest fuera de allowlist
  273. if err := Validate(Op{Kind: "extract_tarball", Args: map[string]string{"src": "/tmp/agh.tar.gz", "dest": "/home/nacho"}}); err == nil {
  274. t.Fatal("extract_tarball dest outside allowlist should be rejected")
  275. }
  276. }
  277. func TestValidateMv(t *testing.T) {
  278. if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/agh-x/AdGuardHome", "dest": "/usr/bin/AdGuardHome"}}); err != nil {
  279. t.Fatalf("valid mv rejected: %v", err)
  280. }
  281. // dest fuera de allowlist
  282. if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/x", "dest": "/etc/passwd;rm"}}); err == nil {
  283. t.Fatal("mv with malicious dest should be rejected")
  284. }
  285. // src con traversal
  286. if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/../etc/shadow", "dest": "/tmp/x"}}); err == nil {
  287. t.Fatal("mv src with traversal should be rejected")
  288. }
  289. }
  290. // TestWriteFileCreatesParentDir: write_file debe crear /etc/AdGuardHome/ si
  291. // no existe (MkdirAll del dir padre).
  292. func TestWriteFileCreatesParentDir(t *testing.T) {
  293. parent := "/tmp/netpulse-mkdir-test-" + t.Name()
  294. defer os.RemoveAll(parent)
  295. path := parent + "/AdGuardHome/AdGuardHome.yaml"
  296. spec := allowlist["write_file"]
  297. if code := spec.exec(nil, map[string]string{"path": path, "content_b64": "Zm9v"}); code != 0 {
  298. t.Fatalf("write_file exec failed: exit %d", code)
  299. }
  300. if _, err := os.ReadFile(path); err != nil {
  301. t.Fatalf("file not written (dir padre no creado?): %v", err)
  302. }
  303. }
  304. // TestWriteFileExec verifica el exec de write_file escribe el contenido real.
  305. // Usa un tmpdir (no fakeRunner) porque exec usa os.WriteFile directamente.
  306. func TestWriteFileExec(t *testing.T) {
  307. // Invoco exec directamente con un path /tmp real y limpio después.
  308. // El path debe casar con reFilePath (^/tmp/...).
  309. path := "/tmp/netpulse-exec-test-" + t.Name()
  310. defer os.Remove(path)
  311. content := "bind_port: 3000\n"
  312. b64 := "YmluZF9wb3J0OiAzMDAwCg==" // base64 de content
  313. spec := allowlist["write_file"]
  314. if spec.exec == nil {
  315. t.Fatal("write_file has no exec")
  316. }
  317. if code := spec.exec(nil, map[string]string{"path": path, "content_b64": b64}); code != 0 {
  318. t.Fatalf("write_file exec failed: exit %d", code)
  319. }
  320. data, err := os.ReadFile(path)
  321. if err != nil {
  322. t.Fatalf("file not written: %v", err)
  323. }
  324. if string(data) != content {
  325. t.Fatalf("content mismatch: got %q want %q", data, content)
  326. }
  327. }
  328. // TestWriteFileRejectsTraversal: path con .. debe ser rechazado por exec
  329. // (defense in depth: aunque el regex lo pille, exec lo revalida).
  330. func TestWriteFileRejectsTraversal(t *testing.T) {
  331. spec := allowlist["write_file"]
  332. // "/tmp/../../../etc/x" no casa el regex → Validate lo rechaza.
  333. // Pero comprobemos exec con un path que SÍ casa el regex pero tiene ..:
  334. // filepath.Clean("/tmp/a/../b") = "/tmp/b" (válido). Para forzar el
  335. // rechazo en exec, pasamos un path que Clean cambie (no debería casar
  336. // el regex, pero si alguien lo bypassa, exec lo para).
  337. // Como no podemos bypassar el regex desde Validate, este test documenta
  338. // la defensa: si path != Clean(path), exit 1.
  339. path := "/tmp/a/./b"
  340. if code := spec.exec(nil, map[string]string{"path": path, "content_b64": "Zm9v"}); code == 0 {
  341. t.Fatal("exec should reject path where Clean(path) != path")
  342. }
  343. }
  344. // TestApplyPlanConDownloadWriteChmod: plan que mezcla los nuevos Kinds con
  345. // los existentes, verificando que Apply despacha exec vs build correctamente.
  346. func TestApplyPlanConDownloadWriteChmod(t *testing.T) {
  347. fr := newFakeRunner()
  348. // download/extract/chmod via fakeRunner (build path). write_file via exec
  349. // (escribe de verdad en /tmp). service via fakeRunner.
  350. tmpFile := "/tmp/netpulse-plan-test-" + t.Name()
  351. defer os.Remove(tmpFile)
  352. sha := strings.Repeat("b", 64)
  353. fr.outputs["sha256sum"] = sha + " " + tmpFile
  354. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  355. ops := []Op{
  356. {Kind: "download", Args: map[string]string{
  357. "url": "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
  358. "dest": tmpFile,
  359. "sha256": sha,
  360. }, Desc: "Download AdGuard tarball"},
  361. {Kind: "write_file", Args: map[string]string{
  362. "path": "/tmp/netpulse-plan-test-cfg.yaml",
  363. "content_b64": "YmluZF9wb3J0OiAzMDAwCg==",
  364. }, Desc: "Write AdGuard config"},
  365. {Kind: "chmod", Args: map[string]string{"mode": "755", "path": tmpFile}, Desc: "Make executable"},
  366. {Kind: "service", Args: map[string]string{"name": "adguardhome", "action": "start"}, Desc: "Start AdGuard"},
  367. }
  368. defer os.Remove("/tmp/netpulse-plan-test-cfg.yaml")
  369. res := e.Apply(ops)
  370. if res.Status != "applied" {
  371. t.Fatalf("expected applied, got %s: %s", res.Status, res.Error)
  372. }
  373. // Verifica que los comandos build se ejecutaron (download, chmod, service).
  374. got := strings.Join(fr.calls, "\n")
  375. for _, want := range []string{"uclient-fetch https:", "chmod 755", "/etc/init.d/adguardhome start"} {
  376. if !strings.Contains(got, want) {
  377. t.Errorf("missing call %q in:\n%s", want, got)
  378. }
  379. }
  380. // Y que write_file escribió el fichero config.
  381. if _, err := os.ReadFile("/tmp/netpulse-plan-test-cfg.yaml"); err != nil {
  382. t.Errorf("config file not written: %v", err)
  383. }
  384. }
  385. func TestApplyDownloadChecksumMismatch(t *testing.T) {
  386. fr := newFakeRunner()
  387. fr.outputs["sha256sum"] = strings.Repeat("c", 64) + " /tmp/netpulse-plan-test-download"
  388. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  389. res := e.Apply([]Op{{
  390. Kind: "download",
  391. Args: map[string]string{
  392. "url": "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
  393. "dest": "/tmp/netpulse-plan-test-download",
  394. "sha256": strings.Repeat("d", 64),
  395. },
  396. Desc: "Download with wrong digest",
  397. }})
  398. if res.Status != "failed" {
  399. t.Fatalf("expected failed, got %s", res.Status)
  400. }
  401. }
  402. func TestUnsafeTarNames(t *testing.T) {
  403. for _, name := range []string{"../etc/passwd", "/etc/passwd", `a\..\b`, "a/../../b"} {
  404. if !unsafeTarNames(name) {
  405. t.Errorf("unsafe name accepted: %q", name)
  406. }
  407. }
  408. for _, name := range []string{"AdGuardHome/AdGuardHome", "dir/file", ""} {
  409. if unsafeTarNames(name) {
  410. t.Errorf("safe name rejected: %q", name)
  411. }
  412. }
  413. }
  414. func TestUnsafeTarTypes(t *testing.T) {
  415. for _, line := range []string{"lrwxrwxrwx 0 0 0 0 Jan 1 00:00 link", "hrw-r--r-- 0 0 0 0 Jan 1 00:00 hard", "brw-r--r-- 0 0 0 0 Jan 1 00:00 dev"} {
  416. if !unsafeTarTypes(line) {
  417. t.Errorf("unsafe tar type accepted: %q", line)
  418. }
  419. }
  420. for _, line := range []string{"-rw-r--r-- 0 0 0 0 Jan 1 00:00 file", "drwxr-xr-x 0 0 0 0 Jan 1 00:00 dir"} {
  421. if unsafeTarTypes(line) {
  422. t.Errorf("safe tar type rejected: %q", line)
  423. }
  424. }
  425. }
  426. func TestApplyExtractRejectsUnsafeTarNames(t *testing.T) {
  427. fr := newFakeRunner()
  428. fr.outputs["tar -tzf"] = "../escape\n"
  429. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  430. res := e.Apply([]Op{{
  431. Kind: "extract_tarball",
  432. Args: map[string]string{"src": "/tmp/netpulse-extract-test.tar.gz", "dest": "/tmp/netpulse-extract-test"},
  433. Desc: "Extract unsafe tarball",
  434. }})
  435. if res.Status != "failed" {
  436. t.Fatalf("expected failed, got %s", res.Status)
  437. }
  438. if strings.Contains(strings.Join(fr.calls, "\n"), "tar -xzf") {
  439. t.Fatal("unsafe tarball must not be extracted")
  440. }
  441. }
  442. func TestApplyExtractRejectsUnsafeTarTypes(t *testing.T) {
  443. fr := newFakeRunner()
  444. fr.outputs["tar -tzf"] = "ok\n"
  445. fr.outputs["tar -tvzf"] = "lrwxrwxrwx 0 0 0 0 Jan 1 00:00 link\n"
  446. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  447. res := e.Apply([]Op{{
  448. Kind: "extract_tarball",
  449. Args: map[string]string{"src": "/tmp/netpulse-extract-test.tar.gz", "dest": "/tmp/netpulse-extract-test"},
  450. Desc: "Extract symlink tarball",
  451. }})
  452. if res.Status != "failed" {
  453. t.Fatalf("expected failed, got %s", res.Status)
  454. }
  455. if strings.Contains(strings.Join(fr.calls, "\n"), "tar -xzf") {
  456. t.Fatal("tarball with symlink must not be extracted")
  457. }
  458. }
  459. func TestApplySuccess(t *testing.T) {
  460. fr := newFakeRunner()
  461. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  462. ops := []Op{
  463. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}, Desc: "Set DNS upstream"},
  464. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit dhcp"},
  465. }
  466. res := e.Apply(ops)
  467. if res.Status != "applied" {
  468. t.Fatalf("expected applied, got %s (error=%s)", res.Status, res.Error)
  469. }
  470. if res.Snapshot != "dhcp" {
  471. t.Fatalf("snapshot should list dhcp, got %q", res.Snapshot)
  472. }
  473. // Verificar que se hizo snapshot (uci export dhcp) antes de ejecutar
  474. foundSnap := false
  475. for _, c := range fr.calls {
  476. if strings.Contains(c, "uci export dhcp") {
  477. foundSnap = true
  478. break
  479. }
  480. }
  481. if !foundSnap {
  482. t.Fatal("should have done uci export for snapshot")
  483. }
  484. // Verificar commit
  485. foundCommit := false
  486. for _, c := range fr.calls {
  487. if c == "uci commit dhcp" {
  488. foundCommit = true
  489. break
  490. }
  491. }
  492. if !foundCommit {
  493. t.Fatal("should have committed dhcp")
  494. }
  495. }
  496. func TestApplyFailingOpReverts(t *testing.T) {
  497. fr := newFakeRunner()
  498. // Hacer que el segundo op (commit) falle
  499. fr.responses["uci commit dhcp"] = 1
  500. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  501. ops := []Op{
  502. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}, Desc: "Set DNS"},
  503. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit"},
  504. }
  505. res := e.Apply(ops)
  506. if res.Status != "failed" {
  507. t.Fatalf("expected failed, got %s", res.Status)
  508. }
  509. // Verificar que se hizo revert de los staged changes
  510. foundRevert := false
  511. for _, c := range fr.calls {
  512. if strings.Contains(c, "uci revert dhcp") {
  513. foundRevert = true
  514. break
  515. }
  516. }
  517. if !foundRevert {
  518. t.Fatal("should have reverted staged changes on failure")
  519. }
  520. }
  521. func TestApplyHealthcheckFailRollsBack(t *testing.T) {
  522. fr := newFakeRunner()
  523. snap := "config dhcp 'lan'\n\toption dns '8.8.8.8'\n\tlist domain '$(reboot)'"
  524. fr.outputs["uci export"] = snap
  525. // Hacer que el ping falle (healthcheck)
  526. fr.responses["ping"] = 1
  527. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  528. ops := []Op{
  529. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "8.8.8.8"}, Desc: "Change DNS"},
  530. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit"},
  531. }
  532. res := e.Apply(ops)
  533. if res.Status != "rolled_back" {
  534. t.Fatalf("expected rolled_back, got %s (error=%s)", res.Status, res.Error)
  535. }
  536. if res.Error != "healthcheck_failed" {
  537. t.Fatalf("error should be healthcheck_failed, got %s", res.Error)
  538. }
  539. // Verificar que se restauró el snapshot (uci import)
  540. foundImport := false
  541. for _, c := range fr.calls {
  542. if strings.Contains(c, "uci import") {
  543. foundImport = true
  544. break
  545. }
  546. }
  547. if !foundImport {
  548. t.Fatal("should have imported snapshot on rollback")
  549. }
  550. if len(fr.inputs) == 0 || fr.inputs[0] != snap {
  551. t.Fatalf("snapshot should reach uci import via stdin, got %q", fr.inputs)
  552. }
  553. }
  554. // TestValidateWgCheck (10.3): el healthcheck del túnel valida interface y
  555. // rechaza metachars shell.
  556. func TestValidateWgCheck(t *testing.T) {
  557. if err := Validate(Op{Kind: "wg_check", Args: map[string]string{"interface": "wg0"}}); err != nil {
  558. t.Fatalf("valid wg_check rejected: %v", err)
  559. }
  560. if err := Validate(Op{Kind: "wg_check", Args: map[string]string{"interface": "wg0; rm -rf /"}}); err == nil {
  561. t.Fatal("wg_check with shell metachars should be rejected")
  562. }
  563. if err := Validate(Op{Kind: "wg_check", Args: map[string]string{}}); err == nil {
  564. t.Fatal("wg_check missing interface should be rejected")
  565. }
  566. }
  567. // TestApplyWgCheckFailRollsBack (10.3): si `wg show wg0` falla tras el apply,
  568. // el executor restaura los snapshots y relanza la red (rollback real), en vez
  569. // de devolver un simple "failed".
  570. func TestApplyWgCheckFailRollsBack(t *testing.T) {
  571. fr := newFakeRunner()
  572. fr.responses["wg show wg0"] = 1 // el túnel no levantó tras el reload
  573. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  574. ops := []Op{
  575. {Kind: "uci_set_named", Args: map[string]string{"config": "network", "section": "wg0", "type": "interface"}, Desc: "Create interface"},
  576. {Kind: "uci_set", Args: map[string]string{"config": "network", "section": "wg0", "option": "proto", "value": "wireguard"}, Desc: "Set proto"},
  577. {Kind: "uci_commit", Args: map[string]string{"config": "network"}, Desc: "Commit"},
  578. {Kind: "service", Args: map[string]string{"name": "network", "action": "reload"}, Desc: "Reload network"},
  579. {Kind: "wg_check", Args: map[string]string{"interface": "wg0"}, Desc: "Check tunnel up"},
  580. }
  581. res := e.Apply(ops)
  582. if res.Status != "rolled_back" {
  583. t.Fatalf("expected rolled_back, got %s (error=%s)", res.Status, res.Error)
  584. }
  585. if res.Error != "wg_check_failed" {
  586. t.Fatalf("error should be wg_check_failed, got %s", res.Error)
  587. }
  588. got := strings.Join(fr.calls, "\n")
  589. if !strings.Contains(got, "uci import") {
  590. t.Error("should have restored the snapshot (uci import) on wg_check failure")
  591. }
  592. if !strings.Contains(got, "/etc/init.d/network reload") {
  593. t.Error("should have reloaded network after restoring the snapshot")
  594. }
  595. }
  596. func TestAffectedConfigsDedup(t *testing.T) {
  597. ops := []Op{
  598. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s1", "option": "o1", "value": "v1"}},
  599. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s2", "option": "o2", "value": "v2"}},
  600. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}},
  601. {Kind: "service", Args: map[string]string{"name": "dnsmasq", "action": "restart"}},
  602. }
  603. cfgs := affectedConfigs(ops)
  604. if len(cfgs) != 1 || cfgs[0] != "dhcp" {
  605. t.Fatalf("expected [dhcp], got %v", cfgs)
  606. }
  607. }
  608. func TestMarshalUnmarshalOps(t *testing.T) {
  609. ops := []Op{
  610. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s", "option": "o", "value": "1.2.3.4"}, Desc: "test"},
  611. }
  612. data, err := MarshalOps(ops)
  613. if err != nil {
  614. t.Fatal(err)
  615. }
  616. got, err := UnmarshalOps(data)
  617. if err != nil {
  618. t.Fatal(err)
  619. }
  620. if len(got) != 1 || got[0].Kind != "uci_set" || got[0].Args["value"] != "1.2.3.4" {
  621. t.Fatalf("roundtrip failed: %+v", got)
  622. }
  623. }
  624. // TestValidateTcpCheck: args host/port validados por regex.
  625. func TestValidateTcpCheck(t *testing.T) {
  626. cases := []struct {
  627. name, host, port string
  628. ok bool
  629. }{
  630. {"ipv4", "127.0.0.1", "3000", true},
  631. {"localhost", "localhost", "53", true},
  632. {"lan-ip", "192.168.1.1", "80", true},
  633. {"port-zero", "127.0.0.1", "0", false},
  634. {"port-too-high", "127.0.0.1", "65536", false},
  635. {"port-leading-zero", "127.0.0.1", "03000", false},
  636. {"host-space", "127.0.0.1 ", "3000", false},
  637. {"host-shell-chars", "127.0.0.1; rm -rf /", "3000", false},
  638. {"missing-port", "127.0.0.1", "", false},
  639. }
  640. for _, c := range cases {
  641. op := Op{Kind: "tcp_check", Args: map[string]string{"host": c.host, "port": c.port}}
  642. err := Validate(op)
  643. if (err == nil) != c.ok {
  644. t.Errorf("%s: esperaba ok=%v, got err=%v", c.name, c.ok, err)
  645. }
  646. }
  647. }
  648. // TestTcpCheckExecOpenThenClosed: el exec de tcp_check devuelve 0 si el
  649. // puerto está abierto y 1 si está cerrado (healthcheck real de servicio).
  650. func TestTcpCheckExecOpenThenClosed(t *testing.T) {
  651. // Acortar el budget para que el caso "cerrado" no tarde 10 s en el test.
  652. prev := tcpCheckBudget
  653. tcpCheckBudget = 300 * time.Millisecond
  654. defer func() { tcpCheckBudget = prev }()
  655. ln, err := net.Listen("tcp", "127.0.0.1:0")
  656. if err != nil {
  657. t.Fatalf("no pude abrir listener: %v", err)
  658. }
  659. port := strconv.Itoa(ln.Addr().(*net.TCPAddr).Port)
  660. spec, ok := allowlist["tcp_check"]
  661. if !ok {
  662. t.Fatal("tcp_check no está en allowlist")
  663. }
  664. // Puerto abierto → 0
  665. if rc := spec.exec(nil, map[string]string{"host": "127.0.0.1", "port": port}); rc != 0 {
  666. t.Errorf("puerto abierto: esperaba 0, got %d", rc)
  667. }
  668. // Cerrar el listener → puerto cerrado → 1 (tras exhausting el budget corto)
  669. ln.Close()
  670. if rc := spec.exec(nil, map[string]string{"host": "127.0.0.1", "port": port}); rc != 1 {
  671. t.Errorf("puerto cerrado: esperaba 1, got %d", rc)
  672. }
  673. }
  674. // --- Fase 18: ownership UCI ---
  675. func TestValidateOwnershipMode(t *testing.T) {
  676. if err := Validate(Op{Kind: "ownership_mode", Args: map[string]string{"enforce": "true"}}); err != nil {
  677. t.Fatalf("ownership_mode enforce=true debería validar: %v", err)
  678. }
  679. if err := Validate(Op{Kind: "ownership_mode", Args: map[string]string{"enforce": "false"}}); err != nil {
  680. t.Fatalf("ownership_mode enforce=false debería validar: %v", err)
  681. }
  682. if err := Validate(Op{Kind: "ownership_mode", Args: map[string]string{"enforce": "yes"}}); err == nil {
  683. t.Fatal("ownership_mode enforce=yes debería rechazarse")
  684. }
  685. if err := Validate(Op{Kind: "ownership_mode", Args: map[string]string{}}); err == nil {
  686. t.Fatal("ownership_mode sin enforce debería rechazarse")
  687. }
  688. }
  689. func TestValidateUciSetManaged(t *testing.T) {
  690. if err := Validate(Op{Kind: "uci_set_managed", Args: map[string]string{"config": "wireless", "section": "guest"}}); err != nil {
  691. t.Fatalf("uci_set_managed válido rechazado: %v", err)
  692. }
  693. if err := Validate(Op{Kind: "uci_set_managed", Args: map[string]string{"config": "wireless", "section": "bad;rm"}}); err == nil {
  694. t.Fatal("uci_set_managed con section malicioso debería rechazarse")
  695. }
  696. if err := Validate(Op{Kind: "uci_set_managed", Args: map[string]string{"config": "wireless"}}); err == nil {
  697. t.Fatal("uci_set_managed sin section debería rechazarse")
  698. }
  699. }
  700. func TestApplyOwnershipBlocksUnmanaged(t *testing.T) {
  701. fr := newFakeRunner()
  702. // La sección dhcp.@dnsmasq[0] existe pero no está gestionada.
  703. fr.responses["uci show dhcp.@dnsmasq[0]"] = 0
  704. fr.responses["uci get dhcp.@dnsmasq[0].np_managed"] = 1
  705. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  706. ops := []Op{
  707. {Kind: "ownership_mode", Args: map[string]string{"enforce": "true"}},
  708. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}},
  709. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}},
  710. }
  711. res := e.Apply(ops)
  712. if res.Status != "failed" {
  713. t.Fatalf("esperaba failed, got %s", res.Status)
  714. }
  715. if !strings.Contains(res.Error, "section_not_managed") {
  716. t.Fatalf("error debería ser section_not_managed, got %q", res.Error)
  717. }
  718. }
  719. func TestApplyOwnershipAllowsManaged(t *testing.T) {
  720. fr := newFakeRunner()
  721. fr.responses["uci show dhcp.@dnsmasq[0]"] = 0
  722. fr.responses["uci get dhcp.@dnsmasq[0].np_managed"] = 0
  723. fr.outputs["uci get dhcp.@dnsmasq[0].np_managed"] = "1"
  724. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  725. ops := []Op{
  726. {Kind: "ownership_mode", Args: map[string]string{"enforce": "true"}},
  727. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}},
  728. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}},
  729. }
  730. res := e.Apply(ops)
  731. if res.Status != "applied" {
  732. t.Fatalf("esperaba applied, got %s (error=%s)", res.Status, res.Error)
  733. }
  734. }
  735. func TestApplyOwnershipUciAddMarksManaged(t *testing.T) {
  736. fr := newFakeRunner()
  737. // uci add wireless wifi-iface devuelve el nombre de la sección creada;
  738. // fakeRunner devuelve "ok" por defecto, que usamos como nombre.
  739. fr.outputs["uci get wireless.@wifi-iface[-1].np_managed"] = "1"
  740. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  741. ops := []Op{
  742. {Kind: "ownership_mode", Args: map[string]string{"enforce": "true"}},
  743. {Kind: "uci_add", Args: map[string]string{"config": "wireless", "type": "wifi-iface"}, Desc: "Add guest iface"},
  744. {Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "ssid", "value": "NetPulse-Guest"}},
  745. {Kind: "uci_commit", Args: map[string]string{"config": "wireless"}},
  746. }
  747. res := e.Apply(ops)
  748. if res.Status != "applied" {
  749. t.Fatalf("esperaba applied, got %s (error=%s)", res.Status, res.Error)
  750. }
  751. got := strings.Join(fr.calls, "\n")
  752. if !strings.Contains(got, "uci add wireless wifi-iface") {
  753. t.Error("falta uci add wireless wifi-iface")
  754. }
  755. if !strings.Contains(got, "uci set wireless.ok.np_managed=1") {
  756. t.Errorf("falta uci set wireless.ok.np_managed=1 tras uci_add. Calls:\n%s", got)
  757. }
  758. }
  759. func TestApplyOwnershipUciSetNamedMarksManaged(t *testing.T) {
  760. fr := newFakeRunner()
  761. // La sección network.guest no existe todavía.
  762. fr.responses["uci show network.guest"] = 1
  763. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  764. ops := []Op{
  765. {Kind: "ownership_mode", Args: map[string]string{"enforce": "true"}},
  766. {Kind: "uci_set_named", Args: map[string]string{"config": "network", "section": "guest", "type": "interface"}},
  767. {Kind: "uci_commit", Args: map[string]string{"config": "network"}},
  768. }
  769. res := e.Apply(ops)
  770. if res.Status != "applied" {
  771. t.Fatalf("esperaba applied, got %s (error=%s)", res.Status, res.Error)
  772. }
  773. got := strings.Join(fr.calls, "\n")
  774. if !strings.Contains(got, "uci set network.guest=interface") {
  775. t.Error("falta uci set network.guest=interface")
  776. }
  777. if !strings.Contains(got, "uci set network.guest.np_managed=1") {
  778. t.Errorf("falta uci set network.guest.np_managed=1. Calls:\n%s", got)
  779. }
  780. }
  781. func TestApplyOwnershipUciSetManagedTakeover(t *testing.T) {
  782. fr := newFakeRunner()
  783. // Sección existente no gestionada; uci_set_managed debe poder marcarla.
  784. fr.responses["uci set wireless.guest.np_managed=1"] = 0
  785. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  786. ops := []Op{
  787. {Kind: "ownership_mode", Args: map[string]string{"enforce": "true"}},
  788. {Kind: "uci_set_managed", Args: map[string]string{"config": "wireless", "section": "guest"}},
  789. {Kind: "uci_commit", Args: map[string]string{"config": "wireless"}},
  790. }
  791. res := e.Apply(ops)
  792. if res.Status != "applied" {
  793. t.Fatalf("esperaba applied, got %s (error=%s)", res.Status, res.Error)
  794. }
  795. }
  796. func TestApplyOwnershipDisabled(t *testing.T) {
  797. fr := newFakeRunner()
  798. // Con enforce=false no debe importar si la sección está gestionada.
  799. fr.responses["uci show dhcp.@dnsmasq[0]"] = 0
  800. fr.responses["uci get dhcp.@dnsmasq[0].np_managed"] = 1
  801. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  802. ops := []Op{
  803. {Kind: "ownership_mode", Args: map[string]string{"enforce": "false"}},
  804. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}},
  805. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}},
  806. }
  807. res := e.Apply(ops)
  808. if res.Status != "applied" {
  809. t.Fatalf("esperaba applied con ownership desactivado, got %s (error=%s)", res.Status, res.Error)
  810. }
  811. }