Răsfoiți Sursa

feat: rejected-token badge on agents and offline reason on integration rows (#1719)

* feat(agents): badge pushes rejected with an invalid token (#1717)

* feat(integrations): show the classified offline reason on each row (#1718)
Nacho 1 lună în urmă
părinte
comite
38012b668f

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

@@ -1309,7 +1309,9 @@
       "kindExternal": "External",
       "netgripTip": "The agent lives inside this router's NetGrip panel",
       "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."
+      "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."
     },
     "upgradeUpdatedDetail": "Updated · {{count}} steps · {{secs}} s",
     "noVitals": "No system metrics",

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

@@ -1309,7 +1309,9 @@
       "kindExternal": "Externo",
       "netgripTip": "El agente vive dentro del panel NetGrip de este router",
       "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."
+      "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."
     },
     "upgradeUpdatedDetail": "Actualizado · {{count}} pasos · {{secs}} s",
     "noVitals": "Sin métricas de sistema",

+ 28 - 15
app/src/components/routers/AgentsSection.tsx

@@ -232,22 +232,35 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
         </div>
       </td>
       <td className="py-3 pr-3">
-        {agent ? (
-          <span
-            title={agent.fresh ? t('routers.agent.freshTip', { version: agent.version }) : t('routers.agent.staleTip')}
-            className="inline-flex items-center gap-1.5 text-caption font-semibold"
-          >
-            <span className={cn('h-1.5 w-1.5 rounded-full', agent.fresh ? 'bg-ok' : 'bg-danger')} aria-hidden="true" />
-            <span className={agent.fresh ? 'text-ok' : 'text-danger'}>
-              {agent.fresh ? t('routers.agents.active') : t('routers.agents.inactive')}
+        <div className="flex flex-wrap items-center gap-2">
+          {agent ? (
+            <span
+              title={agent.fresh ? t('routers.agent.freshTip', { version: agent.version }) : t('routers.agent.staleTip')}
+              className="inline-flex items-center gap-1.5 text-caption font-semibold"
+            >
+              <span className={cn('h-1.5 w-1.5 rounded-full', agent.fresh ? 'bg-ok' : 'bg-danger')} aria-hidden="true" />
+              <span className={agent.fresh ? 'text-ok' : 'text-danger'}>
+                {agent.fresh ? t('routers.agents.active') : t('routers.agents.inactive')}
+              </span>
             </span>
-          </span>
-        ) : (
-          <span title={t('routers.agent.notInstalledTip')} className="inline-flex items-center gap-1.5 text-caption font-semibold text-danger">
-            <span className="h-1.5 w-1.5 rounded-full bg-danger" aria-hidden="true" />
-            {t('routers.agents.notInstalled')}
-          </span>
-        )}
+          ) : (
+            <span title={t('routers.agent.notInstalledTip')} className="inline-flex items-center gap-1.5 text-caption font-semibold text-danger">
+              <span className="h-1.5 w-1.5 rounded-full bg-danger" aria-hidden="true" />
+              {t('routers.agents.notInstalled')}
+            </span>
+          )}
+          {/* #1717: el servidor está rechazando sus pushes con 401 (token
+              viejo tras un reinicio o un cambio de servidor). El primer push
+              válido lo limpia, así que desaparece solo al Rearmar/Reinstalar. */}
+          {agent?.rejectedAt ? (
+            <span
+              title={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')}
+            </span>
+          ) : null}
+        </div>
       </td>
       <td className="py-3 pr-3">
         {agent ? (

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

@@ -605,6 +605,12 @@ export interface AgentInfo {
    *  reporta su agente. Ausente = no lo reporta (agente antiguo). */
   panelPort?: number
   fresh: boolean
+  /**
+   * Unix SEGUNDOS del último push rechazado por autenticación (401, #1717).
+   * Ausente/0 = sin rechazos pendientes: el primer push válido lo limpia, así
+   * que el badge desaparece solo al recuperar el token (Rearm/Reinstall).
+   */
+  rejectedAt?: number
   /**
    * 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.

+ 2 - 0
app/src/lib/integrationsApi.ts

@@ -15,6 +15,8 @@ export interface Integration {
   enabled: boolean
   state: string
   lastError: string
+  /** Código estable del motivo offline (#1718): vacío si empuja o está pausada. */
+  offlineReason?: string
   lastStartMs: number
   lastPushMs: number
   fresh: boolean

+ 11 - 0
app/src/pages/Integrations.tsx

@@ -638,6 +638,17 @@ export default function Integrations() {
                     {t('integrations.meta.lastPush')}: {agoLabel(it.lastPushMs)}
                   </span>
                 </div>
+                {/* #1718: motivo offline clasificado (mismos códigos que la
+                    tarjeta y el detalle). El tooltip lleva el error crudo del
+                    pusher para quien quiera el detalle técnico. */}
+                {it.offlineReason && (
+                  <div
+                    title={it.lastError || undefined}
+                    className="mt-1.5 text-caption text-danger"
+                  >
+                    {t(`routers.statusReason.${it.offlineReason}`, { defaultValue: it.offlineReason })}
+                  </div>
+                )}
                 {editing?.slug === it.slug && (
                   <form onSubmit={(e) => void submitEdit(e)} className="mt-3 border-t border-border pt-3">
                     <div className="text-label uppercase text-text-muted">{t('integrations.edit.title')}</div>

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

@@ -49,6 +49,11 @@ const (
 	ingestRateWindow = time.Minute
 	// agentTokenKeyPrefix: kv agent.token.<slug> = sha256 hex del token.
 	agentTokenKeyPrefix = "agent.token."
+	// agentRejectKeyPrefix: kv agent.reject_ts.<slug> = unix del último push
+	// rechazado por autenticación (#1717). Se limpia con el primer push
+	// 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."
 	// 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
@@ -118,6 +123,21 @@ func (l *ipRateLimit) allow(ip string) (bool, int) {
 
 func agentTokenKey(slug string) string { return agentTokenKeyPrefix + slug }
 
+func agentRejectKey(slug string) string { return agentRejectKeyPrefix + 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) {
+	if s.db == nil {
+		return
+	}
+	_, _ = s.db.Exec(
+		`INSERT INTO kv (key, value) VALUES (?, ?)
+		 ON CONFLICT(key) DO UPDATE SET value=excluded.value`,
+		agentRejectKey(slug), strconv.FormatInt(time.Now().Unix(), 10))
+}
+
 // hashAgentToken: sha256 hex del token (lo único que se persiste).
 func hashAgentToken(token string) string {
 	sum := sha256.Sum256([]byte(token))
@@ -231,12 +251,17 @@ func (s *server) handleIngestAgent(w http.ResponseWriter, r *http.Request) {
 	// 401: Bearer inválido para ese slug
 	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)
 		writeError(w, http.StatusUnauthorized, "unauthorized")
 		return
 	}
 	// 401: HMAC-SHA256 del payload no coincide (R4: firma obligatoria)
 	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)
 		writeError(w, http.StatusUnauthorized, "invalid_signature", err.Error())
 		return
 	}
@@ -556,6 +581,11 @@ type agentListItem struct {
 	// Kind: "native" (agente netpulse-agent) o "external" (pusher externo
 	// tipo scraper de switch gestionado, #285/#288). Default "native".
 	Kind string `json:"kind"`
+	// RejectedAt: unix del último push rechazado por autenticación (401,
+	// #1717). 0/ausente = sin rechazos pendientes; el primer push válido lo
+	// limpia, así que el badge de la UI desaparece solo al recuperar el token
+	// (Rearm/Reinstall).
+	RejectedAt int64 `json:"rejectedAt,omitempty"`
 	// Interval: cadencia de push declarada en segundos (solo externos, #288).
 	Interval int `json:"interval,omitempty"`
 	// PanelPort: the port the router's own panel answers on, as the agent
@@ -634,6 +664,21 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 		}
 	}
 	if s.db != nil {
+		// #1717: rechazos precargados en su propia consulta y ANTES de abrir
+		// el cursor de tokens (con SetMaxOpenConns(1) dos rows abiertos a la
+		// vez hacen deadlock, misma razón del preload de routers de arriba).
+		rejects := map[string]int64{}
+		if rrows, rerr := s.db.Query("SELECT key, value FROM kv WHERE key LIKE ?", agentRejectKeyPrefix+"%"); rerr == nil {
+			for rrows.Next() {
+				var k, v string
+				if rrows.Scan(&k, &v) == nil {
+					if sec, perr := strconv.ParseInt(v, 10, 64); perr == nil {
+						rejects[strings.TrimPrefix(k, agentRejectKeyPrefix)] = sec
+					}
+				}
+			}
+			rrows.Close()
+		}
 		rows, err := s.db.Query("SELECT key FROM kv WHERE key LIKE ? ORDER BY key", agentTokenKeyPrefix+"%")
 		if err == nil {
 			defer rows.Close()
@@ -665,6 +710,7 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 					}
 					_, item.Fresh = s.agents.Fresh(slug)
 				}
+				item.RejectedAt = rejects[slug]
 				if payload != nil {
 					item.PanelPort = payload.PanelPort
 				}
@@ -780,6 +826,8 @@ func (s *server) handleAgentsDelete(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusNotFound, "not_found")
 		return
 	}
+	// #1717: el badge de rechazos no debe sobrevivir al agente.
+	_, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentRejectKey(slug))
 	if s.agents != nil {
 		s.agents.Forget(slug)
 	}
@@ -1230,6 +1278,8 @@ func (s *server) acceptAgentPush(p *probe.Payload) bool {
 			key, strconv.FormatInt(p.Ts, 10)); err != nil {
 			log.Printf("[netpulse] no se pudo persistir el ultimo push de %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))
 	}
 	return true
 }

+ 118 - 0
server-go/internal/httpapi/agent_reject_test.go

@@ -0,0 +1,118 @@
+package httpapi_test
+
+import (
+	"encoding/json"
+	"net/http"
+	"strings"
+	"testing"
+)
+
+// TestIngestRechazoBadgeYLimpiame (#1717): un push con token invalido deja
+// huella (badge en GET /api/agents) y el primer push valido la limpia.
+func TestIngestRechazoBadgeYLimpieza(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	status, token, _ := createAgentToken(t, ts, "patio")
+	if status != 201 || token == "" {
+		t.Fatalf("create: %d", status)
+	}
+
+	// Push con token incorrecto -> 401 y kv agent.reject_ts.patio.
+	res := ingest(t, ts, "deadbeef", "10.9.0.1", validPayload())
+	res.Body.Close()
+	if res.StatusCode != 401 {
+		t.Fatalf("token malo: %d", res.StatusCode)
+	}
+	var rej string
+	if err := ts.db.QueryRow("SELECT value FROM kv WHERE key = 'agent.reject_ts.patio'").Scan(&rej); err != nil {
+		t.Fatalf("kv de rechazo no creado: %v", err)
+	}
+	if rej == "" || rej == "0" {
+		t.Fatalf("kv de rechazo vacío: %q", rej)
+	}
+
+	// La lista de agentes lo expone como rejectedAt.
+	var list1 struct {
+		Agents []struct {
+			Slug       string `json:"slug"`
+			RejectedAt int64  `json:"rejectedAt"`
+		} `json:"agents"`
+	}
+	getAgents := func() (int, []byte) {
+		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()
+		body := new(strings.Builder)
+		buf := make([]byte, 32*1024)
+		for {
+			n, rerr := res.Body.Read(buf)
+			body.Write(buf[:n])
+			if rerr != nil {
+				break
+			}
+		}
+		return res.StatusCode, []byte(body.String())
+	}
+	st, raw := getAgents()
+	if st != 200 {
+		t.Fatalf("GET /api/agents: %d", st)
+	}
+	if err := json.Unmarshal(raw, &list1); err != nil {
+		t.Fatalf("decode agents: %v (%.120s)", err, raw)
+	}
+	found := int64(0)
+	for _, it := range list1.Agents {
+		if it.Slug == "patio" {
+			found = it.RejectedAt
+		}
+	}
+	if found == 0 {
+		t.Fatalf("GET /api/agents no expone rejectedAt para patio")
+	}
+
+	// Firma invalida (token valido, HMAC mal) tambien deja huella.
+	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.0.2")
+	req.Header.Set("Authorization", "Bearer "+token)
+	req.Header.Set("X-Agent-Signature", "caffee")
+	res2, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("ingest firma mala: %v", err)
+	}
+	res2.Body.Close()
+	if res2.StatusCode != 401 {
+		t.Fatalf("firma mala: %d", res2.StatusCode)
+	}
+
+	// Push valido -> 202, kv limpio y rejectedAt fuera de la lista.
+	res3 := ingest(t, ts, token, "10.9.0.3", validPayload())
+	res3.Body.Close()
+	if res3.StatusCode != 202 {
+		t.Fatalf("push válido: %d", res3.StatusCode)
+	}
+	if err := ts.db.QueryRow("SELECT value FROM kv WHERE key = 'agent.reject_ts.patio'").Scan(&rej); err == nil {
+		t.Fatalf("kv de rechazo debería haberse limpiado, queda %q", rej)
+	}
+	st2, raw2 := getAgents()
+	if st2 != 200 {
+		t.Fatalf("GET /api/agents (2): %d", st2)
+	}
+	var list2 struct {
+		Agents []struct {
+			Slug       string `json:"slug"`
+			RejectedAt int64  `json:"rejectedAt"`
+		} `json:"agents"`
+	}
+	if err := json.Unmarshal(raw2, &list2); err != nil {
+		t.Fatalf("decode agents 2: %v (%.120s)", err, raw2)
+	}
+	for _, it := range list2.Agents {
+		if it.Slug == "patio" && it.RejectedAt != 0 {
+			t.Fatalf("rejectedAt debería ser 0 tras un push válido: %d", it.RejectedAt)
+		}
+	}
+}

+ 46 - 14
server-go/internal/httpapi/integrations.go

@@ -25,20 +25,24 @@ import (
 
 // integrationItem es la vista HTTP de una integración (nunca la contraseña).
 type integrationItem struct {
-	Slug        string `json:"slug"`
-	Vendor      string `json:"vendor"`
-	Mode        string `json:"mode"`
-	Host        string `json:"host"`
-	Username    string `json:"username"`
-	Version     string `json:"version"`
-	Arch        string `json:"arch"`
-	IntervalS   int    `json:"intervalS"`
-	Enabled     bool   `json:"enabled"`
-	State       string `json:"state"`
-	LastError   string `json:"lastError"`
-	LastStartMs int64  `json:"lastStartMs"`
-	LastPushMs  int64  `json:"lastPushMs"`
-	Fresh       bool   `json:"fresh"`
+	Slug      string `json:"slug"`
+	Vendor    string `json:"vendor"`
+	Mode      string `json:"mode"`
+	Host      string `json:"host"`
+	Username  string `json:"username"`
+	Version   string `json:"version"`
+	Arch      string `json:"arch"`
+	IntervalS int    `json:"intervalS"`
+	Enabled   bool   `json:"enabled"`
+	State     string `json:"state"`
+	LastError string `json:"lastError"`
+	// OfflineReason (#1718): código estable del motivo por el que la unidad
+	// no está empujando (mismos códigos que la tarjeta y el detalle desde
+	// #1714). Vacío si está empujando, pausada o sin señal clara.
+	OfflineReason string `json:"offlineReason,omitempty"`
+	LastStartMs   int64  `json:"lastStartMs"`
+	LastPushMs    int64  `json:"lastPushMs"`
+	Fresh         bool   `json:"fresh"`
 }
 
 // vendorView es la vista HTTP del manifiesto de un vendor.
@@ -161,7 +165,35 @@ func (s *server) integrationItemOf(row rintegration.Row) integrationItem {
 		IntervalS: row.IntervalS, Enabled: row.Enabled, State: state,
 		LastError: row.LastError, LastStartMs: row.LastStartMs,
 		LastPushMs: lastPush, Fresh: fresh,
+		OfflineReason: s.integrationOfflineReason(row, fresh),
+	}
+}
+
+// integrationOfflineReason (#1718) clasifica por qué una integración no está
+// empujando, con los mismos códigos y la misma precedencia que StatusReasons
+// en el paquete rintegration (que alimenta la tarjeta y el detalle): parada
+// explícita, último error de instalación, o el log del pusher para fallos de
+// poll. Pausada o fresca no tienen motivo.
+func (s *server) integrationOfflineReason(row rintegration.Row, fresh bool) string {
+	if !row.Enabled {
+		return ""
+	}
+	if row.State == "stopped" {
+		return rintegration.ReasonStopped
+	}
+	if fresh {
+		return ""
+	}
+	code := ""
+	if row.State == "error" && row.LastError != "" {
+		code = rintegration.ClassifyPollError(row.LastError)
+	}
+	if (code == "" || code == rintegration.ReasonError) && s.integrations != nil {
+		if msg := s.integrations.LastPollError(row.Slug); msg != "" {
+			code = rintegration.ClassifyPollError(msg)
+		}
 	}
+	return code
 }
 
 func (s *server) integrationList() []integrationItem {

+ 96 - 0
server-go/internal/httpapi/integrations_reason_test.go

@@ -0,0 +1,96 @@
+package httpapi_test
+
+import (
+	"os"
+	"path/filepath"
+	"strconv"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/rintegration"
+)
+
+// TestIntegrationsOfflineReasonEnFilas (#1718): la lista de integraciones
+// lleva el motivo offline clasificado con los mismos códigos que la tarjeta
+// y el detalle (#1714). Fresca o pausada no llevan motivo.
+func TestIntegrationsOfflineReasonEnFilas(t *testing.T) {
+	ts, mgr := makeIntegrationsTestServer(t)
+	store := rintegration.NewStore(ts.db.DB)
+	now := time.Now().Unix()
+
+	// Fresca: empujó hace 10 s con intervalo 45 → sin motivo.
+	fresh := bootIntegrationRow("fresh-push", "routeros", "local", true, "running")
+	if err := store.Upsert(fresh); err != nil {
+		t.Fatal(err)
+	}
+	// Stale (running huérfano): push viejo, sin errores → sin señal clara.
+	stale := bootIntegrationRow("stale-noerr", "routeros", "local", true, "running")
+	if err := store.Upsert(stale); err != nil {
+		t.Fatal(err)
+	}
+	// Error de instalación con credenciales rechazadas en LastError.
+	errRow := bootIntegrationRow("err-401", "routeros", "local", true, "error")
+	errRow.LastError = `exit status 1: 401 Unauthorized: invalid user name or password (rosapi)`
+	if err := store.Upsert(errRow); err != nil {
+		t.Fatal(err)
+	}
+	// Stale cuyo último fallo de poll (log del pusher) es endpoint ausente.
+	logRow := bootIntegrationRow("log-404", "routeros", "local", true, "running")
+	if err := store.Upsert(logRow); err != nil {
+		t.Fatal(err)
+	}
+	logBody := `time=2026-10-31T12:00:00+01:00 level=ERROR msg="routeros-pusher: collection failed" err="404 Not Found: no REST API"`
+	if err := os.MkdirAll(mgr.Dir(), 0o755); err != nil {
+		t.Fatalf("mkdir: %v", err)
+	}
+	if err := os.WriteFile(filepath.Join(mgr.Dir(), "log-404.log"), []byte(logBody), 0o600); err != nil {
+		t.Fatalf("log: %v", err)
+	}
+	// Parada intencional → pusher_stopped.
+	stopped := bootIntegrationRow("stopped", "routeros", "local", true, "stopped")
+	if err := store.Upsert(stopped); err != nil {
+		t.Fatal(err)
+	}
+	// Pausada: aunque tenga error, la UI ya la pinta como pausa.
+	paused := bootIntegrationRow("paused", "routeros", "local", false, "error")
+	paused.LastError = "anything"
+	if err := store.Upsert(paused); err != nil {
+		t.Fatal(err)
+	}
+
+	for _, slug := range []string{"fresh-push", "stale-noerr", "err-401", "log-404", "stopped", "paused"} {
+		if slug == "fresh-push" {
+			continue
+		}
+		sec := now - 200
+		if slug == "stopped" || slug == "paused" {
+			sec = now - 10 // el estado manda antes que la frescura solo en stopped; paused se corta por enabled
+		}
+		if _, err := ts.db.Exec(
+			"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+			"agent.last_push_ts."+slug, strconv.FormatInt(sec, 10),
+		); err != nil {
+			t.Fatal(err)
+		}
+	}
+
+	items := integrationsBySlug(t, ts)
+	want := map[string]string{
+		"fresh-push":  "",
+		"stale-noerr": "",
+		"err-401":     rintegration.ReasonAuthFailed,
+		"log-404":     rintegration.ReasonAPINotFound,
+		"stopped":     rintegration.ReasonStopped,
+		"paused":      "",
+	}
+	for slug, code := range want {
+		it := items[slug]
+		if it == nil {
+			t.Fatalf("%s no está en la lista", slug)
+		}
+		got, _ := it["offlineReason"].(string)
+		if got != code {
+			t.Fatalf("%s: offlineReason = %q, want %q (item: %v)", slug, got, code, it)
+		}
+	}
+}