Skip to content

Commit

Permalink
Protect IPv6 last two octet + fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
tsknadaj committed Oct 10, 2024
1 parent 81b86d6 commit 7e4dfff
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
28 changes: 23 additions & 5 deletions gdpr/protect_ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gdpr
import (
"encoding/binary"
"net"
"net/netip"

"github.com/msales/gox/netx"
)
Expand All @@ -17,14 +18,31 @@ func ProtectIP[T IP](ip T) string {
switch cIP := any(ip).(type) {
// Every other type should end up in this case.
case net.IP:
// if IP is v6, we don't do anything with it.
if cIP.To4() == nil {
// if ip is somehow empty or nil, return empty string
if len(cIP) == 0 {
return ""
}

// if ip is somehow empty, return empty string
if len(cIP) == 0 {
return ""
// if IP is v6, we don't do anything with it.
if cIP.To4() == nil {

// if IPv6 is local we don't do anything
if cIP.String() == "::1" {
return cIP.String()
}

cIP[12] = 0
cIP[13] = 0
cIP[14] = 0
cIP[15] = 0

addr, err := netip.ParseAddr(cIP.String())
// if there is an error, we don't do anything, we return empty value because something is wrong with passed ip
if err != nil {
return ""
}

return addr.StringExpanded()
}

// change last octet of IP v4 to 0 and guard
Expand Down
2 changes: 1 addition & 1 deletion gdpr/protect_ip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func Test_ProtectIP_String(t *testing.T) {
{
name: "raw ip v6",
ip: "2001:0000:130F:0000:0000:09C0:876A:130B",
want: "2001:0000:130F:0000:0000:09C0:0000:0000",
want: "2001:0000:130f:0000:0000:09c0:0000:0000",
},
}
for _, tt := range tests {
Expand Down

0 comments on commit 7e4dfff

Please sign in to comment.