Skip to content

fix: address 0.17.0 review findings - #443

Merged
uniqueg merged 11 commits into
devfrom
fix/review-findings-0.17
Oct 23, 2026
Merged

uniqueg merged 11 commits into
devfrom
fix/review-findings-0.17

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes the findings of the round-2 pre-release review of FOCA 0.17.0 and foca-common 0.2.0 that the maintainer accepted for the release.

Access control

  • M1: _remove_policies fails closed (maintainer decision). Without policies, any error while checking for or removing stored configured rules, also a connection failure or a server selection timeout, is logged as an error ("refusing to start") and raised, so the app refuses to start, as it does if storing configured rules fails. Apps with access control thus need MongoDB at startup also without policies; orchestrators restart them until it is available. Tests cover errors during the check and the removal.
  • The check runs under pymongo.timeout(5) (CONFIGURED_POLICIES_CHECK_TIMEOUT), so startup without MongoDB fails after 5 s instead of blocking for the 30 s default server selection timeout (as long as gunicorn's worker timeout). Checked with gunicorn: the workers log the error and fail to boot, and the master exits non-zero. A test against an unreachable address checks the timeout.
  • The docs, the migration guide ("unset policies requires MongoDB at startup") and the AccessControlConfig.policies docstring (L2, stale since fix(access-control)!: replace policies atomically #423) describe this.
  • DELETE /permissions/{id} returns 404 for configured rules that are not in effect (of a generation that is not active yet), as GET does, and 409 only for rules configured in the active generation (checked again after a failed delete). PUT with their identifier still gets 409 (unique index). The spec and the docs say so.

Docs

  • L3: apps on a shared external MongoDB must set their own db_name, as all apps share the default policy collection (access control docs, migration guide).
  • Migration guide: 0.1.0 values render MongoDB unchanged except for the keep annotation on the claim.
  • README quick start, getting started and authentication docs: named specs entries.
  • Contributing guide: re-run only the failed jobs of a release ("Re-run failed jobs"), never "Re-run all jobs", as builds are not reproducible; requirements/release.txt no longer says releases can be reproduced from their tag.

Packaging

  • Docker image: org.opencontainers.image.version and revision from the build arguments FOCA_VERSION and FOCA_REVISION, which the dev and release push jobs set (version, github.sha). The lines come last, so the other layers stay cached.
  • ELIXIR On-Cloud links to https://elixir-on.cloud/ everywhere (PyPI project URL).
  • Removed the unreferenced images images/{casbin_model.jpeg,foca_favicon.svg,foca_logo.svg,foca_logo_round.svg,foca_seal.svg}. The docs, mkdocs and the chart icons use docs/images/, and images/hint.svg is still used by the examples.

Verification

  • coverage run -m pytest with MongoDB 7.0 on port 12345: 1817 passed, 1 skipped; coverage report: 100%.
  • ruff check, ruff format --check, mypy: pass.
  • pre-commit run --all-files (incl. semgrep, semgrep rule tests, ast-grep and its rule tests): pass.
  • mkdocs build --strict: pass.
  • actionlint: no findings.
  • Not run locally: the Docker build (no Docker daemon in the sandbox). CI builds the images.
  • CI on the final head: all checks pass, including lint and build, unit tests (all Python and MongoDB variants, lowest direct dependencies), integration tests, chart lint and tests, kind install, image builds and scans, codecov and Read the Docs.
  • Reviews: adversarial-reviewer and quality-reviewer, two rounds, then the adversarial reviewer again on the fail-closed change. Round 1 found mediums (the fail-open path on connection failures; the docs and spec did not describe DELETE's 404), which led to the maintainer's fail-closed decision and doc fixes. Later rounds found no high or medium issues; their lows are fixed or declined below.

Declined review findings

  • The permissions API spec names [email protected] as contact (pre-release review). Kept: the maintainer decided that the service address goes into spec contacts (ELIXIR On-Cloud branding is intended).
  • Version and revision labels in the example Dockerfiles (adversarial review). The Dockerfile comment says derived images set their own labels, including these. The examples are not published images.
  • The removal of stored configured rules uses the client's default timeouts, not the 5 s of the check, so if MongoDB becomes unreachable between the check and the removal, a gunicorn worker may hit its timeout and be respawned rather than make the master exit (adversarial review, low). The app still never serves with stale rules; the same applies to storing rules with policies set, so a shorter timeout there would be a separate change.
  • Sourcery: defer activating the empty generation until the old rules are removed. Declined: once the empty generation is active, the revoked rules are no longer enforced, which is the goal; leftovers of the inactive generation are not loaded and are removed on the next startup.
  • Sourcery: run the removal under a deadline, too. Declined for this release, as for the adversarial finding above.

Open questions

None.

Closes #442

🤖 Generated with Claude Code

Summary by Sourcery

Harden access-control startup and permission deletion behavior for the 0.17.0 release, and align packaging, documentation, and image metadata with the reviewed changes.

Bug Fixes:

  • Make startup fail closed when configured access-control rules cannot be checked or removed, with a bounded five-second check timeout.
  • Return 404 when deleting configured permission rules that are not currently in effect, while preserving conflict responses for active configured rules.

Enhancements:

  • Align access-control configuration behavior, shared MongoDB guidance, migration notes, API documentation, and quick-start examples with the updated release behavior.
  • Add OCI image version and revision metadata sourced from the build version and commit.
  • Update the package project URL, release guidance, and migration documentation, and remove unused image assets.

Build:

  • Add version and commit build arguments to Docker image metadata while preserving layer caching.

CI:

  • Pass the commit SHA to Docker builds in development and release workflows.

Documentation:

  • Clarify access-control startup requirements, policy collection isolation, permission deletion responses, release rerun guidance, migration behavior, and named API specification configuration.

Tests:

  • Expand access-control tests for fail-closed startup behavior, timeout handling, database errors, and permission deletion races.

Chores:

  • Remove unreferenced image files.

uniqueg and others added 7 commits October 23, 2026 19:36
Without `security.access_control.policies`, stored configured rules are
removed on startup. Any MongoDB error, also one raised while removing
them, was only logged, so the app started with rules removed from its
configuration in effect, which the permissions API cannot delete.

Tolerate only connection failures and timeouts of the check for stored
configured rules, and give that check a timeout of 5 seconds instead of
the client's server selection timeout (30 s by default, as long as
gunicorn's worker timeout). Errors while removing stored configured
rules are raised, so that the app refuses to start, as it does if
storing configured rules fails.

Also fix the stale `policies` docstring of `AccessControlConfig`.

Refs #442

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Getting a configured rule of a generation that is not active yet
returns 404, but deleting it returned 409, as any stored rule with the
identifier counted. Return 409 only if the rule is configured in the
active generation, as for getting it, and 404 otherwise.

Refs #442

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Access control and migration guide: removing stored configured rules
  fails startup if it fails; apps on a shared external MongoDB must set
  their own `db_name`, as all apps share the default policy collection.
- Migration guide: 0.1.0 values render MongoDB unchanged except for the
  keep annotation on its claim.
- README, getting started and authentication: named `specs` entries.
- Contributing guide: re-run only the failed jobs of a release, as
  builds are not reproducible; `requirements/release.txt` no longer
  claims that releases can be reproduced from their tag.

Refs #442

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add the OCI annotations `org.opencontainers.image.version` and
`revision` to the FOCA images, from the build arguments `FOCA_VERSION`
and `FOCA_REVISION`, which the release and `dev` workflows set to the
version and the commit. They come last in the Dockerfile, so that the
other layers stay cached.

Refs #442

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Link ELIXIR On-Cloud as https://elixir-on.cloud/ in the project URLs,
as in the README and docs, and remove the unreferenced images from
`images/` (the docs use their copies in `docs/images/`; only `hint.svg`
is still used, by the examples).

Refs #442

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Tolerate only connection failures of the check for stored configured
  rules, not other timeouts (e.g., of a slow but available server).
- Document that stored configured rules stay in effect until the next
  startup if the database is not available within 5 seconds, and that
  `policies: []` revokes them reliably.
- Permissions API spec and docs: configured rules not in effect yet are
  not found for GET and DELETE, while PUT still conflicts with them.
- Re-wrap docs, comments and docstrings; clarify the image labels that
  derived images set themselves.

Refs #442

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Explain that a timeout on a slow but reachable server is either
tolerated (`NetworkTimeout`) or raised (`ExecutionTimeout`), and re-wrap
a comment in `requirements/release.txt`.

Refs #442

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR addresses the 0.17.0 review findings by making configured-policy startup behavior fail safely with a five-second, connection-only fallback, correcting permission deletion responses across policy generations, and synchronizing tests, API documentation, migration guidance, release workflows, container provenance metadata, project links, and unused assets.

Sequence diagram for configured-policy startup handling

sequenceDiagram
    participant App
    participant _remove_policies
    participant Adapter
    participant MongoDB

    App->>_remove_policies: _remove_policies(adapter)
    _remove_policies->>Adapter: has_configured_policies()
    Adapter->>MongoDB: Check stored configured rules
    alt ConnectionFailure within 5 seconds
        MongoDB-->>Adapter: Connection failure
        Adapter-->>_remove_policies: ConnectionFailure
        _remove_policies-->>App: Warning, keep stored rules
    else Check succeeds with configured rules
        MongoDB-->>Adapter: configured = true
        _remove_policies->>Adapter: set_configured_policies([])
        Adapter->>MongoDB: Remove stored configured rules
        MongoDB-->>Adapter: Success or error
    else Other check error
        MongoDB-->>Adapter: Error
        Adapter-->>_remove_policies: Propagate error
        _remove_policies-->>App: Startup fails
    end
Loading

Sequence diagram for configured permission deletion responses

sequenceDiagram
    participant Client
    participant API
    participant PermissionsCollection

    Client->>API: deletePermission(id)
    API->>API: _check_not_configured(id)
    API->>PermissionsCollection: delete_one(id, not configured)
    alt Rule deleted
        PermissionsCollection-->>API: deleted_count = 1
        API-->>Client: 200 deleted id
    else Rule not deleted
        PermissionsCollection-->>API: deleted_count = 0
        API->>API: _check_not_configured(id)
        alt Active configured rule
            API-->>Client: 409 Conflict
        else Inactive or missing rule
            API-->>Client: 404 Not Found
        end
    end
Loading

File-Level Changes

Change Details Files
Harden startup handling of stored configured access-control policies with bounded, selective error tolerance.
  • Run the policy-existence check under a five-second MongoDB timeout.
  • Tolerate only connection failures during the check and warn while preserving stored rules.
  • Propagate all other check failures and every removal failure to prevent unsafe startup.
  • Document timeout behavior and reliable revocation with policies: [].
  • Add tests for unreachable databases, check errors, and removal errors.
foca/security/access_control/register_access_control.py
foca/security/access_control/constants.py
foca/models/config.py
docs/access-control.md
docs/migration-0.17.md
tests/security/access_control/test_register_casbin_enforcer.py
Correct deletion semantics for configured permissions across inactive and concurrent generations.
  • Return 404 for configured rules that are not currently in effect.
  • Recheck configuration after a failed deletion so rules becoming active concurrently return 409.
  • Align OpenAPI descriptions and tests with GET, PUT, and DELETE behavior.
foca/security/access_control/access_control_server.py
foca/security/access_control/api/access-control-specs.yaml
docs/access-control.md
tests/security/access_control/test_access_control_server.py
Update operational and user-facing documentation for the release findings.
  • Document explicit database names for applications sharing an external MongoDB policy collection.
  • Clarify migration rendering, including the claim keep annotation.
  • Convert API examples to named specs entries.
  • Clarify that release workflows should rerun only failed jobs because builds are not reproducible.
docs/access-control.md
docs/migration-0.17.md
README.md
docs/authentication.md
docs/getting-started.md
docs/contributing.md
Add container provenance metadata and update release build inputs and project metadata.
  • Set OCI image version and revision labels from FOCA_VERSION and FOCA_REVISION build arguments after cacheable layers.
  • Pass the GitHub commit SHA to development and release image builds.
  • Update the ELIXIR On-Cloud URL and release requirements metadata.
docker/Dockerfile
.github/workflows/checks.yml
.github/workflows/release.yml
pyproject.toml
requirements/release.txt
Remove obsolete image assets that are no longer referenced.
  • Delete unused Casbin and FOCA branding images while retaining assets used by documentation and examples.
images/casbin_model.jpeg
images/foca_favicon.svg
images/foca_logo.svg
images/foca_logo_round.svg
images/foca_seal.svg

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 23, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #443   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           27        27           
  Lines         2869      2872    +3     
=========================================
+ Hits          2869      2872    +3     
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 23, 2026 18:01

@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 3 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="408" />
<code_context>
-                "Removing stored configured policy rules, as "
-                "'security.access_control.policies' is not set."
-            )
-            adapter.set_configured_policies([])
-    except PyMongoError as exc:
+        # Shorter than the client's server selection timeout (30 s by
</code_context>
<issue_to_address>
**Configured rules stop being enforced**

When `_remove_generations` fails after the empty generation is activated, `set_configured_policies([])` has already switched the active marker to the empty generation, so the stored configured rules stop being enforced and can disappear after a later restart.

Defer switching the active marker to the empty generation until cleanup succeeds.
</issue_to_address>

### Comment 2
<location path="foca/security/access_control/register_access_control.py" line_range="408" />
<code_context>
-                "Removing stored configured policy rules, as "
-                "'security.access_control.policies' is not set."
-            )
-            adapter.set_configured_policies([])
-    except PyMongoError as exc:
+        # Shorter than the client's server selection timeout (30 s by
</code_context>
<issue_to_address>
**Policy removal can stall startup**

When mongoDB becomes unavailable after the configured-rule check succeeds but while `set_configured_policies([])` is removing rules, `adapter.set_configured_policies([])` runs outside `pymongo.timeout`, so its MongoDB operations can wait for the client’s 30-second server-selection timeout and exceed Gunicorn’s worker timeout, repeatedly killing startup workers instead of promptly surfacing the removal failure.

Run the removal under an appropriate PyMongo deadline too, allowing its timeout to propagate so startup fails promptly.
</issue_to_address>

### Comment 3
<location path="foca/security/access_control/api/access-control-specs.yaml" line_range="280" />
<code_context>
                 $ref: '#/components/schemas/Error'
         '404':
-          description: The requested permission was not found.
+          description: The requested permission was not found, also if it is a configured rule that is not in effect yet.
           content:
             application/problem+json:
</code_context>
<issue_to_address>
**GET behavior stays underspecified**

When a client uses the OpenAPI spec to determine how GET handles configured rules that are not in effect, the GET 404 description still says only “The permission cannot be found,” so OpenAPI readers are not told that configured rules outside the active generation also produce 404, unlike the updated DELETE description.

Update the GET 404 description to mention configured rules that are not in effect yet.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and when access_control.policies is unset, startup now deletes stored configured rules; if those rules were still needed to restrict access, their removal could expose protected operations or data. The deletion is persisted, so reverting the code will not restore the rules.

Blocking findings: foca/security/access_control/register_access_control.py:408, foca/security/access_control/register_access_control.py:408


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

@uniqueg

uniqueg commented Oct 23, 2026

Copy link
Copy Markdown
Member Author

@sourcery-ai review

@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 2 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="401" />
<code_context>
+            "until the next startup: %s",
             exc,
         )
