TUN-3464: Newtype to wrap []ingress.Rule

This commit is contained in:
Adam Chalmers 2020-10-15 12:41:50 -05:00
parent 4a4a1bb6b1
commit c96b9e8d8f
5 changed files with 59 additions and 50 deletions

View File

@ -196,15 +196,15 @@ func ValidateUrl(c *cli.Context, allowFromArgs bool) (string, error) {
return validUrl, err return validUrl, err
} }
func ReadRules(c *cli.Context) ([]ingress.Rule, error) { func ReadRules(c *cli.Context) (ingress.Ingress, error) {
configFilePath := c.String("config") configFilePath := c.String("config")
if configFilePath == "" { if configFilePath == "" {
return nil, ErrNoConfigFile return ingress.Ingress{}, ErrNoConfigFile
} }
fmt.Printf("Reading from config file %s\n", configFilePath) fmt.Printf("Reading from config file %s\n", configFilePath)
configBytes, err := ioutil.ReadFile(configFilePath) configBytes, err := ioutil.ReadFile(configFilePath)
if err != nil { if err != nil {
return nil, err return ingress.Ingress{}, err
} }
rules, err := ingress.ParseIngress(configBytes) rules, err := ingress.ParseIngress(configBytes)
return rules, err return rules, err

View File

@ -219,7 +219,7 @@ func prepareTunnelConfig(
} }
dialContext := dialer.DialContext dialContext := dialer.DialContext
var ingressRules []ingress.Rule var ingressRules ingress.Ingress
if namedTunnel != nil { if namedTunnel != nil {
clientUUID, err := uuid.NewRandom() clientUUID, err := uuid.NewRandom()
if err != nil { if err != nil {
@ -235,14 +235,13 @@ func prepareTunnelConfig(
if err != nil && err != ingress.ErrNoIngressRules { if err != nil && err != ingress.ErrNoIngressRules {
return nil, err return nil, err
} }
if len(ingressRules) > 0 && c.IsSet("url") { if !ingressRules.IsEmpty() && c.IsSet("url") {
return nil, ingress.ErrURLIncompatibleWithIngress return nil, ingress.ErrURLIncompatibleWithIngress
} }
} }
var originURL string var originURL string
isUsingMultipleOrigins := len(ingressRules) > 0 if ingressRules.IsEmpty() {
if !isUsingMultipleOrigins {
originURL, err = config.ValidateUrl(c, compatibilityMode) originURL, err = config.ValidateUrl(c, compatibilityMode)
if err != nil { if err != nil {
logger.Errorf("Error validating origin URL: %s", err) logger.Errorf("Error validating origin URL: %s", err)
@ -275,10 +274,10 @@ func prepareTunnelConfig(
// List all origin URLs that require validation // List all origin URLs that require validation
var originURLs []string var originURLs []string
if !isUsingMultipleOrigins { if ingressRules.IsEmpty() {
originURLs = append(originURLs, originURL) originURLs = append(originURLs, originURL)
} else { } else {
for _, rule := range ingressRules { for _, rule := range ingressRules.Rules {
originURLs = append(originURLs, rule.Service.String()) originURLs = append(originURLs, rule.Service.String())
} }
} }

View File

@ -33,7 +33,7 @@ type Rule struct {
Service *url.URL Service *url.URL
} }
func (r Rule) String() string { func (r Rule) MultiLineString() string {
var out strings.Builder var out strings.Builder
if r.Hostname != "" { if r.Hostname != "" {
out.WriteString("\thostname: ") out.WriteString("\thostname: ")
@ -59,13 +59,13 @@ func (r *Rule) Matches(hostname, path string) bool {
// FindMatchingRule returns the index of the Ingress Rule which matches the given // FindMatchingRule returns the index of the Ingress Rule which matches the given
// hostname and path. This function assumes the last rule matches everything, // hostname and path. This function assumes the last rule matches everything,
// which is the case if the rules were instantiated via the ingress#Validate method // which is the case if the rules were instantiated via the ingress#Validate method
func FindMatchingRule(hostname, path string, rules []Rule) int { func (ing Ingress) FindMatchingRule(hostname, path string) int {
for i, rule := range rules { for i, rule := range ing.Rules {
if rule.Matches(hostname, path) { if rule.Matches(hostname, path) {
return i return i
} }
} }
return len(rules) - 1 return len(ing.Rules) - 1
} }
func matchHost(ruleHost, reqHost string) bool { func matchHost(ruleHost, reqHost string) bool {
@ -87,51 +87,61 @@ type unvalidatedRule struct {
Service string Service string
} }
type ingress struct { type unvalidatedIngress struct {
Ingress []unvalidatedRule Ingress []unvalidatedRule
Url string URL string
} }
func (ing ingress) validate() ([]Rule, error) { // Ingress maps eyeball requests to origins.
if ing.Url != "" { type Ingress struct {
return nil, ErrURLIncompatibleWithIngress Rules []Rule
}
// IsEmpty checks if there are any ingress rules.
func (ing Ingress) IsEmpty() bool {
return len(ing.Rules) == 0
}
func (ing unvalidatedIngress) validate() (Ingress, error) {
if ing.URL != "" {
return Ingress{}, ErrURLIncompatibleWithIngress
} }
rules := make([]Rule, len(ing.Ingress)) rules := make([]Rule, len(ing.Ingress))
for i, r := range ing.Ingress { for i, r := range ing.Ingress {
service, err := url.Parse(r.Service) service, err := url.Parse(r.Service)
if err != nil { if err != nil {
return nil, err return Ingress{}, err
} }
if service.Scheme == "" || service.Hostname() == "" { if service.Scheme == "" || service.Hostname() == "" {
return nil, fmt.Errorf("The service %s must have a scheme and a hostname", r.Service) return Ingress{}, fmt.Errorf("The service %s must have a scheme and a hostname", r.Service)
} }
if service.Path != "" { if service.Path != "" {
return nil, fmt.Errorf("%s is an invalid address, ingress rules don't support proxying to a different path on the origin service. The path will be the same as the eyeball request's path.", r.Service) return Ingress{}, fmt.Errorf("%s is an invalid address, ingress rules don't support proxying to a different path on the origin service. The path will be the same as the eyeball request's path.", r.Service)
} }
// Ensure that there are no wildcards anywhere except the first character // Ensure that there are no wildcards anywhere except the first character
// of the hostname. // of the hostname.
if strings.LastIndex(r.Hostname, "*") > 0 { if strings.LastIndex(r.Hostname, "*") > 0 {
return nil, errBadWildcard return Ingress{}, errBadWildcard
} }
// The last rule should catch all hostnames. // The last rule should catch all hostnames.
isCatchAllRule := (r.Hostname == "" || r.Hostname == "*") && r.Path == "" isCatchAllRule := (r.Hostname == "" || r.Hostname == "*") && r.Path == ""
isLastRule := i == len(ing.Ingress)-1 isLastRule := i == len(ing.Ingress)-1
if isLastRule && !isCatchAllRule { if isLastRule && !isCatchAllRule {
return nil, errLastRuleNotCatchAll return Ingress{}, errLastRuleNotCatchAll
} }
// ONLY the last rule should catch all hostnames. // ONLY the last rule should catch all hostnames.
if !isLastRule && isCatchAllRule { if !isLastRule && isCatchAllRule {
return nil, errRuleShouldNotBeCatchAll{i: i, hostname: r.Hostname} return Ingress{}, errRuleShouldNotBeCatchAll{i: i, hostname: r.Hostname}
} }
var pathRegex *regexp.Regexp var pathRegex *regexp.Regexp
if r.Path != "" { if r.Path != "" {
pathRegex, err = regexp.Compile(r.Path) pathRegex, err = regexp.Compile(r.Path)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "Rule #%d has an invalid regex", i+1) return Ingress{}, errors.Wrapf(err, "Rule #%d has an invalid regex", i+1)
} }
} }
@ -141,7 +151,7 @@ func (ing ingress) validate() ([]Rule, error) {
Path: pathRegex, Path: pathRegex,
} }
} }
return rules, nil return Ingress{Rules: rules}, nil
} }
type errRuleShouldNotBeCatchAll struct { type errRuleShouldNotBeCatchAll struct {
@ -155,24 +165,24 @@ func (e errRuleShouldNotBeCatchAll) Error() string {
"will never be triggered.", e.i+1, e.hostname) "will never be triggered.", e.i+1, e.hostname)
} }
func ParseIngress(rawYAML []byte) ([]Rule, error) { func ParseIngress(rawYAML []byte) (Ingress, error) {
var ing ingress var ing unvalidatedIngress
if err := yaml.Unmarshal(rawYAML, &ing); err != nil { if err := yaml.Unmarshal(rawYAML, &ing); err != nil {
return nil, err return Ingress{}, err
} }
if len(ing.Ingress) == 0 { if len(ing.Ingress) == 0 {
return nil, ErrNoIngressRules return Ingress{}, ErrNoIngressRules
} }
return ing.validate() return ing.validate()
} }
// RuleCommand checks which ingress rule matches the given request URL. // RuleCommand checks which ingress rule matches the given request URL.
func RuleCommand(rules []Rule, requestURL *url.URL) error { func RuleCommand(ing Ingress, requestURL *url.URL) error {
if requestURL.Hostname() == "" { if requestURL.Hostname() == "" {
return fmt.Errorf("%s is malformed and doesn't have a hostname", requestURL) return fmt.Errorf("%s is malformed and doesn't have a hostname", requestURL)
} }
i := FindMatchingRule(requestURL.Hostname(), requestURL.Path, rules) i := ing.FindMatchingRule(requestURL.Hostname(), requestURL.Path)
fmt.Printf("Matched rule #%d\n", i+1) fmt.Printf("Matched rule #%d\n", i+1)
fmt.Println(rules[i].String()) fmt.Println(ing.Rules[i].MultiLineString())
return nil return nil
} }

View File

@ -20,7 +20,7 @@ func Test_parseIngress(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
args args args args
want []Rule want Ingress
wantErr bool wantErr bool
}{ }{
{ {
@ -37,7 +37,7 @@ ingress:
- hostname: "*" - hostname: "*"
service: https://localhost:8001 service: https://localhost:8001
`}, `},
want: []Rule{ want: Ingress{Rules: []Rule{
{ {
Hostname: "tunnel1.example.com", Hostname: "tunnel1.example.com",
Service: localhost8000, Service: localhost8000,
@ -46,7 +46,7 @@ ingress:
Hostname: "*", Hostname: "*",
Service: localhost8001, Service: localhost8001,
}, },
}, }},
}, },
{ {
name: "Extra keys", name: "Extra keys",
@ -56,12 +56,12 @@ ingress:
service: https://localhost:8000 service: https://localhost:8000
extraKey: extraValue extraKey: extraValue
`}, `},
want: []Rule{ want: Ingress{Rules: []Rule{
{ {
Hostname: "*", Hostname: "*",
Service: localhost8000, Service: localhost8000,
}, },
}, }},
}, },
{ {
name: "Hostname can be omitted", name: "Hostname can be omitted",
@ -69,11 +69,11 @@ extraKey: extraValue
ingress: ingress:
- service: https://localhost:8000 - service: https://localhost:8000
`}, `},
want: []Rule{ want: Ingress{Rules: []Rule{
{ {
Service: localhost8000, Service: localhost8000,
}, },
}, }},
}, },
{ {
name: "Invalid service", name: "Invalid service",
@ -308,13 +308,13 @@ ingress:
- hostname: "*" - hostname: "*"
service: https://localhost:8002 service: https://localhost:8002
` `
rules, err := ParseIngress([]byte(rulesYAML)) ing, err := ParseIngress([]byte(rulesYAML))
if err != nil { if err != nil {
b.Error(err) b.Error(err)
} }
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
FindMatchingRule("tunnel1.example.com", "", rules) ing.FindMatchingRule("tunnel1.example.com", "")
FindMatchingRule("tunnel2.example.com", "", rules) ing.FindMatchingRule("tunnel2.example.com", "")
FindMatchingRule("tunnel3.example.com", "", rules) ing.FindMatchingRule("tunnel3.example.com", "")
} }
} }

View File

@ -93,7 +93,7 @@ type TunnelConfig struct {
NamedTunnel *NamedTunnelConfig NamedTunnel *NamedTunnelConfig
ReplaceExisting bool ReplaceExisting bool
TunnelEventChan chan<- ui.TunnelEvent TunnelEventChan chan<- ui.TunnelEvent
IngressRules []ingress.Rule IngressRules ingress.Ingress
} }
type dupConnRegisterTunnelError struct{} type dupConnRegisterTunnelError struct{}
@ -619,7 +619,7 @@ func LogServerInfo(
type TunnelHandler struct { type TunnelHandler struct {
originUrl string originUrl string
ingressRules []ingress.Rule ingressRules ingress.Ingress
httpHostHeader string httpHostHeader string
muxer *h2mux.Muxer muxer *h2mux.Muxer
httpClient http.RoundTripper httpClient http.RoundTripper
@ -645,7 +645,7 @@ func NewTunnelHandler(ctx context.Context,
// Check single-origin config // Check single-origin config
var originURL string var originURL string
var err error var err error
if len(config.IngressRules) == 0 { if config.IngressRules.IsEmpty() {
originURL, err = validation.ValidateUrl(config.OriginUrl) originURL, err = validation.ValidateUrl(config.OriginUrl)
if err != nil { if err != nil {
return nil, "", fmt.Errorf("unable to parse origin URL %#v", originURL) return nil, "", fmt.Errorf("unable to parse origin URL %#v", originURL)
@ -727,9 +727,9 @@ func (h *TunnelHandler) createRequest(stream *h2mux.MuxedStream) (*http.Request,
return nil, errors.Wrap(err, "invalid request received") return nil, errors.Wrap(err, "invalid request received")
} }
h.AppendTagHeaders(req) h.AppendTagHeaders(req)
if len(h.ingressRules) > 0 { if !h.ingressRules.IsEmpty() {
ruleNumber := ingress.FindMatchingRule(req.Host, req.URL.Path, h.ingressRules) ruleNumber := h.ingressRules.FindMatchingRule(req.Host, req.URL.Path)
destination := h.ingressRules[ruleNumber].Service destination := h.ingressRules.Rules[ruleNumber].Service
req.URL.Host = destination.Host req.URL.Host = destination.Host
req.URL.Scheme = destination.Scheme req.URL.Scheme = destination.Scheme
} }