diff --git a/cmd/cloudflared/config/configuration.go b/cmd/cloudflared/config/configuration.go index 620ade51..344a09fe 100644 --- a/cmd/cloudflared/config/configuration.go +++ b/cmd/cloudflared/config/configuration.go @@ -196,15 +196,15 @@ func ValidateUrl(c *cli.Context, allowFromArgs bool) (string, error) { return validUrl, err } -func ReadRules(c *cli.Context) ([]ingress.Rule, error) { +func ReadRules(c *cli.Context) (ingress.Ingress, error) { configFilePath := c.String("config") if configFilePath == "" { - return nil, ErrNoConfigFile + return ingress.Ingress{}, ErrNoConfigFile } fmt.Printf("Reading from config file %s\n", configFilePath) configBytes, err := ioutil.ReadFile(configFilePath) if err != nil { - return nil, err + return ingress.Ingress{}, err } rules, err := ingress.ParseIngress(configBytes) return rules, err diff --git a/cmd/cloudflared/tunnel/configuration.go b/cmd/cloudflared/tunnel/configuration.go index c91d1008..b67930ef 100644 --- a/cmd/cloudflared/tunnel/configuration.go +++ b/cmd/cloudflared/tunnel/configuration.go @@ -219,7 +219,7 @@ func prepareTunnelConfig( } dialContext := dialer.DialContext - var ingressRules []ingress.Rule + var ingressRules ingress.Ingress if namedTunnel != nil { clientUUID, err := uuid.NewRandom() if err != nil { @@ -235,14 +235,13 @@ func prepareTunnelConfig( if err != nil && err != ingress.ErrNoIngressRules { return nil, err } - if len(ingressRules) > 0 && c.IsSet("url") { + if !ingressRules.IsEmpty() && c.IsSet("url") { return nil, ingress.ErrURLIncompatibleWithIngress } } var originURL string - isUsingMultipleOrigins := len(ingressRules) > 0 - if !isUsingMultipleOrigins { + if ingressRules.IsEmpty() { originURL, err = config.ValidateUrl(c, compatibilityMode) if err != nil { logger.Errorf("Error validating origin URL: %s", err) @@ -275,10 +274,10 @@ func prepareTunnelConfig( // List all origin URLs that require validation var originURLs []string - if !isUsingMultipleOrigins { + if ingressRules.IsEmpty() { originURLs = append(originURLs, originURL) } else { - for _, rule := range ingressRules { + for _, rule := range ingressRules.Rules { originURLs = append(originURLs, rule.Service.String()) } } diff --git a/ingress/ingress.go b/ingress/ingress.go index 3489bbcb..931c7505 100644 --- a/ingress/ingress.go +++ b/ingress/ingress.go @@ -33,7 +33,7 @@ type Rule struct { Service *url.URL } -func (r Rule) String() string { +func (r Rule) MultiLineString() string { var out strings.Builder if r.Hostname != "" { 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 // 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 -func FindMatchingRule(hostname, path string, rules []Rule) int { - for i, rule := range rules { +func (ing Ingress) FindMatchingRule(hostname, path string) int { + for i, rule := range ing.Rules { if rule.Matches(hostname, path) { return i } } - return len(rules) - 1 + return len(ing.Rules) - 1 } func matchHost(ruleHost, reqHost string) bool { @@ -87,51 +87,61 @@ type unvalidatedRule struct { Service string } -type ingress struct { +type unvalidatedIngress struct { Ingress []unvalidatedRule - Url string + URL string } -func (ing ingress) validate() ([]Rule, error) { - if ing.Url != "" { - return nil, ErrURLIncompatibleWithIngress +// Ingress maps eyeball requests to origins. +type Ingress struct { + 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)) for i, r := range ing.Ingress { service, err := url.Parse(r.Service) if err != nil { - return nil, err + return Ingress{}, err } 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 != "" { - 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 // of the hostname. if strings.LastIndex(r.Hostname, "*") > 0 { - return nil, errBadWildcard + return Ingress{}, errBadWildcard } // The last rule should catch all hostnames. isCatchAllRule := (r.Hostname == "" || r.Hostname == "*") && r.Path == "" isLastRule := i == len(ing.Ingress)-1 if isLastRule && !isCatchAllRule { - return nil, errLastRuleNotCatchAll + return Ingress{}, errLastRuleNotCatchAll } // ONLY the last rule should catch all hostnames. if !isLastRule && isCatchAllRule { - return nil, errRuleShouldNotBeCatchAll{i: i, hostname: r.Hostname} + return Ingress{}, errRuleShouldNotBeCatchAll{i: i, hostname: r.Hostname} } var pathRegex *regexp.Regexp if r.Path != "" { pathRegex, err = regexp.Compile(r.Path) 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, } } - return rules, nil + return Ingress{Rules: rules}, nil } type errRuleShouldNotBeCatchAll struct { @@ -155,24 +165,24 @@ func (e errRuleShouldNotBeCatchAll) Error() string { "will never be triggered.", e.i+1, e.hostname) } -func ParseIngress(rawYAML []byte) ([]Rule, error) { - var ing ingress +func ParseIngress(rawYAML []byte) (Ingress, error) { + var ing unvalidatedIngress if err := yaml.Unmarshal(rawYAML, &ing); err != nil { - return nil, err + return Ingress{}, err } if len(ing.Ingress) == 0 { - return nil, ErrNoIngressRules + return Ingress{}, ErrNoIngressRules } return ing.validate() } // 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() == "" { 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.Println(rules[i].String()) + fmt.Println(ing.Rules[i].MultiLineString()) return nil } diff --git a/ingress/ingress_test.go b/ingress/ingress_test.go index 99450a0c..9326e7ce 100644 --- a/ingress/ingress_test.go +++ b/ingress/ingress_test.go @@ -20,7 +20,7 @@ func Test_parseIngress(t *testing.T) { tests := []struct { name string args args - want []Rule + want Ingress wantErr bool }{ { @@ -37,7 +37,7 @@ ingress: - hostname: "*" service: https://localhost:8001 `}, - want: []Rule{ + want: Ingress{Rules: []Rule{ { Hostname: "tunnel1.example.com", Service: localhost8000, @@ -46,7 +46,7 @@ ingress: Hostname: "*", Service: localhost8001, }, - }, + }}, }, { name: "Extra keys", @@ -56,12 +56,12 @@ ingress: service: https://localhost:8000 extraKey: extraValue `}, - want: []Rule{ + want: Ingress{Rules: []Rule{ { Hostname: "*", Service: localhost8000, }, - }, + }}, }, { name: "Hostname can be omitted", @@ -69,11 +69,11 @@ extraKey: extraValue ingress: - service: https://localhost:8000 `}, - want: []Rule{ + want: Ingress{Rules: []Rule{ { Service: localhost8000, }, - }, + }}, }, { name: "Invalid service", @@ -308,13 +308,13 @@ ingress: - hostname: "*" service: https://localhost:8002 ` - rules, err := ParseIngress([]byte(rulesYAML)) + ing, err := ParseIngress([]byte(rulesYAML)) if err != nil { b.Error(err) } for n := 0; n < b.N; n++ { - FindMatchingRule("tunnel1.example.com", "", rules) - FindMatchingRule("tunnel2.example.com", "", rules) - FindMatchingRule("tunnel3.example.com", "", rules) + ing.FindMatchingRule("tunnel1.example.com", "") + ing.FindMatchingRule("tunnel2.example.com", "") + ing.FindMatchingRule("tunnel3.example.com", "") } } diff --git a/origin/tunnel.go b/origin/tunnel.go index 997ea779..f300bba6 100644 --- a/origin/tunnel.go +++ b/origin/tunnel.go @@ -93,7 +93,7 @@ type TunnelConfig struct { NamedTunnel *NamedTunnelConfig ReplaceExisting bool TunnelEventChan chan<- ui.TunnelEvent - IngressRules []ingress.Rule + IngressRules ingress.Ingress } type dupConnRegisterTunnelError struct{} @@ -619,7 +619,7 @@ func LogServerInfo( type TunnelHandler struct { originUrl string - ingressRules []ingress.Rule + ingressRules ingress.Ingress httpHostHeader string muxer *h2mux.Muxer httpClient http.RoundTripper @@ -645,7 +645,7 @@ func NewTunnelHandler(ctx context.Context, // Check single-origin config var originURL string var err error - if len(config.IngressRules) == 0 { + if config.IngressRules.IsEmpty() { originURL, err = validation.ValidateUrl(config.OriginUrl) if err != nil { 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") } h.AppendTagHeaders(req) - if len(h.ingressRules) > 0 { - ruleNumber := ingress.FindMatchingRule(req.Host, req.URL.Path, h.ingressRules) - destination := h.ingressRules[ruleNumber].Service + if !h.ingressRules.IsEmpty() { + ruleNumber := h.ingressRules.FindMatchingRule(req.Host, req.URL.Path) + destination := h.ingressRules.Rules[ruleNumber].Service req.URL.Host = destination.Host req.URL.Scheme = destination.Scheme }