From 684dcd9ae8743813b303549c599fe757b126c139 Mon Sep 17 00:00:00 2001 From: zensh Date: Thu, 30 Jul 2020 14:59:54 +0800 Subject: [PATCH] make IPWhiteList support redirect --- pkg/config/dynamic/middlewares.go | 1 + pkg/middlewares/ipwhitelist/ip_whitelist.go | 11 +++++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/pkg/config/dynamic/middlewares.go b/pkg/config/dynamic/middlewares.go index c4e8be4142..493f731e3d 100644 --- a/pkg/config/dynamic/middlewares.go +++ b/pkg/config/dynamic/middlewares.go @@ -277,6 +277,7 @@ func (s *IPStrategy) Get() (ip.Strategy, error) { type IPWhiteList struct { SourceRange []string `json:"sourceRange,omitempty" toml:"sourceRange,omitempty" yaml:"sourceRange,omitempty"` IPStrategy *IPStrategy `json:"ipStrategy,omitempty" toml:"ipStrategy,omitempty" yaml:"ipStrategy,omitempty" label:"allowEmpty"` + Redirect string `json:"redirect,omitempty" toml:"redirect,omitempty" yaml:"redirect,omitempty"` } // +k8s:deepcopy-gen=true diff --git a/pkg/middlewares/ipwhitelist/ip_whitelist.go b/pkg/middlewares/ipwhitelist/ip_whitelist.go index 5e74685007..b93bd3c253 100644 --- a/pkg/middlewares/ipwhitelist/ip_whitelist.go +++ b/pkg/middlewares/ipwhitelist/ip_whitelist.go @@ -24,6 +24,7 @@ type ipWhiteLister struct { whiteLister *ip.Checker strategy ip.Strategy name string + redirect string } // New builds a new IPWhiteLister given a list of CIDR-Strings to whitelist @@ -52,6 +53,7 @@ func New(ctx context.Context, next http.Handler, config dynamic.IPWhiteList, nam whiteLister: checker, next: next, name: name, + redirect: config.Redirect, }, nil } @@ -68,7 +70,7 @@ func (wl *ipWhiteLister) ServeHTTP(rw http.ResponseWriter, req *http.Request) { logMessage := fmt.Sprintf("rejecting request %+v: %v", req, err) logger.Debug(logMessage) tracing.SetErrorWithEvent(req, logMessage) - reject(ctx, rw) + reject(ctx, rw, req, wl.redirect) return } logger.Debugf("Accept %s: %+v", wl.strategy.GetIP(req), req) @@ -76,7 +78,12 @@ func (wl *ipWhiteLister) ServeHTTP(rw http.ResponseWriter, req *http.Request) { wl.next.ServeHTTP(rw, req) } -func reject(ctx context.Context, rw http.ResponseWriter) { +func reject(ctx context.Context, rw http.ResponseWriter, req *http.Request, redirect string) { + if redirect != "" { + http.Redirect(rw, req, redirect, http.StatusTemporaryRedirect) + return + } + statusCode := http.StatusForbidden rw.WriteHeader(statusCode)