Przeglądaj źródła

feat(orchestr): WiFi guest network module (Phase 17.2) (#132)

* feat(executor): uci_add, uci_delete_section, uci_set_named + section [-1]

New Kinds needed by the WiFi guest module (Phase 17.2):
- uci_add: uci add <config> <type> (create anonymous section).
- uci_delete_section: uci delete <config>.<section> (remove a whole section,
  unlike uci_delete which removes one option).
- uci_set_named: uci set <config>.<section>=<type> (create a named section;
  network interfaces are identified by their section name, e.g. network.guest).
- section regex now allows @tipo[-1] (last section of a type) so a plan can
  set fields on the section just created.

Part of #131

* feat(orchestr): WiFi guest network module (Phase 17.2)

New orchestration module that creates (or removes) an isolated guest WiFi
network on an OpenWrt router.

Enable: guest wifi-iface (AP, isolate=1) + network guest (static 192.168.8.0/24)
+ firewall zone guest (REJECT in/forward, ACCEPT out) + forwarding guest→wan,
then reload network + firewall. 26 ops.

Disable: remove the sections created (by detected index/name) and reload.

Probe (DetectGuestWiFi): reads uci wireless/network/firewall, maps radios to
bands, detects an existing guest iface by SSID (default NetPulse-Guest) and
the guest zone/forwarding indices (for a clean disable).

Gateway-only by default (reuses the allowNonGateway pattern from #120, with a
neutral gateway_only error/message). invertDesired toggles enabled for manual
rollback.

Tests: probe parse (radios, guest present, indices, clean router), enable and
disable ops validated against the executor (contract guaranteed). Suite -race
green.

Part of #131

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 miesięcy temu
rodzic
commit
1f499c7eba

+ 39 - 1
agent/executor/executor.go

@@ -60,7 +60,11 @@ func (shellRunner) Run(name string, args ...string) (string, int) {
 // patrones de validación por campo (sin shell metachars).
 var (
 	reConfig  = regexp.MustCompile(`^[a-z_]+$`)
-	reSection = regexp.MustCompile(`^(@[a-z_]+\[\d+\]|[a-z_]+)$`)
+	// section: nombre de sección (wifi-iface, interface) o referencia
+	// `@tipo[idx]` / `@tipo[-1]`. `[-1]` referencia la ÚLTIMA sección del
+	// tipo — usado tras un uci_add para setear los campos de la sección recién
+	// creada (patrón OpenWrt estándar).
+	reSection = regexp.MustCompile(`^(@[a-z_-]+(\[\d+\]|\[-1\])|[a-z_-]+)$`)
 	reOption  = regexp.MustCompile(`^[a-z_]+$`)
 	// value: alfanumérico + puntos, dos-puntos, barras, hashes, guiones.
 	// Cubre IPs (192.168.1.1), DNS (1.1.1.1#3001), rutas, MACs, puertos.
@@ -130,6 +134,40 @@ var allowlist = map[string]opSpec{
 		},
 		configs: func(a map[string]string) []string { return []string{a["config"]} },
 	},
+	// uci_add: crea una sección nueva. `uci add <config> <type>` imprime el
+	// nombre; luego uci_set sobre @<type>[-1] setea sus campos. Necesario para
+	// crear wifi-iface / network / firewall zone en módulos como WiFi guest.
+	// type: nombre de sección (wifi-iface, interface, zone, forwarding).
+	"uci_add": {
+		required: map[string]*regexp.Regexp{"config": reConfig, "type": reSection},
+		build: func(a map[string]string) (string, []string) {
+			return "uci", []string{"add", a["config"], a["type"]}
+		},
+		configs: func(a map[string]string) []string { return []string{a["config"]} },
+	},
+	// uci_delete_section: borra una sección completa (`uci delete <cfg>.<sec>`),
+	// a diferencia de uci_delete que quita una option. Útil para revertir un
+	// módulo que creó secciones (guest network: quitar la wifi-iface, la
+	// interface, la zone y el forwarding creados al habilitar).
+	"uci_delete_section": {
+		required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection},
+		build: func(a map[string]string) (string, []string) {
+			return "uci", []string{"delete", a["config"] + "." + a["section"]}
+		},
+		configs: func(a map[string]string) []string { return []string{a["config"]} },
+	},
+	// uci_set_named: crea una SECCIÓN NOMBRADA de un tipo: `uci set
+	// <config>.<section>=<type>`. Diferencia con uci_add (sección anónima):
+	// las network interfaces se identifican por su nombre de sección
+	// (network.guest=interface), mientras que wifi-iface/zone/forwarding
+	// pueden ser anónimas (referenciadas por índice @tipo[i]).
+	"uci_set_named": {
+		required: map[string]*regexp.Regexp{"config": reConfig, "section": reSection, "type": reSection},
+		build: func(a map[string]string) (string, []string) {
+			return "uci", []string{"set", a["config"] + "." + a["section"] + "=" + a["type"]}
+		},
+		configs: func(a map[string]string) []string { return []string{a["config"]} },
+	},
 	"service": {
 		required: map[string]*regexp.Regexp{"name": reService, "action": reServiceAct},
 		build: func(a map[string]string) (string, []string) {

+ 46 - 0
agent/executor/executor_test.go

@@ -96,6 +96,52 @@ func TestValidateServiceAction(t *testing.T) {
 	}
 }
 
+// --- Fase 17.2: uci_add + secciones @[-1] ---
+
+func TestValidateUciAdd(t *testing.T) {
+	valid := Op{Kind: "uci_add", Args: map[string]string{"config": "wireless", "type": "wifi-iface"}}
+	if err := Validate(valid); err != nil {
+		t.Fatalf("uci_add válido rechazado: %v", err)
+	}
+	// type con shell metachars → rechazado
+	bad := Op{Kind: "uci_add", Args: map[string]string{"config": "wireless", "type": "wifi-iface; rm -rf /"}}
+	if err := Validate(bad); err == nil {
+		t.Fatal("uci_add type con metachars debería rechazarse")
+	}
+	// config inválido
+	bad2 := Op{Kind: "uci_add", Args: map[string]string{"config": "wireless;", "type": "wifi-iface"}}
+	if err := Validate(bad2); err == nil {
+		t.Fatal("uci_add config inválido debería rechazarse")
+	}
+	// uci_delete_section válido (sección nombrada y @referencia)
+	del := Op{Kind: "uci_delete_section", Args: map[string]string{"config": "network", "section": "guest"}}
+	if err := Validate(del); err != nil {
+		t.Fatalf("uci_delete_section válido rechazado: %v", err)
+	}
+	del2 := Op{Kind: "uci_delete_section", Args: map[string]string{"config": "firewall", "section": "@zone[2]"}}
+	if err := Validate(del2); err != nil {
+		t.Fatalf("uci_delete_section @referencia rechazado: %v", err)
+	}
+}
+
+func TestValidateSectionLastIndex(t *testing.T) {
+	// @wifi-iface[-1] (última sección) válido para uci_set tras uci_add
+	op := Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "ssid", "value": "NetPulse-Guest"}}
+	if err := Validate(op); err != nil {
+		t.Fatalf("@wifi-iface[-1] debería aceptarse: %v", err)
+	}
+	// índice numérico sigue válido
+	op2 := Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[0]", "option": "ssid", "value": "Main"}}
+	if err := Validate(op2); err != nil {
+		t.Fatalf("@wifi-iface[0] debería aceptarse: %v", err)
+	}
+	// negativo distinto de -1 → rechazado
+	op3 := Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-2]", "option": "ssid", "value": "X"}}
+	if err := Validate(op3); err == nil {
+		t.Fatal("@wifi-iface[-2] debería rechazarse (solo -1)")
+	}
+}
+
 // --- Fase 17.1: validación de los nuevos Kinds ---
 
 func TestValidateDownloadURLAllowlist(t *testing.T) {

+ 43 - 3
server-go/internal/httpapi/orchestr.go

@@ -209,9 +209,10 @@ var (
 	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")
+	errAdGuardGatewayOnly      = errors.New("adguard_gateway_only")
+	errAdGuardAlreadyOnGateway = errors.New("adguard_already_on_gateway")
+	errAdGuardInsufficientRAM  = errors.New("adguard_insufficient_ram")
+	errGatewayOnly             = errors.New("gateway_only")
 )
 
 // computeModuleDiff despacha al módulo correcto, ejecutando el probe SSH si
@@ -260,11 +261,40 @@ func (s *server) computeModuleDiff(resource, routerID string, desired json.RawMe
 			return nil, "", err
 		}
 		return ops, sc.InstallMethod(), nil
+	case "guestwifi":
+		var d orchestr.GuestWiFiDesired
+		if err := json.Unmarshal(desired, &d); err != nil {
+			return nil, "", fmt.Errorf("%w: %v", errInvalidDesired, err)
+		}
+		host := s.hostOfRouter(routerID)
+		if host == "" {
+			return nil, "", errRouterNotFound
+		}
+		// La guest red solo tiene sentido en el gateway (distribuye la red)
+		// o en un AP de distribución. Por defecto gateway-only, como AdGuard.
+		isGateway, _ := s.gatewayInfo(routerID)
+		if !isGateway && !d.AllowNonGateway {
+			return nil, "", errGatewayOnly
+		}
+		sc, err := orchestr.DetectGuestWiFi(s.pool, host)
+		if err != nil {
+			return nil, "", fmt.Errorf("%w: %v", errProbeFailed, err)
+		}
+		ops := orchestr.GuestWiFiOps(d, sc)
+		return ops, guestWiFiMethod(d.Enabled), nil
 	default:
 		return nil, "", fmt.Errorf("%w: %s", errUnknownModule, resource)
 	}
 }
 
