Skip to content

feat: report invalid fields in the permissions API - #765

Merged
uniqueg merged 4 commits into
devfrom
feat/760-permissions-invalid-fields
Nov 12, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/760-permissions-invalid-fields

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Summary

FOCA's permissions API (/permissions) now reports invalid rules, identifiers and pages as InvalidFieldsProblem, the same way the app endpoints do. Each response names the field (a JSON Pointer such as #/rule/v0, or the parameter id, page or page_size), gives a stable code, and never includes the rejected value.

  • casbin_rule.validate_rule() and validate_rule_value() raise the new InvalidRuleError. It subclasses ValueError and adds field, code and a reason that leaves out the value. Existing except ValueError callers are unchanged.
  • The codes, with where each is reported, are documented in docs/problems/invalid-request.md. docs/access-control.md has an example response.
  • The migration guide (docs/migration-0.23.md) has a new section for this change: the problem details now come from the mapping for RequestValidationProblem, not BadRequest; with exceptions.public_members, list type, code and errors; and tests should expect InvalidFieldsProblem.

Suggested 0.23 release-note bullet (Features): "The permissions API reports invalid rules, identifiers and pages as invalid fields, with stable codes and without the rejected values (#760, PR #765)."

Verification

  • pytest -m "not mongodb": 4856 passed, 2 skipped. The new tests failed before the change: 93 failed in test_access_control_server.py.
  • Coverage of the changed modules: 100% of the changed lines. Locally, foca/cli.py and foca/testing/pytest_plugin.py stay below 100% without MongoDB; this is unrelated and covered in CI.
  • ruff check, ruff format --check, mypy, ast-grep scan: all clean.
  • adversarial-reviewer found nothing. quality-reviewer raised 4 medium and 2 low findings: the 3 fixed are direct tests for InvalidRuleError, the log flow in _get_rule, and a "Reported at" column in the docs.

Declined review findings

  • Trailing-period normalisation of reason (medium): kept. InvalidRuleError messages also go into logs and ValueError texts that other callers and tests match, so changing their punctuation would spread further than this PR.
  • Page count in the "beyond the last page" detail (low): left out. Clients get total_pages from page 0.
  • test_opt_in_role monkeypatches the predicate (low): grants_opt_in_role has its own tests. This test only checks the field and code mapping.

Open questions

None.

Closes #760

🤖 Generated with Claude Code

https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV

Summary by Sourcery

Expose structured, value-safe validation errors from the permissions API for invalid rules, identifiers, and pagination parameters.

New Features:

  • Report invalid permission rules, identifiers, and pagination parameters as structured invalid-field problems with stable codes and field locations while excluding rejected values.

Enhancements:

  • Preserve ValueError compatibility while enriching rule validation errors with field, code, and value-safe reason metadata.

Documentation:

  • Document permissions API invalid-field codes, response examples, and migration guidance for clients and tests.

Tests:

  • Expand access-control and rule-validation coverage for invalid-field locations, codes, value redaction, and compatibility behavior.

uniqueg and others added 2 commits November 12, 2026 10:24
The permissions API raises InvalidFieldsProblem for invalid rules,
identifiers and pages, naming the field (JSON Pointer or parameter)
with a stable code and never the rejected value. validate_rule() and
validate_rule_value() raise InvalidRuleError, a ValueError carrying
the field and code. Codes are documented in "Invalid requests"; the
0.23 migration guide covers the change.

Closes #760

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Log rejected rule keys in _check_rule_keys, test InvalidRuleError's
field, code and reason directly, and document where each code of the
permissions API is reported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
@sourcery-ai

sourcery-ai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Introduce InvalidRuleError as a ValueError carrying a stable code, field location, and client-safe reason for rule validation failures.

  • foca/security/access_control/foca_casbin_adapter/casbin_rule.py L19-53, L64-89, L110-138 (+2 small edits)

API

Replace plain bad-request failures in the permissions API with structured invalid-field errors for rules, identifiers, and pagination parameters.

  • foca/security/access_control/access_control_server.py L147-221, L237-255, L265-286 (+9 small edits)

Documentation

Document the permission API's invalid-field codes and locations, show a representative response, and explain the 0.23 migration impact.

  • docs/access-control.md L1696-1699, L1748-1767
  • docs/migration-0.23.md L3-9, L31-52
  • docs/problems/invalid-request.md L104-131

Tests

Verify rule-validation metadata and the permissions API's reported field, code, and value-safe details for invalid requests.

  • tests/security/access_control/foca_casbin_adapter/test_casbin_rule.py L15, L159-200
  • tests/security/access_control/test_access_control_server.py L14-17, L598-757 (+6 small edits)
  • tests/test_audit.py L19-584 (4 small edits)

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

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #765   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           74        74           
  Lines         9472      9517   +45     
=========================================
+ Hits          9472      9517   +45     
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 12, 2026 09:56
@sourcery-ai

sourcery-ai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit aa45d08

#760 feat: report invalid fields in the permissions API · 3 of 3 met

# Requirement Status Notes
1 Report invalid fields from the permissions API’s own checks, including subjects, roles, and rule fields. ✅ Met The API raises InvalidFieldsProblem with a JSON Pointer or parameter for invalid rules, roles, identifiers, and pagination.
2 Use stable codes and never quote rejected values in errors. ✅ Met Field errors carry stable codes and value-safe details; rule-validation errors retain ValueError compatibility while exposing a value-safe reason.
3 Document the codes next to the existing ones. ✅ Met The permissions API codes and their reported locations are documented in the invalid-request reference.

@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 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="docs/problems/invalid-request.md" line_range="118" />
<code_context>
+| `unknown-policy-type` | `#/policy_type` | `policy_type` is not defined in the app's access control model. |
+| `unknown-property` | `#/rule/<key>` | `rule` has a key other than `v0` to `v5`. |
+| `non-consecutive-keys` | `#/rule` | The keys of `rule` are not consecutive, starting from `v0`. |
+| `wrong-value-count` | `#/rule` | `rule` has more or fewer values than its policy type's definition has fields. |
+| `too-short`, `too-long` | `#/rule/vN` | A value is empty or longer than 1024 characters. |
+| `invalid-character` | `#/rule/vN`, parameter `id` | A value has a comma or line break, or starts with `#`; or `id` has characters other than those of `access_control.id_charset`. |
</code_context>
<issue_to_address>
**Empty rules report the wrong error**

When an HTTP POST or PUT supplies an empty `rule` object, the request-body schema requires `rule.v0`, so `BodyValidator` rejects the request before `_get_rule()` reports `wrong-value-count` at `#/rule`; callers receive `required` at `#/rule/v0` instead of the documented code and location.

Allow an empty `rule` through body validation so `_get_rule()` can return `wrong-value-count` at `#/rule`.

Also at `docs/problems/invalid-request.md:113`.
</issue_to_address>

### Comment 2
<location path="foca/security/access_control/access_control_server.py" line_range="167" />
<code_context>
     MAX_RULE_VALUES,
+    InvalidRuleError,
     validate_rule,
 )
 from foca.utils.logging import escape_log_value, log_traffic_if
</code_context>
<issue_to_address>
**Aggregate invalid fields**

The issue describes `errors` listing each invalid field, but `_invalid_field` constructs an `InvalidFieldsProblem` with a single `FieldError`. Requests with multiple invalid fields therefore report only the first one found.
</issue_to_address>

### Comment 3
<location path="docs/problems/invalid-request.md" line_range="112" />
<code_context>
+
+| Code | Reported at | Meaning |
+| --- | --- | --- |
+| `invalid-type` | `#`, `#/rule`, `#/policy_type`, `#/rule/vN` | The body or `rule` is not an object, or `policy_type` or a value is not a string. |
+| `required` | `#/rule`, `#/policy_type` | `rule` or `policy_type` is missing. |
+| `pattern-mismatch` | `#/policy_type` | `policy_type` is not `p` or `g`, optionally followed by digits. |
</code_context>
<issue_to_address>
**Pagination type errors are undocumented**

When a request supplies a non-integer value for `page` or `page_size`, a non-integer `page` or `page_size` is rejected by parameter validation with code `invalid-type` at that parameter, but the table lists only body pointers for this code. Callers cannot use the documented code-location mapping to handle these pagination errors consistently.

Add `page` and `page_size` parameters to the documented `invalid-type` locations.
</issue_to_address>

### Comment 4
<location path="tests/security/access_control/foca_casbin_adapter/test_casbin_rule.py" line_range="195" />
<code_context>
+        exc = exc_info.value
+        assert isinstance(exc, InvalidRuleError)
+        assert (exc.field, exc.code) == (field, code)
+        assert "s3cr3t" not in exc.reason
+
+    def test_reason_defaults_to_message(self) -> None:
</code_context>
<issue_to_address>
**Other rejected values leak unnoticed**

When an error echoes a rejected value other than the literal `s3cr3t`, the fixed-string checks in `TestInvalidRuleError.test_fields` (line 195) and `TestInvalidFields._assert_field` (lines 695–696) still pass if an error echoes a rejected value other than `s3cr3t`, such as the 1025-character value in the too-long case. That leaves value disclosure regressions undetected by these tests.

Pass each rejected value to the assertion helper and verify that value is absent from the client-facing error details.

Also at `tests/security/access_control/test_access_control_server.py:695-696`.
</issue_to_address>

Sourcery assessment

Approval pending. 3 findings to address first.

Blocking findings: docs/problems/invalid-request.md:118, foca/security/access_control/access_control_server.py:167, tests/security/access_control/foca_casbin_adapter/test_casbin_rule.py:195


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

Comment thread docs/problems/invalid-request.md Resolved
Comment thread docs/problems/invalid-request.md Resolved
@uniqueg
uniqueg merged commit b96df20 into dev Nov 12, 2026
57 checks passed
@uniqueg
uniqueg deleted the feat/760-permissions-invalid-fields branch November 12, 2026 17:29
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.

feat: report invalid fields in the permissions API

1 participant