Skip to content

feat: report invalid fields in 400 responses - #711

Merged
uniqueg merged 6 commits into
devfrom
feat/586-field-errors
Nov 5, 2026
Merged

uniqueg merged 6 commits into
devfrom
feat/586-field-errors

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Closes #586

Summary

Responses to invalid requests now list all invalid fields in machine-readable form, so clients can show each message at its field. The change is purely additive: title, status and detail stay exactly as before.

  • Format (RFC 9457): 400 problem details get the extension member errors, in the form of the example in RFC 9457 §3.
    • Each entry has a detail, a location and a stable kebab-case code (e.g. required, too-long, invalid-format, unknown-property, unknown-parameter).
    • The location is either pointer (a JSON Pointer as a URI fragment, e.g. #/organization/url) or parameter (the name of a query, path, header, cookie or form-data parameter).
    • The responses also get a top-level code: invalid-request and a type URI.
  • No echoed values: messages are written from the JSON Schema keyword and the schema, never from the rejected value, which may hold credentials (cf. cloud-registry PR 369). Tests cover this for every keyword, for responses and for logs.
    • The validation handler now logs invalid fields by location and code (Request rejected: #/name (too-long)) instead of the validator's message, which quoted the values.
  • Framework-neutral core: foca/errors/fields.py imports only jsonschema and the core. It holds FieldError, json_pointer(), schema_field_errors(), unknown_parameters() and add_field_errors().
  • Exception for apps: apps raise foca.errors.InvalidFieldsProblem(errors, detail=None) for their own checks. It subclasses Connexion's BadRequestProblem (RequestValidationProblem), so exception maps, except clauses and validation_details work unchanged.
  • Thin Connexion 2 hook (foca/api/validation.py):
    • Body: the body validator lists all schema errors. It validates again only when the body is invalid, and keeps Connexion's message as detail.
    • Parameters: a new ParameterValidator uses Connexion's checks up to the first invalid parameter, as before. FOCA then checks the remaining parameters itself: it logs nothing about them, and a failing check never changes the rejection.
    • Errors while listing: if listing fails for any reason, the request is rejected exactly as before, without errors, and a warning is logged.
    • Apps' own validators still win (validator_map).
  • Config: no new config keys.
    • validation_details: false drops errors like the other request-specific details.
    • public_members filters type, code and errors.
    • A type or code mapped to the exception class wins.
  • Docs and schemas:
    • A new page docs/problems/invalid-request.md covers the format, the generic codes, what is collected, app checks, configuration and specifications.
    • The exceptions docs and the migration guide for 0.22 are updated, and foca.errors.fields is added to the API reference.
    • Reusable OpenAPI 3 schemas Problem and FieldError are in foca/api/problem-details.yaml (package data). FOCA's permissions and me APIs declare the same schemas; a test keeps them in sync.

type URI (my choice, reversible): https://foca.readthedocs.io/en/latest/problems/invalid-request/. It is the docs page of the problem type, so it can be dereferenced. It is set as foca.errors.fields.INVALID_REQUEST_TYPE, and the page carries a note not to move it. Apps can map their own type on RequestValidationProblem.

Connexion 3 (1.0.0-rc1):

  • Only the two validator subclasses are Connexion-2 specific.
  • Connexion 3's request validators raise BadRequestProblem from jsonschema errors too. They can feed schema_field_errors() the same way, and the handler only needs add_field_errors().

Limits (documented):

  • errors holds at most 100 entries, and entries are shortened to max_detail_length. Long pointers are cut back to the closest containing field.
  • The body is checked before the parameters, as by Connexion. A request with an invalid body lists only the body's fields.
  • App checks run on schema-valid requests only.
  • Requests rejected for other reasons (invalid JSON, unpaired surrogates, form fields that can't be coerced) get no errors.

Verification

  • pytest with a MongoDB 7.0 on localhost:12345 (at e2b7632): 4588 passed, 3 skipped. Coverage is 100% (coverage report: TOTAL 8964, 0 missed). At cf1f4c3, without MongoDB: 4396 passed; tests/api and tests/errors give 100% coverage of the changed modules.
  • ruff check, ruff format --check, mypy, ast-grep scan and semgrep scan --config .semgrep --error are clean. mkdocs build --strict passes.
  • Downstream dev heads (FOCA installed editable from this branch into their locked environments, uv sync --locked --extra dev):
    • cloud-registry dev at 8b69b3c: 1956 passed, 11 skipped.
    • proTES dev at e47cac2: 1319 passed, 11 skipped.
    • Their Helm chart tests (tests/test_chart.py and the chart and overlay tests, 166 and 107 tests) were deselected. Helm isn't installed on this machine, so the library chart couldn't be built. Those tests don't touch FOCA's Python code.
  • CI on the PR at cf1f4c3 (run 42081900153): all checks passed (3 intended skips), CI passed green.
  • Downstream suites were run again at cf1f4c3 with the same results.

Declined review findings

  • Quality (low), rename FieldError: the reviewer suggested a non-exception name such as InvalidField. Declined: the issue and RFC 9457 call the entries errors (member errors), and the name matches the issue's wording ("field errors").

  • Quality (low), configurable type URI: declined, as there are no new config keys. Mapping type on RequestValidationProblem overrides it, and the docs now say so.

  • Quality (medium), "Must be of type None.": declined after checking. coerce_type raises TypeValidationError only for the types in Connexion's TYPE_MAP, so type is always set there; a comment in the code says so.

  • Sourcery (high), parameters omitted for invalid bodies: declined; my reasoning is in the thread, and the limit is documented. Connexion 2 runs the body validator around the parameter validator, so collecting both would need state shared between Connexion's decorators, plus a separate path for operations without parameters. That fits better with the move to Connexion 3 (FOCA 1.0.0-rc1), and the core is already framework-neutral for it.

Sourcery's other three findings are fixed in cf1f4c3:

  • pointers are validated (this also fixes a possible endless loop when shortening them);
  • when the fields of any parameter can't be listed, no fields are listed, rather than some;
  • with strict_validation, unknown and invalid declared parameters are listed together.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 5 commits November 5, 2026 18:02
Add foca.errors.fields, which converts JSON Schema errors to entries
of the problem details member errors (RFC 9457, section 3: detail,
pointer or parameter, plus a kebab-case code), with messages written
from the schema keyword only, never from the rejected value.

Add InvalidFieldsProblem, a RequestValidationProblem that apps raise
with the invalid fields of their own checks. The validation handler
adds errors, type and code to the problem details, keeping title,
status and detail, and logs the fields by location and code instead
of the validator's message.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
FOCA's body validator collects all schema errors of an invalid body,
and a new parameter validator all invalid parameters, instead of the
first only. Both raise InvalidFieldsProblem, with the message of
Connexion's validator on the first error as detail, as before.
Validators of apps still win.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Document the problem type invalid-request, its entries and generic
codes on a page of its own, whose URL is the type URI, and ship
reusable OpenAPI schemas (Problem, FieldError) in
foca/api/problem-details.yaml, which FOCA's permissions and me APIs
declare too. Update the exceptions docs and the migration guide.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fix review findings: listing invalid fields never turns a rejection
into a 500 (empty parameter names, enum values that aren't JSON, any
failure falls back to the response without errors, with a warning).
The parameter validator reuses Connexion's validate_*_parameter
helpers instead of copying their lookups. Export json_pointer from
foca.errors, qualify the docs on request keys in locations, and test
nullable parameters.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Connexion checks parameters until the first invalid one, as before;
FOCA checks the remaining ones itself, without logging their values
and without failing the rejection (e.g., for parameters whose checks
raise in Connexion). Document that the body is checked before the
parameters, as Connexion does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.22.0 milestone Nov 5, 2026
@uniqueg uniqueg added priority: medium Medium priority type: feature New feature or request labels Nov 5, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR adds RFC 9457-compatible, machine-readable invalid-field reporting to 400 responses by converting schema and parameter validation failures into bounded, location-aware FieldError entries, integrating them through Connexion validation and exception handling, and documenting and testing configuration, API schema, compatibility, and secret-redaction behavior.

Sequence diagram for invalid request field collection

sequenceDiagram
    participant Client
    participant Connexion as Connexion validators
    participant FOCA as FOCA validation
    participant Handler as Exception handler

    Client->>Connexion: Send request
    Connexion->>FOCA: Validate request body
    alt Body invalid
        FOCA->>FOCA: schema_field_errors()
        FOCA-->>Handler: InvalidFieldsProblem(errors, detail)
    else Body valid
        Connexion->>FOCA: Validate parameters
        FOCA->>FOCA: _parameter_errors()
        alt Parameter invalid
            FOCA-->>Handler: InvalidFieldsProblem(errors, detail)
        else Parameters valid
            FOCA-->>Client: Continue request handling
        end
    end
    Handler->>Handler: add_field_errors()
    Handler-->>Client: 400 problem details with errors
Loading

File-Level Changes

Change Details Files
Added a framework-neutral field-error model and JSON Schema conversion utilities for RFC 9457 invalid-request details.
  • Introduced validated FieldError entries with JSON Pointer or parameter locations and kebab-case codes.
  • Converted schema failures into stable, non-value-echoing messages across validation keywords.
  • Added helpers for unknown parameters, truncation, entry limits, serialization, and safe log descriptions.
foca/errors/fields.py
Extended request validation to collect and expose all invalid body and parameter fields while preserving existing rejection details and behavior.
  • Collected body schema errors after Connexion rejects an invalid body.
  • Added parameter validation that preserves Connexion's first-error behavior while safely checking remaining parameters.
  • Handled form-data, unknown parameters, listing failures, and app validator precedence.
  • Registered the new parameter validator for OpenAPI and access-control APIs.
foca/api/validation.py
foca/api/register_openapi.py
foca/security/access_control/register_access_control.py
Integrated invalid field errors into exception handling, configuration filtering, logging, and application-facing exception APIs.
  • Added InvalidFieldsProblem as a RequestValidationProblem-compatible exception for app checks.
  • Added top-level invalid-request type and code plus serialized errors to 400 responses.
  • Kept mapped type/code values authoritative and honored validation_details and public_members.
  • Replaced validator-message logging with location/code logging when field errors are available, preventing rejected values from appearing in responses and logs.
foca/errors/classes.py
foca/errors/__init__.py
foca/errors/exceptions.py
docs/configuration/exceptions.md
Documented and specified the new invalid-request format for consumers and API authors.
  • Added the invalid-request problem page with format, codes, collection limits, app usage, configuration, and migration guidance.
  • Added reusable packaged OpenAPI Problem and FieldError schemas and synchronized FOCA API specifications.
  • Exposed the field utilities in the API reference and packaged the schema data.
docs/problems/invalid-request.md
docs/migration-0.22.md
docs/reference.md
foca/api/problem-details.yaml
foca/security/access_control/api/access-control-specs.yaml
foca/security/access_control/api/me-specs.yaml
mkdocs.yml
pyproject.toml
Added comprehensive coverage for field conversion, response integration, security guarantees, schema synchronization, configuration behavior, and failure fallbacks.
  • Tested all supported schema keywords, pointer escaping, truncation, deduplication, and the 100-entry limit.
  • Tested body, parameter, form-data, unknown-parameter, app-raised, and failed-listing scenarios.
  • Verified unchanged details when validation details are disabled and ensured secrets are absent from responses and logs.
tests/api/test_problem_details.py
tests/api/test_validation.py
tests/errors/test_classes.py
tests/errors/test_errors.py
tests/errors/test_fields.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 5, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #711    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           70        71     +1     
  Lines         8731      8981   +250     
==========================================
+ Hits          8731      8981   +250     
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 5, 2026 17: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 4 issues

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

## Individual Comments

### Comment 1
<location path="foca/errors/fields.py" line_range="116" />
<code_context>
+            raise ValueError(f"Code of field error is not kebab-case: '{self.code}'")
+        if (self.pointer is None) is (self.parameter is None):
+            raise ValueError("Field errors need either a pointer or a parameter.")
+        if self.pointer is not None and not self.pointer.startswith("#"):
+            raise ValueError(
+                f"Pointer of field error is not a URI fragment: '{self.pointer}'"
</code_context>
<issue_to_address>
**Invalid pointers break field reporting**

When an app supplies a pointer that starts with `#` but is not a valid JSON Pointer URI fragment, `FieldError.__post_init__` accepts the pointer and `to_dict()` emits it unchanged, so clients cannot reliably resolve the field; when the pointer is long and has no `/`, truncation repeatedly assigns the same value and hangs the error response.

Validate that pointers are valid JSON Pointer URI fragments before accepting them, and reject invalid values.

Also at `foca/api/problem-details.yaml:61-62`, `foca/errors/fields.py:141`.
</issue_to_address>

### Comment 2
<location path="foca/api/validation.py" line_range="149" />
<code_context>
+            "Invalid fields of a rejected request could not be listed: %s",
+            type(exc).__name__,
+        )
+        return []
+
+
</code_context>
<issue_to_address>
**Field errors become incomplete after listing fails**

When listing an invalid parameter fails and a later parameter is also invalid, `_list_fields` returns an empty list for the failed conversion, but `ParameterValidator` continues collecting later errors and raises `InvalidFieldsProblem` with an incomplete `errors` member instead of falling back to the response without errors.

Propagate listing failures so parameter validation abandons the partial error list and uses the fallback response.

Also at `foca/api/validation.py:325`.
</issue_to_address>

### Comment 3
<location path="foca/api/validation.py" line_range="127" />
<code_context>
+            )
+            if not errors:
+                raise
+            raise InvalidFieldsProblem(errors, detail=exc.detail) from None
+
+
</code_context>
<issue_to_address>
**Parameters omitted for invalid body**

When body validation finds errors, this raises before parameter validation runs, so invalid query, path, header, or other parameter fields on the same request are omitted from `errors`. Collect those errors too to meet the issue's request-wide collection ask.
</issue_to_address>

### Comment 4
<location path="foca/api/validation.py" line_range="299-300" />
<code_context>
+            if self.strict_validation:
+                query = self.validate_query_parameter_list(request)
+                formdata = self.validate_formdata_parameter_list(request)
+                if formdata or query:
+                    raise ExtraParameterProblem(formdata, query)
+            checks = [
+                *(
</code_context>
<issue_to_address>
**Invalid declared fields are omitted**

When strict validation is enabled and a request has both an unknown parameter and an invalid declared parameter, `ExtraParameterProblem` is raised before the declared-parameter checks run, so `_field_errors` reports the unknown parameters but omits the invalid declared parameters from `errors`.

Run the declared-parameter checks before raising `ExtraParameterProblem` and include their errors in the response.

Also at `foca/errors/exceptions.py:356-361`, `foca/api/validation.py:301`.
</issue_to_address>

Linked issues

#586 feat: report invalid fields in 400 responses · 6 of 7 met

# Requirement Status Notes
1 Add errors entries with a readable detail, a body pointer or parameter name, and a stable kebab-case code. ✅ Met The shared field-error implementation handles body and parameter locations, and defines codes and messages from schema constraints.
2 Add a stable top-level code and a type URI for invalid requests. ✅ Met Responses with listed field errors receive the defaults invalid-request and the documented problem-type URI; mapped values are preserved.
3 Collect all errors of a request, including schema errors and errors from app checks. 🟡 Partly met All errors are listed within the body or parameter validation phase, and apps can report their own checks with InvalidFieldsProblem, but an invalid body stops validation before parameters are checked.
4 Keep the format generic to RFC 9457 clients, without requiring clients to know FOCA's codes. ✅ Met The response uses the RFC 9457 errors extension shape, and the documentation describes showing messages without knowing the codes.
5 Document the format and generic codes, and provide a reusable OpenAPI schema for apps. ✅ Met The new invalid-request documentation covers the format and codes, and foca/api/problem-details.yaml supplies reusable Problem and FieldError schemas.
6 Keep title, status, and detail as before. ✅ Met Schema and parameter validation retain Connexion's first-error message as detail; the response handler adds field errors without replacing the existing problem members.
7 Design the change with the move to Connexion 3 in mind. ✅ Met The field-error conversion and response handling are shared outside the Connexion 2 validator subclasses.

Sourcery assessment

Approval pending. 4 findings to address first.

Blocking findings: foca/errors/fields.py:116, foca/api/validation.py:149, foca/api/validation.py:127, foca/api/validation.py:300


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

Comment thread foca/errors/fields.py Resolved
Comment thread foca/api/validation.py Resolved
Comment thread foca/api/validation.py Resolved
Comment thread foca/api/validation.py Resolved
- Reject pointers that aren't JSON Pointers as URI fragments, which
  could also make shortening them loop forever; add the pattern to
  the FieldError schemas.
- List no fields rather than a part of them if those of a parameter
  can't be listed.
- With strict_validation, list invalid declared parameters together
  with unknown ones, checked by FOCA only, without logging values.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 99a5240 into dev Nov 5, 2026
83 checks passed
@uniqueg
uniqueg deleted the feat/586-field-errors branch November 5, 2026 18:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority: medium Medium priority type: feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: report invalid fields in 400 responses

1 participant