From d874d4ce02196c1d1ed46e1092093f9be4473205 Mon Sep 17 00:00:00 2001 From: Shmulik Regev Date: Wed, 16 Aug 2023 17:19:31 +0300 Subject: [PATCH 1/2] Added as simple callback with the filter object so it can be dynamically changed --- ipfilter.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/ipfilter.go b/ipfilter.go index e1c5495..fe9657a 100644 --- a/ipfilter.go +++ b/ipfilter.go @@ -24,6 +24,11 @@ type Config struct { // Block by default. BlockByDefault bool + + // called with the newly created filter object to allow for + // controlling the filter during runtime. + // The underlying filter implementation is thankfully threadsafe + CreatedFilter func(*ipfilter.IPFilter) } // DefaultConfig is the default IPFilter middleware config @@ -55,7 +60,9 @@ func MiddlewareWithConfig(config Config) echo.MiddlewareFunc { BlockByDefault: config.BlockByDefault, Logger: nil, }) - + if config.CreatedFilter != nil { + config.CreatedFilter(filter) + } return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if config.Skipper(c) { From bf221e9e87e27552a090078272da6cec455cefa4 Mon Sep 17 00:00:00 2001 From: Shmulik Regev Date: Wed, 16 Aug 2023 20:27:12 +0300 Subject: [PATCH 2/2] Added some tests --- ipfilter_test.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/ipfilter_test.go b/ipfilter_test.go index a36fd5b..b52bea3 100644 --- a/ipfilter_test.go +++ b/ipfilter_test.go @@ -7,6 +7,7 @@ import ( "testing" ipfilter "github.com/crazy-max/echo-ipfilter" + jpillorafilter "github.com/jpillora/ipfilter" "github.com/labstack/echo/v4" ) @@ -94,6 +95,36 @@ func TestMiddlewareWithConfig(t *testing.T) { ip: "10.1.4.1:80", err: nil, }, + { + name: "dynamically allowed by whitelist", + config: ipfilter.Config{ + WhiteList: []string{ + "10.1.2.0/24", + // this will be dynamically added "10.1.4.0/24", + }, + BlockByDefault: true, + CreatedFilter: func(filter *jpillorafilter.IPFilter) { + filter.AllowIP("10.1.4.0/24") + }, + }, + ip: "10.1.4.1:80", + err: nil, + }, + { + name: "dynamically allowed by whitelist", + config: ipfilter.Config{ + WhiteList: []string{ + "10.1.2.0/24", // will be dynamicaly blocked + "10.1.4.0/24", + }, + BlockByDefault: true, + CreatedFilter: func(filter *jpillorafilter.IPFilter) { + filter.BlockIP("10.1.2.0/24") + }, + }, + ip: "10.1.2.7:80", + err: echo.NewHTTPError(http.StatusForbidden, fmt.Sprintf("IP address %s not allowed", "10.1.2.7")), + }, } for _, tt := range cases {