Skip to content
Open
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
79 changes: 68 additions & 11 deletions src/JsonSchema/SchemaStorage.php
Comment thread
DannyvdSluijs marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,44 @@ class SchemaStorage implements SchemaStorageInterface
{
public const INTERNAL_PROVIDED_SCHEMA_URI = 'internal://provided-schema/';

/**
* Keywords whose value is a schema.
*
* 'items' and 'extends' also appear below, as they hold either a schema or a list of schemas.
*/
private const SCHEMA_KEYWORDS = [
'additionalItems',
'additionalProperties',
'contains',
'contentSchema',
'else',
'extends',
'if',
'items',
'not',
'propertyNames',
'then',
'unevaluatedItems',
'unevaluatedProperties',
];

/**
* Keywords whose value is a list of schemas.
*
* Draft 3's 'disallow' and 'type' take a list mixing type names and schemas: only the
* schemas among them are objects, so the type names are skipped like any other scalar.
*/
private const SCHEMA_ARRAY_KEYWORDS = [
'allOf',
'anyOf',
'disallow',
'extends',
'items',
'oneOf',
'prefixItems',
'type',
];

/**
* Keywords whose value is a map of subschemas keyed by an arbitrary name, so a member
* named after a keyword is a schema rather than that keyword's value.
Expand Down Expand Up @@ -240,8 +278,8 @@ public function resolveRefSchema($refSchema, $resolveStack = [])
* Walk the members of one container - a schema object, or an array such as allOf or a
* tuple items - handing each member to registerAndScanSubschema().
*
* $parentProperty is the keyword the container itself sits under, which is what decides
* whether a member named 'enum' or 'const' is that keyword's value or a schema.
* $parentProperty is the keyword the container itself sits under: inside a schema map, every
* member is a schema whatever its name, see holdsSchemas().
*
* @param mixed $schema
*/
Expand All @@ -252,24 +290,26 @@ private function scanMembersForSubschemas($schema, string $parentId, string $par
}

foreach ($schema as $propertyName => $member) {
// Enum and const don't allow id as a keyword, see https://github.com/json-schema-org/JSON-Schema-Test-Suite/pull/471
// Their values are skipped entirely, but a subschema may legitimately be named
// 'enum' or 'const', so the enclosing keyword decides which of the two this is.
if (
in_array($propertyName, ['enum', 'const'], true)
&& !in_array($parentProperty, self::SCHEMA_MAP_KEYWORDS, true)
) {
// An id only identifies a schema, so only positions holding schemas are descended
Comment thread
DannyvdSluijs marked this conversation as resolved.
Resolved
// into. Data positions such as 'default', 'examples', 'enum', 'const' and any unknown
// keyword are left alone, and an id written there identifies nothing,
// see https://github.com/json-schema-org/JSON-Schema-Test-Suite/pull/471
if (!self::holdsSchemas((string) $propertyName, $parentProperty)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a behaviour change: ids declared under a custom container keyword (OpenAPI-style components, x-definitions, ...) are no longer registered, so $refs to them now fall through to a remote fetch.

Repro: schema {"properties":{"a":{"$ref":"http://example.invalid/c.json"}},"components":{"C":{"$id":"http://example.invalid/c.json","type":"integer"}}} with data {"a":"x"}. On main this reports a type error; with this PR it throws ResourceNotFoundException for http://example.invalid/c.json.

This is more spec-correct, but it breaks setups that work today. Could we either note it in the CHANGELOG as a BC break, or keep a fallback (e.g. register such ids only when nothing else claims the URI)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: main reports the type error, this PR throws ResourceNotFoundException. That's the behaviour #949 asks for (an id under an unknown keyword identifies nothing, as in the test suite's unknownKeyword.json), but you're right that it breaks setups working today. @DannyvdSluijs your call: keep it and flag it in the release notes, or register such ids as a fallback only when no real schema claims the URI? Happy to do either.

continue;
}

// A member of a schema map is a schema named by the author, not a keyword, so its
// name must not decide what its own members hold.
$memberProperty = in_array($parentProperty, self::SCHEMA_MAP_KEYWORDS, true) ? '' : (string) $propertyName;

if (is_array($member)) {
foreach ($member as $item) {
$this->registerAndScanSubschema($item, $parentId, (string) $propertyName);
$this->registerAndScanSubschema($item, $parentId, $memberProperty);
}
continue;
}

$this->registerAndScanSubschema($member, $parentId, (string) $propertyName);
$this->registerAndScanSubschema($member, $parentId, $memberProperty);
}
}

Expand Down Expand Up @@ -372,6 +412,23 @@ private function resolveAnchor(string $ref, array $resolveStack)
return $this->resolveRefSchema($this->anchors[$ref], $resolveStack);
}

/**
* Whether the member named $propertyName holds schemas rather than data.
*
* The members of a schema map are named by the schema author, so a member named after a
* keyword is a schema there, which is what $parentProperty decides.
*/
private static function holdsSchemas(string $propertyName, string $parentProperty): bool
{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still leaks ids from data positions when a subschema's name is a map keyword. scanMembersForSubschemas() passes each map member's own name as $parentProperty, so the members of a property called properties, definitions, $defs, dependencies, patternProperties or dependentSchemas are scanned with that name and holdsSchemas() returns true for all of them.

Repro:

$storage->addSchema('http://example.org/root/', json_decode('{"properties": {"properties": {"type":"object", "default": {"id": "leaked.json"}, "enum": [{"id": "e.json"}], "x-unknown": {"id": "u.json"}}}}'));

This registers http://example.org/root/leaked.json, e.json and u.json. A property named properties is common (e.g. GeoJSON).

Suggestion: track whether the container being scanned is a schema map or a schema, e.g. pass a flag or an empty $parentProperty when recursing into a map member's schema, instead of reusing the member's name.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks! Confirmed with your repro (it leaks on main too, but this PR should close it). Fixed in 71f2003: a member of a schema map is now scanned as a schema, so its own name no longer decides what its members hold. Your case is in the data provider and fails without the fix.

if (in_array($parentProperty, self::SCHEMA_MAP_KEYWORDS, true)) {
return true;
}

return in_array($propertyName, self::SCHEMA_KEYWORDS, true)
|| in_array($propertyName, self::SCHEMA_ARRAY_KEYWORDS, true)
|| in_array($propertyName, self::SCHEMA_MAP_KEYWORDS, true);
}

private function findSchemaIdInObject(object $schema): ?string
{
if (property_exists($schema, 'id') && is_string($schema->id)) {
Expand Down
7 changes: 0 additions & 7 deletions tests/JsonSchemaTestSuiteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -465,13 +465,6 @@ private function shouldNotYieldTest(string $name): bool
'[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',
'[draft7/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',
'[draft7/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',
'[draft2019-09/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',
'[draft2019-09/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',
];

if ($this->is32Bit()) {
Expand Down
93 changes: 93 additions & 0 deletions tests/SchemaStorageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,76 @@ public function subschemaRegistrationProvider(): \Generator
'expectedUris' => ['http://example.org/root/deep.json'],
'unexpectedUris' => [],
];

yield 'a subschema named after a schema map keyword keeps its data positions' => [
'schema' => '{"properties": {"properties": {"default": {"id": "default.json"}, "enum": [{"id": "enum.json"}], "x-unknown": {"id": "unknown.json"}, "definitions": {"x": {"id": "real.json"}}}}}',
'expectedUris' => ['http://example.org/root/real.json'],
'unexpectedUris' => [
'http://example.org/root/default.json',
'http://example.org/root/enum.json',
'http://example.org/root/unknown.json',
],
];

yield 'an id inside a default value is not an identifier' => [
'schema' => '{"default": {"wrapper": {"id": "leaked.json", "type": "string"}}}',
'expectedUris' => [],
'unexpectedUris' => ['http://example.org/root/leaked.json'],
];

yield 'an id inside an examples entry is not an identifier' => [
'schema' => '{"examples": [{"id": "leaked.json", "type": "string"}]}',
'expectedUris' => [],
'unexpectedUris' => ['http://example.org/root/leaked.json'],
];

yield 'an id inside an unknown keyword holding a list is not an identifier' => [
'schema' => '{"not": {"array_of_schemas": [{"id": "leaked.json", "type": "null"}]}}',
'expectedUris' => [],
'unexpectedUris' => ['http://example.org/root/leaked.json'],
];

yield 'an id inside an unknown keyword holding a map is not an identifier' => [
'schema' => '{"not": {"object_of_schemas": {"foo": {"id": "leaked.json", "type": "integer"}}}}',
'expectedUris' => [],
'unexpectedUris' => ['http://example.org/root/leaked.json'],
];

yield 'an id under a keyword holding a single schema is an identifier' => [
'schema' => '{"not": {"id": "real.json", "type": "null"}}',
'expectedUris' => ['http://example.org/root/real.json'],
'unexpectedUris' => [],
];

yield 'an id under a keyword holding a tuple is an identifier' => [
'schema' => '{"items": [{"id": "first.json", "type": "null"}]}',
'expectedUris' => ['http://example.org/root/first.json'],
'unexpectedUris' => [],
];

yield 'an id under the Draft 3 extends keyword holding a schema is an identifier' => [
'schema' => '{"extends": {"id": "base.json", "type": "object"}}',
'expectedUris' => ['http://example.org/root/base.json'],
'unexpectedUris' => [],
];

yield 'an id under the Draft 3 extends keyword holding a list is an identifier' => [
'schema' => '{"extends": [{"id": "base.json", "type": "object"}]}',
'expectedUris' => ['http://example.org/root/base.json'],
'unexpectedUris' => [],
];

yield 'an id in a schema of the Draft 3 disallow keyword is an identifier' => [
'schema' => '{"disallow": ["string", {"id": "disallowed.json", "type": "integer"}]}',
'expectedUris' => ['http://example.org/root/disallowed.json'],
'unexpectedUris' => [],
];

yield 'an id in a schema of the Draft 3 type keyword is an identifier' => [
'schema' => '{"type": ["null", {"id": "typed.json", "type": "string"}]}',
'expectedUris' => ['http://example.org/root/typed.json'],
'unexpectedUris' => [],
];
}

/**
Expand Down Expand Up @@ -530,6 +600,29 @@ public function refBesideIdProvider(): \Generator
yield 'draft 2019-09' => [DraftIdentifiers::DRAFT_2019_09, 'http://example.org/root/sub/target.json#'];
}

/**
* A $ref can be reached through a pointer into any keyword, known or not, so expandRefs()
* must expand it there too, or it no longer resolves against the document's base URI.
*/
public function testRefInsideAnUnknownKeywordIsStillExpanded(): void
{
$schema = json_decode(<<<'JSON'
{
"definitions": {"int": {"type": "integer"}},
"properties": {"a": {"$ref": "#/unknown"}},
"unknown": {"$ref": "#/definitions/int"}
}
JSON
, false);
$data = json_decode('{"a": "x"}', false);

$validator = new Validator();
$validator->validate($data, $schema);

$this->assertFalse($validator->isValid());
$this->assertSame('type', $validator->getErrors()[0]['constraint']['name']);
}

public function testNoDoubleResolve(): void
{
$schemaOne = json_decode('{"id": "test/schema", "$ref": "../test2/schema2"}');
Expand Down