feat: migrar backend unificado a Go 1.27 + SPA Vite embebido
This commit is contained in:
@@ -0,0 +1,266 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"cotizador/internal/auth"
|
||||
"cotizador/internal/config"
|
||||
)
|
||||
|
||||
func newTestServer(t *testing.T) (*Server, http.Handler) {
|
||||
t.Helper()
|
||||
cfg := &config.Config{
|
||||
Port: "3000",
|
||||
AppURL: "https://cotizador.urieljareth.org",
|
||||
JWTSecret: "test-secret-key-for-httpapi-tests-32b",
|
||||
}
|
||||
authSvc := auth.NewService(cfg.JWTSecret, false, nil)
|
||||
srv := NewServer(cfg, nil, authSvc, nil, nil)
|
||||
return srv, srv.Router()
|
||||
}
|
||||
|
||||
func makeCookie(t *testing.T, authSvc *auth.Service, sess auth.SessionPayload) *http.Cookie {
|
||||
t.Helper()
|
||||
tok, err := authSvc.SignSession(sess)
|
||||
if err != nil {
|
||||
t.Fatalf("SignSession: %v", err)
|
||||
}
|
||||
return &http.Cookie{Name: auth.SessionCookieName, Value: tok}
|
||||
}
|
||||
|
||||
func TestOpenAPIAndSPARouting(t *testing.T) {
|
||||
_, router := newTestServer(t)
|
||||
|
||||
// 1. OpenAPI 3.1
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/openapi.json", nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200 for /api/openapi.json, got %d", rec.Code)
|
||||
}
|
||||
var spec map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &spec); err != nil {
|
||||
t.Fatalf("invalid openapi json: %v", err)
|
||||
}
|
||||
if spec["openapi"] != "3.1.0" {
|
||||
t.Fatalf("expected openapi 3.1.0, got %v", spec["openapi"])
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "cotizaciones:approve") {
|
||||
t.Fatal("iron-clad rule violation: openapi mentions cotizaciones:approve")
|
||||
}
|
||||
|
||||
// 2. Unknown /api/* route returns 404 JSON, NOT SPA HTML
|
||||
rec = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodGet, "/api/does-not-exist", nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404 for unknown /api route, got %d", rec.Code)
|
||||
}
|
||||
if !strings.Contains(rec.Header().Get("Content-Type"), "application/json") {
|
||||
t.Fatalf("expected JSON content-type for unknown /api route, got %q", rec.Header().Get("Content-Type"))
|
||||
}
|
||||
|
||||
// 3. SPA routes serve HTML
|
||||
for _, p := range []string{"/", "/login", "/cotizaciones", "/cliente/pagos"} {
|
||||
rec = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodGet, p, nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200 for SPA path %s, got %d", p, rec.Code)
|
||||
}
|
||||
if !strings.Contains(strings.ToLower(rec.Body.String()), "<html") && !strings.Contains(strings.ToLower(rec.Body.String()), "<!doctype html") {
|
||||
t.Fatalf("expected HTML body for SPA path %s", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtectedRoutesRejectUnauthenticated(t *testing.T) {
|
||||
_, router := newTestServer(t)
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodGet, "/api/auth/me"},
|
||||
{http.MethodGet, "/api/dashboard"},
|
||||
{http.MethodGet, "/api/asesores"},
|
||||
{http.MethodGet, "/api/configuracion"},
|
||||
{http.MethodPut, "/api/configuracion"},
|
||||
{http.MethodGet, "/api/catalogo"},
|
||||
{http.MethodPost, "/api/catalogo"},
|
||||
{http.MethodPut, "/api/categorias/cat-1"},
|
||||
{http.MethodDelete, "/api/categorias/cat-1"},
|
||||
{http.MethodGet, "/api/paquetes/paq-1"},
|
||||
{http.MethodPost, "/api/paquetes/paq-1/manage"},
|
||||
{http.MethodGet, "/api/clientes"},
|
||||
{http.MethodPost, "/api/clientes"},
|
||||
{http.MethodGet, "/api/cotizaciones"},
|
||||
{http.MethodPost, "/api/cotizaciones"},
|
||||
{http.MethodPost, "/api/cotizaciones/q1/aprobar"},
|
||||
{http.MethodPost, "/api/cotizaciones/q1/enviar"},
|
||||
{http.MethodGet, "/api/cotizaciones/q1/horas"},
|
||||
{http.MethodPost, "/api/cotizaciones/q1/nota-horas"},
|
||||
{http.MethodPost, "/api/export/pdf"},
|
||||
{http.MethodGet, "/api/export/pdf/q1"},
|
||||
{http.MethodPost, "/api/export/excel"},
|
||||
{http.MethodGet, "/api/export/excel/q1"},
|
||||
{http.MethodGet, "/api/export/catalogo"},
|
||||
{http.MethodPost, "/api/import/catalogo"},
|
||||
{http.MethodGet, "/api/propuesta-ia/q1"},
|
||||
{http.MethodPost, "/api/propuesta-ia/q1"},
|
||||
{http.MethodPatch, "/api/propuesta-ia/q1"},
|
||||
{http.MethodGet, "/api/propuesta-ia/q1/pdf"},
|
||||
{http.MethodGet, "/api/cobros/resumen"},
|
||||
{http.MethodGet, "/api/cobros/programas"},
|
||||
{http.MethodGet, "/api/cobros/pagos"},
|
||||
{http.MethodGet, "/api/agent-keys"},
|
||||
{http.MethodGet, "/api/audit-logs"},
|
||||
{http.MethodGet, "/api/webhooks"},
|
||||
{http.MethodGet, "/api/cliente/resumen"},
|
||||
{http.MethodGet, "/api/cliente/cotizaciones"},
|
||||
{http.MethodGet, "/api/cliente/pagos"},
|
||||
{http.MethodGet, "/api/comprobantes/p1"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s %s without auth: expected 401, got %d (body: %s)", tc.method, tc.path, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanelAndRoleIsolation(t *testing.T) {
|
||||
srv, router := newTestServer(t)
|
||||
|
||||
clienteCookie := makeCookie(t, srv.Auth, auth.SessionPayload{
|
||||
UserID: "u-cli-1",
|
||||
Email: "[email protected]",
|
||||
Name: "Cliente Demo",
|
||||
Role: "cliente",
|
||||
ClienteID: "cli-1",
|
||||
})
|
||||
asesorCookie := makeCookie(t, srv.Auth, auth.SessionPayload{
|
||||
UserID: "u-ase-1",
|
||||
Email: "[email protected]",
|
||||
Name: "Asesor Demo",
|
||||
Role: "asesor",
|
||||
})
|
||||
adminCookie := makeCookie(t, srv.Auth, auth.SessionPayload{
|
||||
UserID: "u-adm-1",
|
||||
Email: "[email protected]",
|
||||
Name: "Uriel Admin",
|
||||
Role: "admin",
|
||||
})
|
||||
|
||||
// Cliente cannot access staff routes
|
||||
staffPaths := []struct{ method, path string }{
|
||||
{http.MethodGet, "/api/dashboard"},
|
||||
{http.MethodGet, "/api/cotizaciones"},
|
||||
{http.MethodGet, "/api/clientes"},
|
||||
{http.MethodGet, "/api/catalogo"},
|
||||
{http.MethodGet, "/api/cobros/programas"},
|
||||
{http.MethodGet, "/api/agent-keys"},
|
||||
{http.MethodGet, "/api/configuracion"},
|
||||
}
|
||||
for _, tc := range staffPaths {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||
req.AddCookie(clienteCookie)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("cliente -> %s %s: expected 403, got %d", tc.method, tc.path, rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Staff (admin/asesor) cannot access /api/cliente/*
|
||||
clientePaths := []struct{ method, path string }{
|
||||
{http.MethodGet, "/api/cliente/resumen"},
|
||||
{http.MethodGet, "/api/cliente/cotizaciones"},
|
||||
{http.MethodGet, "/api/cliente/pagos"},
|
||||
{http.MethodGet, "/api/cliente/push/config"},
|
||||
{http.MethodPost, "/api/cliente/push/suscribir"},
|
||||
{http.MethodDelete, "/api/cliente/push/suscribir"},
|
||||
}
|
||||
for _, tc := range clientePaths {
|
||||
for _, ck := range []*http.Cookie{adminCookie, asesorCookie} {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||
req.AddCookie(ck)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("staff -> %s %s: expected 403, got %d", tc.method, tc.path, rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Asesor cannot access strictly admin-only routes (including aprobar!)
|
||||
adminOnly := []struct{ method, path string }{
|
||||
{http.MethodPost, "/api/cotizaciones/q1/aprobar"},
|
||||
{http.MethodGet, "/api/agent-keys"},
|
||||
{http.MethodPost, "/api/agent-keys"},
|
||||
{http.MethodPost, "/api/agent-keys/k1/rotate"},
|
||||
{http.MethodPost, "/api/agent-keys/k1/revoke"},
|
||||
{http.MethodGet, "/api/audit-logs"},
|
||||
{http.MethodGet, "/api/webhooks"},
|
||||
{http.MethodPost, "/api/webhooks"},
|
||||
{http.MethodDelete, "/api/webhooks/w1"},
|
||||
{http.MethodGet, "/api/webhooks/deliveries"},
|
||||
}
|
||||
for _, tc := range adminOnly {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||
req.AddCookie(asesorCookie)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("asesor -> %s %s: expected 403, got %d", tc.method, tc.path, rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// /api/auth/me works for both admin and cliente without DB
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
ck *http.Cookie
|
||||
role string
|
||||
}{
|
||||
{"admin", adminCookie, "admin"},
|
||||
{"cliente", clienteCookie, "cliente"},
|
||||
} {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/auth/me", nil)
|
||||
req.AddCookie(tc.ck)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("/api/auth/me (%s): expected 200, got %d", tc.name, rec.Code)
|
||||
}
|
||||
var out map[string]any
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &out)
|
||||
u, _ := out["user"].(map[string]any)
|
||||
if u["role"] != tc.role {
|
||||
t.Fatalf("/api/auth/me (%s): expected role %s, got %v", tc.name, tc.role, u["role"])
|
||||
}
|
||||
}
|
||||
|
||||
// /api/auth/logout clears session cookie
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/auth/logout", nil)
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("/api/auth/logout: expected 200, got %d", rec.Code)
|
||||
}
|
||||
var cleared bool
|
||||
for _, c := range rec.Result().Cookies() {
|
||||
if c.Name == auth.SessionCookieName && c.MaxAge < 0 {
|
||||
cleared = true
|
||||
}
|
||||
}
|
||||
if !cleared {
|
||||
t.Fatal("expected logout to clear cotizador-session cookie")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user