Skip to content

Commit

Permalink
openapi3: improve ipv6 validation (#971)
Browse files Browse the repository at this point in the history
  • Loading branch information
AnatolyRugalev authored Jun 27, 2024
1 parent fe47dca commit 42a2d80
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 22 deletions.
31 changes: 13 additions & 18 deletions openapi3/schema_formats.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ package openapi3

import (
"fmt"
"net"
"net/netip"
"regexp"
"strings"
)

const (
Expand Down Expand Up @@ -43,23 +42,15 @@ func DefineStringFormatCallback(name string, callback FormatCallback) {
SchemaStringFormats[name] = Format{callback: callback}
}

func validateIP(ip string) error {
parsed := net.ParseIP(ip)
if parsed == nil {
func validateIPv4(ip string) error {
addr, err := netip.ParseAddr(ip)
if err != nil {
return &SchemaError{
Value: ip,
Reason: "Not an IP address",
}
}
return nil
}

func validateIPv4(ip string) error {
if err := validateIP(ip); err != nil {
return err
}

if !(strings.Count(ip, ":") < 2) {
if !addr.Is4() {
return &SchemaError{
Value: ip,
Reason: "Not an IPv4 address (it's IPv6)",
Expand All @@ -69,11 +60,15 @@ func validateIPv4(ip string) error {
}

func validateIPv6(ip string) error {
if err := validateIP(ip); err != nil {
return err
addr, err := netip.ParseAddr(ip)
if err != nil {
return &SchemaError{
Value: ip,
Reason: "Not an IP address",
Origin: err,
}
}

if !(strings.Count(ip, ":") >= 2) {
if !addr.Is6() {
return &SchemaError{
Value: ip,
Reason: "Not an IPv6 address (it's IPv4)",
Expand Down
9 changes: 5 additions & 4 deletions openapi3/schema_formats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ func TestIssue430(t *testing.T) {
"::FFFF:192.168.0.1": false,
// "[::FFFF:C0A8:1]:80" doesn't parse per net.ParseIP()
// "[::FFFF:C0A8:1%1]:80" doesn't parse per net.ParseIP()
"2001:db8::": false,
}

for datum := range data {
Expand All @@ -53,11 +54,11 @@ func TestIssue430(t *testing.T) {
err = schema.VisitJSON(datum)
require.NoError(t, err)
if isV4 {
require.Nil(t, validateIPv4(datum), "%q should be IPv4", datum)
require.NotNil(t, validateIPv6(datum), "%q should not be IPv6", datum)
assert.Nil(t, validateIPv4(datum), "%q should be IPv4", datum)
assert.NotNil(t, validateIPv6(datum), "%q should not be IPv6", datum)
} else {
require.NotNil(t, validateIPv4(datum), "%q should not be IPv4", datum)
require.Nil(t, validateIPv6(datum), "%q should be IPv6", datum)
assert.NotNil(t, validateIPv4(datum), "%q should not be IPv4", datum)
assert.Nil(t, validateIPv6(datum), "%q should be IPv6", datum)
}
}
}
Expand Down

0 comments on commit 42a2d80

Please sign in to comment.