1
0
Fork 0

New rule syntax

Co-authored-by: jbdoumenjou <jb.doumenjou@gmail.com>
This commit is contained in:
SALLEYRON Julien 2019-01-30 16:24:07 +01:00 committed by Traefiker Bot
parent 7155f0d50d
commit 9ebe3c38b2
89 changed files with 1111 additions and 1357 deletions

97
rules/parser.go Normal file
View file

@ -0,0 +1,97 @@
package rules
import (
"strings"
"github.com/pkg/errors"
"github.com/vulcand/predicate"
)
type treeBuilder func() *tree
// ParseDomains extract domains from rule
func ParseDomains(rule string) ([]string, error) {
parser, err := newParser()
if err != nil {
return nil, err
}
parse, err := parser.Parse(rule)
if err != nil {
return nil, err
}
buildTree, ok := parse.(treeBuilder)
if !ok {
return nil, errors.New("cannot parse")
}
return lower(parseDomain(buildTree())), nil
}
func lower(slice []string) []string {
var lowerStrings []string
for _, value := range slice {
lowerStrings = append(lowerStrings, strings.ToLower(value))
}
return lowerStrings
}
func parseDomain(tree *tree) []string {
switch tree.matcher {
case "and", "or":
return append(parseDomain(tree.ruleLeft), parseDomain(tree.ruleRight)...)
case "Host":
return tree.value
default:
return nil
}
}
func andFunc(left, right treeBuilder) treeBuilder {
return func() *tree {
return &tree{
matcher: "and",
ruleLeft: left(),
ruleRight: right(),
}
}
}
func orFunc(left, right treeBuilder) treeBuilder {
return func() *tree {
return &tree{
matcher: "or",
ruleLeft: left(),
ruleRight: right(),
}
}
}
func newParser() (predicate.Parser, error) {
parserFuncs := make(map[string]interface{})
for matcherName := range funcs {
matcherName := matcherName
fn := func(value ...string) treeBuilder {
return func() *tree {
return &tree{
matcher: matcherName,
value: value,
}
}
}
parserFuncs[matcherName] = fn
parserFuncs[strings.ToLower(matcherName)] = fn
parserFuncs[strings.ToUpper(matcherName)] = fn
parserFuncs[strings.Title(strings.ToLower(matcherName))] = fn
}
return predicate.NewParser(predicate.Def{
Operators: predicate.Operators{
AND: andFunc,
OR: orFunc,
},
Functions: parserFuncs,
})
}

View file

