Repository navigation
Conversation
EricWittmann
left a comment
There was a problem hiding this comment.
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
-
The generated
META-INF/openapi.jsonstill 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.jsonisn'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. -
openApiDocBaseDircan be left over from an earlier load. OnlysetOpenApiDocument(URL)sets it. If the sameOpenApi2JaxRsinstance is later given aStringorInputStream, the old directory is reused and refs resolve against the wrong place. Reset it tonullin those methods, or add an explicitsetBaseDir(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. -
Load failures are silently ignored.
loadDocumentcatchesIOException | RuntimeExceptionand returnsnull. A missing file, a YAML typo or a non-object root (theObjectNodecast) 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
-
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
openapiheader), 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
dereferenceDocumenthandles it)
-
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).
-
Refs can reach any file on disk. A ref like
../../../../etc/passwdis 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 underrootBaseDir, or document the behaviour.
Nits
- In
FileReferenceResolver,@author [email protected]looks copied from another file; it should probably be you. - The
isRemoteregex is compiled on every call; make it astatic final Pattern. - The Javadoc on
dereferenceExternalRefshas an empty@param document, andresolveBaseDirhas a trailing blank Javadoc line. - The test fixtures mix versions (entry file is
3.0.2, common file is3.1.0). That's fine and arguably a good test, but a short comment saying it's deliberate would help.
Signed-off-by: Matheus Cruz <[email protected]>
- 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
left a comment
There was a problem hiding this comment.
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
-
CI fails on Java 17 and 21.
OpenApi2JaxRsTest.testGenerateFull_MultiFileExternalReffails on the new fixture_expected-multi-file/generated-api/pom.xml. It expectsjakarta.enterprise.cdi-api4.1.0andmicroprofile-openapi-api4.1.1, but the template generates5.0.0and4.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 behindmain; it merges cleanly, but please rebase. -
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 } } }
rewriteRefsturns the inner ref intow/Owner.yaml#/$defs/Addr. That ref doesn't have the whole-file prefix, so it goes toresolveFragment, 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
-
rewriteRefsalso rewrites data that isn't a reference. It walks every object, so a literal value likeexample: {"$ref": "literal-data"}comes out as"x/literal-data#/__whole_file__/literal-data". Please skipexample,examples,default,const,enumandx-*values. -
The error for a missing file can be wrong. In
checkAllowed, a file that doesn't exist is compared by its normalized path againstallowedRootDir.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. -
Using the API depends on call order.
setOpenApiDocumentBaseDironly works if called aftersetOpenApiDocument(String/InputStream), because those reset it. This is documented, but an overload such assetOpenApiDocument(String content, Path baseDir)would be harder to misuse for callers like quarkus-openapi-generator. -
Behaviour change for existing callers. Callers using
setOpenApiDocument(URL)with afile:URL will now fail generation on refs that were ignored before. When anything is resolved, the generatedopenapi.jsonis 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 thatgetParent()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.yamlandb/Pet.yaml) are handled correctly by the data model (they becomePet1andPet2). The resulting class names aren't obvious, though, so a short note in the docs would help.
Description
Adds support for resolving
$refsthat 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