Skip to content

Commit

Permalink
Add method to validate IP Block Prefix (#58)
Browse files Browse the repository at this point in the history
Validate that a prefix is a valid IP prefix for IPBlocks.

https://pkg.go.dev/net/netip#ParsePrefix

Signed-off-by: Anya Krupp <[email protected]>
  • Loading branch information
cherchezlafemme authored Oct 4, 2023
1 parent 66fde1c commit a94d0db
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
4 changes: 3 additions & 1 deletion internal/ent/schema/ip_block.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"

"go.infratographer.com/ipam-api/internal/ent/schema/validator"
"go.infratographer.com/ipam-api/x/pubsubinfo"

"go.infratographer.com/x/entx"
Expand Down Expand Up @@ -43,7 +44,8 @@ func (IPBlock) Fields() []ent.Field {
Comment("The prefix of the ip block.").
Annotations(
entgql.OrderField("PREFIX"),
),
).
Validate(validator.IPBlockPref),
field.String("block_type_id").
GoType(gidx.PrefixedID("")).
Immutable().
Expand Down
19 changes: 19 additions & 0 deletions internal/ent/schema/validator/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"net"
"net/netip"
)

// IPAddr returns error if IP address is NOT valid
Expand All @@ -22,3 +23,21 @@ var ErrInvalidIPAddr = errors.New("provided IP Address is invalid")
func InvalidIPAddrError(ip string) error {
return fmt.Errorf("error %w: %s", ErrInvalidIPAddr, ip)
}

// IPBlockPref returns error if IP Block Prefix is NOT valid
func IPBlockPref(prefix string) error {
_, err := netip.ParsePrefix(prefix)
if err != nil {
return InvalidIPPrefError(prefix)
}

return nil
}

// ErrInvalidIPPref is an error raised when provided IP Block Prefix is invalid
var ErrInvalidIPPref = errors.New("provided IP Block Prefix is invalid")

// InvalidIPPrefError returns Error Invalid IP Block Prefix
func InvalidIPPrefError(prefix string) error {
return fmt.Errorf("error %w: %s", ErrInvalidIPPref, prefix)
}

0 comments on commit a94d0db

Please sign in to comment.