4
0
Эх сурвалжийг харах

fix(integrations): ship the server SPKI pin in the pusher env (#1685)

NetPulse serves a self-signed certificate issued for 127.0.0.1, so an
external pusher that relies on standard x509 hostname verification cannot
ingest against a LAN address no matter how valid its token is. The native
agent avoids this by pinning the server SPKI, and reinstall already
derives that value for the agent env (#851 / #870). Reuse it for the
pusher env the app generates, in both modes: local (on-server process)
and ssh (installed on the router, where the same public URL is what the
pusher dials).

Since #13 in netpulse-integrations a pusher with an https NETPULSE_SERVER
refuses to start without that pin, so an env missing it is not a warning
but a dead process: if the server cannot reach its own public URL at that
moment (hairpin NAT, a firewall rule, a certificate mid renewal), the
create answers 201 and the row flips to state=error a second later, with
a log that names the missing variable instead of the failed dial. Derive
the pin before writing anything and, when it cannot be derived over
https, fail the request with the underlying error and the two ways out:
fix NETPULSE_AGENT_URL, or set NETPULSE_SERVER_FP explicitly. reinstall
keeps its own contract, where the pin is an improvement and not a
requirement, through ServerFP; ServerFPWithError exposes the cause for
the caller that needs it.

Re-deriving a stored pin once a certificate is reissued with a new key
pair is the open question in #1684 and is deliberately not part of this
change.

Co-authored-by: Bann-DEV <bann.dev@gmail.com>
Bann-DEV 1 сар өмнө
parent
commit
ee947f9443

+ 15 - 2
server-go/internal/httpapi/integrations.go

@@ -194,6 +194,16 @@ func (s *server) handleIntegrationsCreate(w http.ResponseWriter, r *http.Request
 		return
 	}
 
+	// El env que se va a escribir tiene que poder arrancar: con la URL en https
+	// el pin dejó de ser opcional (#13 en netpulse-integrations), y derivarlo
+	// exige que este server alcance su propia URL pública. Mejor un 502 aquí,
+	// sin tocar nada, que un alta que muere al segundo siguiente.
+	serverURL := s.agentBaseURL(r)
+	if err := requirePusherPin(serverURL); err != nil {
+		writeError(w, http.StatusBadGateway, "fingerprint_unreachable", err.Error())
+		return
+	}
+
 	// Resolver y descargar el último release verificado. En modo local se
 	// extrae el binario aquí (corre en este host); en modo ssh solo se
 	// verifica: el router descarga el asset él mismo.
@@ -260,7 +270,6 @@ func (s *server) handleIntegrationsCreate(w http.ResponseWriter, r *http.Request
 		_ = store.Delete(body.Slug)
 	}
 
-	serverURL := s.agentBaseURL(r)
 	token, err := s.rotateAgentTokenAtomic(body.Slug, func(tok string) error {
 		env := s.pusherEnv(vendor, row, body.Password, serverURL, tok)
 		if vendor.Mode == "local" {
@@ -303,7 +312,7 @@ func (s *server) pusherEnv(v rintegration.Vendor, row rintegration.Row, password
 	if v.Mode == "ssh" {
 		host = "127.0.0.1"
 	}
-	return map[string]string{
+	env := map[string]string{
 		prefix + "HOST":     host,
 		prefix + "USER":     row.Username,
 		prefix + "PASS":     password,
@@ -313,6 +322,10 @@ func (s *server) pusherEnv(v rintegration.Vendor, row rintegration.Row, password
 		"NETPULSE_SLUG":     row.Slug,
 		"NETPULSE_INTERVAL": strconv.Itoa(row.IntervalS) + "s",
 	}
+	for k, v := range pusherPinEnv(serverURL) {
+		env[k] = v
+	}
+	return env
 }
 
 func (s *server) runSSHInstall(v rintegration.Vendor, row rintegration.Row, env map[string]string, assetURL, sha256 string) error {

+ 66 - 0
server-go/internal/httpapi/integrations_pin.go

@@ -0,0 +1,66 @@
+// integrations_pin.go — el pin SPKI del propio server en el entorno de los
+// pushers externos.
+//
+// Un NetPulse que sirve su certificado generado es válido para 127.0.0.1, así
+// que la verificación x509 por nombre contra una dirección de LAN nunca pasa:
+// un pusher que no pinee nada no puede ingestar, ni siquiera con token válido
+// (#8 en gnacho/netpulse-integrations). El agente nativo resuelve esto con
+// pinning de SPKI; `reinstall.ServerFP` (#851/#870) ya hace ese TLS dial con
+// caché por host para el env del agente, y aquí se reutiliza para el de los
+// pushers en lugar de duplicar el cálculo.
+//
+// Con la URL en http no hace falta ninguna variable. Con https, si el pin no se
+// puede derivar el alta se rechaza en vez de escribir un env imposible: desde #13
+// el pusher se niega a arrancar sin pin, así que escribirlo a medias produce un
+// 201 seguido de un state=error que culpa a la variable ausente y no al fallo de
+// red que lo causó. Ver requirePusherPin.
+package httpapi
+
+import (
+	"errors"
+	"fmt"
+	"strings"
+
+	"github.com/gnacho/netpulse/server-go/internal/reinstall"
+)
+
+// envServerFP es la variable que leen los pushers externos
+// (netpulse-integrations/internal/pusher), con el mismo nombre que usa el
+// agente nativo.
+const envServerFP = "NETPULSE_SERVER_FP"
+
+// serverFPWithError es la puerta inyectable del derivado: los tests de
+// requirePusherPin necesitan un fallo de dial a voluntad, no una red que se
+// caiga.
+var serverFPWithError = reinstall.ServerFPWithError
+
+// pusherPinEnv devuelve la entrada de pin para serverURL, o nil si no aplica.
+func pusherPinEnv(serverURL string) map[string]string {
+	fp, _ := serverFPWithError(serverURL)
+	if fp == "" {
+		return nil
+	}
+	return map[string]string{envServerFP: fp}
+}
+
+// requirePusherPin rechaza un alta cuyo env no podría arrancar. Desde #13 en
+// netpulse-integrations, un pusher con NETPULSE_SERVER en https y sin pin se
+// niega a levantar: si aquí el derivado falla (hairpin NAT, firewall, el server
+// que no alcanza su propia URL pública, un certificado a medio renovar), escribir
+// el env sin la variable da un 201 y un state=error al segundo siguiente, con un
+// log que acusa a la variable que falta y no a la red. La URL http sí puede
+// quedarse sin pin: no hay nada que verificar.
+func requirePusherPin(serverURL string) error {
+	if !strings.HasPrefix(strings.ToLower(serverURL), "https://") {
+		return nil
+	}
+	fp, err := serverFPWithError(serverURL)
+	if fp != "" {
+		return nil
+	}
+	if err == nil {
+		err = errors.New("the TLS peer presented no certificate")
+	}
+	return fmt.Errorf("cannot derive the server fingerprint: %w. "+
+		"Check NETPULSE_AGENT_URL or set %s explicitly", err, envServerFP)
+}

+ 126 - 0
server-go/internal/httpapi/integrations_pin_test.go

@@ -0,0 +1,126 @@
+package httpapi
+
+import (
+	"crypto/sha256"
+	"encoding/hex"
+	"errors"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/reinstall"
+	"github.com/gnacho/netpulse/server-go/internal/rintegration"
+)
+
+func acceptAny(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }
+
+func TestPusherPinEnv(t *testing.T) {
+	tlsSrv := httptest.NewTLSServer(http.HandlerFunc(acceptAny))
+	defer tlsSrv.Close()
+	sum := sha256.Sum256(tlsSrv.Certificate().RawSubjectPublicKeyInfo)
+	want := hex.EncodeToString(sum[:])
+
+	if got := pusherPinEnv(tlsSrv.URL); got[envServerFP] != want {
+		t.Fatalf("https pin = %q, want %q", got[envServerFP], want)
+	}
+
+	plain := httptest.NewServer(http.HandlerFunc(acceptAny))
+	defer plain.Close()
+	if got := pusherPinEnv(plain.URL); got != nil {
+		t.Fatalf("http must not carry a pin, got %v", got)
+	}
+
+	// Sin handshake no hay pin: se omite la variable en lugar de inventarla.
+	if got := pusherPinEnv("https://127.0.0.1:1"); got != nil {
+		t.Fatalf("unreachable https must not carry a pin, got %v", got)
+	}
+}
+
+func TestPusherEnvCarriesServerPin(t *testing.T) {
+	tlsSrv := httptest.NewTLSServer(http.HandlerFunc(acceptAny))
+	defer tlsSrv.Close()
+	plain := httptest.NewServer(http.HandlerFunc(acceptAny))
+	defer plain.Close()
+
+	var s *server // pusherEnv no toca estado del servidor.
+	row := rintegration.Row{Slug: "salon", Host: "192.0.2.10", Username: "admin", IntervalS: 30}
+
+	env := s.pusherEnv(rintegration.Vendor{ID: "asuswrt", Mode: "local"}, row, "pw", tlsSrv.URL, "tok")
+	if env[envServerFP] == "" {
+		t.Fatalf("https server URL must ship %s, env=%v", envServerFP, env)
+	}
+	if env["NETPULSE_SERVER"] != tlsSrv.URL || env["NETPULSE_TOKEN"] != "tok" || env["NETPULSE_SLUG"] != "salon" {
+		t.Fatalf("unexpected env: %v", env)
+	}
+
+	// En modo ssh el pusher corre en el router: el host del vendor cambia, el
+	// pin del server NO (es la misma URL pública la que va a verificar).
+	sshEnv := s.pusherEnv(rintegration.Vendor{ID: "asuswrt", Mode: "ssh"}, row, "pw", tlsSrv.URL, "tok")
+	if sshEnv[envServerFP] != env[envServerFP] {
+		t.Fatalf("ssh env pin = %q, want %q", sshEnv[envServerFP], env[envServerFP])
+	}
+	if sshEnv["ASUSWRT_HOST"] != "127.0.0.1" {
+		t.Fatalf("ssh env host = %q, want 127.0.0.1", sshEnv["ASUSWRT_HOST"])
+	}
+
+	httpEnv := s.pusherEnv(rintegration.Vendor{ID: "asuswrt", Mode: "local"}, row, "pw", plain.URL, "tok")
+	if _, present := httpEnv[envServerFP]; present {
+		t.Fatalf("http server must not ship a pin: %v", httpEnv)
+	}
+}
+
+// stubServerFP sustituye el derivado del pin y lo devuelve al terminar.
+func stubServerFP(t *testing.T, fp string, err error) {
+	t.Helper()
+	orig := serverFPWithError
+	serverFPWithError = func(string) (string, error) { return fp, err }
+	t.Cleanup(func() { serverFPWithError = orig })
+}
+
+// Un https sin pin derivable no puede escribirse: el pusher se negaría a
+// arrancar y el alta mentiría con un 201.
+func TestRequirePusherPinRejectsUndiaableHttps(t *testing.T) {
+	cause := errors.New("dial tcp 203.0.113.10:443: connect: connection refused")
+	stubServerFP(t, "", cause)
+
+	err := requirePusherPin("https://netpulse.example:3443")
+	if err == nil {
+		t.Fatal("https sin pin derivable debe rechazar el alta")
+	}
+	for _, want := range []string{"cannot derive the server fingerprint", cause.Error(), "NETPULSE_AGENT_URL", envServerFP} {
+		if !strings.Contains(err.Error(), want) {
+			t.Errorf("el mensaje debe contener %q; es: %q", want, err)
+		}
+	}
+
+	// El mismo fallo sin causa concreta (handshake que no presenta cert) sigue
+	// siendo un rechazo, no un env incompleto.
+	stubServerFP(t, "", nil)
+	if err := requirePusherPin("https://netpulse.example:3443"); err == nil {
+		t.Fatal("un https sin cert también debe rechazarse")
+	}
+}
+
+func TestRequirePusherPinAllowsWhatCanStart(t *testing.T) {
+	stubServerFP(t, "aabb", nil)
+	if err := requirePusherPin("https://netpulse.example:3443"); err != nil {
+		t.Fatalf("con pin derivable no hay que rechazar: %v", err)
+	}
+
+	// http: no hay nada que verificar, así que la ausencia de pin es el estado
+	// correcto, no un error.
+	if err := requirePusherPin("http://192.168.1.5:3000"); err != nil {
+		t.Fatalf("http no necesita pin: %v", err)
+	}
+
+	// Sin stub: un TLS real del todo debe dar el pin por sí solo.
+	tlsSrv := httptest.NewTLSServer(http.HandlerFunc(acceptAny))
+	defer tlsSrv.Close()
+	restore := serverFPWithError
+	serverFPWithError = reinstall.ServerFPWithError
+	t.Cleanup(func() { serverFPWithError = restore })
+	if err := requirePusherPin(tlsSrv.URL); err != nil {
+		t.Fatalf("pin derivable de un TLS real: %v", err)
+	}
+}

+ 19 - 6
server-go/internal/reinstall/fp.go

@@ -31,6 +31,7 @@ const (
 type fpEntry struct {
 	fp     string
 	err    bool
+	reason error // causa del fallo de dial; solo va con err=true
 	filled time.Time
 }
 
@@ -44,11 +45,23 @@ var (
 // del leaf cert servido en serverURL. Solo para URLs https; para http o si
 // el handshake falla devuelve "" (el script se genera entonces sin FP, el
 // comportamiento previo a #851). Con cache por URL: positivo 24 h, negativo
-// 1 min. Nunca propaga error: el FP es mejora, no requisito del reinstall.
+// 1 min. Nunca propaga error: para el reinstall el FP es mejora, no requisito
+// (quien necesite la causa usa ServerFPWithError).
 func ServerFP(serverURL string) string {
+	fp, _ := ServerFPWithError(serverURL)
+	return fp
+}
+
+// ServerFPWithError es ServerFP devolviendo también la causa del fallo de
+// handshake. El reinstall no la necesita (el pin es mejora, no requisito, y un
+// "" simplemente genera el script sin FP), pero quien SÍ la necesita es el alta
+// de un pusher externo sobre https: ahí un "" silencioso se convierte en un
+// 201 seguido de un proceso que se niega a arrancar. Para URLs http, o
+// malformadas, devuelve ("", nil): no hay pin que derivar, pero tampoco error.
+func ServerFPWithError(serverURL string) (string, error) {
 	u, err := url.Parse(serverURL)
 	if err != nil || !strings.EqualFold(u.Scheme, "https") || u.Host == "" {
-		return ""
+		return "", nil
 	}
 	cacheKey := u.Host
 
@@ -59,9 +72,9 @@ func ServerFP(serverURL string) string {
 			ttl = fpNegativeTTL
 		}
 		if fpNow().Sub(e.filled) < ttl {
-			fp := e.fp
+			fp, reason := e.fp, e.reason
 			fpMu.Unlock()
-			return fp
+			return fp, reason
 		}
 	}
 	fpMu.Unlock()
@@ -69,9 +82,9 @@ func ServerFP(serverURL string) string {
 	fp, dialErr := dialFP(u.Host)
 
 	fpMu.Lock()
-	fpCache[cacheKey] = fpEntry{fp: fp, err: dialErr != nil, filled: fpNow()}
+	fpCache[cacheKey] = fpEntry{fp: fp, err: dialErr != nil, reason: dialErr, filled: fpNow()}
 	fpMu.Unlock()
-	return fp
+	return fp, dialErr
 }
 
 // dialFP hace el TLS dial y calcula el pin. Separada de ServerFP para poder