| 1 | package config |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "log" |
| 6 | "net" |
| 7 | "regexp" |
| 8 | "strings" |
| 9 | |
| 10 | "github.com/spf13/viper" |
| 11 | ) |
| 12 | |
| 13 | var ( |
| 14 | AppConfig Config |
| 15 | viperInstance *viper.Viper |
| 16 | Version = "1.9.0" |
| 17 | ) |
| 18 | |
| 19 | type ServerConfig struct { |
| 20 | ListenAddr string `mapstructure:"listen_addr"` |
| 21 | ListenPort int `mapstructure:"listen_port"` |
| 22 | CertPath string `mapstructure:"cert_path"` |
| 23 | CertKeyPath string `mapstructure:"cert_key_path"` |
| 24 | RealIP bool `mapstructure:"real_ip"` |
| 25 | Whitelist []string `mapstructure:"whitelist"` |
| 26 | } |
| 27 | |
| 28 | type LogConfig struct { |
| 29 | Operator string `mapstructure:"operator"` |
| 30 | URL string `mapstructure:"url"` |
| 31 | Description string `mapstructure:"description"` |
| 32 | } |
| 33 | |
| 34 | type BufferSizes struct { |
| 35 | Websocket int `mapstructure:"websocket"` |
| 36 | CTLog int `mapstructure:"ctlog"` |
| 37 | BroadcastManager int `mapstructure:"broadcastmanager"` |
| 38 | } |
| 39 | |
| 40 | type Config struct { |
| 41 | Webserver struct { |
| 42 | ServerConfig `mapstructure:",squash"` |
| 43 | FullURL string `mapstructure:"full_url"` |
| 44 | LiteURL string `mapstructure:"lite_url"` |
| 45 | DomainsOnlyURL string `mapstructure:"domains_only_url"` |
| 46 | CompressionEnabled bool `mapstructure:"compression_enabled"` |
| 47 | } |
| 48 | Prometheus struct { |
| 49 | ServerConfig `mapstructure:",squash"` |
| 50 | Enabled bool `mapstructure:"enabled"` |
| 51 | MetricsURL string `mapstructure:"metrics_url"` |
| 52 | ExposeSystemMetrics bool `mapstructure:"expose_system_metrics"` |
| 53 | } |
| 54 | General struct { |
| 55 | // DisableDefaultLogs indicates whether the default logs used in Google Chrome and provided by Google should be disabled. |
| 56 | DisableDefaultLogs bool `mapstructure:"disable_default_logs"` |
| 57 | // AdditionalLogs contains additional logs provided by the user that can be used in addition to the default logs. |
| 58 | AdditionalLogs []LogConfig `mapstructure:"additional_logs"` |
| 59 | AdditionalTiledLogs []LogConfig `mapstructure:"additional_tiled_logs"` |
| 60 | BufferSizes BufferSizes `mapstructure:"buffer_sizes"` |
| 61 | DropOldLogs *bool `mapstructure:"drop_old_logs"` |
| 62 | Recovery struct { |
| 63 | Enabled bool `mapstructure:"enabled"` |
| 64 | CTIndexFile string `mapstructure:"ct_index_file"` |
| 65 | } `mapstructure:"recovery"` |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | // ReadConfig reads the configuration using Viper and returns a filled Config struct. |
| 70 | // It also validates and stores the result in AppConfig. |
| 71 | func ReadConfig(configPath string) (Config, error) { |
| 72 | v := initViper(configPath) |
| 73 | return loadConfigFromViper(v) |
| 74 | } |
| 75 | |
| 76 | // ValidateConfig validates the config file and returns an error if the config is invalid. |
| 77 | func ValidateConfig(configPath string) error { |
| 78 | _, parseErr := ReadConfig(configPath) |
| 79 | return parseErr |
| 80 | } |
| 81 | |
| 82 | // initViper sets up the viper instance with defaults, config file and environment variable support. |
| 83 | // configPath is the path to the YAML config file (e.g. "config.yaml"). |
| 84 | // Environment variables are mapped with the prefix "CERTSTREAM" and "_" as key delimiter. |
| 85 | // Example: CERTSTREAM_WEBSERVER_LISTEN_PORT overrides webserver.listen_port. |
| 86 | func initViper(configPath string) *viper.Viper { |
| 87 | v := viper.NewWithOptions(viper.KeyDelimiter(".")) |
| 88 | |
| 89 | // Defaults |
| 90 | v.SetDefault("webserver.listen_addr", "0.0.0.0") |
| 91 | v.SetDefault("webserver.listen_port", 8080) |
| 92 | v.SetDefault("webserver.full_url", "/full-stream") |
| 93 | v.SetDefault("webserver.lite_url", "/") |
| 94 | v.SetDefault("webserver.domains_only_url", "/domains-only") |
| 95 | v.SetDefault("webserver.real_ip", false) |
| 96 | v.SetDefault("webserver.compression_enabled", false) |
| 97 | |
| 98 | v.SetDefault("prometheus.enabled", false) |
| 99 | v.SetDefault("prometheus.listen_addr", "0.0.0.0") |
| 100 | v.SetDefault("prometheus.listen_port", 9090) |
| 101 | v.SetDefault("prometheus.metrics_url", "/metrics") |
| 102 | v.SetDefault("prometheus.expose_system_metrics", false) |
| 103 | v.SetDefault("prometheus.real_ip", false) |
| 104 | |
| 105 | v.SetDefault("general.disable_default_logs", false) |
| 106 | v.SetDefault("general.buffer_sizes.websocket", 300) |
| 107 | v.SetDefault("general.buffer_sizes.ctlog", 1000) |
| 108 | v.SetDefault("general.buffer_sizes.broadcastmanager", 10000) |
| 109 | v.SetDefault("general.drop_old_logs", true) |
| 110 | v.SetDefault("general.recovery.enabled", false) |
| 111 | v.SetDefault("general.recovery.ct_index_file", "./ct_index.json") |
| 112 | |
| 113 | // TODO check for missing file?! |
| 114 | // Config file |
| 115 | if configPath != "" { |
| 116 | v.SetConfigFile(configPath) |
| 117 | } else { |
| 118 | v.SetConfigName("config") |
| 119 | v.AddConfigPath(".") |
| 120 | v.AddConfigPath("/app/config") |
| 121 | } |
| 122 | |
| 123 | v.SetConfigType("yaml") |
| 124 | |
| 125 | if err := v.ReadInConfig(); err != nil { |
| 126 | var notFound viper.ConfigFileNotFoundError |
| 127 | if errors.As(err, ¬Found) { |
| 128 | log.Println("No config file found, using defaults and environment variables only") |
| 129 | } else { |
| 130 | log.Fatalf("Error reading config file: %v", err) |
| 131 | } |
| 132 | } else { |
| 133 | log.Printf("Using config file: %s\n", v.ConfigFileUsed()) |
| 134 | } |
| 135 | |
| 136 | // Environment variables |
| 137 | // Prefix: CERTSTREAM (e.g. CERTSTREAM_WEBSERVER_LISTEN_PORT) |
| 138 | // Viper uses "." as key delimiter internally; environment variables use "_". |
| 139 | // We replace "." with "_" when looking up env vars automatically. |
| 140 | v.SetEnvPrefix("CERTSTREAM") |
| 141 | v.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) |
| 142 | v.AutomaticEnv() |
| 143 | |
| 144 | viperInstance = v |
| 145 | return v |
| 146 | } |
| 147 | |
| 148 | // loadConfigFromViper unmarshals a viper instance into a Config struct, validates it |
| 149 | // and stores the result in AppConfig. |
| 150 | func loadConfigFromViper(v *viper.Viper) (Config, error) { |
| 151 | var cfg Config |
| 152 | |
| 153 | if err := v.Unmarshal(&cfg); err != nil { |
| 154 | return cfg, err |
| 155 | } |
| 156 | |
| 157 | if !validateConfig(&cfg) { |
| 158 | return cfg, errors.New("invalid configuration") |
| 159 | } |
| 160 | |
| 161 | AppConfig = cfg |
| 162 | return cfg, nil |
| 163 | } |
| 164 | |
| 165 | // validateConfig validates the config values and sets defaults for missing values. |
| 166 | func validateConfig(config *Config) bool { |
| 167 | // Still matches invalid IP addresses but good enough for detecting completely wrong formats |
| 168 | URLPathRegex := regexp.MustCompile(`^(/[a-zA-Z0-9\-._]+)+$`) |
| 169 | URLRegex := regexp.MustCompile(`^https?://[a-zA-Z0-9\-._]+(:[0-9]+)?(/[a-zA-Z0-9\-._]+)*/?$`) |
| 170 | |
| 171 | // Check webserver config |
| 172 | if config.Webserver.ListenAddr == "" || net.ParseIP(config.Webserver.ListenAddr) == nil { |
| 173 | log.Fatalln("Webhook listen IP is not a valid IP: ", config.Webserver.ListenAddr) |
| 174 | return false |
| 175 | } |
| 176 | |
| 177 | if config.Webserver.ListenPort == 0 { |
| 178 | log.Fatalln("Webhook listen port is not set") |
| 179 | return false |
| 180 | } |
| 181 | |
| 182 | if config.Webserver.FullURL == "" || !URLPathRegex.MatchString(config.Webserver.FullURL) { |
| 183 | log.Println("Webhook full URL is not set or does not match pattern '/...'") |
| 184 | config.Webserver.FullURL = "/full-stream" |
| 185 | } |
| 186 | |
| 187 | if config.Webserver.LiteURL == "" || !URLPathRegex.MatchString(config.Webserver.FullURL) { |
| 188 | log.Println("Webhook lite URL is not set or does not match pattern '/...'") |
| 189 | config.Webserver.LiteURL = "/" |
| 190 | } |
| 191 | |
| 192 | if config.Webserver.DomainsOnlyURL == "" || !URLPathRegex.MatchString(config.Webserver.DomainsOnlyURL) { |
| 193 | log.Println("Webhook domains only URL is not set or does not match pattern '/...'") |
| 194 | config.Webserver.FullURL = "/domains-only" |
| 195 | } |
| 196 | |
| 197 | if config.Webserver.FullURL == config.Webserver.LiteURL { |
| 198 | log.Fatalln("Webhook full URL is the same as lite URL - please fix the config!") |
| 199 | } |
| 200 | |
| 201 | if config.Webserver.DomainsOnlyURL == "" { |
| 202 | config.Webserver.FullURL = "/domains-only" |
| 203 | } |
| 204 | |
| 205 | if config.Prometheus.Enabled { |
| 206 | if config.Prometheus.ListenAddr == "" || net.ParseIP(config.Prometheus.ListenAddr) == nil { |
| 207 | log.Fatalln("Metrics export IP is not a valid IP") |
| 208 | return false |
| 209 | } |
| 210 | |
| 211 | if config.Prometheus.ListenPort == 0 { |
| 212 | log.Fatalln("Metrics export port is not set") |
| 213 | return false |
| 214 | } |
| 215 | |
| 216 | if config.Prometheus.Whitelist == nil { |
| 217 | config.Prometheus.Whitelist = []string{} |
| 218 | } |
| 219 | |
| 220 | // Check if IPs in whitelist match pattern |
| 221 | for _, ip := range config.Prometheus.Whitelist { |
| 222 | if net.ParseIP(ip) == nil { |
| 223 | // Provided entry is not an IP, check if it's a CIDR range |
| 224 | _, _, err := net.ParseCIDR(ip) |
| 225 | if err != nil { |
| 226 | log.Fatalln("Invalid IP in metrics whitelist: ", ip) |
| 227 | return false |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | var validLogs, validTiledLogs []LogConfig |
| 234 | if len(config.General.AdditionalLogs) > 0 { |
| 235 | for _, ctLog := range config.General.AdditionalLogs { |
| 236 | if !URLRegex.MatchString(ctLog.URL) { |
| 237 | log.Println("Ignoring invalid additional log URL: ", ctLog.URL) |
| 238 | continue |
| 239 | } |
| 240 | |
| 241 | validLogs = append(validLogs, ctLog) |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | if len(config.General.AdditionalTiledLogs) > 0 { |
| 246 | for _, ctLog := range config.General.AdditionalTiledLogs { |
| 247 | if !URLRegex.MatchString(ctLog.URL) { |
| 248 | log.Println("Ignoring invalid additional log URL: ", ctLog.URL) |
| 249 | continue |
| 250 | } |
| 251 | |
| 252 | validTiledLogs = append(validTiledLogs, ctLog) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | config.General.AdditionalLogs = validLogs |
| 257 | config.General.AdditionalTiledLogs = validTiledLogs |
| 258 | |
| 259 | if len(config.General.AdditionalLogs) == 0 && len(config.General.AdditionalTiledLogs) == 0 && config.General.DisableDefaultLogs { |
| 260 | log.Fatalln("Default logs are disabled, but no additional logs are configured. Please add at least one log to the config or enable default logs.") |
| 261 | } |
| 262 | |
| 263 | if config.General.BufferSizes.Websocket <= 0 { |
| 264 | config.General.BufferSizes.Websocket = 300 |
| 265 | } |
| 266 | |
| 267 | if config.General.BufferSizes.CTLog <= 0 { |
| 268 | config.General.BufferSizes.CTLog = 1000 |
| 269 | } |
| 270 | |
| 271 | if config.General.BufferSizes.BroadcastManager <= 0 { |
| 272 | config.General.BufferSizes.BroadcastManager = 10000 |
| 273 | } |
| 274 | |
| 275 | // If the cleanup flag is not set, default to true |
| 276 | if config.General.DropOldLogs == nil { |
| 277 | log.Println("drop_old_logs is not set, defaulting to true") |
| 278 | defaultCleanup := true |
| 279 | config.General.DropOldLogs = &defaultCleanup |
| 280 | } |
| 281 | |
| 282 | if config.General.Recovery.Enabled && config.General.Recovery.CTIndexFile == "" { |
| 283 | log.Println("Recovery enabled but no index file specified. Defaulting to ./ct_index.json") |
| 284 | config.General.Recovery.CTIndexFile = "./ct_index.json" |
| 285 | } |
| 286 | |
| 287 | return true |
| 288 | } |