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

@@ -17,6 +17,20 @@ import (
"github.com/ivuorinen/f2b/fail2ban"
)
// createTimeoutContext creates a context with the configured command timeout.
// This helper consolidates the duplicate timeout handling pattern.
// If base is nil, context.Background() is used.
func createTimeoutContext(base context.Context, config *Config) (context.Context, context.CancelFunc) {
if base == nil {
base = context.Background()
}
timeout := shared.DefaultCommandTimeout
if config != nil && config.CommandTimeout > 0 {
timeout = config.CommandTimeout
}
return context.WithTimeout(base, timeout)
}
// IsCI detects if we're running in a CI environment
func IsCI() bool {
return fail2ban.IsCI()
@@ -50,17 +64,8 @@ func NewContextualCommand(
// Get the contextual logger
logger := GetContextualLogger()
// Base on Cobra's context so signals/cancellations propagate
base := cmd.Context()
if base == nil {
base = context.Background()
}
// Create timeout context for the entire operation
timeout := shared.DefaultCommandTimeout
if config != nil && config.CommandTimeout > 0 {
timeout = config.CommandTimeout
}
ctx, cancel := context.WithTimeout(base, timeout)
// Create timeout context based on Cobra's context so signals/cancellations propagate
ctx, cancel := createTimeoutContext(cmd.Context(), config)
defer cancel()
// Extract command name from use string (first word)
@@ -388,22 +393,63 @@ type OperationResult struct {
Status string `json:"status"`
}
// ProcessBanOperation processes ban operations across multiple jails
func ProcessBanOperation(client fail2ban.Client, ip string, jails []string) ([]OperationResult, error) {
// OperationType defines a ban or unban operation with its associated metadata
type OperationType struct {
// MetricsType is the metrics key for this operation (e.g., shared.MetricsBan)
MetricsType string
// Message is the log message for this operation (e.g., shared.MsgBanResult)
Message string
// Operation is the function to execute without context
Operation func(client fail2ban.Client, ip, jail string) (int, error)
// OperationCtx is the function to execute with context
OperationCtx func(ctx context.Context, client fail2ban.Client, ip, jail string) (int, error)
}
// BanOperationType defines the ban operation
var BanOperationType = OperationType{
MetricsType: shared.MetricsBan,
Message: shared.MsgBanResult,
Operation: func(c fail2ban.Client, ip, jail string) (int, error) {
return c.BanIP(ip, jail)
},
OperationCtx: func(ctx context.Context, c fail2ban.Client, ip, jail string) (int, error) {
return c.BanIPWithContext(ctx, ip, jail)
},
}
// UnbanOperationType defines the unban operation
var UnbanOperationType = OperationType{
MetricsType: shared.MetricsUnban,
Message: shared.MsgUnbanResult,
Operation: func(c fail2ban.Client, ip, jail string) (int, error) {
return c.UnbanIP(ip, jail)
},
OperationCtx: func(ctx context.Context, c fail2ban.Client, ip, jail string) (int, error) {
return c.UnbanIPWithContext(ctx, ip, jail)
},
}
// ProcessOperation processes operations across multiple jails using the specified operation type
func ProcessOperation(
client fail2ban.Client,
ip string,
jails []string,
opType OperationType,
) ([]OperationResult, error) {
results := make([]OperationResult, 0, len(jails))
for _, jail := range jails {
code, err := client.BanIP(ip, jail)
code, err := opType.Operation(client, ip, jail)
if err != nil {
return nil, err
}
status := InterpretBanStatus(code, shared.MetricsBan)
status := InterpretBanStatus(code, opType.MetricsType)
Logger.WithFields(map[string]interface{}{
"ip": ip,
"jail": jail,
"status": status,
}).Info(shared.MsgBanResult)
}).Info(opType.Message)
results = append(results, OperationResult{
IP: ip,
@@ -415,6 +461,59 @@ func ProcessBanOperation(client fail2ban.Client, ip string, jails []string) ([]O
return results, nil
}
// ProcessOperationWithContext processes operations across multiple jails with timeout context
func ProcessOperationWithContext(
ctx context.Context,
client fail2ban.Client,
ip string,
jails []string,
opType OperationType,
) ([]OperationResult, error) {
logger := GetContextualLogger()
results := make([]OperationResult, 0, len(jails))
for _, jail := range jails {
// Add jail to context for this operation
jailCtx := WithJail(ctx, jail)
// Time the operation
start := time.Now()
code, err := opType.OperationCtx(jailCtx, client, ip, jail)
duration := time.Since(start)
if err != nil {
// Log the failed operation with timing
logger.LogBanOperation(jailCtx, opType.MetricsType, ip, jail, false, duration)
return nil, err
}
status := InterpretBanStatus(code, opType.MetricsType)
// Log the successful operation with timing
logger.LogBanOperation(jailCtx, opType.MetricsType, ip, jail, true, duration)
// Log the operation-specific message (ban vs unban)
Logger.WithFields(map[string]interface{}{
"ip": ip,
"jail": jail,
"status": status,
}).Info(opType.Message)
results = append(results, OperationResult{
IP: ip,
Jail: jail,
Status: status,
})
}
return results, nil
}
// ProcessBanOperation processes ban operations across multiple jails
func ProcessBanOperation(client fail2ban.Client, ip string, jails []string) ([]OperationResult, error) {
return ProcessOperation(client, ip, jails, BanOperationType)
}
// ProcessBanOperationWithContext processes ban operations across multiple jails with timeout context
func ProcessBanOperationWithContext(
ctx context.Context,
@@ -422,70 +521,12 @@ func ProcessBanOperationWithContext(
ip string,
jails []string,
) ([]OperationResult, error) {
logger := GetContextualLogger()
results := make([]OperationResult, 0, len(jails))
for _, jail := range jails {
// Add jail to context for this operation
jailCtx := WithJail(ctx, jail)
// Time the ban operation
start := time.Now()
code, err := client.BanIPWithContext(jailCtx, ip, jail)
duration := time.Since(start)
if err != nil {
// Log the failed operation with timing
logger.LogBanOperation(jailCtx, shared.MetricsBan, ip, jail, false, duration)
return nil, err
}
status := InterpretBanStatus(code, shared.MetricsBan)
// Log the successful operation with timing
logger.LogBanOperation(jailCtx, shared.MetricsBan, ip, jail, true, duration)
Logger.WithFields(map[string]interface{}{
"ip": ip,
"jail": jail,
"status": status,
}).Info(shared.MsgBanResult)
results = append(results, OperationResult{
IP: ip,
Jail: jail,
Status: status,
})
}
return results, nil
return ProcessOperationWithContext(ctx, client, ip, jails, BanOperationType)
}
// ProcessUnbanOperation processes unban operations across multiple jails
func ProcessUnbanOperation(client fail2ban.Client, ip string, jails []string) ([]OperationResult, error) {
results := make([]OperationResult, 0, len(jails))
for _, jail := range jails {
code, err := client.UnbanIP(ip, jail)
if err != nil {
return nil, err
}
status := InterpretBanStatus(code, shared.MetricsUnban)
Logger.WithFields(map[string]interface{}{
"ip": ip,
"jail": jail,
"status": status,
}).Info(shared.MsgUnbanResult)
results = append(results, OperationResult{
IP: ip,
Jail: jail,
Status: status,
})
}
return results, nil
return ProcessOperation(client, ip, jails, UnbanOperationType)
}
// ProcessUnbanOperationWithContext processes unban operations across multiple jails with timeout context
@@ -495,43 +536,7 @@ func ProcessUnbanOperationWithContext(
ip string,
jails []string,
) ([]OperationResult, error) {
logger := GetContextualLogger()
results := make([]OperationResult, 0, len(jails))
for _, jail := range jails {
// Add jail to context for this operation
jailCtx := WithJail(ctx, jail)
// Time the unban operation
start := time.Now()
code, err := client.UnbanIPWithContext(jailCtx, ip, jail)
duration := time.Since(start)
if err != nil {
// Log the failed operation with timing
logger.LogBanOperation(jailCtx, shared.MetricsUnban, ip, jail, false, duration)
return nil, err
}
status := InterpretBanStatus(code, shared.MetricsUnban)
// Log the successful operation with timing
logger.LogBanOperation(jailCtx, shared.MetricsUnban, ip, jail, true, duration)
Logger.WithFields(map[string]interface{}{
"ip": ip,
"jail": jail,
"status": status,
}).Info(shared.MsgUnbanResult)
results = append(results, OperationResult{
IP: ip,
Jail: jail,
Status: status,
})
}
return results, nil
return ProcessOperationWithContext(ctx, client, ip, jails, UnbanOperationType)
}
// Argument validation helpers