Repository navigation
feat(errors): serve validation error details - #464
Conversation
Add `exceptions.validation_details` (off by default): responses to Connexion's validation exceptions get the validator's reason as `detail`, logged at INFO shortened and escaped, with Connexion's validation logger raised to CRITICAL. Add `exceptions.max_detail_length` (500) and the public `problem_response()` and `shorten_detail()`, moved from cloud-registry. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Document `validation_details`, `max_detail_length`, `problem_response()` and `shorten_detail()`, and add the options to the config template. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Filter out the request validation messages of Connexion's validation logger instead of raising it to CRITICAL, so that its messages on invalid responses are kept (the only record of their cause with `logging: minimal`). Reject exceptions other than werkzeug HTTP exceptions in `problem_response()` with a `ValueError`, and document that rejected values may be logged and that extension members must be public. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThis PR moves request-validation detail handling into FOCA’s exception framework behind opt-in configuration, safely shortens and escapes exposed reasons, adds reusable request-specific problem-response helpers, and routes all responses through shared filtering/header/media-type logic with comprehensive tests and documentation. Sequence diagram for validation error detail handlingsequenceDiagram
participant Client
participant Connexion
participant FOCA
participant ValidationLogger
Client->>Connexion: Invalid request
Connexion->>FOCA: BadRequestProblem or ExtraParameterProblem
FOCA->>FOCA: _validation_reason(exception)
FOCA->>FOCA: _shorten(reason, max_detail_length)
FOCA->>FOCA: escape_log_value(detail)
FOCA-->>ValidationLogger: INFO Request rejected
FOCA->>FOCA: _response(exception, problem, conf)
FOCA->>FOCA: _filter_problem(problem, conf)
FOCA-->>Client: Configured error response with detail
Sequence diagram for request validation logger filteringsequenceDiagram
participant Connexion
participant Filter
participant FOCA
participant ValidationLogger
Connexion->>ValidationLogger: Request validation record
ValidationLogger->>Filter: _keep_response_validation_records(record)
alt validator is response
Filter-->>ValidationLogger: Keep record
else Request validation record
Filter-->>ValidationLogger: Drop record
FOCA-->>ValidationLogger: Log shortened and escaped reason at INFO
end
Flow diagram for request-specific problem responsesflowchart LR
Controller[Controller] --> ProblemResponse[problem_response]
ProblemResponse --> Validate[Validate HTTPException and extensions]
Validate --> Resolve[_resolve_problem]
Resolve --> Shorten[_shorten description]
Shorten --> Response[_response]
Response --> Filter[_filter_problem]
Filter --> Client[Error response with headers and media type]
File-Level Changes
Assessment against linked issues
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 #464 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 29 29
Lines 3287 3342 +55
=========================================
+ Hits 3287 3342 +55
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 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="templates/config.yaml" line_range="31-33" />
<code_context>
# `application/json` if your specs declare it for errors (cf. docs)
media_type: application/problem+json
+ # Serve the reasons of request validation errors as `detail` (cf. docs)
+ validation_details: False
+ # Maximum length of request-specific details (longer ones are shortened)
+ max_detail_length: 500
# SECURITY CONFIGURATION
</code_context>
<issue_to_address>
**Old replicas reject updated configuration**
When a deployment updates the shared configuration with these template keys while replicas running a release without them are still starting or restarting, the old `ConfigParser` validates the new keys against its `ExceptionConfig`, which does not define them, and raises a Pydantic `ValidationError` instead of starting the replica.
Apply the new configuration keys only after all old-version replicas have stopped loading it, or make older replicas tolerate unknown exception settings during the rollout.
</issue_to_address>
### Comment 2
<location path="foca/errors/exceptions.py" line_range="73" />
<code_context>
+_VALIDATION_LOGGER = "connexion.decorators.validation"
+
+# Members of problem details set by `problem_response()` itself
+_RESERVED_MEMBERS = ("title", "status", "detail")
+
+
</code_context>
<issue_to_address>
**Mapped problem members are overwritten**
When a caller supplies `type` or `instance` as an extension, `problem.update(**extensions)` overwrites the mapped `type` or `instance`, so the response carries a caller-supplied problem type or occurrence identifier instead of the mapped value.
Treat `type` and `instance` as reserved members so extensions cannot overwrite their mapped values.
Also at `foca/errors/exceptions.py:345-349`.
</issue_to_address>
### Comment 3
<location path="foca/errors/exceptions.py" line_range="399" />
<code_context>
+ if conf.logging is not ExceptionLoggingEnum.none:
+ logger.info(
+ "Request rejected: %s",
+ escape_log_value(problem.get("detail", problem["title"])),
+ )
+ return _response(exc=exception, problem=problem, conf=conf)
</code_context>
<issue_to_address>
**Escaped log detail exceeds limit**
When the retained portion of a long validation reason contains control characters such as newlines, `_validation_handler_json` shortens the raw reason before `escape_log_value()` expands control characters, so the emitted request-specific log detail exceeds `max_detail_length`.
Escape the reason before applying `_shorten()` so the emitted detail stays within `max_detail_length`.
Also at `foca/errors/exceptions.py:395`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 2 findings to address first, and with validation_details enabled, validator reasons and BadRequestProblem descriptions are returned to callers; problem_response() can also include caller-visible extension values. If those details contain information that should remain private, reverting stops future disclosures but cannot retract what callers have already received.
Blocking findings: templates/config.yaml:33, foca/errors/exceptions.py:73
Reject `type` as an extension member of `problem_response()`, as it is mapped to the exception class, and escape logged validation reasons before shortening them, so that they stay within `max_detail_length`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Moves cloud-registry's validation problem handling into FOCA's error handling (
foca.errors.exceptions,ExceptionConfig), as proposed in #461:exceptions.validation_details: bool = False(new, opt-in): responses to Connexion's validation exceptions (BadRequestProblem,ExtraParameterProblem) get the validator's reason asdetail(lists, e.g., for form data, joined with"; "), falling back to the mapped details if there is none; title and status as mapped. The reason is logged atINFO, shortened and escaped (escape_log_value(); not withlogging: none), instead of the exception. Deviation from the issue: instead of raising Connexion's validation logger (connexion.decorators.validation) toCRITICAL, a logger filter drops its request validation records (body errors, parameter conversion messages with raw values, debug lines) and keeps its response validation records (validator="response"); raising the level would also have dropped the only record of why a response failed validation withlogging: minimal(adversarial review, medium). The filter is added once per process.exceptions.max_detail_length: PositiveInt = 500(new): longer details are shortened in the middle (start and end kept, joined by…), in responses and log messages. Unlike cloud-registry's version, a limit of 1 gives…rather than the whole detail.problem_response(exc, **extensions)(new, public): response with the request-specific description of a werkzeug exception asdetail(shortened), the problem details mapped to its class (title, and other mapped members such astype), status from the exception, and extension members.ValueErrorfor non-werkzeug exceptions (e.g., Connexion'sProblemException), exceptions without an HTTP error status code (400 to 599) or description, and for extension memberstitle,status,detailortype(mapped to the class).shorten_detail(detail)(new, public): for log messages, using the current app'smax_detail_length._response()): configuredmedia_type,public_membersfiltering (withoutdetail, the reason is not sent), and the exception's headers (_build_headers()).docs/configuration/exceptions.md(new section "Request-specific details", with example responses), API reference, and both options intemplates/config.yaml.Backwards compatible: off by default, responses and logs are unchanged; so no migration note (
docs/migration-0.18.mduntouched). The release notes mention it via this PR's commits.Verification
coverage run -m pytest(MongoDB 7.0 on port 12345): 2183 passed, 1 skipped;coverage report: 100%mypy: no issues in 86 source filesruff check .,ruff format --check .: passedpre-commit run --all-files(incl. semgrep and ast-grep and their rule tests): passedmkdocs build --strict: passedDeclined review findings
INFO(adversarial, low): kept, as the issue asks for the reason atINFO; they are shortened and escaped, and the docs now say so. Connexion itself logged parameter conversion errors with the raw value atINFObefore (now filtered out).templates/config.yamlbreak older replicas reading a shared config during a rollout (medium): declined, as this applies to every new option, the issue asks for them in the template, and both are opt-in with defaults.shorten_detail()is not used inside FOCA (quality, low): intentionally public for apps' log messages, per the issue; tested.Open questions
None blocking. From the issue, for the maintainer: turn
validation_detailson by default (and always silence Connexion's unescaped log message), e.g., from FOCA 1.0?Follow-up
In cloud-registry (separate issue there): set
exceptions.validation_details: true, useproblem_response()andshorten_detail()from FOCA, and deletevalidation_problem(),problem(),_response(),shorten_detail(),MAX_DETAIL_LENGTH, the handler registrations and the logger setting increate_app().Closes #461
🤖 Generated with Claude Code
Summary by Sourcery
Add opt-in support for serving and safely logging request-specific validation error details.
New Features:
Enhancements:
Documentation:
Tests: