Add wildcard hostname rule to kubernetes gateway

This commit is contained in:
Joel Berger 2021-04-29 10:18:04 -05:00 committed by GitHub
parent ab71dad51a
commit 70a02158e5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 307 additions and 12 deletions

View file

@ -423,7 +423,17 @@ func (p *Provider) fillGatewayConf(client Client, gateway *v1alpha1.Gateway, con
continue
}
hostRule := hostRule(httpRoute.Spec)
hostRule, err := hostRule(httpRoute.Spec)
if err != nil {
listenerStatuses[i].Conditions = append(listenerStatuses[i].Conditions, metav1.Condition{
Type: string(v1alpha1.ListenerConditionResolvedRefs),
Status: metav1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: string(v1alpha1.ListenerReasonDegradedRoutes),
Message: fmt.Sprintf("Skipping HTTPRoute %s: invalid hostname: %v", httpRoute.Name, err),
})
continue
}
for _, routeRule := range httpRoute.Spec.Rules {
rule, err := extractRule(routeRule, hostRule)
@ -572,20 +582,49 @@ func (p *Provider) makeGatewayStatus(listenerStatuses []v1alpha1.ListenerStatus)
return gatewayStatus, nil
}
func hostRule(httpRouteSpec v1alpha1.HTTPRouteSpec) string {
hostRule := ""
for i, hostname := range httpRouteSpec.Hostnames {
if i > 0 && len(hostname) > 0 {
hostRule += "`, `"
func hostRule(httpRouteSpec v1alpha1.HTTPRouteSpec) (string, error) {
var hostNames []string
var hostRegexNames []string
for _, hostname := range httpRouteSpec.Hostnames {
host := string(hostname)
// When unspecified, "", or *, all hostnames are matched.
// This field can be omitted for protocols that don't require hostname based matching.
// TODO Refactor this when building support for TLS options.
if host == "*" || host == "" {
return "", nil
}
hostRule += string(hostname)
wildcard := strings.Count(host, "*")
if wildcard == 0 {
hostNames = append(hostNames, host)
continue
}
// https://gateway-api.sigs.k8s.io/spec/#networking.x-k8s.io/v1alpha1.Hostname
if !strings.HasPrefix(host, "*.") || wildcard > 1 {
return "", fmt.Errorf("invalid rule: %q", host)
}
hostRegexNames = append(hostRegexNames, strings.Replace(host, "*.", "{subdomain:[a-zA-Z0-9-]+}.", 1))
}
if hostRule != "" {
return "Host(`" + hostRule + "`)"
var res string
if len(hostNames) > 0 {
res = "Host(`" + strings.Join(hostNames, "`, `") + "`)"
}
return ""
if len(hostRegexNames) == 0 {
return res, nil
}
hostRegexp := "HostRegexp(`" + strings.Join(hostRegexNames, "`, `") + "`)"
if len(res) > 0 {
return "(" + res + " || " + hostRegexp + ")", nil
}
return hostRegexp, nil
}
func extractRule(routeRule v1alpha1.HTTPRouteRule, hostRule string) (string, error) {