Просмотр исходного кода

fix(rearmer): rotate the token in the NetGrip env

A NetGrip whose embedded agent held a stale token never recovered: the rearm
restarted the panel and then skipped the rotation because that path only ran for
native agents, and the rotation writes the native env NetGrip does not read. The
token now goes to the panel env and the panel restarts.

Closes #2208
gnacho 6 дней назад
Родитель
Сommit
0202b3b856

+ 4 - 0
CHANGELOG.md

@@ -7,6 +7,10 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ## [Unreleased]
 
+### Fixed
+
+- A NetGrip panel whose embedded agent carries an old token never recovered. The rearm restarted the panel and then rotated the token in the native agent's environment file, which NetGrip does not read, so the panel kept answering 401 every cycle and the supervisor kept restarting it on each cooldown. The token now goes into `/etc/netgrip/netpulse.env`, the file the embedded agent reads, and the panel is restarted after it (#2208).
+
 ## [2.55.1] - 2026-11-28
 
 ### Fixed

+ 15 - 6
server-go/internal/rearmer/rearmer.go

@@ -256,12 +256,14 @@ func (r *Rearmer) Rearm(slug string) (Result, error) {
 	//   (CmdNetgrip), que recarga el env y relanza el agente embebido; es la
 	//   vía de recuperación real para un NetGrip caído (#569).
 	cmd := Cmd
+	netgripKind := false
 	if r.agents != nil {
 		if _, _, kind, _, ok := r.agents.Info(slug); ok && kind == "netgrip" {
 			if _, fresh := r.agents.Fresh(slug); fresh {
 				return Result{}, ErrNetgripAgent
 			}
 			cmd = CmdNetgrip
+			netgripKind = true
 		}
 	}
 	// El slug debe tener token registrado (si no, 404 como DELETE).
@@ -319,16 +321,23 @@ func (r *Rearmer) Rearm(slug string) (Result, error) {
 
 	// #630: si reiniciar el proceso no recuperó el agente, puede ser un 401
 	// por desincronización de token (el server rotó el token pero el .env del
-	// router lo mantiene antiguo). Solo para agentes NATIVOS (cmd = Cmd): se
-	// regenera el token y se aplica en caliente (reescribe el .env + restart),
-	// que es la vía que arregla el desync sin reinstalar. Los NetGrip se
-	// recuperan con su propio CmdNetgrip (recarga env en memoria).
-	if !recovered && cmd == Cmd {
+	// router lo mantiene antiguo). Se regenera el token y se aplica en
+	// caliente (reescribe el .env + restart), que es la vía que arregla el
+	// desync sin reinstalar.
+	// #2208: el agente embebido en NetGrip lee SU env (/etc/netgrip/netpulse.env),
+	// no el del agente nativo, así que la rotación va al fichero del panel.
+	// Antes un NetGrip con token viejo no se recuperaba nunca: el supervisor
+	// reiniciaba el panel cada cooldown y anunciaba una rotación que no hacía.
+	if !recovered {
 		log.Printf("[netpulse] rearmer: %s did not push after restart - rotating token and rewriting env via SSH (timeout %v)", slug, SSHWait)
 		before2 := time.Now()
 		prevSeen2 := prevSeen
 		if err := r.rotateTokenAtomic(slug, func(t string) error {
-			_, err := r.pool.Run(host, reinstall.TokenPushScript(slug, t), SSHWait)
+			cmdTok := reinstall.TokenPushScript(slug, t)
+			if netgripKind {
+				cmdTok = reinstall.TokenPushScriptNetgrip(slug, t)
+			}
+			_, err := r.pool.Run(host, cmdTok, SSHWait)
 			return err
 		}); err == nil {
 			if r.waitForPush(slug, prevSeen2, before2) {

+ 14 - 5
server-go/internal/rearmer/rearmer_test.go

@@ -535,9 +535,11 @@ func (e *rearmEnv) pushNetgrip(slug string) {
 	e.reg.Ingest(&probe.Payload{Router: slug, Ts: e.now.Unix(), Version: "0.70.0", Kind: "netgrip"})
 }
 
-// TestRearmNetgripStaleUsaCmdNetgrip (#569): un agente NetGrip STALE (sin
-// push reciente) SÍ se rearma reiniciando el servicio netgrip del router (no
-// el netpulse-agent, que no existe en ese escenario).
+// TestRearmNetgripStaleUsaCmdNetgrip (#569, #2208): un agente NetGrip STALE
+// (sin push reciente) se rearma reiniciando el servicio netgrip del router (no
+// el netpulse-agent, que no existe en ese escenario). Si el push no vuelve, la
+// rotación de token va al env DEL PANEL (/etc/netgrip/netpulse.env), que es el
+// que su agente embebido lee; antes se saltaba y el panel quedaba en 401.
 func TestRearmNetgripStaleUsaCmdNetgrip(t *testing.T) {
 	env := makeRearmEnv(t, "patio")
 	env.pushNetgrip("patio")
@@ -551,8 +553,8 @@ func TestRearmNetgripStaleUsaCmdNetgrip(t *testing.T) {
 	if !res.Restarted {
 		t.Fatalf("rearm netgrip stale: Restarted=false %+v", res)
 	}
-	if env.ssh.count() != 1 {
-		t.Fatalf("quiero 1 comando SSH, tuve %d", env.ssh.count())
+	if env.ssh.count() != 2 {
+		t.Fatalf("quiero 2 comandos SSH (restart + rotación), tuve %d: %v", env.ssh.count(), env.ssh.cmds)
 	}
 	cmd := env.ssh.cmds[0]
 	if !strings.Contains(cmd, "/etc/init.d/netgrip") {
@@ -561,6 +563,13 @@ func TestRearmNetgripStaleUsaCmdNetgrip(t *testing.T) {
 	if strings.Contains(cmd, "netpulse-agent") {
 		t.Fatalf("el rearm netgrip NO debe tocar netpulse-agent, cmd=%q", cmd)
 	}
+	rot := env.ssh.cmds[1]
+	if !strings.Contains(rot, "ENV_FILE=/etc/netgrip/netpulse.env") {
+		t.Fatalf("la rotación de un NetGrip debe escribir el env del panel, cmd=%q", rot)
+	}
+	if strings.Contains(rot, "/etc/config/netpulse-agent") {
+		t.Fatalf("la rotación de un NetGrip no debe tocar la config del agente nativo, cmd=%q", rot)
+	}
 }
 
 // TestRearmNetgripFreshRechazado (#569): un NetGrip FRESH (empujando) no

+ 34 - 17
server-go/internal/reinstall/reinstall.go

@@ -546,12 +546,41 @@ say "agent started"
 // cuando el token cambia pero el binario y la config ya están bien (rotate
 // "en caliente").
 func TokenPushScript(slug, token string) string {
+	return tokenPushScript(token, "/etc/netpulse-agent.env", "/etc/init.d/netpulse-agent", true)
+}
+
+// TokenPushScriptNetgrip rota el token del agente embebido en NetGrip (#2208).
+// El panel lee su propio env, /etc/netgrip/netpulse.env, con los mismos
+// nombres NETPULSE_*; el del agente nativo no lo alcanza, así que un NetGrip
+// con el token antiguo respondía 401 para siempre aunque el servidor rotase.
+// No sincroniza UCI: NetGrip no lee /etc/config/netpulse-agent.
+func TokenPushScriptNetgrip(slug, token string) string {
+	return tokenPushScript(token, "/etc/netgrip/netpulse.env", "/etc/init.d/netgrip", false)
+}
+
+func tokenPushScript(token, envFile, initPath string, syncUCI bool) string {
+	uci := ""
+	if syncUCI {
+		uci = `
+# #1816: el init del paquete lee UCI primero y solo cae al env si el token de
+# UCI está vacío. Rotar solo el env dejaba el token viejo en
+# /etc/config/netpulse-agent y el agente respondía 401 para siempre. Se
+# sincronizan también server y slug: si UCI apunta a un servidor antiguo, el
+# token nuevo tampoco sirve.
+UCI_CFG=/etc/config/netpulse-agent
+if [ -f "$UCI_CFG" ] && command -v uci >/dev/null 2>&1; then
+	uci -q set netpulse-agent.main.server="$SERVER" || true
+	uci -q set netpulse-agent.main.slug="$SLUG" || true
+	uci -q set netpulse-agent.main.token=` + token + ` || true
+	uci -q commit netpulse-agent || true
+fi`
+	}
 	return `#!/bin/sh
 set -e
-ENV_FILE=/etc/netpulse-agent.env
-INIT=/etc/init.d/netpulse-agent
+ENV_FILE=` + envFile + `
+INIT=` + initPath + `
 # El env debe existir: el router ya tenía el agente instalado.
-[ -f "$ENV_FILE" ] || { echo "netpulse-agent.env does not exist, token not updated" >&2; exit 30; }
+[ -f "$ENV_FILE" ] || { echo "$ENV_FILE does not exist, token not updated" >&2; exit 30; }
 # Conservar el server y el slug del env existente para no romper la config.
 SERVER=$(sed -n 's/^NETPULSE_SERVER=//p' "$ENV_FILE" | head -n1)
 SLUG=$(sed -n 's/^NETPULSE_SLUG=//p' "$ENV_FILE" | head -n1)
@@ -562,7 +591,7 @@ SLUG=$(sed -n 's/^NETPULSE_SLUG=//p' "$ENV_FILE" | head -n1)
 # aplica una vez emparejado.
 FP=$(sed -n 's/^NETPULSE_SERVER_FP=//p' "$ENV_FILE" | head -n1)
 USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+=' "$ENV_FILE" | grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN)=') || true
-[ -n "$SLUG" ] || { echo "netpulse-agent.env has no NETPULSE_SLUG" >&2; exit 31; }
+[ -n "$SLUG" ] || { echo "$ENV_FILE has no NETPULSE_SLUG" >&2; exit 31; }
 umask 077
 cat > "$ENV_FILE.tmp" <<EOF
 NETPULSE_SERVER=$SERVER
@@ -577,19 +606,7 @@ if [ -n "$USER_VARS" ]; then
 fi
 chmod 600 "$ENV_FILE.tmp"
 # Swap atómico: el proceso vivo sigue leyendo el archivo íntegro.
-mv -f "$ENV_FILE.tmp" "$ENV_FILE"
-# #1816: el init del paquete lee UCI primero y solo cae al env si el token de
-# UCI está vacío. Rotar solo el env dejaba el token viejo en
-# /etc/config/netpulse-agent y el agente respondía 401 para siempre. Se
-# sincronizan también server y slug: si UCI apunta a un servidor antiguo, el
-# token nuevo tampoco sirve.
-UCI_CFG=/etc/config/netpulse-agent
-if [ -f "$UCI_CFG" ] && command -v uci >/dev/null 2>&1; then
-	uci -q set netpulse-agent.main.server="$SERVER" || true
-	uci -q set netpulse-agent.main.slug="$SLUG" || true
-	uci -q set netpulse-agent.main.token=` + token + ` || true
-	uci -q commit netpulse-agent || true
-fi
+mv -f "$ENV_FILE.tmp" "$ENV_FILE"` + uci + `
 # procd rearma solito por el file (procd_set_param file), pero por
 # determinismo reiniciamos el servicio explícitamente.
 [ -x "$INIT" ] && "$INIT" restart >/dev/null 2>&1 || true

+ 21 - 0
server-go/internal/reinstall/script_test.go

@@ -246,6 +246,27 @@ func TestTokenPushScriptConfig(t *testing.T) {
 	}
 }
 
+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", "",