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

feat(server): add an optional HTTPS listener (#696) (#709)

NetPulse only served plain HTTP, so the UI could not be a secure
context and Chrome refused to install the PWA. An opt-in extra HTTPS
listener now runs alongside the HTTP one (agents and the updater keep
talking HTTP, so the fleet is not broken): with NETPULSE_TLS_CERT and
NETPULSE_TLS_KEY the user certificates are served, otherwise a
self-signed pair is generated in DATA_DIR. The on-box TLS mode is
untouched. A self-signed cert still shows the browser warning, so PWA
install needs trusted certificates.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 месяцев назад
Родитель
Сommit
643e2b6adc

+ 2 - 0
CHANGELOG.md

@@ -9,6 +9,8 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Added
 
+- **HTTPS nativo opcional para el servidor (#696)**: con `NETPULSE_TLS_ENABLED=1` el servidor escucha HTTPS en un puerto adicional (`NETPULSE_TLS_PORT`, por defecto 3443) **sin tocar el HTTP de `PORT`**, de modo que los agentes y el updater siguen hablando por HTTP y solo la UI/PWA pasa a usar HTTPS. Si configuras `NETPULSE_TLS_CERT` y `NETPULSE_TLS_KEY` se cargan esos certificados (HTTPS válido, necesario para instalar la PWA); si no, se genera un certificado autofirmado en `DATA_DIR` al arrancar para que HTTPS esté disponible sin configurar nada, asumiendo el aviso del navegador (un autofirmado no permite instalar la PWA). Sin ACME.
+
 - **El override manual `attach` ya puede colgar un dispositivo de un router o de un puerto concreto (#690)**: el `parent` solo admitía la MAC de otro device, así que no había forma de anclar un equipo a un AP ni a una boca determinada cuando la inferencia no podía saberlo (NAT, VM sin OUI de hipervisor, cliente callado en un switch que reporta todas las MAC en una boca, recableados). Ahora `parent` acepta tres formas: la MAC de un device (como hasta ahora, backwards-compatible), el id de un router, o `routerId:puerto` para fijar la boca exacta. En la UI el input libre de MAC se sustituye por un selector (routers, sus puertos y dispositivos) que conserva la edición de los overrides existentes con `parent` = MAC.
 
 ### Fixed

+ 15 - 0
server-go/.env.example

@@ -46,3 +46,18 @@ GHOST_PORT_ENABLED=0
 # flash). Es configuración, no compilación: el mismo binario sirve para el
 # CT (sin la variable, todo funciona exactamente como hoy).
 NETPULSE_ONBOX=0
+
+# --- HTTPS adicional (#696) ---
+# 1 = servimos también HTTPS en un listener propio (NETPULSE_TLS_PORT),
+# manteniendo el HTTP de PORT intacto (los agentes y el updater siguen
+# hablando HTTP; la UI/PWA puede usar HTTPS sin romper la flota). Opt-in:
+# sin la variable, el arranque es idéntico al actual. El modo on-box ya
+# sirve HTTPS en PORT y no necesita esta variable.
+NETPULSE_TLS_ENABLED=0
+NETPULSE_TLS_PORT=3443
+# Certs del usuario (opcional, ambos o ninguno): se CARGAN tal cual para
+# servir HTTPS válido (p. ej. para instalar la PWA). Si no se configuran,
+# se genera un autofirmado en DATA_DIR/cert.pem + DATA_DIR/key.pem al
+# arrancar (con el aviso del navegador, sin validez de PWA).
+#NETPULSE_TLS_CERT=/ruta/a/fullchain.pem
+#NETPULSE_TLS_KEY=/ruta/a/privkey.pem

+ 66 - 10
server-go/cmd/netpulse/main.go

@@ -33,16 +33,15 @@ import (
 
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/agentbin"
-	"github.com/gnacho/netpulse/server-go/internal/channelplan"
 	"github.com/gnacho/netpulse/server-go/internal/alerts"
 	"github.com/gnacho/netpulse/server-go/internal/apitoken"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/channelplan"
 	"github.com/gnacho/netpulse/server-go/internal/collectorreader"
 	"github.com/gnacho/netpulse/server-go/internal/config"
 	"github.com/gnacho/netpulse/server-go/internal/configbackup"
 	"github.com/gnacho/netpulse/server-go/internal/db"
 	"github.com/gnacho/netpulse/server-go/internal/firmware"
-	"github.com/gnacho/netpulse/server-go/internal/speedtest"
 	"github.com/gnacho/netpulse/server-go/internal/httpapi"
 	"github.com/gnacho/netpulse/server-go/internal/orchestr"
 	"github.com/gnacho/netpulse/server-go/internal/pathanalysis"
@@ -51,6 +50,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/rearmer"
 	"github.com/gnacho/netpulse/server-go/internal/roamevents"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+	"github.com/gnacho/netpulse/server-go/internal/speedtest"
 	"github.com/gnacho/netpulse/server-go/internal/sse"
 	"github.com/gnacho/netpulse/server-go/internal/sshkey"
 	"github.com/gnacho/netpulse/server-go/internal/staticspa"
@@ -104,6 +104,19 @@ func withSSEWriteTimeout(next http.Handler, long time.Duration) http.Handler {
 	})
 }
 
+// newHTTPServer construye un http.Server con los timeouts comunes (issue #210).
+// Compartido entre el listener HTTP de PORT y el listener HTTPS adicional (#696).
+func newHTTPServer(addr string, h http.Handler) *http.Server {
+	return &http.Server{
+		Addr:              addr,
+		Handler:           h,
+		ReadHeaderTimeout: 10 * time.Second,
+		ReadTimeout:       serverReadTimeout,
+		WriteTimeout:      serverWriteTimeout,
+		IdleTimeout:       2 * time.Minute,
+	}
+}
+
 func main() {
 	if err := run(); err != nil {
 		log.Printf("[netpulse] error fatal en arranque: %v", err)
@@ -455,6 +468,40 @@ func run() error {
 		}
 	}
 
+	// #696: listener HTTPS adicional (NETPULSE_TLS_ENABLED=1). El HTTP de PORT
+	// se mantiene intacto (los agentes y el updater siguen hablando HTTP); la
+	// UI/PWA puede usar HTTPS en NETPULSE_TLS_PORT sin romper la flota. Con
+	// certs del usuario (NETPULSE_TLS_CERT/NETPULSE_TLS_KEY) se cargan; si no,
+	// se genera un autofirmado en DATA_DIR.
+	var extraTLSConf *tls.Config
+	if cfg.TLSEnabled {
+		certPath := cfg.TLSCert
+		keyPath := cfg.TLSKey
+		userCerts := certPath != "" && keyPath != ""
+		if !userCerts {
+			certPath = filepath.Join(cfg.DataDir, "cert.pem")
+			keyPath = filepath.Join(cfg.DataDir, "key.pem")
+		}
+		var err2 error
+		var fp string
+		if userCerts {
+			extraTLSConf, _, err2 = tlscert.Load(certPath, keyPath)
+		} else {
+			extraTLSConf, fp, err2 = tlscert.Ensure(certPath, keyPath)
+		}
+		if err2 != nil {
+			return fmt.Errorf("TLS adicional: %w", err2)
+		}
+		origen := "autofirmado"
+		if userCerts {
+			origen = "usuario"
+		} else {
+			log.Printf("[netpulse] TLS autofirmado: %s", certPath)
+			log.Printf("[netpulse] FINGERPRINT SPKI (sha256): %s", fp)
+		}
+		log.Printf("[netpulse] HTTPS adicional en :%d (cert %s: %s)", cfg.TLSPort, origen, certPath)
+	}
+
 	// Speedtest WAN periódico (#511): store + runner + scheduler. Las
 	// alertas de "velocidad por debajo del plan" se emiten por el MISMO
 	// motor del adapter (la lista de eventos es por instancia). Solo en
@@ -522,16 +569,16 @@ func run() error {
 		handler = fpMux
 	}
 
-	srv := &http.Server{
-		Addr:              fmt.Sprintf(":%d", cfg.Port),
-		Handler:           withSSEWriteTimeout(handler, sseWriteTimeout),
-		ReadHeaderTimeout: 10 * time.Second,
-		ReadTimeout:       serverReadTimeout,
-		WriteTimeout:      serverWriteTimeout,
-		IdleTimeout:       2 * time.Minute,
+	srv := newHTTPServer(fmt.Sprintf(":%d", cfg.Port), withSSEWriteTimeout(handler, sseWriteTimeout))
+
+	// Listener HTTPS adicional (#696): mismo handler y timeouts que el HTTP.
+	var tlsSrv *http.Server
+	if extraTLSConf != nil {
+		tlsSrv = newHTTPServer(fmt.Sprintf(":%d", cfg.TLSPort), withSSEWriteTimeout(handler, sseWriteTimeout))
+		tlsSrv.TLSConfig = extraTLSConf
 	}
 
-	errCh := make(chan error, 1)
+	errCh := make(chan error, 2)
 	go func() {
 		scheme := "http"
 		if cfg.Onbox {
@@ -557,6 +604,12 @@ func run() error {
 		}
 	}()
 
+	if tlsSrv != nil {
+		go func() {
+			errCh <- tlsSrv.ListenAndServeTLS("", "")
+		}()
+	}
+
 	sigCh := make(chan os.Signal, 1)
 	signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)
 
@@ -602,6 +655,9 @@ func run() error {
 		ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
 		defer cancel()
 		_ = srv.Shutdown(ctx)
+		if tlsSrv != nil {
+			_ = tlsSrv.Shutdown(ctx)
+		}
 		_ = dbHandle.Close()
 	}
 	return nil

+ 102 - 55
server-go/internal/config/config.go

@@ -42,33 +42,41 @@ type Webhook struct {
 
 // Config es la config normalizada (equivalente al objeto de loadConfig).
 type Config struct {
-	Port            int
-	NodeEnv         string
-	StaticDir       string // resuelta (absoluta)
-	DataDir         string // resuelta (absoluta)
-	SessionSecret   string // "" si falta (autogenerado en kv)
-	AuthUser        string
-	AuthPass        string
-	DemoMode        bool
-	MaxSSEClients   int
-	Routers         []RouterSeed
-	SSHKeyPath      string
-	Adguard         *AdGuard
-	Webhook         *Webhook
-	WGInterface     string
-	CookieSecure    string // "auto" | "always" | "never"
-	TrustProxy      bool   // confiar en X-Forwarded-For/-Proto (detrás de proxy)
-	MaxTsDriftSec   int    // ventana frescura ts agente en s (0 → default 5 min)
-	GithubRepo      string
-	GithubToken     string
-	ServerRoot      string
-	AutoRearm       bool   // NETPULSE_AUTO_REARM=1: supervisor rearma agentes caídos
-	AutoReinstall   bool   // NETPULSE_AUTO_REINSTALL=1: el supervisor escala rearm→reinstall (#457); exige PUBLIC_URL
-	PublicURL       string // NETPULSE_PUBLIC_URL: URL base con la que los routers alcanzan al server (reinstall/self-heal)
-	BeaconListen    string // NETPULSE_BEACON_LISTEN: socket UDP de beacons embebidos (#291); "" = off, p. ej. ":5140"
-	AgentAutoenroll bool   // AGENT_AUTOENROLL=1: el responder UDP entrega token de alta y /pair lo acepta (#367)
-	Onbox           bool   // NETPULSE_ONBOX=1: modo on-box (Fase 9: config UCI, bootstrap AUTH_PASS)
-	GhostPortEnabled bool  // GHOST_PORT_ENABLED=1: activa alertas de ghost port (#419); default false
+	Port             int
+	NodeEnv          string
+	StaticDir        string // resuelta (absoluta)
+	DataDir          string // resuelta (absoluta)
+	SessionSecret    string // "" si falta (autogenerado en kv)
+	AuthUser         string
+	AuthPass         string
+	DemoMode         bool
+	MaxSSEClients    int
+	Routers          []RouterSeed
+	SSHKeyPath       string
+	Adguard          *AdGuard
+	Webhook          *Webhook
+	WGInterface      string
+	CookieSecure     string // "auto" | "always" | "never"
+	TrustProxy       bool   // confiar en X-Forwarded-For/-Proto (detrás de proxy)
+	MaxTsDriftSec    int    // ventana frescura ts agente en s (0 → default 5 min)
+	GithubRepo       string
+	GithubToken      string
+	ServerRoot       string
+	AutoRearm        bool   // NETPULSE_AUTO_REARM=1: supervisor rearma agentes caídos
+	AutoReinstall    bool   // NETPULSE_AUTO_REINSTALL=1: el supervisor escala rearm→reinstall (#457); exige PUBLIC_URL
+	PublicURL        string // NETPULSE_PUBLIC_URL: URL base con la que los routers alcanzan al server (reinstall/self-heal)
+	BeaconListen     string // NETPULSE_BEACON_LISTEN: socket UDP de beacons embebidos (#291); "" = off, p. ej. ":5140"
+	AgentAutoenroll  bool   // AGENT_AUTOENROLL=1: el responder UDP entrega token de alta y /pair lo acepta (#367)
+	Onbox            bool   // NETPULSE_ONBOX=1: modo on-box (Fase 9: config UCI, bootstrap AUTH_PASS)
+	GhostPortEnabled bool   // GHOST_PORT_ENABLED=1: activa alertas de ghost port (#419); default false
+	// NETPULSE_TLS_ENABLED=1: listener HTTPS adicional (puerto NETPULSE_TLS_PORT,
+	// default 3443) junto al HTTP de PORT. Opt-in: sin la variable, arranque
+	// idéntico al actual. El modo on-box ya sirve HTTPS en PORT (Fase 9) y no
+	// necesita esta variable (#696).
+	TLSEnabled bool
+	TLSPort    int
+	TLSCert    string // NETPULSE_TLS_CERT: path del cert del usuario (opcional; junto a TLSKey)
+	TLSKey     string // NETPULSE_TLS_KEY: path de la clave del usuario (opcional; junto a TLSCert)
 	// RTLConsolePass (NETPULSE_RTL_PASS): contraseña web de la consola de
 	// switches RTLPlayground (KP-9000, #639) para el sondeo HTTP de firmware
 	// y uptime. Default "1234" (la que trae el firmware tras flasheo).
@@ -444,6 +452,41 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		}
 	}
 
+	// NETPULSE_TLS_ENABLED: '0'|'1', opcional — HTTPS adicional en un listener
+	// propio (#696). Opt-in explícito: sin la variable, el binario se comporta
+	// exactamente como hoy (solo HTTP en PORT). El modo on-box ya sirve HTTPS
+	// en PORT y no necesita esta variable.
+	tlsEnabled := false
+	if v, ok := env["NETPULSE_TLS_ENABLED"]; ok && v != "" {
+		switch v {
+		case "0":
+		case "1":
+			tlsEnabled = true
+		default:
+			errs.issues = append(errs.issues, issue{"NETPULSE_TLS_ENABLED", "Invalid enum value. Expected '0' | '1'"})
+		}
+	}
+
+	// NETPULSE_TLS_PORT: int 1..65535, default 3443 (solo relevante si TLS
+	// está habilitado).
+	tlsPort := 3443
+	if v, ok := env["NETPULSE_TLS_PORT"]; ok && v != "" {
+		n, err := strconv.Atoi(strings.TrimSpace(v))
+		if err != nil || n < 1 || n > 65535 {
+			errs.issues = append(errs.issues, issue{"NETPULSE_TLS_PORT", "Expected int 1..65535"})
+		} else {
+			tlsPort = n
+		}
+	}
+
+	// NETPULSE_TLS_CERT / NETPULSE_TLS_KEY: paths del cert del usuario. Ambos
+	// o ninguno (fail-fast si solo viene uno).
+	tlsCert := strings.TrimSpace(env["NETPULSE_TLS_CERT"])
+	tlsKey := strings.TrimSpace(env["NETPULSE_TLS_KEY"])
+	if (tlsCert == "") != (tlsKey == "") {
+		errs.issues = append(errs.issues, issue{"NETPULSE_TLS_CERT/NETPULSE_TLS_KEY", "both must be set together"})
+	}
+
 	if len(errs.issues) > 0 {
 		return nil, &errs
 	}
@@ -487,35 +530,39 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 	}
 
 	return &Config{
-		Port:            port,
-		NodeEnv:         nodeEnv,
-		StaticDir:       resolve(staticDir),
-		DataDir:         resolve(dataDir),
-		SessionSecret:   sessionSecret,
-		AuthUser:        authUser,
-		AuthPass:        authPass,
-		DemoMode:        demoMode,
-		MaxSSEClients:   maxSSE,
-		Routers:         routers,
-		SSHKeyPath:      sshKeyPath,
-		Adguard:         adguard,
-		Webhook:         webhook,
-		WGInterface:     wgInterface,
-		CookieSecure:    cookieSecure,
-		TrustProxy:      trustProxy,
-		MaxTsDriftSec:   maxTsDriftSec,
-		GithubRepo:      githubRepo,
-		GithubToken:     githubToken,
-		ServerRoot:      serverRoot,
-		AutoRearm:       autoRearm,
-		AutoReinstall:   autoReinstall,
-		PublicURL:       publicURL,
-		BeaconListen:    beaconListen,
-		AgentAutoenroll: agentAutoenroll,
-		Onbox:           onbox,
-		GhostPortEnabled: ghostPortEnabled,
-		RTLConsolePass:   rtlPass,
+		Port:              port,
+		NodeEnv:           nodeEnv,
+		StaticDir:         resolve(staticDir),
+		DataDir:           resolve(dataDir),
+		SessionSecret:     sessionSecret,
+		AuthUser:          authUser,
+		AuthPass:          authPass,
+		DemoMode:          demoMode,
+		MaxSSEClients:     maxSSE,
+		Routers:           routers,
+		SSHKeyPath:        sshKeyPath,
+		Adguard:           adguard,
+		Webhook:           webhook,
+		WGInterface:       wgInterface,
+		CookieSecure:      cookieSecure,
+		TrustProxy:        trustProxy,
+		MaxTsDriftSec:     maxTsDriftSec,
+		GithubRepo:        githubRepo,
+		GithubToken:       githubToken,
+		ServerRoot:        serverRoot,
+		AutoRearm:         autoRearm,
+		AutoReinstall:     autoReinstall,
+		PublicURL:         publicURL,
+		BeaconListen:      beaconListen,
+		AgentAutoenroll:   agentAutoenroll,
+		Onbox:             onbox,
+		GhostPortEnabled:  ghostPortEnabled,
+		RTLConsolePass:    rtlPass,
 		RTLConsolePollSec: rtlPollSec,
+		TLSEnabled:        tlsEnabled,
+		TLSPort:           tlsPort,
+		TLSCert:           tlsCert,
+		TLSKey:            tlsKey,
 	}, nil
 }
 

+ 90 - 0
server-go/internal/config/config_test.go

@@ -71,3 +71,93 @@ func TestLoadOnboxCeroEquivaleAHoy(t *testing.T) {
 		t.Fatal("NETPULSE_ONBOX=0 debe dejar Onbox=false (comportamiento actual)")
 	}
 }
+
+// --- TLS adicional (#696) ---
+
+func TestLoadTLSDefaultOff(t *testing.T) {
+	cfg, err := Load(map[string]string{"AUTH_PASS": "segura-y-larga"}, t.TempDir())
+	if err != nil {
+		t.Fatalf("Load: %v", err)
+	}
+	if cfg.TLSEnabled {
+		t.Fatal("TLSEnabled debe ser false por defecto (arranque idéntico al actual)")
+	}
+	if cfg.TLSPort != 3443 {
+		t.Fatalf("TLSPort = %d, esperaba 3443 (default)", cfg.TLSPort)
+	}
+	if cfg.TLSCert != "" || cfg.TLSKey != "" {
+		t.Fatalf("TLSCert/Key = %q/%q, esperaba vacíos por defecto", cfg.TLSCert, cfg.TLSKey)
+	}
+}
+
+func TestLoadTLSEnabledDefaultPort(t *testing.T) {
+	cfg, err := Load(map[string]string{"AUTH_PASS": "segura-y-larga", "NETPULSE_TLS_ENABLED": "1"}, t.TempDir())
+	if err != nil {
+		t.Fatalf("Load: %v", err)
+	}
+	if !cfg.TLSEnabled {
+		t.Fatal("TLSEnabled debe ser true con NETPULSE_TLS_ENABLED=1")
+	}
+	if cfg.TLSPort != 3443 {
+		t.Fatalf("TLSPort = %d, esperaba 3443 (default)", cfg.TLSPort)
+	}
+}
+
+func TestLoadTLSPortOverride(t *testing.T) {
+	cfg, err := Load(map[string]string{
+		"AUTH_PASS": "segura-y-larga", "NETPULSE_TLS_ENABLED": "1", "NETPULSE_TLS_PORT": "8443",
+	}, t.TempDir())
+	if err != nil {
+		t.Fatalf("Load: %v", err)
+	}
+	if cfg.TLSPort != 8443 {
+		t.Fatalf("TLSPort = %d, esperaba 8443", cfg.TLSPort)
+	}
+}
+
+func TestLoadTLSPortInvalido(t *testing.T) {
+	for _, bad := range []string{"0", "65536", "abc"} {
+		_, err := Load(map[string]string{
+			"AUTH_PASS": "segura-y-larga", "NETPULSE_TLS_PORT": bad,
+		}, t.TempDir())
+		if err == nil || !strings.Contains(err.Error(), "NETPULSE_TLS_PORT") {
+			t.Fatalf("NETPULSE_TLS_PORT=%q debe fallar señalando la variable: %v", bad, err)
+		}
+	}
+}
+
+func TestLoadTLSEnumInvalido(t *testing.T) {
+	_, err := Load(map[string]string{"AUTH_PASS": "segura-y-larga", "NETPULSE_TLS_ENABLED": "2"}, t.TempDir())
+	if err == nil || !strings.Contains(err.Error(), "NETPULSE_TLS_ENABLED") {
+		t.Fatalf("NETPULSE_TLS_ENABLED=2 debe fallar señalando la variable: %v", err)
+	}
+}
+
+func TestLoadTLSCertKeyPareja(t *testing.T) {
+	cfg, err := Load(map[string]string{
+		"AUTH_PASS": "segura-y-larga", "NETPULSE_TLS_ENABLED": "1",
+		"NETPULSE_TLS_CERT": "/srv/cert.pem", "NETPULSE_TLS_KEY": "/srv/key.pem",
+	}, t.TempDir())
+	if err != nil {
+		t.Fatalf("Load: %v", err)
+	}
+	if cfg.TLSCert != "/srv/cert.pem" || cfg.TLSKey != "/srv/key.pem" {
+		t.Fatalf("TLSCert/Key = %q/%q, esperaba los paths del usuario", cfg.TLSCert, cfg.TLSKey)
+	}
+}
+
+func TestLoadTLSCertSinKey(t *testing.T) {
+	_, err := Load(map[string]string{
+		"AUTH_PASS": "segura-y-larga", "NETPULSE_TLS_CERT": "/srv/cert.pem",
+	}, t.TempDir())
+	if err == nil || !strings.Contains(err.Error(), "NETPULSE_TLS_CERT/NETPULSE_TLS_KEY") {
+		t.Fatalf("TLS_CERT sin TLS_KEY debe fallar señalando la pareja: %v", err)
+	}
+
+	_, err = Load(map[string]string{
+		"AUTH_PASS": "segura-y-larga", "NETPULSE_TLS_KEY": "/srv/key.pem",
+	}, t.TempDir())
+	if err == nil || !strings.Contains(err.Error(), "NETPULSE_TLS_CERT/NETPULSE_TLS_KEY") {
+		t.Fatalf("TLS_KEY sin TLS_CERT debe fallar señalando la pareja: %v", err)
+	}
+}

+ 11 - 0
server-go/internal/tlscert/tlscert.go

@@ -37,6 +37,17 @@ func Ensure(certPath, keyPath string) (*tls.Config, string, error) {
 	return generate(certPath, keyPath)
 }
 
+// Load carga un par cert/clave existente SIN generar si falta. Es el caso de
+// "certificados del usuario" (NETPULSE_TLS_CERT/NETPULSE_TLS_KEY, #696): si
+// alguno no existe o no parsea, devuelve error en vez de generar un
+// autofirmado en las rutas configuradas.
+func Load(certPath, keyPath string) (*tls.Config, string, error) {
+	if !fileExists(certPath) || !fileExists(keyPath) {
+		return nil, "", fmt.Errorf("cert o clave no encontrados en %s / %s", certPath, keyPath)
+	}
+	return loadExisting(certPath, keyPath)
+}
+
 // Fingerprint calcula el SPKI hash hex de un certificado parsed.
 func Fingerprint(cert *x509.Certificate) string {
 	sum := sha256.Sum256(cert.RawSubjectPublicKeyInfo)

+ 31 - 0
server-go/internal/tlscert/tlscert_test.go

@@ -68,3 +68,34 @@ func TestGeneratedCertUsableByTLS(t *testing.T) {
 		t.Fatal("cert sin PrivateKey")
 	}
 }
+
+func TestLoadUserCerts(t *testing.T) {
+	dir := t.TempDir()
+	certPath := filepath.Join(dir, "cert.pem")
+	keyPath := filepath.Join(dir, "key.pem")
+
+	// Generamos un par con Ensure y luego lo cargamos con Load (caso "certs
+	// del usuario"): debe cargar el existente, no regenerarlo.
+	_, fpGenerated, err := Ensure(certPath, keyPath)
+	if err != nil {
+		t.Fatalf("Ensure: %v", err)
+	}
+	tlsConf, fpLoaded, err := Load(certPath, keyPath)
+	if err != nil {
+		t.Fatalf("Load: %v", err)
+	}
+	if len(tlsConf.Certificates) != 1 {
+		t.Fatal("tls.Config sin certificados")
+	}
+	if fpLoaded != fpGenerated {
+		t.Fatalf("fingerprint de Load (%s) ≠ Ensure (%s)", fpLoaded, fpGenerated)
+	}
+}
+
+func TestLoadMissingFails(t *testing.T) {
+	dir := t.TempDir()
+	_, _, err := Load(filepath.Join(dir, "no-existe.pem"), filepath.Join(dir, "no-existe.key"))
+	if err == nil {
+		t.Fatal("Load con paths inexistentes debe fallar (no genera autofirmado)")
+	}
+}