Skip to content

Commit

Permalink
Merge pull request #533 from martijnhoekstra/valid-cidr-only
Browse files Browse the repository at this point in the history
only accept valid CIDR lengths
  • Loading branch information
mpilquist authored Oct 17, 2023
2 parents d8d69ce + a356bf5 commit fa2d847
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
4 changes: 2 additions & 2 deletions shared/src/main/scala/com/comcast/ip4s/Cidr.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

package com.comcast.ip4s

import scala.util.Try
import scala.util.hashing.MurmurHash3

import cats.{Order, Show}
Expand Down Expand Up @@ -149,7 +148,8 @@ object Cidr {
case CidrPattern(addrStr, prefixBitsStr) =>
for {
addr <- parseAddress(addrStr)
prefixBits <- Try(prefixBitsStr.toInt).toOption
maxPrefixBits = addr.fold(_ => 32, _ => 128)
prefixBits <- prefixBitsStr.toIntOption if prefixBits >= 0 && prefixBits <= maxPrefixBits
} yield Cidr(addr, prefixBits)
case _ => None
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,12 @@ class CidrTest extends BaseTestSuite {
assertEquals(Cidr.fromIpAndMask(ip, mask), Cidr(ip, prefixBits))
}
}

property("parsing from string: only masks with a valid length return a CIDR") {
forAll { (ip: IpAddress, prefixBits: Int) =>
val cidr = Cidr.fromString(s"$ip/$prefixBits")
val max = ip.fold(_ => 32, _ => 128)
assertEquals(cidr.isDefined, (prefixBits <= max && prefixBits >= 0))
}
}
}

0 comments on commit fa2d847

Please sign in to comment.