Skip to content

fix: group-subject warning, listing media type - #639

Merged
uniqueg merged 5 commits into
devfrom
fix/group-warning-listing-type
Nov 3, 2026
Merged

uniqueg merged 5 commits into
devfrom
fix/group-warning-listing-type

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Closes #577

Summary

  • Group-subject warning: with group_mapping set and keep_group_subjects not, FOCA now warns only if a rule actually has a group as its subject, in policies or stored (e.g., written via the permissions API). Otherwise the message is logged at INFO, so apps like proTES that only map groups to roles don't warn on every start.
  • Listing media type: when a specification with the plugin listing's operations is registered, their error responses declare the configured exceptions.media_type, as the permissions API already does. The media type helpers moved to foca/api/register_openapi.py and are shared.
  • Docs: docs/configuration/access-control.md, docs/deployment.md, docs/plugins.md.

Verification

  • ruff check, ruff format --check, mypy, ast-grep scan, mkdocs build --strict: pass
  • coverage run -m pytest -m "not mongodb": 3132 passed, 1 skipped, 100% coverage. Tests marked mongodb didn't run locally (they need the shared port 12345); CI runs them.
  • New tests failed before the fix.

Declined review findings

  • has_stored_group_subjects() filters on v0 without ptype, so it can't use the filter indexes and may scan on large collections. It's one query per start, bounded by the 5 s timeout, and a timeout only logs that the hint couldn't be determined. Listing all policy types of a model isn't worth it for a hint.
  • Unit tests for _get_error_media_type without FOCA config and for _set_error_media_type directly: both paths are covered through the permissions API and listing tests (100% coverage).

🤖 Generated with Claude Code

https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG

Summary by Sourcery

Prevent misleading group-subject warnings and ensure plugin listing errors advertise the application's configured media type.

Bug Fixes:

  • Refine group-subject startup warnings so they are emitted at warning level only when configured or stored policy rules actually use group subjects, while retaining informational logging otherwise.
  • Declare the configured exception media type for plugin listing error responses in merged OpenAPI specifications.

Enhancements:

  • Share OpenAPI error media-type handling between permissions and plugin listing specifications.
  • Detect stored group-subject rules during access-control startup and continue safely when the check cannot be completed.

Documentation:

  • Document the conditional group-subject warning behavior and plugin listing error media-type declarations.

Tests:

  • Add coverage for configured and stored group-subject detection, logging levels, unavailable storage checks, and plugin listing media types.

uniqueg and others added 3 commits November 3, 2026 06:46
Warn about dropped group subjects only if a rule of `policies` has a
group as its subject; otherwise log it at INFO, so that apps that only
map groups to roles don't warn on every start.

Declare the configured `exceptions.media_type` for the errors of the
plugin listing's operations when a specification with them is
registered, as the permissions API already does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Rules with group subjects can also be stored, e.g., written via the
permissions API; warn about those as well, rather than only logging at
INFO. Identify the plugin listing's operations by their IDs, as apps
can override their controllers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Stored rules with group subjects can still apply via role inheritance,
so only say that they don't apply via group claims.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
@uniqueg uniqueg added this to the v0.20.0 milestone Nov 3, 2026
@uniqueg uniqueg added the type: bug Something isn't working label Nov 3, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR makes access-control startup warnings conditional on actual configured or stored group-subject rules, while gracefully handling unavailable persistence checks. It also shares OpenAPI media-type utilities and uses them to ensure plugin listing errors advertise the application’s configured exception media type, with corresponding documentation and coverage.

Sequence diagram for conditional group-subject startup diagnostics

sequenceDiagram
    participant App as Application startup
    participant Register as register_casbin_enforcer
    participant Config as Access control config
    participant Adapter as Casbin adapter
    participant MongoDB as Stored policy database
    participant Logger

    App->>Register: register_casbin_enforcer()
    Register->>Config: _has_group_subject()
    alt Configured group-subject rule exists
        Register->>Logger: logger.log(WARNING)
    else No configured group-subject rule
        Register->>Adapter: has_stored_group_subjects()
        Adapter->>MongoDB: count_documents(query, limit=1)
        alt Stored group-subject rule exists
            MongoDB-->>Adapter: stored = true
            Adapter-->>Register: true
            Register->>Logger: logger.warning()
        else No stored rule or database check fails
            MongoDB-->>Adapter: result or PyMongoError
            Adapter-->>Register: false or exception handled
            Register->>Logger: logger.log(INFO) or logger.warning()
        end
    end
    Register-->>App: Continue startup
Loading

Sequence diagram for plugin listing error media type registration

sequenceDiagram
    participant App as Connexion application
    participant Register as register_openapi
    participant Config as FOCA config
    participant Spec as Plugin listing specification

    App->>Register: register_openapi()
    Register->>Config: _get_error_media_type(app)
    Config-->>Register: exceptions.media_type or default
    Register->>Spec: _iter_operations(spec_parsed)
    loop Plugin listing operations
        Register->>Register: _set_error_media_type(operation, media_type)
    end
    Register-->>App: Register merged specification with configured error media type
Loading

File-Level Changes

