Przeglądaj źródła

fix(device-actions): write DHCP reservation on the router serving the lease (#555)

handleDeviceReservationPut/Get/Delete always resolved the target via
gatewayHost(), which is right for a managed home network where one
gateway serves DHCP but wrong when a device's lease is granted by
another router (e.g. a separate LAN behind an AP/lab router with its
own dnsmasq, like rt-lab on 192.168.2.x): the static host section was
written to the global gateway instead of the router actually serving
that device.

Resolve the target from the device's DHCP server instead:
- Live.RouterServingDHCP(mac) returns the id of the router whose last
  poll reported the MAC in its lease table (the dnsmasq that granted
  it), skipping agent-only routers (no SSH to write the reservation).
- httpapi reservationTargetHost(mac) uses that router via an optional
  adapter interface (leaseRouterResolver); demo keeps falling back to
  the gateway, preserving previous behavior where no lease is known.
- GET/PUT/DELETE /reservation now read/write on that router.

The device-block path already pointed at the device's attachment
router; only the DHCP reservation side was gateway-locked.

6 new tests (live + httpapi with per-host scripted SSH): reservation
targets the serving router on GET/PUT/DELETE, falls back to the
gateway without a resolver, and skips agent-only serving routers.

Closes #537

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

+ 27 - 0
server-go/internal/adapters/live.go

@@ -2782,6 +2782,33 @@ func (l *Live) GetDevices(context.Context) []Device {
 	return devices
 }
 
+// RouterServingDHCP devuelve el id del router cuyo último sondeo reportó la
+// MAC en su tabla de leases DHCP (issue #537). Ese router es el que sirve
+// DHCP al dispositivo (no necesariamente el gateway global: una LAN separada
+// tras un router/AP con su propio dnsmasq, p. ej. rt-lab en 192.168.2.x, es
+// quien concede el lease). Vacío si ningún router la reportó (IP estática o
+// sin lease en el último snapshot).
+func (l *Live) RouterServingDHCP(mac string) string {
+	mac = strings.ToUpper(strings.TrimSpace(mac))
+	if mac == "" {
+		return ""
+	}
+	l.mu.Lock()
+	polled := l.lastPolled
+	l.mu.Unlock()
+	for id, p := range polled {
+		if p == nil || p.cfg.AgentOnly {
+			continue // agent-only no tiene vía SSH para escribir la reserva
+		}
+		for _, le := range p.leases {
+			if strings.ToUpper(le.MAC) == mac {
+				return id
+			}
+		}
+	}
+	return ""
+}
+
 // GetAlerts: copia de las alertas en memoria.
 func (l *Live) GetAlerts(context.Context) []AlertEvent {
 	return l.engine.List()

+ 39 - 0
server-go/internal/adapters/live_vitals_test.go

@@ -132,3 +132,42 @@ func TestPolledFromAgentSystemAntiparpadeo(t *testing.T) {
 		t.Fatalf("VitalsAvailable=%v, esperaba nil (agente netgrip con system)", r.VitalsAvailable)
 	}
 }
+
+// #537: RouterServingDHCP devuelve el router cuyo snapshot reportó la MAC en
+// su tabla de leases (el servidor DHCP real, no necesariamente el gateway).
+func TestRouterServingDHCP(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	l.lastPolled = map[string]*routerPolled{
+		// El gateway tiene los leases de la LAN principal (otras MACs).
+		"gateway": {cfg: RouterConfig{ID: "gateway", Host: "192.168.1.1", IsGateway: true},
+			leases: []DhcpLease{{MAC: "AA:BB:CC:DD:EE:01", IP: "192.168.1.10"}, {MAC: "AA:BB:CC:DD:EE:02", IP: "192.168.1.11"}}},
+		// El router "lab" (LAN 2.x, dnsmasq propio) reporta el lease de la MAC.
+		"lab": {cfg: RouterConfig{ID: "lab", Host: "192.168.2.1"},
+			leases: []DhcpLease{{MAC: devMACLease, IP: "192.168.2.50"}}},
+		// Agent-only: reporta leases pero no tiene SSH → nunca es el target.
+		"sw-ao": {cfg: RouterConfig{ID: "sw-ao", Host: "192.168.1.9", AgentOnly: true},
+			leases: []DhcpLease{{MAC: devMACLease, IP: "192.168.2.51"}}},
+	}
+
+	if got := l.RouterServingDHCP(devMACLease); got != "lab" {
+		t.Fatalf("RouterServingDHCP(%s) = %q, esperaba lab", devMACLease, got)
+	}
+	// MAC servida por el gateway (LAN principal).
+	if got := l.RouterServingDHCP("AA:BB:CC:DD:EE:01"); got != "gateway" {
+		t.Fatalf("RouterServingDHCP(MAC gateway) = %q, esperaba gateway", got)
+	}
+	// MAC con minúsculas se normaliza.
+	if got := l.RouterServingDHCP("aa:bb:cc:dd:ee:01"); got != "gateway" {
+		t.Fatalf("RouterServingDHCP(mac minúsculas) = %q, esperaba gateway", got)
+	}
+	// MAC sin lease en ningún router → "".
+	if got := l.RouterServingDHCP("EE:EE:EE:EE:EE:EE"); got != "" {
+		t.Fatalf("RouterServingDHCP(sin lease) = %q, esperaba vacío", got)
+	}
+	// Vacío → "".
+	if got := l.RouterServingDHCP(""); got != "" {
+		t.Fatalf("RouterServingDHCP(vacío) = %q, esperaba vacío", got)
+	}
+}
+
+const devMACLease = "AA:BB:CC:DD:EE:FF"

+ 30 - 4
server-go/internal/httpapi/device_actions.go

@@ -37,7 +37,7 @@ func uciValue(raw string) string {
 
 // gatewayHost devuelve el host SSH del gateway (router con is_gateway), o ""
 // si no hay gateway configurado o es agent-only. El gateway es quien sirve
-// DHCP (dnsmasq), así que es el target de las reservas de lease.
+// DHCP (dnsmasq), así que es el target por defecto de las reservas de lease.
 func (s *server) gatewayHost() string {
 	for _, r := range routerstore.ListRouters(s.db.DB) {
 		if r.IsGateway && !r.AgentOnly && r.Host != "" {
@@ -47,6 +47,32 @@ func (s *server) gatewayHost() string {
 	return ""
 }
 
+// leaseRouterResolver lo implementa el adapter live para decir qué router
+// reportó la MAC en su tabla de leases DHCP (issue #537). La demo no lo
+// implementa → la reserva cae al gateway, como antes.
+type leaseRouterResolver interface {
+	RouterServingDHCP(mac string) string
+}
+
+// reservationTargetHost resuelve DÓNDE vive la reserva DHCP de un dispositivo
+// (issue #537): no siempre en el gateway global. Un dispositivo cuya IP la
+// concede un router con su propio dnsmasq (p. ej. una LAN separada tras un AP
+// con DHCP propio) debe reservarse en ESE router, que es quien reportó su
+// lease. Orden:
+//  1. Router que reportó la MAC en leases (RouterServingDHCP), si el adapter
+//     lo soporta y el router es alcanzable por SSH.
+//  2. Fallback: el gateway (red gestionada clásica con un solo servidor DHCP).
+func (s *server) reservationTargetHost(mac string) string {
+	if lr, ok := s.adapter.(leaseRouterResolver); ok {
+		if routerID := lr.RouterServingDHCP(mac); routerID != "" {
+			if host := s.hostOfRouter(routerID); host != "" {
+				return host
+			}
+		}
+	}
+	return s.gatewayHost()
+}
+
 // uciShow ejecuta `uci show <config>` en un host y devuelve líneas parseables.
 func (s *server) uciShow(host, config string) ([]string, error) {
 	if s.pool == nil {
@@ -182,7 +208,7 @@ func (s *server) handleDeviceReservationGet(w http.ResponseWriter, r *http.Reque
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}
-	host := s.gatewayHost()
+	host := s.reservationTargetHost(mac)
 	if host == "" {
 		writeError(w, http.StatusBadRequest, "no_gateway")
 		return
@@ -225,7 +251,7 @@ func (s *server) handleDeviceReservationPut(w http.ResponseWriter, r *http.Reque
 		writeError(w, http.StatusBadRequest, "invalid_ip")
 		return
 	}
-	host := s.gatewayHost()
+	host := s.reservationTargetHost(mac)
 	if host == "" {
 		writeError(w, http.StatusBadRequest, "no_gateway")
 		return
@@ -295,7 +321,7 @@ func (s *server) handleDeviceReservationDelete(w http.ResponseWriter, r *http.Re
 		writeError(w, http.StatusBadRequest, "invalid_mac")
 		return
 	}
-	host := s.gatewayHost()
+	host := s.reservationTargetHost(mac)
 	if host == "" {
 		writeError(w, http.StatusBadRequest, "no_gateway")
 		return

+ 179 - 3
server-go/internal/httpapi/device_actions_test.go

@@ -32,6 +32,7 @@ const (
 // --- fake SSHRunner (por subcadena, en orden) ---
 
 type sshRule struct {
+	host     string // opcional: si no vacío, la regla solo aplica a ese host SSH
 	contains string
 	out      string
 	err      error
@@ -40,14 +41,19 @@ type sshRule struct {
 type scriptedSSH struct {
 	mu    sync.Mutex
 	cmds  []string
+	hosts []string
 	rules []sshRule
 }
 
-func (f *scriptedSSH) Run(_host, cmd string, _ time.Duration) (string, error) {
+func (f *scriptedSSH) Run(host, cmd string, _ time.Duration) (string, error) {
 	f.mu.Lock()
 	defer f.mu.Unlock()
 	f.cmds = append(f.cmds, cmd)
+	f.hosts = append(f.hosts, host)
 	for _, r := range f.rules {
+		if r.host != "" && r.host != host {
+			continue
+		}
 		if strings.Contains(cmd, r.contains) {
 			return r.out, r.err
 		}
@@ -66,6 +72,20 @@ func (f *scriptedSSH) saw(substr string) bool {
 	return false
 }
 
+// sawHost es como saw pero acotado a un host SSH concreto (issue #537: la
+// reserva debe escribirse en el router que sirve DHCP, no siempre en el
+// gateway).
+func (f *scriptedSSH) sawHost(host, substr string) bool {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	for i, c := range f.cmds {
+		if i < len(f.hosts) && f.hosts[i] == host && strings.Contains(c, substr) {
+			return true
+		}
+	}
+	return false
+}
+
 func (f *scriptedSSH) count(substr string) int {
 	f.mu.Lock()
 	defer f.mu.Unlock()
@@ -130,7 +150,7 @@ type deviceActionsTestServer struct {
 	cookie string
 }
 
-func makeDeviceActionsTestServer(t *testing.T, ssh *scriptedSSH) *deviceActionsTestServer {
+func makeDeviceActionsTestServer(t *testing.T, ssh *scriptedSSH, adapterOpt ...adapters.Snapshotter) *deviceActionsTestServer {
 	t.Helper()
 	dataDir := t.TempDir()
 	cfg, err := config.Load(map[string]string{
@@ -169,8 +189,12 @@ func makeDeviceActionsTestServer(t *testing.T, ssh *scriptedSSH) *deviceActionsT
 	if ssh != nil {
 		runner = ssh
 	}
+	adapter := adapters.Snapshotter(adapters.NewDemo())
+	if len(adapterOpt) > 0 && adapterOpt[0] != nil {
+		adapter = adapterOpt[0]
+	}
 	handler := httpapi.NewHandler(httpapi.Deps{
-		Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
+		Config: cfg, DB: d, Adapter: adapter, Hub: hub, Secret: secret,
 		Agents: agents, Pool: runner, Started: time.Now(),
 	})
 	srv := httptest.NewServer(handler)
@@ -615,3 +639,155 @@ func TestDeviceActionsAdminOnly(t *testing.T) {
 		}
 	}
 }
+
+// --- #537: la reserva DHCP va al router que sirve el lease, no siempre al
+// gateway global ---
+
+// leaseAwareAdapter envuelve un adapter de test (Demo) añadiéndole la
+// resolución de "qué router reportó el lease de la MAC" (RouterServingDHCP).
+// sirve: MAC → router ID (el router que concede DHCP a esa MAC).
+type leaseAwareAdapter struct {
+	adapters.Snapshotter
+	sirve map[string]string
+}
+
+func (a *leaseAwareAdapter) RouterServingDHCP(mac string) string {
+	return a.sirve[strings.ToUpper(mac)]
+}
+
+// El AP "patio" (192.168.1.2) es quien reporta el lease de devMAC: su host
+// tiene dhcpDevHost (la reserva ya existe ahí). El gateway (192.168.1.1) NO la
+// tiene. Con esto, la reserva debe escribirse/leerse en 192.168.1.2.
+func TestReservationTargetsServingRouter(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{host: "192.168.1.2", contains: "uci show dhcp", out: dhcpDevHost},
+		{host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
+	}}
+	adapter := &leaseAwareAdapter{
+		Snapshotter: adapters.NewDemo(),
+		sirve:       map[string]string{strings.ToUpper(devMAC): "patio"},
+	}
+	// "patio" es el Name del router creado con host 192.168.1.2 en el helper;
+	// el helper guarda apID. Construimos el server y después recuperamos el
+	// ID real del AP para el mapa (por si el helper genera IDs distintos).
+	ts := makeDeviceActionsTestServer(t, ssh, adapter)
+	adapter.sirve[strings.ToUpper(devMAC)] = ts.apID
+
+	// GET: debe leer el uci show dhcp del AP (192.168.1.2), donde está la
+	// reserva → reserved=true.
+	res := deviceReq(t, "GET", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
+	if res.StatusCode != 200 {
+		t.Fatalf("GET reservation: %d", res.StatusCode)
+	}
+	body := decodeBody(t, res)
+	if body["reserved"] != true || body["ip"] != "192.168.1.60" {
+		t.Errorf("reserved payload (desde el router que sirve DHCP): %v", body)
+	}
+	if !ssh.sawHost("192.168.1.2", "uci show dhcp") {
+		t.Fatalf("GET no consultó el router que sirve DHCP: %v", ssh.hosts)
+	}
+}
+
+// PUT: al crear la reserva de un dispositivo cuyo lease lo sirve el AP, el
+// write debe ir al AP (192.168.1.2), NO al gateway (192.168.1.1).
+func TestReservationPutTargetsServingRouter(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{host: "192.168.1.2", contains: "uci show dhcp", out: dhcpEmpty},
+		{host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
+	}}
+	adapter := &leaseAwareAdapter{Snapshotter: adapters.NewDemo()}
+	ts := makeDeviceActionsTestServer(t, ssh, adapter)
+	adapter.sirve = map[string]string{strings.ToUpper(devMAC): ts.apID}
+
+	res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
+		`{"ip":"192.168.1.60","hostname":"tv-salon"}`)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT reservation: %d (body %v)", res.StatusCode, decodeBody(t, res))
+	}
+	res.Body.Close()
+	if !ssh.sawHost("192.168.1.2", "uci set dhcp.np_host_aabbccddeeff=host") {
+		t.Error("la reserva debe escribirse en el router que sirve DHCP (192.168.1.2)")
+	}
+	if ssh.sawHost("192.168.1.1", "uci set dhcp.") {
+		t.Error("la reserva NO debe escribirse en el gateway (192.168.1.1)")
+	}
+	if !ssh.sawHost("192.168.1.2", "/etc/init.d/dnsmasq restart") {
+		t.Error("dnsmasq debe reiniciarse en el router que sirve DHCP")
+	}
+}
+
+// DELETE: si la reserva está en el router que sirve DHCP (no en el gateway),
+// se borra de ahí.
+func TestReservationDeleteTargetsServingRouter(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{host: "192.168.1.2", contains: "uci show dhcp", out: dhcpDevHost},
+		{host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
+	}}
+	adapter := &leaseAwareAdapter{Snapshotter: adapters.NewDemo()}
+	ts := makeDeviceActionsTestServer(t, ssh, adapter)
+	adapter.sirve = map[string]string{strings.ToUpper(devMAC): ts.apID}
+
+	res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
+	if res.StatusCode != 200 {
+		t.Fatalf("DELETE reservation: %d (body %v)", res.StatusCode, decodeBody(t, res))
+	}
+	res.Body.Close()
+	if !ssh.sawHost("192.168.1.2", "uci delete dhcp.np_host_aabbccddeeff") {
+		t.Error("el borrado debe ir al router que sirve DHCP (192.168.1.2)")
+	}
+	if ssh.sawHost("192.168.1.1", "uci delete dhcp.") {
+		t.Error("el borrado NO debe ir al gateway (192.168.1.1)")
+	}
+}
+
+// Sin resolver (adapter por defecto, demo): la reserva sigue cayendo al
+// gateway (red gestionada clásica) - compatibilidad con el comportamiento
+// previo.
+func TestReservationFallsBackToGatewayWithoutResolver(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
+		{host: "192.168.1.2", contains: "uci show dhcp", out: dhcpEmpty},
+	}}
+	ts := makeDeviceActionsTestServer(t, ssh) // demo: sin RouterServingDHCP
+
+	res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
+		`{"ip":"192.168.1.60","hostname":"tv-salon"}`)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT reservation: %d", res.StatusCode)
+	}
+	res.Body.Close()
+	if !ssh.sawHost("192.168.1.1", "uci set dhcp.np_host_aabbccddeeff=host") {
+		t.Error("sin resolver, la reserva debe ir al gateway (192.168.1.1)")
+	}
+}
+
+// El resolver apunta a un router agent-only (sin SSH): no se puede escribir
+// ahí → cae al gateway (hostOfRouter devuelve vacío para agent-only).
+func TestReservationSkipsAgentOnlyServingRouter(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{host: "192.168.1.1", contains: "uci show dhcp", out: dhcpEmpty},
+	}}
+	adapter := &leaseAwareAdapter{Snapshotter: adapters.NewDemo()}
+	ts := makeDeviceActionsTestServer(t, ssh, adapter)
+	// Creamos un router agent-only con host y apuntamos el resolver ahí.
+	agentOnly, err := routerstore.AddRouter(ts.db.DB, routerstore.AddInput{
+		Name: "sw-ao", Host: "192.168.1.9", Type: "openwrt", AgentOnly: true,
+	})
+	if err != nil {
+		t.Fatalf("AddRouter agent-only: %v", err)
+	}
+	adapter.sirve = map[string]string{strings.ToUpper(devMAC): agentOnly.ID}
+
+	res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
+		`{"ip":"192.168.1.60","hostname":"tv-salon"}`)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT reservation: %d", res.StatusCode)
+	}
+	res.Body.Close()
+	if !ssh.sawHost("192.168.1.1", "uci set dhcp.np_host_aabbccddeeff=host") {
+		t.Error("router agent-only sin SSH → la reserva debe caer al gateway")
+	}
+	if ssh.sawHost("192.168.1.9", "uci set dhcp.") {
+		t.Error("no debe intentar escribir en el router agent-only")
+	}
+}