Explorar el Código

feat(orchestr): restrict AdGuard to gateway (RAM + redundancy checks) (#130)

* feat(orchestr): restrict AdGuard to gateway with RAM + redundancy checks

AdGuard filters the network DNS, so by default it only makes sense on the
gateway. The module now enforces that server-side:

- The SSH probe collects free -m (AvailableRAM, MB; parses the 'available'
  column via the header, falls back to 'free' on older free -m).
- AdGuardDesired gains AllowNonGateway (the frontend 'advanced' toggle).
- POST /api/plans rejects with 422 when resource=adguard and:
  - target is not the gateway AND AllowNonGateway is not set ->
    adguard_gateway_only.
  - target is not the gateway AND the gateway already runs AdGuard (vendor
    fork or our binary) -> adguard_already_on_gateway.
  - target is not the gateway, enabling, and has <150 MB free RAM ->
    adguard_insufficient_ram.

Adds gatewayInfo() to resolve the gateway router by is_gateway. Error
mappings in writeModuleErr (all 422).

Tests: parseFreeMem (busybox available, old free fallback, absent) +
probe includes AvailableRAM. Suite -race green.

Part of #120

* feat(ui): gateway-only router dropdown + advanced toggle in orchestration

The router dropdown in /orchestration lists only the gateway by default.
An 'Allow AdGuard on non-gateway routers' checkbox (off by default) reveals
all routers, and selecting a non-gateway shows a strong warning about DNS
scope, RAM and the gateway already running AdGuard.

Gateway is resolved from the view-model (roleBadge 'Principal'); options are
the connected agents (apply runs over SSE).

Part of #120

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho hace 3 meses
padre
commit
54e5308d65

+ 3 - 0
app/public/locales/en/translation.json

@@ -918,6 +918,7 @@
     "title": "Orchestration",
     "subtitle": "Configure network services declaratively. Every change goes through a reviewable plan before applying.",
     "router": "Router",
+    "gateway": "Gateway",
     "generatePlan": "Generate plan",
     "plan": "Plan",
     "apply": "Apply",
@@ -926,6 +927,8 @@
     "failed": "Failed",
     "adguard": {
       "enable": "Enable AdGuard Home",
+      "allowNonGateway": "Allow AdGuard on non-gateway routers",
+      "nonGatewayWarning": "AdGuard only filters DNS for the whole network from the gateway. Elsewhere it would only cover that router's clients, and deploying there requires enough free RAM and a gateway that does not already run AdGuard.",
       "port": "Port",
       "upstream": "Upstream DNS",
       "managedByFirmware": "This router ships a vendor AdGuard Home (GL.iNet). NetPulse won't manage it to avoid breaking its UI: configure it from the router's own interface.",

+ 3 - 0
app/public/locales/es/translation.json

@@ -918,6 +918,7 @@
     "title": "Orquestación",
     "subtitle": "Configura servicios de red de forma declarativa. Cada cambio pasa por un plan revisable antes de aplicarse.",
     "router": "Router",
+    "gateway": "Gateway",
     "generatePlan": "Generar plan",
     "plan": "Plan",
     "apply": "Aplicar",
@@ -926,6 +927,8 @@
     "failed": "Falló",
     "adguard": {
       "enable": "Activar AdGuard Home",
+      "allowNonGateway": "Permitir AdGuard en routers no-gateway",
+      "nonGatewayWarning": "AdGuard solo filtra el DNS de toda la red desde el gateway. En otro router solo filtraría a sus clientes; además el despliegue exige RAM libre suficiente y que el gateway no lo tenga ya activo.",
       "port": "Puerto",
       "upstream": "DNS upstream",
       "managedByFirmware": "Este router trae un AdGuard Home del fabricante (GL.iNet). NetPulse no lo gestiona para no romper su UI: configúralo desde la interfaz del router.",

+ 45 - 7
app/src/pages/Orchestration.tsx

@@ -35,12 +35,15 @@ const methodLabel = (method: string) => {
 
 export default function Orchestration() {
   const { t } = useTranslation()
-  const { agents } = useNetPulse()
+  const { agents, routers } = useNetPulse()
   const auth = useAuth()
   const [routerId, setRouterId] = useState('')
   const [agEnabled, setAgEnabled] = useState(true)
   const [agPort, setAgPort] = useState('3000')
   const [agDns, setAgDns] = useState('1.1.1.1')
+  // issue #120: AdGuard filtra el DNS de la red → por defecto solo el gateway.
+  // El toggle "advanced" permite un router no-gateway (con warning + checks).
+  const [agAllowNonGateway, setAgAllowNonGateway] = useState(false)
   const [plan, setPlan] = useState<Plan | null>(null)
   const [busy, setBusy] = useState(false)
   const [error, setError] = useState('')
@@ -49,10 +52,23 @@ export default function Orchestration() {
   // un error rojo genérico.
   const [firmwareManaged, setFirmwareManaged] = useState(false)
 
-  // Auto-seleccionar el primer router
+  // El gateway del view-model (roleBadge 'Principal'); el selector lo lista
+  // solo por defecto (gateway-only, #120).
+  const gatewayId = routers.find((r) => r.roleBadge === 'Principal')?.id
+  // Routers del dropdown: solo el gateway por defecto; todos si el toggle
+  // advanced está activo. Se listan los AGENTES conectados (el apply usa SSE).
+  const visibleRouters = agAllowNonGateway
+    ? agents
+    : agents.filter((a) => a.slug === gatewayId)
+  const nonGatewaySelected = agAllowNonGateway && routerId !== gatewayId
+
+  // Auto-seleccionar: gateway por defecto (o el primer agente visible).
   useEffect(() => {
-    if (!routerId && agents.length > 0) setRouterId(agents[0].slug)
-  }, [agents, routerId])
+    if (!routerId || !visibleRouters.some((a) => a.slug === routerId)) {
+      const first = visibleRouters[0]
+      if (first) setRouterId(first.slug)
+    }
+  }, [agents, gatewayId, agAllowNonGateway, routerId, visibleRouters])
 
   const createPlan = async () => {
     setBusy(true)
@@ -66,7 +82,7 @@ export default function Orchestration() {
         body: JSON.stringify({
           routerId,
           resource: 'adguard',
-          desired: { enabled: agEnabled, port: agPort, upstreamDns: agDns },
+          desired: { enabled: agEnabled, port: agPort, upstreamDns: agDns, allowNonGateway: agAllowNonGateway },
         }),
       })
       if (!res.ok) {
@@ -153,12 +169,34 @@ export default function Orchestration() {
               onChange={(e) => setRouterId(e.target.value)}
               className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary"
             >
-              {agents.map((a) => (
-                <option key={a.slug} value={a.slug}>{a.slug}</option>
+              {visibleRouters.map((a) => (
+                <option key={a.slug} value={a.slug}>
+                  {a.slug}{a.slug === gatewayId ? ` (${t('orchestration.gateway')})` : ''}
+                </option>
               ))}
             </select>
           </label>
 
+          {/* Toggle advanced (#120): permitir un router no-gateway */}
+          <label className="flex items-center gap-2 pt-6">
+            <input
+              type="checkbox"
+              checked={agAllowNonGateway}
+              onChange={(e) => setAgAllowNonGateway(e.target.checked)}
+              className="h-4 w-4 rounded border-border"
+            />
+            <span className="text-sm text-text-primary">{t('orchestration.adguard.allowNonGateway')}</span>
+          </label>
+
+          {nonGatewaySelected && (
+            <div
+              role="alert"
+              className="mt-2 rounded-xl border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-amber-200 lg:col-span-4"
+            >
+              {t('orchestration.adguard.nonGatewayWarning')}
+            </div>
+          )}
+
           <label className="flex items-center gap-2 pt-6">
             <input
               type="checkbox"

+ 49 - 4
server-go/internal/httpapi/orchestr.go

@@ -205,10 +205,13 @@ func bearerToken(r *http.Request) string {
 // Errores sentinelas del cálculo de diff (mapeados a códigos HTTP por
 // writeModuleErr).
 var (
-	errRouterNotFound = errors.New("router_not_found")
-	errUnknownModule  = errors.New("unknown_module")
-	errProbeFailed    = errors.New("probe_failed")
-	errInvalidDesired = errors.New("invalid_desired")
+	errRouterNotFound           = errors.New("router_not_found")
+	errUnknownModule            = errors.New("unknown_module")
+	errProbeFailed              = errors.New("probe_failed")
+	errInvalidDesired           = errors.New("invalid_desired")
+	errAdGuardGatewayOnly       = errors.New("adguard_gateway_only")
+	errAdGuardAlreadyOnGateway  = errors.New("adguard_already_on_gateway")
+	errAdGuardInsufficientRAM   = errors.New("adguard_insufficient_ram")
 )
 
 // computeModuleDiff despacha al módulo correcto, ejecutando el probe SSH si
@@ -230,10 +233,28 @@ func (s *server) computeModuleDiff(resource, routerID string, desired json.RawMe
 		if host == "" {
 			return nil, "", errRouterNotFound
 		}
+		// AdGuard filtra el DNS de la red → por defecto solo el gateway
+		// (#120). El resto de checks aplican a un target no-gateway.
+		isGateway, gwHost := s.gatewayInfo(routerID)
+		if !isGateway && !d.AllowNonGateway {
+			return nil, "", errAdGuardGatewayOnly
+		}
 		sc, err := orchestr.DetectAdGuard(s.pool, host)
 		if err != nil {
 			return nil, "", fmt.Errorf("%w: %v", errProbeFailed, err)
 		}
+		// Solo se despliega (enabled) en no-gateway con RAM suficiente.
+		if !isGateway && d.Enabled && sc.AvailableRAM > 0 && sc.AvailableRAM < 150 {
+			return nil, "", errAdGuardInsufficientRAM
+		}
+		// Si el gateway ya tiene AdGuard (fork de fabricante o binario
+		// nuestro), desplegar en otro router es redundante.
+		if !isGateway && gwHost != "" && gwHost != host {
+			if gwSc, err := orchestr.DetectAdGuard(s.pool, gwHost); err == nil &&
+				(gwSc.ManagedByFirmware || gwSc.BinaryPresent) {
+				return nil, "", errAdGuardAlreadyOnGateway
+			}
+		}
 		ops, err := orchestr.AdGuardOps(d, sc)
 		if err != nil {
 			return nil, "", err
@@ -244,6 +265,21 @@ func (s *server) computeModuleDiff(resource, routerID string, desired json.RawMe
 	}
 }
 
+// gatewayInfo devuelve (esGateway, gwHost). esGateway: si routerID ES el
+// gateway. gwHost: host del gateway (vacío si no hay gateway configurado).
+func (s *server) gatewayInfo(routerID string) (bool, string) {
+	gwHost := ""
+	for _, r := range routerstore.ListRouters(s.db.DB) {
+		if r.IsGateway {
+			gwHost = r.Host
+			if r.ID == routerID {
+				return true, r.Host
+			}
+		}
+	}
+	return false, gwHost
+}
+
 // hostOfRouter busca el host SSH de un router por ID (scan de ListRouters).
 // Vacío si no existe o es agent-only (sin SSH).
 func (s *server) hostOfRouter(routerID string) string {
@@ -264,6 +300,15 @@ func (s *server) writeModuleErr(w http.ResponseWriter, err error) {
 	case errors.Is(err, errRouterNotFound):
 		writeError(w, http.StatusNotFound, "router_not_found",
 			"Router no encontrado o sin SSH (agent-only).")
+	case errors.Is(err, errAdGuardGatewayOnly):
+		writeError(w, http.StatusUnprocessableEntity, "adguard_gateway_only",
+			"AdGuard filtra el DNS de la red: por defecto solo se despliega en el gateway. Activa 'permitir en otros routers' en el módulo AdGuard para usar un no-gateway.")
+	case errors.Is(err, errAdGuardAlreadyOnGateway):
+		writeError(w, http.StatusUnprocessableEntity, "adguard_already_on_gateway",
+			"El gateway ya tiene AdGuard Home activo (fork de fabricante o binario instalado). Desplegarlo en otro router es redundante.")
+	case errors.Is(err, errAdGuardInsufficientRAM):
+		writeError(w, http.StatusUnprocessableEntity, "adguard_insufficient_ram",
+			"El router no tiene suficiente RAM libre (<150 MB) para AdGuard Home y sus listas de filtros.")
 	case errors.Is(err, errUnknownModule):
 		writeError(w, http.StatusBadRequest, "unknown_module", err.Error())
 	case errors.Is(err, errInvalidDesired):

+ 40 - 0
server-go/internal/orchestr/adguard_probe.go

@@ -12,6 +12,7 @@
 package orchestr
 
 import (
+	"strconv"
 	"strings"
 	"time"
 )
@@ -41,6 +42,9 @@ type AdGuardScenario struct {
 	// BinaryPresent: /usr/bin/AdGuardHome es ejecutable (instalación oficial
 	// previa nuestra; distinguir del fork GL.iNet vía ManagedByFirmware).
 	BinaryPresent bool
+	// AvailableRAM: MB disponibles (`free -m`, columna available). Usado para
+	// el chequeo de recursos de AdGuard (necesita ~150-200 MB, issue #120).
+	AvailableRAM int
 }
 
 // probeCmd es el comando combinado de detección. Una sola sesión SSH.
@@ -58,6 +62,8 @@ echo '===APK_AVAIL==='
 apk search adguard-home 2>/dev/null
 echo '===BINARY==='
 test -x /usr/bin/AdGuardHome && echo present || echo absent
+echo '===MEM==='
+free -m
 echo '===END==='`
 
 // DetectAdGuard ejecuta el comando combinado vía SSH y parsea el estado.
@@ -114,9 +120,43 @@ func parseAdGuardProbe(out string) AdGuardScenario {
 	if bin := firstNonEmpty(sections["BINARY"]); strings.Contains(strings.ToLower(bin), "present") {
 		sc.BinaryPresent = true
 	}
+	sc.AvailableRAM = parseFreeMem(strings.Join(sections["MEM"], "\n"))
 	return sc
 }
 
+// parseFreeMem extrae la RAM disponible (MB) de la salida de `free -m`.
+// Busca la línea "Mem:" y la columna available (la de la cabecera). Si la
+// cabecera no tiene "available" (free -m antiguo/procps), cae a la columna
+// free (f[3]). Distingue por cabecera porque el free antiguo tiene 7 campos
+// pero el 7º es "cached", no "available".
+func parseFreeMem(out string) int {
+	lines := strings.Split(out, "\n")
+	headerHasAvailable := false
+	for _, line := range lines {
+		if strings.Contains(line, "total") && strings.Contains(line, "used") {
+			headerHasAvailable = strings.Contains(line, "available")
+			break
+		}
+	}
+	for _, line := range lines {
+		if !strings.HasPrefix(strings.TrimSpace(line), "Mem:") {
+			continue
+		}
+		f := strings.Fields(line)
+		if headerHasAvailable && len(f) >= 7 {
+			if v, err := strconv.Atoi(f[6]); err == nil {
+				return v
+			}
+		}
+		if len(f) >= 4 {
+			if v, err := strconv.Atoi(f[3]); err == nil {
+				return v
+			}
+		}
+	}
+	return 0
+}
+
 // splitSections parte el output por marcadores ===NAME=== en un map nombre→líneas.
 // Las líneas entre marcadores (no vacías) se asignan a la sección vigente.
 func splitSections(out string) map[string][]string {

+ 48 - 0
server-go/internal/orchestr/adguard_probe_test.go

@@ -243,3 +243,51 @@ func TestDetectAdGuardUsaRunner(t *testing.T) {
 		t.Errorf("DetectAdGuard no parseó arch: %+v", sc)
 	}
 }
+
+// TestParseFreeMem: extrae la columna available de `free -m` (busybox).
+func TestParseFreeMem(t *testing.T) {
+	cases := []struct {
+		name, out string
+		want      int
+	}{
+		{
+			"busybox_con_available",
+			"              total        used        free      shared  buff/cache   available\nMem:           512         300          80          10         132         212\nSwap:            0           0           0",
+			212,
+		},
+		{
+			"free_antiguo_sin_available_fallback_free",
+			"             total       used       free     shared    buffers     cached\nMem:           512        300        200         10          0          0\n-/+ buffers/cache:        300        212\nSwap:            0          0          0",
+			200, // fallback a columna free
+		},
+		{
+			"sin_mem",
+			"===END===",
+			0,
+		},
+		{
+			"mem_vacio_entre_marcadores",
+			"===MEM===\n===END===",
+			0,
+		},
+	}
+	for _, c := range cases {
+		t.Run(c.name, func(t *testing.T) {
+			if got := parseFreeMem(c.out); got != c.want {
+				t.Errorf("parseFreeMem: got %d want %d", got, c.want)
+			}
+		})
+	}
+}
+
+// TestParseAdGuardProbeMembríaIncluyeAvailableRAM: el probe parsea RAM.
+func TestParseAdGuardProbeIncluyeAvailableRAM(t *testing.T) {
+	out := `===MEM===
+              total        used        free      shared  buff/cache   available
+Mem:           512         300          80          10         132         212
+===END===`
+	sc := parseAdGuardProbe(out)
+	if sc.AvailableRAM != 212 {
+		t.Errorf("AvailableRAM: got %d want 212", sc.AvailableRAM)
+	}
+}

+ 4 - 0
server-go/internal/orchestr/modules.go

@@ -30,6 +30,10 @@ type AdGuardDesired struct {
 	Enabled     bool   `json:"enabled"`
 	Port        string `json:"port"`        // puerto HTTP de la UI de AdGuard (default "3000")
 	UpstreamDNS string `json:"upstreamDns"` // DNS upstream (default "1.1.1.1")
+	// AllowNonGateway: permitir AdGuard en un router que no es el gateway.
+	// El servidor lo exige para no rechazar con 422 adguard_gateway_only
+	// (issue #120). El frontend lo expone como toggle "advanced".
+	AllowNonGateway bool `json:"allowNonGateway,omitempty"`
 }
 
 // AdGuardOps genera las Ops para activar/desactivar AdGuard Home según el