Parcourir la source

feat(agent): canonical server-driven reinstall (sha256 verify, self-heal init, watchdog) (#464)

* feat(agent): canonical server-driven reinstall with sha256 verify, self-heal init and watchdog

* docs(readme): agent install happy path via Reinstall and apk post-install config

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho il y a 3 mois
Parent
commit
47321e1d36
3 fichiers modifiés avec 257 ajouts et 23 suppressions
  1. 28 0
      README.md
  2. 105 23
      server-go/internal/httpapi/agent.go
  3. 124 0
      server-go/internal/httpapi/reinstall_script_test.go

+ 28 - 0
README.md

@@ -188,6 +188,18 @@ Settings. Authorize it on each router you want to monitor
 boot via LAN discovery (TCP :22 sweep, ubus/GL-UI fingerprint); the rest
 boot via LAN discovery (TCP :22 sweep, ubus/GL-UI fingerprint); the rest
 are added from Settings. Polling is strictly read-only.
 are added from Settings. Polling is strictly read-only.
 
 
+### Installing the agents (recommended: let the app do it)
+
+Once the router is in the table and its SSH key is authorized, the app can
+install and start the agent by itself: Settings → Agents → **Reinstall**.
+Over one SSH session the server detects the architecture, downloads the
+embedded agent binary from itself (token-authenticated), verifies its
+SHA256, writes the config, installs the procd init (with a self-heal step
+that re-downloads the binary after a `sysupgrade`, which only preserves
+`/etc`), sets up the watchdog cron and restarts the service. The agent
+shows up as connected within seconds. Re-running it is safe: it rotates
+the token and reinstalls.
+
 ## OpenWrt packages
 ## OpenWrt packages
 
 
 Every `v*` release ships the agent and the LuCI app as installable OpenWrt
 Every `v*` release ships the agent and the LuCI app as installable OpenWrt
@@ -216,6 +228,22 @@ both packages together resolves the dependencies without extra feeds. After
 install, LuCI picks up the new pages automatically (the package restarts
 install, LuCI picks up the new pages automatically (the package restarts
 `rpcd` and clears the index cache).
 `rpcd` and clears the index cache).
 
 
+The package ships an empty config, so the service stays inactive until you
+point it at your server (the app cannot know these values). Create the
+agent in the web UI (Settings → Agents) to get its one-time token, then on
+the router:
+
+```sh
+uci set netpulse-agent.main.server='http://<netpulse-server-ip>:3000'
+uci set netpulse-agent.main.slug='<slug>'
+uci set netpulse-agent.main.token='<64-hex token>'
+uci commit netpulse-agent
+service netpulse-agent enable && service netpulse-agent start
+```
+
+If the server can already SSH into the router, prefer the automated path
+above: **Reinstall** does all of this for you.
+
 ## Development
 ## Development
 
 
 ```bash
 ```bash

+ 105 - 23
server-go/internal/httpapi/agent.go

@@ -703,8 +703,17 @@ func (s *server) handleAgentReinstall(w http.ResponseWriter, r *http.Request) {
 	}
 	}
 	serverURL := scheme + "://" + r.Host
 	serverURL := scheme + "://" + r.Host
 
 
+	// Digests sha256 de los binarios embebidos (#463): el router verifica la
+	// descarga antes del swap. Arch sin binario (build dev sin agentes) queda
+	// sin verificar en lugar de bloquear la instalación.
+	digests := map[string]string{
+		"arm64": agentbin.Digest("arm64"),
+		"arm":   agentbin.Digest("arm"),
+		"amd64": agentbin.Digest("amd64"),
+	}
+
 	// Script de instalación (replica install-agent.sh vía SSH, sin scp).
 	// Script de instalación (replica install-agent.sh vía SSH, sin scp).
-	script := reinstallScript(host, slug, token, serverURL)
+	script := reinstallScript(slug, token, serverURL, digests)
 
 
 	before := time.Now()
 	before := time.Now()
 	var prevSeen time.Time
 	var prevSeen time.Time
@@ -714,7 +723,8 @@ func (s *server) handleAgentReinstall(w http.ResponseWriter, r *http.Request) {
 		}
 		}
 	}
 	}
 
 
-	if _, err := s.pool.Run(host, script, 60*time.Second); err != nil {
+	// Descarga + verificación + swap: margen generoso para enlaces lentos.
+	if _, err := s.pool.Run(host, script, 300*time.Second); err != nil {
 		writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
 		writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
 		return
 		return
 	}
 	}
