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

fix: reject rows for unknown slugs and the device signal filter (#2224)

The ingest no longer writes reject rows for a slug that has no token, and the device list applies the minimum signal filter on the click that sets it.

Closes #2219
Closes #2220
Nacho 6 дней назад
Родитель
Сommit
d973c22387

+ 2 - 0
CHANGELOG.md

@@ -19,6 +19,8 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- A push with a bad token for a slug that was never registered no longer leaves two rows in kv. Any host that can reach the ingest could fill the table with invented names, and nothing cleans those keys: the badge exists for agents that exist (#2219).
+- The minimum signal filter of the device list applies on the click that sets it. It was read inside the memo but missing from its dependencies, so the list only changed with the next poll, and never on a static one (#2220).
 - The alert card of the home summary no longer lists read alerts and drops one as soon as it is marked read. When the filter leaves it empty it says so, offers one click back to the whole list and a link to the alert log, and its badge no longer subtracts the same read alert twice (#2217).
 - A WAN port that the user bridged into `br-lan` to run the unit as an access point stops being painted as the WAN port. The label already said LAN N, but the port kept the `wan` id and the panel draws every port with that id as the internet link, so a FRITZ!Box 4040 in AP mode showed its fifth bridged jack as "WAN" while the real uplink was another LAN port. The port now takes the id that matches its label, moves to the end of the chassis and keeps its traffic counters (#2181, reported by @fsolak47).
 - A NetGrip panel whose embedded agent carries an old token never recovered. The rearm restarted the panel and then rotated the token in the native agent's environment file, which NetGrip does not read, so the panel kept answering 401 every cycle and the supervisor kept restarting it on each cooldown. The token now goes into `/etc/netgrip/netpulse.env`, the file the embedded agent reads, and the panel is restarted after it (#2208).

+ 1 - 1
app/src/pages/Devices.tsx

@@ -1842,7 +1842,7 @@ export default function Devices() {
       }
       return a.name.localeCompare(b.name, numLocale())
     })
-  }, [allDevices, online, onlyWeak, weakDbm, onlyUnprotected, routerIds, bandsEffective, groups, q, sort, routers])
+  }, [allDevices, online, onlyWeak, weakDbm, minSignal, onlyUnprotected, routerIds, bandsEffective, groups, q, sort, routers])
 
   // #1207: export CSV de la vista filtrada actual (cliente, sin backend).
   const exportCsv = useCallback(() => {

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

@@ -168,10 +168,20 @@ func agentRejectReasonKey(slug string) string { return agentRejectReasonKeyPrefi
 // autenticación (#1717): la tabla de agentes lo muestra como badge hasta que
 // un push válido lo limpia. Con el motivo (#2211) el panel puede decir por
 // qué, que es la diferencia entre "mira el reloj del router" y "reinícialo".
+//
+// #2219: solo se anota si el slug tiene token registrado. Un slug inventado
+// que llega con un Bearer incorrecto es lo que ve cualquiera que alcance el
+// endpoint, y sin esta guarda cada nombre dejaba dos filas en kv para
+// siempre (nada las limpia: un push válido y la baja de agente necesitan un
+// agente real).
 func (s *server) recordAgentReject(slug, reason string) {
 	if s.db == nil {
 		return
 	}
+	var exists int
+	if err := s.db.QueryRow("SELECT COUNT(*) FROM kv WHERE key = ?", agentTokenKey(slug)).Scan(&exists); err != nil || exists == 0 {
+		return
+	}
 	_, _ = s.db.Exec(
 		`INSERT INTO kv (key, value) VALUES (?, ?)
 		 ON CONFLICT(key) DO UPDATE SET value=excluded.value`,

+ 62 - 0
server-go/internal/httpapi/agent_reject_unknown_slug_2219_test.go

@@ -0,0 +1,62 @@
+// agent_reject_unknown_slug_2219_test.go — #2219: un push con Bearer
+// incorrecto para un slug que no existe dejaba dos filas en kv (timestamp y
+// motivo) sin nada que las limpiara nunca. El badge existe para agentes
+// registrados, así que un slug desconocido no se anota.
+package httpapi_test
+
+import (
+	"net/http"
+	"strings"
+	"testing"
+)
+
+func postIngestRaw(t *testing.T, ts *agentTestServer, token, ip, payload string) int {
+	t.Helper()
+	req, _ := http.NewRequest("POST", ts.URL+"/api/ingest/agent", strings.NewReader(payload))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("X-Forwarded-For", ip)
+	if token != "" {
+		req.Header.Set("Authorization", "Bearer "+token)
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("ingest: %v", err)
+	}
+	defer res.Body.Close()
+	return res.StatusCode
+}
+
+func countKVLike(t *testing.T, ts *agentTestServer, like string) int {
+	t.Helper()
+	var n int
+	if err := ts.db.QueryRow("SELECT COUNT(*) FROM kv WHERE key LIKE ?", like).Scan(&n); err != nil {
+		t.Fatalf("contar %s: %v", like, err)
+	}
+	return n
+}
+
+func TestRejectForUnknownSlugWritesNothing(t *testing.T) {
+	ts := makeAgentTestServer(t)
+
+	unknown := `{"router":"no-existe","ts":1764000000,"version":"0.1.0","data":{}}`
+	if got := postIngestRaw(t, ts, "inventado", "10.9.2.1", unknown); got != 401 {
+		t.Fatalf("token inválido para slug desconocido: %d", got)
+	}
+	for _, prefix := range []string{"agent.reject_ts.%", "agent.reject_reason.%"} {
+		if n := countKVLike(t, ts, prefix); n != 0 {
+			t.Fatalf("%s dejó %d fila(s) para un slug sin token", prefix, n)
+		}
+	}
+
+	// Un slug registrado sí deja constancia, que es para lo que existe el badge.
+	if status, _, _ := createAgentToken(t, ts, "patio"); status != 201 {
+		t.Fatalf("create: %d", status)
+	}
+	registered := strings.Replace(unknown, "no-existe", "patio", 1)
+	if got := postIngestRaw(t, ts, "inventado", "10.9.2.2", registered); got != 401 {
+		t.Fatalf("token inválido para patio: %d", got)
+	}
+	if n := countKVLike(t, ts, "agent.reject_ts.patio"); n != 1 {
+		t.Fatalf("un slug registrado debe dejar su marca de rechazo, filas=%d", n)
+	}
+}