Skip to content

[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
merged 1 commit into from
Oct 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ CHANGELOG
5.4
---

* Add a `Cidr` constraint to validate CIDR notations
* Add a `CssColor` constraint to validate CSS colors
* Add support for `ConstraintViolationList::createFromMessage()`
* Add error's uid to `Count` and `Length` constraints with "exactly" option enabled
Expand Down
80 changes: 80 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Cidr.php
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 <fabien@symfony.com>
*
* 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 <popsorin15@gmail.com>
* @author Calin Bolea <calin.bolea@gmail.com>
*/
#[\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 src/Symfony/Component/Validator/Constraints/CidrValidator.php
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 <fabien@symfony.com>
*
* 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();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,14 @@
<source>This value is not a valid CSS color.</source>
<target>This value is not a valid CSS color.</target>
</trans-unit>
<trans-unit id="102">
<source>This value is not a valid CIDR notation.</source>
<target>This value is not a valid CIDR notation.</target>
</trans-unit>
<trans-unit id="103">
<source>The value of the netmask should be between {{ min }} and {{ max }}.</source>
<target>The value of the netmask should be between {{ min }} and {{ max }}.</target>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,14 @@
<source>This value is not a valid CSS color.</source>
<target>Cette valeur n'est pas une couleur CSS valide.</target>
</trans-unit>
<trans-unit id="102">
<source>This value is not a valid CIDR notation.</source>
<target>Cette valeur n'est pas une notation CIDR valide.</target>
</trans-unit>
<trans-unit id="103">
<source>The value of the netmask should be between {{ min }} and {{ max }}.</source>
<target>La valeur du masque de réseau doit être comprise entre {{ min }} et {{ max }}.</target>
</trans-unit>
</body>
</file>
</xliff>
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,14 @@
<source>This value should be a valid expression.</source>
<target>Această valoare ar trebui să fie o expresie validă.</target>
</trans-unit>
<trans-unit id="102">
<source>This value is not a valid CIDR notation.</source>
<target>Această valoare nu este o notație CIDR validă.</target>
</trans-unit>
<trans-unit id="103">
<source>The value of the netmask should be between {{ min }} and {{ max }}.</source>
<target>Valoarea netmask-ului trebuie sa fie intre {{ min }} si {{ max }}.</target>
</trans-unit>
</body>
</file>
</xliff>
151 changes: 151 additions & 0 deletions src/Symfony/Component/Validator/Tests/Constraints/CidrTest.php
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;
}
Loading