Skip to content

feat: patch specs and policies via config - #409

Merged
uniqueg merged 7 commits into
devfrom
feat/396-config-patches
Oct 22, 2026
Merged

uniqueg merged 7 commits into
devfrom
feat/396-config-patches

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #396.

Operators can adapt an app's API specifications and access control policies in config overlays, without forking or restating them:

  • Named entries: api.specs and security.access_control.policies accept 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 without path). Both are normalized to lists after validation (new SpecConfig.name, unique; names of policy rules via AccessControlConfig.named_policies), so code reading config.api.specs or config.security.access_control.policies is unaffected.
  • Spec patches: api.specs[].patches lists YAML/JSON files or inline mappings, deep-merged into the spec in order after path and append, before add_operation_fields/add_security_fields, with the same rules as path (mappings merged, other values replaced). Relative paths resolve like those of path.
  • Safety: applied patches are logged (INFO). WARNINGs list operations that required authentication or were subject to access control before the patches but not after (security: [], empty alternatives, inherited root security removed, 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 with add_operation_fields applied 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: ...).
  • Docs: "Named entries" (configuration overview), "Named specifications" and "Patching specifications" with a danger banner (API page), named rules with a warning about broad rules and the recipe "Requiring login for reads" (all reads need a token except /service-info; spec patch plus a GET rule 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

  • Mappings instead of named list entries (strategic merge by key). The issue suggested either. I chose mappings for both sections because (1) FOCA's merge already merges mappings, so no new merge semantics are needed and null removal 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 of name for specs and something else for policies.
  • Merge rules of patches = rules of path (as the issue says): null replaces values, it does not delete keys (unlike JSON Merge Patch, RFC 7386). Deleting keys can be added later if needed.
  • Relative patch paths resolve against the base config directory, like path and all other config paths (the issue said "relative to the config file declaring them, as for path", but path resolves against the base config file); overlays typically use absolute paths of mounted files or inline patches. Documented.
  • Warnings are a safety net, not a guarantee: they cover the cases above; external $ref targets are not loaded (a changed or added external reference is warned of instead). The docs say to review patches like code.
  • docs/deployment.md still says "Lists are replaced, not merged" for security.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% coverage
  • Lowest direct dependencies (Python 3.11, pydantic 2.7.0, uv pip install --resolution lowest-direct): affected test modules pass
  • ruff check, ruff format --check, mypy: clean
  • mkdocs build --strict (Python 3.12 docs venv): clean
  • New tests: named entries via config files and overlays (change, add, remove, re-add, list replacing, error cases) in tests/config/test_config_parser.py; model validation in tests/models/test_config.py; patch merge order, JSON/empty files, logs, weakening warnings, invalid specs/files in tests/api/test_register_openapi.py; named rules in tests/security/access_control/test_register_casbin_enforcer.py; the recipe end to end (Foca with base config + overlay, requests with and without tokens, permissions API not opened) in tests/test_recipes.py.
  • CI: all checks pass (unit tests on Python 3.11-3.14 with MongoDB 7.0 and 8.0, lowest direct dependencies, integration, kind chart install, lint/type-check/build, Codecov patch/project, Read the Docs)

Declined review findings

Two rounds of adversarial-reviewer + quality-reviewer; all high/medium findings and most lows fixed (path-level $ref hiding public operations, fields next to $ref silently overridden, protections from add_operation_fields, new/renamed public routes, scheme changes, policies type staying a list, duplicated policy validation, stale names). Declined:

  • Importing the private _requires_authentication from enforcement into register_openapi (quality, medium): same pattern as the existing import of _check_routes_enforced there; making it public would widen FOCA's API for an internal helper.
  • Inlining _iter_operations into _iter_routes callers (quality, low): kept the wrapper so existing call sites and tests stay unchanged.

Sourcery: 7 of 8 comments fixed in 8b4b312 (percent-encoded $ref tokens, invalid security values, names bound to reordered rules, null patch files, fields removed by later patches, log naming the spec; a test case claiming to delete a route with null was dropped since null does not delete keys). Declined:

  • Mixed configured and named rules during reconciliation (Sourcery, high): replacing configured rules as a whole on startup is existing set_configured_policies behaviour 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:

  • Support named API specifications and access-control policies so configuration overlays can add, update, or remove individual entries.
  • Allow operators to apply ordered YAML, JSON, or inline patches to named API specifications.

Bug Fixes:

  • Detect and reject unsafe or invalid configuration overlays and patched specifications instead of silently losing or ignoring changes.

Enhancements:

  • Add startup logging and safety warnings for applied patches, weakened protections, changed security schemes, and named policy rules.
  • Normalize named configuration entries to the existing list-based runtime representation while preserving compatibility with unnamed configurations.

Documentation:

  • Document named entries, specification patching, overlay safety considerations, and the recipe for requiring authentication on selected reads.
  • Update the configuration template to demonstrate named specifications.

Tests:

  • Add coverage for named-entry merging and validation, specification patch behavior and safety warnings, named policy registration, and the authentication overlay recipe.

uniqueg and others added 4 commits October 22, 2026 21:49
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This 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 registration

sequenceDiagram
    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
Loading

Sequence diagram for named policy registration

sequenceDiagram
    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
Loading

Flow diagram for configuration overlay normalization

flowchart 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]
Loading

