Repository navigation
feat: patch specs and policies via config - #409
Conversation
Operators can now adapt an app's API specs and access control policies in config overlays without restating them: - `api.specs` and `security.access_control.policies` accept mappings of names to entries (named entries), besides lists; overlays merge entries by name, and `null` removes one. Overlays switching a non-empty list to named entries, or removing unknown entries, are rejected on startup. - `api.specs[].patches`: YAML/JSON files or inline mappings deep-merged into a spec after `path` and `append`, before `add_operation_fields` and `add_security_fields`. Applied patches are logged; operations that lose authentication or access control are warned of; specs made invalid by patches fail with a clear error. - Named policy rules are logged on startup; errors name invalid rules. Lists keep working as before. Refs #396 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add named entries to the configuration overview, named specs and spec patches (with a warning banner) to the API page, named policy rules and the recipe "require login for all reads except /service-info" to the access control guide, and use a named spec in the config template. Refs #396 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review findings: - Compare protections with path items given via local `$ref` resolved (as Connexion does) and with `add_operation_fields` applied, so that patches cannot hide public operations behind references or fields. - Also warn of new or renamed public operations, path items referring to other files, and changed security schemes. - Wrap any error registering a patched spec in a ValueError naming it. - Keep `access_control.policies` a list (names are kept separately and exposed via `named_policies`), so that code reading the rules works with named rules, too; one validation loop for both forms. - Docs: what the warnings cover, removing all named rules. Refs #396 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Round-2 review findings: - Patches setting fields of path items defined via `$ref` fail on startup: Connexion replaces such fields with those of the referenced object, so a patch adding security would silently not take effect. - Path item references that cannot be resolved to a mapping are listed (and warned of when added) instead of skipped. - Only invalid specs are wrapped in a ValueError; other registration errors keep their type and are logged with a hint to the patches. - `named_policies` returns None if the rules changed after validation; registration uses it instead of the private names. - Iterate operations of a path item via a helper. Refs #396 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThis PR enables operators to modify individual API specifications and access-control policies through composable configuration overlays, adds ordered OpenAPI patching with extensive safety checks and diagnostics, normalizes the new forms for existing runtime code, and documents tested deployment patterns. Sequence diagram for patched OpenAPI registrationsequenceDiagram
participant Config as ConfigParser
participant Register as register_openapi
participant Loader as _load_patch
participant Merge as deep_merge
participant Connexion as Connexion
Config->>Register: Provide SpecConfig with patches
Register->>Register: deepcopy unpatched specification
loop Each patch
Register->>Loader: _load_patch(patch)
Loader-->>Register: Mapping patch
Register->>Merge: deep_merge(specification, patch)
Merge-->>Register: Patched specification
end
Register->>Register: _add_operation_fields(patched_specification)
Register->>Register: _warn_weakened(unpatched, patched)
Register->>Connexion: add_api(specification=patched_specification)
Connexion-->>Register: Registered API or InvalidSpecification
Sequence diagram for named policy registrationsequenceDiagram
participant Config as AccessControlConfig
participant Register as register_casbin_enforcer
participant Policies as _add_policies
participant Adapter as CasbinAdapter
Config->>Register: Provide policies and named_policies
Register->>Policies: _add_policies(adapter, policies, names)
Policies->>Policies: validate_rule(ptype, rule, adapter.model)
Policies->>Adapter: set_configured_policies(policies)
Policies-->>Register: Named policy rules applied
Flow diagram for configuration overlay normalizationflowchart LR
Base[Base configuration] --> Merge[ConfigParser deep_merge]
Overlay[Config overlay] --> Merge
Merge --> Named{Named specs or policies?}
Named -->|yes| Validate[Validate names, removals, and list-to-map changes]
Named -->|no| Model[Validate existing list form]
Validate --> Model[Normalize named entries to lists]
Model --> Runtime[Existing runtime configuration]
File-Level Changes
Possibly linked issues
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 #409 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 27 27
Lines 2510 2708 +198
==========================================
+ Hits 2510 2708 +198
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:
|
There was a problem hiding this comment.
Hey - I've found 8 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/security/access_control/register_access_control.py" line_range="385" />
<code_context>
+ if names is None:
+ raise
+ raise ValueError(f"Invalid policy rule '{names[index]}': {exc}") from exc
adapter.set_configured_policies(policies)
+ if names is not None:
+ logger.info("Named policy rules applied: %s", ", ".join(names) or "none")
</code_context>
<issue_to_address>
**Policy updates expose mixed rules**
When multiple app instances reconcile different named policy sets concurrently, or a database error interrupts one reconciliation while another instance is serving requests, concurrent instances reconciling different named policy sets, or a reconciliation interrupted by a database error, leave the collection with a mixture of old and new rules. `get_enforcer()` loads rules from that shared collection for requests, so serving instances can authorize or deny requests against this unintended policy set until reconciliation succeeds.
Reconcile configured rules as an atomic, serialized replacement so requests observe either the previous complete rule set or the new complete rule set.
</issue_to_address>
### Comment 2
<location path="foca/api/register_openapi.py" line_range="169" />
<code_context>
+ return path_item
+ target: Any = spec
+ for token in ref[2:].split("/"):
+ key = token.replace("~1", "/").replace("~0", "~")
+ target = target.get(key) if isinstance(target, dict) else None
+ if not isinstance(target, dict):
</code_context>
<issue_to_address>
**Weakened referenced routes go unwarned**
When a path-item `$ref` contains a percent-encoded local fragment token and a patch weakens the referenced operation, `_resolve_path_item` leaves the token encoded, so it cannot find the referenced object. `_protections` then compares the same unresolved reference before and after patching and emits no weakening warning, even though the route is weakened.
Percent-decode the URI fragment before decoding and resolving its JSON Pointer tokens.
Also at `foca/api/register_openapi.py:170`.
</issue_to_address>
### Comment 3
<location path="foca/api/register_openapi.py" line_range="209-210" />
<code_context>
+ protections[path] = {f"reference {resolved['$ref']}"}
+ for method, operation_object in _iter_path_item(resolved):
+ protected = set()
+ if _requires_authentication(
+ operation_object.get("security", spec.get("security"))
+ ):
+ protected.add("security")
</code_context>
<issue_to_address>
**Invalid security raises raw TypeError**
When a specification has a non-iterable `security` value, `_requires_authentication` calls `all(security)` and raises `TypeError` during warning analysis, before `app.add_api` can translate the invalid specification into the documented `ValueError`.
Validate `security` before warning analysis and raise the documented invalid-specification error for non-iterable values.
</issue_to_address>
### Comment 4
<location path="foca/models/config.py" line_range="902" />
<code_context>
+ """Get the value of a nested section, or `None` if it is not set."""
+ for key in keys:
+ if not isinstance(data, dict):
+ return None
+ data = data.get(key)
+ return data
</code_context>
<issue_to_address>
**Policy names become mismatched**
When a caller replaces, edits, or reorders policies after validation without changing their count, `named_policies` pairs the saved names with the current rules by position, so registration logs or reports an invalid rule under the wrong name.
Keep policy names associated with the current rules, or invalidate the saved names when policy contents or order changes.
</issue_to_address>
### Comment 5
<location path="foca/api/register_openapi.py" line_range="287-288" />
<code_context>
+ if isinstance(patch, dict):
+ return patch
+ content = ConfigParser.parse_yaml(patch)
+ if content is None:
+ return {}
+ if not isinstance(content, dict):
+ raise ValueError(f"Patch '{patch}' is not a mapping")
</code_context>
<issue_to_address>
**Null patches are silently ignored**
When a patch file contains YAML or JSON `null` rather than being empty, `_load_patch` treats the parsed `None` as an empty patch, so `_apply_patches` accepts it without changing the specification; callers get the original specification with no warning that the patch was a no-op.
Distinguish an empty file from an explicit `null` value and reject `null` as a non-mapping patch.
</issue_to_address>
### Comment 6
<location path="foca/api/register_openapi.py" line_range="322" />
<code_context>
+ content = _load_patch(patch)
+ patch_paths = content.get("paths")
+ if isinstance(patch_paths, dict):
+ patched_paths.update(
+ path
+ for path, path_item in patch_paths.items()
</code_context>
<issue_to_address>
**Removed fields still block references**
When one patch sets fields on a path item, a later patch sets that path item to `null`, and another patch sets only its `$ref`, `patched_paths` retains the path after a later patch replaces its path item with `null`, so a subsequent patch that sets only `$ref` still triggers the override error even though no sibling fields remain; startup fails for a valid final specification.
Check whether fields actually remain beside `$ref` in the final path item before rejecting it.
</issue_to_address>
### Comment 7
<location path="tests/api/test_register_openapi.py" line_range="525-526" />
<code_context>
+ patch: dict[str, Any],
+ ) -> None:
+ """Other patches are not warned of."""
+ self._patched(monkeypatch, patch)
+ assert not self._warnings(logs)
+
+ def test_weakened_operation_fields(
</code_context>
<issue_to_address>
**Deletion test misses ignored patch**
When the `None` path-item patch is ignored, `test_not_weakened` checks only that no warning was emitted, so an implementation that ignores the deletion passes while callers retain the route they asked to remove.
Assert that the patched specification no longer contains the deleted path.
</issue_to_address>
### Comment 8
<location path="foca/api/register_openapi.py" line_range="396" />
<code_context>
+ # Apply patches
+ label = (
+ f"'{spec.name}'"
+ if spec.name is not None
+ else ", ".join(str(path) for path in list_specs)
</code_context>
<issue_to_address>
**Successful spec logs omit names**
When a named specification registers successfully without patches, when a named specification registers successfully without patches, `label` is never logged; the success message logs only `list_specs`, so operators cannot identify the specification by its configured name.
Include the specification label or name in the successful API registration log.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 7 findings to address first, and an overlay can remove an operation’s authentication requirement or add a broad policy that grants access, exposing protected operations or data while deployed. Reverting stops the altered rules from applying going forward, but cannot undo access or data exposure that already occurred.
Blocking findings: foca/security/access_control/register_access_control.py:385, foca/api/register_openapi.py:169, foca/api/register_openapi.py:210, foca/models/config.py:902, foca/api/register_openapi.py:288, and 2 more
- Percent-decode JSON pointer tokens of path item references. - Ignore invalid `security` values when comparing protections (Connexion rejects them) instead of failing with a TypeError. - Bind policy names to their rules: `named_policies` is None if the rules were reordered or changed after validation. - Patch files containing `null` fail like other non-mappings; empty files and files with comments only stay no-ops. - Only reject path item references with sibling fields left in the patched spec, so fields removed by later patches do not count. - Log the spec name after registering a spec. Refs #396 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refs #396 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Closes #396.
Operators can adapt an app's API specifications and access control policies in config overlays, without forking or restating them:
api.specsandsecurity.access_control.policiesaccept a mapping of names to entries, besides the list form. FOCA's config merge already merges mappings, so overlays add, change (merge) or remove (null) single entries by name. Startup fails with a clear error if a file switches a section from a non-empty list to named entries (the list's entries would be lost silently), removes an entry that is not set (e.g., a misspelled name), or changes a spec that is not set (entry withoutpath). Both are normalized to lists after validation (newSpecConfig.name, unique; names of policy rules viaAccessControlConfig.named_policies), so code readingconfig.api.specsorconfig.security.access_control.policiesis unaffected.api.specs[].patcheslists YAML/JSON files or inline mappings, deep-merged into the spec in order afterpathandappend, beforeadd_operation_fields/add_security_fields, with the same rules aspath(mappings merged, other values replaced). Relative paths resolve like those ofpath.security: [], empty alternatives, inherited rootsecurityremoved,x-foca-access-control: false,x-foca-self-service: true), new or renamed operations that are public, path items referring to other files, and changed security schemes; protections are compared withadd_operation_fieldsapplied and local path-item$refs resolved as Connexion does. Startup fails if a spec is invalid after patches (ValueError: API spec '<name>' is invalid after applying patches: ...) or if patches set fields of a path item defined via$ref(Connexion would silently replace them); other registration errors keep their type and are logged with a hint to the patches. Named policy rules are validated with their name in the error and logged (Named policy rules applied: ...)./service-info; spec patch plus aGETrule for any authenticated user, limited to the app's base path so it does not open the permissions API) in the access control guide. The config template uses a named spec.Configs without names or patches behave exactly as before.
Design choices
nullremoval falls out naturally; (2) it is consistent with FOCA's existing config style (db.dbs,collections,group_mapping); (3) it follows Helm's guidance to prefer maps over lists for overridable values, and composes with Helm's own merging of several values files, which replaces lists before FOCA ever sees them. Named list entries would only work in FOCA's merge, not in Helm's. One mechanism for both sections instead ofnamefor specs and something else for policies.path(as the issue says):nullreplaces values, it does not delete keys (unlike JSON Merge Patch, RFC 7386). Deleting keys can be added later if needed.pathand all other config paths (the issue said "relative to the config file declaring them, as forpath", butpathresolves against the base config file); overlays typically use absolute paths of mounted files or inline patches. Documented.$reftargets are not loaded (a changed or added external reference is warned of instead). The docs say to review patches like code.docs/deployment.mdstill says "Lists are replaced, not merged" forsecurity.access_control.policies; left untouched because another PR (feat(chart): Gateway API and ingress guides #397) works on the deployment docs; a pointer to named entries can be added there.How it was verified
coverage run -m pytest+coverage report(MongoDB 7.0 via mise on port 12345, Python 3.13): 1651 passed, 100% coverageuv pip install --resolution lowest-direct): affected test modules passruff check,ruff format --check,mypy: cleanmkdocs build --strict(Python 3.12 docs venv): cleantests/config/test_config_parser.py; model validation intests/models/test_config.py; patch merge order, JSON/empty files, logs, weakening warnings, invalid specs/files intests/api/test_register_openapi.py; named rules intests/security/access_control/test_register_casbin_enforcer.py; the recipe end to end (Focawith base config + overlay, requests with and without tokens, permissions API not opened) intests/test_recipes.py.Declined review findings
Two rounds of adversarial-reviewer + quality-reviewer; all high/medium findings and most lows fixed (path-level
$refhiding public operations, fields next to$refsilently overridden, protections fromadd_operation_fields, new/renamed public routes, scheme changes,policiestype staying a list, duplicated policy validation, stale names). Declined:_requires_authenticationfromenforcementintoregister_openapi(quality, medium): same pattern as the existing import of_check_routes_enforcedthere; making it public would widen FOCA's API for an internal helper._iter_operationsinto_iter_routescallers (quality, low): kept the wrapper so existing call sites and tests stay unchanged.Sourcery: 7 of 8 comments fixed in 8b4b312 (percent-encoded
$reftokens, invalidsecurityvalues, names bound to reordered rules,nullpatch files, fields removed by later patches, log naming the spec; a test case claiming to delete a route withnullwas dropped sincenulldoes not delete keys). Declined:set_configured_policiesbehaviour that this PR does not change; changing it would alter startup semantics for all apps and belongs in a separate issue.Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Enable operators to customize API specifications and access-control policies through safe, composable configuration overlays without forking application configuration.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: