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

feat(agents): NETPULSE_AGENT_URL so agents can use a LAN URL (#1336)

Closes #1335
Nacho 1 месяц назад
Родитель
Сommit
993a6f783e

+ 8 - 2
docs/AGENTE-OPENWRT.md

@@ -66,6 +66,12 @@ descarta lo más viejo (mismo patrón que el fix del buffer del satélite).
   flash es justa: a `/tmp` + script de arranque que lo re-descarga del
   servidor), token en `/etc/netpulse-agent.env` (chmod 600), init procd con
   `respawn`, `enabled` por defecto.
+- La URL base con la que el agente alcanza al server (la del propio comando)
+  se resuelve así (#1335): `NETPULSE_AGENT_URL` (p. ej. una URL de la LAN
+  como `http://192.168.1.50:8080` cuando el server se sirve tras un reverse
+  proxy con dominio público) > `NETPULSE_PUBLIC_URL` > el Host de la
+  petición con la que se generó el comando. Sin variables, el comando usa el
+  dominio desde el que se copió: los routers darían la vuelta por internet.
 - Opcional a futuro: paquete `.ipk` con postinst.
 - Upgrade: el updater existente del servidor se extiende a agentes (el agente
   reporta versión en cada push; el servidor ofrece binario firmado sha256).
@@ -97,8 +103,8 @@ escalado:
    timeout 10 s) y espera otro push nuevo hasta 30 s. Arregla el caso de
    un 401 por token desincronizado.
 3. **Reinstalación** (opt-in, `NETPULSE_AUTO_REINSTALL=1` +
-   `NETPULSE_PUBLIC_URL`): script canónico completo (binario verificado
-   + config + init self-heal), timeout SSH 300 s.
+   `NETPULSE_PUBLIC_URL` o `NETPULSE_AGENT_URL`): script canónico completo
+   (binario verificado + config + init self-heal), timeout SSH 300 s.
 
 Anti-martilleo: el supervisor rearma como mucho 1 vez cada 10 min por
 slug (reinstala 1 vez cada cooldown propio). NetGrip embebido solo

+ 9 - 4
server-go/cmd/netpulse/main.go

@@ -464,16 +464,21 @@ func run() error {
 		}
 		rearmSup = rearmer.NewSupervisor(arm, agentReg, dbHandle.DB, rearmEngine, 0, cooldown)
 		// #457: escalado rearm→reinstall (opt-in doble: AUTO_REINSTALL=1 y
-		// PUBLIC_URL configurada; la config ya lo valida como par).
-		if cfg.AutoReinstall && cfg.PublicURL != "" {
+		// alguna URL de agentes configurada; la config ya lo valida como
+		// par). #1335: AGENT_URL (LAN) manda sobre PUBLIC_URL.
+		agentURL := cfg.AgentURL
+		if agentURL == "" {
+			agentURL = cfg.PublicURL
+		}
+		if cfg.AutoReinstall && agentURL != "" {
 			var rcool time.Duration
 			if v := os.Getenv("NETPULSE_AUTO_REINSTALL_COOLDOWN_S"); v != "" {
 				if sec, err := strconv.Atoi(v); err == nil && sec > 0 {
 					rcool = time.Duration(sec) * time.Second
 				}
 			}
-			rearmSup.EnableReinstall(cfg.PublicURL, rcool)
-			log.Printf("[netpulse] escalado auto-reinstall activo (PUBLIC_URL %s)", cfg.PublicURL)
+			rearmSup.EnableReinstall(agentURL, rcool)
+			log.Printf("[netpulse] escalado auto-reinstall activo (agent URL %s)", agentURL)
 		}
 		rearmSup.Start()
 		if cooldown <= 0 {

+ 18 - 2
server-go/internal/config/config.go

@@ -65,6 +65,7 @@ type Config struct {
 	AutoRearm        bool   // NETPULSE_AUTO_REARM=1: supervisor rearma agentes caídos
 	AutoReinstall    bool   // NETPULSE_AUTO_REINSTALL=1: el supervisor escala rearm→reinstall (#457); exige PUBLIC_URL
 	PublicURL        string // NETPULSE_PUBLIC_URL: URL base con la que los routers alcanzan al server (reinstall/self-heal)
+	AgentURL         string // NETPULSE_AGENT_URL: URL base preferente SOLO para agentes (install line, reinstall, reemit, auto-reinstall); manda sobre PublicURL (#1335)
 	BeaconListen     string // NETPULSE_BEACON_LISTEN: socket UDP de beacons embebidos (#291); "" = off, p. ej. ":5140"
 	AgentAutoenroll  bool   // AGENT_AUTOENROLL=1: el responder UDP entrega token de alta y /pair lo acepta (#367)
 	Onbox            bool   // NETPULSE_ONBOX=1: modo on-box (Fase 9: config UCI, bootstrap AUTH_PASS)
@@ -300,8 +301,22 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 			publicURL = strings.TrimRight(publicURL, "/")
 		}
 	}
-	if autoReinstall && publicURL == "" {
-		errs.issues = append(errs.issues, issue{"NETPULSE_AUTO_REINSTALL", "NETPULSE_PUBLIC_URL is required when auto-reinstall is enabled"})
+	// NETPULSE_AGENT_URL: URL base (http(s)://host[:port]) con la que los
+	// AGENTES deben alcanzar al servidor, p. ej. una URL de la LAN
+	// (http://192.168.1.50:8080) cuando el server se sirve tras un reverse
+	// proxy con dominio público (#1335). Opcional; manda sobre
+	// NETPULSE_PUBLIC_URL en todo lo que configura la conexión agente ->
+	// server (install line, reinstall, reemit, auto-reinstall).
+	agentURL := strings.TrimSpace(env["NETPULSE_AGENT_URL"])
+	if agentURL != "" {
+		if !strings.HasPrefix(agentURL, "http://") && !strings.HasPrefix(agentURL, "https://") {
+			errs.issues = append(errs.issues, issue{"NETPULSE_AGENT_URL", "String must contain a http:// or https:// prefix"})
+		} else {
+			agentURL = strings.TrimRight(agentURL, "/")
+		}
+	}
+	if autoReinstall && publicURL == "" && agentURL == "" {
+		errs.issues = append(errs.issues, issue{"NETPULSE_AUTO_REINSTALL", "NETPULSE_PUBLIC_URL or NETPULSE_AGENT_URL is required when auto-reinstall is enabled"})
 	}
 
 	// MAX_SSE_CLIENTS: int 1..100, default 10
@@ -635,6 +650,7 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		AutoRearm:         autoRearm,
 		AutoReinstall:     autoReinstall,
 		PublicURL:         publicURL,
+		AgentURL:          agentURL,
 		BeaconListen:      beaconListen,
 		AgentAutoenroll:   agentAutoenroll,
 		Onbox:             onbox,

+ 43 - 0
server-go/internal/config/config_test.go

@@ -240,3 +240,46 @@ func TestPrivateCASettings(t *testing.T) {
 		}
 	}
 }
+
+func TestLoadAgentURL(t *testing.T) {
+	// Válida: se acepta y se recorta la barra final.
+	cfg, err := Load(map[string]string{
+		"AUTH_PASS": "diez-carac-", "NETPULSE_AGENT_URL": "http://192.168.1.50:8080/",
+	}, t.TempDir())
+	if err != nil {
+		t.Fatalf("Load: %v", err)
+	}
+	if cfg.AgentURL != "http://192.168.1.50:8080" {
+		t.Fatalf("AgentURL = %q, esperaba %q", cfg.AgentURL, "http://192.168.1.50:8080")
+	}
+
+	// Sin prefijo http(s)://: se rechaza señalando la variable.
+	_, err = Load(map[string]string{
+		"AUTH_PASS": "diez-carac-", "NETPULSE_AGENT_URL": "192.168.1.50:8080",
+	}, t.TempDir())
+	if err == nil || !strings.Contains(err.Error(), "NETPULSE_AGENT_URL") {
+		t.Fatalf("AGENT_URL sin prefijo debe fallar señalando la variable: %v", err)
+	}
+}
+
+func TestLoadAutoReinstallConAgentURL(t *testing.T) {
+	// #1335: AGENT_URL cubre el requisito de URL que pedía AUTO_REINSTALL.
+	cfg, err := Load(map[string]string{
+		"AUTH_PASS": "diez-carac-", "NETPULSE_AUTO_REINSTALL": "1",
+		"NETPULSE_AGENT_URL": "http://192.168.1.50:8080",
+	}, t.TempDir())
+	if err != nil {
+		t.Fatalf("AUTO_REINSTALL con AGENT_URL (sin PUBLIC_URL) no debe fallar: %v", err)
+	}
+	if !cfg.AutoReinstall {
+		t.Fatal("AutoReinstall debe quedar activo")
+	}
+
+	// Sin ninguna de las dos URL sigue fallando.
+	_, err = Load(map[string]string{
+		"AUTH_PASS": "diez-carac-", "NETPULSE_AUTO_REINSTALL": "1",
+	}, t.TempDir())
+	if err == nil || !strings.Contains(err.Error(), "NETPULSE_PUBLIC_URL") {
+		t.Fatalf("AUTO_REINSTALL sin ninguna URL debe fallar señalando el par: %v", err)
+	}
+}

