From 407c9550d793de9673a3251ac34cc7171d1877e9 Mon Sep 17 00:00:00 2001 From: Adam Chalmers Date: Wed, 7 Oct 2020 16:34:53 -0500 Subject: [PATCH] TUN-3440: 'tunnel rule' command to test ingress rules --- cmd/cloudflared/tunnel/cmd.go | 1 + cmd/cloudflared/tunnel/ingress.go | 87 ++++++++++++++++++ cmd/cloudflared/tunnel/ingress_test.go | 118 +++++++++++++++++++++++++ 3 files changed, 206 insertions(+) diff --git a/cmd/cloudflared/tunnel/cmd.go b/cmd/cloudflared/tunnel/cmd.go index d679dcfe..74f648b0 100644 --- a/cmd/cloudflared/tunnel/cmd.go +++ b/cmd/cloudflared/tunnel/cmd.go @@ -183,6 +183,7 @@ func Commands() []*cli.Command { subcommands = append(subcommands, buildCleanupCommand()) subcommands = append(subcommands, buildRouteCommand()) subcommands = append(subcommands, buildValidateCommand()) + subcommands = append(subcommands, buildRuleCommand()) cmds = append(cmds, buildTunnelCommand(subcommands)) diff --git a/cmd/cloudflared/tunnel/ingress.go b/cmd/cloudflared/tunnel/ingress.go index d76b8362..ae5eb201 100644 --- a/cmd/cloudflared/tunnel/ingress.go +++ b/cmd/cloudflared/tunnel/ingress.go @@ -5,6 +5,7 @@ import ( "io/ioutil" "net/url" "regexp" + "strings" "github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil" "github.com/cloudflare/cloudflared/cmd/cloudflared/config" @@ -18,6 +19,8 @@ import ( var ( errNoIngressRules = errors.New("No ingress rules were specified in the config file") errLastRuleNotCatchAll = errors.New("The last ingress rule must match all hostnames (i.e. it must be missing, or must be \"*\")") + errBadWildcard = errors.New("Hostname patterns can have at most one wildcard character (\"*\") and it can only be used for subdomains, e.g. \"*.example.com\"") + errNoIngressRulesMatch = errors.New("The URL didn't match any ingress rules") ) // Each rule route traffic from a hostname/path on the public @@ -35,6 +38,42 @@ type rule struct { Service *url.URL } +func (r rule) String() string { + var out strings.Builder + if r.Hostname != "" { + out.WriteString("\thostname: ") + out.WriteString(r.Hostname) + out.WriteRune('\n') + } + if r.Path != nil { + out.WriteString("\tpath: ") + out.WriteString(r.Path.String()) + out.WriteRune('\n') + } + out.WriteString("\tservice: ") + out.WriteString(r.Service.String()) + return out.String() +} + +func (r rule) matches(requestURL *url.URL) bool { + hostMatch := r.Hostname == "" || r.Hostname == "*" || matchHost(r.Hostname, requestURL.Hostname()) + pathMatch := r.Path == nil || r.Path.MatchString(requestURL.Path) + return hostMatch && pathMatch +} + +func matchHost(ruleHost, reqHost string) bool { + if ruleHost == reqHost { + return true + } + + // Validate hostnames that use wildcards at the start + if strings.HasPrefix(ruleHost, "*.") { + toMatch := strings.TrimPrefix(ruleHost, "*.") + return strings.HasSuffix(reqHost, toMatch) + } + return false +} + type unvalidatedRule struct { Hostname string Path string @@ -53,6 +92,12 @@ func (ing ingress) validate() ([]rule, error) { return nil, err } + // Ensure that there are no wildcards anywhere except the first character + // of the hostname. + if strings.LastIndex(r.Hostname, "*") > 0 { + return nil, errBadWildcard + } + // The last rule should catch all hostnames. isCatchAllRule := (r.Hostname == "" || r.Hostname == "*") && r.Path == "" isLastRule := i == len(ing.Ingress)-1 @@ -141,3 +186,45 @@ func buildValidateCommand() *cli.Command { Description: "Validates the configuration file, ensuring your ingress rules are OK.", } } + +// Checks which ingress rule matches the given URL. +func ruleCommand(c *cli.Context) error { + rules, log, err := ingressContext(c) + if err != nil { + return err + } + requestArg := c.Args().First() + if requestArg == "" { + return errors.New("cloudflared tunnel rule expects a single argument, the URL to test") + } + requestURL, err := url.Parse(requestArg) + if err != nil { + return fmt.Errorf("%s is not a valid URL", requestArg) + } + if requestURL.Hostname() == "" { + return fmt.Errorf("%s is malformed and doesn't have a hostname", requestArg) + } + for i, r := range rules { + if r.matches(requestURL) { + log.Infof("Matched rule #%d", i+1) + fmt.Println(r.String()) + return nil + } + } + return errNoIngressRulesMatch +} + +func buildRuleCommand() *cli.Command { + return &cli.Command{ + Name: "rule", + Action: cliutil.ErrorHandler(ruleCommand), + Usage: "Check which ingress rule matches a given request URL", + UsageText: "cloudflared [--config CONFIGFILE] tunnel ingress rule URL", + ArgsUsage: "URL", + Description: "Check which ingress rule matches a given request URL. " + + "Ingress rules match a request's hostname and path. Hostname is " + + "optional and is either a full hostname like `www.example.com` or a " + + "hostname with a `*` for its subdomains, e.g. `*.example.com`. Path " + + "is optional and matches a regular expression, like `/[a-zA-Z0-9_]+.html`", + } +} diff --git a/cmd/cloudflared/tunnel/ingress_test.go b/cmd/cloudflared/tunnel/ingress_test.go index d7132618..6538e2b2 100644 --- a/cmd/cloudflared/tunnel/ingress_test.go +++ b/cmd/cloudflared/tunnel/ingress_test.go @@ -3,6 +3,7 @@ package tunnel import ( "net/url" "reflect" + "regexp" "testing" "github.com/stretchr/testify/require" @@ -143,3 +144,120 @@ ingress: }) } } + +func MustParse(t *testing.T, rawURL string) *url.URL { + u, err := url.Parse(rawURL) + require.NoError(t, err) + return u +} + +func Test_rule_matches(t *testing.T) { + type fields struct { + Hostname string + Path *regexp.Regexp + Service *url.URL + } + type args struct { + requestURL *url.URL + } + tests := []struct { + name string + fields fields + args args + want bool + }{ + { + name: "Just hostname, pass", + fields: fields{ + Hostname: "example.com", + }, + args: args{ + requestURL: MustParse(t, "https://example.com"), + }, + want: true, + }, + { + name: "Entire hostname is wildcard, should match everything", + fields: fields{ + Hostname: "*", + }, + args: args{ + requestURL: MustParse(t, "https://example.com"), + }, + want: true, + }, + { + name: "Just hostname, fail", + fields: fields{ + Hostname: "example.com", + }, + args: args{ + requestURL: MustParse(t, "https://foo.bar"), + }, + want: false, + }, + { + name: "Just wildcard hostname, pass", + fields: fields{ + Hostname: "*.example.com", + }, + args: args{ + requestURL: MustParse(t, "https://adam.example.com"), + }, + want: true, + }, + { + name: "Just wildcard hostname, fail", + fields: fields{ + Hostname: "*.example.com", + }, + args: args{ + requestURL: MustParse(t, "https://tunnel.com"), + }, + want: false, + }, + { + name: "Just wildcard outside of subdomain in hostname, fail", + fields: fields{ + Hostname: "*example.com", + }, + args: args{ + requestURL: MustParse(t, "https://www.example.com"), + }, + want: false, + }, + { + name: "Wildcard over multiple subdomains", + fields: fields{ + Hostname: "*.example.com", + }, + args: args{ + requestURL: MustParse(t, "https://adam.chalmers.example.com"), + }, + want: true, + }, + { + name: "Hostname and path", + fields: fields{ + Hostname: "*.example.com", + Path: regexp.MustCompile("/static/.*\\.html"), + }, + args: args{ + requestURL: MustParse(t, "https://www.example.com/static/index.html"), + }, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := rule{ + Hostname: tt.fields.Hostname, + Path: tt.fields.Path, + Service: tt.fields.Service, + } + if got := r.matches(tt.args.requestURL); got != tt.want { + t.Errorf("rule.matches() = %v, want %v", got, tt.want) + } + }) + } +}