Skip to content

Add support for cross-file $ref resolution - #502

Open
mathecruz wants to merge 2 commits into
Apitomy:mainfrom
mathecruz:issues/499
Open

mathecruz wants to merge 2 commits into
Apitomy:mainfrom
mathecruz:issues/499

Conversation

@mathecruz

@mathecruz mathecruz commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds support for resolving $refs that point at other local files (e.g. ./common-spec.yaml#/components/schemas/Pet), not just same-document refs.

Previously every consumer (e.g. quarkus-openapi-generator) had to pre-flatten multi-file specs themselves before handing a single JSON document to this library.

Closes #499

@EricWittmann EricWittmann 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 this. The approach is sound: a new FileReferenceResolver is plugged into Library.dereferenceDocument after the document is converted to 3.1 and before pre-processing. The change is small, and nothing happens unless the spec is loaded from a local file. The issues below should be fixed before merging.

Must fix

  1. The generated META-INF/openapi.json still contains the external $ref. The expected output shows "$ref": "./multi-file-common.json#/components/schemas/Pet" copied unchanged into the generated project. multi-file-common.json isn't in that project, so anything that serves this file at runtime (e.g. MicroProfile OpenAPI / Swagger UI) will hit a broken reference. Either write out the dereferenced document, or state this limitation explicitly and add a test for it.

  2. openApiDocBaseDir can be left over from an earlier load. Only setOpenApiDocument(URL) sets it. If the same OpenApi2JaxRs instance is later given a String or InputStream, the old directory is reused and refs resolve against the wrong place. Reset it to null in those methods, or add an explicit setBaseDir(Path) so String/InputStream callers such as quarkus-openapi-generator can also use this feature. As written, the main use case from #499 only works through the URL path.

  3. Load failures are silently ignored. loadDocument catches IOException | RuntimeException and returns null. A missing file, a YAML typo or a non-object root (the ObjectNode cast) all end up as an unresolved ref, and the user gets confusing generated code later instead of an error. At minimum log a warning with the path and the cause; failing fast is probably better.

Should fix

  1. Tests only cover the simplest case. The Javadoc says it supports YAML, refs that chain across files and directories, files that contain only a fragment (no openapi header), and whole-file refs. The single test is one JSON file pointing at a sibling JSON file. Please add tests for:

    • a YAML external file
    • a nested relative ref from a subdirectory (this is what the base-dir tagging exists for)
    • a fragment-only file
    • a ref to a file that doesn't exist
    • two files that reference each other (the cache should prevent infinite recursion; confirm dereferenceDocument handles it)
  2. Base-dir tagging may not survive the import. Nested refs depend on node attributes surviving when the content is imported or copied into the main document. The Javadoc says they do, but nothing tests it. If the library copies nodes rather than re-parenting them, the tags are lost and nested refs quietly fall back to the root directory. This needs a test (see item 4).

  3. Refs can reach any file on disk. A ref like ../../../../etc/passwd is read without restriction. That's low risk for local codegen, but it matters if this ever runs on user-supplied specs on a server. Consider limiting refs to stay under rootBaseDir, or document the behaviour.

Nits

  • In FileReferenceResolver, @author [email protected] looks copied from another file; it should probably be you.
  • The isRemote regex is compiled on every call; make it a static final Pattern.
  • The Javadoc on dereferenceExternalRefs has an empty @param document, and resolveBaseDir has a trailing blank Javadoc line.
  • The test fixtures mix versions (entry file is 3.0.2, common file is 3.1.0). That's fine and arguably a good test, but a short comment saying it's deliberate would help.

- Write the dereferenced, self-contained spec to META-INF/openapi.json
- Reset the base dir when the document is set from a String/InputStream
  and add setOpenApiDocumentBaseDir(Path) for those callers
- Fail fast with ExternalReferenceException on unresolvable file refs
- Rewrite nested refs relative to the root dir instead of tagging nodes,
  since inlined nodes are copied and lose their attributes
- Normalize root refs so mutually referencing files aren't imported twice
- Support whole-file refs, named after the file
- Restrict refs to the document's directory by default
  (configurable via setExternalRefsRootDir(Path))
- Add tests for YAML, nested, fragment-only, whole-file, missing,
  cyclic and out-of-root refs

Signed-off-by: Matheus Cruz <[email protected]>

@EricWittmann EricWittmann 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 update. Every item from my previous review has been addressed, and the redesign is a clear improvement: refs are now rewritten relative to the root directory when each file loads, instead of relying on node attributes. Error handling now stops generation early, there is a limit on which directory refs can reach, and the new tests are thorough. Two more things need fixing before this can be merged.

Must fix

  1. CI fails on Java 17 and 21. OpenApi2JaxRsTest.testGenerateFull_MultiFileExternalRef fails on the new fixture _expected-multi-file/generated-api/pom.xml. It expects jakarta.enterprise.cdi-api 4.1.0 and microprofile-openapi-api 4.1.1, but the template generates 5.0.0 and 4.2, as all the other expected fixtures do. It looks like the fixture was generated against an older template, so regenerating it should fix this. The branch is also a few commits behind main; it merges cleanly, but please rebase.

  2. Internal refs inside a whole-file ref fail to resolve. Take a schema file referenced as a whole ($ref: ./w/Owner.yaml) that has an internal ref:

    type: object
    properties:
      addr: { $ref: "#/$defs/Addr" }
    $defs:
      Addr: { type: object, properties: { city: { type: string } } }

    rewriteRefs turns the inner ref into w/Owner.yaml#/$defs/Addr. That ref doesn't have the whole-file prefix, so it goes to resolveFragment, which reads the raw schema as an OpenAPI document and can't find it:
    ExternalReferenceException: Could not resolve $ref 'w/Owner.yaml#/$defs/Addr': fragment '#/$defs/Addr' was not found in the referenced file.
    The same applies to any #/... ref inside a file that is referenced as a whole. Standalone JSON Schema files often use $defs, so please fix this (e.g. resolve fragments inside whole-file content against the wrapped synthetic node) and add a test.

Should fix

  1. rewriteRefs also rewrites data that isn't a reference. It walks every object, so a literal value like example: {"$ref": "literal-data"} comes out as "x/literal-data#/__whole_file__/literal-data". Please skip example, examples, default, const, enum and x-* values.

  2. The error for a missing file can be wrong. In checkAllowed, a file that doesn't exist is compared by its normalized path against allowedRootDir.toRealPath(). If the allowed directory is under a symlink (e.g. macOS /tmp → /private/tmp), a missing file is reported as "outside of the allowed directory" instead of "file not found". Resolving the real path of the nearest existing parent would fix this.

  3. Using the API depends on call order. setOpenApiDocumentBaseDir only works if called after setOpenApiDocument(String/InputStream), because those reset it. This is documented, but an overload such as setOpenApiDocument(String content, Path baseDir) would be harder to misuse for callers like quarkus-openapi-generator.

  4. Behaviour change for existing callers. Callers using setOpenApiDocument(URL) with a file: URL will now fail generation on refs that were ignored before. When anything is resolved, the generated openapi.json is now re-serialized OpenAPI 3.1 JSON instead of the original text. Both seem reasonable, but they should be called out in the release notes.

Nits

  • In dereference, rewriteRef(ref, rootBaseDir.resolve("_")) passes a placeholder file name so that getParent() returns the root directory. A helper that takes the base directory directly would make this clearer.
  • Two whole-file refs with the same file name (e.g. a/Pet.yaml and b/Pet.yaml) are handled correctly by the data model (they become Pet1 and Pet2). The resulting class names aren't obvious, though, so a short note in the docs would help.

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.

Support OpenAPI specs split across multiple files (cross-file $ref resolution)

2 participants