Explorar el Código

feat(config-backup): authenticate NetGrip snapshot uploads with agent token (#340)

NetPulse already stored UCI snapshots from NetGrip, but POST /api/config-backup
accepted any request. Harden it:

- POST /api/config-backup now requires Authorization: Bearer <agent-token>
  and validates it against X-Router-ID.
- GET/DELETE /api/config-backup* require admin session.
- RequireAuth exempts only POST /api/config-backup from session auth; other
  methods still require a session.
- Add regression tests for unauthorized upload, valid agent upload, and
  admin-only list.

Fixes #340
gnacho hace 3 meses
padre
commit
7a939da776

+ 4 - 0
CHANGELOG.md

@@ -7,6 +7,10 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ## [Unreleased]
 
+### Added
+
+- **Backups centralizados de snapshots UCI (#340)**: el endpoint `POST /api/config-backup` ahora recibe snapshots gzip desde NetGrip autenticados con el token de agente. Los endpoints de lectura/borrado (`GET /api/config-backup`, `GET /api/config-backup/{id}`, `DELETE /api/config-backup/{id}`) requieren rol admin.
+
 ## [2.19.1] - 2026-08-29
 
 ### Fixed

+ 22 - 3
server-go/internal/auth/middleware.go

@@ -57,6 +57,24 @@ func WriteError(w http.ResponseWriter, status int, code string, message ...strin
 	_, _ = w.Write(data)
 }
 
+// isAgentReportPath: /api/agents/{slug}/binary|stream|apply-result|upgrade-result|upgrade-progress.
+func isAgentReportPath(path string) bool {
+	return strings.HasPrefix(path, "/api/agents/") &&
+		(strings.HasSuffix(path, "/binary") || strings.HasSuffix(path, "/stream") ||
+			strings.HasSuffix(path, "/apply-result") || strings.HasSuffix(path, "/upgrade-result") ||
+			strings.HasSuffix(path, "/upgrade-progress"))
+}
+
+// isAnonymousPath indica si la ruta no requiere sesión (auth propia en el handler).
+func isAnonymousPath(path string) bool {
+	if path == "/api/health" || path == "/api/auth/login" ||
+		path == "/api/ingest/agent" || path == "/api/agents/pair" ||
+		isAgentReportPath(path) {
+		return true
+	}
+	return false
+}
+
 // RequireAuth es middleware global: todo /api/* exige sesión salvo
 // /api/health, /api/auth/login, /api/ingest/agent (auth Bearer por token
 // de equipo), /api/agents/pair (pairing token de un solo uso, Fase 9 R3),
@@ -64,14 +82,15 @@ func WriteError(w http.ResponseWriter, status int, code string, message ...strin
 // Fase 6.2), /api/agents/{slug}/stream (SSE bidireccional, Fase 7.3),
 // /api/agents/{slug}/apply-result, /api/agents/{slug}/upgrade-result y
 // /api/agents/{slug}/upgrade-progress (reportes del agente, auth Bearer).
+// POST /api/config-backup (issue #340): recibe snapshots UCI desde NetGrip;
+// auth Bearer por token de agente validado en el handler.
 // Acepta Bearer tokens de API (#330) como alternativa a la cookie de sesión.
 // Fallo → 401 {error:'unauthorized'}.
 func RequireAuth(d *db.DB, secret string, tv TokenValidator, next http.Handler) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		path := r.URL.Path
-		if !strings.HasPrefix(path, "/api/") || path == "/api/health" || path == "/api/auth/login" ||
-			path == "/api/ingest/agent" || path == "/api/agents/pair" ||
-			(strings.HasPrefix(path, "/api/agents/") && (strings.HasSuffix(path, "/binary") || strings.HasSuffix(path, "/stream") || strings.HasSuffix(path, "/apply-result") || strings.HasSuffix(path, "/upgrade-result") || strings.HasSuffix(path, "/upgrade-progress"))) {
+		if !strings.HasPrefix(path, "/api/") || isAnonymousPath(path) ||
+			(path == "/api/config-backup" && r.Method == http.MethodPost) {
 			next.ServeHTTP(w, r)
 			return
 		}

+ 90 - 0
server-go/internal/httpapi/config_backup_test.go

@@ -0,0 +1,90 @@
+// config_backup_test.go — tests del endpoint /api/config-backup (#340).
+package httpapi_test
+
+import (
+	"bytes"
+	"crypto/sha256"
+	"encoding/hex"
+	"io"
+	"net/http"
+	"testing"
+)
+
+func setAgentToken(t *testing.T, ts *testServer, slug, token string) {
+	t.Helper()
+	sum := sha256.Sum256([]byte(token))
+	_, err := ts.db.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?)",
+		"agent.token."+slug, hex.EncodeToString(sum[:]))
+	if err != nil {
+		t.Fatalf("insert agent token: %v", err)
+	}
+}
+
+func TestConfigBackupUploadRequiresAgentToken(t *testing.T) {
+	ts := makeTestServer(t)
+
+	req, _ := http.NewRequest("POST", ts.URL+"/api/config-backup", bytes.NewReader([]byte("fake gzip")))
+	req.Header.Set("Content-Type", "application/gzip")
+	req.Header.Set("X-Router-ID", "flint2")
+	req.Header.Set("X-Snapshot-ID", "snap-1")
+	req.Header.Set("X-Configs", "network,firewall")
+
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("request: %v", err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusUnauthorized {
+		t.Fatalf("sin token: esperaba 401, got %d", res.StatusCode)
+	}
+}
+
+func TestConfigBackupUploadAcceptsValidAgentToken(t *testing.T) {
+	ts := makeTestServer(t)
+	setAgentToken(t, ts, "flint2", "secret-token-123")
+
+	body := []byte("fake gzip payload")
+	req, _ := http.NewRequest("POST", ts.URL+"/api/config-backup", bytes.NewReader(body))
+	req.Header.Set("Content-Type", "application/gzip")
+	req.Header.Set("X-Router-ID", "flint2")
+	req.Header.Set("X-Snapshot-ID", "snap-1")
+	req.Header.Set("X-Configs", "network,firewall")
+	req.Header.Set("Authorization", "Bearer secret-token-123")
+
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("request: %v", err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusOK {
+		b, _ := io.ReadAll(res.Body)
+		t.Fatalf("con token válido: esperaba 200, got %d: %s", res.StatusCode, string(b))
+	}
+
+	// El admin puede listarlo.
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	req2, _ := http.NewRequest("GET", ts.URL+"/api/config-backup?router=flint2", nil)
+	req2.Header.Set("Cookie", "session="+cookie)
+	res2, err := http.DefaultClient.Do(req2)
+	if err != nil {
+		t.Fatalf("list: %v", err)
+	}
+	defer res2.Body.Close()
+	if res2.StatusCode != http.StatusOK {
+		t.Fatalf("list admin: esperaba 200, got %d", res2.StatusCode)
+	}
+}
+
+func TestConfigBackupListRequiresAdmin(t *testing.T) {
+	ts := makeTestServer(t)
+
+	res, err := http.Get(ts.URL + "/api/config-backup")
+	if err != nil {
+		t.Fatalf("request: %v", err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusUnauthorized {
+		t.Fatalf("list sin sesión: esperaba 401, got %d", res.StatusCode)
+	}
+}

+ 8 - 2
server-go/internal/httpapi/httpapi_test.go

@@ -17,6 +17,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/apitoken"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"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/httpapi"
 	"github.com/gnacho/netpulse/server-go/internal/portseries"
@@ -79,12 +80,17 @@ func makeTestServerWithMode(t *testing.T, demoMode bool) *testServer {
 		t.Fatalf("api_tokens schema: %v", err)
 	}
 	tokenStore := apitoken.NewStore(d, secret)
+	configBackup, err := configbackup.NewStore(d)
+	if err != nil {
+		t.Fatalf("config backup store: %v", err)
+	}
 	adapter := adapters.NewDemo()
 	hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
 	handler := httpapi.NewHandler(httpapi.Deps{
 		Config: cfg, DB: d, Adapter: adapter, Hub: hub, Secret: secret,
-		Started:    time.Now(),
-		TokenStore: tokenStore,
+		Started:      time.Now(),
+		TokenStore:   tokenStore,
+		ConfigBackup: configBackup,
 	})
 	srv := httptest.NewServer(handler)
 	ts := &testServer{Server: srv, db: d, secret: secret}

+ 8 - 3
server-go/internal/httpapi/server.go

@@ -278,10 +278,10 @@ func NewHandler(d Deps) http.Handler {
 	mux.HandleFunc("GET /api/system/info", s.handleSystemInfo)
 	mux.HandleFunc("GET /api/reports/weekly", s.handleWeeklyReport)
 	mux.HandleFunc("GET /api/reports/availability", s.handleAvailabilityReport)
-	mux.HandleFunc("GET /api/config-backup", s.handleConfigBackupList)
+	mux.Handle("GET /api/config-backup", auth.RequireAdmin(http.HandlerFunc(s.handleConfigBackupList)))
 	mux.HandleFunc("POST /api/config-backup", s.handleConfigBackupUpload)
-	mux.HandleFunc("GET /api/config-backup/{id}", s.handleConfigBackupDownload)
-	mux.HandleFunc("DELETE /api/config-backup/{id}", s.handleConfigBackupDelete)
+	mux.Handle("GET /api/config-backup/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleConfigBackupDownload)))
+	mux.Handle("DELETE /api/config-backup/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleConfigBackupDelete)))
 
 	// --- Sondeo manual (botón "Refrescar" de Topología; 202 + SSE empuja) ---
 	mux.HandleFunc("POST /api/refresh", s.handleRefresh)
@@ -543,6 +543,11 @@ func (s *server) handleConfigBackupUpload(w http.ResponseWriter, r *http.Request
 		writeError(w, http.StatusBadRequest, "missing X-Router-ID or X-Snapshot-ID header")
 		return
 	}
+	token := bearerToken(r)
+	if token == "" || !s.checkAgentToken(routerID, token) {
+		writeError(w, http.StatusUnauthorized, "unauthorized")
+		return
+	}
 	data, err := io.ReadAll(io.LimitReader(r.Body, 10<<20))
 	if err != nil {
 		writeError(w, http.StatusBadRequest, "read body: "+err.Error())