script_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  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_TMP\"",
  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" = no periodic scans`,
  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_TMP"`,
  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: binary restored\"",
  141. "self-heal: could not restore the binary, the service will not start",
  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. #1855: el
  196. // restart va dentro de un guard que avisa y sale 24 si el agente no arranca.
  197. restart := strings.LastIndex(s, `"$INIT" restart`)
  198. if restart < 0 || !strings.Contains(s[restart:], "exit 24") {
  199. t.Error("el script debe terminar arrancando el servicio y avisar si no arranca")
  200. }
  201. if strings.Index(s, `"$INIT" enable`) > restart {
  202. t.Error("el script debe habilitar el servicio antes de reiniciarlo")
  203. }
  204. }
  205. func TestTokenPushScriptConfig(t *testing.T) {
  206. s := reinstall.TokenPushScript("test-router", strings.Repeat("c3", 32))
  207. for _, want := range []string{
  208. "/etc/netpulse-agent.env",
  209. "NETPULSE_TOKEN=" + strings.Repeat("c3", 32),
  210. "sed -n 's/^NETPULSE_SERVER=//p' \"$ENV_FILE\"",
  211. "sed -n 's/^NETPULSE_SLUG=//p' \"$ENV_FILE\"",
  212. // #851: preservar FP y NETPULSE_* del usuario (p. ej. SCAN_INTERVAL).
  213. "sed -n 's/^NETPULSE_SERVER_FP=//p' \"$ENV_FILE\"",
  214. `printf '%s\n' "$USER_VARS" >> "$ENV_FILE.tmp"`,
  215. "chmod 600 \"$ENV_FILE.tmp\"",
  216. "mv -f \"$ENV_FILE.tmp\" \"$ENV_FILE\"",
  217. "\"$INIT\" restart",
  218. "exit 30",
  219. "exit 31",
  220. } {
  221. if !strings.Contains(s, want) {
  222. t.Errorf("TokenPushScript sin %q", want)
  223. }
  224. }
  225. // No debe descargar binario ni tocar el init (rotate ligero).
  226. if strings.Contains(s, "/binary?arch=") {
  227. t.Error("TokenPushScript no debe descargar el binario")
  228. }
  229. for _, notWant := range []string{"*/2 * * * *", "GOT=$(sha256sum"} {
  230. if strings.Contains(s, notWant) {
  231. t.Errorf("TokenPushScript no debe contener %q (rotate ligero)", notWant)
  232. }
  233. }
  234. }
  235. func TestTokenPushScriptNetgripTargetsPanelEnv(t *testing.T) {
  236. s := reinstall.TokenPushScriptNetgrip("test-router", strings.Repeat("d4", 32))
  237. for _, want := range []string{
  238. "ENV_FILE=/etc/netgrip/netpulse.env",
  239. "INIT=/etc/init.d/netgrip",
  240. "NETPULSE_TOKEN=" + strings.Repeat("d4", 32),
  241. `printf '%s\n' "$USER_VARS" >> "$ENV_FILE.tmp"`,
  242. "\"$INIT\" restart",
  243. } {
  244. if !strings.Contains(s, want) {
  245. t.Errorf("TokenPushScriptNetgrip sin %q", want)
  246. }
  247. }
  248. // NetGrip no lee la config del agente nativo: tocarla sería ruido.
  249. for _, notWant := range []string{"/etc/config/netpulse-agent", "/etc/netpulse-agent.env", "uci -q set"} {
  250. if strings.Contains(s, notWant) {
  251. t.Errorf("TokenPushScriptNetgrip no debe contener %q", notWant)
  252. }
  253. }
  254. }
  255. func TestScriptEmptyDigestSkipsVerify(t *testing.T) {
  256. s := reinstall.Script(
  257. "r", strings.Repeat("b2", 32), "http://s:3000", "",
  258. map[string]string{"arm64": "", "arm": "", "amd64": ""},
  259. )
  260. if !strings.Contains(s, `GOARCH=arm64; SHA256=""`) {
  261. t.Error("sin digest, SHA256 debe quedar vacío")
  262. }
  263. if !strings.Contains(s, `if [ -n "$SHA256" ]; then`) {
  264. t.Error("la verificación debe estar protegida contra digest vacío")
  265. }
  266. }
  267. func TestScriptSelfHealVerifiesDigest(t *testing.T) {
  268. s := reinstall.Script(
  269. "r", strings.Repeat("b2", 32), "https://np.example.org", strings.Repeat("c1", 32),
  270. map[string]string{"arm64": "x", "arm": "x", "amd64": "x"},
  271. )
  272. for _, want := range []string{
  273. "x-checksum-sha256:",
  274. `sha256sum "$tmp"`,
  275. "self-heal: no valid X-Checksum-Sha256, binary discarded",
  276. "self-heal: SHA-256 mismatch, binary discarded",
  277. } {
  278. if !strings.Contains(s, want) {
  279. t.Errorf("init embebido sin %q en el self-heal", want)
  280. }
  281. }
  282. }
  283. func TestSelfHealRequiresHTTPSOrExplicitOptIn(t *testing.T) {
  284. want := []string{
  285. `[ "${NETPULSE_ALLOW_INSECURE_COMMANDS:-}" = "1" ]`,
  286. "self-heal: HTTP without NETPULSE_ALLOW_INSECURE_COMMANDS=1, binary not downloaded",
  287. }
  288. generated := scriptForTest()
  289. for _, w := range want {
  290. if !strings.Contains(generated, w) {
  291. t.Errorf("init generado sin guarda de transporte: falta %q", w)
  292. }
  293. }
  294. for _, path := range []string{
  295. "../../../agent/deploy/netpulse-agent.init",
  296. "../../../install-agent.sh",
  297. } {
  298. b, err := os.ReadFile(filepath.Clean(path))
  299. if err != nil {
  300. t.Fatalf("leyendo %s: %v", path, err)
  301. }
  302. for _, w := range want {
  303. if !strings.Contains(string(b), w) {
  304. t.Errorf("%s sin guarda de transporte: falta %q", path, w)
  305. }
  306. }
  307. }
  308. }
  309. // #851: con server https y FP derivado, el .env generado debe llevar
  310. // NETPULSE_SERVER_FP o el agente entra en bucle fatal al arrancar.
  311. func TestScriptIncludesServerFP(t *testing.T) {
  312. fp := strings.Repeat("c1", 32)
  313. s := reinstall.Script(
  314. "r", strings.Repeat("b2", 32), "https://np.example.org:3443", fp,
  315. map[string]string{"arm64": "x"},
  316. )
  317. for _, want := range []string{
  318. `SERVER="https://np.example.org:3443"`,
  319. `SERVER_FP="` + fp + `"`,
  320. `echo "NETPULSE_SERVER_FP=$SERVER_FP" >> "$ENV_TMP"`,
  321. } {
  322. if !strings.Contains(s, want) {
  323. t.Errorf("script con FP sin %q", want)
  324. }
  325. }
  326. }
  327. // #851: http plano o FP no derivable → script sin FP (comportamiento previo).
  328. func TestScriptEmptyFPSkipsFPLine(t *testing.T) {
  329. for _, u := range []string{"http://192.168.1.226:3000", "https://np.example.org"} {
  330. s := reinstall.Script("r", "tok", u, "", map[string]string{"arm64": "x"})
  331. if !strings.Contains(s, `SERVER_FP=""`) {
  332. t.Errorf("script sin %q para %q", `SERVER_FP=""`, u)
  333. }
  334. if !strings.Contains(s, `if [ -n "$SERVER_FP" ]; then`) {
  335. t.Errorf("script sin guard de FP para %q", u)
  336. }
  337. if strings.Contains(s, "NETPULSE_SERVER_FP=c1") {
  338. t.Errorf("script con FP concreto pese a FP vacío (%q)", u)
  339. }
  340. }
  341. }
  342. // #851: el rotate del token debe conservar el FP del env existente; si se
  343. // pierde, el agente cae en el bucle fatal de "HTTPS requiere NETPULSE_SERVER_FP".
  344. func TestTokenPushPreservesServerFP(t *testing.T) {
  345. s := reinstall.TokenPushScript("test-router", strings.Repeat("c3", 32))
  346. for _, want := range []string{
  347. `sed -n 's/^NETPULSE_SERVER_FP=//p' "$ENV_FILE"`,
  348. `echo "NETPULSE_SERVER_FP=$FP" >> "$ENV_FILE.tmp"`,
  349. } {
  350. if !strings.Contains(s, want) {
  351. t.Errorf("TokenPushScript sin %q", want)
  352. }
  353. }
  354. }
  355. // FORK: with a Trust the script moves the agent to the HTTPS address, writes
  356. // the root to the router, verifies its downloads - including the self-heal's
  357. // - against it, and pins the server. Without one nothing of that appears.
  358. func TestScriptWithTrust(t *testing.T) {
  359. root := "-----BEGIN CERTIFICATE-----\nMIIBtestroot\n-----END CERTIFICATE-----\n"
  360. fp := strings.Repeat("ab", 32)
  361. // A pin derived for the old address is replaced by the trust's.
  362. s := reinstall.Script("test-router", strings.Repeat("a1", 32), "http://192.0.2.10:3000", strings.Repeat("99", 32),
  363. map[string]string{}, reinstall.Trust{ServerURL: "https://192.0.2.10:3443", ServerFP: fp, CAPEM: []byte(root)})
  364. for _, want := range []string{
  365. `SERVER="https://192.0.2.10:3443"`,
  366. "cat > /etc/netpulse-ca.pem <<'CAEOF'\n" + strings.TrimSpace(root) + "\nCAEOF",
  367. `curl -fsSL $CURL_TLS`,
  368. `wget -q $WGET_TLS`,
  369. `SERVER_FP="` + fp + `"`,
  370. `ctls="--cacert /etc/netpulse-ca.pem"`,
  371. } {
  372. if !strings.Contains(s, want) {
  373. t.Errorf("script lacks %q", want)
  374. }
  375. }
  376. if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
  377. t.Fatalf("not valid sh: %v\n%s", err, out)
  378. }
  379. plain := reinstall.Script("test-router", strings.Repeat("a1", 32), "http://192.0.2.10:3000", "", map[string]string{})
  380. if !strings.Contains(plain, "rm -f /etc/netpulse-ca.pem") {
  381. t.Error("a script without a root leaves a stale one on the router")
  382. }
  383. if strings.Contains(s, "rm -f /etc/netpulse-ca.pem") {
  384. t.Error("a script with a root removes it")
  385. }
  386. if strings.Contains(s, strings.Repeat("99", 32)) {
  387. t.Error("the pin passed in survived the trust's")
  388. }
  389. if !strings.Contains(plain, `SERVER_FP=""`) {
  390. t.Error("a script without a pin sets one")
  391. }
  392. for _, notWant := range []string{"CAEOF", "https://"} {
  393. if strings.Contains(plain, notWant) {
  394. t.Errorf("a script without Trust contains %q", notWant)
  395. }
  396. }
  397. if out, err := exec.Command("sh", "-n", "-c", plain).CombinedOutput(); err != nil {
  398. t.Fatalf("not valid sh: %v\n%s", err, out)
  399. }
  400. }
  401. // #1294: EnvScript es la variante ligera: mismo env gestionado (y mismas
  402. // vars de usuario conservadas) que el script completo, pero SIN descargar
  403. // binario ni reescribir el init: solo CA + env + restart del agente.
  404. func TestEnvScriptIsLightweight(t *testing.T) {
  405. full := scriptForTest()
  406. env := reinstall.EnvScript("test-router", strings.Repeat("a1", 32),
  407. "http://192.168.1.226:3000", "", reinstall.WanTargets{})
  408. // Lleva lo esencial del env gestionado.
  409. for _, want := range []string{
  410. `SERVER="http://192.168.1.226:3000"`,
  411. "NETPULSE_SERVER=$SERVER",
  412. "NETPULSE_TOKEN=$TOKEN",
  413. `chmod 600 "$ENV_TMP"`,
  414. // conserva las NETPULSE_* del usuario (#851)
  415. `USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+='`,
  416. // restart para que el agente relea el env
  417. `"$INIT" restart`,
  418. } {
  419. if !strings.Contains(env, want) {
  420. t.Errorf("EnvScript sin %q", want)
  421. }
  422. }
  423. // NO descarga binario ni toca el init (eso es del reinstall completo).
  424. for _, unwanted := range []string{
  425. "/api/agents/$SLUG/binary",
  426. "INITEOF",
  427. "selfheal_binary",
  428. "sha256sum",
  429. } {
  430. if strings.Contains(env, unwanted) {
  431. t.Errorf("EnvScript NO debería contener %q (variante ligera)", unwanted)
  432. }
  433. }
  434. // El bloque del env es literalmente el compartido con el script completo.
  435. if !strings.Contains(full, `USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+='`) {
  436. t.Errorf("script completo perdió el bloque de env compartido")
  437. }
  438. }
  439. // #1294: con trust HTTPS se escribe la CA raíz; sin trust se BORRA la que
  440. // pudiera quedar de una instalación anterior (mismo gesto que el completo).
  441. func TestEnvScriptTrustCA(t *testing.T) {
  442. tr := reinstall.Trust{ServerURL: "https://np.local:3443", ServerFP: "fingerprint",
  443. CAPEM: []byte("-----BEGIN CERTIFICATE-----\nMIIB fake\n-----END CERTIFICATE-----")}
  444. s := reinstall.EnvScript("ap1", "tok", "http://192.168.1.226:3000", "", reinstall.WanTargets{}, tr)
  445. for _, want := range []string{
  446. `SERVER="https://np.local:3443"`,
  447. "MIIB fake",
  448. `SERVER_FP="fingerprint"`,
  449. "NETPULSE_SERVER_FP=$SERVER_FP",
  450. } {
  451. if !strings.Contains(s, want) {
  452. t.Errorf("EnvScript con trust sin %q", want)
  453. }
  454. }
  455. noTrust := reinstall.EnvScript("ap1", "tok", "http://192.168.1.226:3000", "", reinstall.WanTargets{})
  456. if !strings.Contains(noTrust, "rm -f /etc/netpulse-ca.pem") {
  457. t.Errorf("EnvScript sin trust debe borrar la CA previa")
  458. }
  459. }
  460. // #1476: en una actualización de imagen se perdían el init y el env porque no
  461. // estaban en /etc/sysupgrade.conf (OpenWrt solo conserva conffiles de paquetes,
  462. // ese fichero y /lib/upgrade/keep.d/*). El script los añade, sin duplicar
  463. // líneas, después del enable (los symlinks de /etc/rc.d ya existen) y antes del
  464. // restart final.
  465. func TestScriptPreservesOnSysupgrade(t *testing.T) {
  466. s := scriptForTest()
  467. for _, want := range []string{
  468. "P=/etc/sysupgrade.conf",
  469. `ensure_sysupgrade() { grep -qxF "$1" "$P" 2>/dev/null || echo "$1" >> "$P" 2>/dev/null || true; }`,
  470. "ensure_sysupgrade /usr/sbin/netpulse-agent",
  471. "ensure_sysupgrade /etc/netpulse-agent.env",
  472. "ensure_sysupgrade /etc/init.d/netpulse-agent",
  473. `for f in /etc/rc.d/*netpulse-agent*; do [ -e "$f" ] && ensure_sysupgrade "$f"; done`,
  474. } {
  475. if !strings.Contains(s, want) {
  476. t.Errorf("script sin %q", want)
  477. }
  478. }
  479. enable := strings.Index(s, `"$INIT" enable`)
  480. preserve := strings.Index(s, "ensure_sysupgrade /etc/init.d/netpulse-agent")
  481. restart := strings.LastIndex(s, `"$INIT" restart`)
  482. if !(enable >= 0 && preserve > enable && preserve < restart) {
  483. t.Errorf("orden inesperado: enable=%d preserve=%d restart=%d", enable, preserve, restart)
  484. }
  485. }
  486. // #1476: la variante ligera (EnvScript, que corre en la migración a HTTPS
  487. // sobre toda la flota) también escribe las entradas, para curar instalaciones
  488. // antiguas que nunca las añadieron.
  489. func TestEnvScriptPreservesOnSysupgrade(t *testing.T) {
  490. env := reinstall.EnvScript("test-router", strings.Repeat("a1", 32),
  491. "http://192.168.1.226:3000", "", reinstall.WanTargets{})
  492. for _, want := range []string{
  493. "P=/etc/sysupgrade.conf",
  494. "ensure_sysupgrade /etc/init.d/netpulse-agent",
  495. "ensure_sysupgrade /etc/netpulse-agent.env",
  496. } {
  497. if !strings.Contains(env, want) {
  498. t.Errorf("EnvScript sin %q", want)
  499. }
  500. }
  501. }
  502. // #1654: el instalador comprueba que el router alcanza el server antes de
  503. // tocar nada, y copia el binario a un temporal en el mismo directorio para
  504. // renombrarlo después. Una copia directa deja binarios truncados si se corta
  505. // y el fallo del destino se pierde entre la salida del scp.
  506. func TestInstallScriptPreflightAndAtomicBinary(t *testing.T) {
  507. b, err := os.ReadFile(filepath.Clean("../../../install-agent.sh"))
  508. if err != nil {
  509. t.Fatalf("leyendo install-agent.sh: %v", err)
  510. }
  511. script := string(b)
  512. for _, want := range []string{
  513. `'$SERVER/api/health'`,
  514. "NETPULSE_AGENT_URL",
  515. `BIN_TMP="$BIN_DST.new"`,
  516. "mv -f $BIN_TMP $BIN_DST",
  517. "fatal 36",
  518. } {
  519. if !strings.Contains(script, want) {
  520. t.Errorf("install-agent.sh sin %q", want)
  521. }
  522. }
  523. if strings.Contains(script, `scp -Oq $SSH_IDENT_ARGS "$TMP/$BIN_NAME" "$SSH:$BIN_DST"`) {
  524. t.Error("install-agent.sh sigue copiando el binario directo al destino final")
  525. }
  526. }
  527. // #1476 (paso 2): cuando el router ya lleva el paquete, la config vive en
  528. // /etc/config/netpulse-agent (conffile que sobrevive a sysupgrade) y el init
  529. // la lee por UCI. Un reinstall que solo reescribiera el env dejaba la config
  530. // nativa con el token viejo, asi que el script sincroniza las dos.
  531. func TestScriptSyncsUCIConfig(t *testing.T) {
  532. slug, token, url, fp := "test-router", strings.Repeat("a1", 32), "https://192.168.1.226:3000", "sha256//AAAA"
  533. digests := map[string]string{"arm64": "cafebabe"}
  534. s := reinstall.ScriptWithTargets(slug, token, url, fp, digests, reinstall.WanTargets{
  535. WanTarget: "1.1.1.1",
  536. GwTarget: "192.168.1.1",
  537. })
  538. for _, want := range []string{
  539. `UCI_CFG=/etc/config/netpulse-agent`,
  540. `[ -f "$UCI_CFG" ] && command -v uci >/dev/null 2>&1`,
  541. `uci -q set netpulse-agent.main.server="$SERVER"`,
  542. `uci -q set netpulse-agent.main.slug="$SLUG"`,
  543. `uci -q set netpulse-agent.main.token="$TOKEN"`,
  544. `uci -q set netpulse-agent.main.server_fp="$SERVER_FP"`,
  545. `uci -q set netpulse-agent.main.scan_interval="$SCAN_VALUE"`,
  546. `uci -q set netpulse-agent.main.wan_target="1.1.1.1"`,
  547. `uci -q set netpulse-agent.main.gw_target="192.168.1.1"`,
  548. `uci -q commit netpulse-agent`,
  549. } {
  550. if !strings.Contains(s, want) {
  551. t.Errorf("falta en el script: %q", want)
  552. }
  553. }
  554. // Los targets se inyectan entre comillas desde Go: un escapado roto
  555. // dejaria el script invalido justo antes de tocar la config del router.
  556. if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
  557. t.Fatalf("not valid sh: %v\n%s", err, out)
  558. }
  559. }
  560. // Sin objetivos resueltos, el bloque UCI borra las claves en vez de dejarlas
  561. // con el valor de un router anterior.
  562. func TestScriptUCIClearsEmptyTargets(t *testing.T) {
  563. slug, token, url, fp := "test-router", strings.Repeat("a1", 32), "http://192.168.1.226:3000", ""
  564. digests := map[string]string{"arm64": "cafebabe"}
  565. s := reinstall.ScriptWithTargets(slug, token, url, fp, digests, reinstall.WanTargets{})
  566. for _, want := range []string{
  567. `uci -q delete netpulse-agent.main.wan_target`,
  568. `uci -q delete netpulse-agent.main.gw_target`,
  569. } {
  570. if !strings.Contains(s, want) {
  571. t.Errorf("falta en el script: %q", want)
  572. }
  573. }
  574. if strings.Contains(s, `uci -q set netpulse-agent.main.wan_target=""`) {
  575. t.Error("un target vacío no debe escribirse como cadena vacía")
  576. }
  577. if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
  578. t.Fatalf("not valid sh: %v\n%s", err, out)
  579. }
  580. }
  581. // La variante ligera (#1294) migra HTTPS sin reinstalar binario, pero también
  582. // debe dejar la config UCI al día.
  583. func TestEnvScriptSyncsUCIConfig(t *testing.T) {
  584. s := reinstall.EnvScript("test-router", strings.Repeat("a1", 32), "https://192.168.1.226:3000", "sha256//AAAA", reinstall.WanTargets{})
  585. if !strings.Contains(s, `uci -q set netpulse-agent.main.token="$TOKEN"`) {
  586. t.Error("EnvScript debe sincronizar el token en UCI")
  587. }
  588. if !strings.Contains(s, `uci -q delete netpulse-agent.main.server_fp`) {
  589. t.Error("sin FP debe borrar la clave en UCI")
  590. }
  591. if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
  592. t.Fatalf("not valid sh: %v\n%s", err, out)
  593. }
  594. }
  595. // En una instalación por paquete la config UCI ya se conserva, pero un router
  596. // que recibió el paquete y luego un reinstall por SSH tiene que preservarla
  597. // igual que el resto de ficheros del agente.
  598. func TestScriptsPreserveUCIConfig(t *testing.T) {
  599. for name, s := range map[string]string{
  600. "full": reinstall.Script("test-router", strings.Repeat("a1", 32), "http://192.168.1.226:3000", "", map[string]string{"arm64": "cafebabe"}),
  601. "env": reinstall.EnvScript("test-router", strings.Repeat("a1", 32), "http://192.168.1.226:3000", "", reinstall.WanTargets{}),
  602. } {
  603. for _, want := range []string{
  604. `for f in /etc/config/netpulse-agent /etc/uci-defaults/90-netpulse-agent; do`,
  605. `ensure_sysupgrade "$f"`,
  606. } {
  607. if !strings.Contains(s, want) {
  608. t.Errorf("%s: falta en el script: %q", name, want)
  609. }
  610. }
  611. }
  612. }
  613. // #1476: el reinstall instala el paquete .ipk cuando el router tiene opkg, y
  614. // conserva el camino de ficheros sueltos como respaldo si el paquete falla.
  615. func TestScriptInstallsPackageWithFallback(t *testing.T) {
  616. s := reinstall.ScriptWithTargets("test-router", strings.Repeat("a1", 32), "https://192.168.1.226:3000", "sha256//AAAA", map[string]string{"arm64": "cafebabe"}, reinstall.WanTargets{})
  617. for _, want := range []string{
  618. `if command -v opkg >/dev/null 2>&1; then`,
  619. `"$SERVER/api/agents/$SLUG/package?arch=$GOARCH"`,
  620. `opkg install --force-reinstall /tmp/netpulse-agent.ipk`,
  621. `PKG_OK=1`,
  622. `if [ "$PKG_OK" != "1" ]; then`,
  623. `"$SERVER/api/agents/$SLUG/binary?arch=$GOARCH"`,
  624. } {
  625. if !strings.Contains(s, want) {
  626. t.Errorf("falta en el script: %q", want)
  627. }
  628. }
  629. // El bloque del paquete va antes de la descarga del binario suelto: si
  630. // instalase despues, pisaria el init del paquete con el de ficheros sueltos.
  631. pkgIdx := strings.Index(s, `if command -v opkg >/dev/null 2>&1; then`)
  632. binIdx := strings.Index(s, `"$SERVER/api/agents/$SLUG/binary?arch=$GOARCH"`)
  633. if pkgIdx < 0 || binIdx < 0 || pkgIdx > binIdx {
  634. t.Fatalf("orden incorrecto: paquete en %d, binario en %d", pkgIdx, binIdx)
  635. }
  636. if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
  637. t.Fatalf("sh -n: %v\n%s", err, out)
  638. }
  639. }
  640. // El script ligero de entorno no instala paquetes: solo sincroniza config.
  641. func TestEnvScriptDoesNotInstallPackage(t *testing.T) {
  642. s := reinstall.EnvScript("test-router", strings.Repeat("a1", 32), "https://192.168.1.226:3000", "sha256//AAAA", reinstall.WanTargets{})
  643. if strings.Contains(s, "opkg install") {
  644. t.Fatal("el script ligero no debe instalar el paquete")
  645. }
  646. }
  647. // #1816: la rotación en caliente del token escribía solo el env, y el init
  648. // del paquete lee UCI primero. El agente seguía con el token viejo y devolvía
  649. // 401 para siempre. El push debe dejar las dos copias coherentes.
  650. func TestTokenPushScriptSyncsUCIConfig(t *testing.T) {
  651. token := strings.Repeat("ab", 32)
  652. s := reinstall.TokenPushScript("test-router", token)
  653. for _, want := range []string{
  654. `UCI_CFG=/etc/config/netpulse-agent`,
  655. `[ -f "$UCI_CFG" ] && command -v uci >/dev/null 2>&1`,
  656. `uci -q set netpulse-agent.main.server="$SERVER"`,
  657. `uci -q set netpulse-agent.main.slug="$SLUG"`,
  658. `uci -q set netpulse-agent.main.token=` + token,
  659. `uci -q commit netpulse-agent`,
  660. } {
  661. if !strings.Contains(s, want) {
  662. t.Errorf("TokenPushScript no contiene %q", want)
  663. }
  664. }
  665. // El bloque UCI va antes del restart para que el servicio arranque ya con
  666. // el token nuevo en las dos fuentes.
  667. if strings.Index(s, "uci -q commit netpulse-agent") > strings.Index(s, `"$INIT" restart`) {
  668. t.Error("el bloque UCI debe ejecutarse antes del restart")
  669. }
  670. if err := exec.Command("sh", "-n", "-c", s).Run(); err != nil {
  671. t.Fatalf("TokenPushScript no es shell válido: %v", err)
  672. }
  673. }