Skip to content

feat(errors): serve validation error details - #464

Merged
uniqueg merged 5 commits into
devfrom
feat/validation-error-details
Oct 24, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/validation-error-details

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

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 as detail (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 at INFO, shortened and escaped (escape_log_value(); not with logging: none), instead of the exception. Deviation from the issue: instead of raising Connexion's validation logger (connexion.decorators.validation) to CRITICAL, 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 with logging: 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 as detail (shortened), the problem details mapped to its class (title, and other mapped members such as type), status from the exception, and extension members. ValueError for non-werkzeug exceptions (e.g., Connexion's ProblemException), exceptions without an HTTP error status code (400 to 599) or description, and for extension members title, status, detail or type (mapped to the class).
  • shorten_detail(detail) (new, public): for log messages, using the current app's max_detail_length.
  • All these responses share the code path of FOCA's generic handler (_response()): configured media_type, public_members filtering (without detail, the reason is not sent), and the exception's headers (_build_headers()).
  • Docs: docs/configuration/exceptions.md (new section "Request-specific details", with example responses), API reference, and both options in templates/config.yaml.

Backwards compatible: off by default, responses and logs are unchanged; so no migration note (docs/migration-0.18.md untouched). 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 files
  • ruff check ., ruff format --check .: passed
  • pre-commit run --all-files (incl. semgrep and ast-grep and their rule tests): passed
  • mkdocs build --strict: passed
  • CI: all checks passed (unit tests on Python 3.11 to 3.15 with MongoDB 7.0 and 8.0 and lowest dependencies, integration tests, lint/type-check/build, charts, image scans, CodeQL, Codecov, Read the Docs)

Declined review findings

  • Rejected parameter values (e.g., a malformed header or query value) now reach the logs at INFO (adversarial, low): kept, as the issue asks for the reason at INFO; they are shortened and escaped, and the docs now say so. Connexion itself logged parameter conversion errors with the raw value at INFO before (now filtered out).
  • The filter on Connexion's logger is process-wide and permanent (quality, low): documented; it only drops request validation records, which FOCA's handler logs instead, so a second app without the option loses only Connexion's unescaped request messages.
  • Sourcery: new keys in templates/config.yaml break 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_details on 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, use problem_response() and shorten_detail() from FOCA, and delete validation_problem(), problem(), _response(), shorten_detail(), MAX_DETAIL_LENGTH, the handler registrations and the logger setting in create_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:

  • Add opt-in request-validation details in error responses and logs, with configurable maximum detail length.
  • Add public helpers for generating request-specific problem responses and shortening details.

Enhancements:

  • Route validation and request-specific errors through the common configured response handling, including media types, public-member filtering, and exception headers.
  • Filter unescaped Connexion request-validation log records while preserving response-validation records.

Documentation:

  • Document request-specific validation details, detail shortening, problem responses, and the new exception configuration options.

Tests:

  • Add comprehensive coverage for detail shortening, request-specific responses, validation handling, logging, filtering, and configuration behavior.

uniqueg and others added 3 commits October 24, 2026 13:47
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This 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 handling

sequenceDiagram
    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
Loading

Sequence diagram for request validation logger filtering

sequenceDiagram
    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
Loading

Flow diagram for request-specific problem responses

flowchart 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]
Loading

File-Level Changes

Change Details Files
Adds opt-in serving and safe logging of Connexion request-validation reasons.
  • Introduces validation_details and max_detail_length configuration.
  • Handles BadRequestProblem and ExtraParameterProblem with validator reasons as response details, including list joining and mapped-detail fallback.
  • Shortens and escapes logged reasons, while filtering unescaped request-validation records and retaining response-validation records.
  • Documents configuration, behavior, security considerations, and example responses.
foca/errors/exceptions.py
foca/models/config.py
templates/config.yaml
docs/configuration/exceptions.md
docs/reference.md
tests/errors/test_errors.py
Introduces public helpers for request-specific problem responses and detail shortening.
  • Adds problem_response() for Werkzeug HTTP exceptions with mapped metadata, status, description, extensions, configured media type, public-member filtering, and exception headers.
  • Rejects unsupported exceptions, invalid statuses or descriptions, and reserved extension names.
  • Adds shorten_detail() backed by the current app configuration and middle-preserving shortening semantics.
  • Refactors generic error responses through shared filtering and response construction.
foca/errors/exceptions.py
docs/configuration/exceptions.md
docs/reference.md
tests/errors/test_errors.py
Expands automated coverage for validation details, response construction, configuration validation, logging, filtering, truncation, and backwards compatibility.
  • Tests default-disabled behavior and configured media types, public members, headers, mapped problems, and logging modes.
  • Covers malformed or absent validation reasons, form/list details, escaped and truncated values, and process-wide logger-filter installation.
  • Validates positive maximum detail lengths and reserved extension handling.
tests/errors/test_errors.py

Assessment against linked issues

Issue Objective Addressed Explanation
#461 Add opt-in Connexion validation details: return the validator’s reason as a shortened detail (joining lists and falling back to mapped details), log it at INFO in escaped, shortened form, and prevent Connexion from logging the full unescaped request-validation message while preserving default behavior. ✅
#461 Add configurable detail-length limits and public problem_response() and shorten_detail() helpers, with response status, mapped problem members, exception headers, configured media type, and public_members filtering. ✅
#461 Document the new configuration options and public helpers, including example responses, and expose the options in the configuration template. ✅

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 Oct 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (0be1f73) to head (8180ad6).

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     
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 October 24, 2026 12:07

@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="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


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

Comment thread templates/config.yaml Resolved
Comment thread foca/errors/exceptions.py Resolved
Comment thread foca/errors/exceptions.py Resolved
uniqueg and others added 2 commits October 24, 2026 14:14
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]>
@uniqueg
uniqueg merged commit 6661f3f into dev Oct 24, 2026
32 checks passed
@uniqueg
uniqueg deleted the feat/validation-error-details branch October 24, 2026 12:33
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(errors): serve validation error details

1 participant