Passed
Pull Request — master (#333)
by Sergei
02:38
created

Ip::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Attribute;
8
use Closure;
9
use RuntimeException;
10
use Yiisoft\NetworkUtilities\IpHelper;
11
use Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait;
12
use Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait;
13
use Yiisoft\Validator\Rule\Trait\WhenTrait;
14
use Yiisoft\Validator\SerializableRuleInterface;
15
use Yiisoft\Validator\SkipOnEmptyInterface;
16
use Yiisoft\Validator\SkipOnErrorInterface;
17
use Yiisoft\Validator\ValidationContext;
18
use Yiisoft\Validator\WhenInterface;
19
20
use function array_key_exists;
21
use function strlen;
22
23
/**
24
 * Checks if the value is a valid IPv4/IPv6 address or subnet.
25
 *
26
 * It also may change the value if normalization of IPv6 expansion is enabled.
27
 */
28
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
29
final class Ip implements SerializableRuleInterface, SkipOnErrorInterface, WhenInterface, SkipOnEmptyInterface
30
{
31
    use SkipOnEmptyTrait;
32
    use SkipOnErrorTrait;
33
    use WhenTrait;
34
35
    /**
36
     * Negation char.
37
     *
38
     * Used to negate {@see $ranges} or {@see $network} or to negate validating value when {@see $allowNegation}
39
     * is used.
40
     */
41
    private const NEGATION_CHAR = '!';
42
    /**
43
     * @see $networks
44
     */
45
    private array $defaultNetworks = [
46
        '*' => ['any'],
47
        'any' => ['0.0.0.0/0', '::/0'],
48
        'private' => ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fd00::/8'],
49
        'multicast' => ['224.0.0.0/4', 'ff00::/8'],
50
        'linklocal' => ['169.254.0.0/16', 'fe80::/10'],
51
        'localhost' => ['127.0.0.0/8', '::1'],
52
        'documentation' => ['192.0.2.0/24', '198.51.100.0/24', '203.0.113.0/24', '2001:db8::/32'],
53
        'system' => ['multicast', 'linklocal', 'localhost', 'documentation'],
54
    ];
55
56 8
    public function __construct(
57
        /**
58
         * @var array Custom network aliases, that can be used in {@see $ranges}.
59
         *
60
         *  - key - alias name
61
         *  - value - array of strings. String can be an IP range, IP address or another alias. String can be
62
         *    negated with {@see NEGATION_CHAR} (independent of {@see $allowNegation} option).
63
         *
64
         * The following aliases are defined by default in {@see $defaultNetworks} and will be merged with custom ones:
65
         *
66
         *  - `*`: `any`
67
         *  - `any`: `0.0.0.0/0, ::/0`
68
         *  - `private`: `10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fd00::/8`
69
         *  - `multicast`: `224.0.0.0/4, ff00::/8`
70
         *  - `linklocal`: `169.254.0.0/16, fe80::/10`
71
         *  - `localhost`: `127.0.0.0/8', ::1`
72
         *  - `documentation`: `192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32`
73
         *  - `system`: `multicast, linklocal, localhost, documentation`
74
         *
75
         * @see $defaultNetworks
76
         */
77
        private array $networks = [],
78
        /**
79
         * @var bool whether the validating value can be an IPv4 address. Defaults to `true`.
80
         */
81
        private bool $allowIpv4 = true,
82
        /**
83
         * @var bool whether the validating value can be an IPv6 address. Defaults to `true`.
84
         */
85
        private bool $allowIpv6 = true,
86
        /**
87
         * @var bool whether the address can be an IP with CIDR subnet, like `192.168.10.0/24`.
88
         * The following values are possible:
89
         *
90
         * - `false` - the address must not have a subnet (default).
91
         * - `true` - specifying a subnet is optional.
92
         */
93
        private bool $allowSubnet = false,
94
        private bool $requireSubnet = false,
95
        /**
96
         * @var bool whether address may have a {@see NEGATION_CHAR} character at the beginning.
97
         * Defaults to `false`.
98
         */
99
        private bool $allowNegation = false,
100
        /**
101
         * @var string user-defined error message is used when validation fails due to the wrong IP address format.
102
         *
103
         * You may use the following placeholders in the message:
104
         *
105
         * - `{attribute}`: the label of the attribute being validated
106
         * - `{value}`: the value of the attribute being validated
107
         */
108
        private string $message = 'Must be a valid IP address.',
109
        /**
110
         * @var string user-defined error message is used when validation fails due to the disabled IPv4 validation.
111
         *
112
         * You may use the following placeholders in the message:
113
         *
114
         * - `{attribute}`: the label of the attribute being validated
115
         * - `{value}`: the value of the attribute being validated
116
         *
117
         * @see $allowIpv4
118
         */
119
        private string $ipv4NotAllowedMessage = 'Must not be an IPv4 address.',
120
        /**
121
         * @var string user-defined error message is used when validation fails due to the disabled IPv6 validation.
122
         *
123
         * You may use the following placeholders in the message:
124
         *
125
         * - `{attribute}`: the label of the attribute being validated
126
         * - `{value}`: the value of the attribute being validated
127
         *
128
         * @see $allowIpv6
129
         */
130
        private string $ipv6NotAllowedMessage = 'Must not be an IPv6 address.',
131
        /**
132
         * @var string user-defined error message is used when validation fails due to the wrong CIDR.
133
         *
134
         * You may use the following placeholders in the message:
135
         *
136
         * - `{attribute}`: the label of the attribute being validated
137
         * - `{value}`: the value of the attribute being validated
138
         *
139
         * @see $allowSubnet
140
         */
141
        private string $wrongCidrMessage = 'Contains wrong subnet mask.',
142
        /**
143
         * @var string user-defined error message is used when validation fails due to subnet {@see $allowSubnet} is
144
         * used, but the CIDR prefix is not set.
145
         *
146
         * You may use the following placeholders in the message:
147
         *
148
         * - `{attribute}`: the label of the attribute being validated
149
         * - `{value}`: the value of the attribute being validated
150
         *
151
         * @see $allowSubnet
152
         */
153
        private string $noSubnetMessage = 'Must be an IP address with specified subnet.',
154
        /**
155
         * @var string user-defined error message is used when validation fails
156
         * due to {@see $allowSubnet} is false, but CIDR prefix is present.
157
         *
158
         * You may use the following placeholders in the message:
159
         *
160
         * - `{attribute}`: the label of the attribute being validated
161
         * - `{value}`: the value of the attribute being validated
162
         *
163
         * @see $allowSubnet
164
         */
165
        private string $hasSubnetMessage = 'Must not be a subnet.',
166
        /**
167
         * @var string user-defined error message is used when validation fails due to IP address
168
         * is not allowed by {@see $ranges} check.
169
         *
170
         * You may use the following placeholders in the message:
171
         *
172
         * - `{attribute}`: the label of the attribute being validated
173
         * - `{value}`: the value of the attribute being validated
174
         *
175
         * @see $ranges
176
         */
177
        private string $notInRangeMessage = 'Is not in the allowed range.',
178
        /**
179
         * @var string[] The IPv4 or IPv6 ranges that are allowed or forbidden.
180
         *
181
         * The following preparation tasks are performed:
182
         *
183
         * - Recursively substitutes aliases (described in {@see $networks}) with their values.
184
         * - Removes duplicates.
185
         *
186
         * When the array is empty, or the option not set, all IP addresses are allowed.
187
         *
188
         * Otherwise, the rules are checked sequentially until the first match is found.
189
         * An IP address is forbidden, when it has not matched any of the rules.
190
         *
191
         * Example:
192
         *
193
         * ```php
194
         * (new Ip(ranges: [
195
         *     '192.168.10.128'
196
         *     '!192.168.10.0/24',
197
         *     'any' // allows any other IP addresses
198
         * ]);
199
         * ```
200
         *
201
         * In this example, access is allowed for all the IPv4 and IPv6 addresses excluding the `192.168.10.0/24`
202
         * subnet. IPv4 address `192.168.10.128` is also allowed, because it is listed before the restriction.
203
         */
204
        private array $ranges = [],
205
206
        /**
207
         * @var bool|callable|null
208
         */
209
        private $skipOnEmpty = null,
210
        private bool $skipOnError = false,
211
        /**
212
         * @var Closure(mixed, ValidationContext):bool|null
213
         */
214
        private ?Closure $when = null,
215
    ) {
216 8
        foreach ($networks as $key => $_values) {
217 1
            if (array_key_exists($key, $this->defaultNetworks)) {
218 1
                throw new RuntimeException("Network alias \"{$key}\" already set as default.");
219
            }
220
        }
221
222 7
        $this->networks = array_merge($this->defaultNetworks, $this->networks);
223
224 7
        if ($requireSubnet) {
225
            $this->allowSubnet = true;
226
        }
227
228 7
        $this->ranges = $this->prepareRanges($ranges);
229
    }
230
231 1
    public function getName(): string
232
    {
233 1
        return 'ip';
234
    }
235
236
    public function getNetworks(): array
237
    {
238
        return $this->networks;
239
    }
240
241 117
    public function isAllowIpv4(): bool
242
    {
243 117
        return $this->allowIpv4;
244
    }
245
246 35
    public function isAllowIpv6(): bool
247
    {
248 35
        return $this->allowIpv6;
249
    }
250
251 34
    public function isAllowSubnet(): bool
252
    {
253 34
        return $this->allowSubnet;
254
    }
255
256 52
    public function isRequireSubnet(): bool
257
    {
258 52
        return $this->requireSubnet;
259
    }
260
261 8
    public function isAllowNegation(): bool
262
    {
263 8
        return $this->allowNegation;
264
    }
265
266 116
    public function getMessage(): string
267
    {
268 116
        return $this->message;
269
    }
270
271 2
    public function getIpv4NotAllowedMessage(): string
272
    {
273 2
        return $this->ipv4NotAllowedMessage;
274
    }
275
276 1
    public function getIpv6NotAllowedMessage(): string
277
    {
278 1
        return $this->ipv6NotAllowedMessage;
279
    }
280
281 2
    public function getWrongCidrMessage(): string
282
    {
283 2
        return $this->wrongCidrMessage;
284
    }
285
286 4
    public function getNoSubnetMessage(): string
287
    {
288 4
        return $this->noSubnetMessage;
289
    }
290
291 4
    public function getHasSubnetMessage(): string
292
    {
293 4
        return $this->hasSubnetMessage;
294
    }
295
296 16
    public function getNotInRangeMessage(): string
297
    {
298 16
        return $this->notInRangeMessage;
299
    }
300
301 4
    public function getRanges(): array
302
    {
303 4
        return $this->ranges;
304
    }
305
306
    /**
307
     * Parses IP address/range for the negation with {@see NEGATION_CHAR}.
308
     *
309
     * @param $string
310
     *
311
     * @return array `[0 => bool, 1 => string]`
312
     *  - boolean: whether the string is negated
313
     *  - string: the string without negation (when the negation were present)
314
     */
315 42
    private function parseNegatedRange($string): array
316
    {
317 42
        $isNegated = str_starts_with($string, self::NEGATION_CHAR);
318 42
        return [$isNegated, $isNegated ? substr($string, strlen(self::NEGATION_CHAR)) : $string];
319
    }
320
321
    /**
322
     * Prepares array to fill in {@see $ranges}.
323
     *
324
     *  - Recursively substitutes aliases, described in {@see $networks} with their values,
325
     *  - Removes duplicates.
326
     *
327
     * @see $networks
328
     */
329 7
    private function prepareRanges(array $ranges): array
330
    {
331 7
        $result = [];
332 7
        foreach ($ranges as $string) {
333 4
            [$isRangeNegated, $range] = $this->parseNegatedRange($string);
334 4
            if (isset($this->networks[$range])) {
335 3
                $replacements = $this->prepareRanges($this->networks[$range]);
336 3
                foreach ($replacements as &$replacement) {
337 3
                    [$isReplacementNegated, $replacement] = $this->parseNegatedRange($replacement);
338 3
                    $result[] = ($isRangeNegated && !$isReplacementNegated ? self::NEGATION_CHAR : '') . $replacement;
339
                }
340
            } else {
341 4
                $result[] = $string;
342
            }
343
        }
344
345 7
        return array_unique($result);
346
    }
347
348
    /**
349
     * The method checks whether the IP address with specified CIDR is allowed according to the {@see $ranges} list.
350
     */
351 69
    public function isAllowed(string $ip): bool
352
    {
353 69
        if (empty($this->ranges)) {
354 31
            return true;
355
        }
356
357 38
        foreach ($this->ranges as $string) {
358 38
            [$isNegated, $range] = $this->parseNegatedRange($string);
359 38
            if (IpHelper::inRange($ip, $range)) {
360 32
                return !$isNegated;
361
            }
362
        }
363
364 6
        return false;
365
    }
366
367
    /**
368
     * Used to get the Regexp pattern for initial IP address parsing.
369
     */
370 112
    public function getIpParsePattern(): string
371
    {
372 112
        return '/^(?<not>' . preg_quote(
373
            self::NEGATION_CHAR,
374
            '/'
375
        ) . ')?(?<ipCidr>(?<ip>(?:' . IpHelper::IPV4_PATTERN . ')|(?:' . IpHelper::IPV6_PATTERN . '))(?:\/(?<cidr>-?\d+))?)$/';
376
    }
377
378 7
    public function getOptions(): array
379
    {
380
        return [
381 7
            'networks' => $this->networks,
382 7
            'allowIpv4' => $this->allowIpv4,
383 7
            'allowIpv6' => $this->allowIpv6,
384 7
            'allowSubnet' => $this->allowSubnet,
385 7
            'requireSubnet' => $this->requireSubnet,
386 7
            'allowNegation' => $this->allowNegation,
387
            'message' => [
388 7
                'message' => $this->message,
389
            ],
390
            'ipv4NotAllowedMessage' => [
391 7
                'message' => $this->ipv4NotAllowedMessage,
392
            ],
393
            'ipv6NotAllowedMessage' => [
394 7
                'message' => $this->ipv6NotAllowedMessage,
395
            ],
396
            'wrongCidrMessage' => [
397 7
                'message' => $this->wrongCidrMessage,
398
            ],
399
            'noSubnetMessage' => [
400 7
                'message' => $this->noSubnetMessage,
401
            ],
402
            'hasSubnetMessage' => [
403 7
                'message' => $this->hasSubnetMessage,
404
            ],
405
            'notInRangeMessage' => [
406 7
                'message' => $this->notInRangeMessage,
407
            ],
408 7
            'ranges' => $this->ranges,
409 7
            'skipOnEmpty' => $this->getSkipOnEmptyOption(),
410 7
            'skipOnError' => $this->skipOnError,
411
        ];
412
    }
413
414 1
    public function getHandlerClassName(): string
415
    {
416 1
        return IpHandler::class;
417
    }
418
}
419