Repository navigation
feat: report invalid fields in 400 responses - #711
Conversation
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]>
Reviewer's GuideThis 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 collectionsequenceDiagram
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
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
- 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]>
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,statusanddetailstay exactly as before.400problem details get the extension membererrors, in the form of the example in RFC 9457 §3.detail, a location and a stable kebab-casecode(e.g.required,too-long,invalid-format,unknown-property,unknown-parameter).pointer(a JSON Pointer as a URI fragment, e.g.#/organization/url) orparameter(the name of a query, path, header, cookie or form-data parameter).code: invalid-requestand atypeURI.Request rejected: #/name (too-long)) instead of the validator's message, which quoted the values.foca/errors/fields.pyimports only jsonschema and the core. It holdsFieldError,json_pointer(),schema_field_errors(),unknown_parameters()andadd_field_errors().foca.errors.InvalidFieldsProblem(errors, detail=None)for their own checks. It subclasses Connexion'sBadRequestProblem(RequestValidationProblem), so exception maps,exceptclauses andvalidation_detailswork unchanged.foca/api/validation.py):detail.ParameterValidatoruses 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, and a warning is logged.validator_map).validation_details: falsedropserrorslike the other request-specific details.public_membersfilterstype,codeanderrors.typeorcodemapped to the exception class wins.docs/problems/invalid-request.mdcovers the format, the generic codes, what is collected, app checks, configuration and specifications.foca.errors.fieldsis added to the API reference.ProblemandFieldErrorare infoca/api/problem-details.yaml(package data). FOCA's permissions andmeAPIs declare the same schemas; a test keeps them in sync.typeURI (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 asfoca.errors.fields.INVALID_REQUEST_TYPE, and the page carries a note not to move it. Apps can map their owntypeonRequestValidationProblem.Connexion 3 (1.0.0-rc1):
BadRequestProblemfrom jsonschema errors too. They can feedschema_field_errors()the same way, and the handler only needsadd_field_errors().Limits (documented):
errorsholds at most 100 entries, and entries are shortened tomax_detail_length. Long pointers are cut back to the closest containing field.errors.Verification
pytestwith a MongoDB 7.0 onlocalhost:12345(ate2b7632): 4588 passed, 3 skipped. Coverage is 100% (coverage report: TOTAL 8964, 0 missed). Atcf1f4c3, without MongoDB: 4396 passed;tests/apiandtests/errorsgive 100% coverage of the changed modules.ruff check,ruff format --check,mypy,ast-grep scanandsemgrep scan --config .semgrep --errorare clean.mkdocs build --strictpasses.uv sync --locked --extra dev):devat8b69b3c: 1956 passed, 11 skipped.devate47cac2: 1319 passed, 11 skipped.tests/test_chart.pyand 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.cf1f4c3(run 42081900153): all checks passed (3 intended skips),CI passedgreen.cf1f4c3with the same results.Declined review findings
Quality (low), rename
FieldError: the reviewer suggested a non-exception name such asInvalidField. Declined: the issue and RFC 9457 call the entries errors (membererrors), and the name matches the issue's wording ("field errors").Quality (low), configurable
typeURI: declined, as there are no new config keys. MappingtypeonRequestValidationProblemoverrides it, and the docs now say so.Quality (medium), "Must be of type None.": declined after checking.
coerce_typeraisesTypeValidationErroronly for the types in Connexion'sTYPE_MAP, sotypeis 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:strict_validation, unknown and invalid declared parameters are listed together.Open questions
None.
🤖 Generated with Claude Code