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

fix(agents): refuse to serve an agent older than the router (#1840) (#1841)

Nacho 1 месяц назад
Родитель
Сommit
905076e7eb

+ 11 - 1
.github/workflows/release.yml

@@ -54,13 +54,23 @@ jobs:
           echo "agent=$AGENT_VERSION" >> "$GITHUB_OUTPUT"
           PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || true)
           if [ -n "$PREV_TAG" ]; then
+            PREV_AGENT=$(git show "$PREV_TAG:agent/VERSION" 2>/dev/null | tr -d '[:space:]' || true)
             if ! git diff --quiet "$PREV_TAG"..HEAD -- agent/; then
-              PREV_AGENT=$(git show "$PREV_TAG:agent/VERSION" 2>/dev/null | tr -d '[:space:]' || true)
               if [ -n "$PREV_AGENT" ] && [ "$PREV_AGENT" = "$AGENT_VERSION" ]; then
                 echo "::error::agent/ cambió desde $PREV_TAG pero agent/VERSION sigue en $AGENT_VERSION. Sube la versión del agente antes de taguear."
                 exit 1
               fi
             fi
+            # #1840: un release no puede rebajar la versión del agente. Si lo
+            # hace, el servidor embebe un agente más viejo que el que ya corre
+            # en los routers y un reinstall degradaría la flota.
+            if [ -n "$PREV_AGENT" ] && [ "$PREV_AGENT" != "$AGENT_VERSION" ]; then
+              NEWEST=$(printf '%s\n%s\n' "$PREV_AGENT" "$AGENT_VERSION" | sort -V | tail -n 1)
+              if [ "$NEWEST" = "$PREV_AGENT" ]; then
+                echo "::error::agent/VERSION bajó de $PREV_AGENT ($PREV_TAG) a $AGENT_VERSION. Publicar un servidor con un agente embebido más viejo que el de la flota no está permitido (#1840)."
+                exit 1
+              fi
+            fi
           fi
 
       - name: Build frontend + copia dist al embed (necesario para go:embed y tests)

+ 1 - 0
CHANGELOG.md

