Passed
Pull Request — master (#222)
by Alexander
04:33 queued 02:13
created

Ip   A

Complexity

Total Complexity 39

Size/Duplication

Total Lines 355
Duplicated Lines 0 %

Test Coverage

Coverage 94.74%

Importance

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