Repository navigation
feat(spec): let null remove keys in spec patches - #763
Conversation
Patches of API specifications are now merged as a JSON Merge Patch (RFC 7396): null removes a key, at any depth. This lets patches turn an API key scheme into an HTTP bearer scheme and replace a reference to a URL by a local path item, which Connexion otherwise rejects or fetches. Merged specification files can opt in to the same via the new SpecConfig.merge_null_removes (off by default, so that null values such as default: null keep working). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Add the section on merging specification files, describe null in patches, and add the migration guide for 0.23.0. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Patches that remove fields of a path item defined via $ref, while keeping the reference, have no effect, as Connexion uses the fields of the referenced object; FOCA now refuses to start, as for fields set next to a $ref. Also merge spec files with deep_merge only, assert the default of merge_null_removes and rewrap the edited docs. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Decide after each patch whether it removes fields that only the referenced object has: also when the patch restates or adds the $ref, not when it removes fields set next to the reference, and forget the path once a later patch removes the path item or gives it a $ref. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Reviewer's GuideImplementationImplement RFC 7396 null-removal merging and track ineffective removals beside referenced path items across specification layers.
ConfigurationAdd the opt-in
Expose the new migration guide in the documentation navigation.
DocumentationDocument null-removal behavior for patches and merged specification files, including the 0.23.0 migration guidance and links.
TestsCover null-removal merging, configuration defaults, and rejection or acceptance of removals around referenced path items.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #763 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 74 74
Lines 9448 9472 +24
=========================================
+ Hits 9448 9472 +24
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit f495870 #762 feat(spec): let null remove keys in spec patches · 4 of 4 met
|
There was a problem hiding this comment.
Hey - I've found 5 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/api/register_openapi.py" line_range="415" />
<code_context>
+ if any(
+ key != "$ref"
+ and value is None
+ and not (isinstance(item_before, dict) and key in item_before)
+ for key, value in path_item.items()
+ ):
</code_context>
<issue_to_address>
**Referenced fields stay active**
When a patch removes a field already present beside a retained path-item `$ref`, and the referenced object also defines that field, `_track_removals()` skips the removal because the key exists in `item_before`, so the final guard accepts the path and Connexion restores the referenced field or operation; callers still see it.
Track null removals beside a retained `$ref` even when the removed key existed in the prior local path item.
</issue_to_address>
### Comment 2
<location path="foca/api/register_openapi.py" line_range="524" />
<code_context>
list_specs = [spec.path] if isinstance(spec.path, Path) else spec.path
- spec_parsed: dict[str, Any] = ConfigParser.merge_yaml(*list_specs)
+ spec_parsed: dict[str, Any] = ConfigParser.merge_yaml(
+ *list_specs, null_removes=spec.merge_null_removes
+ )
logger.debug("Parsed spec: %s", list_specs)
</code_context>
<issue_to_address>
**Merged removals leave routes active**
When `merge_null_removes` is enabled and a later spec file sets a path-item field to `null` while retaining that path item's `$ref`, `ConfigParser.merge_yaml()` removes only the local field, and `register_openapi()` does not apply the referenced-path removal guard to merged files; Connexion restores the field from the reference, so the route remains available.
Apply the referenced-path removal tracking and guard to merged specs before passing them to Connexion.
Also at `docs/configuration/api.md:87`.
</issue_to_address>
### Comment 3
<location path="foca/api/register_openapi.py" line_range="404" />
<code_context>
+ """
+ for path, path_item in patch_paths.items():
+ if not isinstance(path_item, dict) or "$ref" in path_item:
+ removed_paths.discard(path)
+ if not isinstance(path_item, dict):
+ continue
</code_context>
<issue_to_address>
**Restated references revive removed operations**
When a patch removes a field from a referenced path item and a later patch restates the same `$ref` without restoring that field, `_track_removals()` discards the pending removal marker when the later patch includes `$ref`, so the final guard accepts the path and Connexion restores the removed field or operation; callers still see it.
Keep the removal marker when a later patch repeats the same `$ref`, clearing it only when a later patch supersedes the removal.
</issue_to_address>
### Comment 4
<location path="foca/api/register_openapi.py" line_range="462" />
<code_context>
)
- patched = deep_merge(patched, content)
+ _track_removals(removed_paths, patch_paths, before, patched.get("paths"))
paths = patched.get("paths")
overridden = sorted(
path
</code_context>
<issue_to_address>
**Superseded removals still reject startup**
When one patch removes a field beside a `$ref`, a later patch removes the whole `paths` mapping with `paths: null`, and another patch restores the same path as a ref-only item, `_track_removals()` is not called, so the prior entry in `removed_paths` survives; if a later patch restores that path as a ref-only item, the final guard raises `ValueError` even though the removal was superseded.
Clear removal-tracking state when a patch removes or replaces the entire `paths` mapping.
</issue_to_address>
### Comment 5
<location path="tests/api/test_register_openapi.py" line_range="736" />
<code_context>
+ ) -> None:
+ """Removals are fine once later patches replace the reference."""
+ spec = self._patched(monkeypatch, *self.REFERENCE, *patches)
+ assert set(spec["paths"]["/pets"]) == expected
+
+ def test_removed_field_next_to_reference(
</code_context>
<issue_to_address>
**Replacement reference goes unchecked**
When the patch gives `/pets` a new `$ref`, when a later patch changes `/pets` from `#/x-items` to `#/x-other`, `test_removed_next_to_reference_replaced` only checks the key set at line 736, so it passes if the old reference remains and the path still resolves to the wrong operations.
Assert the complete path item, including the expected `$ref` target, for the replacement case.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 5 findings to address first, and because patches now treat null as removal, a patch can remove an operation’s security requirement or access-control setting and let requests through without the intended protection. Reverting restores the prior behavior, but it cannot undo access that occurred while the weakened specification was active.
Blocking findings: foca/api/register_openapi.py:415, foca/api/register_openapi.py:524, foca/api/register_openapi.py:404, foca/api/register_openapi.py:462, tests/api/test_register_openapi.py:736
Reject every removal next to a $ref that is kept, also of fields set next to it, as the referenced object may have them, too. Keep tracking a removal when a later patch restates the same $ref, and stop when a later patch removes all paths. Merged spec files with merge_null_removes get the same guard, so ConfigParser.merge_yaml() needs no option of its own. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Summary
Spec patches can now remove keys:
nullin a patch removes the key, at any depth, as in a JSON Merge Patch (RFC 7396). Merged spec files (pathwith several files) can opt in to the same with the newSpecConfig.merge_null_removes(off by default).This covers the two cases from trs-filer#128 (TRS 2.0.2):
BEARERAPI key scheme into an HTTP bearer scheme (type: http,scheme: bearer,name: null,in: null); without removingnameandin, Connexion rejects the merged scheme;$refof/service-infoby a local path item ($ref: nullnext toget); Connexion otherwise fetches the referenced file on every start.Changes:
deep_merge()gets a keyword-onlynull_removesoption (RFC 7396:nullremoves keys, removing unset keys is a no-op,nullin mappings that replace non-mappings is dropped, lists are kept as they are). Config files keep the current behaviour (null_removes=False)._apply_patches()merges withnull_removes=True._warn_weakened()is unchanged and still warns: removing a scheme's fields changes the schemes, and a path item that replaces a reference counts as a new operation, which is listed if it is public; removingsecuritywithnullis listed likesecurity: [].ConfigParser.merge_yaml()now merges withdeep_merge()only (the Addict loop behaved the same; checked by the round-2 reviewer on 2,955 file combinations). Withmerge_null_removes,register_openapi()merges the files ofpaththrough the same function as patches (_merge_layers()), so both get the guard below.$refin path items now also covers removals: a patch (or, withmerge_null_removes, a later file) that removes (null) a field of a path item that keeps its$refwould have no effect, as Connexion uses the referenced object (e.g.delete: nullto drop an operation), so FOCA refuses to start, as it does for fields set next to a$ref. Removing the reference itself ($ref: null) is fine; a later layer that removes the path item or allpaths, or gives it another$ref, clears it; restating the same$refdoesn't (_track_removals()). Removing a stray field that was set next to a$refis rejected too, as the referenced object may have it: such fields are ignored by Connexion anyway.docs/configuration/api.md, newdocs/migration-0.23.md(linked from the changelog, index, README and nav), docstrings ofSpecConfig.Merged spec files: opt-in
The issue asked whether merged spec files should get the same semantics as an opt-in or not at all. I made it an opt-in (
merge_null_removes, off by default):nullis a legitimate value in specifications (default: null,example: null), and additions files would otherwise silently lose it.patchesis meant for operators, and an operator's overlay that setspatchesfor a named spec replaces the whole list, so removals that an app put in its ownpatcheswould be lost without notice. With the option, an app like trs-filer putsname: null,in: nulland$ref: nullinto itsadditions.openapi.yamland setsmerge_null_removes: true.Behaviour change
Patches that set a value to
nullnow remove the key instead. This is noted indocs/migration-0.23.md, with the way out (set such values in a file ofpath). Patches that set a whole path item tonullto replace it in a later patch keep working (existing testtest_reference_after_removed_fields). Curated release notes (docs/releases/0.23.0.md) are added by the release-prep PR, as the contributing guide says; the item for them: "Patches of API specifications remove keys withnull(JSON Merge Patch), and merged specification files can opt in viamerge_null_removes(#762, #PR)".Verification
Tests written first; the new end-to-end tests failed before the change (
$refnext to fields rejected,merge_yaml()withoutnull_removes) and pass after it.SpecConfig, files on disk) and Connexion's validation, without mockingadd_api()(tests/api/test_register_openapi.py::TestRemovingKeys): a minimal spec with an API key scheme and a/service-infopath item referring to a URL;requests.get);name/in, Connexion rejects it (ValueError"invalid after applying patches");null, nothing is fetched,GET /service-inforeturns 200,GET /petsreturns 401 (the bearer scheme validates tokens; Connexion ignores API key schemes withoutx-apikeyInfoFunc), and both warnings are logged (new public operation, changed schemes);merge_null_removes: trueworks; without the option Connexion rejects$ref: null.test_deep_merge_null_removes(9 cases),test_merge_yaml_null, a new case oftest_weakened_warned(security: null), themerge_null_removesdefault intests/models/test_config.py, and tests for removals next to$ref(rejected when ineffective, also with the$refrestated or added in the same patch or in a later one, and in merged files; accepted after the reference, the path item or all paths are removed or replaced).ruff format --check,ruff check,mypy,ast-grep scan(only the 2 existing warnings inexamples/),semgrep scan --config .semgrep --error,mkdocs build --strict,coverage run -m pytestwith MongoDB 7.0 on port 12345: 5006 passed, 2 skipped, coverage 100% (run before the last commit, which only touches_apply_patchesand its tests; after it,tests/api tests/config tests/models: 701 passed, the new helper fully covered).ruff,mypy,mkdocs build --strict,tests/api tests/config tests/models(702 passed; the changed modules covered except lines that other test directories cover).Declined review findings
Sourcery (5 medium findings on the removal guard and a test assertion): all fixed in f495870, threads answered.
Two rounds: adversarial + quality, then adversarial. Fixed: removals next to
$refsilently ineffective (round 1, medium) and its gaps (round 2, two mediums and a low); single merge loop inmerge_yaml(), model test of the default, grep hint in the migration guide, docs rewrapped (quality).operationId: showPetByIdof the test's/service-infooperation (quality, not raised as a finding): kept, as it routes to the existing petstore test controllers; a new controller only for the name adds nothing.nullin patches.Open questions
None.
Closes #762
🤖 Generated with Claude Code
https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV