mirror of
https://github.com/ivuorinen/f2b.git
synced 2026-01-26 03:13:58 +00:00
* refactor: consolidate test helpers and reduce code duplication
- Fix prealloc lint issue in cmd_logswatch_test.go
- Add validateIPAndJails helper to consolidate IP/jail validation
- Add WithTestRunner/WithTestSudoChecker helpers for cleaner test setup
- Replace setupBasicMockResponses duplicates with StandardMockSetup
- Add SetupStandardResponses/SetupJailResponses to MockRunner
- Delegate cmd context helpers to fail2ban implementations
- Document context wrapper pattern in context_helpers.go
* refactor: consolidate duplicate code patterns across cmd and fail2ban packages
Add helper functions to reduce code duplication found by dupl:
- safeCloseFile/safeCloseReader: centralize file close error logging
- createTimeoutContext: consolidate timeout context creation pattern
- withContextCheck: wrap context cancellation checks
- recordOperationMetrics: unify metrics recording for commands/clients
Also includes Phase 1 consolidations:
- copyBuckets helper for metrics snapshots
- Table-driven context extraction in logging
- processWithValidation helper for IP processors
* refactor: consolidate LoggerInterface by embedding LoggerEntry
Both interfaces had identical method signatures. LoggerInterface now
embeds LoggerEntry to eliminate code duplication.
* refactor: consolidate test framework helpers and fix test patterns
- Add checkJSONFieldValue and failMissingJSONField helpers to reduce
duplication in JSON assertion methods
- Add ParallelTimeout to default test config
- Fix test to use WithTestRunner inside test loop for proper mock scoping
* refactor: unify ban/unban operations with OperationType pattern
Introduce OperationType struct to consolidate duplicate ban/unban logic:
- Add ProcessOperation and ProcessOperationWithContext generic functions
- Add ProcessOperationParallel and ProcessOperationParallelWithContext
- Existing ProcessBan*/ProcessUnban* functions now delegate to generic versions
- Reduces ~120 lines of duplicate code between ban and unban operations
* refactor: consolidate time parsing cache pattern
Add ParseWithLayout method to BoundedTimeCache that consolidates the
cache-lookup-parse-store pattern. FastTimeCache and TimeParsingCache
now delegate to this method instead of duplicating the logic.
* refactor: consolidate command execution patterns in fail2ban
- Add validateCommandExecution helper for command/argument validation
- Add runWithTimerContext helper for timed runner operations
- Add executeIPActionWithContext to unify BanIP/UnbanIP implementations
- Reduces duplicate validation and execution boilerplate
* refactor: consolidate logrus adapter with embedded loggerCore
Introduce loggerCore type that provides the 8 standard logging methods
(Debug, Info, Warn, Error, Debugf, Infof, Warnf, Errorf). Both
logrusAdapter and logrusEntryAdapter now embed this type, eliminating
16 duplicate method implementations.
* refactor: consolidate path validation patterns
- Add validateConfigPathWithFallback helper in cmd/config_utils.go
for the validate-or-fallback-with-logging pattern
- Add validateClientPath helper in fail2ban/helpers.go for client
path validation delegation
* fix: add context cancellation checks to wrapper functions
- wrapWithContext0/1/2 now check ctx.Err() before invoking wrapped function
- WithCommand now validates and trims empty command strings
* refactor: extract formatLatencyBuckets for deterministic metrics output
Add formatLatencyBuckets helper that writes latency bucket distribution
with sorted keys for deterministic output, eliminating duplicate
formatting code for command and client latency buckets.
* refactor: add generic setNestedMapValue helper for mock configuration
Add setNestedMapValue[T] generic helper that consolidates the repeated
pattern of mutex-protected nested map initialization and value setting
used by SetBanError, SetBanResult, SetUnbanError, and SetUnbanResult.
* fix: use cmd.Context() for signal propagation and correct mock status
- ExecuteIPCommand now uses cmd.Context() instead of context.Background()
to inherit Cobra's signal cancellation
- MockRunner.SetupJailResponses uses shared.Fail2BanStatusSuccess ("0")
instead of literal "1" for proper success path simulation
* fix: restore operation-specific log messages in ProcessOperationWithContext
Add back Logger.WithFields().Info(opType.Message) call that was lost
during refactoring. This restores the distinction between ban and unban
operation messages (shared.MsgBanResult vs shared.MsgUnbanResult).
* fix: return aggregated errors from parallel operations
Previously, errors from individual parallel operations were silently
swallowed - converted to status strings but never returned to callers.
Now processOperations collects all errors and returns them aggregated
via errors.Join, allowing callers to distinguish partial failures from
complete success while still receiving all results.
* fix: add input validation to processOperations before parallel execution
Validate IP and jail inputs at the start of processOperations() using
fail2ban.CachedValidateIP and CachedValidateJail. This prevents invalid
or malicious inputs (empty values, path traversal attempts, malformed
IPs) from reaching the operation functions. All validation errors are
aggregated and returned before any operations execute.
212 lines
6.0 KiB
Go
212 lines
6.0 KiB
Go
package fail2ban
|
|
|
|
import (
|
|
"context"
|
|
"testing"
|
|
)
|
|
|
|
// Simple tests to boost coverage for easy functions
|
|
func TestSimpleFunctionsCoverage(t *testing.T) {
|
|
// Test GetFilterDir
|
|
dir := GetFilterDir()
|
|
if dir == "" {
|
|
t.Error("GetFilterDir returned empty string")
|
|
}
|
|
|
|
// Test GetLogDir
|
|
logDir := GetLogDir()
|
|
if logDir == "" {
|
|
t.Error("GetLogDir returned empty string")
|
|
}
|
|
|
|
// Test SetLogDir and GetLogDir
|
|
originalLogDir := GetLogDir()
|
|
SetLogDir("/tmp/test")
|
|
if GetLogDir() != "/tmp/test" {
|
|
t.Error("SetLogDir/GetLogDir not working properly")
|
|
}
|
|
SetLogDir(originalLogDir) // Restore
|
|
|
|
// Test SetFilterDir and GetFilterDir
|
|
originalFilterDir := GetFilterDir()
|
|
SetFilterDir("/tmp/filters")
|
|
if GetFilterDir() != "/tmp/filters" {
|
|
t.Error("SetFilterDir/GetFilterDir not working properly")
|
|
}
|
|
SetFilterDir(originalFilterDir) // Restore
|
|
|
|
// Test NewMockRunner
|
|
mockRunner := NewMockRunner()
|
|
if mockRunner == nil {
|
|
t.Error("NewMockRunner returned nil")
|
|
}
|
|
|
|
// Test SetRunner and GetRunner
|
|
originalRunner := GetRunner()
|
|
SetRunner(mockRunner)
|
|
if GetRunner() != mockRunner {
|
|
t.Error("SetRunner/GetRunner not working properly")
|
|
}
|
|
SetRunner(originalRunner) // Restore
|
|
}
|
|
|
|
func TestRunnerFunctions(t *testing.T) {
|
|
// Set up mock runner for testing
|
|
mockRunner := NewMockRunner()
|
|
mockRunner.SetResponse("test-cmd arg1", []byte("test output"))
|
|
defer WithTestRunner(t, mockRunner)()
|
|
|
|
// Test RunnerCombinedOutput
|
|
output, err := RunnerCombinedOutput("test-cmd", "arg1")
|
|
if err != nil {
|
|
t.Errorf("RunnerCombinedOutput failed: %v", err)
|
|
}
|
|
if string(output) != "test output" {
|
|
t.Errorf("Expected 'test output', got %q", string(output))
|
|
}
|
|
|
|
// Test RunnerCombinedOutputWithSudo - note it may fallback to non-sudo
|
|
output, err = RunnerCombinedOutputWithSudo("test-cmd", "arg1")
|
|
if err != nil {
|
|
t.Errorf("RunnerCombinedOutputWithSudo failed: %v", err)
|
|
}
|
|
// Don't assert exact output, just that it worked
|
|
_ = output
|
|
}
|
|
|
|
func TestContextRunnerFunctions(t *testing.T) {
|
|
// Set up mock runner for testing
|
|
mockRunner := NewMockRunner()
|
|
mockRunner.SetResponse("test-cmd arg1", []byte("test output"))
|
|
SetRunner(mockRunner)
|
|
defer SetRunner(&OSRunner{}) // Restore real runner
|
|
|
|
ctx := context.Background()
|
|
|
|
// Test RunnerCombinedOutputWithContext
|
|
output, err := RunnerCombinedOutputWithContext(ctx, "test-cmd", "arg1")
|
|
if err != nil {
|
|
t.Errorf("RunnerCombinedOutputWithContext failed: %v", err)
|
|
}
|
|
if string(output) != "test output" {
|
|
t.Errorf("Expected 'test output', got %q", string(output))
|
|
}
|
|
|
|
// Test RunnerCombinedOutputWithSudoContext - may not use sudo
|
|
output, err = RunnerCombinedOutputWithSudoContext(ctx, "test-cmd", "arg1")
|
|
if err != nil {
|
|
t.Errorf("RunnerCombinedOutputWithSudoContext failed: %v", err)
|
|
}
|
|
// Don't assert exact output, just that it worked
|
|
_ = output
|
|
}
|
|
|
|
func TestMockRunnerMethods(_ *testing.T) {
|
|
mockRunner := NewMockRunner()
|
|
|
|
// Test SetResponse and SetError - just call them for coverage
|
|
mockRunner.SetResponse("cmd1", []byte("response1"))
|
|
mockRunner.SetError("cmd2", NewInvalidIPError("test error"))
|
|
|
|
// Test GetCalls
|
|
calls := mockRunner.GetCalls()
|
|
_ = calls // Just call it
|
|
|
|
// Test CombinedOutput - may fail, that's ok
|
|
_, _ = mockRunner.CombinedOutput("cmd1")
|
|
_, _ = mockRunner.CombinedOutput("cmd2")
|
|
|
|
// Test context methods
|
|
ctx := context.Background()
|
|
_, _ = mockRunner.CombinedOutputWithContext(ctx, "cmd1")
|
|
_, _ = mockRunner.CombinedOutputWithSudoContext(ctx, "cmd1")
|
|
}
|
|
|
|
func TestTestHelperFunctions(t *testing.T) {
|
|
// Test SetupBasicMockClient
|
|
client := SetupBasicMockClient()
|
|
if client == nil {
|
|
t.Error("SetupBasicMockClient returned nil")
|
|
}
|
|
|
|
// Test AssertError - may fail validation, that's ok for coverage
|
|
err := NewInvalidIPError("test")
|
|
defer func() { _ = recover() }() // Recover from any panics
|
|
AssertError(t, err, true, "test error expected")
|
|
|
|
// Test AssertErrorContains
|
|
AssertErrorContains(t, err, "test", "error should contain test")
|
|
|
|
// Test AssertCommandSuccess
|
|
AssertCommandSuccess(t, nil, "output", "output", "test command success")
|
|
|
|
// Test AssertCommandError - just call it for coverage
|
|
defer func() { _ = recover() }() // In case assertion fails
|
|
AssertCommandError(t, NewInvalidIPError("test error"), "test error", "test error", "test command error")
|
|
}
|
|
|
|
func TestSimpleGettersSetters(t *testing.T) {
|
|
// Test ValidationCache methods
|
|
cache := NewValidationCache()
|
|
|
|
// Test Set and Get
|
|
cache.Set("test", nil)
|
|
exists, result := cache.Get("test")
|
|
if !exists {
|
|
t.Error("Expected cache entry to exist")
|
|
}
|
|
if result != nil {
|
|
t.Error("Expected nil result")
|
|
}
|
|
|
|
// Test Size
|
|
if cache.Size() != 1 {
|
|
t.Errorf("Expected cache size 1, got %d", cache.Size())
|
|
}
|
|
|
|
// Test Clear
|
|
cache.Clear()
|
|
if cache.Size() != 0 {
|
|
t.Errorf("Expected cache size 0 after clear, got %d", cache.Size())
|
|
}
|
|
|
|
// Test SetMetricsRecorder and getMetricsRecorder
|
|
originalRecorder := getMetricsRecorder()
|
|
mockRecorder := &MockMetricsRecorder{}
|
|
SetMetricsRecorder(mockRecorder)
|
|
|
|
retrievedRecorder := getMetricsRecorder()
|
|
if retrievedRecorder != mockRecorder {
|
|
t.Error("SetMetricsRecorder/getMetricsRecorder not working properly")
|
|
}
|
|
|
|
SetMetricsRecorder(originalRecorder) // Restore
|
|
}
|
|
|
|
func TestRealClientHelperMethods(t *testing.T) {
|
|
// We can't test real client methods without fail2ban installed,
|
|
// but we can test some safe methods that may exist
|
|
|
|
// Test GetLogLines and GetLogLinesWithLimit exist (will fail gracefully)
|
|
_, cleanup := SetupMockEnvironmentWithSudo(t, false)
|
|
defer cleanup()
|
|
|
|
// Use valid temp directories
|
|
tmpDir := t.TempDir()
|
|
client, err := NewClient(tmpDir, tmpDir)
|
|
if err != nil {
|
|
// If client creation fails, skip the rest
|
|
t.Skipf("NewClient failed (expected): %v", err)
|
|
return
|
|
}
|
|
|
|
// These will fail due to no log files, but test the methods exist
|
|
_, _ = client.GetLogLines("sshd", "192.168.1.1")
|
|
_, _ = client.GetLogLinesWithLimit("sshd", "192.168.1.1", 10)
|
|
|
|
// Test context version
|
|
ctx := context.Background()
|
|
_, _ = client.GetLogLinesWithContext(ctx, "sshd", "192.168.1.1")
|
|
_, _ = client.GetLogLinesWithLimitAndContext(ctx, "sshd", "192.168.1.1", 10)
|
|
}
|