mirror of
https://github.com/ivuorinen/f2b.git
synced 2026-02-26 07:53:57 +00:00
refactor: linting, simplification and fixes (#119)
* 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.
This commit is contained in:
@@ -95,6 +95,23 @@ func (btc *BoundedTimeCache) Size() int {
|
||||
return len(btc.cache)
|
||||
}
|
||||
|
||||
// ParseWithLayout parses a time string using the specified layout with caching.
|
||||
// This method consolidates the cache-lookup-parse-store pattern used across
|
||||
// different time parsing caches in the codebase.
|
||||
func (btc *BoundedTimeCache) ParseWithLayout(timeStr, layout string) (time.Time, error) {
|
||||
// Fast path: check cache
|
||||
if cached, ok := btc.Load(timeStr); ok {
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
// Parse and cache - only cache successful parses
|
||||
t, err := time.Parse(layout, timeStr)
|
||||
if err == nil {
|
||||
btc.Store(timeStr, t)
|
||||
}
|
||||
return t, err
|
||||
}
|
||||
|
||||
// BanRecordParser provides high-performance parsing of ban records
|
||||
type BanRecordParser struct {
|
||||
// Pools for zero-allocation parsing (goroutine-safe)
|
||||
@@ -167,17 +184,7 @@ func NewFastTimeCache(layout string) (*FastTimeCache, error) {
|
||||
|
||||
// ParseTimeOptimized parses time with minimal allocations
|
||||
func (ftc *FastTimeCache) ParseTimeOptimized(timeStr string) (time.Time, error) {
|
||||
// Fast path: check cache
|
||||
if cached, ok := ftc.parseCache.Load(timeStr); ok {
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
// Parse and cache - only cache successful parses
|
||||
t, err := time.Parse(ftc.layout, timeStr)
|
||||
if err == nil {
|
||||
ftc.parseCache.Store(timeStr, t)
|
||||
}
|
||||
return t, err
|
||||
return ftc.parseCache.ParseWithLayout(timeStr, ftc.layout)
|
||||
}
|
||||
|
||||
// BuildTimeStringOptimized builds time string with zero allocations using byte buffer
|
||||
|
||||
@@ -12,17 +12,6 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// setupBasicMockResponses sets up the basic responses needed for client initialization
|
||||
func setupBasicMockResponses(m *MockRunner) {
|
||||
m.SetResponse("fail2ban-client -V", []byte("Fail2Ban v0.11.0"))
|
||||
m.SetResponse("sudo fail2ban-client -V", []byte("Fail2Ban v0.11.0"))
|
||||
m.SetResponse("fail2ban-client ping", []byte("Server replied: pong"))
|
||||
m.SetResponse("sudo fail2ban-client ping", []byte("Server replied: pong"))
|
||||
// NewClient calls fetchJailsWithContext which runs status
|
||||
m.SetResponse("fail2ban-client status", []byte("Status\n|- Number of jail: 2\n`- Jail list: sshd, apache"))
|
||||
m.SetResponse("sudo fail2ban-client status", []byte("Status\n|- Number of jail: 2\n`- Jail list: sshd, apache"))
|
||||
}
|
||||
|
||||
// TestListJailsWithContext tests jail listing with context
|
||||
func TestListJailsWithContext(t *testing.T) {
|
||||
tests := []struct {
|
||||
@@ -35,11 +24,11 @@ func TestListJailsWithContext(t *testing.T) {
|
||||
{
|
||||
name: "successful jail listing",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
},
|
||||
timeout: 5 * time.Second,
|
||||
expectError: false,
|
||||
expectJails: []string{"sshd", "apache"}, // From setupBasicMockResponses
|
||||
expectJails: []string{"sshd", "apache"}, // From StandardMockSetup
|
||||
},
|
||||
}
|
||||
|
||||
@@ -83,7 +72,7 @@ func TestStatusAllWithContext(t *testing.T) {
|
||||
{
|
||||
name: "successful status all",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
m.SetResponse("fail2ban-client status", []byte("Status\n|- Number of jail: 1\n`- Jail list: sshd"))
|
||||
m.SetResponse("sudo fail2ban-client status", []byte("Status\n|- Number of jail: 1\n`- Jail list: sshd"))
|
||||
},
|
||||
@@ -94,7 +83,7 @@ func TestStatusAllWithContext(t *testing.T) {
|
||||
{
|
||||
name: "context timeout",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
m.SetResponse("fail2ban-client status", []byte("Status\n|- Number of jail: 1\n`- Jail list: sshd"))
|
||||
m.SetResponse("sudo fail2ban-client status", []byte("Status\n|- Number of jail: 1\n`- Jail list: sshd"))
|
||||
},
|
||||
@@ -145,7 +134,7 @@ func TestStatusJailWithContext(t *testing.T) {
|
||||
name: "successful status jail",
|
||||
jail: "sshd",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
m.SetResponse(
|
||||
"fail2ban-client status sshd",
|
||||
[]byte("Status for the jail: sshd\n|- Filter\n`- Currently banned: 0"),
|
||||
@@ -163,7 +152,7 @@ func TestStatusJailWithContext(t *testing.T) {
|
||||
name: "invalid jail name",
|
||||
jail: "invalid@jail",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
// Validation will fail before command execution
|
||||
},
|
||||
timeout: 5 * time.Second,
|
||||
@@ -173,7 +162,7 @@ func TestStatusJailWithContext(t *testing.T) {
|
||||
name: "context timeout",
|
||||
jail: "sshd",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
m.SetResponse(
|
||||
"fail2ban-client status sshd",
|
||||
[]byte("Status for the jail: sshd\n|- Filter\n`- Currently banned: 0"),
|
||||
@@ -234,7 +223,7 @@ func TestUnbanIPWithContext(t *testing.T) {
|
||||
ip: "192.168.1.100",
|
||||
jail: "sshd",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
m.SetResponse("fail2ban-client set sshd unbanip 192.168.1.100", []byte("0"))
|
||||
m.SetResponse("sudo fail2ban-client set sshd unbanip 192.168.1.100", []byte("0"))
|
||||
},
|
||||
@@ -247,7 +236,7 @@ func TestUnbanIPWithContext(t *testing.T) {
|
||||
ip: "192.168.1.100",
|
||||
jail: "sshd",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
m.SetResponse("fail2ban-client set sshd unbanip 192.168.1.100", []byte("1"))
|
||||
m.SetResponse("sudo fail2ban-client set sshd unbanip 192.168.1.100", []byte("1"))
|
||||
},
|
||||
@@ -260,7 +249,7 @@ func TestUnbanIPWithContext(t *testing.T) {
|
||||
ip: "invalid-ip",
|
||||
jail: "sshd",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
// Validation will fail before command execution
|
||||
},
|
||||
timeout: 5 * time.Second,
|
||||
@@ -271,7 +260,7 @@ func TestUnbanIPWithContext(t *testing.T) {
|
||||
ip: "192.168.1.100",
|
||||
jail: "invalid@jail",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
// Validation will fail before command execution
|
||||
},
|
||||
timeout: 5 * time.Second,
|
||||
@@ -282,7 +271,7 @@ func TestUnbanIPWithContext(t *testing.T) {
|
||||
ip: "192.168.1.100",
|
||||
jail: "sshd",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
m.SetResponse("fail2ban-client set sshd unbanip 192.168.1.100", []byte("0"))
|
||||
m.SetResponse("sudo fail2ban-client set sshd unbanip 192.168.1.100", []byte("0"))
|
||||
},
|
||||
@@ -332,7 +321,7 @@ func TestListFiltersWithContext(t *testing.T) {
|
||||
{
|
||||
name: "successful filter listing",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
// Mock responses not needed - uses file system
|
||||
},
|
||||
setupEnv: func() {
|
||||
@@ -345,7 +334,7 @@ func TestListFiltersWithContext(t *testing.T) {
|
||||
{
|
||||
name: "context timeout",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
// Not applicable for file system operation
|
||||
},
|
||||
setupEnv: func() {
|
||||
@@ -412,7 +401,7 @@ logpath = /var/log/auth.log
|
||||
name: "successful filter test",
|
||||
filter: "sshd",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
m.SetResponse(
|
||||
"fail2ban-regex /var/log/auth.log "+filepath.Join(tmpDir, "sshd.conf"),
|
||||
[]byte("Success: 0 matches"),
|
||||
@@ -429,7 +418,7 @@ logpath = /var/log/auth.log
|
||||
name: "invalid filter name",
|
||||
filter: "invalid@filter",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
// Validation will fail before command execution
|
||||
},
|
||||
timeout: 5 * time.Second,
|
||||
@@ -439,7 +428,7 @@ logpath = /var/log/auth.log
|
||||
name: "context timeout",
|
||||
filter: "sshd",
|
||||
setupMock: func(m *MockRunner) {
|
||||
setupBasicMockResponses(m)
|
||||
StandardMockSetup(m)
|
||||
m.SetResponse(
|
||||
"fail2ban-regex /var/log/auth.log "+filepath.Join(tmpDir, "sshd.conf"),
|
||||
[]byte("Success: 0 matches"),
|
||||
@@ -485,7 +474,7 @@ logpath = /var/log/auth.log
|
||||
// TestWithContextCancellation tests that all WithContext functions respect cancellation
|
||||
func TestWithContextCancellation(t *testing.T) {
|
||||
mock := NewMockRunner()
|
||||
setupBasicMockResponses(mock)
|
||||
StandardMockSetup(mock)
|
||||
SetRunner(mock)
|
||||
|
||||
client, err := NewClient("/var/log", "/etc/fail2ban/filter.d")
|
||||
@@ -520,7 +509,7 @@ func TestWithContextCancellation(t *testing.T) {
|
||||
// TestWithContextDeadline tests that all WithContext functions respect deadlines
|
||||
func TestWithContextDeadline(t *testing.T) {
|
||||
mock := NewMockRunner()
|
||||
setupBasicMockResponses(mock)
|
||||
StandardMockSetup(mock)
|
||||
SetRunner(mock)
|
||||
|
||||
client, err := NewClient("/var/log", "/etc/fail2ban/filter.d")
|
||||
@@ -576,7 +565,7 @@ func TestWithContextDeadline(t *testing.T) {
|
||||
// TestWithContextValidation tests that validation happens before context usage
|
||||
func TestWithContextValidation(t *testing.T) {
|
||||
mock := NewMockRunner()
|
||||
setupBasicMockResponses(mock)
|
||||
StandardMockSetup(mock)
|
||||
SetRunner(mock)
|
||||
|
||||
client, err := NewClient("/var/log", "/etc/fail2ban/filter.d")
|
||||
|
||||
@@ -2,30 +2,60 @@ package fail2ban
|
||||
|
||||
import "context"
|
||||
|
||||
// ContextWrappers provides a helper to automatically generate WithContext method wrappers.
|
||||
// This eliminates the need for duplicate WithContext implementations across different Client types.
|
||||
// Usage: embed this in your Client struct and call DefineContextWrappers to get automatic context support.
|
||||
type ContextWrappers struct{}
|
||||
// Context Wrapper Pattern
|
||||
//
|
||||
// This package provides generic helper functions for creating WithContext method wrappers.
|
||||
// These helpers eliminate boilerplate for methods that simply need context propagation
|
||||
// without additional logic.
|
||||
//
|
||||
// For simple methods (no validation, direct delegation to non-context version):
|
||||
//
|
||||
// func (c *Client) ListJailsWithContext(ctx context.Context) ([]string, error) {
|
||||
// return wrapWithContext0(c.ListJails)(ctx)
|
||||
// }
|
||||
//
|
||||
// For complex methods (validation, custom logic, different execution paths):
|
||||
// Implement the WithContext version directly with the required logic.
|
||||
//
|
||||
// Note: Code generation was evaluated but determined unnecessary because:
|
||||
// - Only 2 methods use the simple wrapper pattern
|
||||
// - Most WithContext methods require custom validation/logic
|
||||
// - The generic helpers below already solve the simple cases cleanly
|
||||
|
||||
// Helper functions to reduce boilerplate in WithContext implementations
|
||||
|
||||
// wrapWithContext0 wraps a function with no parameters to accept a context parameter.
|
||||
// It checks for context cancellation before invoking the underlying function.
|
||||
func wrapWithContext0[T any](fn func() (T, error)) func(context.Context) (T, error) {
|
||||
return func(_ context.Context) (T, error) {
|
||||
return func(ctx context.Context) (T, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
var zero T
|
||||
return zero, err
|
||||
}
|
||||
return fn()
|
||||
}
|
||||
}
|
||||
|
||||
// wrapWithContext1 wraps a function with one parameter to accept a context parameter.
|
||||
// It checks for context cancellation before invoking the underlying function.
|
||||
func wrapWithContext1[T any, A any](fn func(A) (T, error)) func(context.Context, A) (T, error) {
|
||||
return func(_ context.Context, a A) (T, error) {
|
||||
return func(ctx context.Context, a A) (T, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
var zero T
|
||||
return zero, err
|
||||
}
|
||||
return fn(a)
|
||||
}
|
||||
}
|
||||
|
||||
// wrapWithContext2 wraps a function with two parameters to accept a context parameter.
|
||||
// It checks for context cancellation before invoking the underlying function.
|
||||
func wrapWithContext2[T any, A any, B any](fn func(A, B) (T, error)) func(context.Context, A, B) (T, error) {
|
||||
return func(_ context.Context, a A, b B) (T, error) {
|
||||
return func(ctx context.Context, a A, b B) (T, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
var zero T
|
||||
return zero, err
|
||||
}
|
||||
return fn(a, b)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,8 +54,7 @@ func TestRunnerFunctions(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
|
||||
defer WithTestRunner(t, mockRunner)()
|
||||
|
||||
// Test RunnerCombinedOutput
|
||||
output, err := RunnerCombinedOutput("test-cmd", "arg1")
|
||||
|
||||
@@ -52,6 +52,18 @@ func SetFilterDir(dir string) {
|
||||
// OSRunner runs commands locally.
|
||||
type OSRunner struct{}
|
||||
|
||||
// validateCommandExecution validates command name and arguments before execution.
|
||||
// This helper consolidates the duplicate validation pattern used in command execution methods.
|
||||
func validateCommandExecution(ctx context.Context, name string, args []string) error {
|
||||
if err := CachedValidateCommand(ctx, name); err != nil {
|
||||
return fmt.Errorf(shared.ErrCommandValidationFailed, err)
|
||||
}
|
||||
if err := ValidateArgumentsWithContext(ctx, args); err != nil {
|
||||
return fmt.Errorf(shared.ErrArgumentValidationFailed, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CombinedOutput executes a command without sudo.
|
||||
func (r *OSRunner) CombinedOutput(name string, args ...string) ([]byte, error) {
|
||||
return r.CombinedOutputWithContext(context.Background(), name, args...)
|
||||
@@ -59,13 +71,8 @@ func (r *OSRunner) CombinedOutput(name string, args ...string) ([]byte, error) {
|
||||
|
||||
// CombinedOutputWithContext executes a command without sudo with context support.
|
||||
func (r *OSRunner) CombinedOutputWithContext(ctx context.Context, name string, args ...string) ([]byte, error) {
|
||||
// Validate command for security
|
||||
if err := CachedValidateCommand(ctx, name); err != nil {
|
||||
return nil, fmt.Errorf(shared.ErrCommandValidationFailed, err)
|
||||
}
|
||||
// Validate arguments for security
|
||||
if err := ValidateArgumentsWithContext(ctx, args); err != nil {
|
||||
return nil, fmt.Errorf(shared.ErrArgumentValidationFailed, err)
|
||||
if err := validateCommandExecution(ctx, name, args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return exec.CommandContext(ctx, name, args...).CombinedOutput()
|
||||
}
|
||||
@@ -77,13 +84,8 @@ func (r *OSRunner) CombinedOutputWithSudo(name string, args ...string) ([]byte,
|
||||
|
||||
// CombinedOutputWithSudoContext executes a command with sudo if needed, with context support.
|
||||
func (r *OSRunner) CombinedOutputWithSudoContext(ctx context.Context, name string, args ...string) ([]byte, error) {
|
||||
// Validate command for security
|
||||
if err := CachedValidateCommand(ctx, name); err != nil {
|
||||
return nil, fmt.Errorf(shared.ErrCommandValidationFailed, err)
|
||||
}
|
||||
// Validate arguments for security
|
||||
if err := ValidateArgumentsWithContext(ctx, args); err != nil {
|
||||
return nil, fmt.Errorf(shared.ErrArgumentValidationFailed, err)
|
||||
if err := validateCommandExecution(ctx, name, args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
checker := GetSudoChecker()
|
||||
@@ -158,30 +160,38 @@ func RunnerCombinedOutputWithSudo(name string, args ...string) ([]byte, error) {
|
||||
return output, err
|
||||
}
|
||||
|
||||
// runWithTimerContext is a helper that consolidates the common pattern of
|
||||
// creating a timer, getting the runner, executing a command, and finishing the timer.
|
||||
// This reduces code duplication between RunnerCombinedOutputWithContext and RunnerCombinedOutputWithSudoContext.
|
||||
func runWithTimerContext(
|
||||
ctx context.Context,
|
||||
opName, name string,
|
||||
args []string,
|
||||
runFn func(Runner, context.Context, string, ...string) ([]byte, error),
|
||||
) ([]byte, error) {
|
||||
timer := NewTimedOperation(opName, name, args...)
|
||||
runner := GetRunner()
|
||||
output, err := runFn(runner, ctx, name, args...)
|
||||
timer.FinishWithContext(ctx, err)
|
||||
return output, err
|
||||
}
|
||||
|
||||
// RunnerCombinedOutputWithContext invokes the runner for a command with context support.
|
||||
// RunnerCombinedOutputWithContext executes a command with context using the global runner.
|
||||
func RunnerCombinedOutputWithContext(ctx context.Context, name string, args ...string) ([]byte, error) {
|
||||
timer := NewTimedOperation("RunnerCombinedOutputWithContext", name, args...)
|
||||
|
||||
runner := GetRunner()
|
||||
|
||||
output, err := runner.CombinedOutputWithContext(ctx, name, args...)
|
||||
timer.FinishWithContext(ctx, err)
|
||||
|
||||
return output, err
|
||||
return runWithTimerContext(ctx, "RunnerCombinedOutputWithContext", name, args,
|
||||
func(r Runner, c context.Context, n string, a ...string) ([]byte, error) {
|
||||
return r.CombinedOutputWithContext(c, n, a...)
|
||||
})
|
||||
}
|
||||
|
||||
// RunnerCombinedOutputWithSudoContext invokes the runner for a command with sudo and context support.
|
||||
// RunnerCombinedOutputWithSudoContext executes a command with sudo privileges and context using the global runner.
|
||||
func RunnerCombinedOutputWithSudoContext(ctx context.Context, name string, args ...string) ([]byte, error) {
|
||||
timer := NewTimedOperation("RunnerCombinedOutputWithSudoContext", name, args...)
|
||||
|
||||
runner := GetRunner()
|
||||
|
||||
output, err := runner.CombinedOutputWithSudoContext(ctx, name, args...)
|
||||
timer.FinishWithContext(ctx, err)
|
||||
|
||||
return output, err
|
||||
return runWithTimerContext(ctx, "RunnerCombinedOutputWithSudoContext", name, args,
|
||||
func(r Runner, c context.Context, n string, a ...string) ([]byte, error) {
|
||||
return r.CombinedOutputWithSudoContext(c, n, a...)
|
||||
})
|
||||
}
|
||||
|
||||
// MockRunner is a simple mock for Runner, used in unit tests.
|
||||
@@ -274,6 +284,17 @@ func (m *MockRunner) CombinedOutputWithSudo(name string, args ...string) ([]byte
|
||||
return m.CombinedOutput(name, args...)
|
||||
}
|
||||
|
||||
// withContextCheck wraps an operation with context cancellation check.
|
||||
// This helper consolidates the duplicate context cancellation pattern.
|
||||
func withContextCheck(ctx context.Context, fn func() ([]byte, error)) ([]byte, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
}
|
||||
return fn()
|
||||
}
|
||||
|
||||
// SetResponse sets a response for a command.
|
||||
func (m *MockRunner) SetResponse(cmd string, response []byte) {
|
||||
m.mu.Lock()
|
||||
@@ -298,30 +319,50 @@ func (m *MockRunner) GetCalls() []string {
|
||||
return calls
|
||||
}
|
||||
|
||||
// SetupStandardResponses configures comprehensive standard responses for testing.
|
||||
// This eliminates the need for repetitive SetResponse calls in individual tests.
|
||||
func (m *MockRunner) SetupStandardResponses() {
|
||||
StandardMockSetup(m)
|
||||
}
|
||||
|
||||
// SetupJailResponses configures responses for a specific jail.
|
||||
// This is useful for tests that focus on a single jail's behavior.
|
||||
func (m *MockRunner) SetupJailResponses(jail string) {
|
||||
statusResponse := fmt.Sprintf("Status for the jail: %s\n|- Filter\n| |- Currently failed:\t0\n| "+
|
||||
"|- Total failed:\t5\n| `- File list:\t/var/log/auth.log\n`- Actions\n "+
|
||||
"|- Currently banned:\t1\n |- Total banned:\t2\n `- Banned IP list:\t192.168.1.100", jail)
|
||||
|
||||
m.SetResponse(fmt.Sprintf("fail2ban-client status %s", jail), []byte(statusResponse))
|
||||
m.SetResponse(fmt.Sprintf("sudo fail2ban-client status %s", jail), []byte(statusResponse))
|
||||
|
||||
// Common ban/unban operations for the jail (use success status, not already-processed)
|
||||
m.SetResponse(fmt.Sprintf("fail2ban-client set %s banip 192.168.1.100", jail), []byte(shared.Fail2BanStatusSuccess))
|
||||
m.SetResponse(
|
||||
fmt.Sprintf("sudo fail2ban-client set %s banip 192.168.1.100", jail),
|
||||
[]byte(shared.Fail2BanStatusSuccess),
|
||||
)
|
||||
m.SetResponse(
|
||||
fmt.Sprintf("fail2ban-client set %s unbanip 192.168.1.100", jail),
|
||||
[]byte(shared.Fail2BanStatusSuccess),
|
||||
)
|
||||
m.SetResponse(
|
||||
fmt.Sprintf("sudo fail2ban-client set %s unbanip 192.168.1.100", jail),
|
||||
[]byte(shared.Fail2BanStatusSuccess),
|
||||
)
|
||||
}
|
||||
|
||||
// CombinedOutputWithContext returns a mocked response or error for a command with context support.
|
||||
func (m *MockRunner) CombinedOutputWithContext(ctx context.Context, name string, args ...string) ([]byte, error) {
|
||||
// Check if context is canceled
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
// Delegate to the non-context version for simplicity in tests
|
||||
return m.CombinedOutput(name, args...)
|
||||
return withContextCheck(ctx, func() ([]byte, error) {
|
||||
return m.CombinedOutput(name, args...)
|
||||
})
|
||||
}
|
||||
|
||||
// CombinedOutputWithSudoContext returns a mocked response for sudo commands with context support.
|
||||
func (m *MockRunner) CombinedOutputWithSudoContext(ctx context.Context, name string, args ...string) ([]byte, error) {
|
||||
// Check if context is canceled
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
// Delegate to the non-context version for simplicity in tests
|
||||
return m.CombinedOutputWithSudo(name, args...)
|
||||
return withContextCheck(ctx, func() ([]byte, error) {
|
||||
return m.CombinedOutputWithSudo(name, args...)
|
||||
})
|
||||
}
|
||||
|
||||
func (c *RealClient) fetchJailsWithContext(ctx context.Context) ([]string, error) {
|
||||
@@ -487,8 +528,12 @@ func (c *RealClient) StatusJailWithContext(ctx context.Context, jail string) (st
|
||||
return string(out), err
|
||||
}
|
||||
|
||||
// BanIPWithContext bans an IP address in the specified jail with context support.
|
||||
func (c *RealClient) BanIPWithContext(ctx context.Context, ip, jail string) (int, error) {
|
||||
// executeIPActionWithContext executes a ban/unban IP action with validation and response parsing.
|
||||
// It returns (0, nil) for success, (1, nil) if already processed, or an error.
|
||||
func (c *RealClient) executeIPActionWithContext(
|
||||
ctx context.Context,
|
||||
ip, jail, action, errorTemplate string,
|
||||
) (int, error) {
|
||||
if err := CachedValidateIP(ctx, ip); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -497,10 +542,9 @@ func (c *RealClient) BanIPWithContext(ctx context.Context, ip, jail string) (int
|
||||
}
|
||||
|
||||
currentRunner := GetRunner()
|
||||
|
||||
out, err := currentRunner.CombinedOutputWithSudoContext(ctx, c.Path, shared.ActionSet, jail, shared.ActionBanIP, ip)
|
||||
out, err := currentRunner.CombinedOutputWithSudoContext(ctx, c.Path, shared.ActionSet, jail, action, ip)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf(shared.ErrFailedToBanIP, ip, jail, err)
|
||||
return 0, fmt.Errorf(errorTemplate, ip, jail, err)
|
||||
}
|
||||
code := strings.TrimSpace(string(out))
|
||||
if code == shared.Fail2BanStatusSuccess {
|
||||
@@ -512,36 +556,14 @@ func (c *RealClient) BanIPWithContext(ctx context.Context, ip, jail string) (int
|
||||
return 0, fmt.Errorf(shared.ErrUnexpectedOutput, code)
|
||||
}
|
||||
|
||||
// BanIPWithContext bans an IP address in the specified jail with context support.
|
||||
func (c *RealClient) BanIPWithContext(ctx context.Context, ip, jail string) (int, error) {
|
||||
return c.executeIPActionWithContext(ctx, ip, jail, shared.ActionBanIP, shared.ErrFailedToBanIP)
|
||||
}
|
||||
|
||||
// UnbanIPWithContext unbans an IP address from the specified jail with context support.
|
||||
func (c *RealClient) UnbanIPWithContext(ctx context.Context, ip, jail string) (int, error) {
|
||||
if err := CachedValidateIP(ctx, ip); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := CachedValidateJail(ctx, jail); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
currentRunner := GetRunner()
|
||||
|
||||
out, err := currentRunner.CombinedOutputWithSudoContext(
|
||||
ctx,
|
||||
c.Path,
|
||||
shared.ActionSet,
|
||||
jail,
|
||||
shared.ActionUnbanIP,
|
||||
ip,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf(shared.ErrFailedToUnbanIP, ip, jail, err)
|
||||
}
|
||||
code := strings.TrimSpace(string(out))
|
||||
if code == shared.Fail2BanStatusSuccess {
|
||||
return 0, nil
|
||||
}
|
||||
if code == shared.Fail2BanStatusAlreadyProcessed {
|
||||
return 1, nil
|
||||
}
|
||||
return 0, fmt.Errorf(shared.ErrUnexpectedOutput, code)
|
||||
return c.executeIPActionWithContext(ctx, ip, jail, shared.ActionUnbanIP, shared.ErrFailedToUnbanIP)
|
||||
}
|
||||
|
||||
// BannedInWithContext returns a list of jails where the specified IP address is currently banned with context support.
|
||||
|
||||
@@ -10,8 +10,7 @@ import (
|
||||
// TestRunnerConcurrentAccess tests that concurrent access to the runner
|
||||
// is safe and doesn't cause race conditions.
|
||||
func TestRunnerConcurrentAccess(t *testing.T) {
|
||||
original := GetRunner()
|
||||
defer SetRunner(original)
|
||||
defer WithTestRunner(t, GetRunner())()
|
||||
|
||||
const numGoroutines = 100
|
||||
const numOperations = 50
|
||||
@@ -53,12 +52,9 @@ func TestRunnerConcurrentAccess(t *testing.T) {
|
||||
// TestRunnerCombinedOutputConcurrency tests that concurrent calls to
|
||||
// RunnerCombinedOutput are safe.
|
||||
func TestRunnerCombinedOutputConcurrency(t *testing.T) {
|
||||
original := GetRunner()
|
||||
defer SetRunner(original)
|
||||
|
||||
mockRunner := NewMockRunner()
|
||||
defer WithTestRunner(t, mockRunner)()
|
||||
mockRunner.SetResponse("echo test", []byte("test output"))
|
||||
SetRunner(mockRunner)
|
||||
|
||||
const numGoroutines = 50
|
||||
var wg sync.WaitGroup
|
||||
@@ -120,12 +116,10 @@ func TestRunnerCombinedOutputWithSudoConcurrency(t *testing.T) {
|
||||
// TestMixedConcurrentOperations tests mixed concurrent operations including
|
||||
// setting runners and executing commands.
|
||||
func TestMixedConcurrentOperations(t *testing.T) {
|
||||
original := GetRunner()
|
||||
defer SetRunner(original)
|
||||
|
||||
// Set up a single shared MockRunner with all required responses
|
||||
// This avoids race conditions from multiple goroutines setting different runners
|
||||
sharedMockRunner := NewMockRunner()
|
||||
defer WithTestRunner(t, sharedMockRunner)()
|
||||
|
||||
// Set up responses for valid fail2ban commands to avoid validation errors
|
||||
sharedMockRunner.SetResponse("fail2ban-client status", []byte("Status: OK"))
|
||||
@@ -135,8 +129,6 @@ func TestMixedConcurrentOperations(t *testing.T) {
|
||||
sharedMockRunner.SetResponse("sudo fail2ban-client status", []byte("Status: OK"))
|
||||
sharedMockRunner.SetResponse("sudo fail2ban-client -V", []byte("Version: 1.0.0"))
|
||||
|
||||
SetRunner(sharedMockRunner)
|
||||
|
||||
const numGoroutines = 30
|
||||
var wg sync.WaitGroup
|
||||
|
||||
@@ -203,8 +195,7 @@ func TestMixedConcurrentOperations(t *testing.T) {
|
||||
// TestRunnerManagerLockOrdering verifies there are no deadlocks in the
|
||||
// runner manager's lock ordering.
|
||||
func TestRunnerManagerLockOrdering(t *testing.T) {
|
||||
original := GetRunner()
|
||||
defer SetRunner(original)
|
||||
defer WithTestRunner(t, GetRunner())()
|
||||
|
||||
// This test specifically looks for deadlocks by creating scenarios
|
||||
// where multiple goroutines could potentially deadlock if locks
|
||||
@@ -245,13 +236,10 @@ func TestRunnerManagerLockOrdering(t *testing.T) {
|
||||
// TestRunnerStateConsistency verifies that the runner state remains
|
||||
// consistent across concurrent operations.
|
||||
func TestRunnerStateConsistency(t *testing.T) {
|
||||
original := GetRunner()
|
||||
defer SetRunner(original)
|
||||
|
||||
// Set initial state
|
||||
initialRunner := NewMockRunner()
|
||||
initialRunner.SetResponse("initial", []byte("initial response"))
|
||||
SetRunner(initialRunner)
|
||||
defer WithTestRunner(t, initialRunner)()
|
||||
|
||||
const numReaders = 50
|
||||
const numWriters = 10
|
||||
|
||||
@@ -182,7 +182,10 @@ func TestBanIP(t *testing.T) {
|
||||
fmt.Errorf("command failed"),
|
||||
)
|
||||
} else {
|
||||
mock.SetResponse(fmt.Sprintf("sudo fail2ban-client set %s banip %s", tt.jail, tt.ip), []byte(tt.mockResponse))
|
||||
mock.SetResponse(
|
||||
fmt.Sprintf("sudo fail2ban-client set %s banip %s", tt.jail, tt.ip),
|
||||
[]byte(tt.mockResponse),
|
||||
)
|
||||
}
|
||||
|
||||
client, err := NewClient(shared.DefaultLogDir, shared.DefaultFilterDir)
|
||||
|
||||
@@ -11,6 +11,32 @@ import (
|
||||
"github.com/ivuorinen/f2b/shared"
|
||||
)
|
||||
|
||||
// safeCloseFile closes a file and logs any error.
|
||||
// This helper consolidates the duplicate close-and-log pattern.
|
||||
func safeCloseFile(f *os.File, path string) {
|
||||
if f == nil {
|
||||
return
|
||||
}
|
||||
if closeErr := f.Close(); closeErr != nil {
|
||||
getLogger().WithError(closeErr).
|
||||
WithField(shared.LogFieldFile, path).
|
||||
Warn("Failed to close file")
|
||||
}
|
||||
}
|
||||
|
||||
// safeCloseReader closes a reader and logs any error.
|
||||
// This helper consolidates the duplicate close-and-log pattern for io.ReadCloser.
|
||||
func safeCloseReader(r io.ReadCloser, path string) {
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
if closeErr := r.Close(); closeErr != nil {
|
||||
getLogger().WithError(closeErr).
|
||||
WithField(shared.LogFieldFile, path).
|
||||
Warn("Failed to close reader")
|
||||
}
|
||||
}
|
||||
|
||||
// GzipDetector provides utilities for detecting and handling gzip-compressed files
|
||||
type GzipDetector struct{}
|
||||
|
||||
@@ -38,13 +64,7 @@ func (gd *GzipDetector) hasGzipMagicBytes(path string) (bool, error) {
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer func() {
|
||||
if closeErr := f.Close(); closeErr != nil {
|
||||
getLogger().WithError(closeErr).
|
||||
WithField(shared.LogFieldFile, path).
|
||||
Warn("Failed to close file in gzip magic byte check")
|
||||
}
|
||||
}()
|
||||
defer safeCloseFile(f, path)
|
||||
|
||||
var magic [2]byte
|
||||
n, err := f.Read(magic[:])
|
||||
@@ -70,11 +90,7 @@ func (gd *GzipDetector) OpenGzipAwareReader(path string) (io.ReadCloser, error)
|
||||
|
||||
isGzip, err := gd.IsGzipFile(path)
|
||||
if err != nil {
|
||||
if closeErr := f.Close(); closeErr != nil {
|
||||
getLogger().WithError(closeErr).
|
||||
WithField(shared.LogFieldFile, path).
|
||||
Warn("Failed to close file during error handling")
|
||||
}
|
||||
safeCloseFile(f, path)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -82,21 +98,13 @@ func (gd *GzipDetector) OpenGzipAwareReader(path string) (io.ReadCloser, error)
|
||||
// For gzip files, we need to position at the beginning and create gzip reader
|
||||
_, err = f.Seek(0, io.SeekStart)
|
||||
if err != nil {
|
||||
if closeErr := f.Close(); closeErr != nil {
|
||||
getLogger().WithError(closeErr).
|
||||
WithField(shared.LogFieldFile, path).
|
||||
Warn("Failed to close file during seek error handling")
|
||||
}
|
||||
safeCloseFile(f, path)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
gz, err := gzip.NewReader(f)
|
||||
if err != nil {
|
||||
if closeErr := f.Close(); closeErr != nil {
|
||||
getLogger().WithError(closeErr).
|
||||
WithField(shared.LogFieldFile, path).
|
||||
Warn("Failed to close file during gzip reader error handling")
|
||||
}
|
||||
safeCloseFile(f, path)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -128,11 +136,7 @@ func (gd *GzipDetector) CreateGzipAwareScannerWithBuffer(path string, maxLineSiz
|
||||
}
|
||||
|
||||
cleanup := func() {
|
||||
if err := reader.Close(); err != nil {
|
||||
getLogger().WithError(err).
|
||||
WithField(shared.LogFieldFile, path).
|
||||
Warn("Failed to close reader during cleanup")
|
||||
}
|
||||
safeCloseReader(reader, path)
|
||||
}
|
||||
|
||||
return scanner, cleanup, nil
|
||||
|
||||
@@ -792,20 +792,23 @@ func ValidateLogPath(ctx context.Context, path string, logDir string) (string, e
|
||||
return ValidatePathWithSecurity(path, config)
|
||||
}
|
||||
|
||||
// validateClientPath is a generic helper for client path validation.
|
||||
// It reduces duplication between ValidateClientLogPath and ValidateClientFilterPath.
|
||||
func validateClientPath(ctx context.Context, path string, configFn func() PathSecurityConfig) (string, error) {
|
||||
_ = ctx // Context not currently used by ValidatePathWithSecurity
|
||||
return ValidatePathWithSecurity(path, configFn())
|
||||
}
|
||||
|
||||
// ValidateClientLogPath validates log directory path for client initialization
|
||||
// Context parameter accepted for API consistency but not currently used
|
||||
func ValidateClientLogPath(ctx context.Context, logDir string) (string, error) {
|
||||
_ = ctx // Context not currently used by ValidatePathWithSecurity
|
||||
config := CreateLogPathConfig()
|
||||
return ValidatePathWithSecurity(logDir, config)
|
||||
return validateClientPath(ctx, logDir, CreateLogPathConfig)
|
||||
}
|
||||
|
||||
// ValidateClientFilterPath validates filter directory path for client initialization
|
||||
// Context parameter accepted for API consistency but not currently used
|
||||
func ValidateClientFilterPath(ctx context.Context, filterDir string) (string, error) {
|
||||
_ = ctx // Context not currently used by ValidatePathWithSecurity
|
||||
config := CreateFilterPathConfig()
|
||||
return ValidatePathWithSecurity(filterDir, config)
|
||||
return validateClientPath(ctx, filterDir, CreateFilterPathConfig)
|
||||
}
|
||||
|
||||
// ValidateFilterName validates a filter name for path traversal prevention.
|
||||
|
||||
@@ -75,18 +75,14 @@ func TestValidateFilterName(t *testing.T) {
|
||||
|
||||
// TestGetLogLinesWrapper tests the GetLogLines wrapper function
|
||||
func TestGetLogLinesWrapper(t *testing.T) {
|
||||
// Save and restore original runner
|
||||
originalRunner := GetRunner()
|
||||
defer SetRunner(originalRunner)
|
||||
|
||||
mockRunner := NewMockRunner()
|
||||
defer WithTestRunner(t, mockRunner)()
|
||||
mockRunner.SetResponse("fail2ban-client -V", []byte("Fail2Ban v0.11.0"))
|
||||
mockRunner.SetResponse("sudo fail2ban-client -V", []byte("Fail2Ban v0.11.0"))
|
||||
mockRunner.SetResponse("fail2ban-client ping", []byte("Server replied: pong"))
|
||||
mockRunner.SetResponse("sudo fail2ban-client ping", []byte("Server replied: pong"))
|
||||
mockRunner.SetResponse("fail2ban-client status", []byte("Status\n|- Number of jail: 1\n`- Jail list: sshd"))
|
||||
mockRunner.SetResponse("sudo fail2ban-client status", []byte("Status\n|- Number of jail: 1\n`- Jail list: sshd"))
|
||||
SetRunner(mockRunner)
|
||||
|
||||
// Create temporary log directory
|
||||
tmpDir := t.TempDir()
|
||||
@@ -107,9 +103,7 @@ func TestGetLogLinesWrapper(t *testing.T) {
|
||||
|
||||
// TestBanIPWithContext tests the BanIPWithContext function
|
||||
func TestBanIPWithContext(t *testing.T) {
|
||||
// Save and restore original runner
|
||||
originalRunner := GetRunner()
|
||||
defer SetRunner(originalRunner)
|
||||
defer WithTestRunner(t, GetRunner())()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -160,18 +154,14 @@ func TestBanIPWithContext(t *testing.T) {
|
||||
|
||||
// TestGetLogLinesWithLimitAndContext tests the GetLogLinesWithLimitAndContext function
|
||||
func TestGetLogLinesWithLimitAndContext(t *testing.T) {
|
||||
// Save and restore original runner
|
||||
originalRunner := GetRunner()
|
||||
defer SetRunner(originalRunner)
|
||||
|
||||
mockRunner := NewMockRunner()
|
||||
defer WithTestRunner(t, mockRunner)()
|
||||
mockRunner.SetResponse("fail2ban-client -V", []byte("Fail2Ban v0.11.0"))
|
||||
mockRunner.SetResponse("sudo fail2ban-client -V", []byte("Fail2Ban v0.11.0"))
|
||||
mockRunner.SetResponse("fail2ban-client ping", []byte("Server replied: pong"))
|
||||
mockRunner.SetResponse("sudo fail2ban-client ping", []byte("Server replied: pong"))
|
||||
mockRunner.SetResponse("fail2ban-client status", []byte("Status\n|- Number of jail: 1\n`- Jail list: sshd"))
|
||||
mockRunner.SetResponse("sudo fail2ban-client status", []byte("Status\n|- Number of jail: 1\n`- Jail list: sshd"))
|
||||
SetRunner(mockRunner)
|
||||
|
||||
// Create temporary log directory
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
@@ -2,14 +2,47 @@ package fail2ban
|
||||
|
||||
import "github.com/sirupsen/logrus"
|
||||
|
||||
// logrusAdapter wraps logrus to implement our decoupled LoggerInterface
|
||||
type logrusAdapter struct {
|
||||
// loggerCore provides common logging methods that delegate to a logrus.Entry.
|
||||
// This type is embedded in both logrusAdapter and logrusEntryAdapter to
|
||||
// eliminate duplicate method implementations.
|
||||
type loggerCore struct {
|
||||
entry *logrus.Entry
|
||||
}
|
||||
|
||||
// logrusEntryAdapter wraps logrus.Entry to implement LoggerEntry
|
||||
// Debug logs a debug-level message.
|
||||
func (c *loggerCore) Debug(args ...interface{}) { c.entry.Debug(args...) }
|
||||
|
||||
// Info logs an info-level message.
|
||||
func (c *loggerCore) Info(args ...interface{}) { c.entry.Info(args...) }
|
||||
|
||||
// Warn logs a warning-level message.
|
||||
func (c *loggerCore) Warn(args ...interface{}) { c.entry.Warn(args...) }
|
||||
|
||||
// Error logs an error-level message.
|
||||
func (c *loggerCore) Error(args ...interface{}) { c.entry.Error(args...) }
|
||||
|
||||
// Debugf logs a formatted debug-level message.
|
||||
func (c *loggerCore) Debugf(format string, args ...interface{}) { c.entry.Debugf(format, args...) }
|
||||
|
||||
// Infof logs a formatted info-level message.
|
||||
func (c *loggerCore) Infof(format string, args ...interface{}) { c.entry.Infof(format, args...) }
|
||||
|
||||
// Warnf logs a formatted warning-level message.
|
||||
func (c *loggerCore) Warnf(format string, args ...interface{}) { c.entry.Warnf(format, args...) }
|
||||
|
||||
// Errorf logs a formatted error-level message.
|
||||
func (c *loggerCore) Errorf(format string, args ...interface{}) { c.entry.Errorf(format, args...) }
|
||||
|
||||
// logrusAdapter wraps logrus to implement our decoupled LoggerInterface.
|
||||
// It embeds loggerCore to provide the 8 standard logging methods.
|
||||
type logrusAdapter struct {
|
||||
loggerCore // embeds Debug, Info, Warn, Error, Debugf, Infof, Warnf, Errorf
|
||||
}
|
||||
|
||||
// logrusEntryAdapter wraps logrus.Entry to implement LoggerEntry.
|
||||
// It embeds loggerCore to provide the 8 standard logging methods.
|
||||
type logrusEntryAdapter struct {
|
||||
entry *logrus.Entry
|
||||
loggerCore // embeds Debug, Info, Warn, Error, Debugf, Infof, Warnf, Errorf
|
||||
}
|
||||
|
||||
// Ensure logrusAdapter implements LoggerInterface
|
||||
@@ -23,117 +56,37 @@ func NewLogrusAdapter(logger *logrus.Logger) LoggerInterface {
|
||||
if logger == nil {
|
||||
logger = logrus.StandardLogger()
|
||||
}
|
||||
return &logrusAdapter{entry: logrus.NewEntry(logger)}
|
||||
return &logrusAdapter{loggerCore: loggerCore{entry: logrus.NewEntry(logger)}}
|
||||
}
|
||||
|
||||
// WithField implements LoggerInterface
|
||||
func (l *logrusAdapter) WithField(key string, value interface{}) LoggerEntry {
|
||||
return &logrusEntryAdapter{entry: l.entry.WithField(key, value)}
|
||||
return &logrusEntryAdapter{loggerCore: loggerCore{entry: l.entry.WithField(key, value)}}
|
||||
}
|
||||
|
||||
// WithFields implements LoggerInterface
|
||||
func (l *logrusAdapter) WithFields(fields Fields) LoggerEntry {
|
||||
return &logrusEntryAdapter{entry: l.entry.WithFields(logrus.Fields(fields))}
|
||||
return &logrusEntryAdapter{loggerCore: loggerCore{entry: l.entry.WithFields(logrus.Fields(fields))}}
|
||||
}
|
||||
|
||||
// WithError implements LoggerInterface
|
||||
func (l *logrusAdapter) WithError(err error) LoggerEntry {
|
||||
return &logrusEntryAdapter{entry: l.entry.WithError(err)}
|
||||
}
|
||||
|
||||
// Debug implements LoggerInterface
|
||||
func (l *logrusAdapter) Debug(args ...interface{}) {
|
||||
l.entry.Debug(args...)
|
||||
}
|
||||
|
||||
// Info implements LoggerInterface
|
||||
func (l *logrusAdapter) Info(args ...interface{}) {
|
||||
l.entry.Info(args...)
|
||||
}
|
||||
|
||||
// Warn implements LoggerInterface
|
||||
func (l *logrusAdapter) Warn(args ...interface{}) {
|
||||
l.entry.Warn(args...)
|
||||
}
|
||||
|
||||
// Error implements LoggerInterface
|
||||
func (l *logrusAdapter) Error(args ...interface{}) {
|
||||
l.entry.Error(args...)
|
||||
}
|
||||
|
||||
// Debugf implements LoggerInterface
|
||||
func (l *logrusAdapter) Debugf(format string, args ...interface{}) {
|
||||
l.entry.Debugf(format, args...)
|
||||
}
|
||||
|
||||
// Infof implements LoggerInterface
|
||||
func (l *logrusAdapter) Infof(format string, args ...interface{}) {
|
||||
l.entry.Infof(format, args...)
|
||||
}
|
||||
|
||||
// Warnf implements LoggerInterface
|
||||
func (l *logrusAdapter) Warnf(format string, args ...interface{}) {
|
||||
l.entry.Warnf(format, args...)
|
||||
}
|
||||
|
||||
// Errorf implements LoggerInterface
|
||||
func (l *logrusAdapter) Errorf(format string, args ...interface{}) {
|
||||
l.entry.Errorf(format, args...)
|
||||
return &logrusEntryAdapter{loggerCore: loggerCore{entry: l.entry.WithError(err)}}
|
||||
}
|
||||
|
||||
// LoggerEntry implementation for logrusEntryAdapter
|
||||
|
||||
// WithField implements LoggerEntry
|
||||
func (e *logrusEntryAdapter) WithField(key string, value interface{}) LoggerEntry {
|
||||
return &logrusEntryAdapter{entry: e.entry.WithField(key, value)}
|
||||
return &logrusEntryAdapter{loggerCore: loggerCore{entry: e.entry.WithField(key, value)}}
|
||||
}
|
||||
|
||||
// WithFields implements LoggerEntry
|
||||
func (e *logrusEntryAdapter) WithFields(fields Fields) LoggerEntry {
|
||||
return &logrusEntryAdapter{entry: e.entry.WithFields(logrus.Fields(fields))}
|
||||
return &logrusEntryAdapter{loggerCore: loggerCore{entry: e.entry.WithFields(logrus.Fields(fields))}}
|
||||
}
|
||||
|
||||
// WithError implements LoggerEntry
|
||||
func (e *logrusEntryAdapter) WithError(err error) LoggerEntry {
|
||||
return &logrusEntryAdapter{entry: e.entry.WithError(err)}
|
||||
}
|
||||
|
||||
// Debug implements LoggerEntry
|
||||
func (e *logrusEntryAdapter) Debug(args ...interface{}) {
|
||||
e.entry.Debug(args...)
|
||||
}
|
||||
|
||||
// Info implements LoggerEntry
|
||||
func (e *logrusEntryAdapter) Info(args ...interface{}) {
|
||||
e.entry.Info(args...)
|
||||
}
|
||||
|
||||
// Warn implements LoggerEntry
|
||||
func (e *logrusEntryAdapter) Warn(args ...interface{}) {
|
||||
e.entry.Warn(args...)
|
||||
}
|
||||
|
||||
// Error implements LoggerEntry
|
||||
func (e *logrusEntryAdapter) Error(args ...interface{}) {
|
||||
e.entry.Error(args...)
|
||||
}
|
||||
|
||||
// Debugf implements LoggerEntry
|
||||
func (e *logrusEntryAdapter) Debugf(format string, args ...interface{}) {
|
||||
e.entry.Debugf(format, args...)
|
||||
}
|
||||
|
||||
// Infof implements LoggerEntry
|
||||
func (e *logrusEntryAdapter) Infof(format string, args ...interface{}) {
|
||||
e.entry.Infof(format, args...)
|
||||
}
|
||||
|
||||
// Warnf implements LoggerEntry
|
||||
func (e *logrusEntryAdapter) Warnf(format string, args ...interface{}) {
|
||||
e.entry.Warnf(format, args...)
|
||||
}
|
||||
|
||||
// Errorf implements LoggerEntry
|
||||
func (e *logrusEntryAdapter) Errorf(format string, args ...interface{}) {
|
||||
e.entry.Errorf(format, args...)
|
||||
return &logrusEntryAdapter{loggerCore: loggerCore{entry: e.entry.WithError(err)}}
|
||||
}
|
||||
|
||||
@@ -377,11 +377,7 @@ func readLogFile(path string) ([]byte, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
if cerr := reader.Close(); cerr != nil {
|
||||
getLogger().WithError(cerr).Error("failed to close log file")
|
||||
}
|
||||
}()
|
||||
defer safeCloseReader(reader, cleanPath)
|
||||
|
||||
return io.ReadAll(reader)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,17 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// setNestedMapValue sets a value in a nested map[string]map[string]T structure with mutex protection.
|
||||
// It initializes the inner map if nil.
|
||||
func setNestedMapValue[T any](mu *sync.Mutex, mp map[string]map[string]T, jail, ip string, value T) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if mp[jail] == nil {
|
||||
mp[jail] = make(map[string]T)
|
||||
}
|
||||
mp[jail][ip] = value
|
||||
}
|
||||
|
||||
// MockClient is a stateful, thread-safe mock implementation of the Client interface for testing.
|
||||
type MockClient struct {
|
||||
mu sync.Mutex
|
||||
@@ -286,42 +297,22 @@ func (m *MockClient) Reset() {
|
||||
|
||||
// SetBanError configures an error to return for BanIP(ip, jail).
|
||||
func (m *MockClient) SetBanError(jail, ip string, err error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.BanErrors[jail] == nil {
|
||||
m.BanErrors[jail] = make(map[string]error)
|
||||
}
|
||||
m.BanErrors[jail][ip] = err
|
||||
setNestedMapValue(&m.mu, m.BanErrors, jail, ip, err)
|
||||
}
|
||||
|
||||
// SetBanResult configures a result code to return for BanIP(ip, jail).
|
||||
func (m *MockClient) SetBanResult(jail, ip string, result int) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.BanResults[jail] == nil {
|
||||
m.BanResults[jail] = make(map[string]int)
|
||||
}
|
||||
m.BanResults[jail][ip] = result
|
||||
setNestedMapValue(&m.mu, m.BanResults, jail, ip, result)
|
||||
}
|
||||
|
||||
// SetUnbanError configures an error to return for UnbanIP(ip, jail).
|
||||
func (m *MockClient) SetUnbanError(jail, ip string, err error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.UnbanErrors[jail] == nil {
|
||||
m.UnbanErrors[jail] = make(map[string]error)
|
||||
}
|
||||
m.UnbanErrors[jail][ip] = err
|
||||
setNestedMapValue(&m.mu, m.UnbanErrors, jail, ip, err)
|
||||
}
|
||||
|
||||
// SetUnbanResult configures a result code to return for UnbanIP(ip, jail).
|
||||
func (m *MockClient) SetUnbanResult(jail, ip string, result int) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.UnbanResults[jail] == nil {
|
||||
m.UnbanResults[jail] = make(map[string]int)
|
||||
}
|
||||
m.UnbanResults[jail][ip] = result
|
||||
setNestedMapValue(&m.mu, m.UnbanResults, jail, ip, result)
|
||||
}
|
||||
|
||||
// SetStatusJailData configures the status data for a specific jail.
|
||||
|
||||
@@ -262,6 +262,24 @@ func assertContainsText(t *testing.T, lines []string, text string) {
|
||||
t.Errorf("Expected to find '%s' in results", text)
|
||||
}
|
||||
|
||||
// WithTestRunner sets a test runner and returns a cleanup function.
|
||||
// Usage: defer fail2ban.WithTestRunner(t, mockRunner)()
|
||||
func WithTestRunner(t TestingInterface, runner Runner) func() {
|
||||
t.Helper()
|
||||
original := GetRunner()
|
||||
SetRunner(runner)
|
||||
return func() { SetRunner(original) }
|
||||
}
|
||||
|
||||
// WithTestSudoChecker sets a test sudo checker and returns a cleanup function.
|
||||
// Usage: defer fail2ban.WithTestSudoChecker(t, mockChecker)()
|
||||
func WithTestSudoChecker(t TestingInterface, checker SudoChecker) func() {
|
||||
t.Helper()
|
||||
original := GetSudoChecker()
|
||||
SetSudoChecker(checker)
|
||||
return func() { SetSudoChecker(original) }
|
||||
}
|
||||
|
||||
// StandardMockSetup configures comprehensive standard responses for MockRunner
|
||||
// This eliminates the need for repetitive SetResponse calls in individual tests
|
||||
func StandardMockSetup(mockRunner *MockRunner) {
|
||||
|
||||
@@ -36,17 +36,7 @@ func NewTimeParsingCache(layout string) (*TimeParsingCache, error) {
|
||||
|
||||
// ParseTime parses a time string with bounded caching for performance
|
||||
func (tpc *TimeParsingCache) ParseTime(timeStr string) (time.Time, error) {
|
||||
// Check cache first
|
||||
if cached, ok := tpc.parseCache.Load(timeStr); ok {
|
||||
return cached, nil
|
||||
}
|
||||
|
||||
// Parse and cache
|
||||
t, err := time.Parse(tpc.layout, timeStr)
|
||||
if err == nil {
|
||||
tpc.parseCache.Store(timeStr, t)
|
||||
}
|
||||
return t, err
|
||||
return tpc.parseCache.ParseWithLayout(timeStr, tpc.layout)
|
||||
}
|
||||
|
||||
// BuildTimeString efficiently builds a time string from date and time components
|
||||
|
||||
@@ -33,19 +33,10 @@ type LoggerEntry interface {
|
||||
Errorf(format string, args ...interface{})
|
||||
}
|
||||
|
||||
// LoggerInterface defines the top-level logging interface (decoupled from logrus)
|
||||
// LoggerInterface defines the top-level logging interface (decoupled from logrus).
|
||||
// It embeds LoggerEntry since both interfaces share the same method signatures.
|
||||
type LoggerInterface interface {
|
||||
WithField(key string, value interface{}) LoggerEntry
|
||||
WithFields(fields Fields) LoggerEntry
|
||||
WithError(err error) LoggerEntry
|
||||
Debug(args ...interface{})
|
||||
Info(args ...interface{})
|
||||
Warn(args ...interface{})
|
||||
Error(args ...interface{})
|
||||
Debugf(format string, args ...interface{})
|
||||
Infof(format string, args ...interface{})
|
||||
Warnf(format string, args ...interface{})
|
||||
Errorf(format string, args ...interface{})
|
||||
LoggerEntry
|
||||
}
|
||||
|
||||
// LogCollectionConfig configures log line collection behavior
|
||||
|
||||
Reference in New Issue
Block a user