Browse Source

Fixes #3506: Added `\yii\validators\IpValidator` to perform validation of IP addresses and subnets

tags/3.0.0-alpha1
Alexander Makarov 9 years ago
parent
commit
5242765257
  1. 1
      framework/CHANGELOG.md
  2. 78
      framework/assets/yii.validation.js
  3. 7
      framework/messages/ru/yii.php
  4. 8
      framework/messages/uk/yii.php
  5. 547
      framework/validators/IpValidator.php
  6. 2
      framework/validators/Validator.php
  7. 378
      tests/framework/validators/IpValidatorTest.php

1
framework/CHANGELOG.md

@ -30,6 +30,7 @@ Yii Framework 2 Change Log
- Bug #9924: Fixed `yii.js` handleAction corrupted parameter values containing quote (") character (silverfire)
- Bug #9984: Fixed wrong captcha color in case Imagick is used (DrDeath72)
- Bug: Fixed generation of canonical URLs for `ViewAction` pages (samdark)
- Enh #3506: Added `\yii\validators\IpValidator` to perform validation of IP addresses and subnets (SilverFire, samdark)
- Enh #7341: Client validation now skips disabled inputs (SamMousa)
- Enh #7581: Added ability to specify range using anonymous function in `RangeValidator` (RomeroMsk)
- Enh #8613: `yii\widgets\FragmentCache` will not store empty content anymore which fixes some problems related to `yii\filters\PageCache` (kidol)

78
framework/assets/yii.validation.js