@@ -40,6 +40,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- A reinstall no longer downgrades an agent that is ahead of the server (#1840). The binary and the package endpoints compare the version the router last reported with the one embedded in the server and answer with a conflict when the router is newer, because serving an older build would revert fixes without a word. A unit that is down or has never reported is not blocked, so self-heal keeps working, and `?force=1` is the explicit way to reinstall anyway. The release workflow also fails when `agent/VERSION` goes backwards, which is how a server ended up embedding an agent older than the fleet.
 - A gateway without AdGuard no longer leaves half a row empty (#1834). The row width was decided by the two visibility checkboxes while the AdGuard card decided on its own whether to render, so on a unit without AdGuard the WireGuard card kept half the row and the other half stayed blank. The span now follows the cards that actually render: one card takes the full row, two split it. WireGuard is held to the same rule as AdGuard and only appears when the unit has a tunnel, which leaves a configured but idle tunnel visible because the interface is still there.
 - An owut upgrade that finishes updates the stored firmware target (#1825). The target row only got the new version from the agent callback, so a unit upgraded through the owut flow kept showing the previous version on every surface that reads the stored column while the board already reported the new one. The confirmation after the reboot now writes the version the board reports.
 - A locally administered MAC with no address and no lease is no longer remembered (#1818). The NMRP address a Netgear unit announces while it reboots to flash firmware never asks for an IP, so nothing but the memory of the previous cycle kept it in the client list with a lease that did not exist. The entry is still persisted as soon as it has an address, a DHCP lease or a previous record, so virtual machines and phones with MAC randomisation are untouched.

+ 48 - 0
server-go/internal/httpapi/agent.go

@@ -338,6 +338,34 @@ func (s *server) handleIngestAgent(w http.ResponseWriter, r *http.Request) {
 // instalación incluye el token y se ejecuta en el router.
 // ---------------------------------------------------------------------------
 
+// agentDowngradeBlocked (#1840) decide si el servidor debe negarse a servir su
+// binario embebido a un router que ya corre una versión más nueva. Sin esto,
+// un reinstall, un self-heal o la descarga del paquete .ipk revertían fixes en
+// silencio cuando el servidor se construyó con un agente más viejo que el que
+// corre en la flota.
+//
+// Solo aplica a agentes nativos que reportan versión: los external y netgrip
+// se actualizan por su cuenta y usan otra numeración. Sin estado no bloquea,
+// para que un agente caído o recién instalado pueda curarse. ?force=1 es la
+// confirmación explícita del operador.
+func (s *server) agentDowngradeBlocked(slug string, r *http.Request) (reported string, blocked bool) {
+	if r.URL.Query().Get("force") == "1" {
+		return "", false
+	}
+	// Build de desarrollo: la versión embebida no es real (default 0.1.0).
+	if v := agentbin.EmbeddedAgentVersion; v == "" || v == "0.1.0" {
+		return "", false
+	}
+	_, version, kind, _, ok := s.agents.Info(slug)
+	if !ok || version == "" || (kind != "" && kind != "native") {
+		return "", false
+	}
+	if vercmp.CmpBuild(version, agentbin.EmbeddedAgentVersion) > 0 {
+		return version, true
+	}
+	return "", false
+}
+
 func (s *server) handleAgentBinary(w http.ResponseWriter, r *http.Request) {
 	slug := r.PathValue("slug")
 	if !agentSlugRe.MatchString(slug) {
@@ -361,6 +389,12 @@ func (s *server) handleAgentBinary(w http.ResponseWriter, r *http.Request) {
 			"falta ?arch= (amd64, arm64, armv7, mips, mipsle)")
 		return
 	}
+	// #1840: no degradar un agente que ya va por delante del binario embebido.
+	if reported, blocked := s.agentDowngradeBlocked(slug, r); blocked {
+		writeError(w, http.StatusConflict, "agent_downgrade_refused",
+			"el router corre el agente "+reported+" y este servidor embebe "+agentbin.EmbeddedAgentVersion+"; repite con ?force=1 para forzar")
+		return
+	}
 	f, err := agentbin.Open(arch)
 	if err != nil {
 		writeError(w, http.StatusNotFound, "not_found",
@@ -409,6 +443,12 @@ func (s *server) handleAgentPackage(w http.ResponseWriter, r *http.Request) {
 			"falta ?arch= (amd64, arm64, arm, mips, mipsle)")
 		return
 	}
+	// #1840: no degradar un agente que ya va por delante del binario embebido.
+	if reported, blocked := s.agentDowngradeBlocked(slug, r); blocked {
+		writeError(w, http.StatusConflict, "agent_downgrade_refused",
+			"el router corre el agente "+reported+" y este servidor embebe "+agentbin.EmbeddedAgentVersion+"; repite con ?force=1 para forzar")
+		return
+	}
 	// #1476: format=ipk (por defecto) lo compone el servidor al vuelo desde el
 	// binario embebido. format=apk sirve el asset que firma el CI: el formato
 	// v3 de apk-tools no se puede fabricar aqui sin su SDK.
@@ -1027,6 +1067,14 @@ func (s *server) handleAgentReinstall(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusConflict, "netgrip_managed", "agente embebido en NetGrip: actualiza o reinstala el panel NetGrip en el propio router")
 		return
 	}
+	// #1840: no reinstalar un agente que ya va por delante del binario
+	// embebido. El script le dejaría una versión más vieja y perdería fixes
+	// sin avisar; ?force=1 es la confirmación explícita del operador.
+	if reported, blocked := s.agentDowngradeBlocked(slug, r); blocked {
+		writeError(w, http.StatusConflict, "agent_downgrade_refused",
+			"el router corre el agente "+reported+" y este servidor embebe "+agentbin.EmbeddedAgentVersion+"; repite con ?force=1 para forzar")
+		return
+	}
 
 	// Router del slug (tabla routers; mismo host que usa el rearm).
 	host := ""

+ 68 - 0
server-go/internal/httpapi/agent_binary_test.go

@@ -10,6 +10,7 @@ import (
 	"strings"
 	"testing"
 
+	"github.com/gnacho/netpulse/agent/probe"
 	"github.com/gnacho/netpulse/server-go/internal/agentbin"
 )
 
@@ -90,6 +91,73 @@ func TestAgentBinaryUnknownArch(t *testing.T) {
 	}
 }
 
+// #1840: el servidor no debe servir su binario embebido a un agente que ya
+// corre una versión más nueva: sería un downgrade silencioso que revierte
+// fixes. El operador puede forzarlo con ?force=1.
+func TestAgentBinaryRefusesDowngrade(t *testing.T) {
+	prev := agentbin.EmbeddedAgentVersion
+	agentbin.EmbeddedAgentVersion = "3.0.31"
+	t.Cleanup(func() { agentbin.EmbeddedAgentVersion = prev })
+
+	ts := makeAgentTestServer(t)
+	token := createTokenFor(t, ts, "rt1")
+	ts.agents.Ingest(&probe.Payload{Router: "rt1", Kind: "native", Version: "3.0.32"})
+
+	res := getBinary(t, ts, "rt1", token, "?arch=arm64")
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusConflict {
+		body, _ := io.ReadAll(res.Body)
+		t.Fatalf("agente más nuevo: quiero 409, tengo %d: %s", res.StatusCode, body)
+	}
+	body, _ := io.ReadAll(res.Body)
+	if !strings.Contains(string(body), "3.0.32") {
+		t.Fatalf("el error debe decir la versión reportada: %s", body)
+	}
+}
+
+// ?force=1 es la confirmación explícita: sirve el binario aunque el router
+// reporte una versión más nueva (reinstall de un agente roto).
+func TestAgentBinaryForceSkipsDowngradeGuard(t *testing.T) {
+	prev := agentbin.EmbeddedAgentVersion
+	agentbin.EmbeddedAgentVersion = "3.0.31"
+	t.Cleanup(func() { agentbin.EmbeddedAgentVersion = prev })
+
+	ts := makeAgentTestServer(t)
+	token := createTokenFor(t, ts, "rt1")
+	ts.agents.Ingest(&probe.Payload{Router: "rt1", Kind: "native", Version: "3.0.32"})
+
+	res := getBinary(t, ts, "rt1", token, "?arch=arm64&force=1")
+	defer res.Body.Close()
+	// 404 si el árbol no tiene binarios embebidos: el guard ya no bloquea.
+	if res.StatusCode == http.StatusConflict {
+		t.Fatal("?force=1 no debe devolver 409")
+	}
+}
+
+// Sin estado del agente (recién instalado o caído) no se bloquea: hay que
+// poder curarlo. Un agente más viejo que el embebido tampoco se bloquea.
+func TestAgentBinaryDowngradeGuardOnlyForNewerAgents(t *testing.T) {
+	prev := agentbin.EmbeddedAgentVersion
+	agentbin.EmbeddedAgentVersion = "3.0.31"
+	t.Cleanup(func() { agentbin.EmbeddedAgentVersion = prev })
+
+	ts := makeAgentTestServer(t)
+	token := createTokenFor(t, ts, "rt1")
+
+	res := getBinary(t, ts, "rt1", token, "?arch=arm64")
+	res.Body.Close()
+	if res.StatusCode == http.StatusConflict {
+		t.Fatal("sin estado del agente no debe bloquear")
+	}
+
+	ts.agents.Ingest(&probe.Payload{Router: "rt1", Kind: "native", Version: "3.0.30"})
+	res = getBinary(t, ts, "rt1", token, "?arch=arm64")
+	res.Body.Close()
+	if res.StatusCode == http.StatusConflict {
+		t.Fatal("un agente más viejo no debe bloquearse")
+	}
+}
+
 // #1367: el one-liner NO debe pre-descargar el binario (sin arch no puede
 // acertar en MIPS); debe delegar en install-agent.sh, que detecta la arch
 // del router por SSH y descarga del propio server con ?arch=.