add expr helper to check if IP is in ipRange (#113)
* add expr helper to check if IP is in ipRange * update helper name Co-authored-by: erenJag <erenJag>
This commit is contained in:
parent
454e2850b5
commit
f6826c7e47
|
@ -5,6 +5,7 @@ import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/antonmedv/expr"
|
"github.com/antonmedv/expr"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
"gotest.tools/assert"
|
"gotest.tools/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -113,3 +114,22 @@ func TestFile(t *testing.T) {
|
||||||
assert.Equal(t, test.result, result)
|
assert.Equal(t, test.result, result)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIpInRange(t *testing.T) {
|
||||||
|
env := map[string]interface{}{
|
||||||
|
"ip": "192.168.0.1",
|
||||||
|
"ipRange": "192.168.0.0/24",
|
||||||
|
"IpInRange": IpInRange,
|
||||||
|
}
|
||||||
|
code := "IpInRange(ip, ipRange)"
|
||||||
|
log.Printf("Running filter : %s", code)
|
||||||
|
|
||||||
|
program, err := expr.Compile(code, expr.Env(env))
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
output, err := expr.Run(program, env)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
require.Equal(t, true, output)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
|
@ -3,6 +3,7 @@ package exprhelpers
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
@ -36,6 +37,7 @@ func GetExprEnv(ctx map[string]interface{}) map[string]interface{} {
|
||||||
"File": File,
|
"File": File,
|
||||||
"RegexpInFile": RegexpInFile,
|
"RegexpInFile": RegexpInFile,
|
||||||
"Upper": Upper,
|
"Upper": Upper,
|
||||||
|
"IpInRange": IpInRange,
|
||||||
}
|
}
|
||||||
for k, v := range ctx {
|
for k, v := range ctx {
|
||||||
ExprLib[k] = v
|
ExprLib[k] = v
|
||||||
|
@ -101,3 +103,23 @@ func RegexpInFile(data string, filename string) bool {
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func IpInRange(ip string, ipRange string) bool {
|
||||||
|
var err error
|
||||||
|
var ipParsed net.IP
|
||||||
|
var ipRangeParsed *net.IPNet
|
||||||
|
|
||||||
|
ipParsed = net.ParseIP(ip)
|
||||||
|
if ipParsed == nil {
|
||||||
|
log.Errorf("'%s' is not a valid IP", ip)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if _, ipRangeParsed, err = net.ParseCIDR(ipRange); err != nil {
|
||||||
|
log.Errorf("'%s' is not a valid IP Range", ipRange)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if ipRangeParsed.Contains(ipParsed) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue