Skip to content

Add readable access-control setup logs and clean up deprecation/test noise#257

Open
minhpham1810 wants to merge 3 commits intoelixir-cloud-aai:devfrom
minhpham1810:dev_#250
Open

Add readable access-control setup logs and clean up deprecation/test noise#257
minhpham1810 wants to merge 3 commits intoelixir-cloud-aai:devfrom
minhpham1810:dev_#250

Conversation

@minhpham1810
Copy link

@minhpham1810 minhpham1810 commented Mar 19, 2026

Description

Summary

This PR implements issue #250 by adding readable confirmation logs for the access-control setup flow, then updates tests and warning handling so CI output is reliable and low-noise.

What changed

  1. Access-control setup logging
  • Added log confirming enforcer registration in register_access_control.py.
  • Added log confirming permission spec registration in register_access_control.py.
  • Added top-level log confirming access-control registration completion in foca.py.
  1. Test updates
  • Added a focused unit test to validate setup-step logs in test_register_access_control.py.
  • Updated access-control assertions in test_foca.py to use stderr capture, matching current project logging behavior.
  1. Deprecation cleanup
  • Replaced deprecated importlib.resources path usage with files/as_file in:
    • config.py
    • register_access_control.py
  • Added pytest warning filters for known external deprecations in setup.cfg.

Why

  • Improves operator visibility during bootstrap by clearly signaling successful access-control setup steps.
  • Prevents flaky/false-negative log assertions caused by logger capture differences.
  • Reduces warning noise from dependency internals so real regressions are easier to spot.

Validation

  • Ran: pytest -q test_foca.py
  • Result: 15 passed

Fixes #250 (issue)

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have updated the documentation (or documentation does not need to be updated)
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • I have not reduced the existing code coverage

Summary by Sourcery

Document and support MongoDB configuration via a MONGO_URI environment variable while improving access-control setup logging and keeping tests and warnings aligned with the updated behavior.

New Features:

  • Allow configuring the MongoDB client via a MONGO_URI environment variable that takes precedence over other MongoDB-related settings and environment variables.
  • Add explicit informational logs for access-control enforcer and permission-spec registration during application startup.

Enhancements:

  • Replace deprecated importlib.resources path APIs with files/as_file in access-control and model configuration logic.
  • Clarify MongoDB environment variable overrides in the README and sample config template.

CI:

  • Configure pytest warning filters to ignore noisy deprecation warnings from jsonschema so CI output focuses on relevant issues.

Documentation:

  • Expand README and config template documentation to describe MongoDB environment variable override behavior, including MONGO_URI precedence.

Tests:

  • Add unit tests covering MONGO_URI-based MongoDB client creation, precedence, and warning behavior.
  • Add tests to verify access-control registration logs and update access-control tests to assert against captured stderr output.

Add support for a MONGO_URI environment variable that, when set, is used as the complete MongoDB connection string, taking precedence over individual component variables (MONGO_HOST, MONGO_PORT, MONGO_USERNAME, MONGO_PASSWORD, MONGO_DBNAME). This enables advanced connection features such as replica sets, SRV records, TLS options, and URIs from external secret managers.

A warning is logged when MONGO_URI is set alongside individual variables to help users avoid configuration confusion. Full backward compatibility is maintained.
- add INFO log after casbin enforcer registration in register_access_control.py
- add INFO log after permission spec registration in register_access_control.py
- add INFO log after access-control registration in foca.py
- add focused log-flow unit test in test_register_access_control.py
- update access-control tests to assert emitted logs via stderr capture in test_foca.py
- replace deprecated importlib.resources path usage with files/as_file in config.py and register_access_control.py
- suppress known third-party deprecation noise in pytest config in setup.cfg

Suggested PR title

Add readable access-control setup logs and clean up deprecation/test noise

Suggested PR description

Summary
This PR implements issue elixir-cloud-aai#250 by adding readable confirmation logs for the access-control setup flow, then updates tests and warning handling so CI output is reliable and low-noise.

What changed
1. Access-control setup logging
- Added log confirming enforcer registration in register_access_control.py.
- Added log confirming permission spec registration in register_access_control.py.
- Added top-level log confirming access-control registration completion in foca.py.

2. Test updates
- Added a focused unit test to validate setup-step logs in test_register_access_control.py.
- Updated access-control assertions in test_foca.py to use stderr capture, matching current project logging behavior.

3. Deprecation cleanup
- Replaced deprecated importlib.resources path usage with files/as_file in:
  - config.py
  - register_access_control.py
- Added pytest warning filters for known external deprecations in setup.cfg.

Why
- Improves operator visibility during bootstrap by clearly signaling successful access-control setup steps.
- Prevents flaky/false-negative log assertions caused by logger capture differences.
- Reduces warning noise from dependency internals so real regressions are easier to spot.

Validation
- Ran: pytest -q test_foca.py
- Result: 15 passed

Issue
- Closes elixir-cloud-aai#250
@sourcery-ai
Copy link

sourcery-ai bot commented Mar 19, 2026

Reviewer's Guide

Adds explicit environment-variable-driven MongoDB URI support and access-control setup logging, updates tests to validate the new behavior and log outputs, and modernizes resource loading and pytest warning handling.

Sequence diagram for access-control registration and logging

sequenceDiagram
    participant Foca as Foca_create_app
    participant App as Flask_app
    participant AC as register_access_control
    participant Enf as register_enforcer
    participant Perm as register_permission_specs
    participant Log as logger

    Foca->>AC: register_access_control(app, mongo_config, access_control_config)
    AC->>Enf: register_enforcer(app, mongo_config, access_control_config)
    Enf-->>AC: enforcer_registered_app
    AC->>Log: info Access control enforcer registered.

    AC->>Perm: register_permission_specs(app, access_control_config)
    Perm->>Perm: Resolve API spec path
    Perm-->>AC: permission_specs_registered_app
    AC->>Log: info Access control permission specifications registered.

    AC-->>Foca: access_control_configured_app
    Foca->>Log: info Access control registered.
Loading

File-Level Changes

Change Details Files
Introduce MONGO_URI-first MongoDB client configuration with warning + logging and document/env-template support.
  • Extended _create_mongo_client to prefer a non-empty MONGO_URI env var over individual Mongo settings, logging a warning when per-field env vars are present and an info message on registration.
  • Updated README and templates/config.yaml to describe MongoDB environment variable overrides, including MONGO_URI precedence rules.
  • Added unit tests covering MONGO_URI precedence, empty handling, credential-bearing URIs, logging of ignored vars, and full register_mongodb flow with MONGO_URI.
foca/database/register_mongodb.py
README.md
templates/config.yaml
tests/database/test_register_mongodb.py
Improve access-control registration observability and align tests with stderr-based logging behavior.
  • Added info-level logs after registering the access-control enforcer and permission specifications, and a top-level log when access control registration completes in the app factory.
  • Introduced a focused unit test validating that access-control registration logs expected setup messages, using monkeypatched helpers.
  • Adjusted FOCA access-control tests to capture stderr and assert on specific log messages for valid and invalid configurations.
foca/security/access_control/register_access_control.py
foca/foca.py
tests/security/access_control/test_register_access_control.py
tests/test_foca.py
Modernize access-control resource file loading and reduce pytest warning noise from external dependencies.
  • Replaced deprecated importlib.resources.resource_path usage with files/as_file for resolving default access-control model and spec paths.
  • Added pytest filterwarnings configuration for known jsonschema deprecation warnings to keep CI output clean.
foca/models/config.py
foca/security/access_control/register_access_control.py
setup.cfg

Assessment against linked issues

Issue Objective Addressed Explanation
#250 Add a readable log line confirming the access control enforcer has been registered in register_access_control.py at the enforcer registration step.
#250 Add a readable log line confirming permission specifications have been registered in register_access_control.py at the permission specs registration step.
#250 Add a readable log line confirming completion of the access control registration flow in foca.py at the access control setup step.

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

@minhpham1810 minhpham1810 changed the title Dev #250 Add readable access-control setup logs and clean up deprecation/test noise Mar 19, 2026
Copy link

@sourcery-ai sourcery-ai bot left a comment

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/database/register_mongodb.py" line_range="134-143" />
<code_context>
     Returns:
         MongoDB client for Flask application instance.
     """
+    mongo_uri = os.environ.get('MONGO_URI')
+    if mongo_uri is not None and mongo_uri != "":
+        individual_vars = {
+            'MONGO_HOST': os.environ.get('MONGO_HOST'),
+            'MONGO_PORT': os.environ.get('MONGO_PORT'),
+            'MONGO_USERNAME': os.environ.get('MONGO_USERNAME'),
+            'MONGO_PASSWORD': os.environ.get('MONGO_PASSWORD'),
+            'MONGO_DBNAME': os.environ.get('MONGO_DBNAME'),
+        }
+        ignored = [name for name, val in individual_vars.items() if val is not None]
+        if ignored:
+            logger.warning(
</code_context>
<issue_to_address>
**issue:** Align empty-string handling for env vars with the rest of the function when computing ignored variables.

In the new `MONGO_URI` branch, `ignored` is computed with `if val is not None`, so env vars set to `""` are still treated as set and logged as ignored. Elsewhere in this function, empty strings are treated as unset. For consistency and to avoid noisy warnings for empty env vars, use a truthiness check (`if val`) or match the existing predicate (`val is not None and val != ""`).
</issue_to_address>

### Comment 2
<location path="tests/security/access_control/test_register_access_control.py" line_range="118-127" />
<code_context>
+def test_register_access_control_logs_setup_steps(monkeypatch, caplog):
</code_context>
<issue_to_address>
**suggestion (testing):** Scope log capture to the access-control logger for more robust log assertions.

To avoid capturing unrelated INFO logs and making the test brittle, use `caplog.at_level(logging.INFO, logger="foca.security.access_control.register_access_control")` (or the correct module path) and/or assert against `caplog.records` filtered by logger name rather than relying on `caplog.text`. This keeps the test focused on the access-control logger only.

Suggested implementation:

```python
def test_register_access_control_logs_setup_steps(monkeypatch, caplog):
    """Test setup logs for access control registration flow."""
    logger_name = "foca.security.access_control.register_access_control"

    with caplog.at_level(logging.INFO, logger=logger_name):
        access_control = AccessControlConfig(**ACCESS_CONTROL_CONFIG)
        mongo_config = MongoConfig(**MONGO_CONFIG)

        dummy_app = SimpleNamespace(
            app=SimpleNamespace(config=SimpleNamespace(foca=SimpleNamespace(db=None)))
        )

        monkeypatch.setattr(

```

1. Ensure `import logging` is present at the top of `tests/security/access_control/test_register_access_control.py`. If it is missing, add `import logging` alongside the other imports.
2. Update any log assertions later in `test_register_access_control_logs_setup_steps` that currently rely on `caplog.text` to instead filter `caplog.records` by `record.name == logger_name`, e.g.:
   ```python
   records = [r for r in caplog.records if r.name == logger_name]
   assert any("expected message fragment" in r.getMessage() for r in records)
   ```
   This will fully scope the assertions to the access-control logger and avoid brittleness from unrelated INFO logs.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

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.

Add readable logs for Access Control Setup

1 participant