mirror of
https://github.com/cloudflare/cloudflared.git
synced 2025-07-27 01:09:57 +00:00
TUN-3438: move ingress into own package, read into TunnelConfig
This commit is contained in:
166
ingress/ingress.go
Normal file
166
ingress/ingress.go
Normal file
@@ -0,0 +1,166 @@
|
||||
package ingress
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
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")
|
||||
ErrURLIncompatibleWithIngress = errors.New("You can't set the --url flag (or $TUNNEL_URL) when using multiple-origin ingress rules")
|
||||
)
|
||||
|
||||
// Each rule route traffic from a hostname/path on the public
|
||||
// internet to the service running on the given URL.
|
||||
type Rule struct {
|
||||
// Requests for this hostname will be proxied to this rule's service.
|
||||
Hostname string
|
||||
|
||||
// Path is an optional regex that can specify path-driven ingress rules.
|
||||
Path *regexp.Regexp
|
||||
|
||||
// A (probably local) address. Requests for a hostname which matches this
|
||||
// rule's hostname pattern will be proxied to the service running on this
|
||||
// address.
|
||||
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
|
||||
Service string
|
||||
}
|
||||
|
||||
type ingress struct {
|
||||
Ingress []unvalidatedRule
|
||||
Url string
|
||||
}
|
||||
|
||||
func (ing ingress) validate() ([]Rule, error) {
|
||||
if ing.Url != "" {
|
||||
return nil, 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
|
||||
}
|
||||
if service.Scheme == "" || service.Hostname() == "" {
|
||||
return nil, fmt.Errorf("The service %s must have a scheme and a hostname", 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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
// ONLY the last rule should catch all hostnames.
|
||||
if !isLastRule && isCatchAllRule {
|
||||
return nil, 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)
|
||||
}
|
||||
}
|
||||
|
||||
rules[i] = Rule{
|
||||
Hostname: r.Hostname,
|
||||
Service: service,
|
||||
Path: pathRegex,
|
||||
}
|
||||
}
|
||||
return rules, nil
|
||||
}
|
||||
|
||||
type errRuleShouldNotBeCatchAll struct {
|
||||
i int
|
||||
hostname string
|
||||
}
|
||||
|
||||
func (e errRuleShouldNotBeCatchAll) Error() string {
|
||||
return fmt.Sprintf("Rule #%d is matching the hostname '%s', but "+
|
||||
"this will match every hostname, meaning the rules which follow it "+
|
||||
"will never be triggered.", e.i+1, e.hostname)
|
||||
}
|
||||
|
||||
func ParseIngress(rawYAML []byte) ([]Rule, error) {
|
||||
var ing ingress
|
||||
if err := yaml.Unmarshal(rawYAML, &ing); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(ing.Ingress) == 0 {
|
||||
return nil, errNoIngressRules
|
||||
}
|
||||
return ing.validate()
|
||||
}
|
||||
|
||||
// RuleCommand checks which ingress rule matches the given request URL.
|
||||
func RuleCommand(rules []Rule, requestURL *url.URL) error {
|
||||
if requestURL.Hostname() == "" {
|
||||
return fmt.Errorf("%s is malformed and doesn't have a hostname", requestURL)
|
||||
}
|
||||
for i, r := range rules {
|
||||
if r.matches(requestURL) {
|
||||
fmt.Printf("Matched rule #%d\n", i+1)
|
||||
fmt.Println(r.String())
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errNoIngressRulesMatch
|
||||
}
|
271
ingress/ingress_test.go
Normal file
271
ingress/ingress_test.go
Normal file
@@ -0,0 +1,271 @@
|
||||
package ingress
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func Test_parseIngress(t *testing.T) {
|
||||
localhost8000, err := url.Parse("https://localhost:8000")
|
||||
require.NoError(t, err)
|
||||
localhost8001, err := url.Parse("https://localhost:8001")
|
||||
require.NoError(t, err)
|
||||
type args struct {
|
||||
rawYAML string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want []Rule
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "Empty file",
|
||||
args: args{rawYAML: ""},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "Multiple rules",
|
||||
args: args{rawYAML: `
|
||||
ingress:
|
||||
- hostname: tunnel1.example.com
|
||||
service: https://localhost:8000
|
||||
- hostname: "*"
|
||||
service: https://localhost:8001
|
||||
`},
|
||||
want: []Rule{
|
||||
{
|
||||
Hostname: "tunnel1.example.com",
|
||||
Service: localhost8000,
|
||||
},
|
||||
{
|
||||
Hostname: "*",
|
||||
Service: localhost8001,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Extra keys",
|
||||
args: args{rawYAML: `
|
||||
ingress:
|
||||
- hostname: "*"
|
||||
service: https://localhost:8000
|
||||
extraKey: extraValue
|
||||
`},
|
||||
want: []Rule{
|
||||
{
|
||||
Hostname: "*",
|
||||
Service: localhost8000,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Hostname can be omitted",
|
||||
args: args{rawYAML: `
|
||||
ingress:
|
||||
- service: https://localhost:8000
|
||||
`},
|
||||
want: []Rule{
|
||||
{
|
||||
Service: localhost8000,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Invalid service",
|
||||
args: args{rawYAML: `
|
||||
ingress:
|
||||
- hostname: "*"
|
||||
service: https://local host:8000
|
||||
`},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "Invalid YAML",
|
||||
args: args{rawYAML: `
|
||||
key: "value
|
||||
`},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "Last rule isn't catchall",
|
||||
args: args{rawYAML: `
|
||||
ingress:
|
||||
- hostname: example.com
|
||||
service: https://localhost:8000
|
||||
`},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "First rule is catchall",
|
||||
args: args{rawYAML: `
|
||||
ingress:
|
||||
- service: https://localhost:8000
|
||||
- hostname: example.com
|
||||
service: https://localhost:8000
|
||||
`},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "Catch-all rule can't have a path",
|
||||
args: args{rawYAML: `
|
||||
ingress:
|
||||
- service: https://localhost:8001
|
||||
path: /subpath1/(.*)/subpath2
|
||||
`},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "Invalid regex",
|
||||
args: args{rawYAML: `
|
||||
ingress:
|
||||
- hostname: example.com
|
||||
service: https://localhost:8000
|
||||
path: "*/subpath2"
|
||||
- service: https://localhost:8001
|
||||
`},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "Service must have a scheme",
|
||||
args: args{rawYAML: `
|
||||
ingress:
|
||||
- service: localhost:8000
|
||||
`},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := ParseIngress([]byte(tt.args.rawYAML))
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("ParseIngress() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("ParseIngress() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user