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

fix(routerstore): store the bare host of an external unit (#1968) (#1969)

Nacho 3 недель назад
Родитель
Сommit
648c69c61b

+ 3 - 0
server-go/cmd/netpulse/main.go

@@ -288,6 +288,9 @@ func run() error {
 		log.Printf("[netpulse] warning: could not generate SSH key: %v", err)
 	}
 	// Bootstrap de routers: tabla vacía → ROUTERS_JSON o autodetección
+	if n := routerstore.NormalizeExternalHosts(dbHandle.DB); n > 0 {
+		log.Printf("[netpulse] normalized the host of %d external units (#1968)", n)
+	}
 	routers := routerstore.EnsureInitialRouters(dbHandle.DB, cfg)
 
 	// Adapter: DEMO_MODE=1 → demo (dataset canónico + random walk);

+ 73 - 0
server-go/internal/routerstore/bare_host.go

@@ -0,0 +1,73 @@
+package routerstore
+
+import (
+	"database/sql"
+	"log"
+	"net"
+	"regexp"
+	"strings"
+)
+
+// bareHostRe is the contract the unit form applies to a host
+// (httpapi.validateHost): an IP or a hostname, never a URL.
+var bareHostRe = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
+
+// BareHost reduces the host typed in an integration form to the address of a
+// router unit. The integration keeps the full URL because the pusher needs it,
+// but the unit only accepts an IP or a hostname: the unit form rejects a scheme
+// and the ping probe cannot resolve one (#1968). When the address is not
+// usable, the input comes back untouched, so an odd value keeps failing where
+// it already failed instead of turning into something else.
+func BareHost(raw string) string {
+	h := strings.TrimSpace(raw)
+	if i := strings.Index(h, "://"); i >= 0 {
+		h = h[i+3:]
+	}
+	if i := strings.LastIndex(h, "@"); i >= 0 {
+		h = h[i+1:]
+	}
+	if i := strings.IndexAny(h, "/?#"); i >= 0 {
+		h = h[:i]
+	}
+	if host, _, err := net.SplitHostPort(h); err == nil {
+		h = host
+	}
+	h = strings.Trim(h, "[]")
+	if h == "" || !bareHostRe.MatchString(h) {
+		return strings.TrimSpace(raw)
+	}
+	return h
+}
+
+// NormalizeExternalHosts rewrites the host of the external units created before
+// #1968, which stored the integration URL and could not be edited afterwards.
+// It returns how many rows changed and is safe to run on every start.
+func NormalizeExternalHosts(db *sql.DB) int {
+	rows, err := db.Query(`SELECT id, host FROM routers WHERE type = 'external' AND host LIKE '%://%'`)
+	if err != nil {
+		log.Printf("[netpulse] warning: could not read the host of external routers: %v", err)
+		return 0
+	}
+	type pending struct {
+		id   string
+		host string
+	}
+	var fixes []pending
+	for rows.Next() {
+		var p pending
+		if err := rows.Scan(&p.id, &p.host); err != nil {
+			continue
+		}
+		if bare := BareHost(p.host); bare != p.host {
+			p.host = bare
+			fixes = append(fixes, p)
+		}
+	}
+	rows.Close()
+	for _, f := range fixes {
+		if _, err := db.Exec(`UPDATE routers SET host = ? WHERE id = ?`, f.host, f.id); err != nil {
+			log.Printf("[netpulse] warning: could not normalize the host of %s: %v", f.id, err)
+		}
+	}
+	return len(fixes)
+}

+ 91 - 0
server-go/internal/routerstore/bare_host_1968_test.go

@@ -0,0 +1,91 @@
+package routerstore
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// #1968: the integration form asks for the full URL, but the unit only accepts
+// an IP or a hostname. The address is taken out of the URL and anything that
+// does not end up being a valid host is returned untouched.
+func TestBareHostFromIntegrationForm(t *testing.T) {
+	cases := []struct{ in, want string }{
+		{"https://192.168.1.1", "192.168.1.1"},
+		{"https://fw.mandor.lan", "fw.mandor.lan"},
+		{"https://192.168.1.1:8443", "192.168.1.1"},
+		{"http://opnsense.local/", "opnsense.local"},
+		{"https://user:pass@fw.local:8443/ui", "fw.local"},
+		{"192.168.1.1", "192.168.1.1"},
+		{"  fw.local  ", "fw.local"},
+		{"fw.local:8443", "fw.local"},
+		{"", ""},
+		// IPv6 does not fit the form contract (it rejects ':'), so it keeps the
+		// original value instead of becoming something the form still rejects.
+		{"https://[2001:db8::1]:443", "https://[2001:db8::1]:443"},
+		{"https:///path", "https:///path"},
+	}
+	for _, c := range cases {
+		if got := BareHost(c.in); got != c.want {
+			t.Errorf("BareHost(%q) = %q, want %q", c.in, got, c.want)
+		}
+	}
+}
+
+func TestAddRouterStoresTheBareHost(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	cfg, err := AddRouter(d.DB, AddInput{Name: "opnsense", Host: "https://192.168.1.1:8443", Type: "external", AgentOnly: true})
+	if err != nil {
+		t.Fatalf("add: %v", err)
+	}
+	if cfg.Host != "192.168.1.1" {
+		t.Fatalf("host de la unidad = %q, esperaba 192.168.1.1", cfg.Host)
+	}
+	listed := ListRouters(d.DB)
+	if len(listed) != 1 || listed[0].Host != "192.168.1.1" {
+		t.Fatalf("ListRouters devolvio %+v", listed)
+	}
+}
+
+func TestNormalizeExternalHostsFixesExistingRows(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	cfg, err := AddRouter(d.DB, AddInput{Name: "fw", Host: "192.168.1.1", Type: "external", AgentOnly: true})
+	if err != nil {
+		t.Fatalf("add: %v", err)
+	}
+	// Fila tal como la dejaba el alta anterior al arreglo.
+	if _, err := d.DB.Exec(`UPDATE routers SET host = ? WHERE id = ?`, "https://192.168.1.1:8443", cfg.ID); err != nil {
+		t.Fatalf("seed legacy row: %v", err)
+	}
+	if n := NormalizeExternalHosts(d.DB); n != 1 {
+		t.Fatalf("normalizadas = %d, esperaba 1", n)
+	}
+	if got := ListRouters(d.DB)[0].Host; got != "192.168.1.1" {
+		t.Fatalf("host tras normalizar = %q", got)
+	}
+	if n := NormalizeExternalHosts(d.DB); n != 0 {
+		t.Fatalf("segunda pasada cambio %d filas, no es idempotente", n)
+	}
+
+	// Una unidad que no es external no se toca: su host lo valida el formulario.
+	local, err := AddRouter(d.DB, AddInput{Name: "rt1", Host: "192.168.1.2", Type: "openwrt"})
+	if err != nil {
+		t.Fatalf("add local: %v", err)
+	}
+	if _, err := d.DB.Exec(`UPDATE routers SET host = ? WHERE id = ?`, "https://192.168.1.2", local.ID); err != nil {
+		t.Fatalf("seed local row: %v", err)
+	}
+	if n := NormalizeExternalHosts(d.DB); n != 0 {
+		t.Fatalf("normalizo %d unidades que no son external", n)
+	}
+}

+ 4 - 0
server-go/internal/routerstore/routerstore.go

@@ -173,6 +173,10 @@ func AddRouter(db *sql.DB, in AddInput) (adapters.RouterConfig, error) {
 	if in.Type == "" {
 		in.Type = "openwrt"
 	}
+	// #1968: una unidad guarda un host, no una URL. Las integraciones pasan el
+	// host tal cual se teclea (https://host) y la unidad quedaba sin poder
+	// editarse ni sondearse.
+	in.Host = BareHost(in.Host)
 	id := uniqueId(db, in.Name, in.Host)
 	now := time.Now().UnixMilli()
 	name := in.Name