+// guestWiFiMethod es la etiqueta del método (para la UI): enabled/disabled.
+func guestWiFiMethod(enabled bool) string {
+	if enabled {
+		return "enabled"
+	}
+	return "disabled"
+}
+
 // 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) {
@@ -309,6 +339,9 @@ func (s *server) writeModuleErr(w http.ResponseWriter, err error) {
 	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, errGatewayOnly):
+		writeError(w, http.StatusUnprocessableEntity, "gateway_only",
+			"Este módulo por defecto solo se despliega en el gateway. Activa 'permitir en otros routers' para usar un no-gateway.")
 	case errors.Is(err, errUnknownModule):
 		writeError(w, http.StatusBadRequest, "unknown_module", err.Error())
 	case errors.Is(err, errInvalidDesired):
@@ -334,6 +367,13 @@ func invertDesired(resource string, desired json.RawMessage) (json.RawMessage, e
 		}
 		d.Enabled = !d.Enabled
 		return json.Marshal(d)
+	case "guestwifi":
+		var d orchestr.GuestWiFiDesired
+		if err := json.Unmarshal(desired, &d); err != nil {
+			return nil, fmt.Errorf("desired inválido: %w", err)
+		}
+		d.Enabled = !d.Enabled
+		return json.Marshal(d)
 	default:
 		return nil, fmt.Errorf("rollback no soportado para el módulo %q", resource)
 	}