+ 30 - 24
server-go/internal/httpapi/agent.go

@@ -439,6 +439,28 @@ func (s *server) rotateTokenHot(slug, token string) string {
 	return "hot"
 }
 
+// agentBaseURL: URL base con la que los agentes deben alcanzar al server.
+// Cadena de precedencia (#1335): NETPULSE_AGENT_URL (URL de la LAN para los
+// agentes) > NETPULSE_PUBLIC_URL > la URL de la petición actual. Antes de
+// #1335 el install line ignoraba ambas variables y siempre usaba el Host de
+// la sesión, así que tras un reverse proxy con dominio público el comando
+// copiado hacía los routers salir a internet para volver a entrar.
+func (s *server) agentBaseURL(r *http.Request) string {
+	if s.cfg != nil {
+		if s.cfg.AgentURL != "" {
+			return s.cfg.AgentURL
+		}
+		if s.cfg.PublicURL != "" {
+			return s.cfg.PublicURL
+		}
+	}
+	scheme := "http"
+	if auth.IsSecureRequest(r) {
+		scheme = "https"
+	}
+	return scheme + "://" + r.Host
+}
+
 // agentInstallLine: one-liner de instalación vía SSH desde esta máquina.
 // El host del router se resuelve de la tabla routers si el slug existe.
 // Fase 6.2: el binario se descarga del propio servidor con el token del agente
@@ -453,11 +475,7 @@ func (s *server) agentInstallLine(r *http.Request, slug, token string) string {
 			}
 		}
 	}
-	scheme := "http"
-	if auth.IsSecureRequest(r) {
-		scheme = "https"
-	}
-	server := scheme + "://" + r.Host
+	server := s.agentBaseURL(r)
 	// #572: el copy-command corre en el server, donde la llave de routers del
 	// app (cfg.SSHKeyPath) puede ser la única autorizada en el router. Si el
 	// script no la pasa, el SSH cae a la default (~/.ssh/id_*) y falla.
@@ -838,16 +856,10 @@ func (s *server) handleAgentReinstall(w http.ResponseWriter, r *http.Request) {
 	}
 
 	// URL base del server (para que el router descargue el binario).
-	// NETPULSE_PUBLIC_URL manda si está configurada (#457): sin ella, llamar
-	// al endpoint vía localhost haría que el router descargue de localhost.
-	scheme := "http"
-	if auth.IsSecureRequest(r) {
-		scheme = "https"
-	}
-	serverURL := scheme + "://" + r.Host
-	if s.cfg != nil && s.cfg.PublicURL != "" {
-		serverURL = s.cfg.PublicURL
-	}
+	// Cadena #1335: NETPULSE_AGENT_URL > NETPULSE_PUBLIC_URL (#457) > Host de
+	// la petición; sin las variables, llamar al endpoint vía localhost haría
+	// que el router descargue de localhost.
+	serverURL := s.agentBaseURL(r)
 
 	before := time.Now()
 	var prevSeen time.Time
@@ -920,15 +932,9 @@ func (s *server) handleAgentsReemit(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 
-	// URL base y trust: mismas reglas que el reinstall por unidad.
-	scheme := "http"
-	if auth.IsSecureRequest(r) {
-		scheme = "https"
-	}
-	serverURL := scheme + "://" + r.Host
-	if s.cfg != nil && s.cfg.PublicURL != "" {
-		serverURL = s.cfg.PublicURL
-	}
+	// URL base y trust: mismas reglas que el reinstall por unidad
+	// (AGENT_URL > PUBLIC_URL > Host de la petición, #1335).
+	serverURL := s.agentBaseURL(r)
 	trust := tlsmode.AgentTrust(s.tlsMgr, s.fingerprint, serverURL)
 
 	rows := routerstore.ListRouters(s.db.DB)

+ 108 - 0
server-go/internal/httpapi/agent_url_test.go

@@ -0,0 +1,108 @@
+// agent_url_test.go — #1335: NETPULSE_AGENT_URL como URL base preferente con
+// la que los agentes alcanzan al server. Cadena: AGENT_URL > PUBLIC_URL >
+// Host de la petición. Antes de #1335 el install line ignoraba ambas
+// variables, así que tras un reverse proxy con dominio público el comando
+// copiado apuntaba al dominio en vez de a la LAN.
+package httpapi_test
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+)
+
+// makeURLTestServer levanta el handler real con un env extra (las variables
+// NETPULSE_* del caso) para observar cómo queda el install line.
+func makeURLTestServer(t *testing.T, extraEnv map[string]string) *agentTestServer {
+	t.Helper()
+	auth.SetTrustProxy(true)
+	t.Cleanup(func() { auth.SetTrustProxy(false) })
+	dataDir := t.TempDir()
+	env := map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
+		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
+	}
+	for k, v := range extraEnv {
+		env[k] = v
+	}
+	cfg, err := config.Load(env, dataDir)
+	if err != nil {
+		t.Fatalf("config: %v", err)
+	}
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	secret, err := auth.EnsureSessionSecret(d, cfg)
+	if err != nil {
+		t.Fatalf("secret: %v", err)
+	}
+	if err := auth.EnsureUsers(d, cfg); err != nil {
+		t.Fatalf("users: %v", err)
+	}
+	reg := adapters.NewAgentRegistry(90 * time.Second)
+	hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
+	agentHub := sse.NewAgentHub(func(_, _ string) bool { return false })
+	handler := httpapi.NewHandler(httpapi.Deps{
+		Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
+		Agents: reg, Started: time.Now(), AgentHub: agentHub,
+	})
+	srv := httptest.NewServer(handler)
+	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+	if status != 204 {
+		t.Fatalf("login: %d", status)
+	}
+	ts := &agentTestServer{Server: srv, db: d, agents: reg, cookie: cookie}
+	t.Cleanup(func() {
+		srv.Close()
+		d.Close()
+	})
+	return ts
+}
+
+func TestAgentInstallLinePrefiereAgentURL(t *testing.T) {
+	ts := makeURLTestServer(t, map[string]string{
+		"NETPULSE_AGENT_URL":  "http://192.168.1.50:9999",
+		"NETPULSE_PUBLIC_URL": "https://netpulse.example.com",
+	})
+	status, _, install := createAgentToken(t, ts, "rt1")
+	if status != http.StatusCreated {
+		t.Fatalf("POST /api/agents: %d", status)
+	}
+	if !strings.Contains(install, "--server=http://192.168.1.50:9999") {
+		t.Fatalf("install line debe usar AGENT_URL: %s", install)
+	}
+	if strings.Contains(install, "netpulse.example.com") {
+		t.Fatalf("install line no debe usar PUBLIC_URL cuando hay AGENT_URL: %s", install)
+	}
+}
+
+func TestAgentInstallLinePrefierePublicURL(t *testing.T) {
+	ts := makeURLTestServer(t, map[string]string{
+		"NETPULSE_PUBLIC_URL": "https://netpulse.example.com",
+	})
+	_, _, install := createAgentToken(t, ts, "rt1")
+	if !strings.Contains(install, "--server=https://netpulse.example.com") {
+		t.Fatalf("install line debe usar PUBLIC_URL: %s", install)
+	}
+	if strings.Contains(install, "--server="+ts.URL) {
+		t.Fatalf("install line no debe caer al Host de la petición cuando hay PUBLIC_URL: %s", install)
+	}
+}
+
+func TestAgentInstallLineFallbackHostPeticion(t *testing.T) {
+	ts := makeURLTestServer(t, nil)
+	_, _, install := createAgentToken(t, ts, "rt1")
+	if !strings.Contains(install, "--server="+ts.URL) {
+		t.Fatalf("install line debe caer al Host de la petición: %s", install)
+	}
+}

+ 13 - 12
server-go/internal/rearmer/rearmer.go

