executor_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. package executor
  2. import (
  3. "net"
  4. "os"
  5. "strconv"
  6. "strings"
  7. "testing"
  8. "time"
  9. )
  10. // fakeRunner registra los comandos ejecutados y devuelve respuestas canned.
  11. type fakeRunner struct {
  12. calls []string
  13. responses map[string]int // prefix → exitCode (0 si no está)
  14. }
  15. func newFakeRunner() *fakeRunner {
  16. return &fakeRunner{responses: map[string]int{}}
  17. }
  18. func (f *fakeRunner) Run(name string, args ...string) (string, int) {
  19. cmd := name + " " + strings.Join(args, " ")
  20. f.calls = append(f.calls, cmd)
  21. // Buscar respuesta por prefix.
  22. for prefix, code := range f.responses {
  23. if strings.HasPrefix(cmd, prefix) {
  24. if code == 0 {
  25. return "ok", 0
  26. }
  27. return "", code
  28. }
  29. }
  30. return "ok", 0 // default success
  31. }
  32. func TestValidateRejectsUnknownKind(t *testing.T) {
  33. err := Validate(Op{Kind: "rm_rf", Args: map[string]string{}})
  34. if err == nil {
  35. t.Fatal("unknown kind should be rejected")
  36. }
  37. }
  38. func TestValidateRejectsShellMetachars(t *testing.T) {
  39. err := Validate(Op{
  40. Kind: "uci_set",
  41. Args: map[string]string{
  42. "config": "dhcp",
  43. "section": "@dnsmasq[0]",
  44. "option": "server",
  45. "value": "1.1.1.1; rm -rf /", // shell injection
  46. },
  47. })
  48. if err == nil {
  49. t.Fatal("shell metachars in value should be rejected")
  50. }
  51. }
  52. func TestValidateAcceptsValidOp(t *testing.T) {
  53. err := Validate(Op{
  54. Kind: "uci_set",
  55. Args: map[string]string{
  56. "config": "dhcp",
  57. "section": "@dnsmasq[0]",
  58. "option": "server",
  59. "value": "1.1.1.1",
  60. },
  61. })
  62. if err != nil {
  63. t.Fatalf("valid op rejected: %v", err)
  64. }
  65. }
  66. func TestValidateRejectsMissingArg(t *testing.T) {
  67. err := Validate(Op{
  68. Kind: "uci_set",
  69. Args: map[string]string{"config": "dhcp", "section": "foo", "option": "bar"},
  70. // missing "value"
  71. })
  72. if err == nil {
  73. t.Fatal("missing arg should be rejected")
  74. }
  75. }
  76. func TestValidateServiceAction(t *testing.T) {
  77. // Acciones válidas (start/stop añadidos en Fase 17.1 para módulos que
  78. // escuchan en puerto, p. ej. parar AdGuard antes de reconfigurarlo).
  79. for _, action := range []string{"restart", "reload", "enable", "disable", "start", "stop"} {
  80. if err := Validate(Op{Kind: "service", Args: map[string]string{"name": "dnsmasq", "action": action}}); err != nil {
  81. t.Fatalf("action %q should be accepted: %v", action, err)
  82. }
  83. }
  84. // Acción inválida
  85. if err := Validate(Op{Kind: "service", Args: map[string]string{"name": "dnsmasq", "action": "restart;;rm"}}); err == nil {
  86. t.Fatal("action with shell metachars should be rejected")
  87. }
  88. }
  89. // --- Fase 17.1: validación de los nuevos Kinds ---
  90. func TestValidateDownloadURLAllowlist(t *testing.T) {
  91. // URL oficial válida
  92. valid := Op{Kind: "download", Args: map[string]string{
  93. "url": "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
  94. "dest": "/tmp/AdGuardHome.tar.gz",
  95. }}
  96. if err := Validate(valid); err != nil {
  97. t.Fatalf("valid download URL rejected: %v", err)
  98. }
  99. // URL maliciosa (dominio distinto) → rechazo
  100. bad := Op{Kind: "download", Args: map[string]string{
  101. "url": "https://evil.example.com/AdGuardHome.tar.gz",
  102. "dest": "/tmp/x.tar.gz",
  103. }}
  104. if err := Validate(bad); err == nil {
  105. t.Fatal("non-allowlisted download URL should be rejected")
  106. }
  107. // URL oficial pero path fuera de allowlist (otro repo) → rechazo
  108. bad2 := Op{Kind: "download", Args: map[string]string{
  109. "url": "https://github.com/evil/repo/releases/download/v1.0/payload",
  110. "dest": "/tmp/x.tar.gz",
  111. }}
  112. if err := Validate(bad2); err == nil {
  113. t.Fatal("non-AdguardTeam github path should be rejected")
  114. }
  115. }
  116. func TestValidateFilePathAllowlist(t *testing.T) {
  117. for _, p := range []string{"/etc/AdGuardHome.yaml", "/tmp/agh.tar.gz", "/usr/bin/AdGuardHome", "/usr/lib/AdGuardHome/dns"} {
  118. if err := Validate(Op{Kind: "write_file", Args: map[string]string{"path": p, "content_b64": "Zm9v"}}); err != nil {
  119. t.Errorf("path %q should be accepted: %v", p, err)
  120. }
  121. }
  122. for _, p := range []string{"/etc/passwd;rm", "/etc/../etc/shadow", "/root/.ssh/id_rsa", "/var/log/x", "/home/nacho/x"} {
  123. if err := Validate(Op{Kind: "write_file", Args: map[string]string{"path": p, "content_b64": "Zm9v"}}); err == nil {
  124. t.Errorf("path %q should be rejected", p)
  125. }
  126. }
  127. }
  128. func TestValidateChmodMode(t *testing.T) {
  129. for _, m := range []string{"755", "644", "600", "0755", "1777"} {
  130. if err := Validate(Op{Kind: "chmod", Args: map[string]string{"mode": m, "path": "/usr/bin/AdGuardHome"}}); err != nil {
  131. t.Errorf("mode %q should be accepted: %v", m, err)
  132. }
  133. }
  134. for _, m := range []string{"999", "rwxr-xr-x", "755;rm", "abc"} {
  135. if err := Validate(Op{Kind: "chmod", Args: map[string]string{"mode": m, "path": "/usr/bin/AdGuardHome"}}); err == nil {
  136. t.Errorf("mode %q should be rejected", m)
  137. }
  138. }
  139. }
  140. func TestValidateApkInstall(t *testing.T) {
  141. if err := Validate(Op{Kind: "apk_install", Args: map[string]string{"package": "adguard-home"}}); err != nil {
  142. t.Fatalf("valid apk_install rejected: %v", err)
  143. }
  144. if err := Validate(Op{Kind: "apk_install", Args: map[string]string{"package": "adguard-home;rm"}}); err == nil {
  145. t.Fatal("apk_install with shell metachars should be rejected")
  146. }
  147. }
  148. func TestValidateExtractTarball(t *testing.T) {
  149. if err := Validate(Op{Kind: "extract_tarball", Args: map[string]string{"src": "/tmp/agh.tar.gz", "dest": "/tmp/agh"}}); err != nil {
  150. t.Fatalf("valid extract_tarball rejected: %v", err)
  151. }
  152. // dest fuera de allowlist
  153. if err := Validate(Op{Kind: "extract_tarball", Args: map[string]string{"src": "/tmp/agh.tar.gz", "dest": "/home/nacho"}}); err == nil {
  154. t.Fatal("extract_tarball dest outside allowlist should be rejected")
  155. }
  156. }
  157. func TestValidateMv(t *testing.T) {
  158. if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/agh-x/AdGuardHome", "dest": "/usr/bin/AdGuardHome"}}); err != nil {
  159. t.Fatalf("valid mv rejected: %v", err)
  160. }
  161. // dest fuera de allowlist
  162. if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/x", "dest": "/etc/passwd;rm"}}); err == nil {
  163. t.Fatal("mv with malicious dest should be rejected")
  164. }
  165. // src con traversal
  166. if err := Validate(Op{Kind: "mv", Args: map[string]string{"src": "/tmp/../etc/shadow", "dest": "/tmp/x"}}); err == nil {
  167. t.Fatal("mv src with traversal should be rejected")
  168. }
  169. }
  170. // TestWriteFileCreatesParentDir: write_file debe crear /etc/AdGuardHome/ si
  171. // no existe (MkdirAll del dir padre).
  172. func TestWriteFileCreatesParentDir(t *testing.T) {
  173. parent := "/tmp/netpulse-mkdir-test-" + t.Name()
  174. defer os.RemoveAll(parent)
  175. path := parent + "/AdGuardHome/AdGuardHome.yaml"
  176. spec := allowlist["write_file"]
  177. if code := spec.exec(nil, map[string]string{"path": path, "content_b64": "Zm9v"}); code != 0 {
  178. t.Fatalf("write_file exec failed: exit %d", code)
  179. }
  180. if _, err := os.ReadFile(path); err != nil {
  181. t.Fatalf("file not written (dir padre no creado?): %v", err)
  182. }
  183. }
  184. // TestWriteFileExec verifica el exec de write_file escribe el contenido real.
  185. // Usa un tmpdir (no fakeRunner) porque exec usa os.WriteFile directamente.
  186. func TestWriteFileExec(t *testing.T) {
  187. // Invoco exec directamente con un path /tmp real y limpio después.
  188. // El path debe casar con reFilePath (^/tmp/...).
  189. path := "/tmp/netpulse-exec-test-" + t.Name()
  190. defer os.Remove(path)
  191. content := "bind_port: 3000\n"
  192. b64 := "YmluZF9wb3J0OiAzMDAwCg==" // base64 de content
  193. spec := allowlist["write_file"]
  194. if spec.exec == nil {
  195. t.Fatal("write_file has no exec")
  196. }
  197. if code := spec.exec(nil, map[string]string{"path": path, "content_b64": b64}); code != 0 {
  198. t.Fatalf("write_file exec failed: exit %d", code)
  199. }
  200. data, err := os.ReadFile(path)
  201. if err != nil {
  202. t.Fatalf("file not written: %v", err)
  203. }
  204. if string(data) != content {
  205. t.Fatalf("content mismatch: got %q want %q", data, content)
  206. }
  207. }
  208. // TestWriteFileRejectsTraversal: path con .. debe ser rechazado por exec
  209. // (defense in depth: aunque el regex lo pille, exec lo revalida).
  210. func TestWriteFileRejectsTraversal(t *testing.T) {
  211. spec := allowlist["write_file"]
  212. // "/tmp/../../../etc/x" no casa el regex → Validate lo rechaza.
  213. // Pero comprobemos exec con un path que SÍ casa el regex pero tiene ..:
  214. // filepath.Clean("/tmp/a/../b") = "/tmp/b" (válido). Para forzar el
  215. // rechazo en exec, pasamos un path que Clean cambie (no debería casar
  216. // el regex, pero si alguien lo bypassa, exec lo para).
  217. // Como no podemos bypassar el regex desde Validate, este test documenta
  218. // la defensa: si path != Clean(path), exit 1.
  219. path := "/tmp/a/./b"
  220. if code := spec.exec(nil, map[string]string{"path": path, "content_b64": "Zm9v"}); code == 0 {
  221. t.Fatal("exec should reject path where Clean(path) != path")
  222. }
  223. }
  224. // TestApplyPlanConDownloadWriteChmod: plan que mezcla los nuevos Kinds con
  225. // los existentes, verificando que Apply despacha exec vs build correctamente.
  226. func TestApplyPlanConDownloadWriteChmod(t *testing.T) {
  227. fr := newFakeRunner()
  228. // download/extract/chmod via fakeRunner (build path). write_file via exec
  229. // (escribe de verdad en /tmp). service via fakeRunner.
  230. tmpFile := "/tmp/netpulse-plan-test-" + t.Name()
  231. defer os.Remove(tmpFile)
  232. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  233. ops := []Op{
  234. {Kind: "download", Args: map[string]string{
  235. "url": "https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.107.52/AdGuardHome_linux_arm64.tar.gz",
  236. "dest": tmpFile,
  237. }, Desc: "Download AdGuard tarball"},
  238. {Kind: "write_file", Args: map[string]string{
  239. "path": "/tmp/netpulse-plan-test-cfg.yaml",
  240. "content_b64": "YmluZF9wb3J0OiAzMDAwCg==",
  241. }, Desc: "Write AdGuard config"},
  242. {Kind: "chmod", Args: map[string]string{"mode": "755", "path": tmpFile}, Desc: "Make executable"},
  243. {Kind: "service", Args: map[string]string{"name": "adguardhome", "action": "start"}, Desc: "Start AdGuard"},
  244. }
  245. defer os.Remove("/tmp/netpulse-plan-test-cfg.yaml")
  246. res := e.Apply(ops)
  247. if res.Status != "applied" {
  248. t.Fatalf("expected applied, got %s: %s", res.Status, res.Error)
  249. }
  250. // Verifica que los comandos build se ejecutaron (download, chmod, service).
  251. got := strings.Join(fr.calls, "\n")
  252. for _, want := range []string{"uclient-fetch https:", "chmod 755", "/etc/init.d/adguardhome start"} {
  253. if !strings.Contains(got, want) {
  254. t.Errorf("missing call %q in:\n%s", want, got)
  255. }
  256. }
  257. // Y que write_file escribió el fichero config.
  258. if _, err := os.ReadFile("/tmp/netpulse-plan-test-cfg.yaml"); err != nil {
  259. t.Errorf("config file not written: %v", err)
  260. }
  261. }
  262. func TestApplySuccess(t *testing.T) {
  263. fr := newFakeRunner()
  264. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  265. ops := []Op{
  266. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}, Desc: "Set DNS upstream"},
  267. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit dhcp"},
  268. }
  269. res := e.Apply(ops)
  270. if res.Status != "applied" {
  271. t.Fatalf("expected applied, got %s (error=%s)", res.Status, res.Error)
  272. }
  273. if res.Snapshot != "dhcp" {
  274. t.Fatalf("snapshot should list dhcp, got %q", res.Snapshot)
  275. }
  276. // Verificar que se hizo snapshot (uci export dhcp) antes de ejecutar
  277. foundSnap := false
  278. for _, c := range fr.calls {
  279. if strings.Contains(c, "uci export dhcp") {
  280. foundSnap = true
  281. break
  282. }
  283. }
  284. if !foundSnap {
  285. t.Fatal("should have done uci export for snapshot")
  286. }
  287. // Verificar commit
  288. foundCommit := false
  289. for _, c := range fr.calls {
  290. if c == "uci commit dhcp" {
  291. foundCommit = true
  292. break
  293. }
  294. }
  295. if !foundCommit {
  296. t.Fatal("should have committed dhcp")
  297. }
  298. }
  299. func TestApplyFailingOpReverts(t *testing.T) {
  300. fr := newFakeRunner()
  301. // Hacer que el segundo op (commit) falle
  302. fr.responses["uci commit dhcp"] = 1
  303. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  304. ops := []Op{
  305. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "1.1.1.1"}, Desc: "Set DNS"},
  306. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit"},
  307. }
  308. res := e.Apply(ops)
  309. if res.Status != "failed" {
  310. t.Fatalf("expected failed, got %s", res.Status)
  311. }
  312. // Verificar que se hizo revert de los staged changes
  313. foundRevert := false
  314. for _, c := range fr.calls {
  315. if strings.Contains(c, "uci revert dhcp") {
  316. foundRevert = true
  317. break
  318. }
  319. }
  320. if !foundRevert {
  321. t.Fatal("should have reverted staged changes on failure")
  322. }
  323. }
  324. func TestApplyHealthcheckFailRollsBack(t *testing.T) {
  325. fr := newFakeRunner()
  326. // Hacer que el ping falle (healthcheck)
  327. fr.responses["ping"] = 1
  328. e := &Executor{run: fr, now: time.Now, gwTarget: "192.168.1.1"}
  329. ops := []Op{
  330. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "@dnsmasq[0]", "option": "server", "value": "8.8.8.8"}, Desc: "Change DNS"},
  331. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}, Desc: "Commit"},
  332. }
  333. res := e.Apply(ops)
  334. if res.Status != "rolled_back" {
  335. t.Fatalf("expected rolled_back, got %s (error=%s)", res.Status, res.Error)
  336. }
  337. if res.Error != "healthcheck_failed" {
  338. t.Fatalf("error should be healthcheck_failed, got %s", res.Error)
  339. }
  340. // Verificar que se restauró el snapshot (uci import)
  341. foundImport := false
  342. for _, c := range fr.calls {
  343. if strings.Contains(c, "uci import") {
  344. foundImport = true
  345. break
  346. }
  347. }
  348. if !foundImport {
  349. t.Fatal("should have imported snapshot on rollback")
  350. }
  351. }
  352. func TestAffectedConfigsDedup(t *testing.T) {
  353. ops := []Op{
  354. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s1", "option": "o1", "value": "v1"}},
  355. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s2", "option": "o2", "value": "v2"}},
  356. {Kind: "uci_commit", Args: map[string]string{"config": "dhcp"}},
  357. {Kind: "service", Args: map[string]string{"name": "dnsmasq", "action": "restart"}},
  358. }
  359. cfgs := affectedConfigs(ops)
  360. if len(cfgs) != 1 || cfgs[0] != "dhcp" {
  361. t.Fatalf("expected [dhcp], got %v", cfgs)
  362. }
  363. }
  364. func TestMarshalUnmarshalOps(t *testing.T) {
  365. ops := []Op{
  366. {Kind: "uci_set", Args: map[string]string{"config": "dhcp", "section": "s", "option": "o", "value": "1.2.3.4"}, Desc: "test"},
  367. }
  368. data, err := MarshalOps(ops)
  369. if err != nil {
  370. t.Fatal(err)
  371. }
  372. got, err := UnmarshalOps(data)
  373. if err != nil {
  374. t.Fatal(err)
  375. }
  376. if len(got) != 1 || got[0].Kind != "uci_set" || got[0].Args["value"] != "1.2.3.4" {
  377. t.Fatalf("roundtrip failed: %+v", got)
  378. }
  379. }
  380. // TestValidateTcpCheck: args host/port validados por regex.
  381. func TestValidateTcpCheck(t *testing.T) {
  382. cases := []struct {
  383. name, host, port string
  384. ok bool
  385. }{
  386. {"ipv4", "127.0.0.1", "3000", true},
  387. {"localhost", "localhost", "53", true},
  388. {"lan-ip", "192.168.1.1", "80", true},
  389. {"port-zero", "127.0.0.1", "0", false},
  390. {"port-too-high", "127.0.0.1", "65536", false},
  391. {"port-leading-zero", "127.0.0.1", "03000", false},
  392. {"host-space", "127.0.0.1 ", "3000", false},
  393. {"host-shell-chars", "127.0.0.1; rm -rf /", "3000", false},
  394. {"missing-port", "127.0.0.1", "", false},
  395. }
  396. for _, c := range cases {
  397. op := Op{Kind: "tcp_check", Args: map[string]string{"host": c.host, "port": c.port}}
  398. err := Validate(op)
  399. if (err == nil) != c.ok {
  400. t.Errorf("%s: esperaba ok=%v, got err=%v", c.name, c.ok, err)
  401. }
  402. }
  403. }
  404. // TestTcpCheckExecOpenThenClosed: el exec de tcp_check devuelve 0 si el
  405. // puerto está abierto y 1 si está cerrado (healthcheck real de servicio).
  406. func TestTcpCheckExecOpenThenClosed(t *testing.T) {
  407. // Acortar el budget para que el caso "cerrado" no tarde 10 s en el test.
  408. prev := tcpCheckBudget
  409. tcpCheckBudget = 300 * time.Millisecond
  410. defer func() { tcpCheckBudget = prev }()
  411. ln, err := net.Listen("tcp", "127.0.0.1:0")
  412. if err != nil {
  413. t.Fatalf("no pude abrir listener: %v", err)
  414. }
  415. port := strconv.Itoa(ln.Addr().(*net.TCPAddr).Port)
  416. spec, ok := allowlist["tcp_check"]
  417. if !ok {
  418. t.Fatal("tcp_check no está en allowlist")
  419. }
  420. // Puerto abierto → 0
  421. if rc := spec.exec(nil, map[string]string{"host": "127.0.0.1", "port": port}); rc != 0 {
  422. t.Errorf("puerto abierto: esperaba 0, got %d", rc)
  423. }
  424. // Cerrar el listener → puerto cerrado → 1 (tras exhausting el budget corto)
  425. ln.Close()
  426. if rc := spec.exec(nil, map[string]string{"host": "127.0.0.1", "port": port}); rc != 1 {
  427. t.Errorf("puerto cerrado: esperaba 1, got %d", rc)
  428. }
  429. }