+ 274 - 0
server-go/internal/orchestr/guestwifi.go

@@ -0,0 +1,274 @@
+// guestwifi.go — módulo de orquestación "WiFi guest aislada" (Fase 17.2).
+//
+// Crea (o elimina) una red WiFi guest aislada en un router OpenWrt: una
+// wifi-iface en modo AP con isolate, una network estática en subred propia
+// (192.168.8.0/24) y una zona de firewall que solo permite salir a WAN.
+// Todo se hace con Ops allowlistedas del executor (uci_add/uci_set/...).
+package orchestr
+
+import (
+	"fmt"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/executor"
+)
+
+// guestSSIDDefault es el SSID por defecto de la red guest.
+const guestSSIDDefault = "NetPulse-Guest"
+
+// guestIP / guestMask: subred propia de la guest (no choca con la LAN /24).
+const (
+	guestIP   = "192.168.8.1"
+	guestMask = "255.255.255.0"
+)
+
+// GuestWiFiDesired es el estado deseado del módulo.
+type GuestWiFiDesired struct {
+	Enabled  bool   `json:"enabled"`
+	SSID     string `json:"ssid"`
+	Password string `json:"password"`
+	// Band: "2g" | "5g" | "auto". Vacío/auto → el primer radio disponible.
+	Band string `json:"band"`
+	// AllowNonGateway: permitir en un router no-gateway (mismo patrón que
+	// AdGuard, #120). Default solo gateway.
+	AllowNonGateway bool `json:"allowNonGateway,omitempty"`
+}
+
+// GuestWiFiScenario es lo que detecta el probe en el router.
+type GuestWiFiScenario struct {
+	// Radio2G / Radio5G: nombre del radio (radio0, radio1) por banda. Vacío si
+	// el router no tiene esa banda.
+	Radio2G string
+	Radio5G string
+	// GuestPresent: ya existe una wifi-iface con el SSID guest.
+	GuestPresent bool
+	// GuestIfaceIdx: referencia a la wifi-iface guest existente (para disable).
+	GuestIfaceIdx string
+	// GuestZoneIdx / GuestFwdIdx: secciones firewall guest existentes.
+	GuestZoneIdx string
+	GuestFwdIdx  string
+}
+
+// probeGuestWiFiCmd lee el estado de wireless/network/firewall. Una sola sesión.
+const probeGuestWiFiCmd = `echo '===WIRELESS==='
+uci show wireless
+echo '===NETWORK==='
+uci show network
+echo '===FIREWALL==='
+uci show firewall
+echo '===END==='`
+
+// DetectGuestWiFi ejecuta el probe y devuelve el escenario.
+func DetectGuestWiFi(run CommandRunner, host string) (GuestWiFiScenario, error) {
+	out, err := run.Run(host, probeGuestWiFiCmd, 8*time.Second)
+	if err != nil {
+		return GuestWiFiScenario{}, err
+	}
+	return parseGuestWiFi(out), nil
+}
+
+// parseGuestWiFi extrae radios, wifi-ifaces y secciones guest del output.
+// Función pura (testeable sin SSH).
+func parseGuestWiFi(out string) GuestWiFiScenario {
+	sc := GuestWiFiScenario{}
+	sections := splitSections(out)
+	wireless := strings.Join(sections["WIRELESS"], "\n")
+	network := strings.Join(sections["NETWORK"], "\n")
+	firewall := strings.Join(sections["FIREWALL"], "\n")
+
+	// Radios y su banda + wifi-ifaces en orden de aparición.
+	radioBand := map[string]string{}
+	var wifiIfaces []string
+	for _, line := range strings.Split(wireless, "\n") {
+		line = strings.TrimSpace(line)
+		if strings.HasPrefix(line, "wireless.") {
+			rest := strings.TrimPrefix(line, "wireless.")
+			if strings.Contains(rest, "=wifi-device") {
+				name := strings.TrimSuffix(rest, "=wifi-device")
+				radioBand[name] = ""
+				continue
+			}
+			if strings.Contains(rest, "=wifi-iface") {
+				name := strings.TrimSuffix(rest, "=wifi-iface")
+				wifiIfaces = append(wifiIfaces, name)
+				continue
+			}
+			// banda: wireless.radioX.band='2g'
+			if dot := strings.Index(rest, "."); dot > 0 {
+				sec, field := rest[:dot], rest[dot+1:]
+				if _, ok := radioBand[sec]; ok && strings.HasPrefix(field, "band=") {
+					radioBand[sec] = strings.Trim(strings.TrimPrefix(field, "band="), "'")
+				}
+			}
+		}
+	}
+	for name, band := range radioBand {
+		switch band {
+		case "2g":
+			if sc.Radio2G == "" {
+				sc.Radio2G = name
+			}
+		case "5g":
+			if sc.Radio5G == "" {
+				sc.Radio5G = name
+			}
+		}
+	}
+
+	// ¿Existe ya una wifi-iface guest (por ssid)?
+	for i, name := range wifiIfaces {
+		for _, line := range strings.Split(wireless, "\n") {
+			line = strings.TrimSpace(line)
+			if strings.HasPrefix(line, "wireless."+name+".ssid=") {
+				ssid := strings.Trim(strings.TrimPrefix(line, "wireless."+name+".ssid="), "'")
+				if ssid == guestSSIDDefault {
+					sc.GuestPresent = true
+					sc.GuestIfaceIdx = fmt.Sprintf("@wifi-iface[%d]", i)
+				}
+			}
+		}
+	}
+
+	// Firewall: zone name=guest y forwarding src=guest.
+	sc.GuestZoneIdx = guestFirewallIndex(firewall, "zone", "guest")
+	sc.GuestFwdIdx = guestForwardingIndex(firewall)
+	_ = network // (la network guest se borra por nombre "guest", sin índice)
+
+	return sc
+}
+
+// guestFirewallIndex busca la sección @type[i] cuyo name coincide.
+func guestFirewallIndex(firewall, typ, nameWanted string) string {
+	prefix := "firewall.@" + typ + "["
+	for _, line := range strings.Split(firewall, "\n") {
+		line = strings.TrimSpace(line)
+		if !strings.HasPrefix(line, prefix) || !strings.Contains(line, ".name='") {
+			continue
+		}
+		rest := strings.TrimPrefix(line, "firewall.@")
+		idx := ""
+		for _, r := range rest {
+			if r == ']' {
+				break
+			}
+			if r >= '0' && r <= '9' {
+				idx += string(r)
+			}
+		}
+		name := strings.Trim(strings.TrimPrefix(line, "firewall.@"+typ+"["+idx+"].name="), "'")
+		if name == nameWanted {
+			return "@" + typ + "[" + idx + "]"
+		}
+	}
+	return ""
+}
+
+// guestForwardingIndex busca el forwarding con src=guest.
+func guestForwardingIndex(firewall string) string {
+	prefix := "firewall.@forwarding["
+	for _, line := range strings.Split(firewall, "\n") {
+		line = strings.TrimSpace(line)
+		if !strings.HasPrefix(line, prefix) {
+			continue
+		}
+		if strings.Contains(line, "src='guest'") {
+			rest := strings.TrimPrefix(line, "firewall.@")
+			idx := ""
+			for _, r := range rest {
+				if r == ']' {
+					break
+				}
+				if r >= '0' && r <= '9' {
+					idx += string(r)
+				}
+			}
+			return "@forwarding[" + idx + "]"
+		}
+	}
+	return ""
+}
+
+// GuestWiFiOps genera las Ops para activar/desactivar la guest.
+func GuestWiFiOps(desired GuestWiFiDesired, sc GuestWiFiScenario) []executor.Op {
+	if !desired.Enabled {
+		return guestWiFiDisableOps(sc)
+	}
+	ssid := desired.SSID
+	if ssid == "" {
+		ssid = guestSSIDDefault
+	}
+	radio := sc.Radio2G
+	switch {
+	case desired.Band == "5g" && sc.Radio5G != "":
+		radio = sc.Radio5G
+	case desired.Band == "2g" && sc.Radio2G != "":
+		radio = sc.Radio2G
+	case sc.Radio2G == "" && sc.Radio5G != "":
+		radio = sc.Radio5G
+	}
+	password := desired.Password
+	if password == "" {
+		password = "changeme123"
+	}
+	ops := []executor.Op{
+		{Kind: "uci_add", Args: map[string]string{"config": "wireless", "type": "wifi-iface"}, Desc: "Create guest wifi-iface"},
+		{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "device", "value": radio}, Desc: "Bind guest iface to radio"},
+		{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "mode", "value": "ap"}, Desc: "Guest iface mode AP"},
+		{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "ssid", "value": ssid}, Desc: "Set guest SSID"},
+		{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "encryption", "value": "psk2"}, Desc: "Guest WPA2 encryption"},
+		{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "key", "value": password}, Desc: "Set guest password"},
+		{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "network", "value": "guest"}, Desc: "Bind guest iface to guest network"},
+		{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "@wifi-iface[-1]", "option": "isolate", "value": "1"}, Desc: "Isolate guest clients"},
+		{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "Commit wireless"},
+		{Kind: "uci_set_named", Args: map[string]string{"config": "network", "section": "guest", "type": "interface"}, Desc: "Create guest network interface"},
+		{Kind: "uci_set", Args: map[string]string{"config": "network", "section": "guest", "option": "proto", "value": "static"}, Desc: "Guest static IP"},
+		{Kind: "uci_set", Args: map[string]string{"config": "network", "section": "guest", "option": "ipaddr", "value": guestIP}, Desc: "Guest gateway IP"},
+		{Kind: "uci_set", Args: map[string]string{"config": "network", "section": "guest", "option": "netmask", "value": guestMask}, Desc: "Guest netmask"},
+		{Kind: "uci_commit", Args: map[string]string{"config": "network"}, Desc: "Commit network"},
+		{Kind: "uci_add", Args: map[string]string{"config": "firewall", "type": "zone"}, Desc: "Create guest firewall zone"},
+		{Kind: "uci_set", Args: map[string]string{"config": "firewall", "section": "@zone[-1]", "option": "name", "value": "guest"}, Desc: "Name guest zone"},
+		{Kind: "uci_set", Args: map[string]string{"config": "firewall", "section": "@zone[-1]", "option": "network", "value": "guest"}, Desc: "Zone network guest"},
+		{Kind: "uci_set", Args: map[string]string{"config": "firewall", "section": "@zone[-1]", "option": "input", "value": "REJECT"}, Desc: "Zone input REJECT"},
+		{Kind: "uci_set", Args: map[string]string{"config": "firewall", "section": "@zone[-1]", "option": "output", "value": "ACCEPT"}, Desc: "Zone output ACCEPT"},
+		{Kind: "uci_set", Args: map[string]string{"config": "firewall", "section": "@zone[-1]", "option": "forward", "value": "REJECT"}, Desc: "Zone forward REJECT"},
+		{Kind: "uci_add", Args: map[string]string{"config": "firewall", "type": "forwarding"}, Desc: "Create guest forwarding"},
+		{Kind: "uci_set", Args: map[string]string{"config": "firewall", "section": "@forwarding[-1]", "option": "src", "value": "guest"}, Desc: "Forwarding src guest"},
+		{Kind: "uci_set", Args: map[string]string{"config": "firewall", "section": "@forwarding[-1]", "option": "dest", "value": "wan"}, Desc: "Forwarding dest wan"},
+		{Kind: "uci_commit", Args: map[string]string{"config": "firewall"}, Desc: "Commit firewall"},
+		{Kind: "service", Args: map[string]string{"name": "network", "action": "reload"}, Desc: "Reload network (applies wifi)"},
+		{Kind: "service", Args: map[string]string{"name": "firewall", "action": "reload"}, Desc: "Reload firewall"},
+	}
+	return ops
+}
+
+// guestWiFiDisableOps revierte el enable: borra las secciones creadas.
+func guestWiFiDisableOps(sc GuestWiFiScenario) []executor.Op {
+	ops := []executor.Op{}
+	if sc.GuestIfaceIdx != "" {
+		ops = append(ops, executor.Op{Kind: "uci_delete_section", Args: map[string]string{"config": "wireless", "section": sc.GuestIfaceIdx}, Desc: "Remove guest wifi-iface"})
+	}
+	ops = append(ops, executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "Commit wireless"})
+	ops = append(ops, executor.Op{Kind: "uci_delete_section", Args: map[string]string{"config": "network", "section": "guest"}, Desc: "Remove guest network"})
+	ops = append(ops, executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "network"}, Desc: "Commit network"})
+	if sc.GuestZoneIdx != "" {
+		ops = append(ops, executor.Op{Kind: "uci_delete_section", Args: map[string]string{"config": "firewall", "section": sc.GuestZoneIdx}, Desc: "Remove guest zone"})
+	}
+	if sc.GuestFwdIdx != "" {
+		ops = append(ops, executor.Op{Kind: "uci_delete_section", Args: map[string]string{"config": "firewall", "section": sc.GuestFwdIdx}, Desc: "Remove guest forwarding"})
+	}
+	ops = append(ops, executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "firewall"}, Desc: "Commit firewall"})
+	ops = append(ops, executor.Op{Kind: "service", Args: map[string]string{"name": "network", "action": "reload"}, Desc: "Reload network"})
+	ops = append(ops, executor.Op{Kind: "service", Args: map[string]string{"name": "firewall", "action": "reload"}, Desc: "Reload firewall"})
+	return ops
+}
+
+// validateGuestWiFiOps valida cada op contra el executor (usado en tests).
+func validateGuestWiFiOps(ops []executor.Op) error {
+	for _, op := range ops {
+		if err := executor.Validate(op); err != nil {
+			return fmt.Errorf("%s: %w", op.Desc, err)
+		}
+	}
+	return nil
+}

