Pārlūkot izejas kodu

feat(agents): say why a push was rejected (#2212)

The reason behind a 401 is stored next to the timestamp, returned as rejectedReason, shown in the tooltip of the badge and quoted in the auto-rearm alert, so a clock skew no longer looks like a dead token.

Closes #2211
Nacho 6 dienas atpakaļ
vecāks
revīzija
cb60bfd6c7

+ 4 - 0
CHANGELOG.md

@@ -7,6 +7,10 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ## [Unreleased]
 
+### Added
+
+- A rejected push says why. The server answered `unauthorized`, `invalid_signature` or `stale_payload` and kept only a timestamp, so the panel showed the same "token rejected" badge for a stale token, an agent older than the server and a unit whose clock is minutes off. The reason is stored next to the timestamp, returned by `/api/agents` as `rejectedReason`, shown in the badge tooltip with what to check, and quoted in the auto-rearm alert, which no longer says "restarted but did not come back" when the pushes never got in (#2211).
+
 ### Fixed
 
 - 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).

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

@@ -1520,7 +1520,9 @@
       "netgripHint": "The agent lives in the NetGrip panel: Update upgrades the panel itself",
       "netgripStaleHint": "The agent lives in the NetGrip panel. If it stops reporting, restart it with the button (restarts the NetGrip service on the router) or update the panel if a newer version is available.",
       "rejectedBadge": "Token rejected",
-      "rejectedTip": "The server is rejecting this agent pushes with 401: the token does not match (typical after a router reboot or a server move). Rearm or Reinstall to fix it; the badge clears itself on the first good push."
+      "rejectedTip": "The server is rejecting this agent pushes with 401: the token does not match (typical after a router reboot or a server move). Rearm or Reinstall to fix it; the badge clears itself on the first good push.",
+      "rejectedTipStale": "The server rejects this agent because the payload timestamp is outside its freshness window. Check the unit clock first: it has to be within a few minutes of the server.",
+      "rejectedTipSignature": "The server rejects this agent because the signature does not match. The agent build is usually older than this server expects."
     },
     "upgradeUpdatedDetail": "Updated · {{count}} steps · {{secs}} s",
     "noVitals": "No system metrics",

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

@@ -1520,7 +1520,9 @@
       "netgripHint": "El agente vive en el panel NetGrip: Actualizar actualiza el propio panel",
       "netgripStaleHint": "El agente vive en el panel NetGrip. Si no reporta, reinícialo con el botón (reinicia el servicio NetGrip en el router) o actualiza el panel si hay versión nueva.",
       "rejectedBadge": "Token rechazado",
-      "rejectedTip": "El servidor rechaza los pushes de este agente con 401: el token no coincide (típico tras un reinicio del router o un cambio de servidor). Rearmar o Reinstalar lo arregla; el badge se limpia solo con el primer push válido."
+      "rejectedTip": "El servidor rechaza los pushes de este agente con 401: el token no coincide (típico tras un reinicio del router o un cambio de servidor). Rearmar o Reinstalar lo arregla; el badge se limpia solo con el primer push válido.",
+      "rejectedTipStale": "El servidor rechaza a este agente porque la marca de tiempo del payload cae fuera de su ventana de frescura. Mira primero el reloj de la unidad: tiene que estar a pocos minutos del servidor.",
+      "rejectedTipSignature": "El servidor rechaza a este agente porque la firma no coincide. Normalmente el binario del agente es más viejo de lo que espera este servidor."
     },
     "upgradeUpdatedDetail": "Actualizado · {{count}} pasos · {{secs}} s",
     "noVitals": "Sin métricas de sistema",

+ 3 - 1
app/public/locales/ru/translation.json

@@ -1559,7 +1559,9 @@
       "netgripHint": "Агент живёт в панели NetGrip: \"Обновить\" обновляет саму панель",
       "netgripStaleHint": "Агент живёт в панели NetGrip. Если он перестал передавать данные, перезапустите его кнопкой (перезапускает службу NetGrip на роутере) или обновите панель, если есть новая версия.",
       "rejectedBadge": "Токен отклоняется",
-      "rejectedTip": "Сервер отклоняет передачу этого агента с 401: токен не совпадает (типично после перезагрузки роутера или переезда сервера). Исправляется перезапуском или переустановкой, значок снимется сам после первой удачной передачи."
+      "rejectedTip": "Сервер отклоняет передачу этого агента с 401: токен не совпадает (типично после перезагрузки роутера или переезда сервера). Исправляется перезапуском или переустановкой, значок снимется сам после первой удачной передачи.",
+      "rejectedTipStale": "Сервер отклоняет агента: метка времени в payload выходит за окно свежести. Проверьте часы устройства, они должны отличаться от сервера не более чем на несколько минут.",
+      "rejectedTipSignature": "Сервер отклоняет агента: подпись не совпадает. Обычно сборка агента старше, чем ожидает сервер."
     },
     "upgradeUpdatedDetail": "Обновлено · {{count}} шагов · {{secs}} с",
     "noVitals": "Нет системных метрик",

+ 2 - 0
app/public/locales/zh/translation.json

@@ -809,6 +809,8 @@
       "forgotten": "已忘记主机密钥",
       "rejectedBadge": "令牌被拒绝",
       "rejectedTip": "服务器正以 401 拒绝该探针的推送:令牌不匹配(路由器重启或服务器迁移后常见)。用「重启探针」或「重装」修复。首次成功推送后该标记会自动消失。",
+      "rejectedTipStale": "服务器拒绝该 agent,因为负载的时间戳超出了新鲜度窗口。请先检查设备时钟:它必须与服务器相差不超过几分钟。",
+      "rejectedTipSignature": "服务器拒绝该 agent,因为签名不匹配。通常说明 agent 版本比服务器要求的更旧。",
       "rotate": "重新生成令牌",
       "rotateFail": "无法重新生成令牌",
       "rotateRetry": "重试生成令牌",

+ 7 - 1
app/src/components/routers/AgentsSection.tsx

@@ -350,7 +350,13 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
               válido lo limpia, así que desaparece solo al Rearmar/Reinstalar. */}
           {agent?.rejectedAt ? (
             <span
-              title={t('routers.agents.rejectedTip')}
+              title={
+                agent.rejectedReason === 'stale_payload'
+                  ? t('routers.agents.rejectedTipStale')
+                  : agent.rejectedReason === 'invalid_signature'
+                    ? t('routers.agents.rejectedTipSignature')
+                    : t('routers.agents.rejectedTip')
+              }
               className="inline-flex items-center rounded-full border border-danger/40 bg-danger/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-danger"
             >
               {t('routers.agents.rejectedBadge')}

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

@@ -682,6 +682,12 @@ export interface AgentInfo {
    * que el badge desaparece solo al recuperar el token (Rearm/Reinstall).
    */
   rejectedAt?: number
+  /**
+   * Motivo del último 401 (#2211): `unauthorized`, `invalid_signature` o
+   * `stale_payload`. Permite decir en el tooltip qué mirar (token, versión del
+   * agente o reloj) en vez de solo "rechazado".
+   */
+  rejectedReason?: string
   /**
    * true si el agente reporta una versión distinta de la del binario embebido
    * (Fase 6.3, issue #243): hay upgrade disponible vía POST /api/agents/{slug}/upgrade.

+ 51 - 8
server-go/internal/httpapi/agent.go

@@ -57,6 +57,12 @@ const (
 	// válido, de modo que el badge de la tabla de agentes desaparece solo
 	// cuando el agente vuelve a autenticarse (tras Rearm/Reinstall).
 	agentRejectKeyPrefix = "agent.reject_ts."
+	// agentRejectReasonKeyPrefix: kv agent.reject_reason.<slug> = motivo del
+	// último rechazo (#2211): unauthorized, invalid_signature o stale_payload.
+	// El 401 solo dice "rechazado", y sin el motivo un reloj desfasado (que
+	// no se arregla reiniciando nada) parece un agente muerto. Se guarda con
+	// la misma vida que el timestamp: el primer push válido borra los dos.
+	agentRejectReasonKeyPrefix = "agent.reject_reason."
 	// maxTsDrift: ventana de frescura del `ts` del agente (anti-replay,
 	// auditoría de seguridad #2). Payloads con ts fuera de |±maxTsDrift|
 	// respecto al reloj del servidor se rechazan con 401 (evita reinyectar
@@ -156,10 +162,13 @@ func agentTokenKey(slug string) string { return agentTokenKeyPrefix + slug }
 
 func agentRejectKey(slug string) string { return agentRejectKeyPrefix + slug }
 
+func agentRejectReasonKey(slug string) string { return agentRejectReasonKeyPrefix + slug }
+
 // recordAgentReject deja constancia (best-effort) de un push rechazado por
 // autenticación (#1717): la tabla de agentes lo muestra como badge hasta que
-// un push válido lo limpia.
-func (s *server) recordAgentReject(slug string) {
+// 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".
+func (s *server) recordAgentReject(slug, reason string) {
 	if s.db == nil {
 		return
 	}
@@ -167,6 +176,21 @@ func (s *server) recordAgentReject(slug string) {
 		`INSERT INTO kv (key, value) VALUES (?, ?)
 		 ON CONFLICT(key) DO UPDATE SET value=excluded.value`,
 		agentRejectKey(slug), strconv.FormatInt(time.Now().Unix(), 10))
+	if reason != "" {
+		_, _ = s.db.Exec(
+			`INSERT INTO kv (key, value) VALUES (?, ?)
+			 ON CONFLICT(key) DO UPDATE SET value=excluded.value`,
+			agentRejectReasonKey(slug), reason)
+	}
+}
+
+// clearAgentReject borra el badge y su motivo. Lo llaman el primer push
+// válido y la baja del agente.
+func (s *server) clearAgentReject(slug string) {
+	if s.db == nil {
+		return
+	}
+	_, _ = s.db.Exec("DELETE FROM kv WHERE key IN (?, ?)", agentRejectKey(slug), agentRejectReasonKey(slug))
 }
 
 // hashAgentToken: sha256 hex del token (lo único que se persiste).
@@ -283,7 +307,7 @@ func (s *server) handleIngestAgent(w http.ResponseWriter, r *http.Request) {
 	token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
 	if !s.checkAgentToken(p.Router, token) {
 		// #1717: anota el rechazo para el badge de la tabla de agentes.
-		s.recordAgentReject(p.Router)
+		s.recordAgentReject(p.Router, "unauthorized")
 		writeError(w, http.StatusUnauthorized, "unauthorized")
 		return
 	}
@@ -291,8 +315,9 @@ func (s *server) handleIngestAgent(w http.ResponseWriter, r *http.Request) {
 	sig := r.Header.Get("X-Agent-Signature")
 	if err := checkHMAC(token, body, sig); err != nil {
 		// #1717: la firma va ligada al token, así que un fallo de firma es
-		// también un token que no sirve (mismo badge).
-		s.recordAgentReject(p.Router)
+		// también un token que no sirve (mismo badge). El motivo importa:
+		// una firma que no cuadra suele ser un agente viejo (#2211).
+		s.recordAgentReject(p.Router, "invalid_signature")
 		writeError(w, http.StatusUnauthorized, "invalid_signature", err.Error())
 		return
 	}
@@ -300,6 +325,7 @@ func (s *server) handleIngestAgent(w http.ResponseWriter, r *http.Request) {
 	// ventana de frescura respecto al reloj del servidor. Rechaza pushes
 	// viejos capturados/reinyectados y saltos de reloj grandes del agente.
 	if drift := time.Since(time.Unix(p.Ts, 0)); drift < -s.maxTsDrift || drift > s.maxTsDrift {
+		s.recordAgentReject(p.Router, "stale_payload")
 		writeError(w, http.StatusUnauthorized, "stale_payload",
 			"ts fuera de la ventana de frescura (revisa el reloj del router)")
 		return
@@ -782,6 +808,10 @@ type agentListItem struct {
 	// swapping/restarting/failed) con su marca de tiempo. null si no hay
 	// actividad reciente (#284: progreso en vivo para la UI).
 	Upgrade *agentUpgradeInfo `json:"upgrade,omitempty"`
+	// RejectedReason: motivo del último 401 (#2211): unauthorized,
+	// invalid_signature o stale_payload. Con RejectedAt, la UI puede decir
+	// qué mirar (token, versión del agente o reloj) en vez de solo "rechazado".
+	RejectedReason string `json:"rejectedReason,omitempty"`
 	// Kind: "native" (agente netpulse-agent) o "external" (pusher externo
 	// tipo scraper de switch gestionado, #285/#288). Default "native".
 	Kind string `json:"kind"`
@@ -896,6 +926,18 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 			}
 			rrows.Close()
 		}
+		// #2211: el motivo del rechazo, en su propia consulta por la misma
+		// razón que los routers (una sola conexión).
+		rejectReasons := map[string]string{}
+		if qrows, qerr := s.db.Query("SELECT key, value FROM kv WHERE key LIKE ?", agentRejectReasonKeyPrefix+"%"); qerr == nil {
+			for qrows.Next() {
+				var k, v string
+				if qrows.Scan(&k, &v) == nil {
+					rejectReasons[strings.TrimPrefix(k, agentRejectReasonKeyPrefix)] = v
+				}
+			}
+			qrows.Close()
+		}
 		rows, err := s.db.Query("SELECT key FROM kv WHERE key LIKE ? ORDER BY key", agentTokenKeyPrefix+"%")
 		if err == nil {
 			defer rows.Close()
@@ -928,6 +970,7 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 					_, item.Fresh = s.agents.Fresh(slug)
 				}
 				item.RejectedAt = rejects[slug]
+				item.RejectedReason = rejectReasons[slug]
 				if payload != nil {
 					item.PanelPort = payload.PanelPort
 				}
@@ -1065,7 +1108,7 @@ func (s *server) forgetAgent(slug string) (tokenRevoked bool) {
 			tokenRevoked = true
 		}
 	}
-	_, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentRejectKey(slug))
+	s.clearAgentReject(slug)
 	if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", agentStateKey(slug)); err != nil {
 		log.Printf("[netpulse] warning: could not purge agent state for %s: %v", slug, err)
 	}
@@ -1568,8 +1611,8 @@ func (s *server) acceptAgentPush(p *probe.Payload) bool {
 			key, strconv.FormatInt(p.Ts, 10)); err != nil {
 			log.Printf("[netpulse] could not persist last push from %s: %v", p.Router, err)
 		}
-		// #1717: el primer push válido limpia el badge de rechazos.
-		_, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentRejectKey(p.Router))
+		// #1717: el primer push válido limpia el badge de rechazos y su motivo.
+		s.clearAgentReject(p.Router)
 	}
 	return true
 }

+ 125 - 0
server-go/internal/httpapi/agent_reject_reason_2211_test.go

@@ -0,0 +1,125 @@
+// agent_reject_reason_2211_test.go — #2211: el 401 llevaba solo un
+// timestamp, así que un reloj desfasado (stale_payload) o un agente viejo
+// (invalid_signature) se veían igual que un token muerto. El motivo se guarda
+// al lado del timestamp, se expone en la lista de agentes y el primer push
+// válido limpia los dos.
+package httpapi_test
+
+import (
+	"encoding/json"
+	"io"
+	"net/http"
+	"strings"
+	"testing"
+	"time"
+)
+
+func rejectReasonFor(t *testing.T, ts *agentTestServer, slug string) string {
+	t.Helper()
+	var v string
+	err := ts.db.QueryRow("SELECT value FROM kv WHERE key = 'agent.reject_reason.'||? ", slug).Scan(&v)
+	if err != nil {
+		return ""
+	}
+	return v
+}
+
+func agentsRejectReason(t *testing.T, ts *agentTestServer) (int64, string) {
+	t.Helper()
+	req, _ := http.NewRequest("GET", ts.URL+"/api/agents", nil)
+	req.Header.Set("Cookie", "session="+ts.cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("GET /api/agents: %v", err)
+	}
+	defer res.Body.Close()
+	raw, _ := io.ReadAll(res.Body)
+	var list struct {
+		Agents []struct {
+			Slug           string `json:"slug"`
+			RejectedAt     int64  `json:"rejectedAt"`
+			RejectedReason string `json:"rejectedReason"`
+		} `json:"agents"`
+	}
+	if err := json.Unmarshal(raw, &list); err != nil {
+		t.Fatalf("decode agents: %v (%.120s)", err, raw)
+	}
+	for _, it := range list.Agents {
+		if it.Slug == "patio" {
+			return it.RejectedAt, it.RejectedReason
+		}
+	}
+	return 0, ""
+}
+
+func TestIngestRejectReasonPerCause(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	status, token, _ := createAgentToken(t, ts, "patio")
+	if status != 201 || token == "" {
+		t.Fatalf("create: %d", status)
+	}
+
+	cases := []struct {
+		name string
+		do   func()
+		want string
+	}{
+		{
+			name: "token que no cuadra",
+			do: func() {
+				res := ingest(t, ts, "deadbeef", "10.9.1.1", validPayload())
+				res.Body.Close()
+			},
+			want: "unauthorized",
+		},
+		{
+			name: "firma que no cuadra",
+			do: func() {
+				req, _ := http.NewRequest("POST", ts.URL+"/api/ingest/agent", strings.NewReader(validPayload()))
+				req.Header.Set("Content-Type", "application/json")
+				req.Header.Set("X-Forwarded-For", "10.9.1.2")
+				req.Header.Set("Authorization", "Bearer "+token)
+				req.Header.Set("X-Agent-Signature", "caffee")
+				res, err := http.DefaultClient.Do(req)
+				if err != nil {
+					t.Fatalf("firma mala: %v", err)
+				}
+				res.Body.Close()
+			},
+			want: "invalid_signature",
+		},
+		{
+			name: "payload fuera de la ventana de frescura",
+			do: func() {
+				old := time.Now().Add(-10 * time.Minute).Unix()
+				res := ingest(t, ts, token, "10.9.1.3", validPayload(old))
+				res.Body.Close()
+			},
+			want: "stale_payload",
+		},
+	}
+
+	for _, tc := range cases {
+		tc.do()
+		if got := rejectReasonFor(t, ts, "patio"); got != tc.want {
+			t.Fatalf("%s: motivo guardado %q, quería %q", tc.name, got, tc.want)
+		}
+		at, reason := agentsRejectReason(t, ts)
+		if at == 0 || reason != tc.want {
+			t.Fatalf("%s: la lista expone rejectedAt=%d rejectedReason=%q", tc.name, at, reason)
+		}
+	}
+
+	// El primer push válido limpia timestamp y motivo.
+	res := ingest(t, ts, token, "10.9.1.4", validPayload())
+	res.Body.Close()
+	if res.StatusCode != 202 {
+		t.Fatalf("push válido: %d", res.StatusCode)
+	}
+	if got := rejectReasonFor(t, ts, "patio"); got != "" {
+		t.Fatalf("el motivo debe borrarse con un push válido, queda %q", got)
+	}
+	if at, reason := agentsRejectReason(t, ts); at != 0 || reason != "" {
+		t.Fatalf("rejectedAt=%d rejectedReason=%q tras push válido", at, reason)
+	}
+}