Skip to content

Only treat schema bearing positions as identifier locations - #954

Open
Amoifr wants to merge 4 commits into
jsonrainbow:mainfrom
Amoifr:fix-949-schema-id-discovery
Open

Amoifr wants to merge 4 commits into
jsonrainbow:mainfrom
Amoifr:fix-949-schema-id-discovery

Conversation

@Amoifr

@Amoifr Amoifr commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Fixes #949

Problem

SchemaStorage walks a document looking for id / $id so it can register subschemas under their canonical URI. It descends into every member it meets, so an $id written in a position that holds data rather than a schema gets registered as though it identified a schema. When that value collides with a real $id elsewhere in the document, the fake one can win, and a $ref to that URI then resolves to the wrong schema.

That is exactly what unknownKeyword.json in the official suite pins down: an $id buried under an unknown keyword must not shadow the real one.

Cause

scanMembersForSubschemas() skipped enum and const by name. That covers two data positions out of many: default, examples and any unknown keyword were still descended into.

Fix

Instead of listing the positions to avoid, which is open ended, the scanner now only descends into positions that actually hold schemas. Two classification lists sit beside the existing SCHEMA_MAP_KEYWORDS:

  • SCHEMA_KEYWORDS, whose value is a schema (not, if, additionalProperties, and so on)
  • SCHEMA_ARRAY_KEYWORDS, whose value is a list of schemas (allOf, anyOf, prefixItems, and so on)

Everything else is data, and an id inside it identifies nothing.

Members of a schema map (properties, $defs, definitions, ...) remain schemas whatever their name, which is what the existing $parentProperty check already guaranteed: a subschema legitimately named enum is still traversed.

The classification is deliberately draft agnostic, since SchemaStorage is never told which dialect it is reading. A keyword counts if it holds schemas in any draft. That is also the safer direction: treating a keyword unknown to the current draft as a schema position is simply the behaviour every keyword had before.

Tests

Six cases added to subschemaRegistrationProvider(). Four fail without the source change (default, examples, an unknown keyword holding a list, an unknown keyword holding a map). The remaining two guard against over narrowing in the other direction, checking that an id under not and under an items tuple is still registered.

The six now obsolete unknownKeyword.json entries in shouldNotYieldTest() are removed.

Notes

expandRefs() carries the same enum / const special case. I left it untouched: the fixture does not exercise it, and measuring confirmed the scanner change alone is sufficient. Glad to align the two walkers in a follow up if you would prefer they agree.

One caveat on how far I could verify this. JsonSchemaTestSuiteTest currently yields no tests at all, because the upstream suite added a tests/v1/ directory that DraftIdentifiers::fromConstraintName() rejects, and PHPUnit reports that as a warning while still exiting 0. I opened #953 about it. To exercise the unknownKeyword cases here I skipped v1 locally, which is not part of this PR. With the suite unblocked that way, this change takes the failure count from 364 down to 354, repairing 6 suite cases plus the 4 new unit cases, and breaking none.

PHPStan reports no errors. Thanks for the library, and for the very readable SchemaStorage, which made this one pleasant to chase. 🙂

@DannyvdSluijs

Copy link
Copy Markdown
Collaborator

Hello @Amoifr

Thanks for the input on #953, I've just merged #956 which fixes the warning in the PHPUnit workflow. Skipping the v1 folder and fixing the broken tests already in main. Downside is this PR now has conflicts. Could you rebase/recreate the PR?

@Amoifr
Amoifr force-pushed the fix-949-schema-id-discovery branch from 545b1f0 to 8a6ba78 Compare September 16, 2026 07:29
@Amoifr

Amoifr commented Sep 16, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the quick fix in #956, and for the heads-up! Rebased on main. One thing worth mentioning: the two unknownKeyword.json skips this PR removed are now listed under optional/, so I removed those entries instead. Without that, the fix would have had no test covering it. The 6 cases pass now, and they fail if I revert the change.

@DannyvdSluijs DannyvdSluijs left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the additions. A few remarks and there was a merge conflict that should be addressed as well.

Comment thread src/JsonSchema/SchemaStorage.php Resolved
Comment thread src/JsonSchema/SchemaStorage.php Outdated
Comment on lines 255 to 257

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nitpick: This could use an update since the logic is changing.

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.

Updated in ce27bfd, it now points to holdsSchemas() instead of talking about enum and const.

Comment thread tests/JsonSchemaTestSuiteTest.php Outdated
@@ -711,12 +705,6 @@ private function shouldNotYieldTest(string $name): bool
'[draft2019-09/optional/format/uri-template.json]: format: uri-template: a space in a literal is invalid is expected to be invalid',
'[draft2019-09/optional/format/uri-template.json]: format: uri-template: a delete character in a literal is invalid is expected to be invalid',
// Optional unknown keyword: Not yet implemented

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nitpick: Seems like all below items are removed and the comment is left dangling. Could you remove it as well?

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.

Removed, thanks. The conflict was in that same block, so it went away with the rebase on main.

Comment thread src/JsonSchema/SchemaStorage.php Resolved

@DannyvdSluijs DannyvdSluijs left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I overlooked the expand refs also works inside data containers. I guess that change needs to be reverted.

@Amoifr
Amoifr force-pushed the fix-949-schema-id-discovery branch from b81e3c0 to 6796d2f Compare November 26, 2026 09:15
@Amoifr

Amoifr commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Rebased on main to resolve the conflict with #970 (which is also why CI never ran on the previous push). Its anchor handling is kept as is, expandRefs() is now identical to main, and the scan still uses holdsSchemas(). Full suite green locally. Ready for another look whenever you have a minute, thanks for your patience! 🙂

@Roman3349 Roman3349 left a comment

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.

Thanks for the fix! Two issues I'd address before merging, plus one pre-existing one that the PR makes more visible:

expandRefs() (pre-existing, SchemaStorage.php ~L147): it still descends into default, examples and unknown keywords. An $id there still shifts the base URI for $refs beneath it, although this PR says such an id "identifies nothing". And $ref strings inside default/examples data get rewritten into absolute pointers, so with CHECK_MODE_APPLY_DEFAULTS the rewritten value ends up in the user's data. Example: {"definitions":{"int":{"type":"integer"}},"properties":{"a":{"$ref":"#/x-wrap/inner"}},"x-wrap":{"$id":"http://other.invalid/s.json","inner":{"$ref":"#/definitions/int"}}}: the inner $ref becomes http://other.invalid/s.json#/definitions/int and validation tries a network fetch. The two walkers now disagree about what counts as a schema. Could be a follow-up issue.

* 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.

// 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.

@Amoifr

Amoifr commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

On expandRefs(): agreed, it's the other half of the same problem. This PR first skipped data positions there too, but that broke a $ref pointing into an unknown keyword (Danny's review), so it's back to main's behaviour. A follow-up issue sounds right, happy to open it with your example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Schema ids are discovered in annotation data and unknown keywords

3 participants