@@ -739,37 +749,48 @@ func (s *server) handleAgentReinstall(w http.ResponseWriter, r *http.Request) {
 	})
 	})
 }
 }
 
 
-// reinstallScript construye el script POSIX sh que se ejecuta en el router.
-func reinstallScript(host, slug, token, serverURL string) string {
+// reinstallScript construye el script POSIX sh que se ejecuta en el router
+// (#463): instala el agente completo —binario verificado por sha256, config
+// .env, init procd con self-heal y watchdog con su cron— de forma idempotente.
+// digests mapa arch→sha256 del binario embebido; un arch sin digest queda sin
+// verificación (build dev) en lugar de bloquear.
+func reinstallScript(slug, token, serverURL string, digests map[string]string) string {
 	return `#!/bin/sh
 	return `#!/bin/sh
 set -e
 set -e
 INIT=/etc/init.d/netpulse-agent
 INIT=/etc/init.d/netpulse-agent
 BIN=/usr/sbin/netpulse-agent
 BIN=/usr/sbin/netpulse-agent
 ENV_FILE=/etc/netpulse-agent.env
 ENV_FILE=/etc/netpulse-agent.env
+WATCHDOG=/usr/sbin/netpulse-watchdog
 SERVER="` + serverURL + `"
 SERVER="` + serverURL + `"
 SLUG="` + slug + `"
 SLUG="` + slug + `"
 TOKEN="` + token + `"
 TOKEN="` + token + `"
 
 
-# Detectar arquitectura del router
+# Detectar arquitectura del router y el digest esperado del binario embebido
 ARCH=$(uname -m)
 ARCH=$(uname -m)
 case "$ARCH" in
 case "$ARCH" in
-	aarch64|arm64) GOARCH=arm64 ;;
-	armv7l|armv7)  GOARCH=armv7 ;;
+	aarch64|arm64)  GOARCH=arm64; SHA256="` + digests["arm64"] + `" ;;
+	armv7l|armv7|armhf|arm) GOARCH=arm; SHA256="` + digests["arm"] + `" ;;
+	x86_64|amd64)   GOARCH=amd64; SHA256="` + digests["amd64"] + `" ;;
 	*) echo "arch no soportado: $ARCH"; exit 20 ;;
 	*) echo "arch no soportado: $ARCH"; exit 20 ;;
 esac
 esac
 
 
 # Parar servicio previo si existe (el proceso vivo mantiene el binario abierto)
 # Parar servicio previo si existe (el proceso vivo mantiene el binario abierto)
-[ -f "$INIT" ] && $INIT stop >/dev/null 2>&1 || true
+[ -f "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
 
 
 # Descargar el binario del propio server (auth por token)
 # Descargar el binario del propio server (auth por token)
 if command -v curl >/dev/null 2>&1; then
 if command -v curl >/dev/null 2>&1; then
-	curl -fsSL --connect-timeout 10 -H "Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH" -o /tmp/netpulse-agent.new
+	curl -fsSL --connect-timeout 10 -m 600 -H "Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH" -o /tmp/netpulse-agent.new
 else
 else
-	wget -q -O /tmp/netpulse-agent.new --header="Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH"
+	wget -q -T 60 -O /tmp/netpulse-agent.new --header="Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH"
+fi
+
+# Verificación sha256 contra el digest embebido (#463); vacío = sin verificar
+if [ -n "$SHA256" ]; then
+	GOT=$(sha256sum /tmp/netpulse-agent.new | awk '{print $1}')
+	[ "$GOT" = "$SHA256" ] || { echo "sha256 no coincide (esperado $SHA256, obtenido $GOT)"; exit 21; }
 fi
 fi
 chmod 0755 /tmp/netpulse-agent.new
 chmod 0755 /tmp/netpulse-agent.new
-mv /tmp/netpulse-agent.new "$BIN"
-chmod 0755 "$BIN"
+mv -f /tmp/netpulse-agent.new "$BIN"
 
 
 # Config (chmod 600)
 # Config (chmod 600)
 cat > "$ENV_FILE" <<EOF
 cat > "$ENV_FILE" <<EOF
@@ -780,30 +801,91 @@ NETPULSE_TOKEN=$TOKEN
 EOF
 EOF
 chmod 600 "$ENV_FILE"
 chmod 600 "$ENV_FILE"
 
 
-# Init script procd (respawn)
+# Init procd con self-heal (#457): un sysupgrade solo conserva /etc, así que
+# si el binario falta al arrancar se descarga del server con este env.
 cat > "$INIT" <<'INITEOF'
 cat > "$INIT" <<'INITEOF'
 #!/bin/sh /etc/rc.common
 #!/bin/sh /etc/rc.common
-# netpulse-agent — agente nativo NetPulse para OpenWrt
+# netpulse-agent — agente nativo NetPulse para OpenWrt, con self-heal.
+# Config en /etc/netpulse-agent.env (chmod 600); procd reinicia si cambia.
 START=99
 START=99
 STOP=10
 STOP=10
 USE_PROCD=1
 USE_PROCD=1
 
 
+ENV_FILE=/etc/netpulse-agent.env
 BIN=/usr/sbin/netpulse-agent
 BIN=/usr/sbin/netpulse-agent
 [ -x "$BIN" ] || BIN=/tmp/netpulse-agent
 [ -x "$BIN" ] || BIN=/tmp/netpulse-agent
 
 
+selfheal_binary() {
+	[ -x "$BIN" ] && return 0
+	[ -f "$ENV_FILE" ] || return 1
+	. "$ENV_FILE" 2>/dev/null
+	[ -n "${NETPULSE_SERVER:-}" ] && [ -n "${NETPULSE_TOKEN:-}" ] && [ -n "${NETPULSE_SLUG:-}" ] || return 1
+	case "$(uname -m)" in
+		aarch64|arm64) local ARCH=arm64 ;;
+		armv7l|armv7|armhf|arm) local ARCH=arm ;;
+		x86_64|amd64) local ARCH=amd64 ;;
+		*) return 1 ;;
+	esac
+	local url tmp
+	url="${NETPULSE_SERVER%/}/api/agents/${NETPULSE_SLUG}/binary?arch=${ARCH}"
+	logger -t netpulse-agent "self-heal: binario ausente, descargando de $NETPULSE_SERVER"
+	tmp=/tmp/netpulse-agent.$$
+	if command -v curl >/dev/null 2>&1; then
+		curl -fsSL -m 120 -H "Authorization: Bearer $NETPULSE_TOKEN" -o "$tmp" "$url" || return 1
+	else
+		wget -q -T 60 -O "$tmp" --header="Authorization: Bearer $NETPULSE_TOKEN" "$url" || return 1
+	fi
+	chmod 0755 "$tmp" && mv "$tmp" /usr/sbin/netpulse-agent || { rm -f "$tmp"; return 1; }
+	logger -t netpulse-agent "self-heal: binario restaurado"
+	BIN=/usr/sbin/netpulse-agent
+	return 0
+}
+
 start_service() {
 start_service() {
-    procd_open_instance netpulse-agent
-    procd_set_param command "$BIN"
-    procd_set_param respawn "${respawn_threshold:-3600}" "${respawn_timeout:-5}" "${respawn_retry:-5}"
-    procd_set_param stdout 1
-    procd_set_param stderr 1
-    procd_set_param file /etc/netpulse-agent.env
-    procd_close_instance
+	selfheal_binary || logger -t netpulse-agent "self-heal: no se pudo restaurar el binario"
+	procd_open_instance netpulse-agent
+	procd_set_param command "$BIN"
+	procd_set_param respawn "${respawn_threshold:-3600}" "${respawn_timeout:-5}" "${respawn_retry:-5}"
+	procd_set_param stdout 1
+	procd_set_param stderr 1
+	procd_set_param file /etc/netpulse-agent.env
+	procd_close_instance
 }
 }
 INITEOF
 INITEOF
 chmod 0755 "$INIT"
 chmod 0755 "$INIT"
-$INIT enable
-$INIT restart
+
+# Watchdog + cron (mismo criterio que el paquete; detección por pidof,
+# compatible con BusyBox)
+cat > "$WATCHDOG" <<'WGEOF'
+#!/bin/sh
+# netpulse-watchdog — relanza el agente si el proceso murió o el heartbeat
+# lleva >300s sin latir. Cron cada 2 min.
+INIT=/etc/init.d/netpulse-agent
+HB=/tmp/netpulse-agent.heartbeat
+[ -x "$INIT" ] || exit 0
+if ! pidof netpulse-agent >/dev/null 2>&1; then
+	logger -t netpulse-watchdog "agente no está en marcha, reiniciando servicio"
+	"$INIT" restart >/dev/null 2>&1
+	exit 0
+fi
+if [ -f "$HB" ]; then
+	now=$(date +%s)
+	hb=$(cat "$HB" 2>/dev/null)
+	case "$hb" in ''|*[!0-9]*) exit 0 ;; esac
+	age=$((now - hb))
+	if [ "$age" -gt 300 ]; then
+		logger -t netpulse-watchdog "proceso vivo pero sin latido en ${age}s, reiniciando servicio"
+		"$INIT" restart >/dev/null 2>&1
+	fi
+fi
+exit 0
+WGEOF
+chmod 0755 "$WATCHDOG"
+( crontab -l 2>/dev/null | grep -v netpulse-watchdog ; echo '*/2 * * * * /usr/sbin/netpulse-watchdog' ) | crontab -
+/etc/init.d/cron restart >/dev/null 2>&1 || true
+
+"$INIT" enable
+"$INIT" restart
 `
 `
 }
 }
 
 