File-Level Changes

Change Details Files
Add overlay-friendly named configuration entries for API specifications and access-control policies.
  • Accept mappings keyed by name in both configuration sections, with merge, add, null removal, and validation of unknown or duplicate entries.
  • Normalize named specifications and policies to the existing list-based runtime representations while retaining names for logging and diagnostics.
  • Reject unsafe list-to-map transitions and report invalid named policy rules with their names.
foca/config/config_parser.py
foca/models/config.py
foca/security/access_control/register_access_control.py
tests/config/test_config_parser.py
tests/models/test_config.py
tests/security/access_control/test_register_casbin_enforcer.py
Implement ordered OpenAPI specification patches with validation and security regression warnings.
  • Load YAML, JSON, empty-file, or inline mapping patches and deep-merge them after the base spec and append data, before operation and security field augmentation.
  • Resolve patch paths using the base configuration directory and log applied patches.
  • Detect weakened authentication or access-control protections, newly public operations, external references, and security scheme changes.
  • Reject fields patched beside path-item references, wrap post-patch invalid specifications with a clear ValueError, and preserve other registration errors while adding patch diagnostics.
foca/api/register_openapi.py
foca/models/config.py
tests/api/test_register_openapi.py
Document named entries, specification patching, and a secure overlay recipe.
  • Describe named specifications and rules, merge/removal semantics, path resolution, validation failures, and startup warnings.
  • Add danger guidance to review patches and broad access-control rules.
  • Add an end-to-end recipe requiring authentication for selected reads while preserving service-info access and protecting the permissions API.
docs/access-control.md
docs/configuration/access-control.md
docs/configuration/api.md
docs/configuration/index.md
templates/config.yaml
tests/test_recipes.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (0417848) to head (b82f103).

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     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review October 22, 2026 20:48

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/api/register_openapi.py Resolved
Comment thread foca/api/register_openapi.py Resolved
Comment thread foca/models/config.py Resolved
Comment thread foca/api/register_openapi.py Resolved
Comment thread foca/api/register_openapi.py Resolved
Comment thread tests/api/test_register_openapi.py Resolved
Comment thread foca/api/register_openapi.py Resolved
uniqueg and others added 3 commits October 22, 2026 23:10
- 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]>
@uniqueg
uniqueg merged commit db6998c into dev Oct 22, 2026
15 checks passed
@uniqueg
uniqueg deleted the feat/396-config-patches branch October 22, 2026 21:28
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.

1 participant