Browse Source

fix(agents): match agents to routers by hostname/MAC and keep router online when agent is fresh (#317)

- AgentRegistry.MatchRouter resolves an agent to a router by exact slug,
  board hostname or persisted bridge MAC (#282).
- pollRouterAgent uses the fuzzy match, so an agent pushing under a
  user-chosen slug still feeds a router whose auto-generated id differs.
- When SSH auth fails but the matched agent is fresh, emit a one-shot
  non-urgent alert instead of marking the router offline (#281).
- GET /api/agents exposes routerId so the UI can show agent actions even
  when slug != router.id.
- Frontend useAgentFor prefers routerId and falls back to slug.

Closes #281
Closes #282

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 tháng trước cách đây
mục cha
commit
8b417dae8e

+ 2 - 0
app/src/data/types.ts

@@ -372,6 +372,8 @@ export interface OverviewBundle {
  */
 export interface AgentInfo {
   slug: string
+  /** id del router asociado. Puede no coincidir con `slug` (#282). */
+  routerId?: string
   /** Unix SEGUNDOS del último push; null si nunca empujó */
   lastSeen: number | null
   /** Versión del binario netpulse-agent ("" si aún no se conoce) */

+ 4 - 2
app/src/hooks/useAgentFor.ts

@@ -1,8 +1,10 @@
 import { useNetPulse } from '@/data/DataProvider'
 import type { AgentInfo } from '@/data/types'
 
-/** Agente nativo registrado en un router: casa `slug` con `router.id` (Fase 3). */
+/** Agente nativo registrado en un router. El backend resuelve la asociación
+ *  por slug/hostname/MAC, así que preferimos `routerId` y caemos a `slug`
+ *  para compatibilidad con configuraciones antiguas (#282). */
 export function useAgentFor(routerId: string): AgentInfo | undefined {
   const { agents } = useNetPulse()
-  return agents.find((a) => a.slug === routerId)
+  return agents.find((a) => a.routerId === routerId || a.slug === routerId)
 }

+ 113 - 17
server-go/internal/adapters/agent.go

@@ -13,6 +13,7 @@ package adapters
 import (
 	"fmt"
 	"math"
+	"strings"
 	"sync"
 	"time"
 
@@ -200,6 +201,69 @@ func (r *AgentRegistry) Snapshot(slug string) *AgentState {
 	return &cp
 }
 
+// MatchRouter busca el agente asociado a un router: primero por slug exacto,
+// luego por hostname de board y finalmente por bridge MAC (#282). Devuelve
+// el slug real del agente, su payload y si está fresco. Permite que un agente
+// emparejado con un slug elegido por el usuario alimente un router cuyo id
+// autogenerado no coincide con ese slug.
+func (r *AgentRegistry) MatchRouter(cfg RouterConfig, macs map[string]string) (string, *probe.Payload, bool) {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+
+	norm := func(s string) string {
+		return strings.ToLower(strings.TrimSpace(s))
+	}
+	hostNames := []string{}
+	if cfg.Host != "" {
+		hostNames = append(hostNames, norm(cfg.Host))
+	}
+	if cfg.Name != "" && norm(cfg.Name) != norm(cfg.Host) {
+		hostNames = append(hostNames, norm(cfg.Name))
+	}
+	if cfg.ID != "" && norm(cfg.ID) != norm(cfg.Host) && norm(cfg.ID) != norm(cfg.Name) {
+		hostNames = append(hostNames, norm(cfg.ID))
+	}
+
+	var match *AgentState
+	var matchSlug string
+	for slug, st := range r.states {
+		if slug == cfg.ID {
+			match = st
+			matchSlug = slug
+			break
+		}
+		if st.Payload == nil || st.Payload.Data.System == nil || st.Payload.Data.System.Board == nil {
+			continue
+		}
+		h := norm(st.Payload.Data.System.Board.Hostname)
+		if h != "" {
+			for _, candidate := range hostNames {
+				if h == candidate {
+					match = st
+					matchSlug = slug
+					break
+				}
+			}
+		}
+		if match != nil {
+			break
+		}
+		mac := st.Payload.Data.System.BridgeMAC
+		if mac != "" && macs != nil {
+			if routerMac, ok := macs[cfg.ID]; ok && strings.EqualFold(mac, routerMac) {
+				match = st
+				matchSlug = slug
+				break
+			}
+		}
+	}
+	if match == nil {
+		return "", nil, false
+	}
+	fresh := r.now().Sub(match.LastSeen) <= r.effectiveTTL(match)
+	return matchSlug, match.Payload, fresh
+}
+
 // Forget borra el estado del slug (revocación de token).
 func (r *AgentRegistry) Forget(slug string) {
 	r.mu.Lock()
@@ -237,19 +301,27 @@ func agentName(cfg RouterConfig) string {
 	return cfg.Host
 }
 
-// pollRouterAgent: si el agente del router está fresco, construye el sondeo
-// desde su payload (Tier 2); si expiró, emite UNA vez la alerta de caída y
-// devuelve (nil, nil) para que el caller siga por SSH (Tier 0).
-// (fresh, polled) — fresh=false ⇒ el caller hace el sondeo SSH normal.
+// pollRouterAgent: si un agente asociado al router está fresco, construye el
+// sondeo desde su payload (Tier 2). Si expiró, emite UNA vez la alerta de
+// caída y devuelve (false, nil) para que el caller siga por SSH (Tier 0).
+// El emparejamiento no exige slug == router.id: también usa hostname/MAC
+// (#282). Cuando el agente está vivo pero el SSH falla por clave no
+// autorizada, emite una alerta informativa en vez de dejar la tarjeta en
+// offline (#281).
 func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 	l.mu.Lock()
 	reg := l.agents
+	macs := make(map[string]string, len(l.routerMacs))
+	for k, v := range l.routerMacs {
+		macs[k] = v
+	}
 	l.mu.Unlock()
 	if reg == nil {
 		return false, nil
 	}
-	if p, ok := reg.Fresh(cfg.ID); ok {
-		// Recuperación: estaba caído y volvió a empujar → alerta ok.
+
+	slug, p, fresh := reg.MatchRouter(cfg, macs)
+	if fresh {
 		l.mu.Lock()
 		if l.agentDown[cfg.ID] {
 			l.agentDown[cfg.ID] = false
@@ -263,23 +335,47 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 				Time:        "ahora mismo", RouterID: cfg.ID,
 			})
 		}
+		// issue #281: SSH falla por clave no autorizada pero el agente sigue
+		// vivo → avisa una sola vez. Se borra el flag cuando SSH vuelve.
+		if l.lastErr[cfg.ID] != nil && isAccessError(l.lastErr[cfg.ID]) {
+			if !l.sshAuthFailAlerted[cfg.ID] {
+				l.sshAuthFailAlerted[cfg.ID] = true
+				name := agentName(cfg)
+				l.engine.Emit(AlertEvent{
+					ID:       fmt.Sprintf("alert-ssh-auth-%s-%d", cfg.ID, time.Now().UnixMilli()),
+					Category: alerts.CatSystem, Urgent: false,
+					Severity:    "warn",
+					Title:       "Acceso SSH perdido en " + name,
+					Description: fmt.Sprintf("%s no acepta la clave SSH, pero su agente sigue enviando datos. Revisa authorized_keys tras un firmware upgrade.", name),
+					Time:        "ahora mismo", RouterID: cfg.ID,
+				})
+			}
+		} else if l.sshAuthFailAlerted[cfg.ID] {
+			delete(l.sshAuthFailAlerted, cfg.ID)
+			name := agentName(cfg)
+			l.engine.Emit(AlertEvent{
+				ID:       fmt.Sprintf("alert-ssh-auth-ok-%s-%d", cfg.ID, time.Now().UnixMilli()),
+				Category: alerts.CatSystem, Urgent: false,
+				Severity:    "ok",
+				Title:       "Acceso SSH recuperado en " + name,
+				Description: fmt.Sprintf("El acceso SSH a %s funciona de nuevo", name),
+				Time:        "ahora mismo", RouterID: cfg.ID,
+			})
+		}
 		l.mu.Unlock()
 		return true, l.polledFromAgent(cfg, p)
 	}
-	if reg.Expired(cfg.ID) {
-		// Dead Man's Switch (P6): el agente está stale (más allá del TTL),
-		// pero solo disparamos la alerta de caída si lleva más de
-		// agentDownConfirm sin empujar. Entre TTL y agentDownConfirm el
-		// router degrada a SSH silenciosamente (sin alertar), evitando
-		// spam en flapeos breves de fibra/WiFi.
+
+	if slug != "" {
+		// Dead Man's Switch (P6): el agente está stale, pero solo disparamos la
+		// alerta de caída si lleva más de agentDownConfirm sin empujar. Entre
+		// TTL y agentDownConfirm el router degrada a SSH silenciosamente.
 		confirm := l.agentDownConfirm
 		if confirm <= 0 {
 			confirm = 3 * time.Minute
 		}
-		// Pushers externos (#288): escalar la confirmación a su cadencia
-		// declarada (3x interval) para no alertar caídas falsas.
-		confirm = reg.ExternalDownConfirm(cfg.ID, confirm)
-		if reg.StaleFor(cfg.ID, confirm) {
+		confirm = reg.ExternalDownConfirm(slug, confirm)
+		if reg.StaleFor(slug, confirm) {
 			l.mu.Lock()
 			if !l.agentDown[cfg.ID] {
 				l.agentDown[cfg.ID] = true
@@ -307,7 +403,7 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 			l.mu.Unlock()
 		}
 		if cfg.AgentOnly {
-			if p, ok := reg.StalePayload(cfg.ID); ok {
+			if p != nil {
 				return true, l.polledFromAgent(cfg, p)
 			}
 		}

+ 138 - 0
server-go/internal/adapters/agent_match_test.go

@@ -0,0 +1,138 @@
+// agent_match_test.go — Emparejamiento agente↔router por slug/hostname/MAC
+// (#282) y alerta cuando SSH falla pero el agente sigue vivo (#281).
+package adapters
+
+import (
+	"errors"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+func TestAgentRegistryMatchRouterByHostname(t *testing.T) {
+	reg := NewAgentRegistry(90 * time.Second)
+	now := time.Now()
+	reg.SetClock(func() time.Time { return now })
+
+	pl := testPayload()
+	pl.Router = "flint2"
+	pl.Data.System.Board.Hostname = "flint2"
+	reg.Ingest(pl)
+
+	cfg := RouterConfig{ID: "gl-inet-gl-mt6000", Name: "flint2", Host: "192.168.10.1"}
+	slug, p, fresh := reg.MatchRouter(cfg, nil)
+	if !fresh || slug != "flint2" || p == nil {
+		t.Fatalf("esperaba match fresco por hostname; got slug=%q fresh=%v p=%v", slug, fresh, p)
+	}
+}
+
+func TestAgentRegistryMatchRouterByMac(t *testing.T) {
+	reg := NewAgentRegistry(90 * time.Second)
+	now := time.Now()
+	reg.SetClock(func() time.Time { return now })
+
+	pl := testPayload()
+	pl.Router = "ap-east"
+	pl.Data.System.Board.Hostname = "otro"
+	pl.Data.System.BridgeMAC = "94:83:C4:00:00:09"
+	reg.Ingest(pl)
+
+	cfg := RouterConfig{ID: "tp-link-eap225-09", Name: "Este", Host: "192.168.1.9"}
+	macs := map[string]string{cfg.ID: "94:83:C4:00:00:09"}
+	slug, p, fresh := reg.MatchRouter(cfg, macs)
+	if !fresh || slug != "ap-east" || p == nil {
+		t.Fatalf("esperaba match fresco por MAC; got slug=%q fresh=%v p=%v", slug, fresh, p)
+	}
+}
+
+func TestAgentRegistryMatchRouterStale(t *testing.T) {
+	reg := NewAgentRegistry(50 * time.Millisecond)
+	now := time.Now()
+	reg.SetClock(func() time.Time { return now })
+
+	pl := testPayload()
+	pl.Router = "flint2"
+	pl.Data.System.Board.Hostname = "flint2"
+	reg.Ingest(pl)
+
+	now = now.Add(100 * time.Millisecond)
+	cfg := RouterConfig{ID: "gl-inet-gl-mt6000", Name: "flint2", Host: "192.168.10.1"}
+	_, p, fresh := reg.MatchRouter(cfg, nil)
+	if fresh || p == nil {
+		t.Fatalf("esperaba match pero no fresco; got fresh=%v", fresh)
+	}
+}
+
+func TestLiveAgentFuzzyMatchSkipsSSH(t *testing.T) {
+	reg := NewAgentRegistry(90 * time.Second)
+	l := newLiveAgentTest(t, reg)
+
+	pl := testPayload()
+	pl.Router = "flint2"
+	pl.Data.System.Board.Hostname = "flint2"
+	reg.Ingest(pl)
+
+	cfg := RouterConfig{ID: "gl-inet-gl-mt6000", Name: "flint2", Host: "127.0.0.1"}
+	p, err := l.pollRouter(t.Context(), cfg)
+	if err != nil {
+		t.Fatalf("con agente emparejado por hostname no debería tocar SSH: %v", err)
+	}
+	if p.cpu != 12 {
+		t.Fatalf("esperaba datos del payload; cpu=%d", p.cpu)
+	}
+}
+
+func TestLiveAgentSSHAuthFailAlert(t *testing.T) {
+	reg := NewAgentRegistry(90 * time.Second)
+	l := newLiveAgentTest(t, reg)
+
+	// Simula que el último sondeo SSH fue de acceso denegado (#257) y que el
+	// agente sigue empujando (por hostname) -> alerta no urgente (#281).
+	l.mu.Lock()
+	l.lastErr["gl-inet-gl-mt6000"] = errors.New("permission denied")
+	l.mu.Unlock()
+
+	pl := testPayload()
+	pl.Router = "flint2"
+	pl.Data.System.Board.Hostname = "flint2"
+	reg.Ingest(pl)
+
+	cfg := RouterConfig{ID: "gl-inet-gl-mt6000", Name: "flint2", Host: "127.0.0.1"}
+	if _, err := l.pollRouter(t.Context(), cfg); err != nil {
+		t.Fatalf("agente fresco: %v", err)
+	}
+
+	a := findAlert(l.engine.List(), "Acceso SSH perdido")
+	if a == nil {
+		t.Fatalf("esperaba alerta #281; alerts=%+v", l.engine.List())
+	}
+	if a.Category != alerts.CatSystem || a.Urgent || a.Severity != "warn" {
+		t.Fatalf("alerta #281 con categoría errónea: %+v", a)
+	}
+	if !strings.Contains(a.Description, "authorized_keys") {
+		t.Fatalf("descripción sin hint de authorized_keys: %s", a.Description)
+	}
+
+	// Si el acceso SSH se recupera, la alerta no debe repetirse (se borra el flag).
+	l.mu.Lock()
+	delete(l.lastErr, "gl-inet-gl-mt6000")
+	l.mu.Unlock()
+	if _, err := l.pollRouter(t.Context(), cfg); err != nil {
+		t.Fatalf("segundo poll: %v", err)
+	}
+	if n := countAlerts(l.engine.List(), "Acceso SSH perdido"); n != 1 {
+		t.Fatalf("alerta duplicada tras recuperación: %d", n)
+	}
+}
+
+func countAlerts(list []AlertEvent, titlePart string) int {
+	n := 0
+	for _, a := range list {
+		if strings.Contains(a.Title, titlePart) {
+			n++
+		}
+	}
+	return n
+}

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

@@ -227,6 +227,15 @@ type Live struct {
 	agentDown        map[string]bool
 	agentDownConfirm time.Duration // Dead Man's Switch: confirmar caída tras este periodo sin alertar
 
+	// routerMacs: id → bridge MAC persistida en DB. Permite emparejar un agente
+	// con su router aunque el slug elegido por el usuario no coincida con el id
+	// autogenerado del router (#282).
+	routerMacs map[string]string
+
+	// sshAuthFailAlerted evita repetir la alerta de "SSH sin clave pero agente
+	// vivo" (#281). Se limpia cuando el acceso SSH se recupera.
+	sshAuthFailAlerted map[string]bool
+
 	// now: reloj inyectable para tests deterministas (nil → time.Now).
 	// Mismo patrón que AgentRegistry.SetClock.
 	now func() time.Time
@@ -277,7 +286,10 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		wanInfoCache:         map[string]wanInfoCacheEntry{},
 		agentDown:            map[string]bool{},
 		agentDownConfirm:     3 * time.Minute, // Dead Man's Switch (P6): 3 min por defecto
+		routerMacs:           map[string]string{},
+		sshAuthFailAlerted:   map[string]bool{},
 	}
+	l.loadRouterMacs()
 	// Migración una vez (attrib_v2): tabla limpia (index.js:385-394)
 	if d != nil {
 		var flag string
@@ -303,6 +315,26 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 	return l
 }
 
+// loadRouterMacs carga las MACs persistidas de routers para poder emparejar
+// agentes con routers por bridge MAC (#282).
+func (l *Live) loadRouterMacs() {
+	if l.db == nil {
+		return
+	}
+	l.routerMacs = map[string]string{}
+	rows, err := l.db.Query("SELECT id, mac FROM routers WHERE mac IS NOT NULL AND mac != ''")
+	if err != nil {
+		return
+	}
+	defer rows.Close()
+	for rows.Next() {
+		var id, mac string
+		if rows.Scan(&id, &mac) == nil {
+			l.routerMacs[id] = mac
+		}
+	}
+}
+
 // Mode: "live".
 func (l *Live) Mode() string { return "live" }
 
@@ -397,6 +429,12 @@ func (l *Live) SetRouters(list []RouterConfig) {
 			delete(l.wanInfoCache, id)
 		}
 	}
+	for id := range l.sshAuthFailAlerted {
+		if !ids[id] {
+			delete(l.sshAuthFailAlerted, id)
+		}
+	}
+	l.loadRouterMacs()
 }
 
 // probeBackhaul detecta el medio del uplink (interfaz STA asociada → "wifi";

+ 69 - 17
server-go/internal/httpapi/agent.go

@@ -348,7 +348,8 @@ func (s *server) agentInstallLine(r *http.Request, slug, token string) string {
 // agentListItem: lo que ve la UI — NUNCA el token ni su hash.
 type agentListItem struct {
 	Slug     string `json:"slug"`
-	LastSeen *int64 `json:"lastSeen"` // unix SEGUNDOS; null si nunca empujó
+	RouterID string `json:"routerId,omitempty"` // id del router asociado (#282)
+	LastSeen *int64 `json:"lastSeen"`           // unix SEGUNDOS; null si nunca empujó
 	Version  string `json:"version,omitempty"`
 	Fresh    bool   `json:"fresh"`
 	// UpdateAvailable: true si el agente reportó una versión distinta de la
@@ -377,10 +378,10 @@ type agentUpgradeStep struct {
 
 // agentUpgradeInfo es el paso de progreso expuesto en GET /api/agents.
 type agentUpgradeInfo struct {
-	Step  string            `json:"step"`
-	Pct   int               `json:"pct,omitempty"` // 0-100 en "downloading"
-	Error string            `json:"error,omitempty"`
-	Ts    int64             `json:"ts"` // unix segundos del último reporte
+	Step  string             `json:"step"`
+	Pct   int                `json:"pct,omitempty"` // 0-100 en "downloading"
+	Error string             `json:"error,omitempty"`
+	Ts    int64              `json:"ts"`              // unix segundos del último reporte
 	Steps []agentUpgradeStep `json:"steps,omitempty"` // historia de pasos (#284)
 }
 
@@ -409,16 +410,17 @@ func (s *server) routerUpgradeable(slug string) bool {
 // handleAgentsList: slugs con token + last_seen + versión.
 func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 	out := []agentListItem{}
-	// Types de routers por slug, precargados en UNA consulta: con
-	// SetMaxOpenConns(1) un QueryRow dentro del bucle de rows de abajo
-	// esperaría la conexión que el rows activo mantiene (deadlock).
-	routerTypes := map[string]string{}
+	// Routers precargados en UNA consulta: con SetMaxOpenConns(1) un QueryRow
+	// dentro del bucle de rows de abajo esperaría la conexión que el rows
+	// activo mantiene (deadlock). Guardamos id, type, name, host y mac para
+	// resolver la asociación agente↔router (#282).
+	routerByID := map[string]routerIdentity{}
 	if s.db != nil {
-		if rows, err := s.db.Query("SELECT id, type FROM routers"); err == nil {
+		if rows, err := s.db.Query("SELECT id, type, name, host, COALESCE(mac,'') FROM routers"); err == nil {
 			for rows.Next() {
-				var id, typ string
-				if rows.Scan(&id, &typ) == nil {
-					routerTypes[id] = typ
+				var id, typ, name, host, mac string
+				if rows.Scan(&id, &typ, &name, &host, &mac) == nil {
+					routerByID[id] = routerIdentity{ID: id, Type: typ, Name: name, Host: host, Mac: mac}
 				}
 			}
 			rows.Close()
@@ -435,7 +437,11 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 				}
 				slug := strings.TrimPrefix(key, agentTokenKeyPrefix)
 				item := agentListItem{Slug: slug}
+				var payload *probe.Payload
 				if s.agents != nil {
+					if st := s.agents.Snapshot(slug); st != nil {
+						payload = st.Payload
+					}
 					if seen, version, kind, interval, ok := s.agents.Info(slug); ok {
 						ts := seen.Unix()
 						item.LastSeen = &ts
@@ -446,13 +452,18 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 							item.Kind = "native"
 						}
 						item.Interval = interval
-						// Fase 6.3 (issue #243): upgrade disponible si el agente
-						// reporta una versión distinta del binario embebido y es
-						// un agente nativo OpenWrt (no un scraper).
-						item.UpdateAvailable = agentUpgradeable(routerTypes[slug]) && version != "" && version != agentbin.EmbeddedAgentVersion
 					}
 					_, item.Fresh = s.agents.Fresh(slug)
 				}
+				item.RouterID = resolveAgentRouter(slug, payload, routerByID)
+				// Fase 6.3 (issue #243): upgrade disponible si el agente
+				// reporta una versión distinta del binario embebido y el router
+				// asociado es actualizable (nativo OpenWrt/GL.iNet).
+				matchedType := ""
+				if r, ok := routerByID[item.RouterID]; ok {
+					matchedType = r.Type
+				}
+				item.UpdateAvailable = agentUpgradeable(matchedType) && item.Version != "" && item.Version != agentbin.EmbeddedAgentVersion
 				// Progreso en vivo del upgrade (#284), si hay actividad reciente.
 				if st, ok := s.upgrades.snapshot(slug); ok {
 					ts := st.Ts.Unix()
@@ -469,6 +480,47 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 	writeJSON(w, http.StatusOK, map[string]any{"agents": out})
 }
 
+// routerIdentity es la información mínima de un router para resolver la
+// asociación agente↔router sin exponer credenciales.
+type routerIdentity struct {
+	ID   string
+	Type string
+	Name string
+	Host string
+	Mac  string
+}
+
+// resolveAgentRouter devuelve el id del router asociado a un agente. Primero
+// intenta slug == router.id; si no, empareja por hostname del board del
+// payload o por bridge MAC persistida (#282).
+func resolveAgentRouter(slug string, payload *probe.Payload, routers map[string]routerIdentity) string {
+	if slug != "" {
+		if _, ok := routers[slug]; ok {
+			return slug
+		}
+	}
+	if payload == nil || payload.Data.System == nil || payload.Data.System.Board == nil {
+		return ""
+	}
+	norm := func(s string) string { return strings.ToLower(strings.TrimSpace(s)) }
+	hostname := norm(payload.Data.System.Board.Hostname)
+	if hostname != "" {
+		for _, r := range routers {
+			if hostname == norm(r.Host) || hostname == norm(r.Name) {
+				return r.ID
+			}
+		}
+	}
+	if payload.Data.System.BridgeMAC != "" {
+		for _, r := range routers {
+			if strings.EqualFold(payload.Data.System.BridgeMAC, r.Mac) {
+				return r.ID
+			}
+		}
+	}
+	return ""
+}
+
 // handleAgentsDelete: revoca el token del slug (el agente recibirá 401 en su
 // próximo push) y olvida su estado. 404 si no existía.
 func (s *server) handleAgentsDelete(w http.ResponseWriter, r *http.Request) {

+ 48 - 0
server-go/internal/httpapi/agent_match_api_test.go

@@ -0,0 +1,48 @@
+package httpapi_test
+
+import (
+	"fmt"
+	"testing"
+	"time"
+)
+
+// TestAgentsListResolvesRouterIdByHostname verifica que GET /api/agents
+// expone routerId incluso cuando el slug del agente no coincide con el id del
+// router (#282).
+func TestAgentsListResolvesRouterIdByHostname(t *testing.T) {
+	ts := makeAgentTestServer(t)
+
+	// Insertar un router cuyo id autogenerado difiere del slug elegido.
+	_, err := ts.db.Exec("INSERT INTO routers (id, name, host, type, is_gateway, created_at) VALUES (?, ?, ?, ?, ?, ?)",
+		"gl-inet-gl-mt6000", "flint2", "192.168.10.1", "glinet", 1, time.Now().UnixMilli())
+	if err != nil {
+		t.Fatalf("insert router: %v", err)
+	}
+
+	_, token, _ := createAgentToken(t, ts, "flint2")
+
+	// Payload con hostname que casa con el name del router.
+	payload := fmt.Sprintf(`{"router":"flint2","ts":%d,"version":"0.1.0","data":{"system":{"sysinfo":{"uptime":100,"load":[0,0,0],"memory":{"total":100,"free":50,"buffered":0,"available":50}},"board":{"hostname":"flint2","model":"GL-MT6000"},"cpu":10,"temp":40},"wireless":{"clients":{}},"dhcp":{"leases":[]},"fdb":{"macs":{}}}}`, time.Now().Unix())
+	res := ingest(t, ts, token, "10.0.5.1", payload)
+	res.Body.Close()
+	if res.StatusCode != 202 {
+		t.Fatalf("ingest: %d", res.StatusCode)
+	}
+
+	res = get(t, ts.URL, "/api/agents", ts.cookie)
+	body := readJSON(t, res)
+	agents, _ := body["agents"].([]any)
+	var flint2 map[string]any
+	for _, a := range agents {
+		m, _ := a.(map[string]any)
+		if m["slug"] == "flint2" {
+			flint2 = m
+		}
+	}
+	if flint2 == nil {
+		t.Fatalf("agente no listado: %v", body)
+	}
+	if flint2["routerId"] != "gl-inet-gl-mt6000" {
+		t.Fatalf("routerId esperado gl-inet-gl-mt6000, got %v", flint2["routerId"])
+	}
+}