Add 'proxy/' from commit '201b9a652685cdfb72ba81c7e7b00ba1c60a0e35'

git-subtree-dir: proxy
git-subtree-mainline: 571d96e856
git-subtree-split: 201b9a6526
This commit is contained in:
A.Unger
2020-09-18 12:47:26 +02:00
107 changed files with 8151 additions and 0 deletions
+40
View File
@@ -0,0 +1,40 @@
package proxy
import (
"github.com/owncloud/ocis-pkg/v2/log"
"github.com/owncloud/ocis-proxy/pkg/config"
)
// Option defines a single option function.
type Option func(o *Options)
// Options defines the available options for this package.
type Options struct {
Logger log.Logger
Config *config.Config
}
// newOptions initializes the available default options.
func newOptions(opts ...Option) Options {
opt := Options{}
for _, o := range opts {
o(&opt)
}
return opt
}
// Logger provides a function to set the logger option.
func Logger(val log.Logger) Option {
return func(o *Options) {
o.Logger = val
}
}
// Config provides a function to set the config option.
func Config(val *config.Config) Option {
return func(o *Options) {
o.Config = val
}
}
+113
View File
@@ -0,0 +1,113 @@
package policy
import (
"context"
"fmt"
"net/http"
"github.com/micro/go-micro/v2/client/grpc"
accounts "github.com/owncloud/ocis-accounts/pkg/proto/v0"
"github.com/owncloud/ocis-pkg/v2/oidc"
"github.com/owncloud/ocis-proxy/pkg/config"
)
var (
// ErrMultipleSelectors in case there is more then one selector configured.
ErrMultipleSelectors = fmt.Errorf("only one type of policy-selector (static or migration) can be configured")
// ErrSelectorConfigIncomplete if policy_selector conf is missing
ErrSelectorConfigIncomplete = fmt.Errorf("missing either \"static\" or \"migration\" configuration in policy_selector config ")
// ErrUnexpectedConfigError unexpected config error
ErrUnexpectedConfigError = fmt.Errorf("could not initialize policy-selector for given config")
)
// Selector is a function which selects a proxy-policy based on the request.
//
// A policy is a random name which identifies a set of proxy-routes:
//{
// "policies": [
// {
// "name": "us-east-1",
// "routes": [
// {
// "endpoint": "/",
// "backend": "https://backend.us.example.com:8080/app"
// }
// ]
// },
// {
// "name": "eu-ams-1",
// "routes": [
// {
// "endpoint": "/",
// "backend": "https://backend.eu.example.com:8080/app"
// }
// ]
// }
// ]
//}
type Selector func(ctx context.Context, r *http.Request) (string, error)
// LoadSelector constructs a specific policy-selector from a given configuration
func LoadSelector(cfg *config.PolicySelector) (Selector, error) {
if cfg.Migration != nil && cfg.Static != nil {
return nil, ErrMultipleSelectors
}
if cfg.Migration == nil && cfg.Static == nil {
return nil, ErrSelectorConfigIncomplete
}
if cfg.Static != nil {
return NewStaticSelector(cfg.Static), nil
}
if cfg.Migration != nil {
return NewMigrationSelector(
cfg.Migration,
accounts.NewAccountsService("com.owncloud.accounts", grpc.NewClient())), nil
}
return nil, ErrUnexpectedConfigError
}
// NewStaticSelector returns a selector which uses a pre-configured policy.
//
// Configuration:
//
// "policy_selector": {
// "static": {"policy" : "reva"}
// },
func NewStaticSelector(cfg *config.StaticSelectorConf) Selector {
return func(ctx context.Context, r *http.Request) (s string, err error) {
return cfg.Policy, nil
}
}
// NewMigrationSelector selects the policy based on the existence of the oidc "preferred_username" claim in the accounts-service.
// The policy for each case is configurable:
// "policy_selector": {
// "migration": {
// "acc_found_policy" : "reva",
// "acc_not_found_policy": "oc10",
// "unauthenticated_policy": "oc10"
// }
// },
//
// This selector can be used in migration-scenarios where some users have already migrated from ownCloud10 to OCIS and
// thus have an entry in ocis-accounts. All users without accounts entry are routed to the legacy ownCloud10 instance.
func NewMigrationSelector(cfg *config.MigrationSelectorConf, ss accounts.AccountsService) Selector {
var acc = ss
return func(ctx context.Context, r *http.Request) (s string, err error) {
var userID string
if claims := oidc.FromContext(r.Context()); claims != nil {
userID = claims.PreferredUsername
if _, err := acc.GetAccount(ctx, &accounts.GetAccountRequest{Id: userID}); err != nil {
return cfg.AccNotFoundPolicy, nil
}
return cfg.AccFoundPolicy, nil
}
return cfg.UnauthenticatedPolicy, nil
}
}
+97
View File
@@ -0,0 +1,97 @@
package policy
import (
"context"
"fmt"
"net/http/httptest"
"testing"
"github.com/micro/go-micro/v2/client"
"github.com/owncloud/ocis-accounts/pkg/proto/v0"
"github.com/owncloud/ocis-pkg/v2/oidc"
"github.com/owncloud/ocis-proxy/pkg/config"
)
func TestStaticSelector(t *testing.T) {
ctx := context.Background()
req := httptest.NewRequest("GET", "https://example.org/foo", nil)
sel := NewStaticSelector(&config.StaticSelectorConf{Policy: "reva"})
want := "reva"
got, err := sel(ctx, req)
if got != want {
t.Errorf("Expected policy %v got %v", want, got)
}
if err != nil {
t.Errorf("Unexpected error %v", err)
}
sel = NewStaticSelector(&config.StaticSelectorConf{Policy: "foo"})
want = "foo"
got, err = sel(ctx, req)
if got != want {
t.Errorf("Expected policy %v got %v", want, got)
}
if err != nil {
t.Errorf("Unexpected error %v", err)
}
}
type testCase struct {
AccSvcShouldReturnError bool
Claims *oidc.StandardClaims
Expected string
}
func TestMigrationSelector(t *testing.T) {
cfg := config.MigrationSelectorConf{
AccFoundPolicy: "found",
AccNotFoundPolicy: "not_found",
UnauthenticatedPolicy: "unauth",
}
var tests = []testCase{
{true, &oidc.StandardClaims{PreferredUsername: "Hans"}, "not_found"},
{false, &oidc.StandardClaims{PreferredUsername: "Hans"}, "found"},
{false, nil, "unauth"},
}
for _, tc := range tests {
//t.Run(fmt.Sprintf("#%v", k), func(t *testing.T) {
// t.Parallel()
tc := tc
sut := NewMigrationSelector(&cfg, mockAccSvc(tc.AccSvcShouldReturnError))
r := httptest.NewRequest("GET", "https://example.com", nil)
ctx := oidc.NewContext(r.Context(), tc.Claims)
nr := r.WithContext(ctx)
got, err := sut(ctx, nr)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if got != tc.Expected {
t.Errorf("Expected Policy %v got %v", tc.Expected, got)
}
//})
}
}
func mockAccSvc(retErr bool) proto.AccountsService {
if retErr {
return &proto.MockAccountsService{
GetFunc: func(ctx context.Context, in *proto.GetAccountRequest, opts ...client.CallOption) (record *proto.Account, err error) {
return nil, fmt.Errorf("error returned by mockAccountsService GET")
},
}
}
return &proto.MockAccountsService{
GetFunc: func(ctx context.Context, in *proto.GetAccountRequest, opts ...client.CallOption) (record *proto.Account, err error) {
return &proto.Account{}, nil
},
}
}
+385
View File
@@ -0,0 +1,385 @@
package proxy
import (
"context"
"net/http"
"net/http/httputil"
"net/url"
"regexp"
"strings"
"github.com/owncloud/ocis-proxy/pkg/proxy/policy"
"go.opencensus.io/plugin/ochttp/propagation/tracecontext"
"go.opencensus.io/trace"
"github.com/owncloud/ocis-pkg/v2/log"
"github.com/owncloud/ocis-proxy/pkg/config"
)
// MultiHostReverseProxy extends httputil to support multiple hosts with diffent policies
type MultiHostReverseProxy struct {
httputil.ReverseProxy
Directors map[string]map[config.RouteType]map[string]func(req *http.Request)
PolicySelector policy.Selector
logger log.Logger
propagator tracecontext.HTTPFormat
config *config.Config
}
// NewMultiHostReverseProxy undocummented
func NewMultiHostReverseProxy(opts ...Option) *MultiHostReverseProxy {
options := newOptions(opts...)
rp := &MultiHostReverseProxy{
Directors: make(map[string]map[config.RouteType]map[string]func(req *http.Request)),
logger: options.Logger,
config: options.Config,
}
rp.Director = rp.directorSelectionDirector
if options.Config.Policies == nil {
rp.logger.Info().Str("source", "runtime").Msg("Policies")
options.Config.Policies = defaultPolicies()
} else {
rp.logger.Info().Str("source", "file").Msg("Policies")
}
if options.Config.PolicySelector == nil {
firstPolicy := options.Config.Policies[0].Name
rp.logger.Warn().Msgf("policy-selector not configured. Will always use first policy: '%v'", firstPolicy)
options.Config.PolicySelector = &config.PolicySelector{
Static: &config.StaticSelectorConf{
Policy: firstPolicy,
},
}
}
rp.logger.Debug().
Interface("selector_config", options.Config.PolicySelector).
Msg("loading policy-selector")
policySelector, err := policy.LoadSelector(options.Config.PolicySelector)
if err != nil {
rp.logger.Fatal().Err(err).Msg("Could not load policy-selector")
}
rp.PolicySelector = policySelector
for _, pol := range options.Config.Policies {
for _, route := range pol.Routes {
rp.logger.Debug().Str("fwd: ", route.Endpoint)
uri, err := url.Parse(route.Backend)
if err != nil {
rp.logger.
Fatal().
Err(err).
Msgf("malformed url: %v", route.Backend)
}
rp.logger.
Debug().
Interface("route", route).
Msg("adding route")
rp.AddHost(pol.Name, uri, route)
}
}
return rp
}
func (p *MultiHostReverseProxy) directorSelectionDirector(r *http.Request) {
pol, err := p.PolicySelector(r.Context(), r)
if err != nil {
p.logger.Error().Msgf("Error while selecting pol %v", err)
return
}
if _, ok := p.Directors[pol]; !ok {
p.logger.
Error().
Msgf("policy %v is not configured", pol)
return
}
// find matching director
for _, rt := range config.RouteTypes {
var handler func(string, url.URL) bool
switch rt {
case config.QueryRoute:
handler = p.queryRouteMatcher
case config.RegexRoute:
handler = p.regexRouteMatcher
case config.PrefixRoute:
fallthrough
default:
handler = p.prefixRouteMatcher
}
for endpoint := range p.Directors[pol][rt] {
if handler(endpoint, *r.URL) {
p.logger.
Debug().
Str("policy", pol).
Str("prefix", endpoint).
Str("path", r.URL.Path).
Str("routeType", string(rt)).
Msg("director found")
p.Directors[pol][rt][endpoint](r)
return
}
}
}
// override default director with root. If any
if p.Directors[pol][config.PrefixRoute]["/"] != nil {
p.Directors[pol][config.PrefixRoute]["/"](r)
return
}
p.logger.
Warn().
Str("policy", pol).
Str("path", r.URL.Path).
Msg("no director found")
}
func singleJoiningSlash(a, b string) string {
aslash := strings.HasSuffix(a, "/")
bslash := strings.HasPrefix(b, "/")
switch {
case aslash && bslash:
return a + b[1:]
case !aslash && !bslash:
return a + "/" + b
}
return a + b
}
// AddHost undocumented
func (p *MultiHostReverseProxy) AddHost(policy string, target *url.URL, rt config.Route) {
targetQuery := target.RawQuery
if p.Directors[policy] == nil {
p.Directors[policy] = make(map[config.RouteType]map[string]func(req *http.Request))
}
routeType := config.DefaultRouteType
if rt.Type != "" {
routeType = rt.Type
}
if p.Directors[policy][routeType] == nil {
p.Directors[policy][routeType] = make(map[string]func(req *http.Request))
}
p.Directors[policy][routeType][rt.Endpoint] = func(req *http.Request) {
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
// Apache deployments host addresses need to match on req.Host and req.URL.Host
// see https://stackoverflow.com/questions/34745654/golang-reverseproxy-with-apache2-sni-hostname-error
if rt.ApacheVHost {
req.Host = target.Host
}
req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
if targetQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = targetQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
}
if _, ok := req.Header["User-Agent"]; !ok {
// explicitly disable User-Agent so it's not set to default value
req.Header.Set("User-Agent", "")
}
}
}
func (p *MultiHostReverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
var span *trace.Span
// Start root span.
if p.config.Tracing.Enabled {
ctx, span = trace.StartSpan(context.Background(), r.URL.String())
defer span.End()
p.propagator.SpanContextToRequest(span.SpanContext(), r)
}
// Call upstream ServeHTTP
p.ReverseProxy.ServeHTTP(w, r.WithContext(ctx))
}
func (p MultiHostReverseProxy) queryRouteMatcher(endpoint string, target url.URL) bool {
u, _ := url.Parse(endpoint)
if strings.HasPrefix(target.Path, u.Path) && endpoint != "/" {
query := u.Query()
if len(query) != 0 {
rQuery := target.Query()
match := true
for k := range query {
v := query.Get(k)
rv := rQuery.Get(k)
if rv != v {
match = false
break
}
}
return match
}
}
return false
}
func (p *MultiHostReverseProxy) regexRouteMatcher(endpoint string, target url.URL) bool {
matched, err := regexp.MatchString(endpoint, target.String())
if err != nil {
p.logger.Warn().Err(err).Msgf("regex with pattern %s failed", endpoint)
}
return matched
}
func (p *MultiHostReverseProxy) prefixRouteMatcher(endpoint string, target url.URL) bool {
return strings.HasPrefix(target.Path, endpoint) && endpoint != "/"
}
func defaultPolicies() []config.Policy {
return []config.Policy{
{
Name: "reva",
Routes: []config.Route{
{
Endpoint: "/",
Backend: "http://localhost:9100",
},
{
Endpoint: "/.well-known/",
Backend: "http://localhost:9130",
},
{
Endpoint: "/konnect/",
Backend: "http://localhost:9130",
},
{
Endpoint: "/signin/",
Backend: "http://localhost:9130",
},
{
Type: config.RegexRoute,
Endpoint: "/ocs/v[12].php/cloud/user", // we have `user` and `users` in ocis-ocs
Backend: "http://localhost:9110",
},
{
Endpoint: "/ocs/",
Backend: "http://localhost:9140",
},
{
Type: config.QueryRoute,
Endpoint: "/remote.php/?preview=1",
Backend: "http://localhost:9115",
},
{
Endpoint: "/remote.php/",
Backend: "http://localhost:9140",
},
{
Endpoint: "/dav/",
Backend: "http://localhost:9140",
},
{
Endpoint: "/webdav/",
Backend: "http://localhost:9140",
},
{
Endpoint: "/status.php",
Backend: "http://localhost:9140",
},
{
Endpoint: "/index.php/",
Backend: "http://localhost:9140",
},
{
Endpoint: "/data",
Backend: "http://localhost:9140",
},
// if we were using the go micro api gateway we could look up the endpoint in the registry dynamically
{
Endpoint: "/api/v0/accounts",
Backend: "http://localhost:9181",
},
// TODO the lookup needs a better mechanism
{
Endpoint: "/accounts.js",
Backend: "http://localhost:9181",
},
{
Endpoint: "/api/v0/settings",
Backend: "http://localhost:9190",
},
{
Endpoint: "/settings.js",
Backend: "http://localhost:9190",
},
{
Endpoint: "/api/v0/greet",
Backend: "http://localhost:9105",
},
{
Endpoint: "/hello.js",
Backend: "http://localhost:9105",
},
},
},
{
Name: "oc10",
Routes: []config.Route{
{
Endpoint: "/",
Backend: "http://localhost:9100",
},
{
Endpoint: "/.well-known/",
Backend: "http://localhost:9130",
},
{
Endpoint: "/konnect/",
Backend: "http://localhost:9130",
},
{
Endpoint: "/signin/",
Backend: "http://localhost:9130",
},
{
Endpoint: "/ocs/",
Backend: "https://demo.owncloud.com",
ApacheVHost: true,
},
{
Endpoint: "/remote.php/",
Backend: "https://demo.owncloud.com",
ApacheVHost: true,
},
{
Endpoint: "/dav/",
Backend: "https://demo.owncloud.com",
ApacheVHost: true,
},
{
Endpoint: "/webdav/",
Backend: "https://demo.owncloud.com",
ApacheVHost: true,
},
{
Endpoint: "/status.php",
Backend: "https://demo.owncloud.com",
ApacheVHost: true,
},
{
Endpoint: "/index.php/",
Backend: "https://demo.owncloud.com",
ApacheVHost: true,
},
{
Endpoint: "/data",
Backend: "https://demo.owncloud.com",
ApacheVHost: true,
},
},
},
}
}
+222
View File
@@ -0,0 +1,222 @@
package proxy
import (
"bytes"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/owncloud/ocis-proxy/pkg/config"
)
func TestProxyIntegration(t *testing.T) {
var tests = []testCase{
// Simple prefix route
test("simple_prefix", withPolicy("reva", withRoutes{{
Type: config.PrefixRoute,
Endpoint: "/api",
Backend: "http://api.example.com"},
})).withRequest("GET", "https://example.com/api", nil).
expectProxyTo("http://api.example.com/api"),
// Complex prefix route, different method
test("complex_prefix_post", withPolicy("reva", withRoutes{{
Type: config.PrefixRoute,
Endpoint: "/api",
Backend: "http://api.example.com/service1/"},
})).withRequest("POST", "https://example.com/api", nil).
expectProxyTo("http://api.example.com/service1/api"),
// Query route
test("query_route", withPolicy("reva", withRoutes{{
Type: config.QueryRoute,
Endpoint: "/api?format=json",
Backend: "http://backend/"},
})).withRequest("GET", "https://example.com/api?format=json", nil).
expectProxyTo("http://backend/api?format=json"),
// Regex route
test("regex_route", withPolicy("reva", withRoutes{{
Type: config.RegexRoute,
Endpoint: `\/user\/(\d+)`,
Backend: "http://backend/"},
})).withRequest("POST", "https://example.com/user/1234", nil).
expectProxyTo("http://backend/user/1234"),
// Multiple prefix routes 1
test("multiple_prefix", withPolicy("reva", withRoutes{
{
Type: config.PrefixRoute,
Endpoint: "/api",
Backend: "http://api.example.com",
},
{
Type: config.PrefixRoute,
Endpoint: "/payment",
Backend: "http://payment.example.com",
},
})).withRequest("GET", "https://example.com/payment", nil).
expectProxyTo("http://payment.example.com/payment"),
// Multiple prefix routes 2
test("multiple_prefix", withPolicy("reva", withRoutes{
{
Type: config.PrefixRoute,
Endpoint: "/api",
Backend: "http://api.example.com",
},
{
Type: config.PrefixRoute,
Endpoint: "/payment",
Backend: "http://payment.example.com",
},
})).withRequest("GET", "https://example.com/api", nil).
expectProxyTo("http://api.example.com/api"),
// Mixed route types
test("mixed_types", withPolicy("reva", withRoutes{
{
Type: config.PrefixRoute,
Endpoint: "/api",
Backend: "http://api.example.com",
},
{
Type: config.RegexRoute,
Endpoint: `\/user\/(\d+)`,
Backend: "http://users.example.com",
ApacheVHost: false,
},
})).withRequest("GET", "https://example.com/api", nil).
expectProxyTo("http://api.example.com/api"),
// Mixed route types
test("mixed_types", withPolicy("reva", withRoutes{
{
Type: config.PrefixRoute,
Endpoint: "/api",
Backend: "http://api.example.com",
},
{
Type: config.RegexRoute,
Endpoint: `\/user\/(\d+)`,
Backend: "http://users.example.com",
ApacheVHost: false,
},
})).withRequest("GET", "https://example.com/user/1234", nil).
expectProxyTo("http://users.example.com/user/1234"),
}
for k := range tests {
t.Run(tests[k].id, func(t *testing.T) {
t.Parallel()
tc := tests[k]
rp := newTestProxy(testConfig(tc.conf), func(req *http.Request) *http.Response {
if got, want := req.URL.String(), tc.expect.String(); got != want {
t.Errorf("Proxied url should be %v got %v", want, got)
}
if got, want := req.Method, tc.input.Method; got != want {
t.Errorf("Proxied request method should be %v got %v", want, got)
}
if got, want := req.Proto, tc.input.Proto; got != want {
t.Errorf("Proxied request proto should be %v got %v", want, got)
}
return &http.Response{
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewBufferString(`OK`)),
Header: make(http.Header),
}
})
rr := httptest.NewRecorder()
rp.ServeHTTP(rr, tc.input)
if rr.Result().StatusCode != 200 {
t.Errorf("Expected status 200 from proxy-response got %v", rr.Result().StatusCode)
}
resultBody, err := ioutil.ReadAll(rr.Result().Body)
if err != nil {
t.Fatal("Error reading result body")
}
bodyString := string(resultBody)
if bodyString != `OK` {
t.Errorf("Result body of proxied response should be OK, got %v", bodyString)
}
})
}
}
func newTestProxy(cfg *config.Config, fn RoundTripFunc) *MultiHostReverseProxy {
rp := NewMultiHostReverseProxy(Config(cfg))
rp.Transport = fn
return rp
}
type RoundTripFunc func(req *http.Request) *http.Response
// RoundTrip .
func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req), nil
}
type withRoutes []config.Route
type testCase struct {
id string
input *http.Request
expect *url.URL
conf []config.Policy
}
func test(id string, policies ...config.Policy) *testCase {
tc := &testCase{
id: id,
}
for k := range policies {
tc.conf = append(tc.conf, policies[k])
}
return tc
}
func withPolicy(name string, r withRoutes) config.Policy {
return config.Policy{Name: name, Routes: r}
}
func (tc *testCase) withRequest(method string, target string, body io.Reader) *testCase {
tc.input = httptest.NewRequest(method, target, body)
return tc
}
func (tc *testCase) expectProxyTo(strURL string) testCase {
pu, err := url.Parse(strURL)
if err != nil {
log.Fatalf("Error parsing %v", strURL)
}
tc.expect = pu
return *tc
}
func testConfig(policy []config.Policy) *config.Config {
return &config.Config{
File: "",
Log: config.Log{},
Debug: config.Debug{},
HTTP: config.HTTP{},
Tracing: config.Tracing{},
Asset: config.Asset{},
Policies: policy,
OIDC: config.OIDC{},
PolicySelector: nil,
}
}
+112
View File
@@ -0,0 +1,112 @@
package proxy
import (
"net/url"
"testing"
"github.com/owncloud/ocis-proxy/pkg/config"
)
func TestPrefixRouteMatcher(t *testing.T) {
cfg := config.New()
p := NewMultiHostReverseProxy(Config(cfg))
endpoint := "/foobar"
u, _ := url.Parse("/foobar/baz/some/url")
matched := p.prefixRouteMatcher(endpoint, *u)
if !matched {
t.Errorf("Endpoint %s and URL %s should match", endpoint, u.String())
}
}
func TestQueryRouteMatcher(t *testing.T) {
cfg := config.New()
p := NewMultiHostReverseProxy(Config(cfg))
endpoint := "/foobar?parameter=true"
u, _ := url.Parse("/foobar/baz/some/url?parameter=true")
matched := p.queryRouteMatcher(endpoint, *u)
if !matched {
t.Errorf("Endpoint %s and URL %s should match", endpoint, u.String())
}
}
func TestQueryRouteMatcherWithoutParameters(t *testing.T) {
cfg := config.New()
p := NewMultiHostReverseProxy(Config(cfg))
endpoint := "/foobar"
u, _ := url.Parse("/foobar/baz/some/url?parameter=true")
matched := p.queryRouteMatcher(endpoint, *u)
if matched {
t.Errorf("Endpoint %s and URL %s should not match", endpoint, u.String())
}
}
func TestQueryRouteMatcherWithDifferingParameters(t *testing.T) {
cfg := config.New()
p := NewMultiHostReverseProxy(Config(cfg))
endpoint := "/foobar?parameter=false"
u, _ := url.Parse("/foobar/baz/some/url?parameter=true")
matched := p.queryRouteMatcher(endpoint, *u)
if matched {
t.Errorf("Endpoint %s and URL %s should not match", endpoint, u.String())
}
}
func TestQueryRouteMatcherWithMultipleDifferingParameters(t *testing.T) {
cfg := config.New()
p := NewMultiHostReverseProxy(Config(cfg))
endpoint := "/foobar?parameter=false&other=true"
u, _ := url.Parse("/foobar/baz/some/url?parameter=true")
matched := p.queryRouteMatcher(endpoint, *u)
if matched {
t.Errorf("Endpoint %s and URL %s should not match", endpoint, u.String())
}
}
func TestQueryRouteMatcherWithMultipleParameters(t *testing.T) {
cfg := config.New()
p := NewMultiHostReverseProxy(Config(cfg))
endpoint := "/foobar?parameter=false&other=true"
u, _ := url.Parse("/foobar/baz/some/url?parameter=false&other=true")
matched := p.queryRouteMatcher(endpoint, *u)
if !matched {
t.Errorf("Endpoint %s and URL %s should match", endpoint, u.String())
}
}
func TestRegexRouteMatcher(t *testing.T) {
cfg := config.New()
p := NewMultiHostReverseProxy(Config(cfg))
endpoint := ".*some\\/url.*parameter=true"
u, _ := url.Parse("/foobar/baz/some/url?parameter=true")
matched := p.regexRouteMatcher(endpoint, *u)
if !matched {
t.Errorf("Endpoint %s and URL %s should match", endpoint, u.String())
}
}
func TestRegexRouteMatcherWithInvalidPattern(t *testing.T) {
cfg := config.New()
p := NewMultiHostReverseProxy(Config(cfg))
endpoint := "([\\])\\w+"
u, _ := url.Parse("/foobar/baz/some/url?parameter=true")
matched := p.regexRouteMatcher(endpoint, *u)
if matched {
t.Errorf("Endpoint %s and URL %s should not match", endpoint, u.String())
}
}