+ 155 - 0
server-go/internal/orchestr/guestwifi_test.go

@@ -0,0 +1,155 @@
+package orchestr
+
+import (
+	"strings"
+	"testing"
+)
+
+// Fixture real de rt2 (Redmi AX6, OpenWrt stock) — config tras crear la guest.
+const guestWiFiOut = `===WIRELESS===
+wireless.radio0=wifi-device
+wireless.radio0.type='mac80211'
+wireless.radio0.band='2g'
+wireless.radio0.channel='6'
+wireless.radio0.htmode='HE20'
+wireless.radio0.disabled='0'
+wireless.radio1=wifi-device
+wireless.radio1.type='mac80211'
+wireless.radio1.band='5g'
+wireless.radio1.channel='36'
+wireless.radio1.htmode='HE80'
+wireless.radio1.disabled='0'
+wireless.default_radio0=wifi-iface
+wireless.default_radio0.device='radio0'
+wireless.default_radio0.mode='ap'
+wireless.default_radio0.ssid='Home'
+wireless.default_radio0.network='lan'
+wireless.wifinet2=wifi-iface
+wireless.wifinet2.device='radio1'
+wireless.wifinet2.mode='ap'
+wireless.wifinet2.ssid='Home-5G'
+wireless.wifinet2.network='lan'
+wireless.guestwifi=wifi-iface
+wireless.guestwifi.device='radio0'
+wireless.guestwifi.mode='ap'
+wireless.guestwifi.ssid='NetPulse-Guest'
+wireless.guestwifi.network='guest'
+wireless.guestwifi.isolate='1'
+===NETWORK===
+network.lan=interface
+network.lan.device='br-lan'
+network.lan.proto='dhcp'
+network.guest=interface
+network.guest.proto='static'
+network.guest.ipaddr='192.168.8.1'
+network.guest.netmask='255.255.255.0'
+===FIREWALL===
+firewall.@zone[0]=zone
+firewall.@zone[0].name='lan'
+firewall.@zone[0].input='ACCEPT'
+firewall.@zone[1]=zone
+firewall.@zone[1].name='wan'
+firewall.@zone[1].input='REJECT'
+firewall.@zone[2]=zone
+firewall.@zone[2].name='guest'
+firewall.@zone[2].network='guest'
+firewall.@zone[2].input='REJECT'
+firewall.@forwarding[0]=forwarding
+firewall.@forwarding[0].src='lan'
+firewall.@forwarding[0].dest='wan'
+firewall.@forwarding[1]=forwarding
+firewall.@forwarding[1].src='guest'
+firewall.@forwarding[1].dest='wan'
+===END===`
+
+// TestParseGuestWiFiRadiosYGuest: detecta radios, iface guest y secciones.
+func TestParseGuestWiFiRadiosYGuest(t *testing.T) {
+	sc := parseGuestWiFi(guestWiFiOut)
+	if sc.Radio2G != "radio0" {
+		t.Errorf("Radio2G: got %q want radio0", sc.Radio2G)
+	}
+	if sc.Radio5G != "radio1" {
+		t.Errorf("Radio5G: got %q want radio1", sc.Radio5G)
+	}
+	if !sc.GuestPresent {
+		t.Error("GuestPresent: esperaba true (existe iface con NetPulse-Guest)")
+	}
+	if sc.GuestIfaceIdx != "@wifi-iface[2]" {
+		t.Errorf("GuestIfaceIdx: got %q want @wifi-iface[2]", sc.GuestIfaceIdx)
+	}
+	if sc.GuestZoneIdx != "@zone[2]" {
+		t.Errorf("GuestZoneIdx: got %q want @zone[2]", sc.GuestZoneIdx)
+	}
+	if sc.GuestFwdIdx != "@forwarding[1]" {
+		t.Errorf("GuestFwdIdx: got %q want @forwarding[1]", sc.GuestFwdIdx)
+	}
+}
+
+// TestParseGuestWiFiLimpio: sin guest → todas las referencias vacías.
+func TestParseGuestWiFiLimpio(t *testing.T) {
+	out := strings.Replace(guestWiFiOut, "wireless.guestwifi.ssid='NetPulse-Guest'", "wireless.guestwifi.ssid='Other'", 1)
+	// Sin zone guest ni forwarding guest (router sin guest network).
+	out = strings.Replace(out, "firewall.@zone[2].name='guest'\nfirewall.@zone[2].network='guest'\nfirewall.@zone[2].input='REJECT'\n", "", 1)
+	out = strings.Replace(out, "firewall.@forwarding[1]=forwarding\nfirewall.@forwarding[1].src='guest'\nfirewall.@forwarding[1].dest='wan'\n", "", 1)
+	sc := parseGuestWiFi(out)
+	if sc.GuestPresent {
+		t.Error("GuestPresent: esperaba false sin ssid NetPulse-Guest")
+	}
+	if sc.GuestIfaceIdx != "" {
+		t.Errorf("GuestIfaceIdx: got %q want vacío", sc.GuestIfaceIdx)
+	}
+	if sc.GuestZoneIdx != "" || sc.GuestFwdIdx != "" {
+		t.Errorf("indices zone/fwd no vacíos sin guest: %q %q", sc.GuestZoneIdx, sc.GuestFwdIdx)
+	}
+}
+
+// TestGuestWiFiOpsEnable: secuencia enable + todas las ops validan en el
+// executor (contrato orchestr→executor garantizado).
+func TestGuestWiFiOpsEnable(t *testing.T) {
+	sc := parseGuestWiFi(guestWiFiOut)
+	ops := GuestWiFiOps(GuestWiFiDesired{Enabled: true, SSID: "NetPulse-Guest", Password: "supersecret123", Band: "2g"}, sc)
+	if len(ops) == 0 {
+		t.Fatal("enable generó 0 ops")
+	}
+	if err := validateGuestWiFiOps(ops); err != nil {
+		t.Fatalf("ops enable no validan en executor: %v", err)
+	}
+	// Contiene uci_add wireless wifi-iface + uci_set network.guest + zone + reload
+	found := map[string]bool{}
+	for _, o := range ops {
+		found[o.Kind] = true
+	}
+	for _, k := range []string{"uci_add", "uci_set", "uci_commit", "uci_set_named", "service"} {
+		if !found[k] {
+			t.Errorf("enable sin kind %q", k)
+		}
+	}
+}
+
+// TestGuestWiFiOpsDisable: disable revierte con los índices detectados.
+func TestGuestWiFiOpsDisable(t *testing.T) {
+	sc := parseGuestWiFi(guestWiFiOut)
+	ops := GuestWiFiOps(GuestWiFiDesired{Enabled: false}, sc)
+	if err := validateGuestWiFiOps(ops); err != nil {
+		t.Fatalf("ops disable no validan en executor: %v", err)
+	}
+	// Debe borrar la wifi-iface guest, la network guest, la zone y el fwd.
+	del := map[string]bool{}
+	for _, o := range ops {
+		if o.Kind == "uci_delete_section" {
+			del[o.Args["section"]] = true
+		}
+	}
+	if !del["@wifi-iface[2]"] {
+		t.Error("disable sin uci_delete_section de la wifi-iface guest")
+	}
+	if !del["guest"] {
+		t.Error("disable sin uci_delete_section de la network guest")
+	}
+	if !del["@zone[2]"] {
+		t.Error("disable sin uci_delete_section de la zone guest")
+	}
+	if !del["@forwarding[1]"] {
+		t.Error("disable sin uci_delete_section del forwarding guest")
+	}
+}