config

package
v0.19.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 22, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package config provides configuration management for scanorama. It handles loading configuration from files, environment variables, and provides default values for various components.

Package config provides configuration management for scanorama. This file provides centralized, thorough configuration validation that collects all errors and warnings rather than failing on the first one. It can be used from any entry point (CLI, API, config loading).

Index

Constants

View Source
const (
	DefaultPostgresPort    = 5432
	DefaultMaxOpenConns    = 25
	DefaultMaxIdleConns    = 5
	DefaultConnMaxLifetime = 5 * time.Minute
	DefaultConnMaxIdleTime = 5 * time.Minute
	DefaultDirPermissions  = 0o750
	DefaultFilePermissions = 0o600
)

Default configuration values.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIConfig

type APIConfig struct {
	// Enable API server
	Enabled bool `yaml:"enabled" json:"enabled"`

	// Listen host
	Host string `yaml:"host" json:"host"`

	// Listen port
	Port int `yaml:"port" json:"port"`

	// HTTP timeouts
	ReadTimeout  time.Duration `yaml:"read_timeout" json:"read_timeout"`
	WriteTimeout time.Duration `yaml:"write_timeout" json:"write_timeout"`
	IdleTimeout  time.Duration `yaml:"idle_timeout" json:"idle_timeout"`

	// Maximum header size
	MaxHeaderBytes int `yaml:"max_header_bytes" json:"max_header_bytes"`

	// Enable TLS
	TLS TLSConfig `yaml:"tls" json:"tls"`

	// Authentication settings
	AuthEnabled bool     `yaml:"auth_enabled" json:"auth_enabled"`
	APIKeys     []string `yaml:"api_keys" json:"api_keys"`

	// CORS settings
	EnableCORS  bool     `yaml:"enable_cors" json:"enable_cors"`
	CORSOrigins []string `yaml:"cors_origins" json:"cors_origins"`

	// Rate limiting
	RateLimitEnabled  bool          `yaml:"rate_limit_enabled" json:"rate_limit_enabled"`
	RateLimitRequests int           `yaml:"rate_limit_requests" json:"rate_limit_requests"`
	RateLimitWindow   time.Duration `yaml:"rate_limit_window" json:"rate_limit_window"`

	// Request timeout (deprecated, use ReadTimeout)
	RequestTimeout time.Duration `yaml:"request_timeout" json:"request_timeout"`

	// Maximum request size
	MaxRequestSize int64 `yaml:"max_request_size" json:"max_request_size"`
}

APIConfig holds API server settings.

type CORSConfig

type CORSConfig struct {
	// Enable CORS
	Enabled bool `yaml:"enabled" json:"enabled"`

	// Allowed origins
	AllowedOrigins []string `yaml:"allowed_origins" json:"allowed_origins"`

	// Allowed methods
	AllowedMethods []string `yaml:"allowed_methods" json:"allowed_methods"`

	// Allowed headers
	AllowedHeaders []string `yaml:"allowed_headers" json:"allowed_headers"`
}

CORSConfig holds CORS settings.

type Config

type Config struct {
	// Daemon configuration
	Daemon DaemonConfig `yaml:"daemon" json:"daemon"`

	// Database configuration
	Database db.Config `yaml:"database" json:"database"`

	// Scanning configuration
	Scanning ScanningConfig `yaml:"scanning" json:"scanning"`

	// API configuration
	API APIConfig `yaml:"api" json:"api"`

	// Discovery configuration
	Discovery DiscoveryConfig `yaml:"discovery" json:"discovery"`

	// Logging configuration
	Logging LoggingConfig `yaml:"logging" json:"logging"`
}

Config represents the application configuration.

func Default

func Default() *Config

Default returns the default configuration with database credentials loaded from environment variables if available.

func Load

func Load(path string) (*Config, error)

Load loads configuration from a file.

func (*Config) GetAPIAddress

func (c *Config) GetAPIAddress() string

GetAPIAddress returns the full API address.

func (*Config) GetDatabaseConfig

func (c *Config) GetDatabaseConfig() db.Config

GetDatabaseConfig returns the database configuration.

func (*Config) GetLogOutput

func (c *Config) GetLogOutput() string

GetLogOutput returns the log output destination.

func (*Config) IsAPIEnabled

func (c *Config) IsAPIEnabled() bool

IsAPIEnabled returns true if API server is enabled.

func (*Config) IsDaemonMode

func (c *Config) IsDaemonMode() bool

IsDaemonMode returns true if running in daemon mode.

func (*Config) Save

func (c *Config) Save(path string) error

Save saves configuration to a file.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration.

type DaemonConfig

type DaemonConfig struct {
	// PID file location
	PIDFile string `yaml:"pid_file" json:"pid_file"`

	// Working directory
	WorkDir string `yaml:"work_dir" json:"work_dir"`

	// User to run as (for privilege dropping)
	User string `yaml:"user" json:"user"`

	// Group to run as
	Group string `yaml:"group" json:"group"`

	// Enable daemon mode (fork to background)
	Daemonize bool `yaml:"daemonize" json:"daemonize"`

	// Graceful shutdown timeout
	ShutdownTimeout time.Duration `yaml:"shutdown_timeout" json:"shutdown_timeout"`
}

