executor.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. // apk_remove: desinstala un paquete con apk (OpenWrt 24+).
  185. "apk_remove": {
  186. required: map[string]*regexp.Regexp{"package": rePackage},
  187. build: func(a map[string]string) (string, []string) {
  188. return "apk", []string{"del", a["package"]}
  189. },
  190. configs: func(a map[string]string) []string { return nil },
  191. },
  192. // opkg_remove: desinstala un paquete con opkg (OpenWrt clásico).
  193. "opkg_remove": {
  194. required: map[string]*regexp.Regexp{"package": rePackage},
  195. build: func(a map[string]string) (string, []string) {
  196. return "opkg", []string{"remove", a["package"]}
  197. },
  198. configs: func(a map[string]string) []string { return nil },
  199. },
  200. // download: uclient-fetch (presente en OpenWrt por defecto) con allowlist
  201. // estricta de URL (solo releases oficiales de AdGuard). El dest se valida
  202. // con reFilePath. No shell libre: la URL va como arg, no interpolada.
  203. "download": {
  204. required: map[string]*regexp.Regexp{"url": reDownloadURL, "dest": reFilePath},
  205. pathArgs: []string{"dest"},
  206. build: func(a map[string]string) (string, []string) {
  207. return "uclient-fetch", []string{a["url"], "-O", a["dest"]}
  208. },
  209. configs: func(a map[string]string) []string { return nil },
  210. },
  211. // write_file: escribe contenido base64 a path. Se hace en Go (no shell)
  212. // para evitar inyección vía base64 -d | sh. Path sanitizado + re-chequeo.
  213. // Crea el directorio padre si no existe (MkdirAll, modo 0755) — necesario
  214. // para /etc/AdGuardHome/AdGuardHome.yaml donde el dir no existe aún.
  215. "write_file": {
  216. required: map[string]*regexp.Regexp{"path": reFilePath, "content_b64": reBase64},
  217. pathArgs: []string{"path"},
  218. exec: func(_ Runner, a map[string]string) int {
  219. path := a["path"]
  220. clean := filepath.Clean(path)
  221. if clean != path || !reFilePath.MatchString(clean) || strings.Contains(clean, "..") {
  222. return 1
  223. }
  224. data, err := base64.StdEncoding.DecodeString(a["content_b64"])
  225. if err != nil {
  226. return 1
  227. }
  228. if dir := filepath.Dir(clean); dir != "" && dir != "/" {
  229. if err := os.MkdirAll(dir, 0755); err != nil {
  230. return 1
  231. }
  232. }
  233. if err := os.WriteFile(clean, data, 0644); err != nil {
  234. return 1
  235. }
  236. return 0
  237. },
  238. configs: func(a map[string]string) []string { return nil },
  239. },
  240. // mv: mueve un fichero. src y dest en path allowlist. Necesario para el
  241. // escenario "binary" de AdGuard (extraer tarball y mover el binario a
  242. // /usr/bin/AdGuardHome).
  243. "mv": {
  244. required: map[string]*regexp.Regexp{"src": reFilePath, "dest": reFilePath},
  245. pathArgs: []string{"src", "dest"},
  246. build: func(a map[string]string) (string, []string) {
  247. return "mv", []string{a["src"], a["dest"]}
  248. },
  249. configs: func(a map[string]string) []string { return nil },
  250. },
  251. // extract_tarball: tar -xzf SRC -C DEST.
  252. "extract_tarball": {
  253. required: map[string]*regexp.Regexp{"src": reFilePath, "dest": reDirPath},
  254. pathArgs: []string{"src", "dest"},
  255. build: func(a map[string]string) (string, []string) {
  256. return "tar", []string{"-xzf", a["src"], "-C", a["dest"]}
  257. },
  258. configs: func(a map[string]string) []string { return nil },
  259. },
  260. // chmod: modo octal (3-4 dígitos) + path.
  261. "chmod": {
  262. required: map[string]*regexp.Regexp{"mode": reMode, "path": reFilePath},
  263. pathArgs: []string{"path"},
  264. build: func(a map[string]string) (string, []string) {
  265. return "chmod", []string{a["mode"], a["path"]}
  266. },
  267. configs: func(a map[string]string) []string { return nil },
  268. },
  269. // tcp_check: abre una conexión TCP al host:port. Éxito (exit 0) si conecta
  270. // dentro del budget; fallo (exit 1) si no. Es un healthcheck real de
  271. // servicio (el ping del executor solo confirma red). Usado por módulos que
  272. // abren puerto (AdGuard :3000, Tailscale, OpenVPN...): si el servicio no
  273. // levanta, esta op falla → el executor revierte staged.
  274. // Se hace en Go (no shell) para no depender de nc, que no siempre está en
  275. // OpenWrt stock. Reintenta durante tcpCheckBudget (10 s por defecto) cada
  276. // tcpCheckRetry: un servicio puede tardar unos segundos en abrir puerto
  277. // tras `service start` (AdGuard, Tailscale...).
  278. "tcp_check": {
  279. required: map[string]*regexp.Regexp{"host": reHost, "port": rePort},
  280. exec: func(_ Runner, a map[string]string) int {
  281. addr := net.JoinHostPort(a["host"], a["port"])
  282. start := time.Now()
  283. for time.Since(start) < tcpCheckBudget {
  284. conn, err := net.DialTimeout("tcp", addr, 2*time.Second)
  285. if err == nil {
  286. _ = conn.Close()
  287. return 0
  288. }
  289. time.Sleep(tcpCheckRetry)
  290. }
  291. return 1
  292. },
  293. configs: func(a map[string]string) []string { return nil },
  294. },
  295. // wg_check: healthcheck del módulo WireGuard (10.3). Ejecuta
  296. // `wg show <interface>`; exit 0 si el túnel está arriba en el kernel,
  297. // exit 1 si no existe o está caído. Al final del plan (tras el reload de
  298. // red), una fallo aquí significa que el apply aisló el túnel → el executor
  299. // restaura los snapshots (rollback real, ver Apply).
  300. "wg_check": {
  301. required: map[string]*regexp.Regexp{"interface": reSection},
  302. build: func(a map[string]string) (string, []string) {
  303. return "wg", []string{"show", a["interface"]}
  304. },
  305. configs: func(a map[string]string) []string { return nil },
  306. },
  307. // dawn_check: healthcheck del módulo DAWN. Ejecuta
  308. // `ubus call dawn get_network` y verifica que devuelva JSON no vacío
  309. // con vecinos. Si falla, el executor revierte los snapshots UCI.
  310. "dawn_check": {
  311. exec: func(run Runner, a map[string]string) int {
  312. out, code := run.Run("ubus", "call", "dawn", "get_network")
  313. if code != 0 {
  314. return code
  315. }
  316. out = strings.TrimSpace(out)
  317. if out == "" || out == "{}" {
  318. return 1
  319. }
  320. var v map[string]any
  321. if err := json.Unmarshal([]byte(out), &v); err != nil {
  322. return 1
  323. }
  324. if len(v) == 0 {
  325. return 1
  326. }
  327. return 0
  328. },
  329. configs: func(a map[string]string) []string { return nil },
  330. },
  331. // usteer_check: healthcheck del módulo usteer. Ejecuta
  332. // `ubus call usteer remote_hosts` y verifica que devuelva JSON no vacío.
  333. // Si falla, el executor revierte los snapshots UCI.
  334. "usteer_check": {
  335. exec: func(run Runner, a map[string]string) int {
  336. out, code := run.Run("ubus", "call", "usteer", "remote_hosts")
  337. if code != 0 {
  338. return code
  339. }
  340. out = strings.TrimSpace(out)
  341. if out == "" || out == "{}" {
  342. return 1
  343. }
  344. var v map[string]any
  345. if err := json.Unmarshal([]byte(out), &v); err != nil {
  346. return 1
  347. }
  348. if len(v) == 0 {
  349. return 1
  350. }
  351. return 0
  352. },
  353. configs: func(a map[string]string) []string { return nil },
  354. },
  355. // wifi_reload: aplica cambios en /etc/config/wireless sin reboot.
  356. "wifi_reload": {
  357. build: func(a map[string]string) (string, []string) {
  358. return "/sbin/wifi", []string{"reload"}
  359. },
  360. configs: func(a map[string]string) []string { return nil },
  361. },
  362. }
  363. // tcpCheckBudget / tcpCheckRetry controlan los reintentos del Kind tcp_check.
  364. // Son vars de paquete (no const) para poder acortarlos en tests.
  365. var (
  366. tcpCheckBudget = 10 * time.Second
  367. tcpCheckRetry = 500 * time.Millisecond
  368. )
  369. // Executor aplica Ops allowlistedas con snapshot + healthcheck + rollback.
  370. type Executor struct {
  371. run Runner
  372. now func() time.Time
  373. gwTarget string // IP del gateway para healthcheck (APs)
  374. wanTarget string // IP WAN para healthcheck (gateway)
  375. }
  376. // New crea un ejecutor. gwTarget/wanTarget se usan para el healthcheck
  377. // post-apply (al menos uno debe estar configurado).
  378. func New(gwTarget, wanTarget string) *Executor {
  379. return &Executor{run: shellRunner{}, now: time.Now, gwTarget: gwTarget, wanTarget: wanTarget}
  380. }
  381. // SetRunner inyecta un runner fake (tests).
  382. func (e *Executor) SetRunner(r Runner) { e.run = r }
  383. // SetClock inyecta un reloj (tests).
  384. func (e *Executor) SetClock(f func() time.Time) { e.now = f }
  385. // Validate comprueba que una Op pasa el allowlist sin ejecutarla.
  386. func Validate(op Op) error {
  387. spec, ok := allowlist[op.Kind]
  388. if !ok {
  389. return fmt.Errorf("kind %q no allowlistedado", op.Kind)
  390. }
  391. for arg, re := range spec.required {
  392. val, present := op.Args[arg]
  393. if !present || val == "" {
  394. return fmt.Errorf("arg %q requerido para %s", arg, op.Kind)
  395. }
  396. if !re.MatchString(val) {
  397. return fmt.Errorf("arg %q=%q no válido para %s (no casa con %s)", arg, val, op.Kind, re)
  398. }
  399. }
  400. // Defense in depth: args marcados como path no pueden contener ".." ni
  401. // resolverse a algo distinto tras filepath.Clean (p. ej. "/etc/../x").
  402. for _, arg := range spec.pathArgs {
  403. val := op.Args[arg]
  404. if strings.Contains(val, "..") || filepath.Clean(val) != val {
  405. return fmt.Errorf("arg %q=%q contiene traversal (..) para %s", arg, val, op.Kind)
  406. }
  407. }
  408. return nil
  409. }
  410. // Apply ejecuta una lista de Ops con snapshot, commit y healthcheck.
  411. // Devuelve applied si todo OK, rolled_back si el healthcheck falla, o
  412. // failed si alguna Op falla antes del commit.
  413. func (e *Executor) Apply(ops []Op) ApplyResult {
  414. start := e.now()
  415. // 1. Validar todas las Ops antes de tocar nada.
  416. for _, op := range ops {
  417. if err := Validate(op); err != nil {
  418. return ApplyResult{Status: "failed", Op: op.Desc, Error: err.Error(), DurationMs: ms(e.now(), start)}
  419. }
  420. }
  421. // 2. Snapshot de los configs UCI afectados.
  422. affected := affectedConfigs(ops)
  423. snapshots := map[string]string{}
  424. for _, cfg := range affected {
  425. out, code := e.run.Run("uci", "export", cfg)
  426. if code == 0 && out != "" {
  427. snapshots[cfg] = out
  428. }
  429. }
  430. // 3. Ejecutar Ops (staged, sin commit aún).
  431. for _, op := range ops {
  432. spec := allowlist[op.Kind]
  433. var code int
  434. if spec.exec != nil {
  435. code = spec.exec(e.run, op.Args)
  436. } else {
  437. cmd, cmdArgs := spec.build(op.Args)
  438. _, code = e.run.Run(cmd, cmdArgs...)
  439. }
  440. if code != 0 {
  441. if op.Kind == "wg_check" || op.Kind == "dawn_check" || op.Kind == "usteer_check" {
  442. // Healthcheck del módulo: rollback real restaurando snapshots UCI
  443. // y relanzando los servicios afectados.
  444. for cfg, snap := range snapshots {
  445. e.run.Run("sh", "-c", fmt.Sprintf("echo '%s' | uci import", snap))
  446. e.run.Run("uci", "commit", cfg)
  447. }
  448. if op.Kind == "wg_check" {
  449. e.run.Run("/etc/init.d/network", "reload")
  450. }
  451. if op.Kind == "dawn_check" {
  452. e.run.Run("/etc/init.d/dawn", "restart")
  453. e.run.Run("/sbin/wifi", "reload")
  454. }
  455. if op.Kind == "usteer_check" {
  456. e.run.Run("/etc/init.d/usteer", "restart")
  457. e.run.Run("/sbin/wifi", "reload")
  458. }
  459. errKey := "wg_check_failed"
  460. if op.Kind == "dawn_check" {
  461. errKey = "dawn_check_failed"
  462. }
  463. if op.Kind == "usteer_check" {
  464. errKey = "usteer_check_failed"
  465. }
  466. return ApplyResult{Status: "rolled_back", Op: op.Desc, Error: errKey, Snapshot: strings.Join(affected, ","), DurationMs: ms(e.now(), start)}
  467. }
  468. // Revert staged changes y salir.
  469. e.revertStaged(affected)
  470. return ApplyResult{Status: "failed", Op: op.Desc, Error: fmt.Sprintf("%s exit %d", op.Kind, code), DurationMs: ms(e.now(), start)}
  471. }
  472. }
  473. // 4. Commit de cada config afectado.
  474. for _, cfg := range affected {
  475. e.run.Run("uci", "commit", cfg)
  476. }
  477. // 5. Healthcheck.
  478. if !e.healthcheck() {
  479. // ROLLBACK: restaurar snapshots.
  480. for cfg, snap := range snapshots {
  481. e.run.Run("sh", "-c", fmt.Sprintf("echo '%s' | uci import", snap))
  482. e.run.Run("uci", "commit", cfg)
  483. }
  484. return ApplyResult{Status: "rolled_back", Error: "healthcheck_failed", Snapshot: strings.Join(affected, ","), DurationMs: ms(e.now(), start)}
  485. }
  486. return ApplyResult{Status: "applied", Snapshot: strings.Join(affected, ","), DurationMs: ms(e.now(), start)}
  487. }
  488. func (e *Executor) revertStaged(configs []string) {
  489. for _, cfg := range configs {
  490. e.run.Run("uci", "revert", cfg)
  491. }
  492. }
  493. func (e *Executor) healthcheck() bool {
  494. target := e.wanTarget
  495. if target == "" {
  496. target = e.gwTarget
  497. }
  498. if target == "" {
  499. return true // sin target configurado: pasar (mejor falso negativo que bloquear)
  500. }
  501. _, code := e.run.Run("ping", "-c", "1", "-W", "3", target)
  502. return code == 0
  503. }
  504. func affectedConfigs(ops []Op) []string {
  505. seen := map[string]bool{}
  506. var out []string
  507. for _, op := range ops {
  508. spec, ok := allowlist[op.Kind]
  509. if !ok {
  510. continue
  511. }
  512. for _, cfg := range spec.configs(op.Args) {
  513. if cfg != "" && !seen[cfg] {
  514. seen[cfg] = true
  515. out = append(out, cfg)
  516. }
  517. }
  518. }
  519. return out
  520. }
  521. func ms(now, start time.Time) int64 {
  522. return now.Sub(start).Milliseconds()
  523. }
  524. // MarshalOps serializa una lista de Ops a JSON (para enviar vía SSE).
  525. func MarshalOps(ops []Op) (string, error) {
  526. b, err := json.Marshal(ops)
  527. return string(b), err
  528. }
  529. // UnmarshalOps deserializa Ops desde JSON (en el agente, al recibir el SSE).
  530. func UnmarshalOps(data string) ([]Op, error) {
  531. var ops []Op
  532. err := json.Unmarshal([]byte(data), &ops)
  533. return ops, err
  534. }