Skip to content

[BUGFIX] RFC-3986 compliant validation of URI relative references #358

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 23, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/JsonSchema/Constraints/FormatConstraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,26 @@ public function check(&$element, $schema = null, JsonPointer $path = null, $i =

case 'uri':
if (null === filter_var($element, FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE)) {
$this->addError($path, 'Invalid URL format', 'format', array('format' => $schema->format));
// FILTER_VALIDATE_URL does not conform to RFC-3986, and cannot handle relative URLs, but
// the json-schema spec uses RFC-3986, so need a bit of hackery to properly validate them.
// See https://tools.ietf.org/html/rfc3986#section-4.2 for additional information.
if (substr($element, 0, 2) === '//') { // network-path reference
$validURL = filter_var('scheme:' . $element, FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE);
} elseif (substr($element, 0, 1) === '/') { // absolute-path reference
$validURL = filter_var('scheme://host' . $element, FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE);
} elseif (strlen($element)) { // relative-path reference
$pathParts = explode('/', $element, 2);
if ($pathParts[0][0] !== '.' && strpos($pathParts[0], ':') !== false) {
$validURL = null;
} else {
$validURL = filter_var('scheme://host/' . $element, FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE);
}
} else {
$validURL = null;
}
if ($validURL === null) {
$this->addError($path, 'Invalid URL format', 'format', array('format' => $schema->format));
}
}
break;

Expand Down
4 changes: 4 additions & 0 deletions tests/Constraints/FormatTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,9 @@ public function getValidFormats()
array('555 320 1212', 'phone'),

array('http://bluebox.org', 'uri'),
array('//bluebox.org', 'uri'),
array('/absolutePathReference/', 'uri'),
array('relativePathReference/', 'uri'),

array('[email protected]', 'email'),

Expand Down Expand Up @@ -173,6 +176,7 @@ public function getInvalidFormats()
array('1 123 4424', 'phone'),

array('htt:/bluebox.org', 'uri'),
array('', 'uri'),

array('info@somewhere', 'email'),

Expand Down