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

fix(security): auditoría de seguridad — TRUST_PROXY, anti-replay, body cap y password mínima 10 (#59)

* docs: añadir Fase 12 — Auditoría de seguridad y robustez (bug-hunting)

* fix(server): auditoría de seguridad — TRUST_PROXY, anti-replay de ingesta, body cap y password mínima 10

- ClientIP e IsSecureRequest ignoran X-Forwarded-For/-Proto salvo con TRUST_PROXY=1 (evita falsear la IP para evadir el rate-limit de login/ingesta y forzar cookie Secure).
- Ingesta de agentes: valida la frescura de ts (AGENT_MAX_TS_DRIFT_S, default 5 min) — anti-replay de pushes capturados.
- readJSONBody limita el body a 64 KB (abuso de memoria en login/users/config).
- Password mínima 10 caracteres en alta y cambio (alineado con el resto de apps).
- Tests nuevos: TRUST_PROXY (XFF/XFP ignorados), anti-replay (pasado/futuro 401, en ventana 202).

* feat(version): v2.7.0 — changelog, bump de versión y roadmap de la auditoría de seguridad

- CHANGELOG.md nuevo (Keep a Changelog) con la release bug-hunting.
- Bump server-go Version y app a 2.7.0.
- ROADMAP: estado actual v2.7.0 con la Fase 12 completada.

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 месяцев назад
Родитель
Сommit
ab584ffcff

+ 39 - 0
CHANGELOG.md

@@ -0,0 +1,39 @@
+# Changelog
+
+Todos los cambios notables de NetPulse se documentan en este fichero.
+
+El formato se basa en [Keep a Changelog](https://keepachangelog.com/es/1.1.0/),
+y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/).
+
+## [Unreleased]
+
+## [2.7.0] - 2026-08-06
+
+### Added
+
+- Fase 12 en el ROADMAP: auditoría de seguridad y robustez (release bug-hunting).
+- `TRUST_PROXY`: cuando el servidor va detrás de un proxy/reverse, la IP del
+  cliente se toma de `X-Forwarded-For` y el tráfico HTTPS de
+  `X-Forwarded-Proto`. Por defecto no se confía en esas cabeceras.
+- Ventana de frescura del `ts` del agente en la ingesta (`AGENT_MAX_TS_DRIFT_S`,
+  default 5 min): rechaza pushes con marca de tiempo fuera de rango.
+
+### Fixed
+
+- **Bypass de rate-limit por `X-Forwarded-For` falso**: sin `TRUST_PROXY`, la IP
+  del cliente es la del socket; ya no se puede falsear para evadir el bloqueo
+  de fuerza bruta del login ni el rate-limit de la ingesta.
+- **Anti-replay en la ingesta de agentes**: un token robado ya no permite
+  reinyectar payloads antiguos capturados.
+- **Body sin límite en endpoints JSON** (login, usuarios, config, alertas,
+  push): techo de 64 KB por petición.
+- **Password mínima 10 caracteres** en alta y cambio de contraseña (antes 6).
+
+## [2.6.0] - 2026-08-05
+
+- Fase 7 (agente a fondo): iw events en tiempo real, SSE bidireccional
+  (AgentHub + refresh), `.ipk` vía opkg en gateway, profiling, CI de
+  empaquetado `.ipk`/`.apk`, landing web con posicionamiento OpenWrt nativo.
+- Fase 8 (consolidación): métricas en `/api/health`, registry de agentes
+  persistente, escalera de retención, recharts v3, webhook saliente con DLQ.
+- Actualización de stack: TS 7, Tailwind 4, Vite 8, react-router 8, sqlite 1.56.

+ 1 - 1
app/package.json

@@ -1,7 +1,7 @@
 {
   "name": "netpulse",
   "private": true,
-  "version": "2.6.0",
+  "version": "2.7.0",
   "type": "module",
   "scripts": {
     "dev": "vite",

+ 41 - 2
docs/ROADMAP.md

@@ -1,10 +1,13 @@
 # NetPulse — Hoja de ruta
 
-> Actualizada: 2026-08-06 (v2.6.0, Fase 7 completada; **Fase 8 COMPLETA**; Fases 9-11 reordenadas). 
+> Actualizada: 2026-08-06 (v2.7.0, **Fase 12 — Auditoría de seguridad COMPLETA**; Fases 9-11 reordenadas). 
 
-## Estado actual (v2.6.0) ✅
+## Estado actual (v2.7.0) ✅
 
 Hecho y en producción (CT 226 + 4 routers):
+- **Fase 12 — Auditoría de seguridad y robustez** (v2.7.0): TRUST_PROXY
+  (anti-bypass de rate-limit), anti-replay de ingesta, body cap en JSON,
+  password mínima 10, CHANGELOG.md. Cada fix con test propio.
 - **Fase 1 — Topología v5** (v2.1.0): FDB + LLDP en vivo, backhaul real,
   switches gestionados/inferidos, hipervisores con CTs anidados, collector.
 - **Fase 2 — Alertas, Push y agente piloto** (v2.2.0): motor de alertas,
@@ -425,6 +428,42 @@ ningún NOC multi-router; la webapp (Go + SSE) sigue siendo el visor de red.
 
 ---
 
+## Fase 12 — Auditoría de seguridad y robustez (release bug-hunting)
+
+Objetivo: pasada sistemática de caza de bugs y endurecimiento de seguridad
+sobre el código actual (server-go + app + agentes), materializada en una
+release de mantenimiento. Cada hallazgo se abre como issue y se cierra con su
+PR (convención issue→PR).
+
+**Alcance (áreas a revisar):**
+1. **Autenticación y autorización**: revisar que todas las rutas de mutación
+   (crear/revocar agentes, routers, rearm) exijan `RequireAdmin`; que no haya
+   rutas sensibles solo con `requireAuth`. (Relacionado con issue #6.)
+2. **CSRF**: los endpoints de mutación autenticados por cookie deben proteger
+   contra CSRF (SameSite + verificación de Origin cuando aplique).
+3. **Cabeceras de seguridad HTTP**: `X-Content-Type-Options`, `X-Frame-Options`
+   o CSP en respuestas del server y del SPA embebido.
+4. **Ingesta de agentes**: firma HMAC por mensaje + anti-replay (timestamp/nonce)
+   para que un token robado no baste para inyectar datos falsos.
+5. **Path traversal y servido estático**: revisar rutas de estáticos, descargas
+   del binario del agente y cualquier acceso a ficheros.
+6. **Secretos**: confirmar que tokens/secretos no aparecen en logs ni en
+   respuestas; que el `.env` de producción no contiene nada imprimible.
+7. **Dependencias**: `go list -m` y `npm audit` para deps del server-go y del
+   front; cerrar cualquier CVE HIGH/CRITICAL real.
+8. **Bugs latentes**: revisar manejo de errores, cierres de conexiones, races
+   en el poller y caminos de error poco probados.
+
+**Criterios de aceptación:**
+- Ninguna ruta de mutación sensible alcanzable con rol `user`.
+- Las respuestas del server llevan cabeceras de seguridad básicas.
+- 0 CVEs HIGH/CRITICAL reales en deps (audit verde o justificado).
+- Tests nuevos cubriendo cada fix (test que falla primero).
+
+**Deploy**: release + install.sh en CT 226 y agentes.
+
+---
+
 ## Deudas y mejoras transversales (sin fase asignada)
 
 - **Series del collector en server-go**: hoy son independientes

+ 2 - 0
server-go/cmd/netpulse/main.go

@@ -62,6 +62,8 @@ func run() error {
 		fmt.Fprintln(os.Stderr, err.Error())
 		os.Exit(1)
 	}
+	// Auditoría de seguridad #1: la IP confiable (XFF) solo si TRUST_PROXY.
+	auth.SetTrustProxy(cfg.TrustProxy)
 
 	dbHandle, err := db.Open(cfg.DataDir)
 	if err != nil {

+ 27 - 5
server-go/internal/auth/auth.go

@@ -187,11 +187,17 @@ func sessionCookieValue(r *http.Request) string {
 	return m[1]
 }
 
-// IsSecureRequest: URL https o primer X-Forwarded-Proto == "https".
+// IsSecureRequest: URL https, o primer X-Forwarded-Proto == "https" SOLO si
+// TRUST_PROXY (despliegue detrás de proxy con TLS terminado fuera). Sin
+// TRUST_PROXY, un cliente de la LAN no puede forzar la cookie Secure
+// (hallazgo #1 de la auditoría de seguridad).
 func IsSecureRequest(r *http.Request) bool {
 	if r.TLS != nil || r.URL.Scheme == "https" {
 		return true
 	}
+	if !trustProxy {
+		return false
+	}
 	proto := r.Header.Get("X-Forwarded-Proto")
 	if proto == "" {
 		return false
@@ -330,11 +336,27 @@ func SessionIDFromRequest(d *db.DB, secret string, r *http.Request) string {
 // Rate-limit en SQLite (persiste tras reinicios)
 // ---------------------------------------------------------------------------
 
-// ClientIP: primer X-Forwarded-For o la IP remota o 'unknown'.
+// trustProxy es la configuración global del paquete: si es true, ClientIP
+// confía en X-Forwarded-For (despliegue detrás de un proxy/reverse); si es
+// false (defecto), usa la IP remota del socket y XFF se ignora — un cliente
+// de la LAN no puede falsear su IP para evadir el rate-limit de login o de
+// ingesta (auditoría de seguridad, hallazgo #1). Se fija una vez al arrancar
+// desde config (TRUST_PROXY).
+var trustProxy bool
+
+// SetTrustProxy fija si las cabeceras X-Forwarded-For/-Proto son confiables.
+func SetTrustProxy(on bool) { trustProxy = on }
+
+// TrustProxy devuelve el valor actual (útil en tests).
+func TrustProxy() bool { return trustProxy }
+
+// ClientIP: primer X-Forwarded-For (solo si TRUST_PROXY) o la IP remota.
 func ClientIP(r *http.Request) string {
-	if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
-		if first := strings.TrimSpace(strings.Split(xff, ",")[0]); first != "" {
-			return first
+	if trustProxy {
+		if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
+			if first := strings.TrimSpace(strings.Split(xff, ",")[0]); first != "" {
+				return first
+			}
 		}
 	}
 	if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil && host != "" {

+ 41 - 0
server-go/internal/auth/auth_test.go

@@ -139,6 +139,10 @@ func TestSessionWithoutUserIDDoesNotAuthenticate(t *testing.T) {
 }
 
 func TestRateLimitFifthFailArmsLock(t *testing.T) {
+	// El test simula la IP del cliente vía X-Forwarded-For; en producción
+	// solo se confía con TRUST_PROXY (auditoría #1).
+	SetTrustProxy(true)
+	t.Cleanup(func() { SetTrustProxy(false) })
 	d := testDB(t)
 	newReq := func() *http.Request {
 		r := httptest.NewRequest("POST", "/api/auth/login", nil)
@@ -176,6 +180,9 @@ func TestRateLimitFifthFailArmsLock(t *testing.T) {
 }
 
 func TestBuildSessionCookieFlags(t *testing.T) {
+	// El caso X-Forwarded-Proto=https requiere TRUST_PROXY (auditoría #1).
+	SetTrustProxy(true)
+	t.Cleanup(func() { SetTrustProxy(false) })
 	cfg := &config.Config{CookieSecure: "auto"}
 	r := httptest.NewRequest("POST", "http://x/api/auth/login", nil)
 	c := BuildSessionCookie(cfg, r, "id.sig", 2592000)
@@ -200,3 +207,37 @@ func TestBuildSessionCookieFlags(t *testing.T) {
 		t.Fatal("never debe omitir Secure incluso en https")
 	}
 }
+
+func TestClientIPSinTrustProxyIgnoraXFF(t *testing.T) {
+	// Auditoría #1: sin TRUST_PROXY, X-Forwarded-For se IGNORA — la IP del
+	// cliente es la del socket, no se puede falsear para evadir rate-limit.
+	SetTrustProxy(false)
+	t.Cleanup(func() { SetTrustProxy(false) })
+	r := httptest.NewRequest("POST", "/api/auth/login", nil)
+	r.RemoteAddr = "192.168.1.55:50000"
+	r.Header.Set("X-Forwarded-For", "10.9.9.9")
+	if got := ClientIP(r); got != "192.168.1.55" {
+		t.Fatalf("sin TRUST_PROXY debe usar la IP del socket: %q", got)
+	}
+	// Con TRUST_PROXY, XFF es la IP del cliente real (detrás de proxy).
+	SetTrustProxy(true)
+	if got := ClientIP(r); got != "10.9.9.9" {
+		t.Fatalf("con TRUST_PROXY debe usar XFF: %q", got)
+	}
+}
+
+func TestIsSecureRequestSinTrustProxyIgnoraXFP(t *testing.T) {
+	// Auditoría #1: sin TRUST_PROXY, X-Forwarded-Proto se IGNORA (un cliente
+	// de la LAN no puede forzar la cookie Secure).
+	SetTrustProxy(false)
+	t.Cleanup(func() { SetTrustProxy(false) })
+	r := httptest.NewRequest("POST", "http://x/", nil)
+	r.Header.Set("X-Forwarded-Proto", "https")
+	if IsSecureRequest(r) {
+		t.Fatal("sin TRUST_PROXY, XFP=https no debe considerarse seguro")
+	}
+	SetTrustProxy(true)
+	if !IsSecureRequest(r) {
+		t.Fatal("con TRUST_PROXY, XFP=https debe considerarse seguro")
+	}
+}

+ 30 - 0
server-go/internal/config/config.go

@@ -57,6 +57,8 @@ type Config struct {
 	Webhook       *Webhook
 	WGInterface   string
 	CookieSecure  string // "auto" | "always" | "never"
+	TrustProxy    bool   // confiar en X-Forwarded-For/-Proto (detrás de proxy)
+	MaxTsDriftSec int    // ventana frescura ts agente en s (0 → default 5 min)
 	GithubRepo    string
 	GithubToken   string
 	ServerRoot    string
@@ -220,6 +222,32 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		}
 	}
 
+	// TRUST_PROXY: '1' solo cuando el servidor va detrás de un proxy/reverse
+	// que setea X-Forwarded-For/-Proto (p. ej. NPM/Tailscale). Por defecto NO
+	// se confía: la IP del socket es la real (auditoría de seguridad #1).
+	trustProxy := false
+	if v, ok := env["TRUST_PROXY"]; ok && v != "" {
+		switch v {
+		case "0":
+		case "1":
+			trustProxy = true
+		default:
+			errs.issues = append(errs.issues, issue{"TRUST_PROXY", "Invalid enum value. Expected '0' | '1'"})
+		}
+	}
+
+	// AGENT_MAX_TS_DRIFT_S: ventana de frescura del ts del agente en segundos
+	// (anti-replay, auditoría de seguridad #2). 0 → default 5 min.
+	maxTsDriftSec := 0
+	if v, ok := env["AGENT_MAX_TS_DRIFT_S"]; ok && v != "" {
+		n, err := strconv.Atoi(strings.TrimSpace(v))
+		if err != nil || n < 0 {
+			errs.issues = append(errs.issues, issue{"AGENT_MAX_TS_DRIFT_S", "Expected int >= 0"})
+		} else {
+			maxTsDriftSec = n
+		}
+	}
+
 	wgInterface := "wg0"
 	if v, ok := env["WG_INTERFACE"]; ok && v != "" {
 		wgInterface = v
@@ -339,6 +367,8 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		Webhook:       webhook,
 		WGInterface:   wgInterface,
 		CookieSecure:  cookieSecure,
+		TrustProxy:    trustProxy,
+		MaxTsDriftSec: maxTsDriftSec,
 		GithubRepo:    githubRepo,
 		GithubToken:   githubToken,
 		ServerRoot:    serverRoot,

+ 1 - 1
server-go/internal/httpapi/admin_gate_test.go

@@ -51,7 +51,7 @@ func do(t *testing.T, method, base, path, cookie string) *http.Response {
 func TestRutasAdminDevuelven403ParaRolUser(t *testing.T) {
 	ts := makeTestServer(t)
 	_, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
-	userCookie := createUserAndLogin(t, ts.URL, adminCookie, "viewer", "clave1234", "user")
+	userCookie := createUserAndLogin(t, ts.URL, adminCookie, "viewer", "clave12345", "user")
 
 	adminOnly := []struct{ method, path string }{
 		{"POST", "/api/agents"},

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

@@ -43,6 +43,11 @@ const (
 	ingestRateWindow = time.Minute
 	// agentTokenKeyPrefix: kv agent.token.<slug> = sha256 hex del token.
 	agentTokenKeyPrefix = "agent.token."
+	// maxTsDrift: ventana de frescura del `ts` del agente (anti-replay,
+	// auditoría de seguridad #2). Payloads con ts fuera de |±maxTsDrift|
+	// respecto al reloj del servidor se rechazan con 401 (evita reinyectar
+	// pushes viejos capturados). Configurable vía AGENT_MAX_TS_DRIFT_S.
+	maxTsDriftDefault = 5 * time.Minute
 )
 
 // agentSlugRe: slugs de equipo válidos (mismo alfabeto que routerstore).
@@ -198,6 +203,14 @@ func (s *server) handleIngestAgent(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusUnauthorized, "invalid_signature", err.Error())
 		return
 	}
+	// 401: anti-replay (auditoría #2) — el `ts` debe estar dentro de la
+	// ventana de frescura respecto al reloj del servidor. Rechaza pushes
+	// viejos capturados/reinyectados y saltos de reloj grandes del agente.
+	if drift := time.Since(time.Unix(p.Ts, 0)); drift < -s.maxTsDrift || drift > s.maxTsDrift {
+		writeError(w, http.StatusUnauthorized, "stale_payload",
+			"ts fuera de la ventana de frescura (revisa el reloj del router)")
+		return
+	}
 	if s.agents == nil {
 		writeError(w, http.StatusServiceUnavailable, "unavailable",
 			"el servidor no tiene registry de agentes")

+ 53 - 10
server-go/internal/httpapi/agent_api_test.go

@@ -35,6 +35,11 @@ type agentTestServer struct {
 // makeAgentTestServer: app real con registry de agentes + sesión admin.
 func makeAgentTestServer(t *testing.T) *agentTestServer {
 	t.Helper()
+	// Los helpers de test simulan IPs distintas vía X-Forwarded-For (rate
+	// limit); el comportamiento por defecto en producción es NO confiar en
+	// XFF (auditoría #1), así que aquí se activa explícitamente.
+	auth.SetTrustProxy(true)
+	t.Cleanup(func() { auth.SetTrustProxy(false) })
 	dataDir := t.TempDir()
 	cfg, err := config.Load(map[string]string{
 		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
@@ -114,7 +119,16 @@ func ingest(t *testing.T, ts *agentTestServer, token, ip, payload string) *http.
 	return res
 }
 
-const validPayload = `{"router":"patio","ts":1754140000,"version":"0.1.0","data":{"system":{"sysinfo":{"uptime":100,"load":[0,0,0],"memory":{"total":100,"free":50,"buffered":0,"available":50}},"cpu":10,"temp":40},"wireless":{"clients":{}},"dhcp":{"leases":[]},"fdb":{"macs":{}}}}`
+// validPayload construye un payload de agente válido con ts ACTUAL (el
+// anti-replay de la auditoría #2 rechaza ts antiguos, así que el payload de
+// test no puede llevar un ts fijo del pasado).
+func validPayload(ts ...int64) string {
+	t := time.Now().Unix()
+	if len(ts) > 0 {
+		t = ts[0]
+	}
+	return fmt.Sprintf(`{"router":"patio","ts":%d,"version":"0.1.0","data":{"system":{"sysinfo":{"uptime":100,"load":[0,0,0],"memory":{"total":100,"free":50,"buffered":0,"available":50}},"cpu":10,"temp":40},"wireless":{"clients":{}},"dhcp":{"leases":[]},"fdb":{"macs":{}}}}`, t)
+}
 
 func TestIngestTokenValidoEInvalido(t *testing.T) {
 	ts := makeAgentTestServer(t)
@@ -135,7 +149,7 @@ func TestIngestTokenValidoEInvalido(t *testing.T) {
 		t.Fatalf("kv debería guardar sha256: %q", stored)
 	}
 	// Ingesta sin sesión (exenta del middleware) + token válido → 202
-	res := ingest(t, ts, token, "10.0.0.1", validPayload)
+	res := ingest(t, ts, token, "10.0.0.1", validPayload())
 	res.Body.Close()
 	if res.StatusCode != 202 {
 		t.Fatalf("ingest válido: %d", res.StatusCode)
@@ -145,7 +159,7 @@ func TestIngestTokenValidoEInvalido(t *testing.T) {
 	}
 	// Token inválido → 401; sin token → 401; token de otro slug → 401
 	for _, tok := range []string{"", "deadbeef", token + "00"} {
-		res := ingest(t, ts, tok, "10.0.0.2", validPayload)
+		res := ingest(t, ts, tok, "10.0.0.2", validPayload())
 		res.Body.Close()
 		if res.StatusCode != 401 {
 			t.Fatalf("token %q debería dar 401, dio %d", tok, res.StatusCode)
@@ -178,7 +192,7 @@ func TestIngestBodyGrandeYPayloadInvalido(t *testing.T) {
 		}
 	}
 	// El pipeline sigue sano tras los 400
-	res = ingest(t, ts, token, "10.0.1.2", validPayload)
+	res = ingest(t, ts, token, "10.0.1.2", validPayload())
 	res.Body.Close()
 	if res.StatusCode != 202 {
 		t.Fatalf("ingest tras 400s: %d", res.StatusCode)
@@ -190,13 +204,13 @@ func TestIngestRateLimit(t *testing.T) {
 	_, token, _ := createAgentToken(t, ts, "patio")
 	// 30/min por IP: las 30 primeras pasan, la 31 es 429 con Retry-After
 	for i := 0; i < 30; i++ {
-		res := ingest(t, ts, token, "10.0.2.1", validPayload)
+		res := ingest(t, ts, token, "10.0.2.1", validPayload())
 		res.Body.Close()
 		if res.StatusCode != 202 {
 			t.Fatalf("push %d: %d", i, res.StatusCode)
 		}
 	}
-	res := ingest(t, ts, token, "10.0.2.1", validPayload)
+	res := ingest(t, ts, token, "10.0.2.1", validPayload())
 	defer res.Body.Close()
 	if res.StatusCode != 429 {
 		t.Fatalf("push 31 debería ser 429, dio %d", res.StatusCode)
@@ -209,7 +223,7 @@ func TestIngestRateLimit(t *testing.T) {
 		t.Fatalf("429 shape: %v retry=%q", body, res.Header.Get("Retry-After"))
 	}
 	// Otra IP no está limitada
-	res2 := ingest(t, ts, token, "10.0.2.2", validPayload)
+	res2 := ingest(t, ts, token, "10.0.2.2", validPayload())
 	res2.Body.Close()
 	if res2.StatusCode != 202 {
 		t.Fatalf("otra IP: %d", res2.StatusCode)
@@ -243,7 +257,7 @@ func TestAgentsListYRevocacion(t *testing.T) {
 	}
 
 	// Tras un push: lastSeen (unix s) + versión + fresh
-	res2 := ingest(t, ts, token, "10.0.3.1", validPayload)
+	res2 := ingest(t, ts, token, "10.0.3.1", validPayload())
 	res2.Body.Close()
 	res = get(t, ts.URL, "/api/agents", ts.cookie)
 	body = readJSON(t, res)
@@ -270,7 +284,7 @@ func TestAgentsListYRevocacion(t *testing.T) {
 	if resDel.StatusCode != 204 {
 		t.Fatalf("DELETE: %d", resDel.StatusCode)
 	}
-	res3 := ingest(t, ts, token, "10.0.3.2", validPayload)
+	res3 := ingest(t, ts, token, "10.0.3.2", validPayload())
 	res3.Body.Close()
 	if res3.StatusCode != 401 {
 		t.Fatalf("push tras revocar: %d", res3.StatusCode)
@@ -308,7 +322,7 @@ func TestAgentStatePersistenciaYRestauracion(t *testing.T) {
 	ts := makeAgentTestServer(t)
 	_, token, _ := createAgentToken(t, ts, "patio")
 
-	res := ingest(t, ts, token, "10.0.0.1", validPayload)
+	res := ingest(t, ts, token, "10.0.0.1", validPayload())
 	res.Body.Close()
 	if res.StatusCode != 202 {
 		t.Fatalf("ingest: %d", res.StatusCode)
@@ -336,3 +350,32 @@ func TestAgentStatePersistenciaYRestauracion(t *testing.T) {
 		t.Fatalf("payload no fresco tras restauración: fresh=%v", fresh)
 	}
 }
+
+// TestIngestAntiReplay (auditoría #2): un payload con ts fuera de la ventana
+// de frescura (pasado o futuro) se rechaza con 401 stale_payload, aunque el
+// token y el HMAC sean correctos — evita reinyectar pushes viejos capturados.
+func TestIngestAntiReplay(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	_, token, _ := createAgentToken(t, ts, "patio")
+
+	stale := validPayload(time.Now().Add(-10 * time.Minute).Unix())
+	res := ingest(t, ts, token, "10.0.4.1", stale)
+	res.Body.Close()
+	if res.StatusCode != 401 {
+		t.Fatalf("ts pasado debería dar 401, dio %d", res.StatusCode)
+	}
+
+	future := validPayload(time.Now().Add(10 * time.Minute).Unix())
+	res = ingest(t, ts, token, "10.0.4.2", future)
+	res.Body.Close()
+	if res.StatusCode != 401 {
+		t.Fatalf("ts futuro debería dar 401, dio %d", res.StatusCode)
+	}
+
+	// ts justo dentro de la ventana → 202
+	res = ingest(t, ts, token, "10.0.4.3", validPayload(time.Now().Add(-2*time.Minute).Unix()))
+	res.Body.Close()
+	if res.StatusCode != 202 {
+		t.Fatalf("ts en ventana debería dar 202, dio %d", res.StatusCode)
+	}
+}

+ 1 - 1
server-go/internal/httpapi/demo_test.go

@@ -13,7 +13,7 @@ import (
 func TestDemoEnable403ParaRolUser(t *testing.T) {
 	ts := makeTestServer(t)
 	_, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
-	userCookie := createUserAndLogin(t, ts.URL, adminCookie, "viewerdemo", "clave1234", "user")
+	userCookie := createUserAndLogin(t, ts.URL, adminCookie, "viewerdemo", "clave12345", "user")
 
 	res := do(t, "POST", ts.URL, "/api/demo/enable", userCookie)
 	if res.StatusCode != http.StatusForbidden {

+ 7 - 3
server-go/internal/httpapi/httpapi_test.go

@@ -30,6 +30,10 @@ type testServer struct {
 // DB temporal, config AUTH_USER=admin AUTH_PASS=test1234 DEMO_MODE=1.
 func makeTestServer(t *testing.T) *testServer {
 	t.Helper()
+	// Los helpers de test simulan IPs distintas vía X-Forwarded-For (rate
+	// limit); por defecto en producción NO se confía en XFF (auditoría #1).
+	auth.SetTrustProxy(true)
+	t.Cleanup(func() { auth.SetTrustProxy(false) })
 	dataDir := t.TempDir()
 	cfg, err := config.Load(map[string]string{
 		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
@@ -294,7 +298,7 @@ func TestUsersCRUD(t *testing.T) {
 	}
 
 	// Alta 201
-	req, _ := http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"secreto1"}`))
+	req, _ := http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"secreto12345"}`))
 	req.Header.Set("Cookie", "session="+adminCookie)
 	res, _ = http.DefaultClient.Do(req)
 	if res.StatusCode != 201 {
@@ -305,7 +309,7 @@ func TestUsersCRUD(t *testing.T) {
 	res.Body.Close()
 
 	// Duplicado 409
-	req, _ = http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"otra1234"}`))
+	req, _ = http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"otra123456"}`))
 	req.Header.Set("Cookie", "session="+adminCookie)
 	res, _ = http.DefaultClient.Do(req)
 	body = readJSON(t, res)
@@ -326,7 +330,7 @@ func TestUsersCRUD(t *testing.T) {
 	}
 
 	// El usuario creado puede loguear
-	status, anaCookie, _ := loginCookie(t, srv.URL, "ana", "secreto1")
+	status, anaCookie, _ := loginCookie(t, srv.URL, "ana", "secreto12345")
 	if status != 204 {
 		t.Fatalf("login ana: got %d", status)
 	}

+ 1 - 1
server-go/internal/httpapi/rearm_api_test.go

@@ -225,7 +225,7 @@ func TestRearmRecuperado200(t *testing.T) {
 	// En paralelo: 500 ms después el agente "vuelve a empujar"
 	go func() {
 		time.Sleep(200 * time.Millisecond)
-		res := rearmIngest(t, ts, tok, validPayload)
+		res := rearmIngest(t, ts, tok, validPayload())
 		res.Body.Close()
 	}()
 

+ 17 - 3
server-go/internal/httpapi/server.go

@@ -30,7 +30,7 @@ import (
 )
 
 // Version es la versión del backend (app.js:18).
-const Version = "2.6.0"
+const Version = "2.7.0"
 
 // Deps son las dependencias del servidor API (como createApp de app.js).
 type Deps struct {
@@ -87,6 +87,9 @@ type server struct {
 
 	// Rate limit por IP de POST /api/ingest/agent (30/min, SPEC-AGENTE §1).
 	ingestLimit *ipRateLimit
+
+	// Ventana de frescura del `ts` del agente (anti-replay, auditoría #2).
+	maxTsDrift time.Duration
 }
 
 // NewHandler ensambla el handler HTTP completo (API + estáticos + SPA).
@@ -115,6 +118,11 @@ func NewHandler(d Deps) http.Handler {
 		}
 		s.rearmer = rearmer.New(dbHandle, d.Agents, d.Pool, rearmEngine, d.RearmPollWait)
 	}
+	// Ventana de frescura del ts del agente (anti-replay, auditoría #2).
+	s.maxTsDrift = maxTsDriftDefault
+	if d.Config != nil && d.Config.MaxTsDriftSec > 0 {
+		s.maxTsDrift = time.Duration(d.Config.MaxTsDriftSec) * time.Second
+	}
 	mode := d.Adapter.Mode()
 
 	mux := http.NewServeMux()
@@ -252,9 +260,15 @@ func writeError(w http.ResponseWriter, status int, code string, message ...strin
 	writeJSON(w, status, map[string]any{"error": code})
 }
 
-// readJSONBody parsea el body JSON; devuelve false si no es JSON válido
-// (equivalente a c.req.json().catch(() => null)).
+// maxBodyBytes: techo defensivo para cualquier body JSON de sesión
+// (login, users, config, alerts, push). Todos los cuerpos reales son < 1 KB;
+// el cap evita abuso de memoria con bodies gigantes (auditoría #3).
+const maxBodyBytes = 64 << 10
+
+// readJSONBody parsea el body JSON; devuelve false si no es JSON válido o
+// supera maxBodyBytes (equivalente a c.req.json().catch(() => null)).
 func readJSONBody(r *http.Request, dst any) bool {
+	r.Body = http.MaxBytesReader(nil, r.Body, maxBodyBytes)
 	dec := json.NewDecoder(r.Body)
 	if err := dec.Decode(dst); err != nil {
 		return false

+ 4 - 4
server-go/internal/httpapi/users.go

@@ -163,8 +163,8 @@ func (s *server) handleCreateUser(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 	password := *body.Password
-	if len(password) < 6 {
-		writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 6 character(s)")
+	if len(password) < 10 {
+		writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 10 character(s)")
 		return
 	}
 	if len(password) > 128 {
@@ -230,8 +230,8 @@ func (s *server) handleSetPassword(w http.ResponseWriter, r *http.Request) {
 	var body struct {
 		Password *string `json:"password"`
 	}
-	if !readJSONBody(r, &body) || body.Password == nil || len(*body.Password) < 6 || len(*body.Password) > 128 {
-		writeError(w, http.StatusBadRequest, "invalid_input", "password mínimo 6 caracteres")
+	if !readJSONBody(r, &body) || body.Password == nil || len(*body.Password) < 10 || len(*body.Password) > 128 {
+		writeError(w, http.StatusBadRequest, "invalid_input", "password mínimo 10 caracteres")
 		return
 	}
 	hash, err := auth.HashPassword(*body.Password)