DaemonConfig holds daemon-specific settings.

type DiscoveryConfig

type DiscoveryConfig struct {
	// Predefined networks to discover
	Networks []NetworkConfig `yaml:"networks" json:"networks"`

	// Global exclusions applied to all networks
	GlobalExclusions []string `yaml:"global_exclusions" json:"global_exclusions"`

	// Default discovery settings
	Defaults DiscoveryDefaults `yaml:"defaults" json:"defaults"`

	// Enable automatic network seeding from config
	AutoSeed bool `yaml:"auto_seed" json:"auto_seed"`
}

DiscoveryConfig contains discovery engine configuration.

type DiscoveryDefaults

type DiscoveryDefaults struct {
	// Default discovery method
	Method string `yaml:"method" json:"method"`

	// Default timeout for discovery operations
	Timeout string `yaml:"timeout" json:"timeout"`

	// Default schedule for networks without explicit schedule
	Schedule string `yaml:"schedule" json:"schedule"`

	// Default ports for TCP discovery
	Ports string `yaml:"ports" json:"ports"`
}

DiscoveryDefaults contains default discovery settings.

type LoggingConfig

type LoggingConfig struct {
	// Log level (debug, info, warn, error)
	Level string `yaml:"level" json:"level"`

	// Log format (text, json)
	Format string `yaml:"format" json:"format"`

	// Log output (stdout, stderr, file path)
	Output string `yaml:"output" json:"output"`

	// Log file rotation
	Rotation RotationConfig `yaml:"rotation" json:"rotation"`

	// Enable structured logging
	Structured bool `yaml:"structured" json:"structured"`

	// Enable request logging for API
	RequestLogging bool `yaml:"request_logging" json:"request_logging"`
}

LoggingConfig holds logging settings.

type NetworkConfig

type NetworkConfig struct {
	// Network name (must be unique)
	Name string `yaml:"name" json:"name"`

	// CIDR notation (e.g., "192.168.1.0/24")
	CIDR string `yaml:"cidr" json:"cidr"`

	// Discovery method (ping, tcp, arp)
	Method string `yaml:"method" json:"method"`

	// Cron schedule for automatic discovery (optional)
	Schedule string `yaml:"schedule" json:"schedule"`

	// Description of the network
	Description string `yaml:"description" json:"description"`

	// Network-specific exclusions
	Exclusions []string `yaml:"exclusions" json:"exclusions"`

	// Enable/disable this network
	Enabled bool `yaml:"enabled" json:"enabled"`

	// Custom ports for TCP discovery
	Ports string `yaml:"ports" json:"ports"`
}

NetworkConfig defines a network to be discovered.

type RateLimitConfig

type RateLimitConfig struct {
	// Enable rate limiting
	Enabled bool `yaml:"enabled" json:"enabled"`

	// Requests per second
	RequestsPerSecond int `yaml:"requests_per_second" json:"requests_per_second"`

	// Burst size
	BurstSize int `yaml:"burst_size" json:"burst_size"`
}

RateLimitConfig holds rate limiting settings.

type RetryConfig

type RetryConfig struct {
	// Maximum number of retries
	MaxRetries int `yaml:"max_retries" json:"max_retries"`

	// Delay between retries
	RetryDelay time.Duration `yaml:"retry_delay" json:"retry_delay"`

	// Exponential backoff multiplier
	BackoffMultiplier float64 `yaml:"backoff_multiplier" json:"backoff_multiplier"`
}

RetryConfig holds retry settings for failed scans.

type RotationConfig

type RotationConfig struct {
	// Enable log rotation
	Enabled bool `yaml:"enabled" json:"enabled"`

	// Maximum file size in MB
	MaxSizeMB int `yaml:"max_size_mb" json:"max_size_mb"`

	// Maximum number of backup files
	MaxBackups int `yaml:"max_backups" json:"max_backups"`

	// Maximum age in days
	MaxAgeDays int `yaml:"max_age_days" json:"max_age_days"`

	// Compress rotated files
	Compress bool `yaml:"compress" json:"compress"`
}

RotationConfig holds log rotation settings.

type ScanningConfig