@ -68,17 +68,17 @@ yii.validation = (function ($) {
pub.addMessage(messages, options.notEqual, value);
}
},
file: function (attribute, messages, options) {
var files = getUploadedFiles(attribute, messages, options);
$.each(files, function (i, file) {
validateFile(file, messages, options);
});
},
image: function (attribute, messages, options, deferred) {
var files = getUploadedFiles(attribute, messages, options);
$.each(files, function (i, file) {
validateFile(file, messages, options);
@ -90,45 +90,45 @@ yii.validation = (function ($) {
var def = $.Deferred(),
fr = new FileReader(),
img = new Image();
img.onload = function () {
if (options.minWidth && this.width < options.minWidth) {
messages.push(options.underWidth.replace(/\{file\}/g, file.name));
}
if (options.maxWidth && this.width > options.maxWidth) {
messages.push(options.overWidth.replace(/\{file\}/g, file.name));
}
if (options.minHeight && this.height < options.minHeight) {
messages.push(options.underHeight.replace(/\{file\}/g, file.name));
}
if (options.maxHeight && this.height > options.maxHeight) {
messages.push(options.overHeight.replace(/\{file\}/g, file.name));
}
def.resolve();
};
img.onerror = function () {
messages.push(options.notImage.replace(/\{file\}/g, file.name));
def.resolve();
};
fr.onload = function () {
img.src = fr.result;
};
// Resolve deferred if there was error while reading data
fr.onerror = function () {
def.resolve();
};
fr.readAsDataURL(file);
deferred.push(def);
});
},
number: function (value, messages, options) {
@ -161,7 +161,7 @@ yii.validation = (function ($) {
var inArray = true;
$.each($.isArray(value) ? value : [value], function(i, v) {
$.each($.isArray(value) ? value : [value], function (i, v) {
if ($.inArray(v, options.range) == -1) {
inArray = false;
return false;
@ -313,6 +313,54 @@ yii.validation = (function ($) {
if (!valid) {
pub.addMessage(messages, options.message, value);
}
},
ip: function (value, messages, options) {
var getIpVersion = function (value) {
return value.indexOf(':') === -1 ? 4 : 6;
};
var negation = null, cidr = null;
if (options.skipOnEmpty && pub.isEmpty(value)) {
return;
}
var matches = new RegExp(options.ipParsePattern).exec(value);
if (matches) {
negation = (matches[1] !== '') ? matches[1] : null;
cidr = (matches[4] !== '') ? matches[4] : null;
value = matches[2];
}
if (options.subnet === true && cidr === null) {
pub.addMessage(messages, options.messages.noSubnet, value);
return;
}
if (options.subnet === false && cidr !== null) {
pub.addMessage(messages, options.messages.hasSubnet, value);
return;
}
if (options.negation === false && negation !== null) {
pub.addMessage(messages, options.messages.wrongIp, value);
return;
}
if (getIpVersion(value) == 6) {
if (!options.ipv6) {
pub.addMessage(messages, options.messages.ipv6NotAllowed, value);
}
if (!(new RegExp(options.ipv6Pattern)).test(value)) {
pub.addMessage(messages, options.messages.wrongIp, value);
}
} else {
if (!options.ipv4) {
pub.addMessage(messages, options.messages.ipv4NotAllowed, value);
}
if (!(new RegExp(options.ipv4Pattern)).test(value)) {
pub.addMessage(messages, options.messages.wrongIp, value);
}
}
}
};
@ -321,7 +369,7 @@ yii.validation = (function ($) {
if (typeof File === "undefined") {
return [];
}
var files = $(attribute.input).get(0).files;
if (!files) {
messages.push(options.message);

7
framework/messages/ru/yii.php

@ -114,4 +114,11 @@ return [
'{delta, plural, =1{a second} other{# seconds}} ago' => '{delta, plural, =1{секунду} one{# секунду} few{# секунды} many{# секунд} other{# секунды}} назад',
'{delta, plural, =1{a year} other{# years}} ago' => '{delta, plural, =1{год} one{# год} few{# года} many{# лет} other{# года}} назад',
'{delta, plural, =1{an hour} other{# hours}} ago' => '{delta, plural, =1{час} one{# час} few{# часа} many{# часов} other{# часа}} назад',
'{attribute} must not be an IPv6 address.' => 'Значение «{attribute}» не должно быть IPv6 адресом.',
'{attribute} must not be an IPv4 address.' => 'Значение «{attribute}» не должно быть IPv4 адресом.',
'{attribute} contains wrong subnet mask.' => 'Значение «{attribute}» содержит неверную маску подсети.',
'{attribute} must be a valid IP address.' => 'Значение «{attribute}» должно быть правильным IP адресом.',
'{attribute} must be an IP address with specified subnet.' => 'Значение «{attribute}» должно быть IP адресом с подсетью.',
'{attribute} must not be a subnet.' => 'Значение «{attribute}» не должно быть подсетью.',
'{attribute} is not in the allowed range.' => 'Значение «{attribute}» не входит в список разрешенных диапазонов адресов.',
];

8
framework/messages/uk/yii.php

@ -111,4 +111,12 @@ return [
'{nFormatted} {n, plural, =1{petabyte} other{petabytes}}' => '{nFormatted} {n, plural, one{петабайт} few{петабайта} many{петабайтів} other{петабайта}}',
'{nFormatted} {n, plural, =1{tebibyte} other{tebibytes}}' => '{nFormatted} {n, plural, one{тебібайт} few{тебібайта} many{тебібайтів} other{тебібайта}}',
'{nFormatted} {n, plural, =1{terabyte} other{terabytes}}' => '{nFormatted} {n, plural, one{терабайт} few{терабайта} many{терабайтів} other{терабайта}}',
'{attribute} must not be an IPv6 address.' => 'Значення «{attribute}» не повинно бути IPv6 адресою.',
'{attribute} must not be an IPv4 address.' => 'Значення «{attribute}» не повинно бути IPv4 адресою.',
'{attribute} contains wrong subnet mask.' => 'Значення «{attribute}» містить неправильну маску підмережі.',
'{attribute} must be a valid IP address.' => 'Значення «{attribute}» повинно бути правильною IP адресою.',
'{attribute} must be an IP address with specified subnet.' => 'Значення «{attribute}» повинно бути IP адресою з підмережею.',
'{attribute} must not be a subnet.' => 'Значення «{attribute}» не повинно бути підмережею.',
'{attribute} is not in the allowed range.' => 'Значення «{attribute}» не входить в список дозволених діапазонів адрес.',
];

547
framework/validators/IpValidator.php

@ -0,0 +1,547 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\validators;
use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\StringHelper;
use yii\web\JsExpression;
/**
* IpValidator validates whether the attribute value is a valid IPv4/IPv6 address or subnet.
* May change attribute's value if normalization is enabled.
*
* @property array $ranges IPv4 or IPv6 ranges that are allowed or denied.
*
* When the array is empty, all IP addresses are allowed.
* When the array is not empty, the rules are checked sequentially until the first match is found.
* IP address is denied, when it did not match any of the rules.
*
* Example:
* ```php
* [
* 'ranges' => [
* '192.168.10.128'
* '!192.168.10.0/24',
* 'any' // allows any other IP addresses
* ]
* ]
* ```
*
* In this example, access is allowed for all the IPv4 and IPv6 addresses excluding `192.168.10.0/24` subnet.
* IPv4 address `192.168.10.128` is also allowed, because is listed above the restriction. *
* @see isAllowed()
*
* @author Dmitry Naumenko <d.naumenko.a@gmail.com>
* @since 2.0.7
*/
class IpValidator extends Validator
{
/**
* The length of IPv6 address in bits
*/
const IPV6_ADDRESS_LENGTH = 128;
/**
* The length of IPv4 address in bits
*/
const IPV4_ADDRESS_LENGTH = 32;
/**
* Negation char. Used to negate [[ranges]] or [[networks]]
* or to negate validating value when [[negation]] is set to `true`
* @see negation
* @see networks
* @see ranges
*/
const NEGATION_CHAR = '!';
/**
* @var array The network aliases, that can be used in [[ranges]].
* - key - alias name
* - value - array of strings
*
* When $networks contains another alias, the value will be substituted recursively.
* The range or alias could be negated with [[NEGATION_CHAR]].
*
* The following aliases are defined by default:
* - `*`: `any`
* - `any`: `0.0.0.0/0, ::/0`
* - `private`: `10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fd00::/8`
* - `multicast`: `224.0.0.0/4, ff00::/8`
* - `linklocal`: `169.254.0.0/16, fe80::/10`
* - `localhost`: `127.0.0.0/8', ::1`
* - `documentation`: `192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32`
* - `system`: `multicast, linklocal, localhost, documentation`
*
*/
public $networks = [
'*' => ['any'],
'any' => ['0.0.0.0/0', '::/0'],
'private' => ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fd00::/8'],
'multicast' => ['224.0.0.0/4', 'ff00::/8'],
'linklocal' => ['169.254.0.0/16', 'fe80::/10'],
'localhost' => ['127.0.0.0/8', '::1'],
'documentation' => ['192.0.2.0/24', '198.51.100.0/24', '203.0.113.0/24', '2001:db8::/32'],
'system' => ['multicast', 'linklocal', 'localhost', 'documentation'],
];
/**
* @var boolean whether support of IPv6 addresses is enabled
*/
public $ipv6 = true;
/**
* @var boolean whether support of IPv4 addresses is enabled
*/
public $ipv4 = true;
/**
* @var boolean whether the address can be a CIDR subnet
* true - the subnet is required
* false - the address can not have the subnet
* null - ths subnet is optional
*/
public $subnet = false;
/**
* @var boolean whether to add the prefix with the smallest length (32 for IPv4 and 128 for IPv6)
* to an address without it.
* Works only when attribute [[subnet]] is not false.
* Example: `10.0.1.5` will normalized to `10.0.1.5/32`, `2008:db0::1` will be normalized to `2008:db0::1/128`
* @see subnet
*/
public $normalize = false;
/**
* @var boolean whether address may have a [[NEGATION_CHAR]] character at the beginning
*/
public $negation = false;
/**
* @var boolean whether to expand an IPv6 address to the full notation format
*/
public $expandIPv6 = false;
/**
* See [[ranges]]
*
* @var array
* @see ranges
*/
public $_ranges = [];
/**
* @var string Regexp-pattern to validate IPv4 address
*/
public $ipv4Pattern = '/^(?:(?:2(?:[0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9])\.){3}(?:(?:2([0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9]))$/';
/**
* @var string Regexp-pattern to validate IPv6 address
*/
public $ipv6Pattern = '/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/';
/**
* @var string user-defined error message is used when validation fails due to the disabled IPv6 validation
*/
public $ipv6NotAllowed = '{attribute} must not be an IPv6 address.';
/**
* @var string user-defined error message is used when validation fails due to the disabled IPv4 validation
*/
public $ipv4NotAllowed = '{attribute} must not be an IPv4 address.';
/**
* @var string user-defined error message is used when validation fails due to the wrong CIDR
*/
public $wrongCidr = '{attribute} contains wrong subnet mask.';
/**
* @var string user-defined error message is used when validation fails due to the wrong IP address format
*/
public $wrongIp = '{attribute} must be a valid IP address.';
/**
* @var string user-defined error message is used when validation fails due to subnet [[subnet]] set to 'only',
* but the CIDR prefix is not set
* @see subnet
*/
public $noSubnet = '{attribute} must be an IP address with specified subnet.';
/**
* @var string user-defined error message is used when validation fails
* due to [[subnet]] is false, but CIDR prefix is present
* @see subnet
*/
public $hasSubnet = '{attribute} must not be a subnet.';
/**
* @var string user-defined error message is used when validation fails due to IP address
* is not on the [[allow]] list, or is on the [[deny]] list
* @see ranges
*/
public $notInRange = '{attribute} is not in the allowed range.';
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if (!$this->ipv4 && !$this->ipv6) {
throw new InvalidConfigException('Both IPv4 and IPv6 checks can not be disabled at the same time');
}
if (!defined('AF_INET6') && $this->ipv6) {
throw new InvalidConfigException('IPv6 validation can not be used. PHP is compiled without IPv6');
}
}
/**
* @return array
*/
public function getRanges()
{
return $this->_ranges;
}
/**
* Passes input ranges to [[prepareRanges()]], then sets the result to [[_ranges]]
* @param array $ranges
*/
public function setRanges($ranges)
{
$this->_ranges = $this->prepareRanges((array) $ranges);
}
/**
* @inheritdoc
*/
protected function validateValue($value)
{
$result = $this->validateSubnet($value);
if (is_array($result)) {
$result[1] = array_merge(['ip' => is_array($value) ? 'array()' : $value], $result[1]);
return $result;
} else {
return null;
}
}
/**
* @inheritdoc
*/
public function validateAttribute($model, $attribute)
{
$value = $model->$attribute;
$result = $this->validateSubnet($value);
if (is_array($result)) {
$result[1] = array_merge(['ip' => is_array($value) ? 'array()' : $value], $result[1]);
$this->addError($model, $attribute, $result[0], $result[1]);
} else {
$model->$attribute = $result;
}
}
/**
* Validates an IPv4/IPv6 address or subnet
*
* @param $ip string
* @return string|array
* string - the validation was successful;
* array - an error occurred during the validation.
* Array[0] contains the text of an error, array[1] contains values for the placeholders in the error message
*/
private function validateSubnet($ip)
{
if (!is_string($ip)) {
return [$this->wrongIp, []];
}
$negation = null;
$cidr = null;
$isCidrDefault = false;
if (preg_match($this->getIpParsePattern(), $ip, $matches)) {
$negation = ($matches[1] !== '') ? $matches[1] : null;
$ip = $matches[2];
$cidr = isset($matches[4]) ? $matches[4] : null;
}
if ($this->subnet === true && $cidr === null) {
return [$this->noSubnet, []];
}
if ($this->subnet === false && $cidr !== null) {
return [$this->hasSubnet, []];
}
if ($this->negation === false && $negation !== null) {
return [$this->wrongIp, []];
}
if ($this->getIpVersion($ip) == 6) {
if ($cidr !== null) {
if ($cidr > static::IPV6_ADDRESS_LENGTH || $cidr < 0) {
return [$this->wrongCidr, []];
}
} else {
$isCidrDefault = true;
$cidr = static::IPV6_ADDRESS_LENGTH;
}
if (!$this->ipv6) {
return [$this->ipv6NotAllowed, []];
}
if (!$this->validateIPv6($ip)) {
return [$this->wrongIp, []];
}
if ($this->expandIPv6) {
$ip = $this->expandIPv6($ip);
}
} else {
if ($cidr !== null) {
if ($cidr > static::IPV4_ADDRESS_LENGTH || $cidr < 0) {
return [$this->wrongCidr, []];
}
} else {
$isCidrDefault = true;
$cidr = static::IPV4_ADDRESS_LENGTH;
}
if (!$this->ipv4) {
return [$this->ipv4NotAllowed, []];
}
if (!$this->validateIPv4($ip)) {
return [$this->wrongIp, []];
}
}
if (!$this->isAllowed($ip, $cidr)) {
return [$this->notInRange, []];
}
$result = $negation . $ip;
if ($this->subnet !== false && (!$isCidrDefault || $isCidrDefault && $this->normalize)) {
$result .= "/$cidr";
}
return $result;
}
/**
* Expands an IPv6 address to it's full notation. For example `2001:db8::1` will be
* expanded to `2001:0db8:0000:0000:0000:0000:0000:0001`
*
* @param string $ip the original IPv6
* @return string the expanded IPv6
*/
private function expandIPv6($ip)
{
$hex = unpack('H*hex', inet_pton($ip));
return substr(preg_replace('/([a-f0-9]{4})/i', '$1:', $hex['hex']), 0, -1);
}
/**
* The method checks whether the IP address with specified CIDR is allowed according to the [[ranges]] list.
*
* @param string $ip
* @param integer $cidr
* @return boolean
* @see ranges
*/
private function isAllowed($ip, $cidr)
{
if (empty($this->ranges)) {
return true;
}
foreach ($this->ranges as $string) {
list($isNegated, $range) = $this->parseNegatedRange($string);
if ($this->inRange($ip, $cidr, $range)) {
return !$isNegated;
}
}
return false;
}
/**
* Parses IP address/range for the negation with [[NEGATION_CHAR]].
*
* @param $string
* @return array `[0 => boolean, 1 => string]`
* - boolean: whether the string is negated
* - string: the string without negation (when the negation were present)
*/
private function parseNegatedRange ($string) {
$isNegated = strpos($string, static::NEGATION_CHAR) === 0;
return [$isNegated, ($isNegated ? substr($string, strlen(static::NEGATION_CHAR)) : $string)];
}
/**
* Prepares array to fill in [[ranges]]:
* - Recursively substitutes aliases, described in [[networks]] with their values
* - Removes duplicates
*
*
* @param $ranges
* @return array
* @see networks
*/
private function prepareRanges($ranges) {
$result = [];
foreach ($ranges as $string) {
list($isRangeNegated, $range) = $this->parseNegatedRange($string);
if (isset($this->networks[$range])) {
$replacements = $this->prepareRanges($this->networks[$range]);
foreach ($replacements as &$replacement) {
list($isReplacementNegated, $replacement) = $this->parseNegatedRange($replacement);
$result[] = ($isRangeNegated && !$isReplacementNegated ? static::NEGATION_CHAR : '') . $replacement;
}
} else {
$result[] = $string;
}
}
return array_unique($result);
}
/**
* Validates IPv4 address
*
* @param string $value
* @return boolean
*/
protected function validateIPv4($value)
{
return preg_match($this->ipv4Pattern, $value) !== 0;
}
/**
* Validates IPv6 address
*
* @param string $value
* @return boolean
*/
protected function validateIPv6($value)
{
return preg_match($this->ipv6Pattern, $value) !== 0;
}
/**
* Gets the IP version
*
* @param string $ip
* @return integer
*/
private function getIpVersion($ip)
{
return strpos($ip, ':') === false ? 4 : 6;
}
/**
* Used to get the Regexp pattern for initial IP address parsing
* @return string
*/
private function getIpParsePattern()
{
return '/^(' . preg_quote(static::NEGATION_CHAR) . '?)(.+?)(\/(\d+))?$/';
}
/**
* Checks whether the IP is in subnet range
*
* @param string $ip an IPv4 or IPv6 address
* @param integer $cidr
* @param string $range subnet in CIDR format e.g. `10.0.0.0/8` or `2001:af::/64`
* @return bool
*/
private function inRange($ip, $cidr, $range)
{
$ipVersion = $this->getIpVersion($ip);
$binIp = $this->ip2bin($ip);
$parts = explode('/', $range);
$net = array_shift($parts);
$range_cidr = array_shift($parts);
$netVersion = $this->getIpVersion($net);
if ($ipVersion !== $netVersion) {
return false;
}
if ($range_cidr === null) {
$range_cidr = $netVersion === 4 ? static::IPV4_ADDRESS_LENGTH : static::IPV6_ADDRESS_LENGTH;
}
$binNet = $this->ip2bin($net);
if (substr($binIp, 0, $range_cidr) === substr($binNet, 0, $range_cidr) && $cidr >= $range_cidr) {
return true;
}
return false;
}
/**
* Converts IP address to bits representation
*
* @param string $ip
* @return string bits as a string
*/
private function ip2bin($ip)
{
if ($this->getIpVersion($ip) === 4) {
return str_pad(base_convert(ip2long($ip), 10, 2), static::IPV4_ADDRESS_LENGTH, '0', STR_PAD_LEFT);
} else {
$unpack = unpack('A16', inet_pton($ip));
$binStr = array_shift($unpack);
$bytes = static::IPV6_ADDRESS_LENGTH / 8; // 128 bit / 8 = 16 bytes
$result = '';
while ($bytes-- > 0) {
$result = sprintf('%08b', isset($binStr[$bytes]) ? ord($binStr[$bytes]) : '0') . $result;
}
return $result;
}
}
/**
* @inheritdoc
*/
public function clientValidateAttribute($model, $attribute, $view)
{
$messages = [
'ipv6NotAllowed' => $this->ipv6NotAllowed,
'ipv4NotAllowed' => $this->ipv4NotAllowed,
'wrongIp' => $this->wrongIp,
'noSubnet' => $this->noSubnet
];
foreach ($messages as &$message) {
$message = Yii::$app->getI18n()->format($message, [
'attribute' => $model->getAttributeLabel($attribute),
], Yii::$app->language);
}
$options = [
'ipv4Pattern' => new JsExpression($this->ipv4Pattern),
'ipv6Pattern' => new JsExpression($this->ipv6Pattern),
'messages' => $messages,
'ipv4' => (boolean)$this->ipv4,
'ipv6' => (boolean)$this->ipv6,
'ipParsePattern' => Html::escapeJsRegularExpression($this->getIpParsePattern()),
'negation' => $this->negation,
'subnet' => $this->subnet
];
ValidationAsset::register($view);
return 'yii.validation.ip(value, messages, ' . Json::htmlEncode($options) . ');';
}
}

2
framework/validators/Validator.php

@ -42,6 +42,7 @@ use yii\base\NotSupportedException;
* - `trim`: [[FilterValidator]]
* - `unique`: [[UniqueValidator]]
* - `url`: [[UrlValidator]]
* - `ip`: [[IpValidator]]
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
@ -81,6 +82,7 @@ class Validator extends Component
],
'unique' => 'yii\validators\UniqueValidator',
'url' => 'yii\validators\UrlValidator',
'ip' => 'yii\validators\IpValidator',
];
/**
* @var array|string attributes to be validated by this validator. For multiple attributes,

378
tests/framework/validators/IpValidatorTest.php

@ -0,0 +1,378 @@
<?php
namespace yiiunit\framework\validators;
use yii\validators\IpValidator;
use yii\validators\ValidationAsset;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\TestCase;
/**
* @group validators
*/
class IpValidatorTest extends TestCase
{
protected function setUp()
{
parent::setUp();
$this->mockApplication();
}
public function testInitException()
{
$this->setExpectedException('yii\base\InvalidConfigException',
'Both IPv4 and IPv6 checks can not be disabled at the same time');
new IpValidator(['ipv4' => false, 'ipv6' => false]);
}
public function provideRangesForSubstitution() {
return [
['10.0.0.1', ['10.0.0.1']],
[['192.168.0.32', 'fa::/32', 'any'], ['192.168.0.32', 'fa::/32', '0.0.0.0/0', '::/0']],
[['10.0.0.1', '!private'], ['10.0.0.1', '!10.0.0.0/8', '!172.16.0.0/12', '!192.168.0.0/16', '!fd00::/8']],
[['private', '!system'], ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fd00::/8', '!224.0.0.0/4', '!ff00::/8', '!169.254.0.0/16', '!fe80::/10', '!127.0.0.0/8', '!::1', '!192.0.2.0/24', '!198.51.100.0/24', '!203.0.113.0/24', '!2001:db8::/32']]
];
}
/**
* @dataProvider provideRangesForSubstitution
*/
public function testRangesSubstitution($range, $expectedRange)
{
$validator = new IpValidator(['ranges' => $range]);
$this->assertEquals($expectedRange, $validator->ranges);
}
public function testValidateOrder()
{
$validator = new IpValidator([
'ranges' => ['10.0.0.1', '!10.0.0.0/8', '!babe::/8', 'any']
]);
$this->assertTrue($validator->validate('10.0.0.1'));
$this->assertFalse($validator->validate('10.0.0.2'));
$this->assertTrue($validator->validate('192.168.5.101'));
$this->assertTrue($validator->validate('cafe::babe'));
$this->assertFalse($validator->validate('babe::cafe'));
}
public function provideBadIps() {
return [['not.an.ip'], [['what an array', '??']], [123456], [true], [false]];
}
/**
* @dataProvider provideBadIps
*/
public function testValidateValueNotAnIP($badIp)
{
$validator = new IpValidator();
$this->assertFalse($validator->validate($badIp));
}
public function testValidateValueIPv4()
{
$validator = new IpValidator();
$this->assertTrue($validator->validate('192.168.10.11'));
$this->assertTrue($validator->validate('192.168.005.001'));
$this->assertFalse($validator->validate('192.168.5.321'));
$this->assertFalse($validator->validate('!192.168.5.32'));
$this->assertFalse($validator->validate('192.168.5.32/11'));
$validator->ipv4 = false;
$this->assertFalse($validator->validate('192.168.10.11'));
$validator->ipv4 = true;
$validator->subnet = null;
$this->assertTrue($validator->validate('192.168.5.32/11'));
$this->assertTrue($validator->validate('192.168.5.32/32'));
$this->assertTrue($validator->validate('0.0.0.0/0'));
$this->assertFalse($validator->validate('192.168.5.32/33'));
$this->assertFalse($validator->validate('192.168.5.32/33'));
$this->assertFalse($validator->validate('192.168.5.32/af'));
$this->assertFalse($validator->validate('192.168.5.32/11/12'));
$validator->subnet = true;
$this->assertTrue($validator->validate('10.0.0.1/24'));
$this->assertTrue($validator->validate('10.0.0.1/0'));
$this->assertFalse($validator->validate('10.0.0.1'));
$validator->negation = true;
$this->assertTrue($validator->validate('!192.168.5.32/32'));
$this->assertFalse($validator->validate('!!192.168.5.32/32'));
}
public function testValidateValueIPv6()
{
if (!defined('AF_INET6')) {
$this->markTestSkipped('The environment does not support IPv6.');
}
$validator = new IpValidator();
$this->assertTrue($validator->validate('2008:fa::1'));
$this->assertTrue($validator->validate('2008:00fa::0001'));
$this->assertFalse($validator->validate('2008:fz::0'));
$this->assertFalse($validator->validate('2008:fa::0::1'));
$this->assertFalse($validator->validate('!2008:fa::0::1'));
$this->assertFalse($validator->validate('2008:fa::0:1/64'));
$validator->ipv4 = false;
$this->assertTrue($validator->validate('2008:fa::1'));
$validator->ipv6 = false;
$this->assertFalse($validator->validate('2008:fa::1'));
$validator->ipv6 = true;
$validator->subnet = null;
$this->assertTrue($validator->validate('2008:fa::0:1/64'));
$this->assertTrue($validator->validate('2008:fa::0:1/128'));
$this->assertTrue($validator->validate('2008:fa::0:1/0'));
$this->assertFalse($validator->validate('!2008:fa::0:1/0'));
$this->assertFalse($validator->validate('2008:fz::0/129'));
$validator->subnet = true;
$this->assertTrue($validator->validate('2008:db0::1/64'));
$this->assertFalse($validator->validate('2008:db0::1'));
$validator->negation = true;
$this->assertTrue($validator->validate('!2008:fa::0:1/64'));
$this->assertFalse($validator->validate('!!2008:fa::0:1/64'));
}
public function testValidateValueIPvBoth()
{
if (!defined('AF_INET6')) {
$this->markTestSkipped('The environment does not support IPv6.');
}
$validator = new IpValidator();
$this->assertTrue($validator->validate('192.168.10.11'));
$this->assertTrue($validator->validate('2008:fa::1'));
$this->assertTrue($validator->validate('2008:00fa::0001'));
$this->assertTrue($validator->validate('192.168.005.001'));
$this->assertFalse($validator->validate('192.168.5.321'));
$this->assertFalse($validator->validate('!192.168.5.32'));
$this->assertFalse($validator->validate('192.168.5.32/11'));
$this->assertFalse($validator->validate('2008:fz::0'));
$this->assertFalse($validator->validate('2008:fa::0::1'));
$this->assertFalse($validator->validate('!2008:fa::0::1'));
$this->assertFalse($validator->validate('2008:fa::0:1/64'));
$validator->ipv4 = false;
$this->assertFalse($validator->validate('192.168.10.11'));
$this->assertTrue($validator->validate('2008:fa::1'));
$validator->ipv6 = false;
$validator->ipv4 = true;
$this->assertTrue($validator->validate('192.168.10.11'));
$this->assertFalse($validator->validate('2008:fa::1'));
$validator->ipv6 = true;
$validator->subnet = null;
$this->assertTrue($validator->validate('192.168.5.32/11'));
$this->assertTrue($validator->validate('192.168.5.32/32'));
$this->assertTrue($validator->validate('0.0.0.0/0'));
$this->assertTrue($validator->validate('2008:fa::0:1/64'));
$this->assertTrue($validator->validate('2008:fa::0:1/128'));
$this->assertTrue($validator->validate('2008:fa::0:1/0'));
$this->assertFalse($validator->validate('!2008:fa::0:1/0'));
$this->assertFalse($validator->validate('192.168.5.32/33'));
$this->assertFalse($validator->validate('2008:fz::0/129'));
$this->assertFalse($validator->validate('192.168.5.32/33'));
$this->assertFalse($validator->validate('192.168.5.32/af'));
$this->assertFalse($validator->validate('192.168.5.32/11/12'));
$validator->subnet = true;
$this->assertTrue($validator->validate('10.0.0.1/24'));
$this->assertTrue($validator->validate('10.0.0.1/0'));
$this->assertTrue($validator->validate('2008:db0::1/64'));
$this->assertFalse($validator->validate('2008:db0::1'));
$this->assertFalse($validator->validate('10.0.0.1'));
$validator->negation = true;
$this->assertTrue($validator->validate('!192.168.5.32/32'));
$this->assertTrue($validator->validate('!2008:fa::0:1/64'));
$this->assertFalse($validator->validate('!!192.168.5.32/32'));
$this->assertFalse($validator->validate('!!2008:fa::0:1/64'));
}
public function testValidateRangeIPv4()
{
$validator = new IpValidator([
'ranges' => ['10.0.1.0/24']
]);
$this->assertTrue($validator->validate('10.0.1.2'));
$this->assertFalse($validator->validate('192.5.1.1'));
$validator->ranges = ['10.0.1.0/24'];
$this->assertTrue($validator->validate('10.0.1.2'));
$this->assertFalse($validator->validate('10.0.3.2'));
$validator->ranges = ['!10.0.1.0/24', '10.0.0.0/8', 'localhost'];
$this->assertFalse($validator->validate('10.0.1.2'));
$this->assertTrue($validator->validate('127.0.0.1'));
$validator->subnet = null;
$validator->ranges = ['10.0.1.0/24', '!10.0.0.0/8', 'localhost'];
$this->assertTrue($validator->validate('10.0.1.2'));
$this->assertTrue($validator->validate('127.0.0.1'));
$this->assertTrue($validator->validate('10.0.1.28/28'));
$this->assertFalse($validator->validate('10.2.2.2'));
$this->assertFalse($validator->validate('10.0.1.1/22'));
}
public function testValidateRangeIPv6()
{
if (!defined('AF_INET6')) {
$this->markTestSkipped('The environment does not support IPv6.');
}
$validator = new IpValidator([
'ranges' => '2001:db0:1:1::/64'
]);
$this->assertTrue($validator->validate('2001:db0:1:1::6'));
$this->assertFalse($validator->validate('2001:db0:1:2::7'));
$validator->ranges = ['2001:db0:1:2::/64'];
$this->assertTrue($validator->validate('2001:db0:1:2::7'));
$validator->ranges = ['!2001:db0::/32', '2001:db0:1:2::/64', ];
$this->assertFalse($validator->validate('2001:db0:1:2::7'));
$validator->subnet = null;
$validator->ranges = array_reverse($validator->ranges);
$this->assertTrue($validator->validate('2001:db0:1:2::7'));
}
public function testValidateRangeIPvBoth()
{
if (!defined('AF_INET6')) {
$this->markTestSkipped('The environment does not support IPv6.');
}
$validator = new IpValidator([
'ranges' => '10.0.1.0/24',
]);
$this->assertTrue($validator->validate('10.0.1.2'));
$this->assertFalse($validator->validate('192.5.1.1'));
$this->assertFalse($validator->validate('2001:db0:1:2::7'));
$validator->ranges = ['10.0.1.0/24', '2001:db0:1:2::/64', '127.0.0.1'];
$this->assertTrue($validator->validate('2001:db0:1:2::7'));
$this->assertTrue($validator->validate('10.0.1.2'));
$this->assertFalse($validator->validate('10.0.3.2'));
$validator->ranges = ['!system', 'any'];
$this->assertFalse($validator->validate('127.0.0.1'));
$this->assertFalse($validator->validate('fe80::face'));
$this->assertTrue($validator->validate('8.8.8.8'));
$validator->subnet = null;
$validator->ranges = ['10.0.1.0/24', '2001:db0:1:2::/64', 'localhost', '!all'];
$this->assertTrue($validator->validate('10.0.1.2'));
$this->assertTrue($validator->validate('2001:db0:1:2::7'));
$this->assertTrue($validator->validate('127.0.0.1'));
$this->assertTrue($validator->validate('10.0.1.28/28'));
$this->assertFalse($validator->validate('10.2.2.2'));
$this->assertFalse($validator->validate('10.0.1.1/22'));
}
public function testValidateAttributeIPv4()
{
$validator = new IpValidator();
$model = new FakedValidationModel();
$validator->subnet = null;
$model->attr_ip = '8.8.8.8';
$validator->validateAttribute($model, 'attr_ip');
$this->assertFalse($model->hasErrors('attr_ip'));
$this->assertEquals('8.8.8.8', $model->attr_ip);
$validator->subnet = false;
$model->attr_ip = '8.8.8.8';
$validator->validateAttribute($model, 'attr_ip');
$this->assertFalse($model->hasErrors('attr_ip'));
$this->assertEquals('8.8.8.8', $model->attr_ip);
$model->attr_ip = '8.8.8.8/24';
$validator->validateAttribute($model, 'attr_ip');
$this->assertTrue($model->hasErrors('attr_ip'));
$this->assertEquals('attr_ip must not be a subnet.', $model->getFirstError('attr_ip'));
$model->clearErrors();
$validator->subnet = null;
$validator->normalize = true;
$model->attr_ip = '8.8.8.8';
$validator->validateAttribute($model, 'attr_ip');
$this->assertFalse($model->hasErrors('attr_ip'));
$this->assertEquals('8.8.8.8/32', $model->attr_ip);
}
public function testValidateAttributeIPv6()
{
if (!defined('AF_INET6')) {
$this->markTestSkipped('The environment does not support IPv6.');
}
$validator = new IpValidator();
$model = new FakedValidationModel();
$validator->subnet = null;
$model->attr_ip = '2001:db0:1:2::1';
$validator->validateAttribute($model, 'attr_ip');
$this->assertFalse($model->hasErrors('attr_ip'));
$this->assertEquals('2001:db0:1:2::1', $model->attr_ip);
$validator->subnet = false;
$model->attr_ip = '2001:db0:1:2::7';
$validator->validateAttribute($model, 'attr_ip');
$this->assertFalse($model->hasErrors('attr_ip'));
$this->assertEquals('2001:db0:1:2::7', $model->attr_ip);
$model->attr_ip = '2001:db0:1:2::7/64';
$validator->validateAttribute($model, 'attr_ip');
$this->assertTrue($model->hasErrors('attr_ip'));
$this->assertEquals('attr_ip must not be a subnet.', $model->getFirstError('attr_ip'));
$model->clearErrors();
$validator->subnet = null;
$validator->normalize = true;
$model->attr_ip = 'fa01::1';
$validator->validateAttribute($model, 'attr_ip');
$this->assertFalse($model->hasErrors('attr_ip'));
$this->assertEquals('fa01::1/128', $model->attr_ip);
$model->attr_ip = 'fa01::1/64';
$validator->validateAttribute($model, 'attr_ip');
$this->assertFalse($model->hasErrors('attr_ip'));
$this->assertEquals('fa01::1/64', $model->attr_ip);
$validator->expandIPv6 = true;
$model->attr_ip = 'fa01::1/64';
$validator->validateAttribute($model, 'attr_ip');
$this->assertFalse($model->hasErrors('attr_ip'));
$this->assertEquals('fa01:0000:0000:0000:0000:0000:0000:0001/64', $model->attr_ip);
$model->attr_ip = 'fa01::2/614';
$validator->validateAttribute($model, 'attr_ip');
$this->assertTrue($model->hasErrors('attr_ip'));
$this->assertEquals('fa01::2/614', $model->attr_ip);
$this->assertEquals('attr_ip contains wrong subnet mask.', $model->getFirstError('attr_ip'));
}
}
Loading…
Cancel
Save