-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[Validator] Add CidrValidator to allow validation of CIDR notations #43593
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
Merged
derrabus
merged 1 commit into
symfony:5.4
from
popsorin:feature/cidr-notation-constraint
Oct 25, 2021
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\Validator\Constraints; | ||
|
||
use Symfony\Component\Validator\Constraint; | ||
use Symfony\Component\Validator\Exception\ConstraintDefinitionException; | ||
|
||
/** | ||
* Validates that a value is a valid CIDR notation. | ||
* | ||
* @Annotation | ||
* @Target({"PROPERTY", "METHOD", "ANNOTATION"}) | ||
* | ||
* @author Sorin Pop <[email protected]> | ||
* @author Calin Bolea <[email protected]> | ||
*/ | ||
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] | ||
class Cidr extends Constraint | ||
{ | ||
public const INVALID_CIDR_ERROR = '5649e53a-5afb-47c5-a360-ffbab3be8567'; | ||
public const OUT_OF_RANGE_ERROR = 'b9f14a51-acbd-401a-a078-8c6b204ab32f'; | ||
|
||
protected static $errorNames = [ | ||
self::INVALID_CIDR_ERROR => 'INVALID_CIDR_ERROR', | ||
self::OUT_OF_RANGE_ERROR => 'OUT_OF_RANGE_VIOLATION', | ||
]; | ||
|
||
private const NET_MAXES = [ | ||
Ip::ALL => 128, | ||
Ip::V4 => 32, | ||
Ip::V6 => 128, | ||
]; | ||
|
||
public $version = Ip::ALL; | ||
|
||
public $message = 'This value is not a valid CIDR notation.'; | ||
|
||
public $netmaskRangeViolationMessage = 'The value of the netmask should be between {{ min }} and {{ max }}.'; | ||
|
||
public $netmaskMin = 0; | ||
|
||
public $netmaskMax; | ||
|
||
public function __construct( | ||
array $options = null, | ||
string $version = null, | ||
int $netmaskMin = null, | ||
int $netmaskMax = null, | ||
string $message = null, | ||
array $groups = null, | ||
$payload = null | ||
) { | ||
$this->version = $version ?? $options['version'] ?? $this->version; | ||
|
||
if (!\in_array($this->version, array_keys(self::NET_MAXES))) { | ||
throw new ConstraintDefinitionException(sprintf('The option "version" must be one of "%s".', implode('", "', array_keys(self::NET_MAXES)))); | ||
} | ||
|
||
$this->netmaskMin = $netmaskMin ?? $options['netmaskMin'] ?? $this->netmaskMin; | ||
$this->netmaskMax = $netmaskMax ?? $options['netmaskMax'] ?? self::NET_MAXES[$this->version]; | ||
$this->message = $message ?? $this->message; | ||
|
||
unset($options['netmaskMin'], $options['netmaskMax'], $options['version']); | ||
|
||
if ($this->netmaskMin < 0 || $this->netmaskMax > self::NET_MAXES[$this->version] || $this->netmaskMin > $this->netmaskMax) { | ||
throw new ConstraintDefinitionException(sprintf('The netmask range must be between 0 and %d.', self::NET_MAXES[$this->version])); | ||
} | ||
|
||
parent::__construct($options, $groups, $payload); | ||
} | ||
} |
77 changes: 77 additions & 0 deletions
77
src/Symfony/Component/Validator/Constraints/CidrValidator.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\Validator\Constraints; | ||
|
||
use Symfony\Component\Validator\Constraint; | ||
use Symfony\Component\Validator\ConstraintValidator; | ||
use Symfony\Component\Validator\Exception\UnexpectedTypeException; | ||
use Symfony\Component\Validator\Exception\UnexpectedValueException; | ||
|
||
class CidrValidator extends ConstraintValidator | ||
{ | ||
public function validate($value, Constraint $constraint): void | ||
{ | ||
if (!$constraint instanceof Cidr) { | ||
throw new UnexpectedTypeException($constraint, Cidr::class); | ||
} | ||
|
||
if (null === $value || '' === $value) { | ||
return; | ||
} | ||
|
||
if (!\is_string($value)) { | ||
throw new UnexpectedValueException($value, 'string'); | ||
} | ||
|
||
$cidrParts = explode('/', $value, 2); | ||
|
||
if (!isset($cidrParts[1]) | ||
|| !ctype_digit($cidrParts[1]) | ||
|| '' === $cidrParts[0] | ||
) { | ||
$this->context | ||
->buildViolation($constraint->message) | ||
->setCode(Cidr::INVALID_CIDR_ERROR) | ||
->addViolation(); | ||
|
||
return; | ||
} | ||
|
||
$ipAddress = $cidrParts[0]; | ||
$netmask = (int) $cidrParts[1]; | ||
|
||
$validV4 = Ip::V6 !== $constraint->version | ||
&& filter_var($ipAddress, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4) | ||
&& $netmask <= 32; | ||
|
||
$validV6 = Ip::V4 !== $constraint->version | ||
&& filter_var($ipAddress, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6); | ||
|
||
if (!$validV4 && !$validV6) { | ||
$this->context | ||
->buildViolation($constraint->message) | ||
->setCode(Cidr::INVALID_CIDR_ERROR) | ||
->addViolation(); | ||
|
||
return; | ||
} | ||
|
||
if ($netmask < $constraint->netmaskMin || $netmask > $constraint->netmaskMax) { | ||
$this->context | ||
->buildViolation($constraint->netmaskRangeViolationMessage) | ||
->setParameter('{{ min }}', $constraint->netmaskMin) | ||
->setParameter('{{ max }}', $constraint->netmaskMax) | ||
->setCode(Cidr::OUT_OF_RANGE_ERROR) | ||
->addViolation(); | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
151 changes: 151 additions & 0 deletions
151
src/Symfony/Component/Validator/Tests/Constraints/CidrTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,151 @@ | ||
<?php | ||
|
||
namespace Symfony\Component\Validator\Tests\Constraints; | ||
|
||
use PHPUnit\Framework\TestCase; | ||
use Symfony\Component\Validator\Constraints\Cidr; | ||
use Symfony\Component\Validator\Constraints\Ip; | ||
use Symfony\Component\Validator\Exception\ConstraintDefinitionException; | ||
use Symfony\Component\Validator\Mapping\ClassMetadata; | ||
use Symfony\Component\Validator\Mapping\Loader\AnnotationLoader; | ||
|
||
class CidrTest extends TestCase | ||
{ | ||
public function testForAll() | ||
{ | ||
$cidrConstraint = new Cidr(); | ||
|
||
self::assertEquals(Ip::ALL, $cidrConstraint->version); | ||
self::assertEquals(0, $cidrConstraint->netmaskMin); | ||
self::assertEquals(128, $cidrConstraint->netmaskMax); | ||
} | ||
|
||
public function testForV4() | ||
{ | ||
$cidrConstraint = new Cidr(['version' => Ip::V4]); | ||
|
||
self::assertEquals(Ip::V4, $cidrConstraint->version); | ||
self::assertEquals(0, $cidrConstraint->netmaskMin); | ||
self::assertEquals(32, $cidrConstraint->netmaskMax); | ||
} | ||
|
||
public function testForV6() | ||
{ | ||
$cidrConstraint = new Cidr(['version' => Ip::V6]); | ||
|
||
self::assertEquals(Ip::V6, $cidrConstraint->version); | ||
self::assertEquals(0, $cidrConstraint->netmaskMin); | ||
self::assertEquals(128, $cidrConstraint->netmaskMax); | ||
} | ||
|
||
public function testWithInvalidVersion() | ||
{ | ||
$availableVersions = [Ip::ALL, Ip::V4, Ip::V6]; | ||
|
||
self::expectException(ConstraintDefinitionException::class); | ||
self::expectExceptionMessage(sprintf('The option "version" must be one of "%s".', implode('", "', $availableVersions))); | ||
|
||
new Cidr(['version' => '8']); | ||
} | ||
|
||
/** | ||
* @dataProvider getValidMinMaxValues | ||
*/ | ||
public function testWithValidMinMaxValues(string $ipVersion, int $netmaskMin, int $netmaskMax) | ||
{ | ||
$cidrConstraint = new Cidr([ | ||
'version' => $ipVersion, | ||
'netmaskMin' => $netmaskMin, | ||
'netmaskMax' => $netmaskMax, | ||
]); | ||
|
||
self::assertEquals($ipVersion, $cidrConstraint->version); | ||
self::assertEquals($netmaskMin, $cidrConstraint->netmaskMin); | ||
self::assertEquals($netmaskMax, $cidrConstraint->netmaskMax); | ||
} | ||
|
||
/** | ||
* @dataProvider getInvalidMinMaxValues | ||
*/ | ||
public function testWithInvalidMinMaxValues(string $ipVersion, int $netmaskMin, int $netmaskMax) | ||
{ | ||
$expectedMax = Ip::V4 == $ipVersion ? 32 : 128; | ||
|
||
self::expectException(ConstraintDefinitionException::class); | ||
self::expectExceptionMessage(sprintf('The netmask range must be between 0 and %d.', $expectedMax)); | ||
|
||
new Cidr([ | ||
'version' => $ipVersion, | ||
'netmaskMin' => $netmaskMin, | ||
'netmaskMax' => $netmaskMax, | ||
]); | ||
} | ||
|
||
public function getInvalidMinMaxValues(): array | ||
{ | ||
return [ | ||
[Ip::ALL, -1, 23], | ||
[Ip::ALL, 23, 130], | ||
[Ip::ALL, 2, -4], | ||
[Ip::ALL, -12, -40], | ||
[Ip::V4, 0, 33], | ||
[Ip::V4, 2, -10], | ||
[Ip::V4, -4, 128], | ||
[Ip::V4, -5, -1], | ||
[Ip::V6, 5, 200], | ||
[Ip::V6, -1, 120], | ||
[Ip::V6, 0, -10], | ||
[Ip::V6, -15, -20], | ||
]; | ||
} | ||
|
||
public function getValidMinMaxValues(): array | ||
{ | ||
return [ | ||
[Ip::ALL, 0, 23], | ||
[Ip::ALL, 23, 120], | ||
[Ip::V4, 0, 5], | ||
[Ip::V4, 2, 10], | ||
[Ip::V6, 0, 43], | ||
[Ip::V6, 33, 100], | ||
]; | ||
} | ||
|
||
/** | ||
* @requires PHP 8 | ||
*/ | ||
public function testAttributes() | ||
{ | ||
$metadata = new ClassMetadata(CidrDummy::class); | ||
$loader = new AnnotationLoader(); | ||
self::assertTrue($loader->loadClassMetadata($metadata)); | ||
|
||
[$aConstraint] = $metadata->properties['a']->getConstraints(); | ||
self::assertSame(Ip::ALL, $aConstraint->version); | ||
self::assertSame(0, $aConstraint->netmaskMin); | ||
self::assertSame(128, $aConstraint->netmaskMax); | ||
|
||
[$bConstraint] = $metadata->properties['b']->getConstraints(); | ||
self::assertSame(Ip::V6, $bConstraint->version); | ||
self::assertSame('myMessage', $bConstraint->message); | ||
self::assertSame(10, $bConstraint->netmaskMin); | ||
self::assertSame(126, $bConstraint->netmaskMax); | ||
self::assertSame(['Default', 'CidrDummy'], $bConstraint->groups); | ||
|
||
[$cConstraint] = $metadata->properties['c']->getConstraints(); | ||
self::assertSame(['my_group'], $cConstraint->groups); | ||
self::assertSame('some attached data', $cConstraint->payload); | ||
} | ||
} | ||
|
||
class CidrDummy | ||
{ | ||
#[Cidr] | ||
private $a; | ||
|
||
#[Cidr(version: Ip::V6, message: 'myMessage', netmaskMin: 10, netmaskMax: 126)] | ||
private $b; | ||
|
||
#[Cidr(groups: ['my_group'], payload: 'some attached data')] | ||
private $c; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.