Change Details Files
Refine startup diagnostics for group subjects so warnings are emitted only when dropped group subjects can affect configured or persisted rules.
  • Inspect configured policies for group-prefixed subjects and log the existing diagnostic at WARNING only when relevant, otherwise INFO.
  • Query non-configured stored rules for group subjects during registration to detect rules written through APIs or retained from prior configuration.
  • Bound the stored-rule check and continue startup with a warning if the database check fails.
  • Document the updated warning behavior.
foca/security/access_control/register_access_control.py
foca/security/access_control/foca_casbin_adapter/adapter.py
docs/configuration/access-control.md
docs/deployment.md
tests/security/access_control/foca_casbin_adapter/test_adapter.py
tests/security/access_control/test_register_access_control.py
Centralize OpenAPI error media-type handling and apply the configured exception media type to plugin listing operations.
  • Add shared helpers to resolve the configured media type, iterate operations, and rewrite 4xx/5xx response content.
  • Reuse the helpers for permissions API specifications.
  • Patch plugin listing operations identified by operation ID when specifications are registered.
  • Document the plugin listing response behavior and verify merged specifications and served errors.
foca/api/register_openapi.py
foca/security/access_control/register_access_control.py
docs/plugins.md
tests/plugins/test_plugin_api.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 Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (1122ead) to head (5d7e456).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #639   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           56        56           
  Lines         7090      7119   +29     
=========================================
+ Hits          7090      7119   +29     
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 November 3, 2026 06:33

@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/api/register_openapi.py" line_range="172" />
<code_context>
+    for status, response in operation.get("responses", {}).items():
+        content = response.get("content", {})
+        if str(status)[0] in "45" and DEFAULT_ERROR_MEDIA_TYPE in content:
+            content[media_type] = content.pop(DEFAULT_ERROR_MEDIA_TYPE)
+
+
</code_context>
<issue_to_address>
**Existing error schema is overwritten**

When a merged listing response already contains both `application/problem+json` and the configured media type, `content[media_type]` replaces any schema already declared for the configured media type with the `application/problem+json` schema, so the served listing advertises the wrong schema or fails response validation.

Preserve an existing configured-media-type entry instead of unconditionally replacing it.
</issue_to_address>

### Comment 2
<location path="foca/api/register_openapi.py" line_range="433-439" />
<code_context>
         spec_parsed: dict[str, Any] = ConfigParser.merge_yaml(*list_specs)
         logger.debug("Parsed spec: %s", list_specs)

+        # Declare the media type that the plugin listing's errors have; the
+        # app's patches may still change it
+        media_type = _get_error_media_type(app)
+        for operation_object in _iter_operations(spec_parsed):
+            if operation_object.get("operationId") in _PLUGIN_LISTING_OPERATIONS:
+                _set_error_media_type(operation_object, media_type)
+
         # Add/replace root objects
         if spec.append is not None:
</code_context>
<issue_to_address>
**Appended errors advertise stale media types**

When the specification adds or replaces plugin-listing paths through append, `register_openapi` rewrites media types before applying `spec.append`, so appended plugin-listing responses keep `application/problem+json` and the served document disagrees with the configured runtime media type.

Apply the error media-type rewrite after `spec.append` has been applied.
</issue_to_address>

### Comment 3
<location path="foca/security/access_control/register_access_control.py" line_range="295-299" />
<code_context>
+        Whether the subject of a rule of `policies`, which follows the policy
+        type (empty rules fail validation later), has the group prefix.
+    """
+    return any(
+        subject.startswith(GROUP_PREFIX)
+        for rule in access_control_config.policies or []
+        for subject in rule[1:2]
+    )
+
+
</code_context>
<issue_to_address>
**Dropped groups get info-only logs**

When a supported custom Casbin model places the subject outside the first policy value, the configured-rule check assumes the subject is the first policy value, and the stored-rule query only checks `v0`, so both checks miss group-subject rules and startup logs INFO instead of the intended warning.

Use the model's configured subject field for both the configured-rule check and the stored-rule query.

Also at `foca/security/access_control/foca_casbin_adapter/adapter.py:751-764`.
</issue_to_address>

Linked issues

#577 fix: group-subject warning, listing media type · 3 of 3 met

# Requirement Status Notes
1 Avoid a warning when group subjects are unused, but warn when configured policies use them. ✅ Met The configured-policy check logs at INFO when no rule has a group subject and at WARNING when one does.
2 Also detect stored rules with group subjects when deciding whether to warn. ✅ Met Startup checks non-configured stored rules and warns when they have group subjects; a failed check logs a warning and does not stop startup.
3 Declare the configured error media type in the served plugin listing spec, with tests covering both media types. ✅ Met The listing operations’ error responses are patched during registration, and the parametrized test covers application/json and application/problem+json.

Sourcery assessment

Approval pending. 3 findings to address first.

Blocking findings: foca/api/register_openapi.py:172, foca/api/register_openapi.py:439, foca/security/access_control/register_access_control.py:299


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
uniqueg and others added 2 commits November 3, 2026 07:48
@uniqueg
uniqueg merged commit f521cd3 into dev Nov 3, 2026
56 checks passed
@uniqueg
uniqueg deleted the fix/group-warning-listing-type branch November 3, 2026 07:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: group-subject warning, listing media type

1 participant