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()), " %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") } }