From e60a0213123ea0a2fefb7245a212b0bffbc49868 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Ondr=C3=A1=C4=8Dek?= Date: Tue, 24 Nov 2026 22:40:15 +0100 Subject: [PATCH 1/7] fix: Validate the uri, uri-reference and email formats as defined by RFC 3986 and RFC 5321 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Roman Ondráček --- .../Drafts/Draft06/FormatConstraint.php | 3 +- .../Drafts/Draft07/FormatConstraint.php | 3 +- .../Drafts/Draft2019/FormatConstraint.php | 3 +- .../Constraints/FormatConstraint.php | 3 +- .../Tool/Validator/EmailValidator.php | 54 ++++++++++++++ .../Validator/RelativeReferenceValidator.php | 8 +-- src/JsonSchema/Tool/Validator/Rfc3986.php | 59 +++++++++++++++ .../Tool/Validator/UriValidator.php | 4 ++ tests/Constraints/FormatConstraintTest.php | 3 +- tests/JsonSchemaTestSuiteTest.php | 72 ------------------- tests/Tool/Validator/EmailValidatorTest.php | 51 +++++++++++++ .../RelativeReferenceValidatorTest.php | 10 +++ tests/Tool/Validator/UriValidatorTest.php | 6 ++ 13 files changed, 197 insertions(+), 82 deletions(-) create mode 100644 src/JsonSchema/Tool/Validator/EmailValidator.php create mode 100644 src/JsonSchema/Tool/Validator/Rfc3986.php create mode 100644 tests/Tool/Validator/EmailValidatorTest.php diff --git a/src/JsonSchema/Constraints/Drafts/Draft06/FormatConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft06/FormatConstraint.php index b268d640a..9dcf5555f 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft06/FormatConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft06/FormatConstraint.php @@ -11,6 +11,7 @@ use JsonSchema\Entity\ErrorBagProxy; use JsonSchema\Entity\JsonPointer; use JsonSchema\Rfc3339; +use JsonSchema\Tool\Validator\EmailValidator; use JsonSchema\Tool\Validator\RelativeReferenceValidator; use JsonSchema\Tool\Validator\UriValidator; @@ -108,7 +109,7 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n break; case 'email': - if (filter_var($value, FILTER_VALIDATE_EMAIL, FILTER_NULL_ON_FAILURE | FILTER_FLAG_EMAIL_UNICODE) === null) { + if (!EmailValidator::isValid($value)) { $this->addError(ConstraintError::FORMAT_EMAIL(), $path, ['format' => $schema->format]); } break; diff --git a/src/JsonSchema/Constraints/Drafts/Draft07/FormatConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft07/FormatConstraint.php index 452348531..042a97501 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft07/FormatConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft07/FormatConstraint.php @@ -13,6 +13,7 @@ use JsonSchema\Entity\JsonPointer; use JsonSchema\Exception\RuntimeException; use JsonSchema\Rfc3339; +use JsonSchema\Tool\Validator\EmailValidator; use JsonSchema\Tool\Validator\RelativeReferenceValidator; use JsonSchema\Tool\Validator\UriValidator; @@ -124,7 +125,7 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n break; case 'email': - if (filter_var($value, FILTER_VALIDATE_EMAIL, FILTER_NULL_ON_FAILURE | FILTER_FLAG_EMAIL_UNICODE) === null) { + if (!EmailValidator::isValid($value)) { $this->addError(ConstraintError::FORMAT_EMAIL(), $path, ['format' => $schema->format]); } break; diff --git a/src/JsonSchema/Constraints/Drafts/Draft2019/FormatConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft2019/FormatConstraint.php index 797989b72..5d56e2122 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft2019/FormatConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft2019/FormatConstraint.php @@ -13,6 +13,7 @@ use JsonSchema\Entity\JsonPointer; use JsonSchema\Exception\RuntimeException; use JsonSchema\Rfc3339; +use JsonSchema\Tool\Validator\EmailValidator; use JsonSchema\Tool\Validator\RelativeReferenceValidator; use JsonSchema\Tool\Validator\UriValidator; @@ -133,7 +134,7 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n } break; case 'email': - if (filter_var($value, FILTER_VALIDATE_EMAIL, FILTER_NULL_ON_FAILURE | FILTER_FLAG_EMAIL_UNICODE) === null) { + if (!EmailValidator::isValid($value)) { $this->addError(ConstraintError::FORMAT_EMAIL(), $path, ['format' => $schema->format]); } break; diff --git a/src/JsonSchema/Constraints/FormatConstraint.php b/src/JsonSchema/Constraints/FormatConstraint.php index 20fdb2077..0f1e8cd29 100644 --- a/src/JsonSchema/Constraints/FormatConstraint.php +++ b/src/JsonSchema/Constraints/FormatConstraint.php @@ -14,6 +14,7 @@ use JsonSchema\ConstraintError; use JsonSchema\Entity\JsonPointer; use JsonSchema\Rfc3339; +use JsonSchema\Tool\Validator\EmailValidator; use JsonSchema\Tool\Validator\RelativeReferenceValidator; use JsonSchema\Tool\Validator\UriValidator; @@ -116,7 +117,7 @@ public function check(&$element, $schema = null, ?JsonPointer $path = null, $i = break; case 'email': - if (is_string($element) && null === filter_var($element, FILTER_VALIDATE_EMAIL, FILTER_NULL_ON_FAILURE | FILTER_FLAG_EMAIL_UNICODE)) { + if (is_string($element) && !EmailValidator::isValid($element)) { $this->addError(ConstraintError::FORMAT_EMAIL(), $path, ['format' => $schema->format]); } break; diff --git a/src/JsonSchema/Tool/Validator/EmailValidator.php b/src/JsonSchema/Tool/Validator/EmailValidator.php new file mode 100644 index 000000000..8e66b9fe3 --- /dev/null +++ b/src/JsonSchema/Tool/Validator/EmailValidator.php @@ -0,0 +1,54 @@ +[0-9.]++)|IPv6:(?[0-9A-Fa-f:.]++))\]\z/i', $domain, $matches) !== 1) { + return false; + } + + if (isset($matches['ipv6']) && $matches['ipv6'] !== '') { + return filter_var($matches['ipv6'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; + } + + return filter_var($matches['ipv4'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false; + } +} diff --git a/src/JsonSchema/Tool/Validator/RelativeReferenceValidator.php b/src/JsonSchema/Tool/Validator/RelativeReferenceValidator.php index 2cf71bc49..ce14bb890 100644 --- a/src/JsonSchema/Tool/Validator/RelativeReferenceValidator.php +++ b/src/JsonSchema/Tool/Validator/RelativeReferenceValidator.php @@ -8,6 +8,10 @@ class RelativeReferenceValidator { public static function isValid(string $ref): bool { + if (!Rfc3986::isUriReference($ref)) { + return false; + } + // Relative reference pattern as per RFC 3986, Section 4.1 $pattern = '/^(([^\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/'; @@ -32,10 +36,6 @@ public static function isValid(string $ref): bool return false; // Invalid scheme separator } - if (preg_match('/^\/\/$/', $ref)) { - return false; // Empty authority - } - if (preg_match('/^\/\/\/[^\/]/', $ref)) { return false; // Invalid authority with three slashes } diff --git a/src/JsonSchema/Tool/Validator/Rfc3986.php b/src/JsonSchema/Tool/Validator/Rfc3986.php new file mode 100644 index 000000000..f3f7ddac2 --- /dev/null +++ b/src/JsonSchema/Tool/Validator/Rfc3986.php @@ -0,0 +1,59 @@ +[0-9A-Fa-f:.]++)\]/', $value, $matches) === 1) { + return filter_var($matches['ipLiteral'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; + } + + return true; + } +} diff --git a/src/JsonSchema/Tool/Validator/UriValidator.php b/src/JsonSchema/Tool/Validator/UriValidator.php index 178fce918..1a516395a 100644 --- a/src/JsonSchema/Tool/Validator/UriValidator.php +++ b/src/JsonSchema/Tool/Validator/UriValidator.php @@ -8,6 +8,10 @@ class UriValidator { public static function isValid(string $uri): bool { + if (!Rfc3986::isUri($uri)) { + return false; + } + // RFC 3986: Hierarchical URIs (http, https, ftp, etc.) $hierarchicalPattern = '/^ ([a-z][a-z0-9+\-.]*):\/\/ # Scheme (http, https, ftp, etc.) diff --git a/tests/Constraints/FormatConstraintTest.php b/tests/Constraints/FormatConstraintTest.php index ef71bbbda..1c400ef87 100644 --- a/tests/Constraints/FormatConstraintTest.php +++ b/tests/Constraints/FormatConstraintTest.php @@ -157,6 +157,7 @@ public function getValidFormats(): \Generator yield [4.2, 'uri-reference']; yield ['info@something.edu', 'email']; + yield ['info@somewhere', 'email']; yield [42, 'email']; yield [4.2, 'email']; @@ -232,8 +233,6 @@ public function getInvalidFormats(): \Generator yield ['relativePathReference/', 'uri']; yield ['relative/Path:Reference/', 'uri']; - yield ['info@somewhere', 'email']; - yield ['256.2.2.2', 'ip-address']; yield [':::ff', 'ipv6']; diff --git a/tests/JsonSchemaTestSuiteTest.php b/tests/JsonSchemaTestSuiteTest.php index 204cbd993..75a82c79e 100644 --- a/tests/JsonSchemaTestSuiteTest.php +++ b/tests/JsonSchemaTestSuiteTest.php @@ -145,7 +145,6 @@ private function shouldNotYieldTest(string $name): bool '[draft2019-09/ref.json]: $ref with $recursiveAnchor: extra items disallowed for root is expected to be invalid', '[draft2019-09/unevaluatedProperties.json]: unevaluatedProperties with $recursiveRef: with no unevaluated properties is expected to be valid', '[draft2019-09/unevaluatedItems.json]: unevaluatedItems with $recursiveRef: with no unevaluated items is expected to be valid', - // Optional: Anchor, not yet implemented // Optional: bignum — PHP does not natively support arbitrary-precision integers/floats '[draft3/optional/bignum.json]: integer: a bignum is an integer is expected to be valid', '[draft3/optional/bignum.json]: integer: a negative bignum is an integer is expected to be valid', @@ -188,27 +187,6 @@ private function shouldNotYieldTest(string $name): bool '[draft2019-09/optional/format/ecmascript-regex.json]: Python-specific regular expression syntax is not valid ECMA 262: inline comment group (?#...) is not ECMA 262 is expected to be invalid', '[draft2019-09/optional/format/ecmascript-regex.json]: global inline flag groups are not valid ECMA 262: a single global inline flag (?i) is expected to be invalid', '[draft2019-09/optional/format/ecmascript-regex.json]: global inline flag groups are not valid ECMA 262: multiple global inline flags (?ims) is expected to be invalid', - // Optional: email - '[draft4/optional/format/email.json]: validation of e-mail addresses: a quoted string with a space in the local part is valid is expected to be valid', - '[draft4/optional/format/email.json]: validation of e-mail addresses: a domain that looks like an IPv4 address without brackets is valid is expected to be valid', - '[draft4/optional/format/email.json]: validation of e-mail addresses: a quoted string containing only a space in the local part is valid is expected to be valid', - '[draft4/optional/format/email.json]: validation of e-mail addresses: a non-ASCII character in the local part is not valid is expected to be invalid', - '[draft4/optional/format/email.json]: validation of e-mail addresses: a single-label domain is valid is expected to be valid', - '[draft6/optional/format/email.json]: validation of e-mail addresses: a quoted string with a space in the local part is valid is expected to be valid', - '[draft6/optional/format/email.json]: validation of e-mail addresses: a domain that looks like an IPv4 address without brackets is valid is expected to be valid', - '[draft6/optional/format/email.json]: validation of e-mail addresses: a quoted string containing only a space in the local part is valid is expected to be valid', - '[draft6/optional/format/email.json]: validation of e-mail addresses: a non-ASCII character in the local part is not valid is expected to be invalid', - '[draft6/optional/format/email.json]: validation of e-mail addresses: a single-label domain is valid is expected to be valid', - '[draft7/optional/format/email.json]: validation of e-mail addresses: a quoted string with a space in the local part is valid is expected to be valid', - '[draft7/optional/format/email.json]: validation of e-mail addresses: a domain that looks like an IPv4 address without brackets is valid is expected to be valid', - '[draft7/optional/format/email.json]: validation of e-mail addresses: a quoted string containing only a space in the local part is valid is expected to be valid', - '[draft7/optional/format/email.json]: validation of e-mail addresses: a non-ASCII character in the local part is not valid is expected to be invalid', - '[draft7/optional/format/email.json]: validation of e-mail addresses: a single-label domain is valid is expected to be valid', - '[draft2019-09/optional/format/email.json]: validation of e-mail addresses: a quoted string with a space in the local part is valid is expected to be valid', - '[draft2019-09/optional/format/email.json]: validation of e-mail addresses: a domain that looks like an IPv4 address without brackets is valid is expected to be valid', - '[draft2019-09/optional/format/email.json]: validation of e-mail addresses: a quoted string containing only a space in the local part is valid is expected to be valid', - '[draft2019-09/optional/format/email.json]: validation of e-mail addresses: a non-ASCII character in the local part is not valid is expected to be invalid', - '[draft2019-09/optional/format/email.json]: validation of e-mail addresses: a single-label domain is valid is expected to be valid', // Optional: idn-hostname — IDN hostname format validation is not implemented '[draft7/optional/format/idn-hostname.json]: validation of internationalized host names: Exceptions that are DISALLOWED, left-to-right chars is expected to be invalid', '[draft7/optional/format/idn-hostname.json]: validation of internationalized host names: Exceptions that are DISALLOWED, right-to-left chars is expected to be invalid', @@ -313,61 +291,11 @@ private function shouldNotYieldTest(string $name): bool '[draft2019-09/optional/format/idn-hostname.json]: validation of separators in internationalized host names: label too long if separator ignored (ideographic full stop) is expected to be valid', '[draft2019-09/optional/format/idn-hostname.json]: validation of separators in internationalized host names: label too long if separator ignored (fullwidth full stop) is expected to be valid', '[draft2019-09/optional/format/idn-hostname.json]: validation of separators in internationalized host names: label too long if separator ignored (halfwidth ideographic full stop) is expected to be valid', - '[draft2019-09/optional/format/uri.json]: validation of URIs: invalid userinfo is expected to be invalid', // Optional format time: '[draft7/optional/format/time.json]: validation of time strings: time with unknown local offset is valid is expected to be valid', '[draft7/optional/format/time.json]: validation of time strings: a valid time string with a 15 digit second fraction is expected to be valid', '[draft2019-09/optional/format/time.json]: validation of time strings: time with unknown local offset is valid is expected to be valid', // Input contains -00:00 fails on last comparison. '[draft2019-09/optional/format/time.json]: validation of time strings: a valid time string with a 15 digit second fraction is expected to be valid', // should be handled same as PR#940 - // Optional format uri: Not yet implemented - '[draft4/optional/format/uri.json]: validation of URIs: invalid userinfo is expected to be invalid', - '[draft4/optional/format/uri.json]: validation of URIs: invalid percent-encoding with non-hex digits is expected to be invalid', - '[draft4/optional/format/uri.json]: validation of URIs: incomplete percent-encoding triplet is expected to be invalid', - '[draft4/optional/format/uri.json]: validation of URIs: lone percent sign is invalid is expected to be invalid', - '[draft4/optional/format/uri.json]: validation of URIs: leading zero in an embedded IPv4 address is invalid is expected to be invalid', - '[draft4/optional/format/uri.json]: validation of URIs: a trailing newline after a valid URI is invalid is expected to be invalid', - '[draft6/optional/format/uri.json]: validation of URIs: invalid userinfo is expected to be invalid', - '[draft6/optional/format/uri.json]: validation of URIs: invalid percent-encoding with non-hex digits is expected to be invalid', - '[draft6/optional/format/uri.json]: validation of URIs: incomplete percent-encoding triplet is expected to be invalid', - '[draft6/optional/format/uri.json]: validation of URIs: lone percent sign is invalid is expected to be invalid', - '[draft6/optional/format/uri.json]: validation of URIs: leading zero in an embedded IPv4 address is invalid is expected to be invalid', - '[draft6/optional/format/uri.json]: validation of URIs: a trailing newline after a valid URI is invalid is expected to be invalid', - '[draft7/optional/format/uri.json]: validation of URIs: invalid userinfo is expected to be invalid', - '[draft7/optional/format/uri.json]: validation of URIs: invalid percent-encoding with non-hex digits is expected to be invalid', - '[draft7/optional/format/uri.json]: validation of URIs: incomplete percent-encoding triplet is expected to be invalid', - '[draft7/optional/format/uri.json]: validation of URIs: lone percent sign is invalid is expected to be invalid', - '[draft7/optional/format/uri.json]: validation of URIs: leading zero in an embedded IPv4 address is invalid is expected to be invalid', - '[draft7/optional/format/uri.json]: validation of URIs: a trailing newline after a valid URI is invalid is expected to be invalid', - '[draft2019-09/optional/format/uri.json]: validation of URIs: invalid percent-encoding with non-hex digits is expected to be invalid', - '[draft2019-09/optional/format/uri.json]: validation of URIs: incomplete percent-encoding triplet is expected to be invalid', - '[draft2019-09/optional/format/uri.json]: validation of URIs: lone percent sign is invalid is expected to be invalid', - '[draft2019-09/optional/format/uri.json]: validation of URIs: leading zero in an embedded IPv4 address is invalid is expected to be invalid', - '[draft2019-09/optional/format/uri.json]: validation of URIs: a trailing newline after a valid URI is invalid is expected to be invalid', - // Optional format uri-reference: Not yet implemented - '[draft6/optional/format/uri-reference.json]: validation of URI References: unescaped non US-ASCII characters is expected to be invalid', - '[draft6/optional/format/uri-reference.json]: validation of URI References: a network-path reference with an empty authority is expected to be valid', - '[draft6/optional/format/uri-reference.json]: validation of URI References: a double quote in a path is expected to be invalid', - '[draft6/optional/format/uri-reference.json]: validation of URI References: square brackets outside an authority is expected to be invalid', - '[draft6/optional/format/uri-reference.json]: validation of URI References: a non-numeric port in a network-path reference is expected to be invalid', - '[draft6/optional/format/uri-reference.json]: validation of URI References: more than one at-sign in the authority is expected to be invalid', - '[draft6/optional/format/uri-reference.json]: validation of URI References: a leading zero in the IPv4 part of an IPv6 literal is expected to be invalid', - '[draft6/optional/format/uri-reference.json]: validation of URI References: a colon in the first segment of a relative-path reference is expected to be invalid', - '[draft7/optional/format/uri-reference.json]: validation of URI References: unescaped non US-ASCII characters is expected to be invalid', - '[draft7/optional/format/uri-reference.json]: validation of URI References: a network-path reference with an empty authority is expected to be valid', - '[draft7/optional/format/uri-reference.json]: validation of URI References: a double quote in a path is expected to be invalid', - '[draft7/optional/format/uri-reference.json]: validation of URI References: square brackets outside an authority is expected to be invalid', - '[draft7/optional/format/uri-reference.json]: validation of URI References: a non-numeric port in a network-path reference is expected to be invalid', - '[draft7/optional/format/uri-reference.json]: validation of URI References: more than one at-sign in the authority is expected to be invalid', - '[draft7/optional/format/uri-reference.json]: validation of URI References: a leading zero in the IPv4 part of an IPv6 literal is expected to be invalid', - '[draft7/optional/format/uri-reference.json]: validation of URI References: a colon in the first segment of a relative-path reference is expected to be invalid', - '[draft2019-09/optional/format/uri-reference.json]: validation of URI References: unescaped non US-ASCII characters is expected to be invalid', - '[draft2019-09/optional/format/uri-reference.json]: validation of URI References: a network-path reference with an empty authority is expected to be valid', - '[draft2019-09/optional/format/uri-reference.json]: validation of URI References: a double quote in a path is expected to be invalid', - '[draft2019-09/optional/format/uri-reference.json]: validation of URI References: square brackets outside an authority is expected to be invalid', - '[draft2019-09/optional/format/uri-reference.json]: validation of URI References: a non-numeric port in a network-path reference is expected to be invalid', - '[draft2019-09/optional/format/uri-reference.json]: validation of URI References: more than one at-sign in the authority is expected to be invalid', - '[draft2019-09/optional/format/uri-reference.json]: validation of URI References: a leading zero in the IPv4 part of an IPv6 literal is expected to be invalid', - '[draft2019-09/optional/format/uri-reference.json]: validation of URI References: a colon in the first segment of a relative-path reference is expected to be invalid', // Optional unknown keyword: Not yet implemented '[draft6/optional/unknownKeyword.json]: $id inside an unknown keyword is not a real identifier: type matches second anyOf, which has a real schema in it is expected to be valid', '[draft6/optional/unknownKeyword.json]: $id inside an unknown keyword is not a real identifier: type matches non-schema in third anyOf is expected to be invalid', diff --git a/tests/Tool/Validator/EmailValidatorTest.php b/tests/Tool/Validator/EmailValidatorTest.php new file mode 100644 index 000000000..0cfcd27e2 --- /dev/null +++ b/tests/Tool/Validator/EmailValidatorTest.php @@ -0,0 +1,51 @@ + ['email' => 'joe.bloggs@example.com']; + yield 'Quoted string with a space' => ['email' => '"joe bloggs"@example.com']; + yield 'Quoted string with only a space' => ['email' => '" "@iana.org']; + yield 'Quoted pair' => ['email' => '"\a"@iana.org']; + yield 'Single-label domain' => ['email' => 'test@io']; + yield 'Domain that looks like an IPv4 address' => ['email' => 'test@255.255.255.255']; + yield 'IPv4 address literal' => ['email' => 'joe.bloggs@[127.0.0.1]']; + yield 'IPv6 address literal' => ['email' => 'joe.bloggs@[IPv6:::1]']; + yield 'IPv6 address literal with a lowercase tag' => ['email' => 'a@[ipv6:::1]']; + } + + public function invalidEmailDataProvider(): \Generator + { + yield 'Non-ASCII character in the local part' => ['email' => 'aé@iana.org']; + yield 'Non-ASCII character in the domain' => ['email' => 'a@é.org']; + yield 'Two subsequent dots in the local part' => ['email' => 'te..st@example.com']; + yield 'Unquoted space in the local part' => ['email' => 'joe bloggs@example.com']; + yield 'Trailing new line' => ['email' => "test@iana.org\n"]; + yield 'Domain ending with a dot' => ['email' => 'test@iana.org.']; + yield 'Domain label starting with a hyphen' => ['email' => 'test@-iana.org']; + yield 'Invalid IPv4 address literal' => ['email' => 'joe.bloggs@[127.0.0.300]']; + yield 'Address literal that is not an address' => ['email' => 'test@[RFC-5322-domain-literal]']; + yield 'Local part exceeding 64 octets' => ['email' => str_repeat('a', 65) . '@example.com']; + yield 'Missing local part' => ['email' => '@example.com']; + } +} diff --git a/tests/Tool/Validator/RelativeReferenceValidatorTest.php b/tests/Tool/Validator/RelativeReferenceValidatorTest.php index 0346ba289..f9a3cab40 100644 --- a/tests/Tool/Validator/RelativeReferenceValidatorTest.php +++ b/tests/Tool/Validator/RelativeReferenceValidatorTest.php @@ -34,6 +34,8 @@ public function validRelativeReferenceDataProvider(): \Generator yield 'Query and fragment' => ['ref' => '?query#fragment']; yield 'Percent-encoded triplet' => ['ref' => '/%41']; yield 'Percent-encoded triplet in lower case' => ['ref' => '/%c3%a9']; + yield 'Network-path reference with an empty authority' => ['ref' => '//']; + yield 'Colon in a segment after a dot-segment' => ['ref' => './a:b']; } public function invalidRelativeReferenceDataProvider(): \Generator @@ -45,5 +47,13 @@ public function invalidRelativeReferenceDataProvider(): \Generator yield 'Incomplete percent-encoding triplet' => ['ref' => '/%A']; yield 'Percent-encoding with non-hex digits' => ['ref' => '/%zz']; yield 'Percent sign in a query' => ['ref' => '?100%']; + yield 'Non-ASCII character' => ['ref' => '/foobar®.txt']; + yield 'Double quote in a path' => ['ref' => '/a"b']; + yield 'Square brackets outside an authority' => ['ref' => '/[::1]']; + yield 'Non-numeric port' => ['ref' => '//example.com:abc/p']; + yield 'More than one at-sign in the authority' => ['ref' => '//a@b@example.com/']; + yield 'Leading zero in the IPv4 part of an IPv6 literal' => ['ref' => '//[::ffff:192.168.0.01]/p']; + yield 'Colon in the first segment of a relative-path reference' => ['ref' => '1:b']; + yield 'Trailing new line' => ['ref' => "/foo\n"]; } } diff --git a/tests/Tool/Validator/UriValidatorTest.php b/tests/Tool/Validator/UriValidatorTest.php index 69b7282e4..bcd4d95a0 100644 --- a/tests/Tool/Validator/UriValidatorTest.php +++ b/tests/Tool/Validator/UriValidatorTest.php @@ -50,5 +50,11 @@ public function invalidUriDataProvider(): \Generator yield 'Invalid path characters with "^"' => ['uri' => 'http://example.com/^invalid']; yield 'Only mailto:' => ['uri' => 'mailto:']; yield 'Invalid email used in mailto:' => ['uri' => 'mailto:user@.com']; + yield 'Trailing new line' => ['uri' => "http://foo.bar/\n"]; + yield 'Lone percent sign' => ['uri' => 'http://example.com/%']; + yield 'Incomplete percent-encoding triplet' => ['uri' => 'http://example.com/%A']; + yield 'Percent-encoding with non-hex digits' => ['uri' => 'http://example.com/%6G']; + yield 'Square bracket in the userinfo' => ['uri' => 'https://[@example.org/test.txt']; + yield 'Leading zero in the IPv4 part of an IPv6 literal' => ['uri' => 'http://[::ffff:01.2.3.4]']; } } From fd0c06420cd4e166e5c378b8393816d496e54166 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Ondr=C3=A1=C4=8Dek?= Date: Fri, 4 Dec 2026 11:41:58 +0100 Subject: [PATCH 2/7] refactor: drop relative reference checks covered by the RFC 3986 grammar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Roman Ondráček --- .../Validator/RelativeReferenceValidator.php | 28 ------------------- 1 file changed, 28 deletions(-) diff --git a/src/JsonSchema/Tool/Validator/RelativeReferenceValidator.php b/src/JsonSchema/Tool/Validator/RelativeReferenceValidator.php index ce14bb890..d65edf261 100644 --- a/src/JsonSchema/Tool/Validator/RelativeReferenceValidator.php +++ b/src/JsonSchema/Tool/Validator/RelativeReferenceValidator.php @@ -12,42 +12,14 @@ public static function isValid(string $ref): bool return false; } - // Relative reference pattern as per RFC 3986, Section 4.1 - $pattern = '/^(([^\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/'; - - if (preg_match($pattern, $ref) !== 1) { - return false; - } - - // Additional checks for invalid cases - if (strpos($ref, '\\') !== false) { - return false; // Backslashes are not allowed in URI references - } - if (preg_match('/^(http|https):\/\//', $ref)) { return false; // Absolute URI } - if (preg_match('/^:\/\//', $ref)) { - return false; // Missing scheme in authority - } - - if (preg_match('/^:\//', $ref)) { - return false; // Invalid scheme separator - } - if (preg_match('/^\/\/\/[^\/]/', $ref)) { return false; // Invalid authority with three slashes } - if (preg_match('/\s/', $ref)) { - return false; // Spaces are not allowed in URIs - } - - if (preg_match('/%(?![0-9A-Fa-f]{2})/', $ref)) { - return false; // A percent sign must introduce a two digit hexadecimal triplet - } - return true; } } From b5a2c2af3f4f6cf24fc4d112cf1b32bd6d1624fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Ondr=C3=A1=C4=8Dek?= Date: Fri, 4 Dec 2026 12:06:09 +0100 Subject: [PATCH 3/7] fix: Follow RFC 3986 for uri and uri-reference and RFC 5321 for email address literals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Roman Ondráček --- .../Tool/Validator/EmailValidator.php | 82 ++++++++++++++++++- .../Validator/RelativeReferenceValidator.php | 17 +--- src/JsonSchema/Tool/Validator/Rfc3986.php | 28 +++++-- .../Tool/Validator/UriValidator.php | 73 +---------------- tests/Constraints/FormatConstraintTest.php | 3 +- tests/Tool/Validator/EmailValidatorTest.php | 16 ++++ .../RelativeReferenceValidatorTest.php | 5 +- tests/Tool/Validator/Rfc3986Test.php | 75 +++++++++++++++++ tests/Tool/Validator/UriValidatorTest.php | 21 ++++- 9 files changed, 219 insertions(+), 101 deletions(-) create mode 100644 tests/Tool/Validator/Rfc3986Test.php diff --git a/src/JsonSchema/Tool/Validator/EmailValidator.php b/src/JsonSchema/Tool/Validator/EmailValidator.php index 8e66b9fe3..c37efb840 100644 --- a/src/JsonSchema/Tool/Validator/EmailValidator.php +++ b/src/JsonSchema/Tool/Validator/EmailValidator.php @@ -11,6 +11,11 @@ class EmailValidator { public static function isValid(string $email): bool { + // A path is limited to 256 octets including the angle brackets, RFC 5321, section 4.5.3.1.3 + if (strlen($email) > 254) { + return false; + } + $at = strrpos($email, '@'); if ($at === false) { return false; @@ -36,19 +41,88 @@ private static function isValidDomain(string $domain): bool { $label = '[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?'; - return strlen($domain) <= 255 && preg_match('/^' . $label . '(?:\.' . $label . ')*\z/', $domain) === 1; + return preg_match('/^' . $label . '(?:\.' . $label . ')*\z/', $domain) === 1; } + /** + * Validates an IPv4 or IPv6 address literal of RFC 5321, section 4.1.3. + */ private static function isValidAddressLiteral(string $domain): bool { - if (preg_match('/^\[(?:(?[0-9.]++)|IPv6:(?[0-9A-Fa-f:.]++))\]\z/i', $domain, $matches) !== 1) { + if (preg_match('/^\[(?:(?[0-9.]++)|IPv6:(?[0-9A-Fa-f:.]++))]\z/i', $domain, $matches) !== 1) { return false; } if (isset($matches['ipv6']) && $matches['ipv6'] !== '') { - return filter_var($matches['ipv6'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; + return self::isValidIpv6($matches['ipv6']); + } + + return self::isValidIpv4($matches['ipv4']); + } + + private static function isValidIpv4(string $address): bool + { + // Snum is one to three digits, leading zeros are allowed + if (preg_match('/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\z/', $address, $matches) !== 1) { + return false; + } + + foreach (array_slice($matches, 1) as $snum) { + if ((int) $snum > 255) { + return false; + } + } + + return true; + } + + private static function isValidIpv6(string $address): bool + { + $maxGroups = 8; + + $lastColon = strrpos($address, ':'); + if ($lastColon === false) { + return false; + } + + // IPv6v4-full and IPv6v4-comp end with an IPv4 address that takes the place of two groups + $ipv4 = substr($address, $lastColon + 1); + if (strpos($ipv4, '.') !== false) { + if (!self::isValidIpv4($ipv4)) { + return false; + } + + $address = substr($address, 0, $lastColon + 1); + if (substr($address, -2) !== '::') { + $address = substr($address, 0, -1); + } + $maxGroups = 6; + } + + $parts = explode('::', $address); + if (count($parts) > 2) { + return false; + } + + $groupCounts = array_map([self::class, 'countIpv6Groups'], $parts); + if (in_array(null, $groupCounts, true)) { + return false; + } + + // IPv6-full has all groups, in IPv6-comp the "::" stands for at least two of them + return count($parts) === 1 ? $groupCounts[0] === $maxGroups : array_sum($groupCounts) <= $maxGroups - 2; + } + + private static function countIpv6Groups(string $groups): ?int + { + if ($groups === '') { + return 0; + } + + if (preg_match('/^[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*+\z/', $groups) !== 1) { + return null; } - return filter_var($matches['ipv4'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false; + return substr_count($groups, ':') + 1; } } diff --git a/src/JsonSchema/Tool/Validator/RelativeReferenceValidator.php b/src/JsonSchema/Tool/Validator/RelativeReferenceValidator.php index d65edf261..9d6fdaf9a 100644 --- a/src/JsonSchema/Tool/Validator/RelativeReferenceValidator.php +++ b/src/JsonSchema/Tool/Validator/RelativeReferenceValidator.php @@ -4,22 +4,13 @@ namespace JsonSchema\Tool\Validator; +/** + * Validates a relative reference as defined by RFC 3986, section 4.2. + */ class RelativeReferenceValidator { public static function isValid(string $ref): bool { - if (!Rfc3986::isUriReference($ref)) { - return false; - } - - if (preg_match('/^(http|https):\/\//', $ref)) { - return false; // Absolute URI - } - - if (preg_match('/^\/\/\/[^\/]/', $ref)) { - return false; // Invalid authority with three slashes - } - - return true; + return Rfc3986::isRelativeReference($ref); } } diff --git a/src/JsonSchema/Tool/Validator/Rfc3986.php b/src/JsonSchema/Tool/Validator/Rfc3986.php index f3f7ddac2..9a3cebac6 100644 --- a/src/JsonSchema/Tool/Validator/Rfc3986.php +++ b/src/JsonSchema/Tool/Validator/Rfc3986.php @@ -5,7 +5,7 @@ namespace JsonSchema\Tool\Validator; /** - * Matches the URI and URI-reference grammar of RFC 3986, section 3 and 4.1. + * Matches the URI, relative-ref and URI-reference grammar of RFC 3986, sections 3, 4.1 and 4.2. * * @internal */ @@ -13,15 +13,20 @@ class Rfc3986 { public static function isUri(string $value): bool { - return self::matches($value, false); + return self::matches($value, true, false); + } + + public static function isRelativeReference(string $value): bool + { + return self::matches($value, false, true); } public static function isUriReference(string $value): bool { - return self::matches($value, true); + return self::matches($value, true, true); } - private static function matches(string $value, bool $allowRelative): bool + private static function matches(string $value, bool $allowAbsolute, bool $allowRelative): bool { $unreservedSubDelims = 'A-Za-z0-9\-._~!$&\'()*+,;='; // Matches runs of characters possessively, keeping long values within the PCRE backtracking limits @@ -31,7 +36,7 @@ private static function matches(string $value, bool $allowRelative): bool $scheme = '[A-Za-z][A-Za-z0-9+\-.]*+'; $ipvFuture = '[vV][0-9A-Fa-f]++\.[' . $unreservedSubDelims . ':]++'; - $authority = '(?:' . $chars(':') . '*+@)?(?:\[(?:[0-9A-Fa-f:.]++|' . $ipvFuture . ')\]|' . $chars('') . '*+)(?::[0-9]*+)?'; + $authority = '(?:' . $chars(':') . '*+@)?(?:\[(?:[0-9A-Fa-f:.]++|' . $ipvFuture . ')]|' . $chars('') . '*+)(?::[0-9]*+)?'; $pathAbempty = '(?:\/' . $chars(':@') . '*+)*+'; $pathAbsolute = '\/(?:' . $chars(':@') . '++' . $pathAbempty . ')?'; $pathRootless = $chars(':@') . '++' . $pathAbempty; @@ -41,16 +46,21 @@ private static function matches(string $value, bool $allowRelative): bool $hierPart = '(?:\/\/' . $authority . $pathAbempty . '|' . $pathAbsolute . '|' . $pathRootless . '|)'; $relativePart = '(?:\/\/' . $authority . $pathAbempty . '|' . $pathAbsolute . '|' . $pathNoScheme . '|)'; - $pattern = $allowRelative - ? '(?:' . $scheme . ':' . $hierPart . '|' . $relativePart . ')' - : $scheme . ':' . $hierPart; + $absolute = $scheme . ':' . $hierPart; + if ($allowAbsolute && $allowRelative) { + $pattern = '(?:' . $absolute . '|' . $relativePart . ')'; + } elseif ($allowAbsolute) { + $pattern = $absolute; + } else { + $pattern = $relativePart; + } if (preg_match('/^' . $pattern . $query . $fragment . '\z/', $value) !== 1) { return false; } // The grammar only checks the characters of an IP literal, its address is checked separately - if (preg_match('/^(?:' . $scheme . ':)?\/\/(?:[^\/?#@]*+@)?\[(?[0-9A-Fa-f:.]++)\]/', $value, $matches) === 1) { + if (preg_match('/^(?:' . $scheme . ':)?\/\/(?:[^\/?#@]*+@)?\[(?[0-9A-Fa-f:.]++)]/', $value, $matches) === 1) { return filter_var($matches['ipLiteral'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; } diff --git a/src/JsonSchema/Tool/Validator/UriValidator.php b/src/JsonSchema/Tool/Validator/UriValidator.php index 1a516395a..ba3b51e93 100644 --- a/src/JsonSchema/Tool/Validator/UriValidator.php +++ b/src/JsonSchema/Tool/Validator/UriValidator.php @@ -4,78 +4,13 @@ namespace JsonSchema\Tool\Validator; +/** + * Validates a URI as defined by RFC 3986, section 3. + */ class UriValidator { public static function isValid(string $uri): bool { - if (!Rfc3986::isUri($uri)) { - return false; - } - - // RFC 3986: Hierarchical URIs (http, https, ftp, etc.) - $hierarchicalPattern = '/^ - ([a-z][a-z0-9+\-.]*):\/\/ # Scheme (http, https, ftp, etc.) - (?:([^:@\/?#]+)(?::([^@\/?#]*))?@)? # Optional userinfo (user:pass@) - ([a-z0-9._~-]+|\[[a-f0-9:.]+\]) # Hostname or IPv6 in brackets - (?::(\d{1,5}))? # Optional port - (\/[a-zA-Z0-9._~!$&\'()*+,;=:@\/%-]*)* # Path (valid characters only) - (\?([^#]*))? # Optional query - (\#(.*))? # Optional fragment - $/ix'; - - // RFC 3986: Non-Hierarchical URIs (mailto, data, urn, news) - $nonHierarchicalPattern = '/^ - (mailto|data|urn|news|tel|file): # Only allow known non-hierarchical schemes - (.+) # Must contain at least one character after scheme - $/ix'; - - // Validation for newsgroup name (alphanumeric + dots, no empty segments) - $newsGroupPattern = '/^[a-z0-9]+(\.[a-z0-9]+)*$/i'; - $telPattern = '/^\+?[0-9.\-() ]+$/'; // Allows +, digits, separators - - // RFC 5322-compliant email validation for `mailto:` URIs - $emailPattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/'; - - // First, check if it's a valid hierarchical URI - if (preg_match($hierarchicalPattern, $uri, $matches) === 1) { - // Validate domain name (no double dots like example..com) - if (!empty($matches[4]) && preg_match('/\.\./', $matches[4])) { - return false; - } - - // Validate port (should be between 1 and 65535 if specified) - if (!empty($matches[5]) && ($matches[5] < 1 || $matches[5] > 65535)) { - return false; - } - - // Validate the path (reject illegal characters: < > { } | \ ^ `) - if (!empty($matches[6]) && preg_match('/[<>{}|\\\^`]/', $matches[6])) { - return false; - } - - return true; - } - - // If not hierarchical, check non-hierarchical URIs - if (preg_match($nonHierarchicalPattern, $uri, $matches) === 1) { - $scheme = strtolower($matches[1]); // Extract the scheme - - // Special case: `mailto:` must contain a **valid email address** - if ($scheme === 'mailto') { - return preg_match($emailPattern, $matches[2]) === 1; - } - - if ($scheme === 'news') { - return preg_match($newsGroupPattern, $matches[2]) === 1; - } - - if ($scheme === 'tel') { - return preg_match($telPattern, $matches[2]) === 1; - } - - return true; // Valid non-hierarchical URI - } - - return false; + return Rfc3986::isUri($uri); } } diff --git a/tests/Constraints/FormatConstraintTest.php b/tests/Constraints/FormatConstraintTest.php index 1c400ef87..59cd979f0 100644 --- a/tests/Constraints/FormatConstraintTest.php +++ b/tests/Constraints/FormatConstraintTest.php @@ -147,6 +147,7 @@ public function getValidFormats(): \Generator yield ['555 320 1212', 'phone']; yield ['http://bluebox.org', 'uri']; + yield ['htt:/bluebox.org', 'uri']; yield ['//bluebox.org', 'uri-reference']; yield ['/absolutePathReference/', 'uri-reference']; yield ['./relativePathReference/', 'uri-reference']; @@ -223,7 +224,7 @@ public function getInvalidFormats(): \Generator yield ['1 123 4424', 'phone']; - yield ['htt:/bluebox.org', 'uri']; + yield ['ht!tp://bluebox.org', 'uri']; yield ['.relative:path/reference/', 'uri']; yield ['', 'uri']; yield ['//bluebox.org', 'uri']; diff --git a/tests/Tool/Validator/EmailValidatorTest.php b/tests/Tool/Validator/EmailValidatorTest.php index 0cfcd27e2..f3faf1bfe 100644 --- a/tests/Tool/Validator/EmailValidatorTest.php +++ b/tests/Tool/Validator/EmailValidatorTest.php @@ -32,6 +32,13 @@ public function validEmailDataProvider(): \Generator yield 'IPv4 address literal' => ['email' => 'joe.bloggs@[127.0.0.1]']; yield 'IPv6 address literal' => ['email' => 'joe.bloggs@[IPv6:::1]']; yield 'IPv6 address literal with a lowercase tag' => ['email' => 'a@[ipv6:::1]']; + yield 'IPv4 address literal with leading zeros' => ['email' => 'a@[127.000.000.001]']; + yield 'Full IPv6 address literal' => ['email' => 'a@[IPv6:1:2:3:4:5:6:7:8]']; + yield 'Compressed IPv6 address literal with six groups' => ['email' => 'a@[IPv6:1:2:3::4:5:6]']; + yield 'Full IPv6 address literal ending with an IPv4 address' => ['email' => 'a@[IPv6:1:2:3:4:5:6:1.2.3.4]']; + yield 'Compressed IPv6 address literal ending with an IPv4 address' => ['email' => 'a@[IPv6:::ffff:1.2.3.4]']; + yield 'Empty quoted string' => ['email' => '""@example.com']; + yield 'Address of 254 octets' => ['email' => str_repeat('a', 64) . '@' . str_repeat('b', 63) . '.' . str_repeat('c', 63) . '.' . str_repeat('d', 61)]; } public function invalidEmailDataProvider(): \Generator @@ -47,5 +54,14 @@ public function invalidEmailDataProvider(): \Generator yield 'Address literal that is not an address' => ['email' => 'test@[RFC-5322-domain-literal]']; yield 'Local part exceeding 64 octets' => ['email' => str_repeat('a', 65) . '@example.com']; yield 'Missing local part' => ['email' => '@example.com']; + yield 'Unterminated quoted pair' => ['email' => '"\\"@example.com']; + yield 'Domain label exceeding 63 octets' => ['email' => 'a@' . str_repeat('b', 64) . '.com']; + yield 'Address exceeding 254 octets' => ['email' => str_repeat('a', 64) . '@' . str_repeat('b', 63) . '.' . str_repeat('c', 63) . '.' . str_repeat('d', 62)]; + yield 'IPv6 address literal with two "::"' => ['email' => 'a@[IPv6:1::2::3]']; + yield 'IPv6 address literal with "::" standing for one group' => ['email' => 'a@[IPv6:1:2:3:4:5:6:7::]']; + yield 'Compressed IPv6 address literal with seven groups' => ['email' => 'a@[IPv6:1::3:4:5:6:7:8]']; + yield 'Compressed IPv6 address literal ending with an IPv4 address and five groups' => ['email' => 'a@[IPv6:1:2:3:4:5::1.2.3.4]']; + yield 'IPv6 address literal with a group of five digits' => ['email' => 'a@[IPv6:12345::]']; + yield 'IPv4 address literal with three numbers' => ['email' => 'a@[1.2.3]']; } } diff --git a/tests/Tool/Validator/RelativeReferenceValidatorTest.php b/tests/Tool/Validator/RelativeReferenceValidatorTest.php index f9a3cab40..1de392ff1 100644 --- a/tests/Tool/Validator/RelativeReferenceValidatorTest.php +++ b/tests/Tool/Validator/RelativeReferenceValidatorTest.php @@ -36,12 +36,15 @@ public function validRelativeReferenceDataProvider(): \Generator yield 'Percent-encoded triplet in lower case' => ['ref' => '/%c3%a9']; yield 'Network-path reference with an empty authority' => ['ref' => '//']; yield 'Colon in a segment after a dot-segment' => ['ref' => './a:b']; + yield 'Empty authority followed by a path' => ['ref' => '///three/slashes']; + yield 'Empty string' => ['ref' => '']; } public function invalidRelativeReferenceDataProvider(): \Generator { yield 'Absolute URI' => ['ref' => 'http://example.com']; - yield 'Three slashes' => ['ref' => '///three/slashes']; + yield 'Absolute URI with an upper case scheme' => ['ref' => 'HTTP://example.com']; + yield 'Absolute URI with an unregistered scheme' => ['ref' => 'foo:bar']; yield 'Path with spaces' => ['ref' => '/path with spaces']; yield 'Lone percent sign' => ['ref' => '/%']; yield 'Incomplete percent-encoding triplet' => ['ref' => '/%A']; diff --git a/tests/Tool/Validator/Rfc3986Test.php b/tests/Tool/Validator/Rfc3986Test.php new file mode 100644 index 000000000..49f04ead8 --- /dev/null +++ b/tests/Tool/Validator/Rfc3986Test.php @@ -0,0 +1,75 @@ + ['https://user:pass@example.com:8080/a/b?q=1#f', true, false]; + yield 'Scheme with digits and symbols' => ['a1+b-c.d:x', true, false]; + yield 'Scheme in upper case' => ['HTTP://example.com', true, false]; + yield 'Scheme starting with a digit' => ['1a:x', false, false]; + yield 'Only a scheme' => ['urn:', true, false]; + yield 'Path-rootless with a colon' => ['urn:a:b', true, false]; + yield 'Empty port' => ['http://example.com:/', true, false]; + yield 'Port with many digits' => ['http://example.com:123456/', true, false]; + yield 'Non-numeric port' => ['http://example.com:8a/', false, false]; + yield 'IPv4 address' => ['http://192.168.0.1/', true, false]; + yield 'IPv6 literal' => ['http://[2001:db8::1]/', true, false]; + yield 'IPv6 literal with seven groups and "::"' => ['http://[1:2:3:4:5:6:7::]/', true, false]; + yield 'IPv6 literal ending with an IPv4 address' => ['http://[::ffff:192.168.0.1]/', true, false]; + yield 'IPv6 literal with nine groups' => ['http://[1:2:3:4:5:6:7:8:9]/', false, false]; + yield 'IPv6 literal with two "::"' => ['http://[1::2::3]/', false, false]; + yield 'IPv6 literal with a leading zero in the IPv4 part' => ['http://[::ffff:01.2.3.4]/', false, false]; + yield 'IPv6 literal with a zone identifier' => ['http://[fe80::1%25eth0]/', false, false]; + yield 'IPv4 address in brackets' => ['http://[1.2.3.4]/', false, false]; + yield 'IPvFuture literal' => ['http://[v1.fe:x]/', true, false]; + yield 'IPvFuture literal in upper case' => ['http://[V1F.a]/', true, false]; + yield 'IPvFuture literal without an address' => ['http://[v1.]/', false, false]; + yield 'Text after an IP literal' => ['http://[::1]x/', false, false]; + yield 'Two at-signs in the authority' => ['http://a@b@example.com/', false, false]; + yield 'Query and fragment with slashes and question marks' => ['http://h/?a/b?c#d/e?f', true, false]; + yield 'Second number sign' => ['http://h/#a#b', false, false]; + yield 'Percent-encoded triplet' => ['http://h/%41%c3%a9', true, false]; + yield 'Incomplete percent-encoding triplet' => ['http://h/%4', false, false]; + yield 'Space' => ['http://h/a b', false, false]; + yield 'Non-ASCII character' => ['http://h/é', false, false]; + yield 'Trailing new line' => ["http://h/\n", false, false]; + yield 'Empty string' => ['', false, true]; + yield 'Network-path reference' => ['//example.com/a', false, true]; + yield 'Empty authority' => ['//', false, true]; + yield 'Empty authority followed by a path' => ['///a', false, true]; + yield 'Absolute-path reference' => ['/a/b', false, true]; + yield 'Relative-path reference' => ['a/b:c', false, true]; + yield 'Colon in the first segment' => ['a:b/c', true, false]; + yield 'Colon in the first segment that cannot be a scheme' => ['1:b', false, false]; + yield 'Colon after a dot-segment' => ['./1:b', false, true]; + yield 'Query only' => ['?a', false, true]; + yield 'Fragment only' => ['#a', false, true]; + yield 'Backslash' => ['a\\b', false, false]; + } +} diff --git a/tests/Tool/Validator/UriValidatorTest.php b/tests/Tool/Validator/UriValidatorTest.php index bcd4d95a0..3ccaf7fad 100644 --- a/tests/Tool/Validator/UriValidatorTest.php +++ b/tests/Tool/Validator/UriValidatorTest.php @@ -37,24 +37,37 @@ public function validUriDataProvider(): \Generator yield 'File URI with implicit localhost (empty host)' => ['uri' => 'file:///path/to/file.txt']; yield 'File URI with explicit host' => ['uri' => 'file://some-host/path/to/file.txt']; yield 'File URI without any host' => ['uri' => 'file:/path/to/file.txt']; + yield 'Unregistered scheme' => ['uri' => 'foo:bar']; + yield 'Scheme in upper case' => ['uri' => 'HTTP://example.com']; + yield 'Tag URI' => ['uri' => 'tag:example.com,2020:x']; + yield 'Sub-delimiter in a reg-name' => ['uri' => 'http://a!b.com/']; + yield 'Percent-encoded reg-name' => ['uri' => 'http://%65xample.com/']; + yield 'Empty segment in a reg-name' => ['uri' => 'https://example..com']; + yield 'IPvFuture literal' => ['uri' => 'http://[v1.fe]/']; + yield 'Empty user in the userinfo' => ['uri' => 'http://:p@h/']; + yield 'Empty authority' => ['uri' => 'http://']; + yield 'Empty authority followed by a path' => ['uri' => 'http:///x']; + yield 'Port with more than five digits' => ['uri' => 'https://example.com:65536']; + yield 'Only a scheme' => ['uri' => 'mailto:']; + yield 'Mailto with only a query' => ['uri' => 'mailto:?to=user@example.com']; + yield 'Mailto with several addresses' => ['uri' => 'mailto:a@example.com,b@example.com']; } public function invalidUriDataProvider(): \Generator { yield 'Invalid schema' => ['uri' => 'ht!tp://example.com']; yield 'Missing schema' => ['uri' => '://example.com']; - yield 'Double dot in domain' => ['uri' => 'https://example..com']; - yield 'To high of a port number' => ['uri' => 'https://example.com:65536']; yield 'Invalid path characters with "<>"' => ['uri' => 'http://example.com/<>']; yield 'Invalid path characters with "{}"' => ['uri' => 'http://example.com/{bad}']; yield 'Invalid path characters with "^"' => ['uri' => 'http://example.com/^invalid']; - yield 'Only mailto:' => ['uri' => 'mailto:']; - yield 'Invalid email used in mailto:' => ['uri' => 'mailto:user@.com']; yield 'Trailing new line' => ['uri' => "http://foo.bar/\n"]; yield 'Lone percent sign' => ['uri' => 'http://example.com/%']; yield 'Incomplete percent-encoding triplet' => ['uri' => 'http://example.com/%A']; yield 'Percent-encoding with non-hex digits' => ['uri' => 'http://example.com/%6G']; yield 'Square bracket in the userinfo' => ['uri' => 'https://[@example.org/test.txt']; yield 'Leading zero in the IPv4 part of an IPv6 literal' => ['uri' => 'http://[::ffff:01.2.3.4]']; + yield 'Relative reference' => ['uri' => '/path']; + yield 'Network-path reference' => ['uri' => '//example.com']; + yield 'Empty string' => ['uri' => '']; } } From eef7d78e88a5baf5299e90c29cd80e00996df58e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Ondr=C3=A1=C4=8Dek?= Date: Tue, 24 Nov 2026 14:10:17 +0100 Subject: [PATCH 4/7] feat: Support Draft-04 in strict mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Roman Ondráček --- README.md | 2 +- .../Draft04/AdditionalItemsConstraint.php | 64 +++++ .../AdditionalPropertiesConstraint.php | 78 ++++++ .../Drafts/Draft04/AllOfConstraint.php | 42 +++ .../Drafts/Draft04/AnyOfConstraint.php | 51 ++++ .../Drafts/Draft04/DependenciesConstraint.php | 64 +++++ .../Drafts/Draft04/Draft04Constraint.php | 137 ++++++++++ .../Drafts/Draft04/EnumConstraint.php | 37 +++ .../Constraints/Drafts/Draft04/Factory.php | 41 +++ .../Drafts/Draft04/FormatConstraint.php | 245 ++++++++++++++++++ .../Drafts/Draft04/ItemsConstraint.php | 54 ++++ .../Drafts/Draft04/MaxItemsConstraint.php | 39 +++ .../Drafts/Draft04/MaxLengthConstraint.php | 39 +++ .../Draft04/MaxPropertiesConstraint.php | 39 +++ .../Drafts/Draft04/MaximumConstraint.php | 46 ++++ .../Drafts/Draft04/MinItemsConstraint.php | 39 +++ .../Drafts/Draft04/MinLengthConstraint.php | 39 +++ .../Draft04/MinPropertiesConstraint.php | 39 +++ .../Drafts/Draft04/MinimumConstraint.php | 46 ++++ .../Drafts/Draft04/MultipleOfConstraint.php | 54 ++++ .../Drafts/Draft04/NotConstraint.php | 40 +++ .../Drafts/Draft04/OneOfConstraint.php | 50 ++++ .../Drafts/Draft04/PatternConstraint.php | 43 +++ .../Draft04/PatternPropertiesConstraint.php | 55 ++++ .../Drafts/Draft04/PropertiesConstraint.php | 51 ++++ .../Drafts/Draft04/RefConstraint.php | 43 +++ .../Drafts/Draft04/RequiredConstraint.php | 40 +++ .../Drafts/Draft04/TypeConstraint.php | 50 ++++ .../Drafts/Draft04/UniqueItemsConstraint.php | 48 ++++ src/JsonSchema/Constraints/Factory.php | 1 + .../AdditionalPropertiesConstraintTest.php | 50 ++++ .../Draft04/Draft04ConstraintTest.php | 69 +++++ tests/Constraints/Draft04/EcmaPatternTest.php | 85 ++++++ .../Draft04/EnumConstraintTest.php | 43 +++ tests/Constraints/Draft04/ErrorPathTest.php | 61 +++++ .../Draft04/FormatConstraintTest.php | 68 +++++ .../Draft04/MultipleOfConstraintTest.php | 50 ++++ .../Draft04/PatternConstraintTest.php | 25 ++ .../Constraints/Draft04/RefConstraintTest.php | 51 ++++ tests/Constraints/SchemaValidationTest.php | 2 +- tests/JsonSchemaTestSuiteTest.php | 36 ++- tests/ValidatorTest.php | 1 + 42 files changed, 2150 insertions(+), 7 deletions(-) create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/AdditionalItemsConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/AdditionalPropertiesConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/AllOfConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/AnyOfConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/DependenciesConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/Draft04Constraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/EnumConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/Factory.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/FormatConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/ItemsConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/MaxItemsConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/MaxLengthConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/MaxPropertiesConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/MaximumConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/MinItemsConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/MinLengthConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/MinPropertiesConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/MinimumConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/MultipleOfConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/NotConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/OneOfConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/PatternConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/PatternPropertiesConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/PropertiesConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/RefConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/RequiredConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/TypeConstraint.php create mode 100644 src/JsonSchema/Constraints/Drafts/Draft04/UniqueItemsConstraint.php create mode 100644 tests/Constraints/Draft04/AdditionalPropertiesConstraintTest.php create mode 100644 tests/Constraints/Draft04/Draft04ConstraintTest.php create mode 100644 tests/Constraints/Draft04/EcmaPatternTest.php create mode 100644 tests/Constraints/Draft04/EnumConstraintTest.php create mode 100644 tests/Constraints/Draft04/ErrorPathTest.php create mode 100644 tests/Constraints/Draft04/FormatConstraintTest.php create mode 100644 tests/Constraints/Draft04/MultipleOfConstraintTest.php create mode 100644 tests/Constraints/Draft04/PatternConstraintTest.php create mode 100644 tests/Constraints/Draft04/RefConstraintTest.php diff --git a/README.md b/README.md index 938b77d9f..b263eba1f 100644 --- a/README.md +++ b/README.md @@ -217,7 +217,7 @@ original data. [^2]: `CHECK_MODE_EARLY_COERCE` has no effect unless used in combination with `CHECK_MODE_COERCE_TYPES`. If enabled, the validator will use (and coerce) the first compatible type it encounters, even if the schema defines another type that matches directly and does not require coercion. -[^3]: `CHECK_MODE_STRICT` only can be used for Draft-6, Draft 7 or Draft 2019-09 at this point. +[^3]: `CHECK_MODE_STRICT` only can be used for Draft-4, Draft-6, Draft 7 or Draft 2019-09 at this point. ## Running the tests diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/AdditionalItemsConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/AdditionalItemsConstraint.php new file mode 100644 index 000000000..ace53a661 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/AdditionalItemsConstraint.php @@ -0,0 +1,64 @@ +factory = $factory ?: new Factory(); + $this->initialiseErrorBag($this->factory); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'additionalItems')) { + return; + } + + if ($schema->additionalItems === true) { + return; + } + if ($schema->additionalItems === false && !property_exists($schema, 'items')) { + return; + } + + if (!is_array($value)) { + return; + } + if (!property_exists($schema, 'items')) { + return; + } + if (property_exists($schema, 'items') && is_object($schema->items)) { + return; + } + + $additionalItems = array_diff_key($value, property_exists($schema, 'items') ? $schema->items : []); + $basePath = $path ?? new JsonPointer(''); + + foreach ($additionalItems as $propertyName => $propertyValue) { + $incrementedPath = $basePath->withPropertyPaths(array_merge($basePath->getPropertyPaths(), [$propertyName])); + + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($propertyValue, $schema->additionalItems, $incrementedPath, $i); + + if ($schemaConstraint->isValid()) { + continue; + } + + $this->addError(ConstraintError::ADDITIONAL_ITEMS(), $incrementedPath, ['item' => $i, 'property' => $propertyName, 'additionalItems' => $schema->additionalItems]); + } + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/AdditionalPropertiesConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/AdditionalPropertiesConstraint.php new file mode 100644 index 000000000..b095eca59 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/AdditionalPropertiesConstraint.php @@ -0,0 +1,78 @@ +factory = $factory ?: new Factory(); + $this->initialiseErrorBag($this->factory); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'additionalProperties')) { + return; + } + + if ($schema->additionalProperties === true) { + return; + } + + if (!is_object($value)) { + return; + } + + $additionalProperties = get_object_vars($value); + + if (isset($schema->properties)) { + $additionalProperties = array_diff_key($additionalProperties, (array) $schema->properties); + } + + if (isset($schema->patternProperties)) { + $patterns = array_keys(get_object_vars($schema->patternProperties)); + + foreach ($additionalProperties as $key => $_) { + foreach ($patterns as $pattern) { + if (preg_match(EcmaPatternConverter::toPcre($pattern), (string) $key)) { + unset($additionalProperties[$key]); + break; + } + } + } + } + + if (is_object($schema->additionalProperties)) { + foreach ($additionalProperties as $key => $additionalPropertiesValue) { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($additionalPropertiesValue, $schema->additionalProperties, ($path ?? new JsonPointer(''))->withAppendedPath($key), $i); + + // The property is permitted by the schema, so it is never an "additional property" + // error; what it failed is the sub-schema, and those errors carry the reason. + if (!$schemaConstraint->isValid()) { + $this->addErrors($schemaConstraint->getErrors()); + } + + unset($additionalProperties[$key]); + } + } + + foreach ($additionalProperties as $key => $additionalPropertiesValue) { + $this->addError(ConstraintError::ADDITIONAL_PROPERTIES(), ($path ?? new JsonPointer(''))->withAppendedPath($key), ['found' => $key]); + } + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/AllOfConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/AllOfConstraint.php new file mode 100644 index 000000000..e6b7cbf01 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/AllOfConstraint.php @@ -0,0 +1,42 @@ +factory = $factory ?: new Factory(); + $this->initialiseErrorBag($this->factory); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'allOf')) { + return; + } + + foreach ($schema->allOf as $allOfSchema) { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $allOfSchema, $path, $i); + + if ($schemaConstraint->isValid()) { + continue; + } + $this->addError(ConstraintError::ALL_OF(), $path); + $this->addErrors($schemaConstraint->getErrors()); + } + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/AnyOfConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/AnyOfConstraint.php new file mode 100644 index 000000000..1d0bb57f9 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/AnyOfConstraint.php @@ -0,0 +1,51 @@ +factory = $factory ?: new Factory(); + $this->initialiseErrorBag($this->factory); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'anyOf')) { + return; + } + + foreach ($schema->anyOf as $anyOfSchema) { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + + try { + $schemaConstraint->check($value, $anyOfSchema, $path, $i); + + if ($schemaConstraint->isValid()) { + $this->errorBag()->reset(); + + return; + } + + $this->addErrors($schemaConstraint->getErrors()); + } catch (ValidationException $e) { + } + } + + $this->addError(ConstraintError::ANY_OF(), $path); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/DependenciesConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/DependenciesConstraint.php new file mode 100644 index 000000000..62358329f --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/DependenciesConstraint.php @@ -0,0 +1,64 @@ +factory = $factory ?: new Factory(); + $this->initialiseErrorBag($this->factory); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'dependencies')) { + return; + } + + if (!is_object($value)) { + return; + } + + foreach ($schema->dependencies as $dependant => $dependencies) { + if (!property_exists($value, $dependant)) { + continue; + } + if ($dependencies === true) { + continue; + } + if ($dependencies === false) { + $this->addError(ConstraintError::FALSE(), $path, ['dependant' => $dependant]); + continue; + } + + if (is_array($dependencies)) { + foreach ($dependencies as $dependency) { + if (property_exists($value, $dependant) && !property_exists($value, $dependency)) { + $this->addError(ConstraintError::DEPENDENCIES(), $path, ['dependant' => $dependant, 'dependency' => $dependency]); + } + } + } + + if (is_object($dependencies)) { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $dependencies, $path, $i); + if (!$schemaConstraint->isValid()) { + $this->addErrors($schemaConstraint->getErrors()); + } + } + } + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/Draft04Constraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/Draft04Constraint.php new file mode 100644 index 000000000..ddd01b56b --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/Draft04Constraint.php @@ -0,0 +1,137 @@ +getSchemaStorage() : new SchemaStorage(), + $factory ? $factory->getUriRetriever() : new UriRetriever(), + $factory ? $factory->getConfig() : Constraint::CHECK_MODE_NORMAL + )); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (is_bool($schema)) { + if ($schema === false) { + $this->addError(ConstraintError::FALSE(), $path, []); + } + + return; + } + + if ($this->factory->getConfig(Constraint::CHECK_MODE_VALIDATE_SCHEMA)) { + // validate the schema only once, not each of its subschemas + $this->factory->removeConfig(Constraint::CHECK_MODE_VALIDATE_SCHEMA); + try { + $this->validateSchema($schema, $path); + $this->check($value, $schema, $path, $i); + } finally { + $this->factory->addConfig(Constraint::CHECK_MODE_VALIDATE_SCHEMA); + } + + return; + } + + // Apply defaults + $this->checkForKeyword('ref', $value, $schema, $path, $i); + if (property_exists($schema, '$ref')) { + // All other keywords in a schema containing $ref are ignored + return; + } + + $this->checkForKeyword('required', $value, $schema, $path, $i); + $this->checkForKeyword('properties', $value, $schema, $path, $i); + $this->checkForKeyword('patternProperties', $value, $schema, $path, $i); + $this->checkForKeyword('type', $value, $schema, $path, $i); + $this->checkForKeyword('not', $value, $schema, $path, $i); + $this->checkForKeyword('dependencies', $value, $schema, $path, $i); + $this->checkForKeyword('allOf', $value, $schema, $path, $i); + $this->checkForKeyword('anyOf', $value, $schema, $path, $i); + $this->checkForKeyword('oneOf', $value, $schema, $path, $i); + + $this->checkForKeyword('additionalProperties', $value, $schema, $path, $i); + $this->checkForKeyword('items', $value, $schema, $path, $i); + $this->checkForKeyword('additionalItems', $value, $schema, $path, $i); + $this->checkForKeyword('uniqueItems', $value, $schema, $path, $i); + $this->checkForKeyword('minItems', $value, $schema, $path, $i); + $this->checkForKeyword('minProperties', $value, $schema, $path, $i); + $this->checkForKeyword('maxProperties', $value, $schema, $path, $i); + $this->checkForKeyword('minimum', $value, $schema, $path, $i); + $this->checkForKeyword('maximum', $value, $schema, $path, $i); + $this->checkForKeyword('minLength', $value, $schema, $path, $i); + $this->checkForKeyword('maxItems', $value, $schema, $path, $i); + $this->checkForKeyword('maxLength', $value, $schema, $path, $i); + $this->checkForKeyword('enum', $value, $schema, $path, $i); + $this->checkForKeyword('multipleOf', $value, $schema, $path, $i); + $this->checkForKeyword('format', $value, $schema, $path, $i); + $this->checkForKeyword('pattern', $value, $schema, $path, $i); + } + + /** + * Validates the schema against the meta-schema of this draft + * + * @param mixed $schema + */ + private function validateSchema($schema, ?JsonPointer $path): void + { + $initialConfig = $this->factory->getConfig(); + // the meta-schema must not modify the schema + $this->factory->removeConfig(Constraint::CHECK_MODE_APPLY_DEFAULTS); + $this->factory->addConfig(Constraint::CHECK_MODE_TYPE_CAST); + $validator = new self($this->factory); + $this->factory->setConfig($initialConfig); + + $metaSchema = $this->factory->getSchemaStorage()->getSchema(DraftIdentifiers::DRAFT_4); + try { + $validator->check($schema, $metaSchema); + } catch (\Exception $e) { + if ($this->factory->getConfig(Constraint::CHECK_MODE_EXCEPTIONS)) { + throw new InvalidSchemaException('Schema did not pass validation', 0, $e); + } + } + + $errors = $validator->getErrors(); + if ($errors === []) { + return; + } + + foreach ($errors as &$error) { + $error['context'] = Validator::ERROR_SCHEMA_VALIDATION; + } + unset($error); + $this->addErrors($errors); + + $initialContext = $this->factory->getErrorContext(); + $this->factory->setErrorContext(Validator::ERROR_SCHEMA_VALIDATION); + $this->addError(ConstraintError::INVALID_SCHEMA(), $path); + $this->factory->setErrorContext($initialContext); + } + + /** + * @param mixed $value + * @param mixed $schema + * @param mixed $i + */ + protected function checkForKeyword(string $keyword, $value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + $validator = $this->factory->createInstanceFor($keyword); + $validator->check($value, $schema, $path, $i); + + $this->addErrors($validator->getErrors()); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/EnumConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/EnumConstraint.php new file mode 100644 index 000000000..8155d2b2e --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/EnumConstraint.php @@ -0,0 +1,37 @@ +initialiseErrorBag($factory ?: new Factory()); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'enum')) { + return; + } + + foreach ($schema->enum as $enumCase) { + if (DeepComparer::isEqual($value, $enumCase)) { + return; + } + } + + $this->addError(ConstraintError::ENUM(), $path, ['enum' => $schema->enum]); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/Factory.php b/src/JsonSchema/Constraints/Drafts/Draft04/Factory.php new file mode 100644 index 000000000..cda38f970 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/Factory.php @@ -0,0 +1,41 @@ + + */ + protected $constraintMap = [ + 'schema' => Draft04Constraint::class, + 'additionalProperties' => AdditionalPropertiesConstraint::class, + 'additionalItems' => AdditionalItemsConstraint::class, + 'dependencies' => DependenciesConstraint::class, + 'type' => TypeConstraint::class, + 'enum' => EnumConstraint::class, + 'uniqueItems' => UniqueItemsConstraint::class, + 'minItems' => MinItemsConstraint::class, + 'minProperties' => MinPropertiesConstraint::class, + 'maxProperties' => MaxPropertiesConstraint::class, + 'minimum' => MinimumConstraint::class, + 'maximum' => MaximumConstraint::class, + 'minLength' => MinLengthConstraint::class, + 'maxLength' => MaxLengthConstraint::class, + 'maxItems' => MaxItemsConstraint::class, + 'multipleOf' => MultipleOfConstraint::class, + 'required' => RequiredConstraint::class, + 'format' => FormatConstraint::class, + 'anyOf' => AnyOfConstraint::class, + 'allOf' => AllOfConstraint::class, + 'oneOf' => OneOfConstraint::class, + 'not' => NotConstraint::class, + 'patternProperties' => PatternPropertiesConstraint::class, + 'pattern' => PatternConstraint::class, + 'properties' => PropertiesConstraint::class, + 'items' => ItemsConstraint::class, + 'ref' => RefConstraint::class, + ]; +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/FormatConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/FormatConstraint.php new file mode 100644 index 000000000..dbe06da1a --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/FormatConstraint.php @@ -0,0 +1,245 @@ +factory = $factory ?: new Factory(); + $this->initialiseErrorBag($this->factory); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'format') || $this->factory->getConfig(Constraint::CHECK_MODE_DISABLE_FORMAT)) { + return; + } + + if (!is_string($value)) { + return; + } + + switch ($schema->format) { + case 'date': + if (!$this->validateDateTime($value, 'Y-m-d')) { + $this->addError(ConstraintError::FORMAT_DATE(), $path, ['date' => $value, 'format' => $schema->format]); + } + break; + case 'time': + if (!$this->validateDateTime($value, 'H:i:s')) { + $this->addError(ConstraintError::FORMAT_TIME(), $path, ['time' => $value, 'format' => $schema->format]); + } + break; + case 'date-time': + if (!$this->validateRfc3339DateTime($value)) { + $this->addError(ConstraintError::FORMAT_DATE_TIME(), $path, ['dateTime' => $value, 'format' => $schema->format]); + } + break; + case 'utc-millisec': + if (!$this->validateDateTime($value, 'U')) { + $this->addError(ConstraintError::FORMAT_DATE_UTC(), $path, ['value' => $value, 'format' => $schema->format]); + } + break; + case 'regex': + if (!$this->validateRegex($value)) { + $this->addError(ConstraintError::FORMAT_REGEX(), $path, ['value' => $value, 'format' => $schema->format]); + } + break; + case 'ip-address': + case 'ipv4': + if (filter_var($value, FILTER_VALIDATE_IP, FILTER_NULL_ON_FAILURE | FILTER_FLAG_IPV4) === null) { + $this->addError(ConstraintError::FORMAT_IP(), $path, ['format' => $schema->format]); + } + break; + case 'ipv6': + if (filter_var($value, FILTER_VALIDATE_IP, FILTER_NULL_ON_FAILURE | FILTER_FLAG_IPV6) === null) { + $this->addError(ConstraintError::FORMAT_IP(), $path, ['format' => $schema->format]); + } + break; + case 'color': + if (!$this->validateColor($value)) { + $this->addError(ConstraintError::FORMAT_COLOR(), $path, ['format' => $schema->format]); + } + break; + case 'style': + if (!$this->validateStyle($value)) { + $this->addError(ConstraintError::FORMAT_STYLE(), $path, ['format' => $schema->format]); + } + break; + case 'phone': + if (!$this->validatePhone($value)) { + $this->addError(ConstraintError::FORMAT_PHONE(), $path, ['format' => $schema->format]); + } + break; + case 'uri': + if (!UriValidator::isValid($value)) { + $this->addError(ConstraintError::FORMAT_URL(), $path, ['format' => $schema->format]); + } + break; + + case 'uriref': + case 'uri-reference': + if (!(UriValidator::isValid($value) || RelativeReferenceValidator::isValid($value))) { + $this->addError(ConstraintError::FORMAT_URL(), $path, ['format' => $schema->format]); + } + break; + case 'uri-template': + if (!$this->validateUriTemplate($value)) { + $this->addError(ConstraintError::FORMAT_URI_TEMPLATE(), $path, ['format' => $schema->format]); + } + break; + + case 'email': + if (filter_var($value, FILTER_VALIDATE_EMAIL, FILTER_NULL_ON_FAILURE | FILTER_FLAG_EMAIL_UNICODE) === null) { + $this->addError(ConstraintError::FORMAT_EMAIL(), $path, ['format' => $schema->format]); + } + break; + case 'host-name': + case 'hostname': + if (!$this->validateHostname($value)) { + $this->addError(ConstraintError::FORMAT_HOSTNAME(), $path, ['format' => $schema->format]); + } + break; + case 'json-pointer': + if (!$this->validateJsonPointer($value)) { + $this->addError(ConstraintError::FORMAT_JSON_POINTER(), $path, ['format' => $schema->format]); + } + break; + default: + break; + } + } + + private function validateDateTime(string $datetime, string $format): bool + { + try { + $dt = \DateTime::createFromFormat($format, $datetime); + } catch (\Throwable $e) { + return false; + } + + if (!$dt) { + return false; + } + + return $datetime === $dt->format($format); + } + + private function validateRegex(string $regex): bool + { + return @preg_match(self::jsonPatternToPhpRegex($regex), '') !== false; + } + + /** + * Transform a JSON pattern into a PCRE regex + */ + private static function jsonPatternToPhpRegex(string $pattern): string + { + return '~' . str_replace('~', '\\~', $pattern) . '~u'; + } + + private function validateColor(string $color): bool + { + if (in_array(strtolower($color), ['aqua', 'black', 'blue', 'fuchsia', + 'gray', 'green', 'lime', 'maroon', 'navy', 'olive', 'orange', 'purple', + 'red', 'silver', 'teal', 'white', 'yellow'])) { + return true; + } + + return preg_match('/^#([a-f0-9]{3}|[a-f0-9]{6})$/i', $color) === 1; + } + + private function validateStyle(string $style): bool + { + $properties = explode(';', rtrim($style, ';')); + $invalidEntries = preg_grep('/^\s*[-a-z]+\s*:\s*.+$/i', $properties, PREG_GREP_INVERT); + + return empty($invalidEntries); + } + + private function validatePhone(string $phone): bool + { + return preg_match('/^\+?(\(\d{3}\)|\d{3}) \d{3} \d{4}$/', $phone) === 1; + } + + private function validateHostname(string $host): bool + { + $hostnameRegex = '/^(?!-)(?!.*?[^A-Za-z0-9\-\.])(?:(?!-)[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?\.)*(?!-)[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?$/'; + + return preg_match($hostnameRegex, $host) === 1; + } + + private function validateJsonPointer(string $value): bool + { + // Must be empty or start with a forward slash + if ($value !== '' && $value[0] !== '/') { + return false; + } + + // Split into reference tokens and check for invalid escape sequences + $tokens = explode('/', $value); + array_shift($tokens); // remove leading empty part due to leading slash + + foreach ($tokens as $token) { + // "~" must only be followed by "0" or "1" + if (preg_match('/~(?![01])/', $token)) { + return false; + } + } + + return true; + } + + private function validateRfc3339DateTime(string $value): bool + { + $dateTime = Rfc3339::createFromString($value); + if (is_null($dateTime)) { + return false; + } + + // Compare value and date result to be equal + return true; + } + + /** + * Validates a URI template according to the ABNF of RFC 6570 section 2. + */ + private function validateUriTemplate(string $value): bool + { + $pctEncoded = '%[0-9A-Fa-f]{2}'; + // Any Unicode character except CTL, SP, '"', '%', '<', '>', '\', '^', '`', '{', '|' and '}' (ucschar / iprivate). + // BMP and supplementary ranges are kept in separate classes, as PCRE2 10.46 fails to match some BMP code + // points when a single class holds too many ranges. + $literal = '(?:[\x21\x23\x24\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E\x{A0}-\x{D7FF}\x{E000}-\x{FDCF}\x{FDF0}-\x{FFEF}]' + . '|[\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}' + . '\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}' + . '\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}\x{F0000}-\x{FFFFD}' + . '\x{100000}-\x{10FFFD}])'; + $varchar = '(?:[A-Za-z0-9_]|' . $pctEncoded . ')'; + $varspec = $varchar . '(?:\.?' . $varchar . ')*(?::[1-9][0-9]{0,3}|\*)?'; + $expression = '\{[+#.\/;?&]?' . $varspec . '(?:,' . $varspec . ')*\}'; + + return preg_match( + '/^(?:' . $literal . '|' . $pctEncoded . '|' . $expression . ')*\z/u', + $value + ) === 1; + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/ItemsConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/ItemsConstraint.php new file mode 100644 index 000000000..08a422b39 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/ItemsConstraint.php @@ -0,0 +1,54 @@ +factory = $factory ?: new Factory(); + $this->initialiseErrorBag($this->factory); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'items')) { + return; + } + + if (!is_array($value)) { + return; + } + + $basePath = $path ?? new JsonPointer(''); + foreach ($value as $propertyName => $propertyValue) { + $itemSchema = $schema->items; + if (is_array($itemSchema)) { + if (!array_key_exists($propertyName, $itemSchema)) { + continue; + } + + $itemSchema = $itemSchema[$propertyName]; + } + $incrementedPath = $basePath->withPropertyPaths(array_merge($basePath->getPropertyPaths(), [$propertyName])); + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($propertyValue, $itemSchema, $incrementedPath, $i); + if ($schemaConstraint->isValid()) { + continue; + } + + $this->addErrors($schemaConstraint->getErrors()); + } + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/MaxItemsConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/MaxItemsConstraint.php new file mode 100644 index 000000000..a2c734036 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/MaxItemsConstraint.php @@ -0,0 +1,39 @@ +initialiseErrorBag($factory ?: new Factory()); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'maxItems')) { + return; + } + + if (!is_array($value)) { + return; + } + + $count = count($value); + if ($count <= $schema->maxItems) { + return; + } + + $this->addError(ConstraintError::MAX_ITEMS(), $path, ['maxItems' => $schema->maxItems, 'found' => $count]); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/MaxLengthConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/MaxLengthConstraint.php new file mode 100644 index 000000000..7563ea23f --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/MaxLengthConstraint.php @@ -0,0 +1,39 @@ +initialiseErrorBag($factory ?: new Factory()); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'maxLength')) { + return; + } + + if (!is_string($value)) { + return; + } + + $length = mb_strlen($value, 'UTF-8'); + if ($length <= $schema->maxLength) { + return; + } + + $this->addError(ConstraintError::LENGTH_MAX(), $path, ['maxLength' => $schema->maxLength, 'found' => $length]); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/MaxPropertiesConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/MaxPropertiesConstraint.php new file mode 100644 index 000000000..ce32bcd7d --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/MaxPropertiesConstraint.php @@ -0,0 +1,39 @@ +initialiseErrorBag($factory ?: new Factory()); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'maxProperties')) { + return; + } + + if (!is_object($value)) { + return; + } + + $count = count(get_object_vars($value)); + if ($count <= $schema->maxProperties) { + return; + } + + $this->addError(ConstraintError::PROPERTIES_MAX(), $path, ['maxProperties' => $schema->maxProperties, 'found' => $count]); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/MaximumConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/MaximumConstraint.php new file mode 100644 index 000000000..2350442b5 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/MaximumConstraint.php @@ -0,0 +1,46 @@ +initialiseErrorBag($factory ?: new Factory()); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'maximum')) { + return; + } + + if (!is_numeric($value)) { + return; + } + + $exclusive = property_exists($schema, 'exclusiveMaximum') && $schema->exclusiveMaximum === true; + if ($exclusive ? $value < $schema->maximum : $value <= $schema->maximum) { + return; + } + + $this->addError( + $exclusive ? ConstraintError::EXCLUSIVE_MAXIMUM() : ConstraintError::MAXIMUM(), + $path, + ['maximum' => $schema->maximum, 'found' => $value] + ); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/MinItemsConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/MinItemsConstraint.php new file mode 100644 index 000000000..944c5688c --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/MinItemsConstraint.php @@ -0,0 +1,39 @@ +initialiseErrorBag($factory ?: new Factory()); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'minItems')) { + return; + } + + if (!is_array($value)) { + return; + } + + $count = count($value); + if ($count >= $schema->minItems) { + return; + } + + $this->addError(ConstraintError::MIN_ITEMS(), $path, ['minItems' => $schema->minItems, 'found' => $count]); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/MinLengthConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/MinLengthConstraint.php new file mode 100644 index 000000000..f634d7764 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/MinLengthConstraint.php @@ -0,0 +1,39 @@ +initialiseErrorBag($factory ?: new Factory()); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'minLength')) { + return; + } + + if (!is_string($value)) { + return; + } + + $length = mb_strlen($value, 'UTF-8'); + if ($length >= $schema->minLength) { + return; + } + + $this->addError(ConstraintError::LENGTH_MIN(), $path, ['minLength' => $schema->minLength, 'found' => $length]); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/MinPropertiesConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/MinPropertiesConstraint.php new file mode 100644 index 000000000..0707e9547 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/MinPropertiesConstraint.php @@ -0,0 +1,39 @@ +initialiseErrorBag($factory ?: new Factory()); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'minProperties')) { + return; + } + + if (!is_object($value)) { + return; + } + + $count = count(get_object_vars($value)); + if ($count >= $schema->minProperties) { + return; + } + + $this->addError(ConstraintError::PROPERTIES_MIN(), $path, ['minProperties' => $schema->minProperties, 'found' => $count]); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/MinimumConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/MinimumConstraint.php new file mode 100644 index 000000000..6a41d10db --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/MinimumConstraint.php @@ -0,0 +1,46 @@ +initialiseErrorBag($factory ?: new Factory()); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'minimum')) { + return; + } + + if (!is_numeric($value)) { + return; + } + + $exclusive = property_exists($schema, 'exclusiveMinimum') && $schema->exclusiveMinimum === true; + if ($exclusive ? $value > $schema->minimum : $value >= $schema->minimum) { + return; + } + + $this->addError( + $exclusive ? ConstraintError::EXCLUSIVE_MINIMUM() : ConstraintError::MINIMUM(), + $path, + ['minimum' => $schema->minimum, 'found' => $value] + ); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/MultipleOfConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/MultipleOfConstraint.php new file mode 100644 index 000000000..98bd06110 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/MultipleOfConstraint.php @@ -0,0 +1,54 @@ +initialiseErrorBag($factory ?: new Factory()); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'multipleOf')) { + return; + } + + if ((!is_int($schema->multipleOf) && !is_float($schema->multipleOf)) || $schema->multipleOf <= 0.0) { + return; + } + + if (!is_int($value) && !is_float($value)) { + return; + } + + if ($this->isMultipleOf($value, $schema->multipleOf)) { + return; + } + + $this->addError(ConstraintError::MULTIPLE_OF(), $path, ['multipleOf' => $schema->multipleOf, 'found' => $value]); + } + + /** + * @param int|float $number1 + * @param int|float $number2 + */ + private function isMultipleOf($number1, $number2): bool + { + $modulus = ($number1 - round($number1 / $number2) * $number2); + $precision = 0.0000000001; + + return -$precision < $modulus && $modulus < $precision; + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/NotConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/NotConstraint.php new file mode 100644 index 000000000..027692377 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/NotConstraint.php @@ -0,0 +1,40 @@ +factory = $factory ?: new Factory(); + $this->initialiseErrorBag($this->factory); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'not')) { + return; + } + + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $schema->not, $path, $i); + + if (!$schemaConstraint->isValid()) { + return; + } + + $this->addError(ConstraintError::NOT(), $path); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/OneOfConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/OneOfConstraint.php new file mode 100644 index 000000000..3806db53f --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/OneOfConstraint.php @@ -0,0 +1,50 @@ +factory = $factory ?: new Factory(); + $this->initialiseErrorBag($this->factory); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'oneOf')) { + return; + } + + $matchedSchema = 0; + foreach ($schema->oneOf as $oneOfSchema) { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $oneOfSchema, $path, $i); + + if ($schemaConstraint->isValid()) { + $matchedSchema++; + continue; + } + + $this->addErrors($schemaConstraint->getErrors()); + } + + if ($matchedSchema !== 1) { + $this->addError(ConstraintError::ONE_OF(), $path); + } else { + $this->errorBag()->reset(); + } + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/PatternConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/PatternConstraint.php new file mode 100644 index 000000000..0e53ee8cd --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/PatternConstraint.php @@ -0,0 +1,43 @@ +factory = $factory ?: new Factory(); + $this->initialiseErrorBag($this->factory); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'pattern')) { + return; + } + + if (!is_string($value)) { + return; + } + + $matchPattern = EcmaPatternConverter::toPcre($schema->pattern); + if (preg_match($matchPattern, $value) === 1) { + return; + } + + $this->addError(ConstraintError::PATTERN(), $path, ['pattern' => $schema->pattern, 'found' => $value]); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/PatternPropertiesConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/PatternPropertiesConstraint.php new file mode 100644 index 000000000..66597aa56 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/PatternPropertiesConstraint.php @@ -0,0 +1,55 @@ +factory = $factory ?: new Factory(); + $this->initialiseErrorBag($this->factory); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'patternProperties')) { + return; + } + + if (!is_object($value)) { + return; + } + + $properties = get_object_vars($value); + + $basePath = $path ?? new JsonPointer(''); + foreach ($properties as $propertyName => $propertyValue) { + $incrementedPath = $basePath->withPropertyPaths(array_merge($basePath->getPropertyPaths(), [$propertyName])); + + foreach ($schema->patternProperties as $patternPropertyRegex => $patternPropertySchema) { + $matchPattern = EcmaPatternConverter::toPcre($patternPropertyRegex); + if (preg_match($matchPattern, (string) $propertyName)) { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($propertyValue, $patternPropertySchema, $incrementedPath, $i); + if ($schemaConstraint->isValid()) { + continue; + } + + $this->addErrors($schemaConstraint->getErrors()); + } + } + } + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/PropertiesConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/PropertiesConstraint.php new file mode 100644 index 000000000..77a0e91e0 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/PropertiesConstraint.php @@ -0,0 +1,51 @@ +factory = $factory ?: new Factory(); + $this->initialiseErrorBag($this->factory); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'properties')) { + return; + } + + if (!is_object($value)) { + return; + } + + $basePath = $path ?? new JsonPointer(''); + foreach ($schema->properties as $propertyName => $propertySchema) { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + if (!property_exists($value, $propertyName)) { + continue; + } + + $incrementedPath = $basePath->withPropertyPaths(array_merge($basePath->getPropertyPaths(), [$propertyName])); + + $schemaConstraint->check($value->{$propertyName}, $propertySchema, $incrementedPath, $i); + if ($schemaConstraint->isValid()) { + continue; + } + + $this->addErrors($schemaConstraint->getErrors()); + } + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/RefConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/RefConstraint.php new file mode 100644 index 000000000..1eff31653 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/RefConstraint.php @@ -0,0 +1,43 @@ +factory = $factory ?: new Factory(); + $this->initialiseErrorBag($this->factory); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, '$ref')) { + return; + } + + // A $ref that cannot be resolved is a broken schema, not invalid data: the exception + // is left to propagate rather than letting the value pass as if the $ref was absent. + $refSchema = $this->factory->getSchemaStorage()->resolveRefSchema($schema); + + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $refSchema, $path, $i); + + if ($schemaConstraint->isValid()) { + return; + } + + $this->addErrors($schemaConstraint->getErrors()); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/RequiredConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/RequiredConstraint.php new file mode 100644 index 000000000..2bd2170a9 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/RequiredConstraint.php @@ -0,0 +1,40 @@ +initialiseErrorBag($factory ?: new Factory()); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'required')) { + return; + } + + if (!is_object($value)) { + return; + } + + foreach ($schema->required as $required) { + if (property_exists($value, $required)) { + continue; + } + + $this->addError(ConstraintError::REQUIRED(), ($path ?? new JsonPointer(''))->withAppendedPath($required), ['property' => $required]); + } + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/TypeConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/TypeConstraint.php new file mode 100644 index 000000000..01360edad --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/TypeConstraint.php @@ -0,0 +1,50 @@ +initialiseErrorBag($factory ?: new Factory()); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'type')) { + return; + } + + $schemaTypes = (array) $schema->type; + $valueType = strtolower(gettype($value)); + // All specific number types are a number + $valueIsNumber = $valueType === 'double' || $valueType === 'integer'; + // A float is not an integer even if its fractional part is zero + $isInteger = is_int($value); + + foreach ($schemaTypes as $type) { + if ($valueType === $type) { + return; + } + + if ($type === 'number' && $valueIsNumber) { + return; + } + if ($type === 'integer' && $isInteger) { + return; + } + } + + $this->addError(ConstraintError::TYPE(), $path, ['found' => $valueType, 'expected' => implode(', ', $schemaTypes)]); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/UniqueItemsConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/UniqueItemsConstraint.php new file mode 100644 index 000000000..94b1f6620 --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft04/UniqueItemsConstraint.php @@ -0,0 +1,48 @@ +initialiseErrorBag($factory ?: new Factory()); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!property_exists($schema, 'uniqueItems')) { + return; + } + if (!is_array($value)) { + return; + } + + if ($schema->uniqueItems !== true) { + // If unique items not is true duplicates are allowed. + return; + } + + $count = count($value); + for ($x = 0; $x < $count - 1; $x++) { + for ($y = $x + 1; $y < $count; $y++) { + if (DeepComparer::isEqual($value[$x], $value[$y])) { + $this->addError(ConstraintError::UNIQUE_ITEMS(), $path); + + return; + } + } + } + } +} diff --git a/src/JsonSchema/Constraints/Factory.php b/src/JsonSchema/Constraints/Factory.php index 6cbefcef7..f9514fbde 100644 --- a/src/JsonSchema/Constraints/Factory.php +++ b/src/JsonSchema/Constraints/Factory.php @@ -74,6 +74,7 @@ class Factory 'format' => 'JsonSchema\Constraints\FormatConstraint', 'schema' => 'JsonSchema\Constraints\SchemaConstraint', 'validator' => 'JsonSchema\Validator', + 'draft04' => Drafts\Draft04\Draft04Constraint::class, 'draft06' => Drafts\Draft06\Draft06Constraint::class, 'draft07' => Drafts\Draft07\Draft07Constraint::class, 'draft2019-09' => Drafts\Draft2019\Draft2019Constraint::class, diff --git a/tests/Constraints/Draft04/AdditionalPropertiesConstraintTest.php b/tests/Constraints/Draft04/AdditionalPropertiesConstraintTest.php new file mode 100644 index 000000000..fe82d0530 --- /dev/null +++ b/tests/Constraints/Draft04/AdditionalPropertiesConstraintTest.php @@ -0,0 +1,50 @@ +check($value, $schema); + + $errors = $constraint->getErrors(); + $this->assertCount(1, $errors); + $this->assertSame('/bar', $errors[0]['pointer']); + $this->assertSame('type', $errors[0]['constraint']['name']); + } + + public function testAPropertyMatchingTheSubSchemaIsNotReported(): void + { + $constraint = new AdditionalPropertiesConstraint(); + $schema = json_decode('{"additionalProperties": {"type": "integer"}}'); + $value = json_decode('{"bar": 1}'); + + $constraint->check($value, $schema); + + $this->assertSame([], $constraint->getErrors()); + } + + public function testAdditionalPropertiesFalseStillReportsTheProperty(): void + { + $constraint = new AdditionalPropertiesConstraint(); + $schema = json_decode('{"properties": {"foo": {}}, "additionalProperties": false}'); + $value = json_decode('{"foo": "ok", "bar": 1}'); + + $constraint->check($value, $schema); + + $errors = $constraint->getErrors(); + $this->assertCount(1, $errors); + $this->assertSame('/bar', $errors[0]['pointer']); + $this->assertSame('additionalProp', $errors[0]['constraint']['name']); + } +} diff --git a/tests/Constraints/Draft04/Draft04ConstraintTest.php b/tests/Constraints/Draft04/Draft04ConstraintTest.php new file mode 100644 index 000000000..3e36275cc --- /dev/null +++ b/tests/Constraints/Draft04/Draft04ConstraintTest.php @@ -0,0 +1,69 @@ +{'$schema'} = DraftIdentifiers::DRAFT_4; + + $validator = new Validator(); + $validator->validate($data, $decodedSchema, Constraint::CHECK_MODE_STRICT); + + self::assertSame($expectedToBeValid, $validator->isValid(), (string) json_encode($validator->getErrors())); + } + + /** + * @return array + */ + public static function provideCases(): array + { + return [ + 'const is not a Draft-04 keyword' => ['{"const": 1}', 2, true], + 'contains is not a Draft-04 keyword' => ['{"contains": {"type": "string"}}', [1], true], + 'propertyNames is not a Draft-04 keyword' => ['{"propertyNames": {"maxLength": 1}}', (object) ['foo' => 1], true], + 'exclusiveMinimum without minimum is ignored' => ['{"exclusiveMinimum": 5}', 5, true], + 'exclusiveMaximum without maximum is ignored' => ['{"exclusiveMaximum": 5}', 5, true], + 'minimum is inclusive by default' => ['{"minimum": 5}', 5, true], + 'minimum is exclusive with exclusiveMinimum' => ['{"minimum": 5, "exclusiveMinimum": true}', 5, false], + 'minimum stays inclusive with exclusiveMinimum false' => ['{"minimum": 5, "exclusiveMinimum": false}', 5, true], + 'below minimum is invalid' => ['{"minimum": 5}', 4, false], + 'maximum is inclusive by default' => ['{"maximum": 5}', 5, true], + 'maximum is exclusive with exclusiveMaximum' => ['{"maximum": 5, "exclusiveMaximum": true}', 5, false], + 'above maximum is invalid' => ['{"maximum": 5}', 6, false], + 'a float with zero fractional part is not an integer' => ['{"type": "integer"}', 1.0, false], + 'an integer is an integer' => ['{"type": "integer"}', 1, true], + 'a numeric string is not equal to a number in enum' => ['{"enum": [1]}', '1', false], + 'a float is equal to a mathematically equal integer in enum' => ['{"enum": [1]}', 1.0, true], + '$ref overrides sibling keywords' => ['{"definitions": {"a": {"type": "integer"}}, "$ref": "#/definitions/a", "maximum": 0}', 5, true], + ]; + } + + public function testExclusiveMinimumReportsTheMinimum(): void + { + $schema = json_decode('{"$schema": "' . DraftIdentifiers::DRAFT_4 . '", "minimum": 5, "exclusiveMinimum": true}'); + $data = 5; + + $validator = new Validator(); + $validator->validate($data, $schema, Constraint::CHECK_MODE_STRICT); + + $errors = $validator->getErrors(); + self::assertCount(1, $errors); + self::assertSame('exclusiveMinimum', $errors[0]['constraint']['name']); + self::assertSame('Must have a minimum value greater than 5', $errors[0]['message']); + } +} diff --git a/tests/Constraints/Draft04/EcmaPatternTest.php b/tests/Constraints/Draft04/EcmaPatternTest.php new file mode 100644 index 000000000..ec012638c --- /dev/null +++ b/tests/Constraints/Draft04/EcmaPatternTest.php @@ -0,0 +1,85 @@ +validate($decodedData, json_decode($schema), Constraint::CHECK_MODE_STRICT); + + self::assertSame($expectedToBeValid, $validator->isValid(), (string) json_encode($validator->getErrors())); + } + + /** + * @return array + */ + public static function provideNonAsciiCases(): array + { + return [ + 'ASCII digit matches \\d in patternProperties' => [ + <<<'JSON' + { + "$schema": "http://json-schema.org/draft-04/schema#", + "patternProperties": {"^\\d+$": {"type": "string"}}, + "additionalProperties": false + } +JSON + , + '{"5": "ok"}', + true, + ], + 'Arabic-Indic digit does not match \\d in patternProperties' => [ + <<<'JSON' + { + "$schema": "http://json-schema.org/draft-04/schema#", + "patternProperties": {"^\\d+$": {"type": "string"}}, + "additionalProperties": false + } +JSON + , + '{"٣": "ok"}', + false, + ], + 'accented letter does not match \\w in pattern' => [ + <<<'JSON' + { + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "string", + "pattern": "^\\w+$" + } +JSON + , + '"é"', + false, + ], + '\\w inside a character class in patternProperties' => [ + <<<'JSON' + { + "$schema": "http://json-schema.org/draft-04/schema#", + "patternProperties": {"^[\\w-]+$": {"type": "string"}}, + "additionalProperties": false + } +JSON + , + '{"foo-bar": "ok"}', + true, + ], + ]; + } +} diff --git a/tests/Constraints/Draft04/EnumConstraintTest.php b/tests/Constraints/Draft04/EnumConstraintTest.php new file mode 100644 index 000000000..de39fd57a --- /dev/null +++ b/tests/Constraints/Draft04/EnumConstraintTest.php @@ -0,0 +1,43 @@ + $enum + */ + public function testValueIsComparedWithTheEnumCases($value, array $enum, bool $expectedToBeValid): void + { + $constraint = new EnumConstraint(); + $schema = (object) ['enum' => $enum]; + + $constraint->check($value, $schema); + + $this->assertSame($expectedToBeValid, $constraint->isValid()); + } + + /** + * @return array, bool}> + */ + public static function provideCases(): array + { + return [ + 'an integer matches an equal integer' => [1, [1], true], + 'a float matches a mathematically equal integer' => [1.0, [1], true], + 'an integer matches a mathematically equal float' => [1, [1.0], true], + 'a numeric string does not match an integer' => ['1', [1], false], + 'a numeric string does not match a float' => ['1.5', [1.5], false], + 'an integer does not match a numeric string' => [1, ['1'], false], + 'a numeric string in exponent notation does not match an integer' => ['1e0', [1], false], + ]; + } +} diff --git a/tests/Constraints/Draft04/ErrorPathTest.php b/tests/Constraints/Draft04/ErrorPathTest.php new file mode 100644 index 000000000..5a68e0389 --- /dev/null +++ b/tests/Constraints/Draft04/ErrorPathTest.php @@ -0,0 +1,61 @@ +validate( + '{"type": "object", "required": ["bar"], "properties": {"foo": {"type": "integer"}, "n": {"type": "object", "properties": {"x": {"type": "integer"}}}}}', + '{"foo": "bar", "n": {"x": "y"}}' + ); + + $this->assertSame(['/bar', '/foo', '/n/x'], array_column($errors, 'pointer')); + $this->assertSame(['bar', 'foo', 'n.x'], array_column($errors, 'property')); + } + + public function testItemErrorsAreReportedAtTheirIndex(): void + { + $errors = $this->validate( + '{"properties": {"list": {"items": {"type": "integer"}}, "tuple": {"items": [{"type": "integer"}], "additionalItems": {"type": "integer"}}}}', + '{"list": [1, "a"], "tuple": ["b", "c"]}' + ); + + $this->assertSame(['/list/1', '/tuple/0', '/tuple/1'], array_column($errors, 'pointer')); + } + + public function testPatternPropertyErrorsAreReportedAtThePropertyPath(): void + { + $errors = $this->validate( + '{"patternProperties": {"^p": {"type": "integer"}}}', + '{"p1": "a", "p2": "b"}' + ); + + $this->assertSame(['/p1', '/p2'], array_column($errors, 'pointer')); + } + + /** + * @return list> + */ + private function validate(string $schema, string $data): array + { + $schema = json_decode($schema); + $schema->{'$schema'} = self::SCHEMA_URI; + $data = json_decode($data); + + $validator = new Validator(new Factory(null, null, Constraint::CHECK_MODE_STRICT)); + $validator->validate($data, $schema); + + return $validator->getErrors(); + } +} diff --git a/tests/Constraints/Draft04/FormatConstraintTest.php b/tests/Constraints/Draft04/FormatConstraintTest.php new file mode 100644 index 000000000..e4b99a83f --- /dev/null +++ b/tests/Constraints/Draft04/FormatConstraintTest.php @@ -0,0 +1,68 @@ +format = $format; + + $validator->check($string, $schema); + + $this->assertCount(1, $validator->getErrors(), 'Expected 1 error'); + } + + /** + * @dataProvider getValidFormats + */ + public function testValidFormat($string, $format): void + { + $validator = new FormatConstraint(); + $schema = new \stdClass(); + $schema->format = $format; + + $validator->check($string, $schema); + + $this->assertTrue($validator->isValid()); + } + + public function testFormatIsIgnoredWhenDisabled(): void + { + $validator = new FormatConstraint(new Factory(null, null, Constraint::CHECK_MODE_DISABLE_FORMAT)); + $schema = new \stdClass(); + $schema->format = 'date'; + $value = 'not-a-date'; + + $validator->check($value, $schema); + + $this->assertTrue($validator->isValid()); + } + + public function getInvalidFormats(): Generator + { + yield 'Date-time format with value containing null byte' => ["2020-01-01T12:34:56\x00", 'date-time']; + yield 'Date format with value containing null byte' => ["2020-01-01\x00", 'date']; + yield 'Time format with value containing null byte' => ["13:37:00\x00", 'time']; + yield 'URI template format with trailing new line' => ["http://example.com/{term}\n", 'uri-template']; + } + + public function getValidFormats(): Generator + { + yield 'Date-time format with value containing high-precision fractional seconds' => ['2020-01-01T12:00:02.0000001Z', 'date-time']; + yield 'URI template format with non-Latin literal' => ['http://例え.jp/π/{term}', 'uri-template']; + } +} diff --git a/tests/Constraints/Draft04/MultipleOfConstraintTest.php b/tests/Constraints/Draft04/MultipleOfConstraintTest.php new file mode 100644 index 000000000..6a73dd80a --- /dev/null +++ b/tests/Constraints/Draft04/MultipleOfConstraintTest.php @@ -0,0 +1,50 @@ + $multipleOf]; + $value = 5; + + $constraint->check($value, $schema); + + $this->assertSame([], $constraint->getErrors()); + } + + /** + * @return array + */ + public static function provideNonPositiveMultipleOf(): array + { + return [ + 'zero' => [0], + 'zero as float' => [0.0], + 'negative integer' => [-2], + ]; + } + + public function testAValueThatIsNotAMultipleIsReported(): void + { + $constraint = new MultipleOfConstraint(); + $schema = (object) ['multipleOf' => 2]; + $value = 5; + + $constraint->check($value, $schema); + + $this->assertCount(1, $constraint->getErrors()); + } +} diff --git a/tests/Constraints/Draft04/PatternConstraintTest.php b/tests/Constraints/Draft04/PatternConstraintTest.php new file mode 100644 index 000000000..314fb0b0a --- /dev/null +++ b/tests/Constraints/Draft04/PatternConstraintTest.php @@ -0,0 +1,25 @@ +check($value, $schema); + + $errors = $constraint->getErrors(); + $this->assertCount(1, $errors); + $this->assertSame('Does not match the regex pattern ^[a-z]+$', $errors[0]['message']); + $this->assertSame(['pattern' => '^[a-z]+$', 'found' => 'ABC'], $errors[0]['constraint']['params']); + } +} diff --git a/tests/Constraints/Draft04/RefConstraintTest.php b/tests/Constraints/Draft04/RefConstraintTest.php new file mode 100644 index 000000000..53e7a433a --- /dev/null +++ b/tests/Constraints/Draft04/RefConstraintTest.php @@ -0,0 +1,51 @@ +expectException(UnresolvableJsonPointerException::class); + + $validator->validate($data, $schema, Constraint::CHECK_MODE_STRICT); + } + + public function testAnUnresolvableRefInsideAnApplicatorIsNotSwallowed(): void + { + $validator = new Validator(); + $data = new \stdClass(); + $schema = json_decode('{"$schema": "' . self::DIALECT . '", "anyOf": [{"$ref": "#/$defs/nonExistent"}, {}]}'); + + $this->expectException(UnresolvableJsonPointerException::class); + + $validator->validate($data, $schema, Constraint::CHECK_MODE_STRICT); + } + + public function testAResolvableRefStillValidates(): void + { + $validator = new Validator(); + $data = json_decode('{"child": 1}'); + $schema = json_decode( + '{"$schema": "' . self::DIALECT . '", "$defs": {"num": {"type": "integer"}},' + . ' "properties": {"child": {"$ref": "#/$defs/num"}}}' + ); + + $validator->validate($data, $schema, Constraint::CHECK_MODE_STRICT); + + self::assertTrue($validator->isValid(), (string) json_encode($validator->getErrors())); + } +} diff --git a/tests/Constraints/SchemaValidationTest.php b/tests/Constraints/SchemaValidationTest.php index fa6d0ecd2..0d25c48be 100644 --- a/tests/Constraints/SchemaValidationTest.php +++ b/tests/Constraints/SchemaValidationTest.php @@ -98,7 +98,7 @@ public function testValidCases($schema): void public function getStrictModeInvalidTests(): \Generator { - foreach ([DraftIdentifiers::DRAFT_6, DraftIdentifiers::DRAFT_7, DraftIdentifiers::DRAFT_2019_09] as $dialect) { + foreach ([DraftIdentifiers::DRAFT_4, DraftIdentifiers::DRAFT_6, DraftIdentifiers::DRAFT_7, DraftIdentifiers::DRAFT_2019_09] as $dialect) { yield $dialect . ' top-level keyword' => [$dialect, '{"minLength": "1"}']; yield $dialect . ' keyword in a subschema' => [$dialect, '{"properties": {"propertyOne": {"minLength": "1"}}}']; yield $dialect . ' keyword in a nested subschema' => [$dialect, '{"properties": {"propertyOne": {"items": {"properties": {"a": {"type": 5}}}}}}']; diff --git a/tests/JsonSchemaTestSuiteTest.php b/tests/JsonSchemaTestSuiteTest.php index 75a82c79e..ca3e402d6 100644 --- a/tests/JsonSchemaTestSuiteTest.php +++ b/tests/JsonSchemaTestSuiteTest.php @@ -85,11 +85,7 @@ function ($file) { $test->valid ? 'valid' : 'invalid' ); - if ($this->shouldNotYieldTest($name)) { - continue; - } - - yield $name => [ + $case = [ 'testCaseDescription' => $testCase->description, 'testDescription' => $test->description, 'schema' => $testCase->schema, @@ -98,6 +94,16 @@ function ($file) { 'draft' => DraftIdentifiers::fromConstraintName($baseDraftName), 'expectedValidationResult' => $test->valid, ]; + + if (!$this->shouldNotYieldTest($name)) { + yield $name => $case; + } + + // Draft-04 is validated by the legacy constraints by default, and by its own constraint set in strict mode + $strictName = $name . ' (strict mode)'; + if ($baseDraftName === 'draft4' && !$this->shouldNotYieldTest($strictName)) { + yield $strictName => array_merge($case, ['checkMode' => $case['checkMode'] | Constraint::CHECK_MODE_STRICT]); + } } } } @@ -125,6 +131,26 @@ private function loadRemotesIntoStorage(SchemaStorageInterface $storage): void private function shouldNotYieldTest(string $name): bool { $skip = [ + // Draft-04 in strict mode: PHP does not natively support arbitrary-precision integers and its float precision differs from the ECMAScript model + '[draft4/optional/bignum.json]: integer: a bignum is an integer is expected to be valid (strict mode)', + '[draft4/optional/bignum.json]: integer: a negative bignum is an integer is expected to be valid (strict mode)', + '[draft4/optional/float-overflow.json]: all integers are multiples of 0.5, if overflow is handled: valid if optional overflow handling is implemented is expected to be valid (strict mode)', + // Draft-04 in strict mode: zero-width whitespace is not matched by \s, like in the other drafts + '[draft4/optional/ecmascript-regex.json]: ECMA 262 \S matches everything but whitespace: zero-width whitespace does not match is expected to be invalid (strict mode)', + '[draft4/optional/ecmascript-regex.json]: ECMA 262 \s matches whitespace: zero-width whitespace matches is expected to be valid (strict mode)', + // Draft-04 in strict mode: the format implementation shares the limitations of the other drafts + '[draft4/optional/format/email.json]: validation of e-mail addresses: a domain that looks like an IPv4 address without brackets is valid is expected to be valid (strict mode)', + '[draft4/optional/format/email.json]: validation of e-mail addresses: a non-ASCII character in the local part is not valid is expected to be invalid (strict mode)', + '[draft4/optional/format/email.json]: validation of e-mail addresses: a quoted string containing only a space in the local part is valid is expected to be valid (strict mode)', + '[draft4/optional/format/email.json]: validation of e-mail addresses: a quoted string with a space in the local part is valid is expected to be valid (strict mode)', + '[draft4/optional/format/email.json]: validation of e-mail addresses: a single-label domain is valid is expected to be valid (strict mode)', + '[draft4/optional/format/hostname.json]: validation of host names: exceeds maximum overall length (256) is expected to be invalid (strict mode)', + '[draft4/optional/format/uri.json]: validation of URIs: a trailing newline after a valid URI is invalid is expected to be invalid (strict mode)', + '[draft4/optional/format/uri.json]: validation of URIs: incomplete percent-encoding triplet is expected to be invalid (strict mode)', + '[draft4/optional/format/uri.json]: validation of URIs: invalid percent-encoding with non-hex digits is expected to be invalid (strict mode)', + '[draft4/optional/format/uri.json]: validation of URIs: invalid userinfo is expected to be invalid (strict mode)', + '[draft4/optional/format/uri.json]: validation of URIs: leading zero in an embedded IPv4 address is invalid is expected to be invalid (strict mode)', + '[draft4/optional/format/uri.json]: validation of URIs: lone percent sign is invalid is expected to be invalid (strict mode)', // Draft 2019-09 complex constraints, which aren't supported initially '[draft2019-09/recursiveRef.json]: $recursiveRef without $recursiveAnchor works like $ref: recursive mismatch is expected to be invalid', '[draft2019-09/recursiveRef.json]: $recursiveRef without using nesting: integer does not match as a property value is expected to be invalid', diff --git a/tests/ValidatorTest.php b/tests/ValidatorTest.php index c0016664b..437a59cd4 100644 --- a/tests/ValidatorTest.php +++ b/tests/ValidatorTest.php @@ -87,6 +87,7 @@ public function draftIdentifiersNotSupportedForStrictMode(): \Generator { foreach (DraftIdentifiers::getEnumerators() as $draft) { switch ($draft) { + case DraftIdentifiers::DRAFT_4(): case DraftIdentifiers::DRAFT_6(): case DraftIdentifiers::DRAFT_7(): case DraftIdentifiers::DRAFT_2019_09(): From dc1e95628f1f9f527059b28a4650a75d3c38cd08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Ondr=C3=A1=C4=8Dek?= Date: Tue, 24 Nov 2026 22:42:48 +0100 Subject: [PATCH 5/7] fix: Apply the pattern and format fixes to Draft-04 in strict mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Roman Ondráček --- .../Drafts/Draft04/FormatConstraint.php | 3 ++- tests/JsonSchemaTestSuiteTest.php | 14 -------------- 2 files changed, 2 insertions(+), 15 deletions(-) diff --git a/src/JsonSchema/Constraints/Drafts/Draft04/FormatConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft04/FormatConstraint.php index dbe06da1a..c4680b025 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft04/FormatConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft04/FormatConstraint.php @@ -11,6 +11,7 @@ use JsonSchema\Entity\ErrorBagProxy; use JsonSchema\Entity\JsonPointer; use JsonSchema\Rfc3339; +use JsonSchema\Tool\Validator\EmailValidator; use JsonSchema\Tool\Validator\RelativeReferenceValidator; use JsonSchema\Tool\Validator\UriValidator; @@ -108,7 +109,7 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n break; case 'email': - if (filter_var($value, FILTER_VALIDATE_EMAIL, FILTER_NULL_ON_FAILURE | FILTER_FLAG_EMAIL_UNICODE) === null) { + if (!EmailValidator::isValid($value)) { $this->addError(ConstraintError::FORMAT_EMAIL(), $path, ['format' => $schema->format]); } break; diff --git a/tests/JsonSchemaTestSuiteTest.php b/tests/JsonSchemaTestSuiteTest.php index ca3e402d6..e524e30bb 100644 --- a/tests/JsonSchemaTestSuiteTest.php +++ b/tests/JsonSchemaTestSuiteTest.php @@ -135,22 +135,8 @@ private function shouldNotYieldTest(string $name): bool '[draft4/optional/bignum.json]: integer: a bignum is an integer is expected to be valid (strict mode)', '[draft4/optional/bignum.json]: integer: a negative bignum is an integer is expected to be valid (strict mode)', '[draft4/optional/float-overflow.json]: all integers are multiples of 0.5, if overflow is handled: valid if optional overflow handling is implemented is expected to be valid (strict mode)', - // Draft-04 in strict mode: zero-width whitespace is not matched by \s, like in the other drafts - '[draft4/optional/ecmascript-regex.json]: ECMA 262 \S matches everything but whitespace: zero-width whitespace does not match is expected to be invalid (strict mode)', - '[draft4/optional/ecmascript-regex.json]: ECMA 262 \s matches whitespace: zero-width whitespace matches is expected to be valid (strict mode)', // Draft-04 in strict mode: the format implementation shares the limitations of the other drafts - '[draft4/optional/format/email.json]: validation of e-mail addresses: a domain that looks like an IPv4 address without brackets is valid is expected to be valid (strict mode)', - '[draft4/optional/format/email.json]: validation of e-mail addresses: a non-ASCII character in the local part is not valid is expected to be invalid (strict mode)', - '[draft4/optional/format/email.json]: validation of e-mail addresses: a quoted string containing only a space in the local part is valid is expected to be valid (strict mode)', - '[draft4/optional/format/email.json]: validation of e-mail addresses: a quoted string with a space in the local part is valid is expected to be valid (strict mode)', - '[draft4/optional/format/email.json]: validation of e-mail addresses: a single-label domain is valid is expected to be valid (strict mode)', '[draft4/optional/format/hostname.json]: validation of host names: exceeds maximum overall length (256) is expected to be invalid (strict mode)', - '[draft4/optional/format/uri.json]: validation of URIs: a trailing newline after a valid URI is invalid is expected to be invalid (strict mode)', - '[draft4/optional/format/uri.json]: validation of URIs: incomplete percent-encoding triplet is expected to be invalid (strict mode)', - '[draft4/optional/format/uri.json]: validation of URIs: invalid percent-encoding with non-hex digits is expected to be invalid (strict mode)', - '[draft4/optional/format/uri.json]: validation of URIs: invalid userinfo is expected to be invalid (strict mode)', - '[draft4/optional/format/uri.json]: validation of URIs: leading zero in an embedded IPv4 address is invalid is expected to be invalid (strict mode)', - '[draft4/optional/format/uri.json]: validation of URIs: lone percent sign is invalid is expected to be invalid (strict mode)', // Draft 2019-09 complex constraints, which aren't supported initially '[draft2019-09/recursiveRef.json]: $recursiveRef without $recursiveAnchor works like $ref: recursive mismatch is expected to be invalid', '[draft2019-09/recursiveRef.json]: $recursiveRef without using nesting: integer does not match as a property value is expected to be invalid', From 3e8150777cbc91fc7d249fc60bda3700ba41edef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Ondr=C3=A1=C4=8Dek?= Date: Fri, 4 Dec 2026 15:30:36 +0100 Subject: [PATCH 6/7] test: Skip the Draft-04 bignum multipleOf test in strict mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Roman Ondráček --- tests/JsonSchemaTestSuiteTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/JsonSchemaTestSuiteTest.php b/tests/JsonSchemaTestSuiteTest.php index e524e30bb..2b17ae68e 100644 --- a/tests/JsonSchemaTestSuiteTest.php +++ b/tests/JsonSchemaTestSuiteTest.php @@ -134,6 +134,7 @@ private function shouldNotYieldTest(string $name): bool // Draft-04 in strict mode: PHP does not natively support arbitrary-precision integers and its float precision differs from the ECMAScript model '[draft4/optional/bignum.json]: integer: a bignum is an integer is expected to be valid (strict mode)', '[draft4/optional/bignum.json]: integer: a negative bignum is an integer is expected to be valid (strict mode)', + '[draft4/optional/bignum.json]: multipleOf with integers above 2^53: 1e20 is not multiple of 3 is expected to be invalid (strict mode)', '[draft4/optional/float-overflow.json]: all integers are multiples of 0.5, if overflow is handled: valid if optional overflow handling is implemented is expected to be valid (strict mode)', // Draft-04 in strict mode: the format implementation shares the limitations of the other drafts '[draft4/optional/format/hostname.json]: validation of host names: exceeds maximum overall length (256) is expected to be invalid (strict mode)', From 54c0ce682bd7937e5bf1f266a4d2e94bc3be1992 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Ondr=C3=A1=C4=8Dek?= Date: Fri, 4 Dec 2026 15:42:22 +0100 Subject: [PATCH 7/7] test: Skip the Draft-04 small multiple of large integer test in strict mode on 32 bits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Roman Ondráček --- tests/JsonSchemaTestSuiteTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/JsonSchemaTestSuiteTest.php b/tests/JsonSchemaTestSuiteTest.php index 2b17ae68e..77d78bade 100644 --- a/tests/JsonSchemaTestSuiteTest.php +++ b/tests/JsonSchemaTestSuiteTest.php @@ -320,6 +320,7 @@ private function shouldNotYieldTest(string $name): bool if ($this->is32Bit()) { $skip[] = '[draft4/multipleOf.json]: small multiple of large integer: any integer is a multiple of 1e-8 is expected to be valid'; // Test case contains a number which doesn't fit in 32 bits + $skip[] = '[draft4/multipleOf.json]: small multiple of large integer: any integer is a multiple of 1e-8 is expected to be valid (strict mode)'; } return in_array($name, $skip, true);