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

fix(firmware): pass removePackages to owut download and refuse install without image (#1769) (#1770)

Nacho 1 месяц назад
Родитель
Сommit
62d014d5a4

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

@@ -2539,6 +2539,7 @@
     "tipInstallOwut": "Installs the owut package (attended sysupgrade) on the unit via SSH",
     "tipOwutDownload": "Builds and downloads the image on the unit with owut, without flashing, to review it before installing",
     "tipOwutInstallImage": "Installs the image downloaded in the previous step on the unit",
+    "tipOwutInstallNeedsDownload": "Download the image first: Install image flashes the file produced by Download image",
     "tipUpgradeOwut": "Flashes the target version now with owut (keeping current packages)",
     "tipSchedule": "Schedule the upgrade for later or recurring",
     "tipSave": "Saves model and target for the classic flow (URL/image)",

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

@@ -2539,6 +2539,7 @@
     "tipInstallOwut": "Instala el paquete owut (attended sysupgrade) en la unidad por SSH",
     "tipOwutDownload": "Construye y descarga la imagen en la unidad con owut, sin flashear, para revisarla antes de instalar",
     "tipOwutInstallImage": "Instala en la unidad la imagen descargada en el paso anterior",
+    "tipOwutInstallNeedsDownload": "Descarga antes la imagen: Instalar imagen flashea el fichero que produce Descargar imagen",
     "tipUpgradeOwut": "Flashea ahora la versión de destino con owut (con los paquetes actuales)",
     "tipSchedule": "Programa la actualización para más tarde o de forma recurrente",
     "tipSave": "Guarda modelo y target para el flujo clásico (URL/imagen)",

+ 31 - 5
app/src/pages/FirmwareUpgrades.tsx

@@ -145,6 +145,9 @@ export default function FirmwareUpgrades() {
   // #1414: pasos owut por pasos (download) y subida de imagen local.
   const [owutDlBusy, setOwutDlBusy] = useState<Record<string, boolean>>({})
   const [owutDlOutput, setOwutDlOutput] = useState<Record<string, string>>({})
+  // #1769: la imagen solo puede flashearse tras un download exitoso de esta
+  // sesión (el server además pre-comprueba /tmp/firmware.bin por SSH).
+  const [owutDlOk, setOwutDlOk] = useState<Record<string, boolean>>({})
   const [uploadBusy, setUploadBusy] = useState<Record<string, boolean>>({})
   const [uploadInfo, setUploadInfo] = useState<Record<string, { name: string; size: number; checksum: string }>>({})
   // #1414: SHA256 de referencia introducido por el admin para contrastarlo
@@ -308,6 +311,11 @@ export default function FirmwareUpgrades() {
   }, [anyActive])
 
   const updateEdit = (id: string, patch: Partial<FirmwareItem>) => {
+    if (patch.targetVersion !== undefined) {
+      // #1769: la imagen descargada corresponde al target con el que se
+      // generó; al cambiar el target hay que volver a descargar.
+      setOwutDlOk((prev) => ({ ...prev, [id]: false }))
+    }
     setEdits((prev) => ({ ...prev, [id]: { ...prev[id], ...patch } }))
   }
 
@@ -518,19 +526,25 @@ export default function FirmwareUpgrades() {
 
   // #1414: paso intermedio del flujo owut por pasos: construye y descarga la
   // imagen en el router SIN flashear, para revisar antes de instalar.
-  const runOwutDownload = async (id: string) => {
+  // #1769: acepta la lista de paquetes a excluir (owut -r), la misma que el
+  // upgrade one-shot; sin ella ASU rechaza routers con paquetes de terceros.
+  const runOwutDownload = async (id: string, missing: string[] = []) => {
     const e = edits[id]
     setOwutDlBusy((prev) => ({ ...prev, [id]: true }))
+    setOwutDlOk((prev) => ({ ...prev, [id]: false }))
     setError('')
     try {
+      const stored = (removePkgs[id] ?? '').trim()
+      const removePackages = stored ? stored.split(/[\s,]+/).filter(Boolean) : missing
       const res = await fetch(`/api/firmware-upgrades/${encodeURIComponent(id)}/owut-download`, {
         method: 'POST',
         headers: { 'Content-Type': 'application/json' },
-        body: JSON.stringify({ targetVersion: e?.targetVersion ?? '' }),
+        body: JSON.stringify({ targetVersion: e?.targetVersion ?? '', removePackages }),
       })
       const body = await res.json().catch(() => ({}))
       if (!res.ok) throw new Error(body?.error?.message ?? body?.message ?? `HTTP ${res.status}`)
       setOwutDlOutput((prev) => ({ ...prev, [id]: String(body.output ?? '') }))
+      setOwutDlOk((prev) => ({ ...prev, [id]: true }))
     } catch (err) {
       setError(String(err))
     } finally {
@@ -1216,7 +1230,15 @@ export default function FirmwareUpgrades() {
                           <>
                             <button
                               type="button"
-                              onClick={() => void runOwutDownload(item.routerId)}
+                              onClick={() => {
+                                // #1769: mismos paquetes a excluir que el
+                                // one-shot, prerrellenados desde el check.
+                                const missing = owut?.missingPkgs ?? []
+                                if (missing.length && !(removePkgs[item.routerId] ?? '').trim()) {
+                                  setRemovePkgs((prev) => ({ ...prev, [item.routerId]: missing.join(' ') }))
+                                }
+                                void runOwutDownload(item.routerId, missing)
+                              }}
                               disabled={owutDlBusy[item.routerId] || !!active}
                               title={t('firmwareUpgrades.tipOwutDownload')}
                               className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-4 text-sm font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
@@ -1227,8 +1249,12 @@ export default function FirmwareUpgrades() {
                             <button
                               type="button"
                               onClick={() => void runOwutInstallImage(item.routerId)}
-                              disabled={!!active || busy[item.routerId] === 'upgrade' || scheduled}
-                              title={t('firmwareUpgrades.tipOwutInstallImage')}
+                              disabled={!!active || busy[item.routerId] === 'upgrade' || scheduled || !owutDlOk[item.routerId]}
+                              title={
+                                owutDlOk[item.routerId]
+                                  ? t('firmwareUpgrades.tipOwutInstallImage')
+                                  : t('firmwareUpgrades.tipOwutInstallNeedsDownload')
+                              }
                               className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-4 text-sm font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
                             >
                               <Rocket className="h-4 w-4" strokeWidth={1.75} />

+ 26 - 2
server-go/internal/firmware/owut_flow.go

@@ -218,12 +218,18 @@ const owutDownloadTimeout = 10 * time.Minute
 // OwutDownloadCmd construye `owut download` (paso intermedio del flujo por
 // pasos de #1414): construye la imagen en ASU y la descarga al router SIN
 // flashear, para que el admin la revise antes de `owut install`. Sin -q a
-// propósito: la salida completa es la revisión.
-func OwutDownloadCmd(target, current string) string {
+// propósito: la salida completa es la revisión. removePkgs excluye paquetes
+// locales sin feed oficial (owut "-r"), igual que OwutUpgradeCmd: sin eso
+// ASU se niega a construir la imagen si el router lleva paquetes de terceros
+// (#1769).
+func OwutDownloadCmd(target, current string, removePkgs []string) string {
 	cmd := "owut download"
 	if target != "" && current != "" && target != current {
 		cmd += " -V " + shQuote(target)
 	}
+	if pkgs := sanitizeRemovePkgs(removePkgs); pkgs != "" {
+		cmd += " -r " + shQuote(pkgs)
+	}
 	return cmd
 }
 
@@ -242,6 +248,24 @@ func RunOwutDownload(runner Runner, host, cmd string) (int, string, error) {
 // upgrade; el resultado se confirma por el board info tras el reboot).
 func OwutInstallCmd() string { return "owut install" }
 
+// owutImageCheckCmd: `owut download` deja la imagen en /tmp/firmware.bin
+// (su ruta por defecto para download/verify/install) y `owut install` la
+// espera ahí. Comprobarla antes de lanzar el flash evita el error crudo de
+// sysupgrade cuando no hay nada descargado (#1769).
+const owutImageCheckCmd = "test -s /tmp/firmware.bin"
+
+// HasOwutDownloadedImage informa de si el router tiene una imagen descargada
+// lista para `owut install`. Tolerante: runner o host vacíos → false. Un
+// fallo de transporte también cuenta como "no hay imagen": sin confirmación
+// no se flashea.
+func HasOwutDownloadedImage(runner Runner, host string) bool {
+	if runner == nil || host == "" {
+		return false
+	}
+	_, err := runner.Run(host, owutImageCheckCmd, owutDetectTimeout)
+	return err == nil
+}
+
 // Platform es la foto de plataforma de un router: si tiene owut y si lleva
 // firmware de fabricante. Vendor != "" significa firmware compilado por el
 // vendor con su propia gestión de actualizaciones (GL.iNet): NetPulse NO

+ 37 - 0
server-go/internal/firmware/owut_flow_test.go

@@ -131,6 +131,43 @@ func TestOwutUpgradeCmd(t *testing.T) {
 	}
 }
 
+// #1769: el download del flujo por pasos acepta la misma lista de
+// exclusiones que el one-shot; sin -r, ASU rechaza routers con paquetes
+// de terceros (p. ej. netgrip) y el paso final no tiene imagen.
+func TestOwutDownloadCmdRemovePkgs(t *testing.T) {
+	if got := OwutDownloadCmd("25.12.6", "25.12.5", nil); got != "owut download -V '25.12.6'" {
+		t.Fatalf("salto de versión sin exclusiones: %q", got)
+	}
+	if got := OwutDownloadCmd("25.12.5", "25.12.5", nil); got != "owut download" {
+		t.Fatalf("rebuild sin exclusiones: %q", got)
+	}
+	if got := OwutDownloadCmd("25.12.5", "25.12.5", []string{"netgrip"}); got != "owut download -r 'netgrip'" {
+		t.Fatalf("exclusión de paquete local: %q", got)
+	}
+	if got := OwutDownloadCmd("25.12.6", "25.12.5", []string{"bad pkg!", "netgrip", "x"}); got != "owut download -V '25.12.6' -r 'netgrip x'" {
+		t.Fatalf("nombres hostiles se filtran: %q", got)
+	}
+}
+
+// #1769: el pre-check de imagen antes de flashear. Tolerante: sin runner o
+// sin host no hay imagen, y un fallo de transporte tampoco confirma.
+func TestHasOwutDownloadedImage(t *testing.T) {
+	if HasOwutDownloadedImage(nil, "h") {
+		t.Fatal("runner nil debe dar false")
+	}
+	f := &fakeSSHRunner{}
+	if !HasOwutDownloadedImage(f, "h") {
+		t.Fatalf("test -s ok debe dar true; comando: %q", f.got)
+	}
+	if f.got != "test -s /tmp/firmware.bin" {
+		t.Fatalf("comando de chequeo: %q", f.got)
+	}
+	fail := &fakeSSHRunner{err: errors.New("exit 1")}
+	if HasOwutDownloadedImage(fail, "h") {
+		t.Fatal("sin imagen debe dar false")
+	}
+}
+
 func TestRunOwutUpgradeParsesExit(t *testing.T) {
 	f := &fakeSSHRunner{out: "There are no changes to upgrade\n__owut_exit__=0\n"}
 	exit, out, err := RunOwutUpgrade(f, "h", OwutUpgradeCmd("25.12.5", "25.12.5", nil))

+ 16 - 3
server-go/internal/httpapi/firmware_owut.go

@@ -197,12 +197,13 @@ func (s *server) registerFirmwareOwutRoutes(mux *http.ServeMux) {
 			return
 		}
 		var body struct {
-			TargetVersion string `json:"targetVersion"`
+			TargetVersion string   `json:"targetVersion"`
+			RemovePkgs    []string `json:"removePackages"`
 		}
 		if st := readJSONBody(w, r, &body); st != 0 {
 			return
 		}
-		cmd := firmware.OwutDownloadCmd(body.TargetVersion, s.detectedFirmwareVersion(id))
+		cmd := firmware.OwutDownloadCmd(body.TargetVersion, s.detectedFirmwareVersion(id), body.RemovePkgs)
 		exit, out, err := firmware.RunOwutDownload(s.pool, host, cmd)
 		if err != nil || exit != 0 {
 			msg := owutTail(out, err)
@@ -240,6 +241,13 @@ func (s *server) registerFirmwareOwutRoutes(mux *http.ServeMux) {
 				"owut no está instalado en el router: instálalo primero con el botón Instalar owut.")
 			return
 		}
+		// #1769: sin imagen descargada no se entra en la máquina de estados:
+		// el error crudo de sysupgrade no dice al admin qué hacer.
+		if !firmware.HasOwutDownloadedImage(s.pool, host) {
+			writeError(w, http.StatusPreconditionFailed, "owut_no_image",
+				"No hay imagen descargada en el router: ejecuta antes Descargar imagen (owut download) y revisa su salida.")
+			return
+		}
 		target := ""
 		if t, _ := s.firmware.GetTarget(id); t != nil {
 			target = t.TargetVersion
@@ -388,7 +396,12 @@ func (s *server) runOwutInstallImage(id int64, routerID, host, target string) {
 		if strings.TrimSpace(msg) == "" {
 			msg = fmt.Sprintf("owut install falló (exit %d)", exit)
 		}
-		log.Printf("[firmware] owut install %s falló (exit %d): %s", routerID, exit, msg)
+		// #1769: si el fallo es "no hay imagen", el detalle debe decir qué
+		// hacer, no repetir el error de sysupgrade.
+		if strings.Contains(out, "Image file") && strings.Contains(out, "does not exist") {
+			msg = "No hay imagen descargada en el router: ejecuta antes Descargar imagen (owut download) y revisa su salida."
+		}
+		log.Printf("[firmware] owut install %s falló (exit %d): %s", routerID, exit, owutTail(out, err))
 		_ = s.firmware.SetStatus(id, "failed", msg, "")
 		s.emitFirmwareResult(routerID, from, target, "manual", false, msg)
 	}

+ 57 - 0
server-go/internal/httpapi/firmware_owut_test.go

@@ -4,6 +4,7 @@ package httpapi_test
 
 import (
 	"bytes"
+	"errors"
 	"fmt"
 	"io"
 	"net/http"
@@ -211,6 +212,62 @@ func TestOwutUpgradeRequiresTarget(t *testing.T) {
 	}
 }
 
+// #1769: el download del flujo por pasos propaga removePackages a owut -r,
+// igual que el one-shot; sin eso ASU rechaza routers con paquetes de
+// terceros y el paso final se queda sin imagen.
+func TestOwutDownloadEndpointPassesRemovePackages(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{contains: "command -v owut", out: "__owut__\n"},
+		{contains: "owut download", out: "Downloading image to /tmp/firmware.bin\n__owut_exit__=0\n"},
+	}}
+	ts, rid := makeOwutTestServer(t, ssh)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-download",
+		`{"targetVersion":"25.12.6","removePackages":["netgrip"]}`, cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != 200 {
+		t.Fatalf("status %d: %v", res.StatusCode, body)
+	}
+	if !ssh.saw("owut download -r 'netgrip'") {
+		t.Fatalf("comando lanzado: %v", ssh.cmdsSnapshot())
+	}
+}
+
+// #1769: instalar sin imagen previa no entra en la máquina de estados:
+// 422 con código accionable y ningún upgrade creado.
+func TestOwutInstallImageRequiresDownloadedImage(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{contains: "command -v owut", out: "__owut__\n"},
+		{contains: "test -s /tmp/firmware.bin", err: errors.New("exit 1")},
+	}}
+	ts, rid := makeOwutTestServer(t, ssh)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-install-image", `{}`, cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != http.StatusPreconditionFailed {
+		t.Fatalf("status %d: %v", res.StatusCode, body)
+	}
+	errObj, _ := body["error"].(string)
+	if errObj != "owut_no_image" {
+		t.Fatalf("error: %v", body)
+	}
+	deadline := time.Now().Add(2 * time.Second)
+	for time.Now().Before(deadline) {
+		res := getJSONPath(t, ts.URL, "/api/firmware-upgrades", cookie)
+		for _, it := range readJSONArray(t, res) {
+			m, _ := it.(map[string]any)
+			if m["routerId"] == rid {
+				if up, ok := m["upgrade"].(map[string]any); ok {
+					t.Fatalf("no debió crearse ningún upgrade: %v", up)
+				}
+			}
+		}
+		time.Sleep(50 * time.Millisecond)
+	}
+}
+
 func TestRecurrencePutGetDelete(t *testing.T) {
 	ts, rid := makeOwutTestServer(t, nil)
 	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")