executor_test.go 18 KB

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