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:
2026-01-25 19:07:45 +02:00
committed by GitHub
parent a668c4563e
commit 605f2b9580
33 changed files with 752 additions and 768 deletions

View File

@@ -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.