| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708 |
- // script_test.go — contrato de reinstall.Script (#463/#457): instalación
- // completa del agente (binario verificado, init self-heal, watchdog, cron).
- package reinstall_test
- import (
- "os"
- "os/exec"
- "path/filepath"
- "strings"
- "testing"
- "github.com/gnacho/netpulse/server-go/internal/reinstall"
- )
- func scriptForTest() string {
- return reinstall.Script(
- "test-router",
- strings.Repeat("a1", 32), // 64 hex como un token real
- "http://192.168.1.226:3000",
- "",
- map[string]string{
- "arm64": "cafebabe",
- "arm": "deadbeef",
- "amd64": "abcd1234",
- "mipsle": "0123feed",
- "mips": "4567beef",
- },
- )
- }
- func TestScriptConfig(t *testing.T) {
- s := scriptForTest()
- for _, want := range []string{
- `SERVER="http://192.168.1.226:3000"`,
- `SLUG="test-router"`,
- `NETPULSE_SERVER=$SERVER`,
- `NETPULSE_SLUG=$SLUG`,
- `NETPULSE_TOKEN=$TOKEN`,
- "chmod 600 \"$ENV_TMP\"",
- } {
- if !strings.Contains(s, want) {
- t.Errorf("script sin %q", want)
- }
- }
- }
- // #851: el env generado documenta las opciones disponibles como líneas
- // comentadas con sus defaults.
- func TestScriptEnvDocumentsDefaults(t *testing.T) {
- s := scriptForTest()
- for _, want := range []string{
- "# NETPULSE_INTERVAL=30",
- `# NETPULSE_SCAN_INTERVAL: "0" = no periodic scans`,
- "NETPULSE_SCAN_INTERVAL=$SCAN_VALUE",
- "# NETPULSE_WAN_TARGET=1.1.1.1",
- "# NETPULSE_GW_TARGET=192.168.8.1",
- "# NETPULSE_HEARTBEAT_FILE=/tmp/netpulse-agent.heartbeat",
- } {
- if !strings.Contains(s, want) {
- t.Errorf("env generado sin %q", want)
- }
- }
- }
- // #851: el rewrite del env conserva las NETPULSE_* del usuario (p. ej.
- // NETPULSE_SCAN_INTERVAL=0) en vez de pisarlas.
- // TestScriptWritesActiveTargets (#1204): con objetivos resueltos por el
- // server, el env lleva las líneas ACTIVAS (no comentadas); sin objetivos,
- // siguen documentadas como antes.
- func TestScriptWritesActiveTargets(t *testing.T) {
- slug, token, url, fp := "test-router", strings.Repeat("a1", 32), "http://192.168.1.226:3000", ""
- digests := map[string]string{"arm64": "cafebabe"}
- withWan := reinstall.ScriptWithTargets(slug, token, url, fp, digests, reinstall.WanTargets{WanTarget: "1.1.1.1"})
- if !strings.Contains(withWan, "\nNETPULSE_WAN_TARGET=1.1.1.1\n") {
- t.Errorf("gateway sin línea WAN activa")
- }
- if strings.Contains(withWan, "\nNETPULSE_GW_TARGET=") {
- t.Errorf("el gateway no debe llevar GW_TARGET activo")
- }
- withGw := reinstall.ScriptWithTargets(slug, token, url, fp, digests, reinstall.WanTargets{GwTarget: "192.168.1.1"})
- if !strings.Contains(withGw, "\nNETPULSE_GW_TARGET=192.168.1.1\n") {
- t.Errorf("AP sin línea GW activa")
- }
- if strings.Contains(withGw, "\nNETPULSE_WAN_TARGET=") {
- t.Errorf("el AP no debe llevar WAN_TARGET activo")
- }
- plain := scriptForTest()
- if !strings.Contains(plain, "# NETPULSE_WAN_TARGET=1.1.1.1") || !strings.Contains(plain, "# NETPULSE_GW_TARGET=192.168.8.1") {
- t.Errorf("sin objetivos las líneas deben seguir comentadas")
- }
- }
- func TestScriptPreservesUserVars(t *testing.T) {
- s := scriptForTest()
- for _, want := range []string{
- `USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+=' "$ENV_FILE"`,
- `grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN|WAN_TARGET|GW_TARGET|SCAN_INTERVAL)='`,
- `printf '%s\n' "$USER_VARS" >> "$ENV_TMP"`,
- } {
- if !strings.Contains(s, want) {
- t.Errorf("script sin preservación de vars de usuario: falta %q", want)
- }
- }
- }
- func TestScriptArchAndDigests(t *testing.T) {
- s := scriptForTest()
- for _, want := range []string{
- "aarch64|arm64) GOARCH=arm64; SHA256=\"cafebabe\"",
- "armv7l|armv7|armhf|arm) GOARCH=arm; SHA256=\"deadbeef\"",
- "x86_64|amd64) GOARCH=amd64; SHA256=\"abcd1234\"",
- `/api/agents/$SLUG/binary?arch=$GOARCH`,
- } {
- if !strings.Contains(s, want) {
- t.Errorf("script sin %q", want)
- }
- }
- if strings.Contains(s, "arch=armv7\"") {
- t.Error("el script no debe pedir arch=armv7 (normalizeArch espera arm)")
- }
- // #488: uname -m "mips" no distingue endianness; el script lo detecta
- // con el byte EI_DATA del ELF y mapea a mipsle/mips con su digest.
- for _, want := range []string{
- `1) GOARCH=mipsle; SHA256="0123feed"`,
- `2) GOARCH=mips; SHA256="4567beef"`,
- `head -c 6 /bin/sh | tail -c 1 | tr '\001\002' '12'`,
- } {
- if !strings.Contains(s, want) {
- t.Errorf("script sin %q", want)
- }
- }
- if strings.Count(s, "mipsle") < 2 {
- t.Errorf("el self-heal del init también debe resolver mipsle (apariciones: %d)",
- strings.Count(s, "mipsle"))
- }
- if !strings.Contains(s, `GOT=$(sha256sum /tmp/netpulse-agent.new | awk '{print $1}')`) {
- t.Error("sin verificación sha256sum")
- }
- if !strings.Contains(s, "exit 21") {
- t.Error("sin código de salida 21 para sha256 mismatch")
- }
- }
- func TestScriptSelfHealInit(t *testing.T) {
- s := scriptForTest()
- for _, want := range []string{
- "selfheal_binary()",
- `url="${NETPULSE_SERVER%/}/api/agents/${NETPULSE_SLUG}/binary?arch=${ARCH}"`,
- "logger -t netpulse-agent \"self-heal: binary restored\"",
- "self-heal: could not restore the binary, the service will not start",
- } {
- if !strings.Contains(s, want) {
- t.Errorf("init sin self-heal: falta %q", want)
- }
- }
- if strings.Count(s, "armv7l|armv7|armhf|arm") != 2 {
- t.Errorf("case de arch incompleto (apariciones: %d, esperadas 2)",
- strings.Count(s, "armv7l|armv7|armhf|arm"))
- }
- }
- // #879: el init entregado por el reinstall auto-repara la entrada de cron del
- // antiguo watchdog (tras sysupgrade /etc sobrevive pero el binario no, y cron
- // loguearía un comando inexistente cada 2 min).
- func TestScriptInitSelfHealsStaleWatchdogCron(t *testing.T) {
- s := scriptForTest()
- for _, want := range []string{
- "cleanup_stale_watchdog_cron()",
- "[ -f /usr/sbin/netpulse-watchdog ] && return 0",
- "crontab -l 2>/dev/null | grep -q netpulse-watchdog || return 0",
- "cleanup_stale_watchdog_cron",
- } {
- if !strings.Contains(s, want) {
- t.Errorf("init sin self-heal #879: falta %q", want)
- }
- }
- }
- // #851: el watchdog cron YA NO se instala; el script limpia los restos de
- // instalaciones previas que sí lo tenían.
- func TestScriptNoWatchdogCron(t *testing.T) {
- s := scriptForTest()
- for _, notWant := range []string{
- "*/2 * * * *",
- "proceso vivo pero sin latido",
- `echo '*/2`,
- "/etc/init.d/cron restart",
- } {
- if strings.Contains(s, notWant) {
- t.Errorf("script con watchdog/cron (%q) pese a #851", notWant)
- }
- }
- for _, want := range []string{
- `rm -f /usr/sbin/netpulse-watchdog`,
- `sed -i '/netpulse-watchdog/d' /etc/crontabs/root`,
- } {
- if !strings.Contains(s, want) {
- t.Errorf("script sin limpieza legacy del watchdog: falta %q", want)
- }
- }
- }
- func TestScriptFinishesWithStart(t *testing.T) {
- s := scriptForTest()
- // #1476: entre enable y restart va la preservación en sysupgrade.conf, así
- // que el final ya no es la pareja literal; lo que importa es que el último
- // gesto sea arrancar el servicio y que el enable vaya antes. #1855: el
- // restart va dentro de un guard que avisa y sale 24 si el agente no arranca.
- restart := strings.LastIndex(s, `"$INIT" restart`)
- if restart < 0 || !strings.Contains(s[restart:], "exit 24") {
- t.Error("el script debe terminar arrancando el servicio y avisar si no arranca")
- }
- if strings.Index(s, `"$INIT" enable`) > restart {
- t.Error("el script debe habilitar el servicio antes de reiniciarlo")
- }
- }
- func TestTokenPushScriptConfig(t *testing.T) {
- s := reinstall.TokenPushScript("test-router", strings.Repeat("c3", 32))
- for _, want := range []string{
- "/etc/netpulse-agent.env",
- "NETPULSE_TOKEN=" + strings.Repeat("c3", 32),
- "sed -n 's/^NETPULSE_SERVER=//p' \"$ENV_FILE\"",
- "sed -n 's/^NETPULSE_SLUG=//p' \"$ENV_FILE\"",
- // #851: preservar FP y NETPULSE_* del usuario (p. ej. SCAN_INTERVAL).
- "sed -n 's/^NETPULSE_SERVER_FP=//p' \"$ENV_FILE\"",
- `printf '%s\n' "$USER_VARS" >> "$ENV_FILE.tmp"`,
- "chmod 600 \"$ENV_FILE.tmp\"",
- "mv -f \"$ENV_FILE.tmp\" \"$ENV_FILE\"",
- "\"$INIT\" restart",
- "exit 30",
- "exit 31",
- } {
- if !strings.Contains(s, want) {
- t.Errorf("TokenPushScript sin %q", want)
- }
- }
- // No debe descargar binario ni tocar el init (rotate ligero).
- if strings.Contains(s, "/binary?arch=") {
- t.Error("TokenPushScript no debe descargar el binario")
- }
- for _, notWant := range []string{"*/2 * * * *", "GOT=$(sha256sum"} {
- if strings.Contains(s, notWant) {
- t.Errorf("TokenPushScript no debe contener %q (rotate ligero)", notWant)
- }
- }
- }
- func TestTokenPushScriptNetgripTargetsPanelEnv(t *testing.T) {
- s := reinstall.TokenPushScriptNetgrip("test-router", strings.Repeat("d4", 32))
- for _, want := range []string{
- "ENV_FILE=/etc/netgrip/netpulse.env",
- "INIT=/etc/init.d/netgrip",
- "NETPULSE_TOKEN=" + strings.Repeat("d4", 32),
- `printf '%s\n' "$USER_VARS" >> "$ENV_FILE.tmp"`,
- "\"$INIT\" restart",
- } {
- if !strings.Contains(s, want) {
- t.Errorf("TokenPushScriptNetgrip sin %q", want)
- }
- }
- // NetGrip no lee la config del agente nativo: tocarla sería ruido.
- for _, notWant := range []string{"/etc/config/netpulse-agent", "/etc/netpulse-agent.env", "uci -q set"} {
- if strings.Contains(s, notWant) {
- t.Errorf("TokenPushScriptNetgrip no debe contener %q", notWant)
- }
- }
- }
- func TestScriptEmptyDigestSkipsVerify(t *testing.T) {
- s := reinstall.Script(
- "r", strings.Repeat("b2", 32), "http://s:3000", "",
- map[string]string{"arm64": "", "arm": "", "amd64": ""},
- )
- if !strings.Contains(s, `GOARCH=arm64; SHA256=""`) {
- t.Error("sin digest, SHA256 debe quedar vacío")
- }
- if !strings.Contains(s, `if [ -n "$SHA256" ]; then`) {
- t.Error("la verificación debe estar protegida contra digest vacío")
- }
- }
- func TestScriptSelfHealVerifiesDigest(t *testing.T) {
- s := reinstall.Script(
- "r", strings.Repeat("b2", 32), "https://np.example.org", strings.Repeat("c1", 32),
- map[string]string{"arm64": "x", "arm": "x", "amd64": "x"},
- )
- for _, want := range []string{
- "x-checksum-sha256:",
- `sha256sum "$tmp"`,
- "self-heal: no valid X-Checksum-Sha256, binary discarded",
- "self-heal: SHA-256 mismatch, binary discarded",
- } {
- if !strings.Contains(s, want) {
- t.Errorf("init embebido sin %q en el self-heal", want)
- }
- }
- }
- func TestSelfHealRequiresHTTPSOrExplicitOptIn(t *testing.T) {
- want := []string{
- `[ "${NETPULSE_ALLOW_INSECURE_COMMANDS:-}" = "1" ]`,
- "self-heal: HTTP without NETPULSE_ALLOW_INSECURE_COMMANDS=1, binary not downloaded",
- }
- generated := scriptForTest()
- for _, w := range want {
- if !strings.Contains(generated, w) {
- t.Errorf("init generado sin guarda de transporte: falta %q", w)
- }
- }
- for _, path := range []string{
- "../../../agent/deploy/netpulse-agent.init",
- "../../../install-agent.sh",
- } {
- b, err := os.ReadFile(filepath.Clean(path))
- if err != nil {
- t.Fatalf("leyendo %s: %v", path, err)
- }
- for _, w := range want {
- if !strings.Contains(string(b), w) {
- t.Errorf("%s sin guarda de transporte: falta %q", path, w)
- }
- }
- }
- }
- // #851: con server https y FP derivado, el .env generado debe llevar
- // NETPULSE_SERVER_FP o el agente entra en bucle fatal al arrancar.
- func TestScriptIncludesServerFP(t *testing.T) {
- fp := strings.Repeat("c1", 32)
- s := reinstall.Script(
- "r", strings.Repeat("b2", 32), "https://np.example.org:3443", fp,
- map[string]string{"arm64": "x"},
- )
- for _, want := range []string{
- `SERVER="https://np.example.org:3443"`,
- `SERVER_FP="` + fp + `"`,
- `echo "NETPULSE_SERVER_FP=$SERVER_FP" >> "$ENV_TMP"`,
- } {
- if !strings.Contains(s, want) {
- t.Errorf("script con FP sin %q", want)
- }
- }
- }
- // #851: http plano o FP no derivable → script sin FP (comportamiento previo).
- func TestScriptEmptyFPSkipsFPLine(t *testing.T) {
- for _, u := range []string{"http://192.168.1.226:3000", "https://np.example.org"} {
- s := reinstall.Script("r", "tok", u, "", map[string]string{"arm64": "x"})
- if !strings.Contains(s, `SERVER_FP=""`) {
- t.Errorf("script sin %q para %q", `SERVER_FP=""`, u)
- }
- if !strings.Contains(s, `if [ -n "$SERVER_FP" ]; then`) {
- t.Errorf("script sin guard de FP para %q", u)
- }
- if strings.Contains(s, "NETPULSE_SERVER_FP=c1") {
- t.Errorf("script con FP concreto pese a FP vacío (%q)", u)
- }
- }
- }
- // #851: el rotate del token debe conservar el FP del env existente; si se
- // pierde, el agente cae en el bucle fatal de "HTTPS requiere NETPULSE_SERVER_FP".
- func TestTokenPushPreservesServerFP(t *testing.T) {
- s := reinstall.TokenPushScript("test-router", strings.Repeat("c3", 32))
- for _, want := range []string{
- `sed -n 's/^NETPULSE_SERVER_FP=//p' "$ENV_FILE"`,
- `echo "NETPULSE_SERVER_FP=$FP" >> "$ENV_FILE.tmp"`,
- } {
- if !strings.Contains(s, want) {
- t.Errorf("TokenPushScript sin %q", want)
- }
- }
- }
- // FORK: with a Trust the script moves the agent to the HTTPS address, writes
- // the root to the router, verifies its downloads - including the self-heal's
- // - against it, and pins the server. Without one nothing of that appears.
- func TestScriptWithTrust(t *testing.T) {
- root := "-----BEGIN CERTIFICATE-----\nMIIBtestroot\n-----END CERTIFICATE-----\n"
- fp := strings.Repeat("ab", 32)
- // A pin derived for the old address is replaced by the trust's.
- s := reinstall.Script("test-router", strings.Repeat("a1", 32), "http://192.0.2.10:3000", strings.Repeat("99", 32),
- map[string]string{}, reinstall.Trust{ServerURL: "https://192.0.2.10:3443", ServerFP: fp, CAPEM: []byte(root)})
- for _, want := range []string{
- `SERVER="https://192.0.2.10:3443"`,
- "cat > /etc/netpulse-ca.pem <<'CAEOF'\n" + strings.TrimSpace(root) + "\nCAEOF",
- `curl -fsSL $CURL_TLS`,
- `wget -q $WGET_TLS`,
- `SERVER_FP="` + fp + `"`,
- `ctls="--cacert /etc/netpulse-ca.pem"`,
- } {
- if !strings.Contains(s, want) {
- t.Errorf("script lacks %q", want)
- }
- }
- if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
- t.Fatalf("not valid sh: %v\n%s", err, out)
- }
- plain := reinstall.Script("test-router", strings.Repeat("a1", 32), "http://192.0.2.10:3000", "", map[string]string{})
- if !strings.Contains(plain, "rm -f /etc/netpulse-ca.pem") {
- t.Error("a script without a root leaves a stale one on the router")
- }
- if strings.Contains(s, "rm -f /etc/netpulse-ca.pem") {
- t.Error("a script with a root removes it")
- }
- if strings.Contains(s, strings.Repeat("99", 32)) {
- t.Error("the pin passed in survived the trust's")
- }
- if !strings.Contains(plain, `SERVER_FP=""`) {
- t.Error("a script without a pin sets one")
- }
- for _, notWant := range []string{"CAEOF", "https://"} {
- if strings.Contains(plain, notWant) {
- t.Errorf("a script without Trust contains %q", notWant)
- }
- }
- if out, err := exec.Command("sh", "-n", "-c", plain).CombinedOutput(); err != nil {
- t.Fatalf("not valid sh: %v\n%s", err, out)
- }
- }
- // #1294: EnvScript es la variante ligera: mismo env gestionado (y mismas
- // vars de usuario conservadas) que el script completo, pero SIN descargar
- // binario ni reescribir el init: solo CA + env + restart del agente.
- func TestEnvScriptIsLightweight(t *testing.T) {
- full := scriptForTest()
- env := reinstall.EnvScript("test-router", strings.Repeat("a1", 32),
- "http://192.168.1.226:3000", "", reinstall.WanTargets{})
- // Lleva lo esencial del env gestionado.
- for _, want := range []string{
- `SERVER="http://192.168.1.226:3000"`,
- "NETPULSE_SERVER=$SERVER",
- "NETPULSE_TOKEN=$TOKEN",
- `chmod 600 "$ENV_TMP"`,
- // conserva las NETPULSE_* del usuario (#851)
- `USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+='`,
- // restart para que el agente relea el env
- `"$INIT" restart`,
- } {
- if !strings.Contains(env, want) {
- t.Errorf("EnvScript sin %q", want)
- }
- }
- // NO descarga binario ni toca el init (eso es del reinstall completo).
- for _, unwanted := range []string{
- "/api/agents/$SLUG/binary",
- "INITEOF",
- "selfheal_binary",
- "sha256sum",
- } {
- if strings.Contains(env, unwanted) {
- t.Errorf("EnvScript NO debería contener %q (variante ligera)", unwanted)
- }
- }
- // El bloque del env es literalmente el compartido con el script completo.
- if !strings.Contains(full, `USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+='`) {
- t.Errorf("script completo perdió el bloque de env compartido")
- }
- }
- // #1294: con trust HTTPS se escribe la CA raíz; sin trust se BORRA la que
- // pudiera quedar de una instalación anterior (mismo gesto que el completo).
- func TestEnvScriptTrustCA(t *testing.T) {
- tr := reinstall.Trust{ServerURL: "https://np.local:3443", ServerFP: "fingerprint",
- CAPEM: []byte("-----BEGIN CERTIFICATE-----\nMIIB fake\n-----END CERTIFICATE-----")}
- s := reinstall.EnvScript("ap1", "tok", "http://192.168.1.226:3000", "", reinstall.WanTargets{}, tr)
- for _, want := range []string{
- `SERVER="https://np.local:3443"`,
- "MIIB fake",
- `SERVER_FP="fingerprint"`,
- "NETPULSE_SERVER_FP=$SERVER_FP",
- } {
- if !strings.Contains(s, want) {
- t.Errorf("EnvScript con trust sin %q", want)
- }
- }
- noTrust := reinstall.EnvScript("ap1", "tok", "http://192.168.1.226:3000", "", reinstall.WanTargets{})
- if !strings.Contains(noTrust, "rm -f /etc/netpulse-ca.pem") {
- t.Errorf("EnvScript sin trust debe borrar la CA previa")
- }
- }
- // #1476: en una actualización de imagen se perdían el init y el env porque no
- // estaban en /etc/sysupgrade.conf (OpenWrt solo conserva conffiles de paquetes,
- // ese fichero y /lib/upgrade/keep.d/*). El script los añade, sin duplicar
- // líneas, después del enable (los symlinks de /etc/rc.d ya existen) y antes del
- // restart final.
- func TestScriptPreservesOnSysupgrade(t *testing.T) {
- s := scriptForTest()
- for _, want := range []string{
- "P=/etc/sysupgrade.conf",
- `ensure_sysupgrade() { grep -qxF "$1" "$P" 2>/dev/null || echo "$1" >> "$P" 2>/dev/null || true; }`,
- "ensure_sysupgrade /usr/sbin/netpulse-agent",
- "ensure_sysupgrade /etc/netpulse-agent.env",
- "ensure_sysupgrade /etc/init.d/netpulse-agent",
- `for f in /etc/rc.d/*netpulse-agent*; do [ -e "$f" ] && ensure_sysupgrade "$f"; done`,
- } {
- if !strings.Contains(s, want) {
- t.Errorf("script sin %q", want)
- }
- }
- enable := strings.Index(s, `"$INIT" enable`)
- preserve := strings.Index(s, "ensure_sysupgrade /etc/init.d/netpulse-agent")
- restart := strings.LastIndex(s, `"$INIT" restart`)
- if !(enable >= 0 && preserve > enable && preserve < restart) {
- t.Errorf("orden inesperado: enable=%d preserve=%d restart=%d", enable, preserve, restart)
- }
- }
- // #1476: la variante ligera (EnvScript, que corre en la migración a HTTPS
- // sobre toda la flota) también escribe las entradas, para curar instalaciones
- // antiguas que nunca las añadieron.
- func TestEnvScriptPreservesOnSysupgrade(t *testing.T) {
- env := reinstall.EnvScript("test-router", strings.Repeat("a1", 32),
- "http://192.168.1.226:3000", "", reinstall.WanTargets{})
- for _, want := range []string{
- "P=/etc/sysupgrade.conf",
- "ensure_sysupgrade /etc/init.d/netpulse-agent",
- "ensure_sysupgrade /etc/netpulse-agent.env",
- } {
- if !strings.Contains(env, want) {
- t.Errorf("EnvScript sin %q", want)
- }
- }
- }
- // #1654: el instalador comprueba que el router alcanza el server antes de
- // tocar nada, y copia el binario a un temporal en el mismo directorio para
- // renombrarlo después. Una copia directa deja binarios truncados si se corta
- // y el fallo del destino se pierde entre la salida del scp.
- func TestInstallScriptPreflightAndAtomicBinary(t *testing.T) {
- b, err := os.ReadFile(filepath.Clean("../../../install-agent.sh"))
- if err != nil {
- t.Fatalf("leyendo install-agent.sh: %v", err)
- }
- script := string(b)
- for _, want := range []string{
- `'$SERVER/api/health'`,
- "NETPULSE_AGENT_URL",
- `BIN_TMP="$BIN_DST.new"`,
- "mv -f $BIN_TMP $BIN_DST",
- "fatal 36",
- } {
- if !strings.Contains(script, want) {
- t.Errorf("install-agent.sh sin %q", want)
- }
- }
- if strings.Contains(script, `scp -Oq $SSH_IDENT_ARGS "$TMP/$BIN_NAME" "$SSH:$BIN_DST"`) {
- t.Error("install-agent.sh sigue copiando el binario directo al destino final")
- }
- }
- // #1476 (paso 2): cuando el router ya lleva el paquete, la config vive en
- // /etc/config/netpulse-agent (conffile que sobrevive a sysupgrade) y el init
- // la lee por UCI. Un reinstall que solo reescribiera el env dejaba la config
- // nativa con el token viejo, asi que el script sincroniza las dos.
- func TestScriptSyncsUCIConfig(t *testing.T) {
- slug, token, url, fp := "test-router", strings.Repeat("a1", 32), "https://192.168.1.226:3000", "sha256//AAAA"
- digests := map[string]string{"arm64": "cafebabe"}
- s := reinstall.ScriptWithTargets(slug, token, url, fp, digests, reinstall.WanTargets{
- WanTarget: "1.1.1.1",
- GwTarget: "192.168.1.1",
- })
- for _, want := range []string{
- `UCI_CFG=/etc/config/netpulse-agent`,
- `[ -f "$UCI_CFG" ] && command -v uci >/dev/null 2>&1`,
- `uci -q set netpulse-agent.main.server="$SERVER"`,
- `uci -q set netpulse-agent.main.slug="$SLUG"`,
- `uci -q set netpulse-agent.main.token="$TOKEN"`,
- `uci -q set netpulse-agent.main.server_fp="$SERVER_FP"`,
- `uci -q set netpulse-agent.main.scan_interval="$SCAN_VALUE"`,
- `uci -q set netpulse-agent.main.wan_target="1.1.1.1"`,
- `uci -q set netpulse-agent.main.gw_target="192.168.1.1"`,
- `uci -q commit netpulse-agent`,
- } {
- if !strings.Contains(s, want) {
- t.Errorf("falta en el script: %q", want)
- }
- }
- // Los targets se inyectan entre comillas desde Go: un escapado roto
- // dejaria el script invalido justo antes de tocar la config del router.
- if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
- t.Fatalf("not valid sh: %v\n%s", err, out)
- }
- }
- // Sin objetivos resueltos, el bloque UCI borra las claves en vez de dejarlas
- // con el valor de un router anterior.
- func TestScriptUCIClearsEmptyTargets(t *testing.T) {
- slug, token, url, fp := "test-router", strings.Repeat("a1", 32), "http://192.168.1.226:3000", ""
- digests := map[string]string{"arm64": "cafebabe"}
- s := reinstall.ScriptWithTargets(slug, token, url, fp, digests, reinstall.WanTargets{})
- for _, want := range []string{
- `uci -q delete netpulse-agent.main.wan_target`,
- `uci -q delete netpulse-agent.main.gw_target`,
- } {
- if !strings.Contains(s, want) {
- t.Errorf("falta en el script: %q", want)
- }
- }
- if strings.Contains(s, `uci -q set netpulse-agent.main.wan_target=""`) {
- t.Error("un target vacío no debe escribirse como cadena vacía")
- }
- if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
- t.Fatalf("not valid sh: %v\n%s", err, out)
- }
- }
- // La variante ligera (#1294) migra HTTPS sin reinstalar binario, pero también
- // debe dejar la config UCI al día.
- func TestEnvScriptSyncsUCIConfig(t *testing.T) {
- s := reinstall.EnvScript("test-router", strings.Repeat("a1", 32), "https://192.168.1.226:3000", "sha256//AAAA", reinstall.WanTargets{})
- if !strings.Contains(s, `uci -q set netpulse-agent.main.token="$TOKEN"`) {
- t.Error("EnvScript debe sincronizar el token en UCI")
- }
- if !strings.Contains(s, `uci -q delete netpulse-agent.main.server_fp`) {
- t.Error("sin FP debe borrar la clave en UCI")
- }
- if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
- t.Fatalf("not valid sh: %v\n%s", err, out)
- }
- }
- // En una instalación por paquete la config UCI ya se conserva, pero un router
- // que recibió el paquete y luego un reinstall por SSH tiene que preservarla
- // igual que el resto de ficheros del agente.
- func TestScriptsPreserveUCIConfig(t *testing.T) {
- for name, s := range map[string]string{
- "full": reinstall.Script("test-router", strings.Repeat("a1", 32), "http://192.168.1.226:3000", "", map[string]string{"arm64": "cafebabe"}),
- "env": reinstall.EnvScript("test-router", strings.Repeat("a1", 32), "http://192.168.1.226:3000", "", reinstall.WanTargets{}),
- } {
- for _, want := range []string{
- `for f in /etc/config/netpulse-agent /etc/uci-defaults/90-netpulse-agent; do`,
- `ensure_sysupgrade "$f"`,
- } {
- if !strings.Contains(s, want) {
- t.Errorf("%s: falta en el script: %q", name, want)
- }
- }
- }
- }
- // #1476: el reinstall instala el paquete .ipk cuando el router tiene opkg, y
- // conserva el camino de ficheros sueltos como respaldo si el paquete falla.
- func TestScriptInstallsPackageWithFallback(t *testing.T) {
- s := reinstall.ScriptWithTargets("test-router", strings.Repeat("a1", 32), "https://192.168.1.226:3000", "sha256//AAAA", map[string]string{"arm64": "cafebabe"}, reinstall.WanTargets{})
- for _, want := range []string{
- `if command -v opkg >/dev/null 2>&1; then`,
- `"$SERVER/api/agents/$SLUG/package?arch=$GOARCH"`,
- `opkg install --force-reinstall /tmp/netpulse-agent.ipk`,
- `PKG_OK=1`,
- `if [ "$PKG_OK" != "1" ]; then`,
- `"$SERVER/api/agents/$SLUG/binary?arch=$GOARCH"`,
- } {
- if !strings.Contains(s, want) {
- t.Errorf("falta en el script: %q", want)
- }
- }
- // El bloque del paquete va antes de la descarga del binario suelto: si
- // instalase despues, pisaria el init del paquete con el de ficheros sueltos.
- pkgIdx := strings.Index(s, `if command -v opkg >/dev/null 2>&1; then`)
- binIdx := strings.Index(s, `"$SERVER/api/agents/$SLUG/binary?arch=$GOARCH"`)
- if pkgIdx < 0 || binIdx < 0 || pkgIdx > binIdx {
- t.Fatalf("orden incorrecto: paquete en %d, binario en %d", pkgIdx, binIdx)
- }
- if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
- t.Fatalf("sh -n: %v\n%s", err, out)
- }
- }
- // El script ligero de entorno no instala paquetes: solo sincroniza config.
- func TestEnvScriptDoesNotInstallPackage(t *testing.T) {
- s := reinstall.EnvScript("test-router", strings.Repeat("a1", 32), "https://192.168.1.226:3000", "sha256//AAAA", reinstall.WanTargets{})
- if strings.Contains(s, "opkg install") {
- t.Fatal("el script ligero no debe instalar el paquete")
- }
- }
- // #1816: la rotación en caliente del token escribía solo el env, y el init
- // del paquete lee UCI primero. El agente seguía con el token viejo y devolvía
- // 401 para siempre. El push debe dejar las dos copias coherentes.
- func TestTokenPushScriptSyncsUCIConfig(t *testing.T) {
- token := strings.Repeat("ab", 32)
- s := reinstall.TokenPushScript("test-router", token)
- for _, want := range []string{
- `UCI_CFG=/etc/config/netpulse-agent`,
- `[ -f "$UCI_CFG" ] && command -v uci >/dev/null 2>&1`,
- `uci -q set netpulse-agent.main.server="$SERVER"`,
- `uci -q set netpulse-agent.main.slug="$SLUG"`,
- `uci -q set netpulse-agent.main.token=` + token,
- `uci -q commit netpulse-agent`,
- } {
- if !strings.Contains(s, want) {
- t.Errorf("TokenPushScript no contiene %q", want)
- }
- }
- // El bloque UCI va antes del restart para que el servicio arranque ya con
- // el token nuevo en las dos fuentes.
- if strings.Index(s, "uci -q commit netpulse-agent") > strings.Index(s, `"$INIT" restart`) {
- t.Error("el bloque UCI debe ejecutarse antes del restart")
- }
- if err := exec.Command("sh", "-n", "-c", s).Run(); err != nil {
- t.Fatalf("TokenPushScript no es shell válido: %v", err)
- }
- }
|