+        return
+    if configured:
+        # E.g., set via a config overlay that was removed since
</code_context>
<issue_to_address>
**Stored policies stay active**

When the configured-policy check fails with a database connection error, `_remove_policies` returns without removing the stored configured rules, so they remain active until the next startup despite the `Attributes` section and `register_casbin_enforcer` docstring saying unset policies are removed; callers can believe access was revoked.

Update the `Attributes` section and docstring to explain that the rules remain active until the next startup when the configured-policy check fails.

Also at `foca/models/config.py:767-772`.
</issue_to_address>

### Comment 2
<location path="tests/security/access_control/test_register_casbin_enforcer.py" line_range="249" />
<code_context>
         with caplog.at_level(logging.WARNING, logger=module.logger.name):
             _register_policies(None)
-        assert "Could not remove stored configured policy rules" in caplog.text
+        assert "Could not check for stored configured policy rules" in caplog.text
+
+    def test_unset_check_times_out(
</code_context>
<issue_to_address>
**Timeout regression goes undetected**

When the check takes longer than 0.1 seconds but finishes in under 10 seconds, `test_unset_check_times_out` accepts any elapsed time under 10 seconds, so a broken check that ignores the configured 0.1-second timeout and takes 9 seconds still passes. The test therefore does not verify the timeout it configures.

Use an elapsed-time bound that meaningfully verifies the configured timeout while allowing reasonable test overhead.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and when access_control.policies is unset, startup now deletes stored configured rules; removing a rule can change who is allowed or denied, and reverting the code will not restore deleted database records. The 5-second database timeout leaves existing rules in place, but does not make deletions reversible.

Blocking findings: foca/security/access_control/register_access_control.py:401, tests/security/access_control/test_register_casbin_enforcer.py:249


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

uniqueg and others added 4 commits October 23, 2026 20:23
Maintainer decision: apps must never start with stored configured rules
in effect that were removed from their configuration. Without
`security.access_control.policies`, any error while checking for stored
configured rules, also a connection failure or server selection
timeout, now makes startup fail, with an error, as errors while
removing them already did. The check keeps its timeout of 5 seconds, so
that startup fails soon: gunicorn's master exits when a worker fails to
boot, and orchestrators such as Kubernetes restart the app until
MongoDB is available.

Refs #442

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Log the same error for failures to remove stored configured rules as
for failures to check for them, with a hint that also covers missing
permissions, and fix a stale test docstring.

Refs #442

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Check that the check gives up within 3 s for a timeout of 0.1 s, and
describe in the spec that getting a configured rule not in effect yet
returns 404, as deleting it does.

Refs #442

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit f6ded57 into dev Oct 23, 2026
26 checks passed
@uniqueg
uniqueg deleted the fix/review-findings-0.17 branch October 23, 2026 18:58
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.

fix: address 0.17.0 review findings

1 participant