script_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. // script_test.go — contrato de reinstall.Script (#463/#457): instalación
  2. // completa del agente (binario verificado, init self-heal, watchdog, cron).
  3. package reinstall_test
  4. import (
  5. "os"
  6. "os/exec"
  7. "path/filepath"
  8. "strings"
  9. "testing"
  10. "github.com/gnacho/netpulse/server-go/internal/reinstall"
  11. )
  12. func scriptForTest() string {
  13. return reinstall.Script(
  14. "test-router",
  15. strings.Repeat("a1", 32), // 64 hex como un token real
  16. "http://192.168.1.226:3000",
  17. "",
  18. map[string]string{
  19. "arm64": "cafebabe",
  20. "arm": "deadbeef",
  21. "amd64": "abcd1234",
  22. "mipsle": "0123feed",
  23. "mips": "4567beef",
  24. },
  25. )
  26. }
  27. func TestScriptConfig(t *testing.T) {
  28. s := scriptForTest()
  29. for _, want := range []string{
  30. `SERVER="http://192.168.1.226:3000"`,
  31. `SLUG="test-router"`,
  32. `NETPULSE_SERVER=$SERVER`,
  33. `NETPULSE_SLUG=$SLUG`,
  34. `NETPULSE_TOKEN=$TOKEN`,
  35. "chmod 600 \"$ENV_FILE\"",
  36. } {
  37. if !strings.Contains(s, want) {
  38. t.Errorf("script sin %q", want)
  39. }
  40. }
  41. }
  42. // #851: el env generado documenta las opciones disponibles como líneas
  43. // comentadas con sus defaults.
  44. func TestScriptEnvDocumentsDefaults(t *testing.T) {
  45. s := scriptForTest()
  46. for _, want := range []string{
  47. "# NETPULSE_INTERVAL=30",
  48. `# NETPULSE_SCAN_INTERVAL: "0" = sin scans periódicos`,
  49. "NETPULSE_SCAN_INTERVAL=$SCAN_VALUE",
  50. "# NETPULSE_WAN_TARGET=1.1.1.1",
  51. "# NETPULSE_GW_TARGET=192.168.8.1",
  52. "# NETPULSE_HEARTBEAT_FILE=/tmp/netpulse-agent.heartbeat",
  53. } {
  54. if !strings.Contains(s, want) {
  55. t.Errorf("env generado sin %q", want)
  56. }
  57. }
  58. }
  59. // #851: el rewrite del env conserva las NETPULSE_* del usuario (p. ej.
  60. // NETPULSE_SCAN_INTERVAL=0) en vez de pisarlas.
  61. // TestScriptWritesActiveTargets (#1204): con objetivos resueltos por el
  62. // server, el env lleva las líneas ACTIVAS (no comentadas); sin objetivos,
  63. // siguen documentadas como antes.
  64. func TestScriptWritesActiveTargets(t *testing.T) {
  65. slug, token, url, fp := "test-router", strings.Repeat("a1", 32), "http://192.168.1.226:3000", ""
  66. digests := map[string]string{"arm64": "cafebabe"}
  67. withWan := reinstall.ScriptWithTargets(slug, token, url, fp, digests, reinstall.WanTargets{WanTarget: "1.1.1.1"})
  68. if !strings.Contains(withWan, "\nNETPULSE_WAN_TARGET=1.1.1.1\n") {
  69. t.Errorf("gateway sin línea WAN activa")
  70. }
  71. if strings.Contains(withWan, "\nNETPULSE_GW_TARGET=") {
  72. t.Errorf("el gateway no debe llevar GW_TARGET activo")
  73. }
  74. withGw := reinstall.ScriptWithTargets(slug, token, url, fp, digests, reinstall.WanTargets{GwTarget: "192.168.1.1"})
  75. if !strings.Contains(withGw, "\nNETPULSE_GW_TARGET=192.168.1.1\n") {
  76. t.Errorf("AP sin línea GW activa")
  77. }
  78. if strings.Contains(withGw, "\nNETPULSE_WAN_TARGET=") {
  79. t.Errorf("el AP no debe llevar WAN_TARGET activo")
  80. }
  81. plain := scriptForTest()
  82. if !strings.Contains(plain, "# NETPULSE_WAN_TARGET=1.1.1.1") || !strings.Contains(plain, "# NETPULSE_GW_TARGET=192.168.8.1") {
  83. t.Errorf("sin objetivos las líneas deben seguir comentadas")
  84. }
  85. }
  86. func TestScriptPreservesUserVars(t *testing.T) {
  87. s := scriptForTest()
  88. for _, want := range []string{
  89. `USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+=' "$ENV_FILE"`,
  90. `grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN|WAN_TARGET|GW_TARGET|SCAN_INTERVAL)='`,
  91. `printf '%s\n' "$USER_VARS" >> "$ENV_FILE"`,
  92. } {
  93. if !strings.Contains(s, want) {
  94. t.Errorf("script sin preservación de vars de usuario: falta %q", want)
  95. }
  96. }
  97. }
  98. func TestScriptArchAndDigests(t *testing.T) {
  99. s := scriptForTest()
  100. for _, want := range []string{
  101. "aarch64|arm64) GOARCH=arm64; SHA256=\"cafebabe\"",
  102. "armv7l|armv7|armhf|arm) GOARCH=arm; SHA256=\"deadbeef\"",
  103. "x86_64|amd64) GOARCH=amd64; SHA256=\"abcd1234\"",
  104. `/api/agents/$SLUG/binary?arch=$GOARCH`,
  105. } {
  106. if !strings.Contains(s, want) {
  107. t.Errorf("script sin %q", want)
  108. }
  109. }
  110. if strings.Contains(s, "arch=armv7\"") {
  111. t.Error("el script no debe pedir arch=armv7 (normalizeArch espera arm)")
  112. }
  113. // #488: uname -m "mips" no distingue endianness; el script lo detecta
  114. // con el byte EI_DATA del ELF y mapea a mipsle/mips con su digest.
  115. for _, want := range []string{
  116. `1) GOARCH=mipsle; SHA256="0123feed"`,
  117. `2) GOARCH=mips; SHA256="4567beef"`,
  118. `head -c 6 /bin/sh | tail -c 1 | tr '\001\002' '12'`,
  119. } {
  120. if !strings.Contains(s, want) {
  121. t.Errorf("script sin %q", want)
  122. }
  123. }
  124. if strings.Count(s, "mipsle") < 2 {
  125. t.Errorf("el self-heal del init también debe resolver mipsle (apariciones: %d)",
  126. strings.Count(s, "mipsle"))
  127. }
  128. if !strings.Contains(s, `GOT=$(sha256sum /tmp/netpulse-agent.new | awk '{print $1}')`) {
  129. t.Error("sin verificación sha256sum")
  130. }
  131. if !strings.Contains(s, "exit 21") {
  132. t.Error("sin código de salida 21 para sha256 mismatch")
  133. }
  134. }
  135. func TestScriptSelfHealInit(t *testing.T) {
  136. s := scriptForTest()
  137. for _, want := range []string{
  138. "selfheal_binary()",
  139. `url="${NETPULSE_SERVER%/}/api/agents/${NETPULSE_SLUG}/binary?arch=${ARCH}"`,
  140. "logger -t netpulse-agent \"self-heal: binario restaurado\"",
  141. "selfheal_binary || logger -t netpulse-agent \"self-heal: no se pudo restaurar el binario\"",
  142. } {
  143. if !strings.Contains(s, want) {
  144. t.Errorf("init sin self-heal: falta %q", want)
  145. }
  146. }
  147. if strings.Count(s, "armv7l|armv7|armhf|arm") != 2 {
  148. t.Errorf("case de arch incompleto (apariciones: %d, esperadas 2)",
  149. strings.Count(s, "armv7l|armv7|armhf|arm"))
  150. }
  151. }
  152. // #879: el init entregado por el reinstall auto-repara la entrada de cron del
  153. // antiguo watchdog (tras sysupgrade /etc sobrevive pero el binario no, y cron
  154. // loguearía un comando inexistente cada 2 min).
  155. func TestScriptInitSelfHealsStaleWatchdogCron(t *testing.T) {
  156. s := scriptForTest()
  157. for _, want := range []string{
  158. "cleanup_stale_watchdog_cron()",
  159. "[ -f /usr/sbin/netpulse-watchdog ] && return 0",
  160. "crontab -l 2>/dev/null | grep -q netpulse-watchdog || return 0",
  161. "cleanup_stale_watchdog_cron",
  162. } {
  163. if !strings.Contains(s, want) {
  164. t.Errorf("init sin self-heal #879: falta %q", want)
  165. }
  166. }
  167. }
  168. // #851: el watchdog cron YA NO se instala; el script limpia los restos de
  169. // instalaciones previas que sí lo tenían.
  170. func TestScriptNoWatchdogCron(t *testing.T) {
  171. s := scriptForTest()
  172. for _, notWant := range []string{
  173. "*/2 * * * *",
  174. "proceso vivo pero sin latido",
  175. `echo '*/2`,
  176. "/etc/init.d/cron restart",
  177. } {
  178. if strings.Contains(s, notWant) {
  179. t.Errorf("script con watchdog/cron (%q) pese a #851", notWant)
  180. }
  181. }
  182. for _, want := range []string{
  183. `rm -f /usr/sbin/netpulse-watchdog`,
  184. `sed -i '/netpulse-watchdog/d' /etc/crontabs/root`,
  185. } {
  186. if !strings.Contains(s, want) {
  187. t.Errorf("script sin limpieza legacy del watchdog: falta %q", want)
  188. }
  189. }
  190. }
  191. func TestScriptFinishesWithStart(t *testing.T) {
  192. s := scriptForTest()
  193. // #1476: entre enable y restart va la preservación en sysupgrade.conf, así
  194. // que el final ya no es la pareja literal; lo que importa es que el último
  195. // gesto sea arrancar el servicio y que el enable vaya antes.
  196. if !strings.HasSuffix(strings.TrimSpace(s), "\"$INIT\" restart") {
  197. t.Error("el script debe terminar con el restart del servicio")
  198. }
  199. if strings.Index(s, `"$INIT" enable`) > strings.LastIndex(s, `"$INIT" restart`) {
  200. t.Error("el script debe habilitar el servicio antes de reiniciarlo")
  201. }
  202. }
  203. func TestTokenPushScriptConfig(t *testing.T) {
  204. s := reinstall.TokenPushScript("test-router", strings.Repeat("c3", 32))
  205. for _, want := range []string{
  206. "/etc/netpulse-agent.env",
  207. "NETPULSE_TOKEN=" + strings.Repeat("c3", 32),
  208. "sed -n 's/^NETPULSE_SERVER=//p' \"$ENV_FILE\"",
  209. "sed -n 's/^NETPULSE_SLUG=//p' \"$ENV_FILE\"",
  210. // #851: preservar FP y NETPULSE_* del usuario (p. ej. SCAN_INTERVAL).
  211. "sed -n 's/^NETPULSE_SERVER_FP=//p' \"$ENV_FILE\"",
  212. `printf '%s\n' "$USER_VARS" >> "$ENV_FILE.tmp"`,
  213. "chmod 600 \"$ENV_FILE.tmp\"",
  214. "mv -f \"$ENV_FILE.tmp\" \"$ENV_FILE\"",
  215. "\"$INIT\" restart",
  216. "exit 30",
  217. "exit 31",
  218. } {
  219. if !strings.Contains(s, want) {
  220. t.Errorf("TokenPushScript sin %q", want)
  221. }
  222. }
  223. // No debe descargar binario ni tocar el init (rotate ligero).
  224. if strings.Contains(s, "/binary?arch=") {
  225. t.Error("TokenPushScript no debe descargar el binario")
  226. }
  227. for _, notWant := range []string{"*/2 * * * *", "GOT=$(sha256sum"} {
  228. if strings.Contains(s, notWant) {
  229. t.Errorf("TokenPushScript no debe contener %q (rotate ligero)", notWant)
  230. }
  231. }
  232. }
  233. func TestScriptEmptyDigestSkipsVerify(t *testing.T) {
  234. s := reinstall.Script(
  235. "r", strings.Repeat("b2", 32), "http://s:3000", "",
  236. map[string]string{"arm64": "", "arm": "", "amd64": ""},
  237. )
  238. if !strings.Contains(s, `GOARCH=arm64; SHA256=""`) {
  239. t.Error("sin digest, SHA256 debe quedar vacío")
  240. }
  241. if !strings.Contains(s, `if [ -n "$SHA256" ]; then`) {
  242. t.Error("la verificación debe estar protegida contra digest vacío")
  243. }
  244. }
  245. func TestScriptSelfHealVerifiesDigest(t *testing.T) {
  246. s := reinstall.Script(
  247. "r", strings.Repeat("b2", 32), "https://np.example.org", strings.Repeat("c1", 32),
  248. map[string]string{"arm64": "x", "arm": "x", "amd64": "x"},
  249. )
  250. for _, want := range []string{
  251. "x-checksum-sha256:",
  252. `sha256sum "$tmp"`,
  253. "self-heal: sin X-Checksum-Sha256 válido, binario descartado",
  254. "self-heal: SHA-256 no coincide, binario descartado",
  255. } {
  256. if !strings.Contains(s, want) {
  257. t.Errorf("init embebido sin %q en el self-heal", want)
  258. }
  259. }
  260. }
  261. func TestSelfHealRequiresHTTPSOrExplicitOptIn(t *testing.T) {
  262. want := []string{
  263. `[ "${NETPULSE_ALLOW_INSECURE_COMMANDS:-}" = "1" ]`,
  264. "self-heal: HTTP sin NETPULSE_ALLOW_INSECURE_COMMANDS=1, binario no descargado",
  265. }
  266. generated := scriptForTest()
  267. for _, w := range want {
  268. if !strings.Contains(generated, w) {
  269. t.Errorf("init generado sin guarda de transporte: falta %q", w)
  270. }
  271. }
  272. for _, path := range []string{
  273. "../../../agent/deploy/netpulse-agent.init",
  274. "../../../install-agent.sh",
  275. } {
  276. b, err := os.ReadFile(filepath.Clean(path))
  277. if err != nil {
  278. t.Fatalf("leyendo %s: %v", path, err)
  279. }
  280. for _, w := range want {
  281. if !strings.Contains(string(b), w) {
  282. t.Errorf("%s sin guarda de transporte: falta %q", path, w)
  283. }
  284. }
  285. }
  286. }
  287. // #851: con server https y FP derivado, el .env generado debe llevar
  288. // NETPULSE_SERVER_FP o el agente entra en bucle fatal al arrancar.
  289. func TestScriptIncludesServerFP(t *testing.T) {
  290. fp := strings.Repeat("c1", 32)
  291. s := reinstall.Script(
  292. "r", strings.Repeat("b2", 32), "https://np.example.org:3443", fp,
  293. map[string]string{"arm64": "x"},
  294. )
  295. for _, want := range []string{
  296. `SERVER="https://np.example.org:3443"`,
  297. `SERVER_FP="` + fp + `"`,
  298. `echo "NETPULSE_SERVER_FP=$SERVER_FP" >> "$ENV_FILE"`,
  299. } {
  300. if !strings.Contains(s, want) {
  301. t.Errorf("script con FP sin %q", want)
  302. }
  303. }
  304. }
  305. // #851: http plano o FP no derivable → script sin FP (comportamiento previo).
  306. func TestScriptEmptyFPSkipsFPLine(t *testing.T) {
  307. for _, u := range []string{"http://192.168.1.226:3000", "https://np.example.org"} {
  308. s := reinstall.Script("r", "tok", u, "", map[string]string{"arm64": "x"})
  309. if !strings.Contains(s, `SERVER_FP=""`) {
  310. t.Errorf("script sin %q para %q", `SERVER_FP=""`, u)
  311. }
  312. if !strings.Contains(s, `if [ -n "$SERVER_FP" ]; then`) {
  313. t.Errorf("script sin guard de FP para %q", u)
  314. }
  315. if strings.Contains(s, "NETPULSE_SERVER_FP=c1") {
  316. t.Errorf("script con FP concreto pese a FP vacío (%q)", u)
  317. }
  318. }
  319. }
  320. // #851: el rotate del token debe conservar el FP del env existente; si se
  321. // pierde, el agente cae en el bucle fatal de "HTTPS requiere NETPULSE_SERVER_FP".
  322. func TestTokenPushPreservesServerFP(t *testing.T) {
  323. s := reinstall.TokenPushScript("test-router", strings.Repeat("c3", 32))
  324. for _, want := range []string{
  325. `sed -n 's/^NETPULSE_SERVER_FP=//p' "$ENV_FILE"`,
  326. `echo "NETPULSE_SERVER_FP=$FP" >> "$ENV_FILE.tmp"`,
  327. } {
  328. if !strings.Contains(s, want) {
  329. t.Errorf("TokenPushScript sin %q", want)
  330. }
  331. }
  332. }
  333. // FORK: with a Trust the script moves the agent to the HTTPS address, writes
  334. // the root to the router, verifies its downloads - including the self-heal's
  335. // - against it, and pins the server. Without one nothing of that appears.
  336. func TestScriptWithTrust(t *testing.T) {
  337. root := "-----BEGIN CERTIFICATE-----\nMIIBtestroot\n-----END CERTIFICATE-----\n"
  338. fp := strings.Repeat("ab", 32)
  339. // A pin derived for the old address is replaced by the trust's.
  340. s := reinstall.Script("test-router", strings.Repeat("a1", 32), "http://192.0.2.10:3000", strings.Repeat("99", 32),
  341. map[string]string{}, reinstall.Trust{ServerURL: "https://192.0.2.10:3443", ServerFP: fp, CAPEM: []byte(root)})
  342. for _, want := range []string{
  343. `SERVER="https://192.0.2.10:3443"`,
  344. "cat > /etc/netpulse-ca.pem <<'CAEOF'\n" + strings.TrimSpace(root) + "\nCAEOF",
  345. `curl -fsSL $CURL_TLS`,
  346. `wget -q $WGET_TLS`,
  347. `SERVER_FP="` + fp + `"`,
  348. `ctls="--cacert /etc/netpulse-ca.pem"`,
  349. } {
  350. if !strings.Contains(s, want) {
  351. t.Errorf("script lacks %q", want)
  352. }
  353. }
  354. if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
  355. t.Fatalf("not valid sh: %v\n%s", err, out)
  356. }
  357. plain := reinstall.Script("test-router", strings.Repeat("a1", 32), "http://192.0.2.10:3000", "", map[string]string{})
  358. if !strings.Contains(plain, "rm -f /etc/netpulse-ca.pem") {
  359. t.Error("a script without a root leaves a stale one on the router")
  360. }
  361. if strings.Contains(s, "rm -f /etc/netpulse-ca.pem") {
  362. t.Error("a script with a root removes it")
  363. }
  364. if strings.Contains(s, strings.Repeat("99", 32)) {
  365. t.Error("the pin passed in survived the trust's")
  366. }
  367. if !strings.Contains(plain, `SERVER_FP=""`) {
  368. t.Error("a script without a pin sets one")
  369. }
  370. for _, notWant := range []string{"CAEOF", "https://"} {
  371. if strings.Contains(plain, notWant) {
  372. t.Errorf("a script without Trust contains %q", notWant)
  373. }
  374. }
  375. if out, err := exec.Command("sh", "-n", "-c", plain).CombinedOutput(); err != nil {
  376. t.Fatalf("not valid sh: %v\n%s", err, out)
  377. }
  378. }
  379. // #1294: EnvScript es la variante ligera: mismo env gestionado (y mismas
  380. // vars de usuario conservadas) que el script completo, pero SIN descargar
  381. // binario ni reescribir el init: solo CA + env + restart del agente.
  382. func TestEnvScriptIsLightweight(t *testing.T) {
  383. full := scriptForTest()
  384. env := reinstall.EnvScript("test-router", strings.Repeat("a1", 32),
  385. "http://192.168.1.226:3000", "", reinstall.WanTargets{})
  386. // Lleva lo esencial del env gestionado.
  387. for _, want := range []string{
  388. `SERVER="http://192.168.1.226:3000"`,
  389. "NETPULSE_SERVER=$SERVER",
  390. "NETPULSE_TOKEN=$TOKEN",
  391. `chmod 600 "$ENV_FILE"`,
  392. // conserva las NETPULSE_* del usuario (#851)
  393. `USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+='`,
  394. // restart para que el agente relea el env
  395. `"$INIT" restart`,
  396. } {
  397. if !strings.Contains(env, want) {
  398. t.Errorf("EnvScript sin %q", want)
  399. }
  400. }
  401. // NO descarga binario ni toca el init (eso es del reinstall completo).
  402. for _, unwanted := range []string{
  403. "/api/agents/$SLUG/binary",
  404. "INITEOF",
  405. "selfheal_binary",
  406. "sha256sum",
  407. } {
  408. if strings.Contains(env, unwanted) {
  409. t.Errorf("EnvScript NO debería contener %q (variante ligera)", unwanted)
  410. }
  411. }
  412. // El bloque del env es literalmente el compartido con el script completo.
  413. if !strings.Contains(full, `USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+='`) {
  414. t.Errorf("script completo perdió el bloque de env compartido")
  415. }
  416. }
  417. // #1294: con trust HTTPS se escribe la CA raíz; sin trust se BORRA la que
  418. // pudiera quedar de una instalación anterior (mismo gesto que el completo).
  419. func TestEnvScriptTrustCA(t *testing.T) {
  420. tr := reinstall.Trust{ServerURL: "https://np.local:3443", ServerFP: "fingerprint",
  421. CAPEM: []byte("-----BEGIN CERTIFICATE-----\nMIIB fake\n-----END CERTIFICATE-----")}
  422. s := reinstall.EnvScript("ap1", "tok", "http://192.168.1.226:3000", "", reinstall.WanTargets{}, tr)
  423. for _, want := range []string{
  424. `SERVER="https://np.local:3443"`,
  425. "MIIB fake",
  426. `SERVER_FP="fingerprint"`,
  427. "NETPULSE_SERVER_FP=$SERVER_FP",
  428. } {
  429. if !strings.Contains(s, want) {
  430. t.Errorf("EnvScript con trust sin %q", want)
  431. }
  432. }
  433. noTrust := reinstall.EnvScript("ap1", "tok", "http://192.168.1.226:3000", "", reinstall.WanTargets{})
  434. if !strings.Contains(noTrust, "rm -f /etc/netpulse-ca.pem") {
  435. t.Errorf("EnvScript sin trust debe borrar la CA previa")
  436. }
  437. }
  438. // #1476: en una actualización de imagen se perdían el init y el env porque no
  439. // estaban en /etc/sysupgrade.conf (OpenWrt solo conserva conffiles de paquetes,
  440. // ese fichero y /lib/upgrade/keep.d/*). El script los añade, sin duplicar
  441. // líneas, después del enable (los symlinks de /etc/rc.d ya existen) y antes del
  442. // restart final.
  443. func TestScriptPreservesOnSysupgrade(t *testing.T) {
  444. s := scriptForTest()
  445. for _, want := range []string{
  446. "P=/etc/sysupgrade.conf",
  447. `ensure_sysupgrade() { grep -qxF "$1" "$P" 2>/dev/null || echo "$1" >> "$P"; }`,
  448. "ensure_sysupgrade /usr/sbin/netpulse-agent",
  449. "ensure_sysupgrade /etc/netpulse-agent.env",
  450. "ensure_sysupgrade /etc/init.d/netpulse-agent",
  451. `for f in /etc/rc.d/*netpulse-agent*; do [ -e "$f" ] && ensure_sysupgrade "$f"; done`,
  452. } {
  453. if !strings.Contains(s, want) {
  454. t.Errorf("script sin %q", want)
  455. }
  456. }
  457. enable := strings.Index(s, `"$INIT" enable`)
  458. preserve := strings.Index(s, "ensure_sysupgrade /etc/init.d/netpulse-agent")
  459. restart := strings.LastIndex(s, `"$INIT" restart`)
  460. if !(enable >= 0 && preserve > enable && preserve < restart) {
  461. t.Errorf("orden inesperado: enable=%d preserve=%d restart=%d", enable, preserve, restart)
  462. }
  463. }
  464. // #1476: la variante ligera (EnvScript, que corre en la migración a HTTPS
  465. // sobre toda la flota) también escribe las entradas, para curar instalaciones
  466. // antiguas que nunca las añadieron.
  467. func TestEnvScriptPreservesOnSysupgrade(t *testing.T) {
  468. env := reinstall.EnvScript("test-router", strings.Repeat("a1", 32),
  469. "http://192.168.1.226:3000", "", reinstall.WanTargets{})
  470. for _, want := range []string{
  471. "P=/etc/sysupgrade.conf",
  472. "ensure_sysupgrade /etc/init.d/netpulse-agent",
  473. "ensure_sysupgrade /etc/netpulse-agent.env",
  474. } {
  475. if !strings.Contains(env, want) {
  476. t.Errorf("EnvScript sin %q", want)
  477. }
  478. }
  479. }
  480. // #1654: el instalador comprueba que el router alcanza el server antes de
  481. // tocar nada, y copia el binario a un temporal en el mismo directorio para
  482. // renombrarlo después. Una copia directa deja binarios truncados si se corta
  483. // y el fallo del destino se pierde entre la salida del scp.
  484. func TestInstallScriptPreflightAndAtomicBinary(t *testing.T) {
  485. b, err := os.ReadFile(filepath.Clean("../../../install-agent.sh"))
  486. if err != nil {
  487. t.Fatalf("leyendo install-agent.sh: %v", err)
  488. }
  489. script := string(b)
  490. for _, want := range []string{
  491. `'$SERVER/api/health'`,
  492. "NETPULSE_AGENT_URL",
  493. `BIN_TMP="$BIN_DST.new"`,
  494. "mv -f $BIN_TMP $BIN_DST",
  495. "fatal 36",
  496. } {
  497. if !strings.Contains(script, want) {
  498. t.Errorf("install-agent.sh sin %q", want)
  499. }
  500. }
  501. if strings.Contains(script, `scp -Oq $SSH_IDENT_ARGS "$TMP/$BIN_NAME" "$SSH:$BIN_DST"`) {
  502. t.Error("install-agent.sh sigue copiando el binario directo al destino final")
  503. }
  504. }