Documentation
¶
Overview ¶
Package processor provides interfaces and types for processing OPNsense configurations.
Package processor provides interfaces and types for processing OPNsense configurations. It enables flexible analysis of OPNsense configurations through an options pattern, allowing features like statistics generation, dead-rule detection, and other analyses to be enabled independently.
Index ¶
- Constants
- Variables
- func ExampleUsage(cfg *model.OpnSenseDocument)
- func NewTestError(id int, message string) error
- func ProcessConfigFromFile(configPath string) error
- type Config
- type ConfigInfo
- type CoreProcessor
- type CustomCheck
- type CustomProcessorExample
- type DHCPScopeStatistics
- type ExampleProcessor
- type Finding
- type Findings
- type InterfaceStatistics
- type Job
- type Option
- type OutputFormat
- type Processor
- type Report
- func (r *Report) AddFinding(severity Severity, finding Finding)
- func (r *Report) HasCriticalFindings() bool
- func (r *Report) Summary() string
- func (r *Report) ToFormat(format OutputFormat) (string, error)
- func (r *Report) ToJSON() (string, error)
- func (r *Report) ToMarkdown() string
- func (r *Report) ToYAML() (string, error)
- func (r *Report) TotalFindings() int
- type Result
- type ServiceStatistics
- type Severity
- type Statistics
- type StatisticsSummary
- type TestError
- type TestHostnameError
- type UnsupportedFormatError
- type ValidationError
- type WorkerPool
- type WorkerPoolOption
Constants ¶
const ( // DefaultWorkerCount is the default number of workers (NumCPU - 1, minimum 1). DefaultWorkerCount = 0 // 0 means auto-detect // DefaultJobQueueSize is the default job queue buffer size multiplier. DefaultJobQueueSize = 2 )
WorkerPoolDefaults contains default configuration values for the worker pool.
const ( // NetworkAny represents the "any" network in firewall rules. NetworkAny = "any" // ProtocolHTTPS represents the HTTPS protocol identifier. ProtocolHTTPS = "https" // RuleTypePass represents a firewall pass rule. RuleTypePass = "pass" // FindingTypeSecurity identifies security-related audit findings. FindingTypeSecurity = "security" // ThemeLight specifies the light color theme for terminal output. ThemeLight = "light" // ThemeDark specifies the dark color theme for terminal output. ThemeDark = "dark" // StatusNotEnabled is the display string for disabled features. StatusNotEnabled = "❌" // StatusEnabled is the display string for enabled features. StatusEnabled = "✅" // NoConfigAvailable is the placeholder text when configuration data is missing. NoConfigAvailable = "*No configuration available*" )
Compatibility constants mirroring values from the internal/constants package. These are duplicated here to avoid import cycles while preserving existing APIs.
Variables ¶
var ( // ErrConfigurationNil is returned when configuration is nil. ErrConfigurationNil = errors.New("configuration cannot be nil") ErrNormalizedConfigUnavailable = errors.New("no normalized configuration available for markdown conversion") )
Error constants for the processor package.
var ErrWorkerPoolClosed = errors.New("worker pool is closed")
ErrWorkerPoolClosed is returned when operations are attempted on a closed pool.
Functions ¶
func ExampleUsage ¶
func ExampleUsage(cfg *model.OpnSenseDocument)
ExampleUsage demonstrates various ways to process an OpnSense configuration document using the processor, including basic, security-focused, and comprehensive analyses, as well as handling custom timeouts and reporting in multiple formats.
func NewTestError ¶
NewTestError creates a new test error with goroutine ID.
func ProcessConfigFromFile ¶
ProcessConfigFromFile loads an OpnSense configuration from the specified file path, processes it with all analysis features enabled, and prints a summary of the results. Returns an error if processing fails.
Types ¶
type Config ¶
type Config struct {
// EnableStats controls whether to generate configuration statistics
EnableStats bool
// EnableDeadRuleCheck controls whether to analyze for unused/dead rules
EnableDeadRuleCheck bool
// EnableSecurityAnalysis controls whether to perform security analysis
EnableSecurityAnalysis bool
// EnablePerformanceAnalysis controls whether to analyze performance aspects
EnablePerformanceAnalysis bool
// EnableComplianceCheck controls whether to check compliance with best practices
EnableComplianceCheck bool
}
Config holds the configuration for the processor.
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a Config with default settings.
func (*Config) ApplyOptions ¶
ApplyOptions applies the given options to the configuration.
type ConfigInfo ¶
type ConfigInfo struct {
// Hostname is the configured hostname of the OPNsense system
Hostname string `json:"hostname"`
// Domain is the configured domain name
Domain string `json:"domain"`
// Version is the OPNsense version (if available)
Version string `json:"version,omitempty"`
// Theme is the configured web UI theme
Theme string `json:"theme,omitempty"`
}
ConfigInfo contains basic information about the processed configuration.
type CoreProcessor ¶
type CoreProcessor struct {
// contains filtered or unexported fields
}
CoreProcessor implements the Processor interface with normalize, validate, analyze, and transform capabilities.
func NewCoreProcessor ¶
func NewCoreProcessor() (*CoreProcessor, error)
NewCoreProcessor returns a new CoreProcessor instance with a validator and a markdown generator initialized. NewCoreProcessor creates and returns a CoreProcessor configured with a markdown generator (using converter.DefaultOptions) and a new validator. It returns an error if the markdown generator cannot be created.
func (*CoreProcessor) Process ¶
func (p *CoreProcessor) Process(ctx context.Context, cfg *model.OpnSenseDocument, opts ...Option) (*Report, error)
Process analyzes the given OPNsense configuration and returns a comprehensive report.
type CustomCheck ¶
type CustomCheck struct {
Name string
Description string
CheckFunc func(*model.OpnSenseDocument) []Finding
}
CustomCheck represents a custom analysis check.
func ExampleCustomCheck ¶
func ExampleCustomCheck() CustomCheck
ExampleCustomCheck returns a custom check that detects if the OpnSense configuration is using the default theme. The check produces a finding if no specific theme is set, recommending that a theme be configured for consistency.
type CustomProcessorExample ¶
type CustomProcessorExample struct {
*ExampleProcessor
// contains filtered or unexported fields
}
CustomProcessorExample shows how to create a custom processor implementation that extends or modifies the behavior of the example processor.
func NewCustomProcessor ¶
func NewCustomProcessor(customChecks []CustomCheck) *CustomProcessorExample
NewCustomProcessor returns a CustomProcessorExample that applies the provided custom checks in addition to the standard processing.
func (*CustomProcessorExample) Process ¶
func (p *CustomProcessorExample) Process( ctx context.Context, cfg *model.OpnSenseDocument, opts ...Option, ) (*Report, error)
Process extends the base processor with custom checks.
type DHCPScopeStatistics ¶
type DHCPScopeStatistics struct {
Interface string `json:"interface"`
Enabled bool `json:"enabled"`
From string `json:"from"`
To string `json:"to"`
}
DHCPScopeStatistics contains statistics for DHCP scopes.
type ExampleProcessor ¶
type ExampleProcessor struct{}
ExampleProcessor provides a basic implementation of the Processor interface. This serves as a reference implementation and can be extended with more sophisticated analysis.
func NewExampleProcessor ¶
func NewExampleProcessor() *ExampleProcessor
NewExampleProcessor returns a new ExampleProcessor for analyzing OPNsense configurations.
func (*ExampleProcessor) Process ¶
func (p *ExampleProcessor) Process(ctx context.Context, cfg *model.OpnSenseDocument, opts ...Option) (*Report, error)
Process analyzes the given OPNsense configuration and returns a comprehensive report.
type Finding ¶
type Finding struct {
// Type categorizes the finding (e.g., "security", "performance", "compliance")
Type string `json:"type"`
// Title is a brief description of the finding
Title string `json:"title"`
// Description provides detailed information about the finding
Description string `json:"description"`
// Recommendation suggests how to address the finding
Recommendation string `json:"recommendation,omitempty"`
// Component identifies the configuration component involved
Component string `json:"component,omitempty"`
// Reference provides additional information or documentation links
Reference string `json:"reference,omitempty"`
}
Finding represents a single analysis finding.
type Findings ¶
type Findings struct {
// Critical findings that require immediate attention
Critical []Finding `json:"critical,omitempty"`
// High severity findings
High []Finding `json:"high,omitempty"`
// Medium severity findings
Medium []Finding `json:"medium,omitempty"`
// Low severity findings
Low []Finding `json:"low,omitempty"`
// Informational findings
Info []Finding `json:"info,omitempty"`
}
Findings contains analysis findings categorized by severity and type.
type InterfaceStatistics ¶
type InterfaceStatistics struct {
Name string `json:"name"`
Type string `json:"type"`
Enabled bool `json:"enabled"`
HasIPv4 bool `json:"hasIpv4"`
HasIPv6 bool `json:"hasIpv6"`
HasDHCP bool `json:"hasDhcp"`
BlockPriv bool `json:"blockPriv"`
BlockBogons bool `json:"blockBogons"`
}
InterfaceStatistics contains detailed statistics for a single interface.
type Job ¶ added in v1.1.0
type Job[T any, R any] struct { // ID uniquely identifies this job for tracking. ID string // Input is the data to be processed. Input T // Process is the function that processes the input and returns a result. Process func(ctx context.Context, input T) (R, error) }
Job represents a unit of work to be processed by the worker pool.
type Option ¶
type Option func(*Config)
Option represents a configuration option for the processor. This follows the functional options pattern to allow flexible configuration.
func WithAllFeatures ¶
func WithAllFeatures() Option
WithAllFeatures enables all available analysis features.
func WithComplianceCheck ¶
func WithComplianceCheck() Option
WithComplianceCheck enables compliance checking in the processor.
func WithDeadRuleCheck ¶
func WithDeadRuleCheck() Option
WithDeadRuleCheck enables dead rule detection in the processor.
func WithPerformanceAnalysis ¶
func WithPerformanceAnalysis() Option
WithPerformanceAnalysis enables performance analysis in the processor.
func WithSecurityAnalysis ¶
func WithSecurityAnalysis() Option
WithSecurityAnalysis enables security analysis in the processor.
type OutputFormat ¶
type OutputFormat string
OutputFormat represents the supported output formats.
const ( // OutputFormatMarkdown outputs the report as Markdown. OutputFormatMarkdown OutputFormat = "markdown" // OutputFormatJSON outputs the report as JSON. OutputFormatJSON OutputFormat = "json" // OutputFormatYAML outputs the report as YAML. OutputFormatYAML OutputFormat = "yaml" )
type Processor ¶
type Processor interface {
// Process analyzes the given OPNsense configuration and returns a comprehensive report.
// The context allows for cancellation and timeout control.
// Options can be used to enable specific analysis features.
Process(ctx context.Context, cfg *model.OpnSenseDocument, opts ...Option) (*Report, error)
}
Processor defines the interface for processing OPNsense configurations. It provides a flexible way to analyze configurations with configurable options.
type Report ¶
type Report struct {
// GeneratedAt contains the timestamp when the report was generated
GeneratedAt time.Time `json:"generatedAt"`
// ConfigInfo contains basic information about the processed configuration
ConfigInfo ConfigInfo `json:"configInfo"`
// NormalizedConfig contains the processed and normalized configuration
NormalizedConfig *model.OpnSenseDocument `json:"normalizedConfig,omitempty"`
// Statistics contains various statistics about the configuration
Statistics *Statistics `json:"statistics,omitempty"`
// Findings contains analysis findings categorized by type
Findings Findings `json:"findings"`
// ProcessorConfig contains the configuration used during processing
ProcessorConfig Config `json:"processorConfig"`
// contains filtered or unexported fields
}
Report contains the results of processing an OPNsense configuration. It includes the normalized configuration, analysis findings, and statistics.
func NewReport ¶
func NewReport(cfg *model.OpnSenseDocument, processorConfig Config) *Report
NewReport returns a new Report instance populated with configuration metadata, processor settings, and optionally generated statistics and normalized configuration data.
func (*Report) AddFinding ¶
AddFinding adds a finding to the report with the specified severity.
func (*Report) HasCriticalFindings ¶
HasCriticalFindings returns true if the report contains critical findings.
func (*Report) ToFormat ¶
func (r *Report) ToFormat(format OutputFormat) (string, error)
ToFormat returns the report in the specified format.
func (*Report) ToMarkdown ¶
ToMarkdown returns the report formatted as Markdown using the markdown library.
func (*Report) TotalFindings ¶
TotalFindings returns the total number of findings across all severities.
type Result ¶ added in v1.1.0
type Result[R any] struct { // JobID is the ID of the job that produced this result. JobID string // Value is the result of successful processing. Value R // Err is any error that occurred during processing. Err error }
Result represents the outcome of processing a job.
func ProcessBatch ¶ added in v1.1.0
func ProcessBatch[T, R any]( ctx context.Context, inputs []T, processFn func(ctx context.Context, input T) (R, error), opts ...WorkerPoolOption[T, R], ) ([]Result[R], error)
ProcessBatch processes a batch of inputs using the worker pool and collects all results. ProcessBatch processes a slice of inputs concurrently using a worker pool and returns the collected results.
It submits each input as a job to a new WorkerPool created with the provided context and options. If submission is interrupted (for example by context cancellation), only results for the jobs successfully submitted are collected and returned. If ctx is canceled during submission or result collection, the function returns the partial results along with ctx.Err(). The worker pool is closed before ProcessBatch returns.
type ServiceStatistics ¶
type ServiceStatistics struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Details map[string]string `json:"details,omitempty"`
}
ServiceStatistics contains statistics for individual services.
type Severity ¶
type Severity string
Severity represents the severity levels for findings.
const ( // SeverityCritical represents critical findings that require immediate attention. SeverityCritical Severity = "critical" // SeverityHigh represents high-severity findings that should be addressed soon. SeverityHigh Severity = "high" // SeverityMedium represents medium-severity findings worth investigating. SeverityMedium Severity = "medium" // SeverityLow represents low-severity findings for general improvement. SeverityLow Severity = "low" // SeverityInfo represents informational findings with no immediate action required. SeverityInfo Severity = "info" )
Severity constants represent the different levels of finding severity.
type Statistics ¶
type Statistics struct {
// Interface statistics
TotalInterfaces int `json:"totalInterfaces"`
InterfacesByType map[string]int `json:"interfacesByType"`
InterfaceDetails []InterfaceStatistics `json:"interfaceDetails"`
// Firewall and NAT statistics
TotalFirewallRules int `json:"totalFirewallRules"`
RulesByInterface map[string]int `json:"rulesByInterface"`
RulesByType map[string]int `json:"rulesByType"`
NATEntries int `json:"natEntries"`
NATMode string `json:"natMode"`
// Gateway statistics
TotalGateways int `json:"totalGateways"`
TotalGatewayGroups int `json:"totalGatewayGroups"`
// DHCP statistics
DHCPScopes int `json:"dhcpScopes"`
DHCPScopeDetails []DHCPScopeStatistics `json:"dhcpScopeDetails"`
// User and group statistics
TotalUsers int `json:"totalUsers"`
UsersByScope map[string]int `json:"usersByScope"`
TotalGroups int `json:"totalGroups"`
GroupsByScope map[string]int `json:"groupsByScope"`
// Service statistics
EnabledServices []string `json:"enabledServices"`
TotalServices int `json:"totalServices"`
ServiceDetails []ServiceStatistics `json:"serviceDetails"`
// System configuration statistics
SysctlSettings int `json:"sysctlSettings"`
LoadBalancerMonitors int `json:"loadBalancerMonitors"`
SecurityFeatures []string `json:"securityFeatures"`
// IDS/IPS statistics
IDSEnabled bool `json:"idsEnabled"`
IDSMode string `json:"idsMode"`
IDSMonitoredInterfaces []string `json:"idsMonitoredInterfaces,omitempty"`
IDSDetectionProfile string `json:"idsDetectionProfile,omitempty"`
IDSLoggingEnabled bool `json:"idsLoggingEnabled"`
// Summary counts for quick reference
Summary StatisticsSummary `json:"summary"`
}
Statistics contains various statistics about the configuration.
type StatisticsSummary ¶
type StatisticsSummary struct {
TotalConfigItems int `json:"totalConfigItems"`
SecurityScore int `json:"securityScore"`
ConfigComplexity int `json:"configComplexity"`
HasSecurityFeatures bool `json:"hasSecurityFeatures"`
}
StatisticsSummary provides high-level summary statistics.
type TestHostnameError ¶
TestHostnameError represents a hostname mismatch error in tests.
func (*TestHostnameError) Error ¶
func (e *TestHostnameError) Error() string
Error returns a formatted string describing the hostname mismatch, including expected and actual values.
type UnsupportedFormatError ¶
type UnsupportedFormatError struct {
Format string
}
UnsupportedFormatError represents an error for unsupported output formats.
func (*UnsupportedFormatError) Error ¶
func (e *UnsupportedFormatError) Error() string
Error returns a string describing the unsupported format.
type ValidationError ¶
ValidationError represents a validation error with field and message information.
func (ValidationError) Error ¶
func (e ValidationError) Error() string
Error implements the error interface for ValidationError.
type WorkerPool ¶ added in v1.1.0
WorkerPool manages a pool of workers for concurrent job processing. It supports context-based cancellation and graceful shutdown.
func NewWorkerPool ¶ added in v1.1.0
func NewWorkerPool[T, R any](ctx context.Context, opts ...WorkerPoolOption[T, R]) *WorkerPool[T, R]
NewWorkerPool creates a new WorkerPool with the specified context and options. If worker count is not specified or is 0, it defaults to NumCPU-1 (minimum 1).
func (*WorkerPool[T, R]) Cancel ¶ added in v1.1.0
func (wp *WorkerPool[T, R]) Cancel()
Cancel immediately cancels all pending work and shuts down the pool.
func (*WorkerPool[T, R]) Close ¶ added in v1.1.0
func (wp *WorkerPool[T, R]) Close()
Close gracefully shuts down the worker pool. It stops accepting new jobs, waits for in-flight jobs to complete, and closes the results channel.
func (*WorkerPool[T, R]) IsClosed ¶ added in v1.1.0
func (wp *WorkerPool[T, R]) IsClosed() bool
IsClosed returns true if the pool has been closed.
func (*WorkerPool[T, R]) Results ¶ added in v1.1.0
func (wp *WorkerPool[T, R]) Results() <-chan Result[R]
Results returns the results channel for reading processed results.
func (*WorkerPool[T, R]) Submit ¶ added in v1.1.0
func (wp *WorkerPool[T, R]) Submit(job Job[T, R]) error
Submit adds a job to the work queue. Returns ErrWorkerPoolClosed if the pool is closed. Returns context error if the context is cancelled while waiting.
func (*WorkerPool[T, R]) WorkerCount ¶ added in v1.1.0
func (wp *WorkerPool[T, R]) WorkerCount() int
WorkerCount returns the number of workers in the pool.
type WorkerPoolOption ¶ added in v1.1.0
type WorkerPoolOption[T any, R any] func(*WorkerPool[T, R])
WorkerPoolOption configures a WorkerPool.
func WithMaxRetries ¶ added in v1.1.0
func WithMaxRetries[T, R any](retries int) WorkerPoolOption[T, R]
WithMaxRetries sets the maximum number of retries for failed jobs.
func WithWorkerCount ¶ added in v1.1.0
func WithWorkerCount[T, R any](count int) WorkerPoolOption[T, R]
WithWorkerCount sets the number of workers in the pool.