Skip to content

Reject cyclic $ref in schema validation - #434

Merged
vstakhov merged 2 commits into
vstakhov:masterfrom
Mohil-Ahuja:fix-389-schema-ref-cycle
Oct 29, 2026
Merged

vstakhov merged 2 commits into
vstakhov:masterfrom
Mohil-Ahuja:fix-389-schema-ref-cycle

Conversation

@Mohil-Ahuja

Copy link
Copy Markdown
Contributor

Fixes #389.

A $ref that leads back to a schema already being followed for the same object, like {"$ref": "#"} or two definitions pointing at each other, made ucl_schema_validate() recurse until the stack overflowed. Following a $ref consumes none of the object, so nothing ever ended the recursion.

ucl_schema_validate() and the three helpers that call it now pass along a chain of the $refs being followed, kept on the stack. When a $ref resolves to a schema that is already in the chain for the same object, validation fails with UCL_SCHEMA_INVALID_SCHEMA ("cyclic reference: #"). Recursion that descends into the object is unaffected: the "root pointer ref" cases in ref.json, where foo refers back to #, still validate nested data.

Two cases added to tests/schema/ref.json: a self reference, and two definitions that refer to each other (valid when the data never reaches them, invalid when it does). Without the change test_schema < tests/schema/ref.json segfaults; with it, every file in tests/schema/ passes.

A schema whose $ref leads back to itself without consuming any of the
object, such as {"$ref": "#"}, made ucl_schema_validate() recurse
until the stack was exhausted.

Keep a chain of the $refs being followed, on the stack, and fail with
UCL_SCHEMA_INVALID_SCHEMA when a $ref resolves to a schema that is
already being followed for the same object. Recursive schemas that
descend into the object, like the root pointer ref tests, are not
affected.

Fixes vstakhov#389
@Mohil-Ahuja

Copy link
Copy Markdown
Contributor Author

@vstakhov gentle ping on this one when you have a moment. It still merges cleanly. Happy to change anything.

A schema reached through a $ref is evaluated under the root its local
refs resolve against, and that root changes when the chain crosses an
external ref. A schema object shared between the root document and an
ext_refs entry can therefore be reached twice for the same object
under different roots without any cycle, which the (schema, obj) key
wrongly rejected. Include the root in the frame; the set of roots is
still finite, so cycles are still caught.

Add a C regression test for the shared case and for a real cycle that
alternates between two roots, and align the new refs parameters with
clang-format.
@vstakhov
vstakhov merged commit 1778e38 into vstakhov:master Oct 29, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Stack overflow in JSON schema validation with cyclic $ref

2 participants