Files
Charon/backend/internal/api/handlers/crowdsec_pull_apply_integration_test.go
T
GitHub Actions e299aa6b52 feat(tests): enhance test coverage and error handling across various components
- Added a test case in CrowdSecConfig to show improved error message when preset is not cached.
- Introduced a new test suite for the Dashboard component, verifying counts and health status.
- Updated SMTPSettings tests to utilize a shared render function and added tests for backend validation errors.
- Modified Security.audit tests to improve input handling and removed redundant export failure test.
- Refactored Security tests to remove export functionality and ensure correct rendering of components.
- Enhanced UsersPage tests with new scenarios for updating user permissions and manual invite link flow.
- Created a new utility for rendering components with a QueryClient and MemoryRouter for better test isolation.
- Updated go-test-coverage script to improve error handling and coverage reporting.
2025-12-11 00:26:07 +00:00

174 lines
6.1 KiB
Go

package handlers
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/Wikid82/charon/backend/internal/crowdsec"
)
// TestPullThenApplyIntegration tests the complete pull→apply workflow from the user's perspective.
// This reproduces the scenario where a user pulls a preset and then tries to apply it.
func TestPullThenApplyIntegration(t *testing.T) {
gin.SetMode(gin.TestMode)
// Setup
cacheDir := t.TempDir()
dataDir := t.TempDir()
cache, err := crowdsec.NewHubCache(cacheDir, time.Hour)
require.NoError(t, err)
archive := makePresetTarGz(t, map[string]string{
"config.yaml": "test: config\nversion: 1",
})
hub := crowdsec.NewHubService(nil, cache, dataDir)
hub.HubBaseURL = "http://test.hub"
hub.HTTPClient = &http.Client{
Transport: testRoundTripper(func(req *http.Request) (*http.Response, error) {
switch req.URL.String() {
case "http://test.hub/api/index.json":
body := `{"items":[{"name":"test/preset","title":"Test","description":"Test preset","etag":"abc123","download_url":"http://test.hub/test.tgz","preview_url":"http://test.hub/test.yaml"}]}`
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil
case "http://test.hub/test.yaml":
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader("preview content")), Header: make(http.Header)}, nil
case "http://test.hub/test.tgz":
return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(archive)), Header: make(http.Header)}, nil
default:
return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader("")), Header: make(http.Header)}, nil
}
}),
}
db := OpenTestDB(t)
handler := NewCrowdsecHandler(db, &fakeExec{}, "/bin/false", dataDir)
handler.Hub = hub
r := gin.New()
g := r.Group("/api/v1")
handler.RegisterRoutes(g)
// Step 1: Pull the preset
t.Log("User pulls preset")
pullPayload, _ := json.Marshal(map[string]string{"slug": "test/preset"})
pullReq := httptest.NewRequest(http.MethodPost, "/api/v1/admin/crowdsec/presets/pull", bytes.NewReader(pullPayload))
pullReq.Header.Set("Content-Type", "application/json")
pullResp := httptest.NewRecorder()
r.ServeHTTP(pullResp, pullReq)
require.Equal(t, http.StatusOK, pullResp.Code, "Pull should succeed")
var pullResult map[string]interface{}
err = json.Unmarshal(pullResp.Body.Bytes(), &pullResult)
require.NoError(t, err)
require.Equal(t, "pulled", pullResult["status"])
require.NotEmpty(t, pullResult["cache_key"], "Pull should return cache_key")
require.NotEmpty(t, pullResult["preview"], "Pull should return preview")
t.Log("Pull succeeded, cache_key:", pullResult["cache_key"])
// Verify cache was populated
ctx := context.Background()
cached, err := cache.Load(ctx, "test/preset")
require.NoError(t, err, "Preset should be cached after pull")
require.Equal(t, "test/preset", cached.Slug)
t.Log("Cache verified, slug:", cached.Slug)
// Step 2: Apply the preset (this should use the cached data)
t.Log("User applies preset")
applyPayload, _ := json.Marshal(map[string]string{"slug": "test/preset"})
applyReq := httptest.NewRequest(http.MethodPost, "/api/v1/admin/crowdsec/presets/apply", bytes.NewReader(applyPayload))
applyReq.Header.Set("Content-Type", "application/json")
applyResp := httptest.NewRecorder()
r.ServeHTTP(applyResp, applyReq)
// This should NOT return "preset not cached" error
require.Equal(t, http.StatusOK, applyResp.Code, "Apply should succeed after pull. Response: %s", applyResp.Body.String())
var applyResult map[string]interface{}
err = json.Unmarshal(applyResp.Body.Bytes(), &applyResult)
require.NoError(t, err)
require.Equal(t, "applied", applyResult["status"], "Apply status should be 'applied'")
require.NotEmpty(t, applyResult["backup"], "Apply should return backup path")
t.Log("Apply succeeded, backup:", applyResult["backup"])
}
// TestApplyWithoutPullReturnsProperError verifies the error message when applying without pulling first.
func TestApplyWithoutPullReturnsProperError(t *testing.T) {
gin.SetMode(gin.TestMode)
cacheDir := t.TempDir()
dataDir := t.TempDir()
cache, err := crowdsec.NewHubCache(cacheDir, time.Hour)
require.NoError(t, err)
// Empty cache, no cscli
hub := crowdsec.NewHubService(nil, cache, dataDir)
db := OpenTestDB(t)
handler := NewCrowdsecHandler(db, &fakeExec{}, "/bin/false", dataDir)
handler.Hub = hub
r := gin.New()
g := r.Group("/api/v1")
handler.RegisterRoutes(g)
// Try to apply without pulling first
t.Log("User tries to apply preset without pulling first")
applyPayload, _ := json.Marshal(map[string]string{"slug": "test/preset"})
applyReq := httptest.NewRequest(http.MethodPost, "/api/v1/admin/crowdsec/presets/apply", bytes.NewReader(applyPayload))
applyReq.Header.Set("Content-Type", "application/json")
applyResp := httptest.NewRecorder()
r.ServeHTTP(applyResp, applyReq)
require.Equal(t, http.StatusInternalServerError, applyResp.Code, "Apply should fail without cache")
var errorResult map[string]interface{}
err = json.Unmarshal(applyResp.Body.Bytes(), &errorResult)
require.NoError(t, err)
errorMsg := errorResult["error"].(string)
require.Contains(t, errorMsg, "not cached", "Error should mention preset not cached")
require.Contains(t, errorMsg, "Pull", "Error should guide user to pull first")
t.Log("Proper error message returned:", errorMsg)
}
func makePresetTarGz(t *testing.T, files map[string]string) []byte {
t.Helper()
buf := &bytes.Buffer{}
gw := gzip.NewWriter(buf)
tw := tar.NewWriter(gw)
for name, content := range files {
hdr := &tar.Header{Name: name, Mode: 0o644, Size: int64(len(content))}
require.NoError(t, tw.WriteHeader(hdr))
_, err := tw.Write([]byte(content))
require.NoError(t, err)
}
require.NoError(t, tw.Close())
require.NoError(t, gw.Close())
return buf.Bytes()
}
type testRoundTripper func(*http.Request) (*http.Response, error)
func (t testRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
return t(req)
}