internal/source/gitlab/client/utils.go (43 lines of code) (raw):
package client
import (
"fmt"
"regexp"
"strings"
"gitlab.com/gitlab-org/labkit/log"
)
// Reference for below limits: https://www.ietf.org/rfc/rfc1035.txt
const FQDNMaxLength = 255
const DNSLabelMaxLength = 63
var (
ErrHostnameEmpty = fmt.Errorf("hostname cannot be empty")
ErrHostnameToLong = fmt.Errorf("hostname is too long")
ErrHostnameInvalid = fmt.Errorf("hostname is invalid")
regexHostName = regexp.MustCompile(`^[a-zA-Z0-9._\:\[\]-]+$`)
protocolDivider = "://"
)
// ValidateHostName Validates the hostname to ensure it is a valid and well-formed URL
func ValidateHostName(hostname string) error {
// Handle potential protocols in the hostname for backwards compatibility.
if strings.Contains(hostname, protocolDivider) {
log.Info("hostname has protocol divider")
if parts := strings.Split(hostname, protocolDivider); len(parts) > 1 {
hostname = parts[1]
}
}
if hostname == "" {
return ErrHostnameEmpty
}
// Check if the hostname is too long
if len(hostname) > FQDNMaxLength {
return ErrHostnameToLong
}
labels := strings.Split(hostname, ".")
for _, label := range labels {
if len(label) > DNSLabelMaxLength {
return ErrHostnameToLong
}
}
// Check if the hostname contains invalid characters
if !isValidHostname(hostname) {
return ErrHostnameInvalid
}
return nil
}
// isValidHostname checks if the hostname contains only valid characters (a-z, A-Z, 0-9, ., -, _)
func isValidHostname(hostname string) bool {
return regexHostName.MatchString(hostname)
}