executor.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. // Package executor — ejecutor sandboxeado de operaciones de escritura en el
  2. // router (Fase 10). El servidor envía una lista de Ops allowlistedas vía SSE;
  3. // el ejecutor las valida, hace snapshot, aplica en staging, commit, healthcheck
  4. // y rollback automático si falla.
  5. //
  6. // Allowlist estricta: cada Kind tiene un patrón regex por arg. Args que no
  7. // casan → rechazo inmediato. Shell libre PROHIBIDO.
  8. package executor
  9. import (
  10. "encoding/base64"
  11. "encoding/json"
  12. "fmt"
  13. "net"
  14. "os"
  15. "os/exec"
  16. "path/filepath"
  17. "regexp"
  18. "strings"
  19. "time"
  20. )
  21. // Op es una operación allowlistedada que el ejecutor puede aplicar.
  22. type Op struct {
  23. Kind string `json:"kind"` // uci_set|uci_delete|uci_add_list|uci_commit|service|install|wg_check
  24. Args map[string]string `json:"args"`
  25. Desc string `json:"desc"` // descripción humana para el diff
  26. }
  27. // ApplyResult es el resultado de ejecutar un plan.
  28. type ApplyResult struct {
  29. Status string `json:"status"` // applied|failed|rolled_back
  30. Op string `json:"op,omitempty"`
  31. Error string `json:"error,omitempty"`
  32. DurationMs int64 `json:"duration_ms"`
  33. Snapshot string `json:"snapshot,omitempty"` // configs afectados
  34. }
  35. // Runner ejecuta comandos en el router. Interfaz para inyectar fakes en tests.
  36. type Runner interface {
  37. Run(name string, args ...string) (stdout string, exitCode int)
  38. }
  39. // shellRunner usa exec.Command en producción.
  40. type shellRunner struct{}
  41. func (shellRunner) Run(name string, args ...string) (string, int) {
  42. out, err := exec.Command(name, args...).Output()
  43. code := 0
  44. if err != nil {
  45. if ee, ok := err.(*exec.ExitError); ok {
  46. code = ee.ExitCode()
  47. } else {
  48. code = -1
  49. }
  50. }
  51. return string(out), code
  52. }
  53. // patrones de validación por campo (sin shell metachars).
  54. var (
  55. reConfig = regexp.MustCompile(`^[a-z_]+$`)
  56. // section: nombre de sección (wifi-iface, interface, eth1) o referencia
  57. // `@tipo[idx]` / `@tipo[-1]`. Los dígitos cubren interfaces UCI reales
  58. // (eth1, wlan0, br-lan). `[-1]` referencia la ÚLTIMA sección del tipo —
  59. // usado tras un uci_add para setear los campos de la sección recién
  60. // creada (patrón OpenWrt estándar).
  61. reSection = regexp.MustCompile(`^(@[a-z0-9_-]+(\[\d+\]|\[-1\])|[a-z0-9_-]+)$`)
  62. reOption = regexp.MustCompile(`^[a-z0-9_]+$`)
  63. // value: alfanumérico + puntos, dos-puntos, barras, hashes, guiones.
  64. // Cubre IPs (192.168.1.1), DNS (1.1.1.1#3001), rutas, MACs, puertos.
  65. reValue = regexp.MustCompile(`^[a-zA-Z0-9_.:/#,-]+$`)
  66. reService = regexp.MustCompile(`^[a-z_-]+$`)
  67. reServiceAct = regexp.MustCompile(`^(restart|reload|enable|disable|start|stop)$`)
  68. rePackage = regexp.MustCompile(`^[a-z0-9_-]+$`)
  69. // Rutas de fichero permitidas para write_file/download/extract/chmod.
  70. // "/root" excluido a propósito (no hace falta para AdGuard y reduce la
  71. // superficie: .ssh/id_rsa etc. no deben ser escribibles).
  72. // Además del regex, Validate aplica filepath.Clean + rechazo de ".." a los
  73. // args marcados como path en opSpec (defense in depth: ".." casa el charset).
  74. reFilePath = regexp.MustCompile(`^/(etc|tmp|usr/bin|usr/lib|var/etc)/[A-Za-z0-9_./-]+$`)
  75. reDirPath = regexp.MustCompile(`^/(etc|tmp|usr/bin|usr/lib|opt|var/etc)/[A-Za-z0-9_./-]+$`)
  76. // Allowlist de dominios de descarga: SOLO releases oficiales de AdGuard.
  77. // Cualquier otra URL (incluida un attacker que controle el plan) se rechaza.
  78. reDownloadURL = regexp.MustCompile(`^https://github\.com/AdguardTeam/AdGuardHome/releases/download/v[0-9]+\.[0-9]+\.[0-9]+/AdGuardHome_linux_[a-z0-9]+\.tar\.gz$`)
  79. reMode = regexp.MustCompile(`^[0-7]{3,4}$`)
  80. // base64 estándar (sin newlines). La validación final la hace base64.Decode.
  81. reBase64 = regexp.MustCompile(`^[A-Za-z0-9+/]+={0,2}$`)
  82. // tcp_check: host (IPv4 o hostname simple) + puerto (1-65535).
  83. reHost = regexp.MustCompile(`^([0-9]{1,3}[.]){3}[0-9]{1,3}$|^[a-zA-Z0-9.-]{1,253}$`)
  84. // rePort valida 1-65535 sin ceros a la izquierda.
  85. rePort = regexp.MustCompile(`^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$`)
  86. )
  87. // opSpec define los args requeridos y su validación para cada Kind.
  88. type opSpec struct {
  89. required map[string]*regexp.Regexp
  90. build func(args map[string]string) (cmd string, cmdArgs []string)
  91. // exec, si está presente, reemplaza a build. Para Kinds que no son un
  92. // simple exec.Command (p. ej. write_file escribe el fichero en Go).
  93. exec func(run Runner, args map[string]string) int
  94. // pathArgs: args que son rutas de fichero/directorio. Validate les aplica
  95. // un check anti-traversal además del regex (filepath.Clean + sin "..").
  96. pathArgs []string
  97. configs func(args map[string]string) []string // UCI configs afectados (para snapshot)
  98. }
  99. var allowlist = map[string]opSpec{
  100. "uci_set": {
  101. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection, "option": reOption, "value": reValue},
  102. build: func(a map[string]string) (string, []string) {
  103. return "uci", []string{"set", fmt.Sprintf("%s.%s.%s=%s", a["config"], a["section"], a["option"], a["value"])}
  104. },
  105. configs: func(a map[string]string) []string { return []string{a["config"]} },
  106. },
  107. "uci_delete": {
  108. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection, "option": reOption},
  109. build: func(a map[string]string) (string, []string) {
  110. return "uci", []string{"delete", fmt.Sprintf("%s.%s.%s", a["config"], a["section"], a["option"])}
  111. },
  112. configs: func(a map[string]string) []string { return []string{a["config"]} },
  113. },
  114. "uci_add_list": {
  115. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection, "option": reOption, "value": reValue},
  116. build: func(a map[string]string) (string, []string) {
  117. return "uci", []string{"add_list", fmt.Sprintf("%s.%s.%s=%s", a["config"], a["section"], a["option"], a["value"])}
  118. },
  119. configs: func(a map[string]string) []string { return []string{a["config"]} },
  120. },
  121. "uci_commit": {
  122. required: map[string]*regexp.Regexp{"config": reConfig},
  123. build: func(a map[string]string) (string, []string) {
  124. return "uci", []string{"commit", a["config"]}
  125. },
  126. configs: func(a map[string]string) []string { return []string{a["config"]} },
  127. },
  128. // uci_add: crea una sección nueva. `uci add <config> <type>` imprime el
  129. // nombre; luego uci_set sobre @<type>[-1] setea sus campos. Necesario para
  130. // crear wifi-iface / network / firewall zone en módulos como WiFi guest.
  131. // type: nombre de sección (wifi-iface, interface, zone, forwarding).
  132. "uci_add": {
  133. required: map[string]*regexp.Regexp{"config": reConfig, "type": reSection},
  134. build: func(a map[string]string) (string, []string) {
  135. return "uci", []string{"add", a["config"], a["type"]}
  136. },
  137. configs: func(a map[string]string) []string { return []string{a["config"]} },
  138. },
  139. // uci_delete_section: borra una sección completa (`uci delete <cfg>.<sec>`),
  140. // a diferencia de uci_delete que quita una option. Útil para revertir un
  141. // módulo que creó secciones (guest network: quitar la wifi-iface, la
  142. // interface, la zone y el forwarding creados al habilitar).
  143. "uci_delete_section": {
  144. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection},
  145. build: func(a map[string]string) (string, []string) {
  146. return "uci", []string{"delete", a["config"] + "." + a["section"]}
  147. },
  148. configs: func(a map[string]string) []string { return []string{a["config"]} },
  149. },
  150. // uci_set_named: crea una SECCIÓN NOMBRADA de un tipo: `uci set
  151. // <config>.<section>=<type>`. Diferencia con uci_add (sección anónima):
  152. // las network interfaces se identifican por su nombre de sección
  153. // (network.guest=interface), mientras que wifi-iface/zone/forwarding
  154. // pueden ser anónimas (referenciadas por índice @tipo[i]).
  155. "uci_set_named": {
  156. required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection, "type": reSection},
  157. build: func(a map[string]string) (string, []string) {
  158. return "uci", []string{"set", a["config"] + "." + a["section"] + "=" + a["type"]}
  159. },
  160. configs: func(a map[string]string) []string { return []string{a["config"]} },
  161. },
  162. "service": {
  163. required: map[string]*regexp.Regexp{"name": reService, "action": reServiceAct},
  164. build: func(a map[string]string) (string, []string) {
  165. return "/etc/init.d/" + a["name"], []string{a["action"]}
  166. },
  167. configs: func(a map[string]string) []string { return nil },
  168. },
  169. "install": {
  170. required: map[string]*regexp.Regexp{"package": rePackage},
  171. build: func(a map[string]string) (string, []string) {
  172. return "opkg", []string{"install", a["package"]}
  173. },
  174. configs: func(a map[string]string) []string { return nil },
  175. },
  176. // apk_install: OpenWrt 24+ usa apk en vez de opkg.
  177. "apk_install": {
  178. required: map[string]*regexp.Regexp{"package": rePackage},
  179. build: func(a map[string]string) (string, []string) {
  180. return "apk", []string{"add", a["package"]}
  181. },
  182. configs: func(a map[string]string) []string { return nil },
  183. },
  184. // download: uclient-fetch (presente en OpenWrt por defecto) con allowlist
  185. // estricta de URL (solo releases oficiales de AdGuard). El dest se valida
  186. // con reFilePath. No shell libre: la URL va como arg, no interpolada.
  187. "download": {
  188. required: map[string]*regexp.Regexp{"url": reDownloadURL, "dest": reFilePath},
  189. pathArgs: []string{"dest"},
  190. build: func(a map[string]string) (string, []string) {
  191. return "uclient-fetch", []string{a["url"], "-O", a["dest"]}
  192. },
  193. configs: func(a map[string]string) []string { return nil },
  194. },
  195. // write_file: escribe contenido base64 a path. Se hace en Go (no shell)
  196. // para evitar inyección vía base64 -d | sh. Path sanitizado + re-chequeo.
  197. // Crea el directorio padre si no existe (MkdirAll, modo 0755) — necesario
  198. // para /etc/AdGuardHome/AdGuardHome.yaml donde el dir no existe aún.
  199. "write_file": {
  200. required: map[string]*regexp.Regexp{"path": reFilePath, "content_b64": reBase64},
  201. pathArgs: []string{"path"},
  202. exec: func(_ Runner, a map[string]string) int {
  203. path := a["path"]
  204. clean := filepath.Clean(path)
  205. if clean != path || !reFilePath.MatchString(clean) || strings.Contains(clean, "..") {
  206. return 1
  207. }
  208. data, err := base64.StdEncoding.DecodeString(a["content_b64"])
  209. if err != nil {
  210. return 1
  211. }
  212. if dir := filepath.Dir(clean); dir != "" && dir != "/" {
  213. if err := os.MkdirAll(dir, 0755); err != nil {
  214. return 1
  215. }
  216. }
  217. if err := os.WriteFile(clean, data, 0644); err != nil {
  218. return 1
  219. }
  220. return 0
  221. },
  222. configs: func(a map[string]string) []string { return nil },
  223. },
  224. // mv: mueve un fichero. src y dest en path allowlist. Necesario para el
  225. // escenario "binary" de AdGuard (extraer tarball y mover el binario a
  226. // /usr/bin/AdGuardHome).
  227. "mv": {
  228. required: map[string]*regexp.Regexp{"src": reFilePath, "dest": reFilePath},
  229. pathArgs: []string{"src", "dest"},
  230. build: func(a map[string]string) (string, []string) {
  231. return "mv", []string{a["src"], a["dest"]}
  232. },
  233. configs: func(a map[string]string) []string { return nil },
  234. },
  235. // extract_tarball: tar -xzf SRC -C DEST.
  236. "extract_tarball": {
  237. required: map[string]*regexp.Regexp{"src": reFilePath, "dest": reDirPath},
  238. pathArgs: []string{"src", "dest"},
  239. build: func(a map[string]string) (string, []string) {
  240. return "tar", []string{"-xzf", a["src"], "-C", a["dest"]}
  241. },
  242. configs: func(a map[string]string) []string { return nil },
  243. },
  244. // chmod: modo octal (3-4 dígitos) + path.
  245. "chmod": {
  246. required: map[string]*regexp.Regexp{"mode": reMode, "path": reFilePath},
  247. pathArgs: []string{"path"},
  248. build: func(a map[string]string) (string, []string) {
  249. return "chmod", []string{a["mode"], a["path"]}
  250. },
  251. configs: func(a map[string]string) []string { return nil },
  252. },
  253. // tcp_check: abre una conexión TCP al host:port. Éxito (exit 0) si conecta
  254. // dentro del budget; fallo (exit 1) si no. Es un healthcheck real de
  255. // servicio (el ping del executor solo confirma red). Usado por módulos que
  256. // abren puerto (AdGuard :3000, Tailscale, OpenVPN...): si el servicio no
  257. // levanta, esta op falla → el executor revierte staged.
  258. // Se hace en Go (no shell) para no depender de nc, que no siempre está en
  259. // OpenWrt stock. Reintenta durante tcpCheckBudget (10 s por defecto) cada
  260. // tcpCheckRetry: un servicio puede tardar unos segundos en abrir puerto
  261. // tras `service start` (AdGuard, Tailscale...).
  262. "tcp_check": {
  263. required: map[string]*regexp.Regexp{"host": reHost, "port": rePort},
  264. exec: func(_ Runner, a map[string]string) int {
  265. addr := net.JoinHostPort(a["host"], a["port"])
  266. start := time.Now()
  267. for time.Since(start) < tcpCheckBudget {
  268. conn, err := net.DialTimeout("tcp", addr, 2*time.Second)
  269. if err == nil {
  270. _ = conn.Close()
  271. return 0
  272. }
  273. time.Sleep(tcpCheckRetry)
  274. }
  275. return 1
  276. },
  277. configs: func(a map[string]string) []string { return nil },
  278. },
  279. // wg_check: healthcheck del módulo WireGuard (10.3). Ejecuta
  280. // `wg show <interface>`; exit 0 si el túnel está arriba en el kernel,
  281. // exit 1 si no existe o está caído. Al final del plan (tras el reload de
  282. // red), una fallo aquí significa que el apply aisló el túnel → el executor
  283. // restaura los snapshots (rollback real, ver Apply).
  284. "wg_check": {
  285. required: map[string]*regexp.Regexp{"interface": reSection},
  286. build: func(a map[string]string) (string, []string) {
  287. return "wg", []string{"show", a["interface"]}
  288. },
  289. configs: func(a map[string]string) []string { return nil },
  290. },
  291. // dawn_check: healthcheck del módulo DAWN. Ejecuta
  292. // `ubus call dawn get_network` y verifica que devuelva JSON no vacío
  293. // con vecinos. Si falla, el executor revierte los snapshots UCI.
  294. "dawn_check": {
  295. exec: func(run Runner, a map[string]string) int {
  296. out, code := run.Run("ubus", "call", "dawn", "get_network")
  297. if code != 0 {
  298. return code
  299. }
  300. out = strings.TrimSpace(out)
  301. if out == "" || out == "{}" {
  302. return 1
  303. }
  304. var v map[string]any
  305. if err := json.Unmarshal([]byte(out), &v); err != nil {
  306. return 1
  307. }
  308. if len(v) == 0 {
  309. return 1
  310. }
  311. return 0
  312. },
  313. configs: func(a map[string]string) []string { return nil },
  314. },
  315. // wifi_reload: aplica cambios en /etc/config/wireless sin reboot.
  316. "wifi_reload": {
  317. build: func(a map[string]string) (string, []string) {
  318. return "/sbin/wifi", []string{"reload"}
  319. },
  320. configs: func(a map[string]string) []string { return nil },
  321. },
  322. }
  323. // tcpCheckBudget / tcpCheckRetry controlan los reintentos del Kind tcp_check.
  324. // Son vars de paquete (no const) para poder acortarlos en tests.
  325. var (
  326. tcpCheckBudget = 10 * time.Second
  327. tcpCheckRetry = 500 * time.Millisecond
  328. )
  329. // Executor aplica Ops allowlistedas con snapshot + healthcheck + rollback.
  330. type Executor struct {
  331. run Runner
  332. now func() time.Time
  333. gwTarget string // IP del gateway para healthcheck (APs)
  334. wanTarget string // IP WAN para healthcheck (gateway)
  335. }
  336. // New crea un ejecutor. gwTarget/wanTarget se usan para el healthcheck
  337. // post-apply (al menos uno debe estar configurado).
  338. func New(gwTarget, wanTarget string) *Executor {
  339. return &Executor{run: shellRunner{}, now: time.Now, gwTarget: gwTarget, wanTarget: wanTarget}
  340. }
  341. // SetRunner inyecta un runner fake (tests).
  342. func (e *Executor) SetRunner(r Runner) { e.run = r }
  343. // SetClock inyecta un reloj (tests).
  344. func (e *Executor) SetClock(f func() time.Time) { e.now = f }
  345. // Validate comprueba que una Op pasa el allowlist sin ejecutarla.
  346. func Validate(op Op) error {
  347. spec, ok := allowlist[op.Kind]
  348. if !ok {
  349. return fmt.Errorf("kind %q no allowlistedado", op.Kind)
  350. }
  351. for arg, re := range spec.required {
  352. val, present := op.Args[arg]
  353. if !present || val == "" {
  354. return fmt.Errorf("arg %q requerido para %s", arg, op.Kind)
  355. }
  356. if !re.MatchString(val) {
  357. return fmt.Errorf("arg %q=%q no válido para %s (no casa con %s)", arg, val, op.Kind, re)
  358. }
  359. }
  360. // Defense in depth: args marcados como path no pueden contener ".." ni
  361. // resolverse a algo distinto tras filepath.Clean (p. ej. "/etc/../x").
  362. for _, arg := range spec.pathArgs {
  363. val := op.Args[arg]
  364. if strings.Contains(val, "..") || filepath.Clean(val) != val {
  365. return fmt.Errorf("arg %q=%q contiene traversal (..) para %s", arg, val, op.Kind)
  366. }
  367. }
  368. return nil
  369. }
  370. // Apply ejecuta una lista de Ops con snapshot, commit y healthcheck.
  371. // Devuelve applied si todo OK, rolled_back si el healthcheck falla, o
  372. // failed si alguna Op falla antes del commit.
  373. func (e *Executor) Apply(ops []Op) ApplyResult {
  374. start := e.now()
  375. // 1. Validar todas las Ops antes de tocar nada.
  376. for _, op := range ops {
  377. if err := Validate(op); err != nil {
  378. return ApplyResult{Status: "failed", Op: op.Desc, Error: err.Error(), DurationMs: ms(e.now(), start)}
  379. }
  380. }
  381. // 2. Snapshot de los configs UCI afectados.
  382. affected := affectedConfigs(ops)
  383. snapshots := map[string]string{}
  384. for _, cfg := range affected {
  385. out, code := e.run.Run("uci", "export", cfg)
  386. if code == 0 && out != "" {
  387. snapshots[cfg] = out
  388. }
  389. }
  390. // 3. Ejecutar Ops (staged, sin commit aún).
  391. for _, op := range ops {
  392. spec := allowlist[op.Kind]
  393. var code int
  394. if spec.exec != nil {
  395. code = spec.exec(e.run, op.Args)
  396. } else {
  397. cmd, cmdArgs := spec.build(op.Args)
  398. _, code = e.run.Run(cmd, cmdArgs...)
  399. }
  400. if code != 0 {
  401. if op.Kind == "wg_check" || op.Kind == "dawn_check" {
  402. // Healthcheck del módulo: rollback real restaurando snapshots UCI
  403. // y relanzando los servicios afectados.
  404. for cfg, snap := range snapshots {
  405. e.run.Run("sh", "-c", fmt.Sprintf("echo '%s' | uci import", snap))
  406. e.run.Run("uci", "commit", cfg)
  407. }
  408. if op.Kind == "wg_check" {
  409. e.run.Run("/etc/init.d/network", "reload")
  410. }
  411. if op.Kind == "dawn_check" {
  412. e.run.Run("/etc/init.d/dawn", "restart")
  413. e.run.Run("/sbin/wifi", "reload")
  414. }
  415. errKey := "wg_check_failed"
  416. if op.Kind == "dawn_check" {
  417. errKey = "dawn_check_failed"
  418. }
  419. return ApplyResult{Status: "rolled_back", Op: op.Desc, Error: errKey, Snapshot: strings.Join(affected, ","), DurationMs: ms(e.now(), start)}
  420. }
  421. // Revert staged changes y salir.
  422. e.revertStaged(affected)
  423. return ApplyResult{Status: "failed", Op: op.Desc, Error: fmt.Sprintf("%s exit %d", op.Kind, code), DurationMs: ms(e.now(), start)}
  424. }
  425. }
  426. // 4. Commit de cada config afectado.
  427. for _, cfg := range affected {
  428. e.run.Run("uci", "commit", cfg)
  429. }
  430. // 5. Healthcheck.
  431. if !e.healthcheck() {
  432. // ROLLBACK: restaurar snapshots.
  433. for cfg, snap := range snapshots {
  434. e.run.Run("sh", "-c", fmt.Sprintf("echo '%s' | uci import", snap))
  435. e.run.Run("uci", "commit", cfg)
  436. }
  437. return ApplyResult{Status: "rolled_back", Error: "healthcheck_failed", Snapshot: strings.Join(affected, ","), DurationMs: ms(e.now(), start)}
  438. }
  439. return ApplyResult{Status: "applied", Snapshot: strings.Join(affected, ","), DurationMs: ms(e.now(), start)}
  440. }
  441. func (e *Executor) revertStaged(configs []string) {
  442. for _, cfg := range configs {
  443. e.run.Run("uci", "revert", cfg)
  444. }
  445. }
  446. func (e *Executor) healthcheck() bool {
  447. target := e.wanTarget
  448. if target == "" {
  449. target = e.gwTarget
  450. }
  451. if target == "" {
  452. return true // sin target configurado: pasar (mejor falso negativo que bloquear)
  453. }
  454. _, code := e.run.Run("ping", "-c", "1", "-W", "3", target)
  455. return code == 0
  456. }
  457. func affectedConfigs(ops []Op) []string {
  458. seen := map[string]bool{}
  459. var out []string
  460. for _, op := range ops {
  461. spec, ok := allowlist[op.Kind]
  462. if !ok {
  463. continue
  464. }
  465. for _, cfg := range spec.configs(op.Args) {
  466. if cfg != "" && !seen[cfg] {
  467. seen[cfg] = true
  468. out = append(out, cfg)
  469. }
  470. }
  471. }
  472. return out
  473. }
  474. func ms(now, start time.Time) int64 {
  475. return now.Sub(start).Milliseconds()
  476. }
  477. // MarshalOps serializa una lista de Ops a JSON (para enviar vía SSE).
  478. func MarshalOps(ops []Op) (string, error) {
  479. b, err := json.Marshal(ops)
  480. return string(b), err
  481. }
  482. // UnmarshalOps deserializa Ops desde JSON (en el agente, al recibir el SSE).
  483. func UnmarshalOps(data string) ([]Op, error) {
  484. var ops []Op
  485. err := json.Unmarshal([]byte(data), &ops)
  486. return ops, err
  487. }