type ScanningConfig struct {
	// Number of concurrent scanning workers
	WorkerPoolSize int `yaml:"worker_pool_size" json:"worker_pool_size"`

	// Default scan interval for targets
	DefaultInterval time.Duration `yaml:"default_interval" json:"default_interval"`

	// Maximum scan timeout per target
	MaxScanTimeout time.Duration `yaml:"max_scan_timeout" json:"max_scan_timeout"`

	// Default ports to scan
	DefaultPorts string `yaml:"default_ports" json:"default_ports"`

	// Preferred scan mode
	ScanMode string `yaml:"scan_mode" json:"scan_mode"`

	// Maximum concurrent targets per job
	MaxConcurrentTargets int `yaml:"max_concurrent_targets" json:"max_concurrent_targets"`

	// Enable service detection
	EnableServiceDetection bool `yaml:"enable_service_detection" json:"enable_service_detection"`

	// Enable OS detection
	EnableOSDetection bool `yaml:"enable_os_detection" json:"enable_os_detection"`

	// Retry configuration
	Retry RetryConfig `yaml:"retry" json:"retry"`

	// Rate limiting
	RateLimit RateLimitConfig `yaml:"rate_limit" json:"rate_limit"`
}

ScanningConfig holds scanning-related settings.

type Severity added in v0.13.0

type Severity int

Severity represents the severity level of a validation issue.

const (
	// SeverityError indicates a hard validation error that must be fixed.
	SeverityError Severity = iota
	// SeverityWarning indicates a potential issue that should be reviewed.
	SeverityWarning
)

type TLSConfig

type TLSConfig struct {
	// Enable TLS
	Enabled bool `yaml:"enabled" json:"enabled"`

	// Certificate file path
	CertFile string `yaml:"cert_file" json:"cert_file"`

	// Private key file path
	KeyFile string `yaml:"key_file" json:"key_file"`

	// CA certificate file (for client authentication)
	CAFile string `yaml:"ca_file" json:"ca_file"`
}

TLSConfig holds TLS settings.

type ValidationIssue added in v0.13.0

type ValidationIssue struct {
	// Section is the config section where the issue was found
	// (e.g., "database", "api").
	Section string
	// Field is the specific field name within the section.
	Field string
	// Message describes the issue.
	Message string
	// Severity indicates whether this is an error or warning.
	Severity Severity
}

ValidationIssue represents a single validation error or warning.

func (ValidationIssue) Error added in v0.13.0

func (v ValidationIssue) Error() string

Error implements the error interface for ValidationIssue.

type ValidationResult added in v0.13.0

type ValidationResult struct {
	// Errors contains hard validation errors.
	Errors []ValidationIssue
	// Warnings contains non-fatal validation warnings.
	Warnings []ValidationIssue
}

ValidationResult holds the collected errors and warnings from validation.

func ValidateAPIConfig added in v0.13.0

func ValidateAPIConfig(cfg *APIConfig) *ValidationResult

ValidateAPIConfig validates the API configuration section, including TLS and auth.

func ValidateAndNormalize added in v0.13.0

func ValidateAndNormalize(cfg *Config) *ValidationResult

ValidateAndNormalize validates the config and applies normalization (lowercasing, path cleaning, etc.). It modifies the config in place. Call this instead of ValidateConfig when you want the config to be cleaned up as part of validation.

func ValidateConfig added in v0.13.0

func ValidateConfig(cfg *Config) *ValidationResult

ValidateConfig runs all section validators on a full Config and collects all errors and warnings. This is the main entry point for comprehensive config validation.

func ValidateDaemonConfig added in v0.13.0

func ValidateDaemonConfig(cfg *DaemonConfig) *ValidationResult

ValidateDaemonConfig validates the daemon configuration section.

func ValidateDatabaseConfig added in v0.13.0

func ValidateDatabaseConfig(cfg *db.Config) *ValidationResult

ValidateDatabaseConfig validates the database configuration section.

func ValidateDiscoveryConfig added in v0.13.0

func ValidateDiscoveryConfig(
	cfg *DiscoveryConfig,
) *ValidationResult

ValidateDiscoveryConfig validates the discovery configuration section.

func ValidateLoggingConfig added in v0.13.0

func ValidateLoggingConfig(
	cfg *LoggingConfig,
) *ValidationResult

ValidateLoggingConfig validates the logging configuration section.

func ValidateScanningConfig added in v0.13.0

func ValidateScanningConfig(
	cfg *ScanningConfig,
) *ValidationResult

ValidateScanningConfig validates the scanning configuration section.

func (*ValidationResult) AllIssues added in v0.13.0

func (r *ValidationResult) AllIssues() []ValidationIssue

AllIssues returns all errors and warnings combined.

func (*ValidationResult) AsError added in v0.13.0

func (r *ValidationResult) AsError() error

AsError returns the ValidationResult as an error if there are errors, or nil if valid.

func (*ValidationResult) Error added in v0.13.0

func (r *ValidationResult) Error() string

Error returns a combined error message from all validation errors, or empty string if valid.

func (*ValidationResult) HasErrors added in v0.13.0

func (r *ValidationResult) HasErrors() bool

HasErrors returns true if there are any validation errors.

func (*ValidationResult) HasWarnings added in v0.13.0

func (r *ValidationResult) HasWarnings() bool

HasWarnings returns true if there are any validation warnings.

func (*ValidationResult) IsValid added in v0.13.0

func (r *ValidationResult) IsValid() bool

IsValid returns true if there are no validation errors (warnings are OK).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL