config

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package config provides configuration management for apt-proxy.

Package config provides configuration loading orchestration. The actual CLI/ENV resolution lives in loader_flags.go, YAML handling in loader_yaml.go, merging in loader_merge.go, validation in loader_validate.go, and config file path search in loader_search.go.

Package config CLI flag definitions and CLI/ENV resolution helpers.

Package config configuration merging logic between file/CLI/ENV sources.

Package config configuration file location helpers.

Package config configuration validation and state hand-off.

Package config YAML file loading and conversion.

Index

Constants

View Source
const (
	StorageBackendDisk = "disk"
	StorageBackendS3   = "s3"
)

Storage backend identifiers used by StorageConfig.Backend.

View Source
const (
	EnvHost        = "APT_PROXY_HOST"
	EnvPort        = "APT_PROXY_PORT"
	EnvMode        = "APT_PROXY_MODE"
	EnvCacheDir    = "APT_PROXY_CACHEDIR"
	EnvDebug       = "APT_PROXY_DEBUG"
	EnvUbuntu      = "APT_PROXY_UBUNTU"
	EnvUbuntuPorts = "APT_PROXY_UBUNTU_PORTS"
	EnvDebian      = "APT_PROXY_DEBIAN"
	EnvCentOS      = "APT_PROXY_CENTOS"
	EnvAlpine      = "APT_PROXY_ALPINE"

	// Cache configuration environment variables
	EnvCacheMaxSize         = "APT_PROXY_CACHE_MAX_SIZE"
	EnvCacheTTL             = "APT_PROXY_CACHE_TTL"
	EnvCacheCleanupInterval = "APT_PROXY_CACHE_CLEANUP_INTERVAL"

	// TLS configuration environment variables
	EnvTLSEnabled  = "APT_PROXY_TLS_ENABLED"
	EnvTLSCertFile = "APT_PROXY_TLS_CERT"
	EnvTLSKeyFile  = "APT_PROXY_TLS_KEY"

	// Security configuration environment variables
	EnvAPIKey                = "APT_PROXY_API_KEY" // #nosec G101 -- env var name, not a credential
	EnvEnableAPIAuth         = "APT_PROXY_ENABLE_API_AUTH"
	EnvAPIRateLimitPerMinute = "APT_PROXY_API_RATE_LIMIT_PER_MINUTE"
	EnvTrustedProxies        = "APT_PROXY_TRUSTED_PROXIES"

	// Configuration file environment variable
	EnvConfigFile = "APT_PROXY_CONFIG_FILE"

	// Upstream transport
	EnvUpstreamKeepAlive = "APT_PROXY_UPSTREAM_KEEP_ALIVE"

	// Distributions configuration (distributions.yaml) path
	EnvDistributionsConfig = "APT_PROXY_DISTRIBUTIONS_CONFIG"

	// Storage backend selection: "disk" (default) or "s3"
	EnvStorageBackend = "APT_PROXY_STORAGE_BACKEND"

	// S3 storage backend environment variables. Credentials default to the
	// canonical AWS_* names so existing IAM tooling (instance role, IRSA,
	// shared credentials) keeps working without explicit configuration.
	EnvS3Endpoint     = "APT_PROXY_S3_ENDPOINT"
	EnvS3Region       = "APT_PROXY_S3_REGION"
	EnvS3Bucket       = "APT_PROXY_S3_BUCKET"
	EnvS3Prefix       = "APT_PROXY_S3_PREFIX"
	EnvS3AccessKey    = "APT_PROXY_S3_ACCESS_KEY"    // #nosec G101 -- env var name, not a credential
	EnvS3SecretKey    = "APT_PROXY_S3_SECRET_KEY"    // #nosec G101 -- env var name, not a credential
	EnvS3SessionToken = "APT_PROXY_S3_SESSION_TOKEN" // #nosec G101 -- env var name, not a credential
	EnvS3UseSSL       = "APT_PROXY_S3_USE_SSL"
	EnvS3UsePathStyle = "APT_PROXY_S3_USE_PATH_STYLE"
	EnvS3InlineMaxMB  = "APT_PROXY_S3_INLINE_MAX_MB"
	EnvS3TempDir      = "APT_PROXY_S3_TEMP_DIR"
)

Environment variable names for configuration

View Source
const (
	DefaultHost     = "0.0.0.0"
	DefaultPort     = "3142"
	DefaultCacheDir = "./.aptcache"

	// Default cache configuration values (as strings for flag parsing)
	DefaultCacheMaxSizeGB          = 10  // 10 GB
	DefaultCacheTTLHours           = 168 // 7 days
	DefaultCacheCleanupIntervalMin = 60  // 1 hour

	// Default configuration file paths (searched in order)
	DefaultConfigFileName = "apt-proxy.yaml"

	// Default async benchmark setting
	DefaultAsyncBenchmark = true // Enable async mirror benchmark by default for faster startup

	// Default API rate limit: requests per IP per minute (0 = disabled)
	DefaultAPIRateLimitPerMinute = 60

	// Default storage backend (local disk preserves prior behaviour).
	DefaultStorageBackend = "disk"
	// Default in-memory write threshold for the S3 backend, in mebibytes.
	// Above this size a spill to TempDir occurs before PutObject runs.
	DefaultS3InlineMaxMB = 32
	// Default object-key prefix for the S3 backend. The trailing slash is
	// significant: it keeps every cached body/header inside a single
	// "folder" so the bucket can be shared with other tooling.
	DefaultS3Prefix = "apt-proxy/"
)

Default configuration values

View Source
const (
	EnvLogLevel        = "APT_PROXY_LOG_LEVEL"
	EnvLogFormat       = "APT_PROXY_LOG_FORMAT"
	EnvLogLevelLegacy  = "LOG_LEVEL"
	EnvLogFormatLegacy = "LOG_FORMAT"
)

Environment variable names for logging configuration. The historical names (LOG_LEVEL / LOG_FORMAT) collide with other tooling, so the canonical names are now prefixed with APT_PROXY_. The unprefixed variants are read as a fallback (see ResolveLogLevelEnv) so existing deployments don't break.

Variables

This section is empty.

Functions

func ApplyToState added in v0.12.0

func ApplyToState(config *Config, st *state.AppState, reg *distro.Registry) error

ApplyToState writes the proxy mode and per-distro mirror URLs from config into the supplied AppState. Aliases are resolved against reg when reg is non-nil.

This replaces the previous package-global UpdateGlobalState helper: callers must now own (and supply) the AppState explicitly so that multiple Servers in the same process can each configure their own state without collision.

func FindConfigFile

func FindConfigFile() string

FindConfigFile searches for a configuration file in common locations. Returns the path to the first file found, or empty string if none found.

func GetAllowedModes

func GetAllowedModes() []string

GetAllowedModes returns the list of allowed mode values

func GetConfigFilePaths

func GetConfigFilePaths() []string

GetConfigFilePaths returns a slice of paths searched for configuration files. Useful for debugging and logging.

func IsConfigFileProvided

func IsConfigFileProvided() bool

IsConfigFileProvided checks if a config file path was explicitly provided via CLI flag or environment variable.

func ModeToInt

func ModeToInt(mode string) int

ModeToInt converts a validated mode string to its corresponding integer constant. This function should only be called after mode validation via configutil.ResolveEnum.

func ValidateConfig

func ValidateConfig(config *Config) error

ValidateConfig performs validation on the configuration to ensure all required fields are set and valid. Returns an error if validation fails.

Types

type CacheConfig

type CacheConfig struct {
	// MaxSize is the maximum cache size in bytes (default: 10GB).
	// Internal representation; not read from YAML.
	MaxSize int64 `yaml:"-"`
	// MaxSizeGB is an alternative way to specify max size in GB for YAML config.
	// Not read from the top-level Config YAML; YAMLConfig.Cache.MaxSizeGB
	// is the user-facing knob.
	MaxSizeGB int64 `yaml:"-"`
	// TTL is the time-to-live for cached items (default: 7 days).
	// Internal representation; not read from YAML.
	TTL time.Duration `yaml:"-"`
	// TTLHours is an alternative way to specify TTL in hours for YAML config.
	// Not read from the top-level Config YAML; YAMLConfig.Cache.TTLHours
	// is the user-facing knob.
	TTLHours int `yaml:"-"`
	// CleanupInterval is the interval between cleanup runs (default: 1 hour).
	// Internal representation; not read from YAML.
	CleanupInterval time.Duration `yaml:"-"`
	// CleanupIntervalMin is an alternative way to specify cleanup interval in minutes for YAML config.
	// Not read from the top-level Config YAML; YAMLConfig.Cache.CleanupIntervalMin
	// is the user-facing knob.
	CleanupIntervalMin int `yaml:"-"`
}

CacheConfig holds cache-specific configuration.

Only the *GB / *Hours / *Min fields are user-facing in YAML (via the human-friendly YAMLConfig.Cache.* schema). The raw byte / time.Duration fields are internal representations populated by the loader; they carry `yaml:"-"` so the struct does not falsely advertise YAML support for "max_size" / "ttl" / "cleanup_interval" etc.

type Config

type Config struct {
	Debug                   bool           `yaml:"debug"`
	CacheDir                string         `yaml:"cache_dir"`
	Mode                    int            `yaml:"mode"`
	Listen                  string         `yaml:"listen"`
	Mirrors                 MirrorConfig   `yaml:"mirrors"`
	Cache                   CacheConfig    `yaml:"cache"`
	Storage                 StorageConfig  `yaml:"storage"`
	TLS                     TLSConfig      `yaml:"tls"`
	Security                SecurityConfig `yaml:"security"`
	DistributionsConfigPath string         `yaml:"distributions_config"`
	// UpstreamKeepAlive enables HTTP keep-alive to upstream mirrors (default true).
	UpstreamKeepAlive bool `yaml:"upstream_keep_alive"`
}

Config holds all application configuration

func LoadConfigFile

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

LoadConfigFile loads configuration from a YAML file. It returns nil if the file does not exist.

The path is operator-controlled: it comes from the --config CLI flag, the APT_PROXY_CONFIG_FILE environment variable, or FindConfigFile's well-known search list. Cleaning the path before reading mirrors what FindConfigFile already does and keeps gosec G304 narrow to this single, audited site.

func MergeConfigs deprecated

func MergeConfigs(base, override *Config) *Config

MergeConfigs merges two configurations, with values from 'override' taking precedence. Zero values in 'override' do not override values in 'base'.

Deprecated: prefer MergeConfigsWithExplicit, which can distinguish "user wrote false/0" from "field defaulted". UpstreamKeepAlive in particular is a bool whose zero value (false) cannot be safely overridden here without the explicit-set mask.

func MergeConfigsWithExplicit added in v0.10.0

func MergeConfigsWithExplicit(base, override *Config, ex *cliExplicit) *Config

MergeConfigsWithExplicit is like MergeConfigs but uses the explicit mask to decide whether a zero/empty value in `override` should overwrite `base`. Pass nil to fall back to MergeConfigs' permissive zero-value handling.

func ParseFlags

func ParseFlags() (*Config, error)

ParseFlags parses command-line flags and returns a Config struct with all application settings. It validates the mode parameter and sets up global state. Configuration priority: CLI flag > environment variable > default value. Returns an error if flag parsing fails or if an invalid mode is specified.

func ParseFlagsWithConfigFile

func ParseFlagsWithConfigFile() (*Config, error)

ParseFlagsWithConfigFile parses command-line flags and optionally loads configuration from a YAML file. Priority: CLI > ENV > Config File > Default.

type MirrorConfig

type MirrorConfig struct {
	Ubuntu      string `yaml:"ubuntu"`
	UbuntuPorts string `yaml:"ubuntu_ports"`
	Debian      string `yaml:"debian"`
	CentOS      string `yaml:"centos"`
	Alpine      string `yaml:"alpine"`
}

MirrorConfig holds mirror-specific configuration

type S3Config added in v0.11.0

type S3Config struct {
	// Endpoint is the host[:port] of the S3 service, e.g. "s3.amazonaws.com"
	// or "minio.example.com:9000".
	Endpoint string `yaml:"endpoint"`
	// Region is the AWS-style region; required for AWS S3, ignored by most
	// MinIO-flavoured services.
	Region string `yaml:"region"`
	// Bucket is the destination bucket. It must already exist.
	Bucket string `yaml:"bucket"`
	// Prefix is an optional sub-path inside the bucket (e.g. "apt-proxy/")
	// allowing several deployments to share one bucket safely.
	Prefix string `yaml:"prefix"`
	// AccessKey / SecretKey are the static IAM credentials.
	AccessKey string `yaml:"access_key"`
	SecretKey string `yaml:"secret_key"`
	// SessionToken is the optional STS session token.
	SessionToken string `yaml:"session_token"`
	// UseSSL enables HTTPS to the endpoint. Defaults to true.
	UseSSL bool `yaml:"use_ssl"`
	// UsePathStyle forces path-style URLs. MinIO/Ceph generally need this.
	UsePathStyle bool `yaml:"use_path_style"`
	// InlineMaxMB is the in-memory write-buffer threshold in mebibytes.
	// Writes whose total size exceeds this value spill to a temp file before
	// being uploaded. Zero falls back to the package default (32).
	InlineMaxMB int64 `yaml:"inline_max_mb"`
	// TempDir is where spilled writes are staged. Empty means os.TempDir().
	TempDir string `yaml:"temp_dir"`
}

S3Config holds the S3-compatible-storage credentials and tunables. Endpoint, Bucket, AccessKey and SecretKey are required when Backend == "s3"; the rest of the fields have sensible defaults.

type SecurityConfig

type SecurityConfig struct {
	// APIKey is the key required for accessing protected API endpoints.
	// If empty, API authentication is disabled.
	APIKey string `yaml:"api_key"`
	// EnableAPIAuth enables API authentication when APIKey is set.
	EnableAPIAuth bool `yaml:"enable_api_auth"`
	// APIRateLimitPerMinute limits API requests per IP per minute (0 = disabled). Default 60.
	APIRateLimitPerMinute int `yaml:"api_rate_limit_per_minute"`
	// TrustedProxies is the list of CIDR networks (e.g. "10.0.0.0/8") whose
	// X-Forwarded-For header is honored for the API rate-limit / IP-based
	// audit fields. Leave empty to ignore XFF entirely (default secure).
	TrustedProxies []string `yaml:"trusted_proxies"`
}

SecurityConfig holds security-related configuration

type StorageConfig added in v0.11.0

type StorageConfig struct {
	// Backend selects which storage implementation to use.
	// Empty defaults to "disk" for backward compatibility.
	Backend string   `yaml:"backend"`
	S3      S3Config `yaml:"s3"`
}

StorageConfig selects and configures the cache storage backend. "disk" (default) keeps the cache on the local filesystem under CacheDir; "s3" puts every cached body/header into an S3-compatible bucket so that many apt-proxy instances can share a single cache pool.

type TLSConfig

type TLSConfig struct {
	// Enabled indicates whether TLS is enabled
	Enabled bool `yaml:"enabled"`
	// CertFile is the path to the TLS certificate file
	CertFile string `yaml:"cert_file"`
	// KeyFile is the path to the TLS private key file
	KeyFile string `yaml:"key_file"`
}

TLSConfig holds TLS/HTTPS configuration

type YAMLConfig

type YAMLConfig struct {
	Server struct {
		Host  string `yaml:"host"`
		Port  string `yaml:"port"`
		Debug bool   `yaml:"debug"`
	} `yaml:"server"`

	Cache struct {
		Dir                string `yaml:"dir"`
		MaxSizeGB          int64  `yaml:"max_size_gb"`
		TTLHours           int    `yaml:"ttl_hours"`
		CleanupIntervalMin int    `yaml:"cleanup_interval_min"`
	} `yaml:"cache"`

	Mirrors struct {
		Ubuntu      string `yaml:"ubuntu"`
		UbuntuPorts string `yaml:"ubuntu_ports"`
		Debian      string `yaml:"debian"`
		CentOS      string `yaml:"centos"`
		Alpine      string `yaml:"alpine"`
	} `yaml:"mirrors"`

	TLS struct {
		Enabled  bool   `yaml:"enabled"`
		CertFile string `yaml:"cert_file"`
		KeyFile  string `yaml:"key_file"`
	} `yaml:"tls"`

	Security struct {
		APIKey                string   `yaml:"api_key"`
		EnableAPIAuth         bool     `yaml:"enable_api_auth"`
		APIRateLimitPerMinute int      `yaml:"api_rate_limit_per_minute"`
		TrustedProxies        []string `yaml:"trusted_proxies"`
	} `yaml:"security"`

	Storage struct {
		Backend string `yaml:"backend"`
		S3      struct {
			Endpoint     string `yaml:"endpoint"`
			Region       string `yaml:"region"`
			Bucket       string `yaml:"bucket"`
			Prefix       string `yaml:"prefix"`
			AccessKey    string `yaml:"access_key"`
			SecretKey    string `yaml:"secret_key"`
			SessionToken string `yaml:"session_token"`
			UseSSL       bool   `yaml:"use_ssl"`
			UsePathStyle bool   `yaml:"use_path_style"`
			InlineMaxMB  int64  `yaml:"inline_max_mb"`
			TempDir      string `yaml:"temp_dir"`
		} `yaml:"s3"`
	} `yaml:"storage"`

	Mode                string `yaml:"mode"`
	DistributionsConfig string `yaml:"distributions_config"`

	// UpstreamKeepAlive enables HTTP keep-alive to upstream mirrors.
	// Pointer to distinguish "user did not set" (nil → leave to defaults
	// or CLI/ENV) from "user explicitly set false" (disable keep-alive).
	UpstreamKeepAlive *bool `yaml:"upstream_keep_alive"`
}

YAMLConfig represents the YAML configuration file structure. It uses a more user-friendly structure that maps to the internal Config.

Jump to

Keyboard shortcuts

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