Skip to content

refact whitelist/allowlist: net.IP to net/netip #3683

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions pkg/apiserver/apic.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"errors"
"fmt"
"math/rand"
"net"
"net/netip"
"net/http"
"net/url"
"slices"
Expand Down Expand Up @@ -844,26 +844,31 @@

// if decisions is whitelisted: return representation of the whitelist ip or cidr
// if not whitelisted: empty string
func (a *apic) whitelistedBy(decision *models.Decision, additionalIPs []net.IP, additionalRanges []*net.IPNet) string {
func (a *apic) whitelistedBy(decision *models.Decision, additionalIPs []netip.Addr, additionalRanges []netip.Prefix) string {
if decision.Value == nil {
return ""
}

ipval := net.ParseIP(*decision.Value)
ipval, err := netip.ParseAddr(*decision.Value)
if err != nil {
// XXX: handle error?
return ""
}

Check warning on line 856 in pkg/apiserver/apic.go

View check run for this annotation

Codecov / codecov/patch

pkg/apiserver/apic.go#L854-L856

Added lines #L854 - L856 were not covered by tests

for _, cidr := range a.whitelists.Cidrs {
if cidr.Contains(ipval) {
return cidr.String()
}
}

for _, ip := range a.whitelists.Ips {
if ip != nil && ip.Equal(ipval) {
if ip == ipval {
return ip.String()
}
}

for _, ip := range additionalIPs {
if ip.Equal(ipval) {
if ip == ipval {
return ip.String()
}
}
Expand Down
8 changes: 4 additions & 4 deletions pkg/apiserver/apic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"net"
"net/netip"
"net/http"
"net/url"
"os"
Expand Down Expand Up @@ -528,14 +528,14 @@ func TestAPICWhitelists(t *testing.T) {
api := getAPIC(t, ctx)
// one whitelist on IP, one on CIDR
api.whitelists = &csconfig.CapiWhitelist{}
api.whitelists.Ips = append(api.whitelists.Ips, net.ParseIP("9.2.3.4"), net.ParseIP("7.2.3.4"))
api.whitelists.Ips = append(api.whitelists.Ips, netip.MustParseAddr("9.2.3.4"), netip.MustParseAddr("7.2.3.4"))

_, tnet, err := net.ParseCIDR("13.2.3.0/24")
tnet, err := netip.ParsePrefix("13.2.3.0/24")
require.NoError(t, err)

api.whitelists.Cidrs = append(api.whitelists.Cidrs, tnet)

_, tnet, err = net.ParseCIDR("11.2.3.0/24")
tnet, err = netip.ParsePrefix("11.2.3.0/24")
require.NoError(t, err)

api.whitelists.Cidrs = append(api.whitelists.Cidrs, tnet)
Expand Down
17 changes: 9 additions & 8 deletions pkg/csconfig/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"io"
"net"
"net/netip"
"os"
"strings"
"time"
Expand Down Expand Up @@ -276,8 +277,8 @@ func toValidCIDR(ip string) string {
}

type CapiWhitelist struct {
Ips []net.IP `yaml:"ips,omitempty"`
Cidrs []*net.IPNet `yaml:"cidrs,omitempty"`
Ips []netip.Addr `yaml:"ips,omitempty"`
Cidrs []netip.Prefix `yaml:"cidrs,omitempty"`
}

type LocalAPIAutoRegisterCfg struct {
Expand Down Expand Up @@ -450,21 +451,21 @@ func parseCapiWhitelists(fd io.Reader) (*CapiWhitelist, error) {
}

ret := &CapiWhitelist{
Ips: make([]net.IP, len(fromCfg.Ips)),
Cidrs: make([]*net.IPNet, len(fromCfg.Cidrs)),
Ips: make([]netip.Addr, len(fromCfg.Ips)),
Cidrs: make([]netip.Prefix, len(fromCfg.Cidrs)),
}

for idx, v := range fromCfg.Ips {
ip := net.ParseIP(v)
if ip == nil {
return nil, fmt.Errorf("invalid IP address: %s", v)
ip, err := netip.ParseAddr(v)
if err != nil {
return nil, err
}

ret.Ips[idx] = ip
}

for idx, v := range fromCfg.Cidrs {
_, tnet, err := net.ParseCIDR(v)
tnet, err := netip.ParsePrefix(v)
if err != nil {
return nil, err
}
Expand Down
25 changes: 9 additions & 16 deletions pkg/csconfig/api_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package csconfig

import (
"net"
"net/netip"
"os"
"strings"
"testing"
Expand Down Expand Up @@ -271,13 +271,6 @@ func TestLoadAPIServer(t *testing.T) {
}
}

func mustParseCIDRNet(t *testing.T, s string) *net.IPNet {
_, ipNet, err := net.ParseCIDR(s)
require.NoError(t, err)

return ipNet
}

func TestParseCapiWhitelists(t *testing.T) {
tests := []struct {
name string
Expand All @@ -289,33 +282,33 @@ func TestParseCapiWhitelists(t *testing.T) {
name: "empty file",
input: "",
expected: &CapiWhitelist{
Ips: []net.IP{},
Cidrs: []*net.IPNet{},
Ips: []netip.Addr{},
Cidrs: []netip.Prefix{},
},
expectedErr: "empty file",
},
{
name: "empty ip and cidr",
input: `{"ips": [], "cidrs": []}`,
expected: &CapiWhitelist{
Ips: []net.IP{},
Cidrs: []*net.IPNet{},
Ips: []netip.Addr{},
Cidrs: []netip.Prefix{},
},
},
{
name: "some ip",
input: `{"ips": ["1.2.3.4"]}`,
expected: &CapiWhitelist{
Ips: []net.IP{net.IPv4(1, 2, 3, 4)},
Cidrs: []*net.IPNet{},
Ips: []netip.Addr{netip.MustParseAddr("1.2.3.4")},
Cidrs: []netip.Prefix{},
},
},
{
name: "some cidr",
input: `{"cidrs": ["1.2.3.0/24"]}`,
expected: &CapiWhitelist{
Ips: []net.IP{},
Cidrs: []*net.IPNet{mustParseCIDRNet(t, "1.2.3.0/24")},
Ips: []netip.Addr{},
Cidrs: []netip.Prefix{netip.MustParsePrefix("1.2.3.0/24")},
},
},
}
Expand Down
14 changes: 7 additions & 7 deletions pkg/database/allowlists.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import (
"context"
"fmt"
"net"
"net/netip"
"strings"
"time"

Expand Down Expand Up @@ -354,31 +354,31 @@
return true, reason, nil
}

func (c *Client) GetAllowlistsContentForAPIC(ctx context.Context) ([]net.IP, []*net.IPNet, error) {
func (c *Client) GetAllowlistsContentForAPIC(ctx context.Context) ([]netip.Addr, []netip.Prefix, error) {
allowlists, err := c.ListAllowLists(ctx, true)
if err != nil {
return nil, nil, fmt.Errorf("unable to get allowlists: %w", err)
}

var (
ips []net.IP
nets []*net.IPNet
ips []netip.Addr
nets []netip.Prefix
)

for _, allowlist := range allowlists {
for _, item := range allowlist.Edges.AllowlistItems {
if item.ExpiresAt.IsZero() || item.ExpiresAt.After(time.Now().UTC()) {
if strings.Contains(item.Value, "/") {
_, ipNet, err := net.ParseCIDR(item.Value)
ipNet, err := netip.ParsePrefix(item.Value)

Check warning on line 372 in pkg/database/allowlists.go

View check run for this annotation

Codecov / codecov/patch

pkg/database/allowlists.go#L372

Added line #L372 was not covered by tests
if err != nil {
c.Log.Errorf("unable to parse CIDR %s: %s", item.Value, err)
continue
}

nets = append(nets, ipNet)
} else {
ip := net.ParseIP(item.Value)
if ip == nil {
ip, err := netip.ParseAddr(item.Value)
if err != nil {
c.Log.Errorf("unable to parse IP %s", item.Value)
continue
}
Expand Down
19 changes: 11 additions & 8 deletions pkg/parser/whitelist.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package parser

import (
"fmt"
"net"
"net/netip"

"github.com/expr-lang/expr"
"github.com/expr-lang/expr/vm"
Expand All @@ -15,9 +15,9 @@ import (
type Whitelist struct {
Reason string `yaml:"reason,omitempty"`
Ips []string `yaml:"ip,omitempty"`
B_Ips []net.IP
B_Ips []netip.Addr
Cidrs []string `yaml:"cidr,omitempty"`
B_Cidrs []*net.IPNet
B_Cidrs []netip.Prefix
Exprs []string `yaml:"expression,omitempty"`
B_Exprs []*ExprWhitelist
}
Expand Down Expand Up @@ -50,7 +50,7 @@ func (n *Node) CheckIPsWL(p *types.Event) bool {
break
}
for _, v := range n.Whitelist.B_Ips {
if v.Equal(src) {
if v == src {
n.Logger.Debugf("Event from [%s] is whitelisted by IP (%s), reason [%s]", src, v, n.Whitelist.Reason)
isWhitelisted = true
break
Expand Down Expand Up @@ -110,14 +110,17 @@ func (n *Node) CheckExprWL(cachedExprEnv map[string]interface{}, p *types.Event)

func (n *Node) CompileWLs() (bool, error) {
for _, v := range n.Whitelist.Ips {
n.Whitelist.B_Ips = append(n.Whitelist.B_Ips, net.ParseIP(v))
n.Logger.Debugf("adding ip %s to whitelists", net.ParseIP(v))
if addr, err := netip.ParseAddr(v); err == nil {
n.Whitelist.B_Ips = append(n.Whitelist.B_Ips, addr)
n.Logger.Debugf("adding ip %s to whitelists", addr)
}
// XXX: handle error?
}

for _, v := range n.Whitelist.Cidrs {
_, tnet, err := net.ParseCIDR(v)
tnet, err := netip.ParsePrefix(v)
if err != nil {
return false, fmt.Errorf("unable to parse cidr whitelist '%s' : %v", v, err)
return false, fmt.Errorf("parsing whitelist: %w", err)
}
n.Whitelist.B_Cidrs = append(n.Whitelist.B_Cidrs, tnet)
n.Logger.Debugf("adding cidr %s to whitelists", tnet)
Expand Down
2 changes: 1 addition & 1 deletion pkg/parser/whitelist_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func TestWhitelistCompile(t *testing.T) {
"127.0.0.1/1000",
},
},
expectedErr: "invalid CIDR address",
expectedErr: `parsing whitelist: netip.ParsePrefix("127.0.0.1/1000"): prefix length out of range`,
},
{
name: "Valid EXPR whitelist",
Expand Down
18 changes: 12 additions & 6 deletions pkg/types/event.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package types

import (
"net"
"net/netip"
"strings"
"time"

Expand Down Expand Up @@ -117,17 +117,23 @@ func (e *Event) GetMeta(key string) string {
return ""
}

func (e *Event) ParseIPSources() []net.IP {
var srcs []net.IP
func (e *Event) ParseIPSources() []netip.Addr {
var srcs []netip.Addr

switch e.Type {
case LOG:
if _, ok := e.Meta["source_ip"]; ok {
srcs = append(srcs, net.ParseIP(e.Meta["source_ip"]))
if val, ok := e.Meta["source_ip"]; ok {
if addr, err := netip.ParseAddr(val); err == nil {
srcs = append(srcs, addr)
}
// XXX handle error?
}
case OVFLW:
for k := range e.Overflow.Sources {
srcs = append(srcs, net.ParseIP(k))
if addr, err := netip.ParseAddr(k); err == nil {
srcs = append(srcs, addr)
}
// XXX handle error?
}
}

Expand Down
20 changes: 8 additions & 12 deletions pkg/types/event_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package types

import (
"net"
"net/netip"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -91,7 +91,7 @@ func TestParseIPSources(t *testing.T) {
tests := []struct {
name string
evt Event
expected []net.IP
expected []netip.Addr
}{
{
name: "ParseIPSources: Valid Log Sources",
Expand All @@ -101,8 +101,8 @@ func TestParseIPSources(t *testing.T) {
"source_ip": "127.0.0.1",
},
},
expected: []net.IP{
net.ParseIP("127.0.0.1"),
expected: []netip.Addr{
netip.MustParseAddr("127.0.0.1"),
},
},
{
Expand All @@ -115,8 +115,8 @@ func TestParseIPSources(t *testing.T) {
},
},
},
expected: []net.IP{
net.ParseIP("127.0.0.1"),
expected: []netip.Addr{
netip.MustParseAddr("127.0.0.1"),
},
},
{
Expand All @@ -127,9 +127,7 @@ func TestParseIPSources(t *testing.T) {
"source_ip": "IAMNOTANIP",
},
},
expected: []net.IP{
nil,
},
expected: nil,
},
{
name: "ParseIPSources: Invalid Overflow Sources",
Expand All @@ -141,9 +139,7 @@ func TestParseIPSources(t *testing.T) {
},
},
},
expected: []net.IP{
nil,
},
expected: nil,
},
}

Expand Down
Loading