package config import ( "errors" "fmt" "net" "strconv" "strings" ) const ( defaultKafkaBrokers = "localhost:9092" kafkaBrokersSeparator = "," ) // parseKafkaBrokers splits a comma-separated broker list. Empty entries are // kept so that validation can reject values such as "a:9092,,b:9092". func parseKafkaBrokers(raw string) []string { if strings.TrimSpace(raw) == "" { return nil } entries := strings.Split(raw, kafkaBrokersSeparator) brokers := make([]string, 0, len(entries)) for _, entry := range entries { brokers = append(brokers, strings.TrimSpace(entry)) } return brokers } func (config Config) ValidateKafka() error { if len(config.KafkaBrokers) == 0 { return errors.New("Config.ValidateKafka - KAFKA_BROKERS must not be empty") } for index, broker := range config.KafkaBrokers { // Report the position instead of the value so a mistyped entry with // embedded credentials does not reach logs. if !validKafkaBroker(broker) { return fmt.Errorf("Config.ValidateKafka - KAFKA_BROKERS entry %d must be a host:port address with a nonzero port", index+1) } } return nil } // validKafkaBroker accepts a hostname or IP address with a port in 1-65535. // URL schemes, user info, and paths are rejected because Kafka clients expect // plain bootstrap addresses. func validKafkaBroker(broker string) bool { host, port, err := net.SplitHostPort(broker) if err != nil { return false } number, err := strconv.Atoi(port) if err != nil || number < 1 || number > maxPortNumber { return false } return net.ParseIP(host) != nil || validHostname(host) } func validHostname(host string) bool { if host == "" { return false } for _, label := range strings.Split(host, ".") { if !validHostnameLabel(label) { return false } } return true } func validHostnameLabel(label string) bool { if label == "" || strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") { return false } for _, character := range label { isLetter := (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') isDigit := character >= '0' && character <= '9' if !isLetter && !isDigit && character != '-' && character != '_' { return false } } return true }