@ -1,45 +1,116 @@
package rules
import (
"errors"
"fmt"
"net/http"
"reflect"
"sort"
"strings"
"github.com/containous/mux"
"github.com/containous/traefik/hostresolver"
"github.com/containous/traefik/old/middlewares"
"github.com/containous/traefik/old/types"
"github.com/containous/traefik/log"
"github.com/containous/traefik/middlewares/requestdecorator"
"github.com/vulcand/predicate"
)
// Rules holds rule parsing and configuration
type Rules struct {
Route *types.ServerRoute
err error
HostResolver *hostresolver.Resolver
var funcs = map[string]func(*mux.Route, ...string) error{
"Host": host,
"HostRegexp": hostRegexp,
"Path": path,
"PathPrefix": pathPrefix,
"Method": methods,
"Headers": headers,
"HeadersRegexp": headersRegexp,
"Query": query,
}
func (r *Rules) host(hosts ...string) *mux.Route {
// Router handle routing with rules
type Router struct {
*mux.Router
parser predicate.Parser
}
// NewRouter returns a new router instance.
func NewRouter() (*Router, error) {
parser, err := newParser()
if err != nil {
return nil, err
}
return &Router{
Router: mux.NewRouter().SkipClean(true),
parser: parser,
}, nil
}
// AddRoute add a new route to the router.
func (r *Router) AddRoute(rule string, priority int, handler http.Handler) error {
parse, err := r.parser.Parse(rule)
if err != nil {
return fmt.Errorf("error while parsing rule %s: %v", rule, err)
}
buildTree, ok := parse.(treeBuilder)
if !ok {
return fmt.Errorf("error while parsing rule %s", rule)
}
if priority == 0 {
priority = len(rule)
}
route := r.NewRoute().Handler(handler).Priority(priority)
return addRuleOnRoute(route, buildTree())
}
type tree struct {
matcher string
value []string
ruleLeft *tree
ruleRight *tree
}
func path(route *mux.Route, paths ...string) error {
rt := route.Subrouter()
for _, path := range paths {
tmpRt := rt.Path(path)
if tmpRt.GetError() != nil {
return tmpRt.GetError()
}
}
return nil
}
func pathPrefix(route *mux.Route, paths ...string) error {
rt := route.Subrouter()
for _, path := range paths {
tmpRt := rt.PathPrefix(path)
if tmpRt.GetError() != nil {
return tmpRt.GetError()
}
}
return nil
}
func host(route *mux.Route, hosts ...string) error {
for i, host := range hosts {
hosts[i] = strings.ToLower(host)
}
return r.Route.Route.MatcherFunc(func(req *http.Request, route *mux.RouteMatch) bool {
reqHost := middlewares.GetCanonizedHost(req.Context())
route.MatcherFunc(func(req *http.Request, _ *mux.RouteMatch) bool {
reqHost := requestdecorator.GetCanonizedHost(req.Context())
if len(reqHost) == 0 {
log.FromContext(req.Context()).Warnf("Could not retrieve CanonizedHost, rejecting %s", req.Host)
return false
}
if r.HostResolver != nil && r.HostResolver.CnameFlattening {
reqH, flatH := r.HostResolver.CNAMEFlatten(reqHost)
flatH := requestdecorator.GetCNAMEFlatten(req.Context())
if len(flatH) > 0 {
for _, host := range hosts {
if strings.EqualFold(reqH, host) || strings.EqualFold(flatH, host) {
if strings.EqualFold(reqHost, host) || strings.EqualFold(flatH, host) {
return true
}
// FIXME
//log.Debugf("CNAMEFlattening: request %s which resolved to %s, is not matched to route %s", reqH, flatH, host)
log.FromContext(req.Context()).Debugf("CNAMEFlattening: request %s which resolved to %s, is not matched to route %s", reqHost, flatH, host)
}
return false
}
@ -51,270 +122,107 @@ func (r *Rules) host(hosts ...string) *mux.Route {
}
return false
})
return nil
}
func (r *Rules) hostRegexp(hostPatterns ...string) *mux.Route {
router := r.Route.Route.Subrouter()
for _, hostPattern := range hostPatterns {
router.Host(hostPattern)
}
return r.Route.Route
}
func (r *Rules) path(paths ...string) *mux.Route {
router := r.Route.Route.Subrouter()
for _, path := range paths {
router.Path(path)
}
return r.Route.Route
}
func (r *Rules) pathPrefix(paths ...string) *mux.Route {
router := r.Route.Route.Subrouter()
for _, path := range paths {
buildPath(path, router)
}
return r.Route.Route
}
func buildPath(path string, router *mux.Router) {
// {} are used to define a regex pattern in http://www.gorillatoolkit.org/pkg/mux.
// if we find a { in the path, that means we use regex, then the gorilla/mux implementation is chosen
// otherwise, we use a lightweight implementation
if strings.Contains(path, "{") {
router.PathPrefix(path)
} else {
m := &prefixMatcher{prefix: path}
router.NewRoute().MatcherFunc(m.Match)
}
}
type prefixMatcher struct {
prefix string
}
func (m *prefixMatcher) Match(r *http.Request, _ *mux.RouteMatch) bool {
return strings.HasPrefix(r.URL.Path, m.prefix) || strings.HasPrefix(r.URL.Path, m.prefix+"/")
}
type bySize []string
func (a bySize) Len() int { return len(a) }
func (a bySize) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a bySize) Less(i, j int) bool { return len(a[i]) > len(a[j]) }
func (r *Rules) pathStrip(paths ...string) *mux.Route {
sort.Sort(bySize(paths))
r.Route.StripPrefixes = paths
router := r.Route.Route.Subrouter()
for _, path := range paths {
router.Path(strings.TrimSpace(path))
}
return r.Route.Route
}
func (r *Rules) pathStripRegex(paths ...string) *mux.Route {
sort.Sort(bySize(paths))
r.Route.StripPrefixesRegex = paths
router := r.Route.Route.Subrouter()
for _, path := range paths {
router.Path(path)
}
return r.Route.Route
}
func (r *Rules) replacePath(paths ...string) *mux.Route {
for _, path := range paths {
r.Route.ReplacePath = path
}
return r.Route.Route
}
func (r *Rules) replacePathRegex(paths ...string) *mux.Route {
for _, path := range paths {
r.Route.ReplacePathRegex = path
}
return r.Route.Route
}
func (r *Rules) addPrefix(paths ...string) *mux.Route {
for _, path := range paths {
r.Route.AddPrefix = path
}
return r.Route.Route
}
func (r *Rules) pathPrefixStrip(paths ...string) *mux.Route {
sort.Sort(bySize(paths))
r.Route.StripPrefixes = paths
router := r.Route.Route.Subrouter()
for _, path := range paths {
buildPath(path, router)
}
return r.Route.Route
}
func (r *Rules) pathPrefixStripRegex(paths ...string) *mux.Route {
sort.Sort(bySize(paths))
r.Route.StripPrefixesRegex = paths
router := r.Route.Route.Subrouter()
for _, path := range paths {
router.PathPrefix(path)
}
return r.Route.Route
}
func (r *Rules) methods(methods ...string) *mux.Route {
return r.Route.Route.Methods(methods...)
}
func (r *Rules) headers(headers ...string) *mux.Route {
return r.Route.Route.Headers(headers...)
}
func (r *Rules) headersRegexp(headers ...string) *mux.Route {
return r.Route.Route.HeadersRegexp(headers...)
}
func (r *Rules) query(query ...string) *mux.Route {
var queries []string
for _, elem := range query {
queries = append(queries, strings.Split(elem, "=")...)
}
return r.Route.Route.Queries(queries...)
}
func (r *Rules) parseRules(expression string, onRule func(functionName string, function interface{}, arguments []string) error) error {
functions := map[string]interface{}{
"Host": r.host,
"HostRegexp": r.hostRegexp,
"Path": r.path,
"PathStrip": r.pathStrip,
"PathStripRegex": r.pathStripRegex,
"PathPrefix": r.pathPrefix,
"PathPrefixStrip": r.pathPrefixStrip,
"PathPrefixStripRegex": r.pathPrefixStripRegex,
"Method": r.methods,
"Headers": r.headers,
"HeadersRegexp": r.headersRegexp,
"AddPrefix": r.addPrefix,
"ReplacePath": r.replacePath,
"ReplacePathRegex": r.replacePathRegex,
"Query": r.query,
}
if len(expression) == 0 {
return errors.New("empty rule")
}
f := func(c rune) bool {
return c == ':'
}
// Allow multiple rules separated by ;
splitRule := func(c rune) bool {
return c == ';'
}
parsedRules := strings.FieldsFunc(expression, splitRule)
for _, rule := range parsedRules {
// get function
parsedFunctions := strings.FieldsFunc(rule, f)
if len(parsedFunctions) == 0 {
return fmt.Errorf("error parsing rule: '%s'", rule)
}
functionName := strings.TrimSpace(parsedFunctions[0])
parsedFunction, ok := functions[functionName]
if !ok {
return fmt.Errorf("error parsing rule: '%s'. Unknown function: '%s'", rule, parsedFunctions[0])
}
parsedFunctions = append(parsedFunctions[:0], parsedFunctions[1:]...)
// get function
fargs := func(c rune) bool {
return c == ','
}
parsedArgs := strings.FieldsFunc(strings.Join(parsedFunctions, ":"), fargs)
if len(parsedArgs) == 0 {
return fmt.Errorf("error parsing args from rule: '%s'", rule)
}
for i := range parsedArgs {
parsedArgs[i] = strings.TrimSpace(parsedArgs[i])
}
err := onRule(functionName, parsedFunction, parsedArgs)
if err != nil {
return fmt.Errorf("parsing error on rule: %v", err)
func hostRegexp(route *mux.Route, hosts ...string) error {
router := route.Subrouter()
for _, host := range hosts {
tmpRt := router.Host(host)
if tmpRt.GetError() != nil {
return tmpRt.GetError()
}
}
return nil
}
// Parse parses rules expressions
func (r *Rules) Parse(expression string) (*mux.Route, error) {
var resultRoute *mux.Route
err := r.parseRules(expression, func(functionName string, function interface{}, arguments []string) error {
inputs := make([]reflect.Value, len(arguments))
for i := range arguments {
inputs[i] = reflect.ValueOf(arguments[i])
}
method := reflect.ValueOf(function)
if method.IsValid() {
resultRoute = method.Call(inputs)[0].Interface().(*mux.Route)
if r.err != nil {
return r.err
}
if resultRoute == nil {
return fmt.Errorf("invalid expression: %s", expression)
}
if resultRoute.GetError() != nil {
return resultRoute.GetError()
}
} else {
return fmt.Errorf("method not found: '%s'", functionName)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("error parsing rule: %v", err)
}
return resultRoute, nil
func methods(route *mux.Route, methods ...string) error {
return route.Methods(methods...).GetError()
}
// ParseDomains parses rules expressions and returns domains
func (r *Rules) ParseDomains(expression string) ([]string, error) {
var domains []string
isHostRule := false
err := r.parseRules(expression, func(functionName string, function interface{}, arguments []string) error {
if functionName == "Host" {
isHostRule = true
domains = append(domains, arguments...)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("error parsing domains: %v", err)
}
var cleanDomains []string
for _, domain := range domains {
canonicalDomain := strings.ToLower(domain)
if len(canonicalDomain) > 0 {
cleanDomains = append(cleanDomains, canonicalDomain)
}
}
// Return an error if an Host rule is detected but no domain are parsed
if isHostRule && len(cleanDomains) == 0 {
return nil, fmt.Errorf("unable to parse correctly the domains in the Host rule from %q", expression)
}
return cleanDomains, nil
func headers(route *mux.Route, headers ...string) error {
return route.Headers(headers...).GetError()
}
func headersRegexp(route *mux.Route, headers ...string) error {
return route.HeadersRegexp(headers...).GetError()
}
func query(route *mux.Route, query ...string) error {
var queries []string
for _, elem := range query {
queries = append(queries, strings.Split(elem, "=")...)
}
route.Queries(queries...)
// Queries can return nil so we can't chain the GetError()
return route.GetError()
}
func addRuleOnRouter(router *mux.Router, rule *tree) error {
switch rule.matcher {
case "and":
route := router.NewRoute()
err := addRuleOnRoute(route, rule.ruleLeft)
if err != nil {
return err
}
return addRuleOnRoute(route, rule.ruleRight)
case "or":
err := addRuleOnRouter(router, rule.ruleLeft)
if err != nil {
return err
}
return addRuleOnRouter(router, rule.ruleRight)
default:
err := checkRule(rule)
if err != nil {
return err
}
return funcs[rule.matcher](router.NewRoute(), rule.value...)
}
}
func addRuleOnRoute(route *mux.Route, rule *tree) error {
switch rule.matcher {
case "and":
err := addRuleOnRoute(route, rule.ruleLeft)
if err != nil {
return err
}
return addRuleOnRoute(route, rule.ruleRight)
case "or":
subRouter := route.Subrouter()
err := addRuleOnRouter(subRouter, rule.ruleLeft)
if err != nil {
return err
}
return addRuleOnRouter(subRouter, rule.ruleRight)
default:
err := checkRule(rule)
if err != nil {
return err
}
return funcs[rule.matcher](route, rule.value...)
}
}
func checkRule(rule *tree) error {
if len(rule.value) == 0 {
return fmt.Errorf("no args for matcher %s", rule.matcher)
}
for _, v := range rule.value {
if len(v) == 0 {
return fmt.Errorf("empty args for matcher %s, %v", rule.matcher, rule.value)
}
}
return nil
}

View file

@ -2,169 +2,569 @@ package rules
import (
"net/http"
"net/url"
"net/http/httptest"
"testing"
"github.com/containous/mux"
"github.com/containous/traefik/old/middlewares"
"github.com/containous/traefik/old/types"
"github.com/containous/traefik/middlewares/requestdecorator"
"github.com/containous/traefik/testhelpers"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestParseOneRule(t *testing.T) {
reqHostMid := &middlewares.RequestHost{}
rules := &Rules{
Route: &types.ServerRoute{
Route: mux.NewRouter().NewRoute(),
},
}
expression := "Host:foo.bar"
routeResult, err := rules.Parse(expression)
require.NoError(t, err, "Error while building route for %s", expression)
request := testhelpers.MustNewRequest(http.MethodGet, "http://foo.bar", nil)
reqHostMid.ServeHTTP(nil, request, func(w http.ResponseWriter, r *http.Request) {
routeMatch := routeResult.Match(r, &mux.RouteMatch{Route: routeResult})
assert.True(t, routeMatch, "Rule %s don't match.", expression)
})
}
func TestParseTwoRules(t *testing.T) {
reqHostMid := &middlewares.RequestHost{}
rules := &Rules{
Route: &types.ServerRoute{
Route: mux.NewRouter().NewRoute(),
},
}
expression := "Host: Foo.Bar ; Path:/FOObar"
routeResult, err := rules.Parse(expression)
require.NoError(t, err, "Error while building route for %s.", expression)
request := testhelpers.MustNewRequest(http.MethodGet, "http://foo.bar/foobar", nil)
reqHostMid.ServeHTTP(nil, request, func(w http.ResponseWriter, r *http.Request) {
routeMatch := routeResult.Match(r, &mux.RouteMatch{Route: routeResult})
assert.False(t, routeMatch, "Rule %s don't match.", expression)
})
request = testhelpers.MustNewRequest(http.MethodGet, "http://foo.bar/FOObar", nil)
reqHostMid.ServeHTTP(nil, request, func(w http.ResponseWriter, r *http.Request) {
routeMatch := routeResult.Match(r, &mux.RouteMatch{Route: routeResult})
assert.True(t, routeMatch, "Rule %s don't match.", expression)
})
}
func TestParseDomains(t *testing.T) {
rules := &Rules{}
tests := []struct {
description string
expression string
domain []string
errorExpected bool
func Test_addRoute(t *testing.T) {
testCases := []struct {
desc string
rule string
headers map[string]string
expected map[string]int
expectedError bool
}{
{
description: "Many host rules",
expression: "Host:foo.bar,test.bar",
domain: []string{"foo.bar", "test.bar"},
errorExpected: false,
desc: "no tree",
expectedError: true,
},
{
description: "No host rule",
expression: "Path:/test",
errorExpected: false,
desc: "Rule with no matcher",
rule: "rulewithnotmatcher",
expectedError: true,
},
{
description: "Host rule and another rule",
expression: "Host:foo.bar;Path:/test",
domain: []string{"foo.bar"},
errorExpected: false,
desc: "PathPrefix",
rule: "PathPrefix(`/foo`)",
expected: map[string]int{
"http://localhost/foo": http.StatusOK,
},
},
{
description: "Host rule to trim and another rule",
expression: "Host: Foo.Bar ;Path:/test",
domain: []string{"foo.bar"},
errorExpected: false,
desc: "wrong PathPrefix",
rule: "PathPrefix(`/bar`)",
expected: map[string]int{
"http://localhost/foo": http.StatusNotFound,
},
},
{
description: "Host rule with no domain",
expression: "Host: ;Path:/test",
errorExpected: true,
desc: "Host",
rule: "Host(`localhost`)",
expected: map[string]int{
"http://localhost/foo": http.StatusOK,
},
},
{
desc: "wrong Host",
rule: "Host(`nope`)",
expected: map[string]int{
"http://localhost/foo": http.StatusNotFound,
},
},
{
desc: "Host and PathPrefix",
rule: "Host(`localhost`) && PathPrefix(`/foo`)",
expected: map[string]int{
"http://localhost/foo": http.StatusOK,
},
},
{
desc: "Host and PathPrefix wrong PathPrefix",
rule: "Host(`localhost`) && PathPrefix(`/bar`)",
expected: map[string]int{
"http://localhost/foo": http.StatusNotFound,
},
},
{
desc: "Host and PathPrefix wrong Host",
rule: "Host(`nope`) && PathPrefix(`/foo`)",
expected: map[string]int{
"http://localhost/foo": http.StatusNotFound,
},
},
{
desc: "Host and PathPrefix Host OR, first host",
rule: "Host(`nope`,`localhost`) && PathPrefix(`/foo`)",
expected: map[string]int{
"http://localhost/foo": http.StatusOK,
},
},
{
desc: "Host and PathPrefix Host OR, second host",
rule: "Host(`nope`,`localhost`) && PathPrefix(`/foo`)",
expected: map[string]int{
"http://nope/foo": http.StatusOK,
},
},
{
desc: "Host and PathPrefix Host OR, first host and wrong PathPrefix",
rule: "Host(`nope,localhost`) && PathPrefix(`/bar`)",
expected: map[string]int{
"http://localhost/foo": http.StatusNotFound,
},
},
{
desc: "HostRegexp with capturing group",
rule: "HostRegexp(`{subdomain:(foo\\.)?bar\\.com}`)",
expected: map[string]int{
"http://foo.bar.com": http.StatusOK,
"http://bar.com": http.StatusOK,
"http://fooubar.com": http.StatusNotFound,
"http://barucom": http.StatusNotFound,
"http://barcom": http.StatusNotFound,
},
},
{
desc: "HostRegexp with non capturing group",
rule: "HostRegexp(`{subdomain:(?:foo\\.)?bar\\.com}`)",
expected: map[string]int{
"http://foo.bar.com": http.StatusOK,
"http://bar.com": http.StatusOK,
"http://fooubar.com": http.StatusNotFound,
"http://barucom": http.StatusNotFound,
"http://barcom": http.StatusNotFound,
},
},
{
desc: "Methods with GET",
rule: "Method(`GET`)",
expected: map[string]int{
"http://localhost/foo": http.StatusOK,
},
},
{
desc: "Methods with GET and POST",
rule: "Method(`GET`,`POST`)",
expected: map[string]int{
"http://localhost/foo": http.StatusOK,
},
},
{
desc: "Methods with POST",
rule: "Method(`POST`)",
expected: map[string]int{
"http://localhost/foo": http.StatusMethodNotAllowed,
},
},
{
desc: "Header with matching header",
rule: "Headers(`Content-Type`,`application/json`)",
headers: map[string]string{
"Content-Type": "application/json",
},
expected: map[string]int{
"http://localhost/foo": http.StatusOK,
},
},
{
desc: "Header without matching header",
rule: "Headers(`Content-Type`,`application/foo`)",
headers: map[string]string{
"Content-Type": "application/json",
},
expected: map[string]int{
"http://localhost/foo": http.StatusNotFound,
},
},
{
desc: "HeaderRegExp with matching header",
rule: "HeadersRegexp(`Content-Type`, `application/(text|json)`)",
headers: map[string]string{
"Content-Type": "application/json",
},
expected: map[string]int{
"http://localhost/foo": http.StatusOK,
},
},
{
desc: "HeaderRegExp without matching header",
rule: "HeadersRegexp(`Content-Type`, `application/(text|json)`)",
headers: map[string]string{
"Content-Type": "application/foo",
},
expected: map[string]int{
"http://localhost/foo": http.StatusNotFound,
},
},
{
desc: "HeaderRegExp with matching second header",
rule: "HeadersRegexp(`Content-Type`, `application/(text|json)`)",
headers: map[string]string{
"Content-Type": "application/text",
},
expected: map[string]int{
"http://localhost/foo": http.StatusOK,
},
},
{
desc: "Query with multiple params",
rule: "Query(`foo=bar`, `bar=baz`)",
expected: map[string]int{
"http://localhost/foo?foo=bar&bar=baz": http.StatusOK,
"http://localhost/foo?bar=baz": http.StatusNotFound,
},
},
{
desc: "Rule with simple path",
rule: `Path("/a")`,
expected: map[string]int{
"http://plop/a": http.StatusOK,
},
},
{
desc: `Rule with a simple host`,
rule: `Host("plop")`,
expected: map[string]int{
"http://plop": http.StatusOK,
},
},
{
desc: "Rule with Path AND Host",
rule: `Path("/a") && Host("plop")`,
expected: map[string]int{
"http://plop/a": http.StatusOK,
"http://plopi/a": http.StatusNotFound,
},
},
{
desc: "Rule with Host OR Host",
rule: `Host("tchouk") || Host("pouet")`,
expected: map[string]int{
"http://tchouk/toto": http.StatusOK,
"http://pouet/a": http.StatusOK,
"http://plopi/a": http.StatusNotFound,
},
},
{
desc: "Rule with host OR (host AND path)",
rule: `Host("tchouk") || (Host("pouet") && Path("/powpow"))`,
expected: map[string]int{
"http://tchouk/toto": http.StatusOK,
"http://tchouk/powpow": http.StatusOK,
"http://pouet/powpow": http.StatusOK,
"http://pouet/toto": http.StatusNotFound,
"http://plopi/a": http.StatusNotFound,
},
},
{
desc: "Rule with host OR host AND path",
rule: `Host("tchouk") || Host("pouet") && Path("/powpow")`,
expected: map[string]int{
"http://tchouk/toto": http.StatusOK,
"http://tchouk/powpow": http.StatusOK,
"http://pouet/powpow": http.StatusOK,
"http://pouet/toto": http.StatusNotFound,
"http://plopi/a": http.StatusNotFound,
},
},
{
desc: "Rule with (host OR host) AND path",
rule: `(Host("tchouk") || Host("pouet")) && Path("/powpow")`,
expected: map[string]int{
"http://tchouk/toto": http.StatusNotFound,
"http://tchouk/powpow": http.StatusOK,
"http://pouet/powpow": http.StatusOK,
"http://pouet/toto": http.StatusNotFound,
"http://plopi/a": http.StatusNotFound,
},
},
{
desc: "Rule with multiple host AND path",
rule: `(Host("tchouk","pouet")) && Path("/powpow")`,
expected: map[string]int{
"http://tchouk/toto": http.StatusNotFound,
"http://tchouk/powpow": http.StatusOK,
"http://pouet/powpow": http.StatusOK,
"http://pouet/toto": http.StatusNotFound,
"http://plopi/a": http.StatusNotFound,
},
},
{
desc: "Rule with multiple host AND multiple path",
rule: `Host("tchouk","pouet") && Path("/powpow", "/titi")`,
expected: map[string]int{
"http://tchouk/toto": http.StatusNotFound,
"http://tchouk/powpow": http.StatusOK,
"http://pouet/powpow": http.StatusOK,
"http://tchouk/titi": http.StatusOK,
"http://pouet/titi": http.StatusOK,
"http://pouet/toto": http.StatusNotFound,
"http://plopi/a": http.StatusNotFound,
},
},
{
desc: "Rule with (host AND path) OR (host AND path)",
rule: `(Host("tchouk") && Path("/titi")) || ((Host("pouet")) && Path("/powpow"))`,
expected: map[string]int{
"http://tchouk/titi": http.StatusOK,
"http://tchouk/powpow": http.StatusNotFound,
"http://pouet/powpow": http.StatusOK,
"http://pouet/toto": http.StatusNotFound,
"http://plopi/a": http.StatusNotFound,
},
},
{
desc: "Rule without quote",
rule: `Host(tchouk)`,
expectedError: true,
},
{
desc: "Rule case UPPER",
rule: `(HOST("tchouk") && PATHPREFIX("/titi"))`,
expected: map[string]int{
"http://tchouk/titi": http.StatusOK,
"http://tchouk/powpow": http.StatusNotFound,
},
},
{
desc: "Rule case lower",
rule: `(host("tchouk") && pathprefix("/titi"))`,
expected: map[string]int{
"http://tchouk/titi": http.StatusOK,
"http://tchouk/powpow": http.StatusNotFound,
},
},
{
desc: "Rule case CamelCase",
rule: `(Host("tchouk") && PathPrefix("/titi"))`,
expected: map[string]int{
"http://tchouk/titi": http.StatusOK,
"http://tchouk/powpow": http.StatusNotFound,
},
},
{
desc: "Rule case Title",
rule: `(Host("tchouk") && Pathprefix("/titi"))`,
expected: map[string]int{
"http://tchouk/titi": http.StatusOK,
"http://tchouk/powpow": http.StatusNotFound,
},
},
{
desc: "Rule Path with error",
rule: `Path("titi")`,
expectedError: true,
},
{
desc: "Rule PathPrefix with error",
rule: `PathPrefix("titi")`,
expectedError: true,
},
{
desc: "Rule HostRegexp with error",
rule: `HostRegexp("{test")`,
expectedError: true,
},
{
desc: "Rule Headers with error",
rule: `Headers("titi")`,
expectedError: true,
},
{
desc: "Rule HeadersRegexp with error",
rule: `HeadersRegexp("titi")`,
expectedError: true,
},
{
desc: "Rule Query",
rule: `Query("titi")`,
expectedError: true,
},
{
desc: "Rule Query with bad syntax",
rule: `Query("titi={test")`,
expectedError: true,
},
{
desc: "Rule with Path without args",
rule: `Host("tchouk") && Path()`,
expectedError: true,
},
{
desc: "Rule with an empty path",
rule: `Host("tchouk") && Path("")`,
expectedError: true,
},
{
desc: "Rule with an empty path",
rule: `Host("tchouk") && Path("", "/titi")`,
expectedError: true,
},
}
for _, test := range tests {
for _, test := range testCases {
test := test
t.Run(test.expression, func(t *testing.T) {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
domains, err := rules.ParseDomains(test.expression)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
router, err := NewRouter()
require.NoError(t, err)
if test.errorExpected {
require.Errorf(t, err, "unable to parse correctly the domains in the Host rule from %q", test.expression)
err = router.AddRoute(test.rule, 0, handler)
if test.expectedError {
require.Error(t, err)
} else {
require.NoError(t, err, "%s: Error while parsing domain.", test.expression)
}
require.NoError(t, err)
assert.EqualValues(t, test.domain, domains, "%s: Error parsing domains from expression.", test.expression)
// RequestDecorator is necessary for the host rule
reqHost := requestdecorator.New(nil)
results := make(map[string]int)
for calledURL := range test.expected {
w := httptest.NewRecorder()
req := testhelpers.MustNewRequest(http.MethodGet, calledURL, nil)
for key, value := range test.headers {
req.Header.Set(key, value)
}
reqHost.ServeHTTP(w, req, router.ServeHTTP)
results[calledURL] = w.Code
}
assert.Equal(t, test.expected, results)
}
})
}
}
func TestPriorities(t *testing.T) {
router := mux.NewRouter()
router.StrictSlash(true)
func Test_addRoutePriority(t *testing.T) {
type Case struct {
xFrom string
rule string
priority int
}
rules := &Rules{Route: &types.ServerRoute{Route: router.NewRoute()}}
expression01 := "PathPrefix:/foo"
testCases := []struct {
desc string
path string
cases []Case
expected string
}{
{
desc: "Higher priority on second rule",
path: "/my",
cases: []Case{
{
xFrom: "header1",
rule: "PathPrefix(`/my`)",
priority: 10,
},
{
xFrom: "header2",
rule: "PathPrefix(`/my`)",
priority: 20,
},
},
expected: "header2",
},
{
desc: "Higher priority on first rule",
path: "/my",
cases: []Case{
{
xFrom: "header1",
rule: "PathPrefix(`/my`)",
priority: 20,
},
{
xFrom: "header2",
rule: "PathPrefix(`/my`)",
priority: 10,
},
},
expected: "header1",
},
{
desc: "Higher priority on second rule with different rule",
path: "/mypath",
cases: []Case{
{
xFrom: "header1",
rule: "PathPrefix(`/mypath`)",
priority: 10,
},
{
xFrom: "header2",
rule: "PathPrefix(`/my`)",
priority: 20,
},
},
expected: "header2",
},
{
desc: "Higher priority on longest rule (longest first)",
path: "/mypath",
cases: []Case{
{
xFrom: "header1",
rule: "PathPrefix(`/mypath`)",
},
{
xFrom: "header2",
rule: "PathPrefix(`/my`)",
},
},
expected: "header1",
},
{
desc: "Higher priority on longest rule (longest second)",
path: "/mypath",
cases: []Case{
{
xFrom: "header1",
rule: "PathPrefix(`/my`)",
},
{
xFrom: "header2",
rule: "PathPrefix(`/mypath`)",
},
},
expected: "header2",
},
{
desc: "Higher priority on longest rule (longest third)",
path: "/mypath",
cases: []Case{
{
xFrom: "header1",
rule: "PathPrefix(`/my`)",
},
{
xFrom: "header2",
rule: "PathPrefix(`/mypa`)",
},
{
xFrom: "header3",
rule: "PathPrefix(`/mypath`)",
},
},
expected: "header3",
},
}
routeFoo, err := rules.Parse(expression01)
require.NoError(t, err, "Error while building route for %s", expression01)
for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
router, err := NewRouter()
require.NoError(t, err)
fooHandler := &fakeHandler{name: "fooHandler"}
routeFoo.Handler(fooHandler)
for _, route := range test.cases {
route := route
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-From", route.xFrom)
})
routeMatch := router.Match(&http.Request{URL: &url.URL{Path: "/foo"}}, &mux.RouteMatch{})
assert.True(t, routeMatch, "Error matching route")
err := router.AddRoute(route.rule, route.priority, handler)
require.NoError(t, err, route.rule)
}
routeMatch = router.Match(&http.Request{URL: &url.URL{Path: "/fo"}}, &mux.RouteMatch{})
assert.False(t, routeMatch, "Error matching route")
router.SortRoutes()
multipleRules := &Rules{Route: &types.ServerRoute{Route: router.NewRoute()}}
expression02 := "PathPrefix:/foobar"
w := httptest.NewRecorder()
req := testhelpers.MustNewRequest(http.MethodGet, test.path, nil)
routeFoobar, err := multipleRules.Parse(expression02)
require.NoError(t, err, "Error while building route for %s", expression02)
router.ServeHTTP(w, req)
foobarHandler := &fakeHandler{name: "foobarHandler"}
routeFoobar.Handler(foobarHandler)
routeMatch = router.Match(&http.Request{URL: &url.URL{Path: "/foo"}}, &mux.RouteMatch{})
assert.True(t, routeMatch, "Error matching route")
fooMatcher := &mux.RouteMatch{}
routeMatch = router.Match(&http.Request{URL: &url.URL{Path: "/foobar"}}, fooMatcher)
assert.True(t, routeMatch, "Error matching route")
assert.NotEqual(t, fooMatcher.Handler, foobarHandler, "Error matching priority")
assert.Equal(t, fooMatcher.Handler, fooHandler, "Error matching priority")
routeFoo.Priority(1)
routeFoobar.Priority(10)
router.SortRoutes()
foobarMatcher := &mux.RouteMatch{}
routeMatch = router.Match(&http.Request{URL: &url.URL{Path: "/foobar"}}, foobarMatcher)
assert.True(t, routeMatch, "Error matching route")
assert.Equal(t, foobarMatcher.Handler, foobarHandler, "Error matching priority")
assert.NotEqual(t, foobarMatcher.Handler, fooHandler, "Error matching priority")
assert.Equal(t, test.expected, w.Header().Get("X-From"))
})
}
}
func TestHostRegexp(t *testing.T) {
@ -235,13 +635,9 @@ func TestHostRegexp(t *testing.T) {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
rls := &Rules{
Route: &types.ServerRoute{
Route: &mux.Route{},
},
}
rt := rls.hostRegexp(test.hostExp)
rt := &mux.Route{}
err := hostRegexp(rt, test.hostExp)
require.NoError(t, err)
for testURL, match := range test.urls {
req := testhelpers.MustNewRequest(http.MethodGet, testURL, nil)
@ -251,83 +647,57 @@ func TestHostRegexp(t *testing.T) {
}
}
func TestParseInvalidSyntax(t *testing.T) {
router := mux.NewRouter()
rules := &Rules{Route: &types.ServerRoute{Route: router.NewRoute()}}
expression01 := "Path: /path1;Query:param_one=true, /path2"
routeFoo, err := rules.Parse(expression01)
require.Error(t, err)
assert.Nil(t, routeFoo)
}
func TestPathPrefix(t *testing.T) {
func TestParseDomains(t *testing.T) {
testCases := []struct {
desc string
path string
urls map[string]bool
description string
expression string
domain []string
errorExpected bool
}{
{
desc: "leading slash",
path: "/bar",
urls: map[string]bool{
"http://foo.com/bar": true,
"http://foo.com/bar/": true,
},
description: "Many host rules",
expression: "Host(`foo.bar`,`test.bar`)",
domain: []string{"foo.bar", "test.bar"},
errorExpected: false,
},
{
desc: "leading trailing slash",
path: "/bar/",
urls: map[string]bool{
"http://foo.com/bar": false,
"http://foo.com/bar/": true,
},
description: "No host rule",
expression: "Path(`/test`)",
errorExpected: false,
},
{
desc: "no slash",
path: "bar",
urls: map[string]bool{
"http://foo.com/bar": false,
"http://foo.com/bar/": false,
},
description: "Host rule and another rule",
expression: "Host(`foo.bar`) && Path(`/test`)",
domain: []string{"foo.bar"},
errorExpected: false,
},
{
desc: "trailing slash",
path: "bar/",
urls: map[string]bool{
"http://foo.com/bar": false,
"http://foo.com/bar/": false,
},
description: "Host rule to trim and another rule",
expression: "Host(`Foo.Bar`) && Path(`/test`)",
domain: []string{"foo.bar"},
errorExpected: false,
},
{
description: "Host rule with no domain",
expression: "Host() && Path(`/test`)",
errorExpected: false,
},
}
for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) {
t.Run(test.expression, func(t *testing.T) {
t.Parallel()
rls := &Rules{
Route: &types.ServerRoute{
Route: &mux.Route{},
},
domains, err := ParseDomains(test.expression)
if test.errorExpected {
require.Errorf(t, err, "unable to parse correctly the domains in the Host rule from %q", test.expression)
} else {
require.NoError(t, err, "%s: Error while parsing domain.", test.expression)
}
rt := rls.pathPrefix(test.path)
for testURL, expectedMatch := range test.urls {
req := testhelpers.MustNewRequest(http.MethodGet, testURL, nil)
match := rt.Match(req, &mux.RouteMatch{})
if match != expectedMatch {
t.Errorf("Error matching %s with %s, got %v expected %v", test.path, testURL, match, expectedMatch)
}
}
assert.EqualValues(t, test.domain, domains, "%s: Error parsing domains from expression.", test.expression)
})
}
}
type fakeHandler struct {
name string
}
func (h *fakeHandler) ServeHTTP(http.ResponseWriter, *http.Request) {}