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

feat(backups): take a config backup over ssh when there is no agent (#1899) (#1911)

* feat(backups): take a config backup over ssh when there is no agent (#1899)

* docs(changelog): cover the ssh config backup (#1899)
Nacho 4 недель назад
Родитель
Сommit
25c174b40b

+ 2 - 0
CHANGELOG.md

@@ -8,6 +8,8 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 ## [Unreleased]
 
 ### Added
+- A configuration backup no longer needs an agent on the unit (#1899). The button only rendered for a unit with an agent, so a router managed over plain SSH had no way to keep a copy of its config even though the server can already reach it. The server now builds the archive itself with `sysupgrade --create-backup`, brings it back base64 encoded over the SSH channel, always removes the temporary file on the unit, whose /tmp is RAM, and stores it where the agent backups already live, so one list and one download serve both kinds. A unit that does have an agent still prefers the event stream and only falls back to SSH when the agent is not connected.
+
 
 - Reinstalling an agent now shows what the install script actually said (#1894). The handler discarded the script output with `_`, so the operator got a red "exit status 1" that vanished after eight seconds and the server journal had nothing at all. The output is captured and returned with the response, on failure and on success, it is written to the server journal either way, and the UI shows it in a collapsible frame under the message. A failed reinstall no longer hides itself: the error stays until the next attempt, so it can be read, copied and attached to a report.
 

+ 24 - 3
app/src/components/routers/AgentBackupButton.tsx

@@ -11,6 +11,8 @@ interface AgentBackupButtonProps {
   /** id del router: el resultado se confirma viendo aparecer la entrada en
    *  GET /api/firmware-backups/{routerId}. */
   routerId?: string
+  /** #1899: permite la copia por SSH en una unidad OpenWrt sin agente. */
+  allowSsh?: boolean
   className?: string
 }
 
@@ -34,9 +36,9 @@ const BACKUP_WAIT_S = 45
  *   not_connected → 409, agente sin SSE (a diferencia del upgrade no se encola)
  *   fail          → petición fallida (red, 4xx/5xx)
  */
-export function AgentBackupButton({ agent, routerId, className }: AgentBackupButtonProps) {
+export function AgentBackupButton({ agent, routerId, allowSsh = false, className }: AgentBackupButtonProps) {
   const { t } = useTranslation()
-  const { backupAgent } = useNetPulse()
+  const { backupAgent, backupRouterSsh } = useNetPulse()
   const auth = useAuth()
   const [state, setState] = useState<BackupState>('idle')
   const [clickTs, setClickTs] = useState(0)
@@ -83,7 +85,8 @@ export function AgentBackupButton({ agent, routerId, className }: AgentBackupBut
   }, [state, routerId, clickTs])
 
   if (auth?.role !== 'admin') return null
-  if (!agent || !routerId) return null
+  // #1899: sin agente el boton solo existe si la unidad puede por SSH.
+  if (!routerId || (!agent && !allowSsh)) return null
 
   const label =
     state === 'busy' ? t('routers.agent.backupSent')
@@ -100,10 +103,28 @@ export function AgentBackupButton({ agent, routerId, className }: AgentBackupBut
       onClick={async () => {
         if (state === 'busy' || state === 'waiting') return
         setState('busy')
+        // #1899: la via SSH guarda la copia en el servidor antes de responder,
+        // asi que el sondeo de abajo la encuentra en el primer tick.
+        const viaSsh = async (id: string) => {
+          const res = await backupRouterSsh(id)
+          if (res?.ok) {
+            setClickTs(Date.now())
+            setState('waiting')
+          } else {
+            setState('fail')
+            toIdle(6000)
+          }
+        }
+        if (!agent) {
+          if (allowSsh) await viaSsh(routerId)
+          return
+        }
         const res = await backupAgent(agent.slug)
         if (res === 'sent') {
           setClickTs(Date.now())
           setState('waiting')
+        } else if (res === 'not_connected' && allowSsh) {
+          await viaSsh(routerId)
         } else if (res === 'not_connected') {
           setState('not_connected')
           toIdle(6000)

+ 5 - 2
app/src/components/routers/RouterDetailHeader.tsx

@@ -21,6 +21,9 @@ export function RouterDetailHeader({ router }: { router: Router }) {
   const isGateway = router.roleBadge === 'Principal'
   const osLabel = osBadge(router.type)
   const agent = useAgentFor(router.id)
+  // #1899: la copia de config tambien existe en una unidad OpenWrt sin agente
+  // (la hace el servidor por SSH), asi que el boton no depende del agente.
+  const canSshBackup = !router.type || router.type === 'openwrt'
   // #1136: el chip AdGuard solo tiene sentido con AdGuard configurado; sin
   // host era un adorno fijo en la cabecera del gateway.
   const { adguard } = useNetPulse()
@@ -121,13 +124,13 @@ export function RouterDetailHeader({ router }: { router: Router }) {
                   <AgentUpgradeButton agent={agent} />
                 </motion.span>
               )}
-              {agent && (
+              {(agent || canSshBackup) && (
                 <motion.span
                   initial={reduce ? false : { opacity: 0, scale: 0.9 }}
                   animate={{ opacity: 1, scale: 1 }}
                   transition={{ duration: 0.2, delay: 0.15 + (pills.length + 3) * 0.06 }}
                 >
-                  <AgentBackupButton agent={agent} routerId={router.id} />
+                  <AgentBackupButton agent={agent} routerId={router.id} allowSsh={canSshBackup} />
                 </motion.span>
               )}
             </div>

+ 23 - 1
app/src/data/DataProvider.tsx

@@ -225,6 +225,8 @@ export interface NetPulseApi extends NetPulseData {
    * imperativo). null si la petición falló (demo siempre null).
    */
   backupAgent: (slug: string) => Promise<'sent' | 'not_connected' | null>
+  /** #1899: copia de config por SSH en una unidad OpenWrt sin agente. */
+  backupRouterSsh: (routerId: string) => Promise<{ ok: boolean; error?: string } | null>
   /**
    * #251: POST /api/agents/upgrade-all — envía el upgrade a todos los agentes
    * con versión desactualizada. Devuelve el resumen por slug; null si falló.
@@ -1235,6 +1237,25 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     }
   }, [])
 
+  // #1899: la copia la hace el propio servidor por SSH (sysupgrade
+  // --create-backup + base64) y la guarda donde la UI ya lista backups, asi
+  // que la entrada aparece en el mismo sitio que las del agente.
+  const backupRouterSsh = useCallback(async (routerId: string): Promise<{ ok: boolean; error?: string } | null> => {
+    if (modeRef.current !== 'live') return null
+    try {
+      const res = await fetch(`/api/firmware-backups/${encodeURIComponent(routerId)}`, {
+        method: 'POST',
+        signal: AbortSignal.timeout(150_000),
+      })
+      if (res.status === 401) redirectLogin()
+      const body = (await res.json().catch(() => ({}))) as { error?: string; message?: string }
+      if (!res.ok) return { ok: false, error: body?.message ?? body?.error ?? `HTTP ${res.status}` }
+      return { ok: true }
+    } catch (e) {
+      return { ok: false, error: String(e) }
+    }
+  }, [])
+
   const upgradeAllAgents = useCallback(async (): Promise<{ sent: number; total: number; message: string; agents: { slug: string; status: string }[] } | null> => {    if (modeRef.current !== 'live') return null
     try {
       const res = await fetch('/api/agents/upgrade-all', {
@@ -1447,13 +1468,14 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       rearmAgent,
       upgradeAgent,
       backupAgent,
+      backupRouterSsh,
       upgradeAllAgents,
       reinstallAgent,
       uninstallAgent,
       removeAgent,
       createAgentInstall,
     }),
-    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, clearAllAlerts, silenceAlert, approveImpostorBssid, setPeerUrgent, dismissAlert, rearmAgent, upgradeAgent, backupAgent, upgradeAllAgents, reinstallAgent, uninstallAgent, removeAgent, createAgentInstall],
+    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, clearAllAlerts, silenceAlert, approveImpostorBssid, setPeerUrgent, dismissAlert, rearmAgent, upgradeAgent, backupAgent, upgradeAllAgents, backupRouterSsh, reinstallAgent, uninstallAgent, removeAgent, createAgentInstall],
   )
 
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>

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

@@ -1312,7 +1312,7 @@ export default function FirmwareUpgrades() {
               )}
 
               <div className="mt-3 flex justify-end">
-                <AgentBackupButton agent={findAgentFor(agents, item.routerId)} routerId={item.routerId} />
+                <AgentBackupButton agent={findAgentFor(agents, item.routerId)} routerId={item.routerId} allowSsh />
               </div>
 
               <details

+ 1 - 0
server-go/internal/httpapi/firmware.go

@@ -59,6 +59,7 @@ func (s *server) registerFirmwareRoutes(mux *http.ServeMux) {
 	s.registerFirmwareOwutRoutes(mux)
 	// Método por unidad + imagen subida desde local (#1414).
 	s.registerFirmwareUploadRoutes(mux)
+	s.registerFirmwareBackupSshRoutes(mux) // #1899
 	// Backups de config en el server (#1414).
 	s.registerFirmwareBackupRoutes(mux)
 	// Disponibilidad real de releases (#1444): lista cacheada, chequeo

+ 115 - 0
server-go/internal/httpapi/firmware_backup_ssh.go

@@ -0,0 +1,115 @@
+package httpapi
+
+// #1899: copia de config en unidades OpenWrt que NO tienen agente (solo SSH).
+// Hasta aquí el botón "Backup config" pedía al agente un sysupgrade -b por SSE
+// y el agente subía el tar.gz; una unidad solo SSH no tenía camino. El server
+// ya sabe hablar con esa unidad por SSH, así que el backup lo hace él y lo
+// guarda en el mismo almacén que lista y descarga la UI.
+
+import (
+	"context"
+	"encoding/base64"
+	"errors"
+	"net/http"
+	"os"
+	"path/filepath"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+)
+
+// sshConfigBackupCmd crea el tar.gz con sysupgrade, lo vuelca en base64 (el
+// canal SSH del pool devuelve texto y un tar.gz crudo no sobreviviría) y borra
+// el temporal SIEMPRE: en el router /tmp es tmpfs, o sea RAM (#1897).
+const sshConfigBackupCmd = `tmp=/tmp/netpulse-config-backup-$$.tar.gz
+sysupgrade --create-backup "$tmp" >/dev/null 2>&1 && base64 "$tmp"
+rc=$?
+rm -f "$tmp"
+exit $rc`
+
+// sshConfigBackupTimeout: sysupgrade empaqueta /etc y puede tardar en unidades
+// lentas; el agente tiene un presupuesto parecido en su flujo.
+const sshConfigBackupTimeout = 120 * time.Second
+
+// configBackupSshCapable: mismo criterio que la página de firmware: OpenWrt
+// vanilla. Un managed-switch o un external SNMP no tienen sysupgrade.
+func configBackupSshCapable(rows []adapters.RouterConfig, id string) bool {
+	for _, rc := range rows {
+		if rc.ID == id {
+			return rc.Type == "" || rc.Type == "openwrt"
+		}
+	}
+	return false
+}
+
+// decodeSshBackup: base64 con saltos de línea de busybox -> bytes del tar.gz.
+func decodeSshBackup(out string) ([]byte, error) {
+	clean := strings.Map(func(r rune) rune {
+		if r == '\n' || r == '\r' || r == ' ' || r == '\t' {
+			return -1
+		}
+		return r
+	}, out)
+	if clean == "" {
+		return nil, errors.New("la unidad no devolvió ningún backup")
+	}
+	data, err := base64.StdEncoding.DecodeString(clean)
+	if err != nil {
+		return nil, errors.New("la salida de la unidad no es un backup válido")
+	}
+	return data, nil
+}
+
+func (s *server) registerFirmwareBackupSshRoutes(mux *http.ServeMux) {
+	mux.Handle("POST /api/firmware-backups/{routerId}", auth.RequireAdmin(http.HandlerFunc(s.handleFirmwareBackupSsh)))
+}
+
+func (s *server) handleFirmwareBackupSsh(w http.ResponseWriter, r *http.Request) {
+	id := r.PathValue("routerId")
+	if s.db == nil || s.pool == nil {
+		writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
+		return
+	}
+	if !configBackupSshCapable(routerstore.ListRouters(s.db.DB), id) {
+		writeError(w, http.StatusUnprocessableEntity, "not_openwrt",
+			"esta unidad no es un OpenWrt gestionable por SSH: su copia se hace con su propio mecanismo")
+		return
+	}
+	host := s.hostOfRouter(id)
+	if host == "" {
+		writeError(w, http.StatusNotFound, "not_found", "no hay router con ese id")
+		return
+	}
+	out, err := s.pool.Run(host, sshConfigBackupCmd, sshConfigBackupTimeout)
+	if err != nil {
+		writeJSON(w, http.StatusBadGateway, map[string]any{
+			"error": "ssh_backup_failed", "message": err.Error(),
+		})
+		return
+	}
+	data, err := decodeSshBackup(out)
+	if err != nil {
+		writeError(w, http.StatusBadGateway, "backup_invalid", err.Error())
+		return
+	}
+	if len(data) > maxFirmwareUpload {
+		writeError(w, http.StatusRequestEntityTooLarge, "backup_too_large", "backup mayor del tope")
+		return
+	}
+	dir := s.firmwareBackupDir()
+	if err := ensureBackupDir(dir); err != nil {
+		writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
+		return
+	}
+	name := s.firmwareBackupName(context.Background(), id)
+	dest := filepath.Join(dir, name)
+	if err := os.WriteFile(dest, data, backupFileMode); err != nil {
+		writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
+		return
+	}
+	pruneFirmwareBackups(dir, id)
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true, "name": name, "size": len(data)})
+}

+ 110 - 0
server-go/internal/httpapi/firmware_backup_ssh_1899_test.go

@@ -0,0 +1,110 @@
+package httpapi
+
+// #1899: copia de config por SSH en unidades sin agente.
+
+import (
+	"encoding/base64"
+	"encoding/json"
+	"net/http/httptest"
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+)
+
+type sshBackupFakePool struct {
+	out string
+	err error
+	cmd string
+}
+
+func (p *sshBackupFakePool) Run(host, cmd string, timeout time.Duration) (string, error) {
+	p.cmd = cmd
+	return p.out, p.err
+}
+
+func makeSshBackupServer(t *testing.T, typ string, payload string) (*server, string, *sshBackupFakePool) {
+	t.Helper()
+	dataDir := t.TempDir()
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
+		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
+	}, dataDir)
+	if err != nil {
+		t.Fatalf("config: %v", err)
+	}
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	r, err := routerstore.AddRouter(d.DB, routerstore.AddInput{
+		Name: "SshUnit", Host: "192.168.1.61", Type: typ,
+	})
+	if err != nil {
+		t.Fatalf("add router: %v", err)
+	}
+	pool := &sshBackupFakePool{out: payload}
+	return &server{cfg: cfg, db: d, pool: pool}, r.ID, pool
+}
+
+func TestSshConfigBackupStoresTheArchive(t *testing.T) {
+	// base64 con saltos de línea, como lo emite busybox en el router.
+	raw := "TAR-GZ-DE-PRUEBA"
+	payload := base64.StdEncoding.EncodeToString([]byte(raw))
+	payload = payload[:4] + "\n" + payload[4:] + "\n"
+	s, id, pool := makeSshBackupServer(t, "openwrt", payload)
+	req := httptest.NewRequest("POST", "/api/firmware-backups/"+id, nil)
+	req.SetPathValue("routerId", id)
+	rec := httptest.NewRecorder()
+	s.handleFirmwareBackupSsh(rec, req)
+	if rec.Code != 200 {
+		t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String())
+	}
+	var body struct {
+		Name string `json:"name"`
+		Size int    `json:"size"`
+	}
+	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+		t.Fatalf("json: %v", err)
+	}
+	if body.Size != len(raw) {
+		t.Fatalf("size = %d, body %s", body.Size, rec.Body.String())
+	}
+	data, err := os.ReadFile(filepath.Join(s.firmwareBackupDir(), body.Name))
+	if err != nil {
+		t.Fatalf("el backup no quedó guardado: %v", err)
+	}
+	if string(data) != raw {
+		t.Fatalf("contenido = %q", data)
+	}
+	// El temporal del router se borra siempre: /tmp allí es RAM (#1897).
+	if !strings.Contains(pool.cmd, "rm -f") || !strings.Contains(pool.cmd, "sysupgrade --create-backup") {
+		t.Fatalf("comando inesperado: %s", pool.cmd)
+	}
+}
+
+func TestSshConfigBackupRejectsNonOpenwrt(t *testing.T) {
+	s, id, _ := makeSshBackupServer(t, "managed-switch", "")
+	req := httptest.NewRequest("POST", "/api/firmware-backups/"+id, nil)
+	req.SetPathValue("routerId", id)
+	rec := httptest.NewRecorder()
+	s.handleFirmwareBackupSsh(rec, req)
+	if rec.Code != 422 {
+		t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String())
+	}
+}
+
+func TestDecodeSshBackupRejectsGarbage(t *testing.T) {
+	if _, err := decodeSshBackup("   \n"); err == nil {
+		t.Fatal("salida vacía aceptada")
+	}
+	if _, err := decodeSshBackup("esto no es base64!!!"); err == nil {
+		t.Fatal("base64 inválido aceptado")
+	}
+}