refactor: update function signatures and improve code readability

This commit is contained in:
GitHub Actions
2025-12-31 21:29:53 +00:00
parent caeea504a5
commit 7524d4d3aa
7 changed files with 50 additions and 44 deletions

View File

@@ -31,7 +31,7 @@ func (m *mockStopExecutor) Stop(_ context.Context, _ string) error {
return m.stopErr
}
func (m *mockStopExecutor) Status(_ context.Context, _ string) (bool, int, error) {
func (m *mockStopExecutor) Status(_ context.Context, _ string) (running bool, pid int, err error) {
return false, 0, nil
}

View File

@@ -43,7 +43,7 @@ func NewLogsWSHandler(tracker *services.WebSocketTracker) *LogsWSHandler {
}
// LogsWebSocketHandler handles WebSocket connections for live log streaming.
// DEPRECATED: Use NewLogsWSHandler().HandleWebSocket instead. Kept for backward compatibility.
// Deprecated: Use NewLogsWSHandler().HandleWebSocket instead. Kept for backward compatibility.
func LogsWebSocketHandler(c *gin.Context) {
// For backward compatibility, create a nil tracker if called directly
handler := NewLogsWSHandler(nil)

View File

@@ -34,21 +34,19 @@ func NewSecurityHeadersHandler(db *gorm.DB, caddyManager *caddy.Manager) *Securi
// RegisterRoutes registers all security headers routes
func (h *SecurityHeadersHandler) RegisterRoutes(router *gin.RouterGroup) {
group := router.Group("/security/headers")
{
group.GET("/profiles", h.ListProfiles)
group.GET("/profiles/:id", h.GetProfile)
group.POST("/profiles", h.CreateProfile)
group.PUT("/profiles/:id", h.UpdateProfile)
group.DELETE("/profiles/:id", h.DeleteProfile)
group.GET("/profiles", h.ListProfiles)
group.GET("/profiles/:id", h.GetProfile)
group.POST("/profiles", h.CreateProfile)
group.PUT("/profiles/:id", h.UpdateProfile)
group.DELETE("/profiles/:id", h.DeleteProfile)
group.GET("/presets", h.GetPresets)
group.POST("/presets/apply", h.ApplyPreset)
group.GET("/presets", h.GetPresets)
group.POST("/presets/apply", h.ApplyPreset)
group.POST("/score", h.CalculateScore)
group.POST("/score", h.CalculateScore)
group.POST("/csp/validate", h.ValidateCSP)
group.POST("/csp/build", h.BuildCSP)
}
group.POST("/csp/validate", h.ValidateCSP)
group.POST("/csp/build", h.BuildCSP)
}
// ListProfiles returns all security header profiles

View File

@@ -402,7 +402,7 @@ func Register(router *gin.Engine, db *gorm.DB, cfg config.Config) error {
// Ensure log directory and file exist for LogWatcher
// This prevents failures after container restart when log file doesn't exist yet
if err := os.MkdirAll(filepath.Dir(accessLogPath), 0755); err != nil {
if err := os.MkdirAll(filepath.Dir(accessLogPath), 0o755); err != nil {
logger.Log().WithError(err).WithField("path", accessLogPath).Warn("Failed to create log directory for LogWatcher")
}
if _, err := os.Stat(accessLogPath); os.IsNotExist(err) {

View File

@@ -1024,9 +1024,9 @@ func TestEnsureCAPIRegistered_StandardLayoutExists(t *testing.T) {
// Create config directory with credentials file (standard layout)
configDir := filepath.Join(tmpDir, "config")
require.NoError(t, os.MkdirAll(configDir, 0755))
require.NoError(t, os.MkdirAll(configDir, 0o755))
credsPath := filepath.Join(configDir, "online_api_credentials.yaml")
require.NoError(t, os.WriteFile(credsPath, []byte("url: https://api.crowdsec.net\nlogin: test"), 0644))
require.NoError(t, os.WriteFile(credsPath, []byte("url: https://api.crowdsec.net\nlogin: test"), 0o644))
exec := &stubEnvExecutor{}
svc := NewConsoleEnrollmentService(db, exec, tmpDir, "secret")
@@ -1068,9 +1068,9 @@ func TestFindConfigPath_StandardLayout(t *testing.T) {
// Create config directory with config.yaml (standard layout)
configDir := filepath.Join(tmpDir, "config")
require.NoError(t, os.MkdirAll(configDir, 0755))
require.NoError(t, os.MkdirAll(configDir, 0o755))
configPath := filepath.Join(configDir, "config.yaml")
require.NoError(t, os.WriteFile(configPath, []byte("common:\n daemonize: false"), 0644))
require.NoError(t, os.WriteFile(configPath, []byte("common:\n daemonize: false"), 0o644))
exec := &stubEnvExecutor{}
svc := NewConsoleEnrollmentService(db, exec, tmpDir, "secret")

View File

@@ -738,7 +738,10 @@ func TestNewSafeHTTPClient_MetadataEndpoint(t *testing.T) {
)
// AWS metadata endpoint
_, err := client.Get("http://169.254.169.254/latest/meta-data/")
resp, err := client.Get("http://169.254.169.254/latest/meta-data/")
if resp != nil {
defer resp.Body.Close()
}
if err == nil {
t.Error("expected cloud metadata endpoint to be blocked")
}

View File

@@ -13,7 +13,12 @@ import {
useValidateCSP,
useBuildCSP,
} from '../useSecurityHeaders';
import { securityHeadersApi } from '../../api/securityHeaders';
import {
securityHeadersApi,
SecurityHeaderProfile,
SecurityHeaderPreset,
CreateProfileRequest,
} from '../../api/securityHeaders';
import toast from 'react-hot-toast';
vi.mock('../../api/securityHeaders');
@@ -39,12 +44,12 @@ describe('useSecurityHeaders', () => {
describe('useSecurityHeaderProfiles', () => {
it('should fetch profiles successfully', async () => {
const mockProfiles = [
{ id: 1, name: 'Profile 1', security_score: 85 },
{ id: 2, name: 'Profile 2', security_score: 90 },
const mockProfiles: SecurityHeaderProfile[] = [
{ id: 1, name: 'Profile 1', security_score: 85 } as SecurityHeaderProfile,
{ id: 2, name: 'Profile 2', security_score: 90 } as SecurityHeaderProfile,
];
vi.mocked(securityHeadersApi.listProfiles).mockResolvedValue(mockProfiles as any);
vi.mocked(securityHeadersApi.listProfiles).mockResolvedValue(mockProfiles);
const { result } = renderHook(() => useSecurityHeaderProfiles(), {
wrapper: createWrapper(),
@@ -71,9 +76,9 @@ describe('useSecurityHeaders', () => {
describe('useSecurityHeaderProfile', () => {
it('should fetch a single profile', async () => {
const mockProfile = { id: 1, name: 'Profile 1', security_score: 85 };
const mockProfile: SecurityHeaderProfile = { id: 1, name: 'Profile 1', security_score: 85 } as SecurityHeaderProfile;
vi.mocked(securityHeadersApi.getProfile).mockResolvedValue(mockProfile as any);
vi.mocked(securityHeadersApi.getProfile).mockResolvedValue(mockProfile);
const { result } = renderHook(() => useSecurityHeaderProfile(1), {
wrapper: createWrapper(),
@@ -97,16 +102,16 @@ describe('useSecurityHeaders', () => {
describe('useCreateSecurityHeaderProfile', () => {
it('should create a profile successfully', async () => {
const newProfile = { name: 'New Profile', hsts_enabled: true };
const createdProfile = { id: 1, ...newProfile, security_score: 80 };
const newProfile: CreateProfileRequest = { name: 'New Profile', hsts_enabled: true };
const createdProfile: SecurityHeaderProfile = { id: 1, ...newProfile, security_score: 80 } as SecurityHeaderProfile;
vi.mocked(securityHeadersApi.createProfile).mockResolvedValue(createdProfile as any);
vi.mocked(securityHeadersApi.createProfile).mockResolvedValue(createdProfile);
const { result } = renderHook(() => useCreateSecurityHeaderProfile(), {
wrapper: createWrapper(),
});
result.current.mutate(newProfile as any);
result.current.mutate(newProfile);
await waitFor(() => expect(result.current.isSuccess).toBe(true));
@@ -121,7 +126,7 @@ describe('useSecurityHeaders', () => {
wrapper: createWrapper(),
});
result.current.mutate({ name: 'Test' } as any);
result.current.mutate({ name: 'Test' });
await waitFor(() => expect(result.current.isError).toBe(true));
@@ -131,16 +136,16 @@ describe('useSecurityHeaders', () => {
describe('useUpdateSecurityHeaderProfile', () => {
it('should update a profile successfully', async () => {
const updateData = { name: 'Updated Profile' };
const updatedProfile = { id: 1, ...updateData, security_score: 85 };
const updateData: Partial<CreateProfileRequest> = { name: 'Updated Profile' };
const updatedProfile: SecurityHeaderProfile = { id: 1, ...updateData, security_score: 85 } as SecurityHeaderProfile;
vi.mocked(securityHeadersApi.updateProfile).mockResolvedValue(updatedProfile as any);
vi.mocked(securityHeadersApi.updateProfile).mockResolvedValue(updatedProfile);
const { result } = renderHook(() => useUpdateSecurityHeaderProfile(), {
wrapper: createWrapper(),
});
result.current.mutate({ id: 1, data: updateData as any });
result.current.mutate({ id: 1, data: updateData });
await waitFor(() => expect(result.current.isSuccess).toBe(true));
@@ -155,7 +160,7 @@ describe('useSecurityHeaders', () => {
wrapper: createWrapper(),
});
result.current.mutate({ id: 1, data: { name: 'Test' } as any });
result.current.mutate({ id: 1, data: { name: 'Test' } });
await waitFor(() => expect(result.current.isError).toBe(true));
@@ -196,12 +201,12 @@ describe('useSecurityHeaders', () => {
describe('useSecurityHeaderPresets', () => {
it('should fetch presets successfully', async () => {
const mockPresets = [
{ type: 'basic', name: 'Basic Security', score: 65 },
{ type: 'strict', name: 'Strict Security', score: 85 },
const mockPresets: SecurityHeaderPreset[] = [
{ preset_type: 'basic', name: 'Basic Security', security_score: 65 } as SecurityHeaderPreset,
{ preset_type: 'strict', name: 'Strict Security', security_score: 85 } as SecurityHeaderPreset,
];
vi.mocked(securityHeadersApi.getPresets).mockResolvedValue(mockPresets as any);
vi.mocked(securityHeadersApi.getPresets).mockResolvedValue(mockPresets);
const { result } = renderHook(() => useSecurityHeaderPresets(), {
wrapper: createWrapper(),
@@ -215,9 +220,9 @@ describe('useSecurityHeaders', () => {
describe('useApplySecurityHeaderPreset', () => {
it('should apply preset successfully', async () => {
const appliedProfile = { id: 1, name: 'Basic Security', security_score: 65 };
const appliedProfile: SecurityHeaderProfile = { id: 1, name: 'Basic Security', security_score: 65 } as SecurityHeaderProfile;
vi.mocked(securityHeadersApi.applyPreset).mockResolvedValue(appliedProfile as any);
vi.mocked(securityHeadersApi.applyPreset).mockResolvedValue(appliedProfile);
const { result } = renderHook(() => useApplySecurityHeaderPreset(), {
wrapper: createWrapper(),
@@ -247,7 +252,7 @@ describe('useSecurityHeaders', () => {
wrapper: createWrapper(),
});
result.current.mutate({ hsts_enabled: true } as any);
result.current.mutate({ hsts_enabled: true });
await waitFor(() => expect(result.current.isSuccess).toBe(true));