@@ -344,11 +344,11 @@ func (r *Rearmer) Rearm(slug string) (Result, error) {
 // init self-heal + watchdog) y espera el push de vuelta. Es el escalado
 // cuando un rearme no recupera el agente (proceso muerto o binario perdido
 // por un sysupgrade).
-func (r *Rearmer) Reinstall(slug, publicURL string) (Result, error) {
+func (r *Rearmer) Reinstall(slug, agentURL string) (Result, error) {
 	if r.db == nil {
 		return Result{}, ErrNoDB
 	}
-	if publicURL == "" {
+	if agentURL == "" {
 		return Result{}, fmt.Errorf("reinstall automático sin NETPULSE_PUBLIC_URL")
 	}
 	if r.agents != nil {
@@ -398,9 +398,9 @@ func (r *Rearmer) Reinstall(slug, publicURL string) (Result, error) {
 	if err := r.rotateTokenAtomic(slug, func(t string) error {
 		var trust []reinstall.Trust
 		if f := r.trust.Load(); f != nil {
-			trust = append(trust, (*f)(publicURL))
+			trust = append(trust, (*f)(agentURL))
 		}
-		_, err := r.pool.Run(host, reinstall.ScriptWithTargets(slug, t, publicURL, reinstall.ServerFP(publicURL), reinstall.Digests(), targets, trust...), ReinstallSSHWait)
+		_, err := r.pool.Run(host, reinstall.ScriptWithTargets(slug, t, agentURL, reinstall.ServerFP(agentURL), reinstall.Digests(), targets, trust...), ReinstallSSHWait)
 		return err
 	}); err != nil {
 		return Result{}, fmt.Errorf("no se pudo instalar el agente en %s: %w", host, err)
@@ -468,7 +468,7 @@ type Supervisor struct {
 	// NETPULSE_PUBLIC_URL). Cuando un rearme ejecutado NO recupera el push,
 	// se reinstala el agente completo con cooldown propio (1 h por slug).
 	autoReinstall     bool
-	publicURL         string
+	agentURL          string
 	reinstallSlots    map[string]time.Time
 	reinstallCooldown time.Duration
 
@@ -511,14 +511,15 @@ func NewSupervisor(r *Rearmer, registry *adapters.AgentRegistry, db *sql.DB, eng
 }
 
 // EnableReinstall activa el escalado rearm→reinstall del supervisor (#457).
-// Requiere publicURL (NETPULSE_PUBLIC_URL): es la URL con la que el router
-// descarga el binario del servidor. cooldown <= 0 → 1 h.
-func (s *Supervisor) EnableReinstall(publicURL string, cooldown time.Duration) {
+// Requiere agentURL: la URL efectiva con la que los routers descargan el
+// binario del servidor (NETPULSE_AGENT_URL o NETPULSE_PUBLIC_URL; #1335).
+// cooldown <= 0 → 1 h.
+func (s *Supervisor) EnableReinstall(agentURL string, cooldown time.Duration) {
 	if cooldown <= 0 {
 		cooldown = ReinstallCooldownDefault
 	}
 	s.autoReinstall = true
-	s.publicURL = publicURL
+	s.agentURL = agentURL
 	s.reinstallCooldown = cooldown
 }
 
@@ -625,13 +626,13 @@ func (s *Supervisor) CheckOnce() {
 			continue
 		}
 		log.Printf("[netpulse] supervisor: el rearme no recuperó a %s — escalando (rotación de token%s)",
-			slug, map[bool]string{true: ", luego reinstall si sigue caído", false: ""}[s.autoReinstall && s.publicURL != ""])
+			slug, map[bool]string{true: ", luego reinstall si sigue caído", false: ""}[s.autoReinstall && s.agentURL != ""])
 		// #457: el rearme no recuperó el agente (proceso muerto o binario
 		// perdido). Si el escalado está activo, reinstalación completa con
 		// cooldown propio; solo para slugs con preconditions válidas.
-		if s.autoReinstall && s.publicURL != "" && s.reinstallSlotFree(slug) {
+		if s.autoReinstall && s.agentURL != "" && s.reinstallSlotFree(slug) {
 			log.Printf("[netpulse] supervisor: reinstalando el agente en %s vía SSH (timeout %v)", slug, ReinstallSSHWait)
-			if r2, err := s.rearmer.Reinstall(slug, s.publicURL); err == nil {
+			if r2, err := s.rearmer.Reinstall(slug, s.agentURL); err == nil {
 				s.markReinstallSlot(slug)
 				if r2.Recovered {
 					log.Printf("[netpulse] supervisor: agente %s recuperado con la reinstalación", slug)