Files
f2b/cmd/logging.go
Ismo Vuorinen 605f2b9580 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.
2026-01-25 19:07:45 +02:00

218 lines
6.2 KiB
Go

// Package cmd provides structured logging and contextual logging capabilities.
// This package implements context-aware logging with request tracing and
// structured field support for better observability in f2b operations.
package cmd
import (
"context"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/ivuorinen/f2b/fail2ban"
"github.com/ivuorinen/f2b/shared"
)
// ContextualLogger provides structured logging with context propagation
type ContextualLogger struct {
*logrus.Logger
defaultFields logrus.Fields
}
// NewContextualLogger creates a new contextual logger using the centralized cmd.Logger
func NewContextualLogger() *ContextualLogger {
// Use cmd.Logger as the backend, but with JSON formatter for structured logging
contextLogger := logrus.New()
contextLogger.SetOutput(Logger.Out)
contextLogger.SetLevel(Logger.GetLevel())
contextLogger.SetFormatter(&logrus.JSONFormatter{
TimestampFormat: time.RFC3339Nano,
FieldMap: logrus.FieldMap{
logrus.FieldKeyTime: "timestamp",
logrus.FieldKeyLevel: "level",
logrus.FieldKeyMsg: "message",
},
})
return &ContextualLogger{
Logger: contextLogger,
defaultFields: logrus.Fields{
"service": "f2b",
"version": getVersion(),
},
}
}
// Build-time variables set via ldflags
var (
version = "dev"
// Additional build variables that may be used in the future
_ = "unknown" // commit placeholder
_ = "unknown" // date placeholder
_ = "unknown" // builtBy placeholder
)
// getVersion returns the version from build variables or default
func getVersion() string {
return version
}
// contextKeyEntry defines a context key and its log field name
type contextKeyEntry struct {
key any // The context key to look up
fieldName string // The log field name to use
}
// contextKeys lists all context keys to extract for logging
var contextKeys = []contextKeyEntry{
{shared.ContextKeyRequestID, string(shared.ContextKeyRequestID)},
{shared.ContextKeyOperation, string(shared.ContextKeyOperation)},
{shared.ContextKeyIP, string(shared.ContextKeyIP)},
{shared.ContextKeyJail, string(shared.ContextKeyJail)},
{shared.ContextKeyCommand, string(shared.ContextKeyCommand)},
}
// WithContext creates a logger entry with context values
func (cl *ContextualLogger) WithContext(ctx context.Context) *logrus.Entry {
entry := cl.WithFields(cl.defaultFields)
// Extract context values and add as fields using table-driven approach
for _, ck := range contextKeys {
if val := ctx.Value(ck.key); val != nil {
entry = entry.WithField(ck.fieldName, val)
}
}
return entry
}
// WithOperation adds operation context and returns a new context.
// Delegates to fail2ban.WithOperation for consistent validation.
func WithOperation(ctx context.Context, operation string) context.Context {
return fail2ban.WithOperation(ctx, operation)
}
// WithIP adds IP context and returns a new context.
// Delegates to fail2ban.WithIP for consistent IP validation.
func WithIP(ctx context.Context, ip string) context.Context {
return fail2ban.WithIP(ctx, ip)
}
// WithJail adds jail context and returns a new context.
// Delegates to fail2ban.WithJail for consistent jail name validation.
func WithJail(ctx context.Context, jail string) context.Context {
return fail2ban.WithJail(ctx, jail)
}
// WithCommand adds command context and returns a new context.
// This is cmd-specific as fail2ban doesn't need command tracking.
// Empty commands are not stored in context.
func WithCommand(ctx context.Context, command string) context.Context {
command = strings.TrimSpace(command)
if command == "" {
return ctx
}
return context.WithValue(ctx, shared.ContextKeyCommand, command)
}
// WithRequestID adds request ID context and returns a new context.
// Delegates to fail2ban.WithRequestID for consistent validation.
func WithRequestID(ctx context.Context, requestID string) context.Context {
return fail2ban.WithRequestID(ctx, requestID)
}
// LogOperation logs the start and end of an operation with timing and metrics
func (cl *ContextualLogger) LogOperation(ctx context.Context, operation string, fn func() error) error {
start := time.Now()
ctx = WithOperation(ctx, operation)
// Get metrics instance
metrics := GetGlobalMetrics()
cl.WithContext(ctx).WithField("action", shared.ActionStart).Info("Operation started")
err := fn()
duration := time.Since(start)
entry := cl.WithContext(ctx).WithField("duration_ms", duration.Milliseconds())
// Record metrics based on operation type
success := err == nil
if command := ctx.Value(shared.ContextKeyCommand); command != nil {
if cmdStr, ok := command.(string); ok {
metrics.RecordCommandExecution(cmdStr, duration, success)
}
}
if err != nil {
entry.WithError(err).Error("Operation failed")
} else {
entry.Info("Operation completed")
}
return err
}
// LogBanOperation logs ban/unban operations with structured context and metrics
func (cl *ContextualLogger) LogBanOperation(
ctx context.Context,
operation, ip, jail string,
success bool,
duration time.Duration,
) {
ctx = WithOperation(ctx, operation)
ctx = WithIP(ctx, ip)
ctx = WithJail(ctx, jail)
// Record metrics
metrics := GetGlobalMetrics()
metrics.RecordBanOperation(operation, duration, success)
entry := cl.WithContext(ctx).WithFields(logrus.Fields{
"success": success,
"duration_ms": duration.Milliseconds(),
})
if success {
entry.Info("Ban operation completed")
} else {
entry.Error("Ban operation failed")
}
}
// LogCommandExecution logs command execution with context
func (cl *ContextualLogger) LogCommandExecution(
ctx context.Context,
command string,
args []string,
duration time.Duration,
err error,
) {
ctx = WithCommand(ctx, command)
entry := cl.WithContext(ctx).WithFields(logrus.Fields{
"args": args,
"duration_ms": duration.Milliseconds(),
})
if err != nil {
entry.WithError(err).Error("Command execution failed")
} else {
entry.Info("Command executed successfully")
}
}
// Global contextual logger instance
var contextualLogger = NewContextualLogger()
// GetContextualLogger returns the global contextual logger
func GetContextualLogger() *ContextualLogger {
return contextualLogger
}
// SetContextualLogger sets a new global contextual logger
func SetContextualLogger(logger *ContextualLogger) {
contextualLogger = logger
}