+ 124 - 0
server-go/internal/httpapi/reinstall_script_test.go

@@ -0,0 +1,124 @@
+// reinstall_script_test.go — contrato de reinstallScript (#463): instalación
+// completa del agente (binario verificado, init self-heal, watchdog, cron).
+package httpapi
+
+import (
+	"strings"
+	"testing"
+)
+
+func reinstallScriptForTest(t *testing.T) string {
+	t.Helper()
+	return reinstallScript(
+		"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",
+		},
+	)
+}
+
+func TestReinstallScriptConfig(t *testing.T) {
+	s := reinstallScriptForTest(t)
+	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_FILE\"",
+	} {
+		if !strings.Contains(s, want) {
+			t.Errorf("script sin %q", want)
+		}
+	}
+}
+
+func TestReinstallScriptArchAndDigests(t *testing.T) {
+	s := reinstallScriptForTest(t)
+	// Mapeo uname → goarch con alias arm completos.
+	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)
+		}
+	}
+	// El armv7 legacy (que el endpoint normaliza a arm) ya no se pide.
+	if strings.Contains(s, "arch=armv7\"") {
+		t.Error("el script no debe pedir arch=armv7 (normalizeArch espera arm)")
+	}
+	// Verificación sha256 presente y aborta con exit 21 si no coincide.
+	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 TestReinstallScriptSelfHealInit(t *testing.T) {
+	s := reinstallScriptForTest(t)
+	for _, want := range []string{
+		"selfheal_binary()",
+		`url="${NETPULSE_SERVER%/}/api/agents/${NETPULSE_SLUG}/binary?arch=${ARCH}"`,
+		"logger -t netpulse-agent \"self-heal: binario restaurado\"",
+		"selfheal_binary || logger -t netpulse-agent \"self-heal: no se pudo restaurar el binario\"",
+	} {
+		if !strings.Contains(s, want) {
+			t.Errorf("init sin self-heal: falta %q", want)
+		}
+	}
+	// El self-heal debe conocer los tres archs (mismo case que el exterior).
+	if strings.Count(s, "armv7l|armv7|armhf|arm") != 2 {
+		t.Errorf("case de arch incompleto en el script (apariciones: %d, esperadas 2)",
+			strings.Count(s, "armv7l|armv7|armhf|arm"))
+	}
+}
+
+func TestReinstallScriptWatchdogAndCron(t *testing.T) {
+	s := reinstallScriptForTest(t)
+	for _, want := range []string{
+		"pidof netpulse-agent", // pidof, nunca pgrep -x (BusyBox)
+		`echo '*/2 * * * * /usr/sbin/netpulse-watchdog'`,
+		"/etc/init.d/cron restart",
+	} {
+		if !strings.Contains(s, want) {
+			t.Errorf("watchdog/cron incompleto: falta %q", want)
+		}
+	}
+	if strings.Contains(s, "pgrep -x") {
+		t.Error("el watchdog no debe usar pgrep -x (bug BusyBox)")
+	}
+	// Idempotencia del cron: reemplaza la línea previa en vez de duplicarla.
+	if !strings.Contains(s, "grep -v netpulse-watchdog") {
+		t.Error("el cron no es idempotente")
+	}
+}
+
+func TestReinstallScriptFinishesWithStart(t *testing.T) {
+	s := reinstallScriptForTest(t)
+	if !strings.HasSuffix(strings.TrimSpace(s), "\"$INIT\" enable\n\"$INIT\" restart") {
+		t.Error("el script debe terminar con enable + restart")
+	}
+}
+
+func TestReinstallScriptEmptyDigestSkipsVerify(t *testing.T) {
+	s := reinstallScript(
+		"r", strings.Repeat("b2", 32), "http://s:3000",
+		map[string]string{"arm64": "", "arm": "", "amd64": ""},
+	)
+	// Sin digests: el case asigna SHA256 vacío y el guard salta la verificación.
+	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")
+	}
+}