Skip to content

fix(errors): log invalid responses without bodies - #671

Merged
uniqueg merged 3 commits into
devfrom
feat/616-default-problem-details
Nov 4, 2026
Merged

uniqueg merged 3 commits into
devfrom
feat/616-default-problem-details

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Response validation failures: Connexion logged the validator's message with the whole response body, and FOCA's handler logged it again in the traceback. Connexion's message is now filtered out, for all apps of the process and whatever validation_details is, and a new handler for NonConformingResponse logs one line: the operation, the schema path of the failed keyword and, for required, the missing properties. All of these come from the specification, so nothing of the body is logged, not even keys. Clients get the same problem details as before; app mappings win.
  • Default problem details: already on dev: _resolve_problem() gives unmapped Connexion and Werkzeug exceptions their status and phrase, and _build_headers() keeps their headers, with tests in TestBuildProblem and TestBuildHeaders. No change needed, so apps can drop their mappings when they switch.
  • Docs: docs/configuration/exceptions.md, new section "Invalid responses".

Closes #616

Verification

  • ruff check, ruff format --check, mypy, ast-grep scan, mkdocs build --strict: pass.
  • coverage run -m pytest with MongoDB 7.0: 3398 passed, 1 skipped, 100% coverage.
  • Both reviewer subagents, then a second adversarial round (no high or medium findings in round 2).
  • CI: see the checks of this PR.

Declined review findings

  • Filtering Connexion's DEBUG records with bodies in extra fields (connexion.apis.abstract): unrelated to failed responses and existing behaviour; the docs say to keep that logger above DEBUG in production.
  • Conditional response filter: always on, as logging the body isn't something an app should get by default; documented.
  • A property that is writeOnly and absent can be listed as missing next to a really missing one: a wrong name from the specification in a log line, nothing leaked.

🤖 Generated with Claude Code

Summary by Sourcery

Handle invalid API responses with privacy-preserving logs that expose specification metadata without response content.

Bug Fixes:

  • Prevent invalid response bodies and body-derived details from being emitted in application logs while preserving existing client problem responses.

Enhancements:

  • Add dedicated handling for non-conforming responses that logs only the operation, specification schema failure path, and missing required properties.
  • Filter Connexion response-validation messages process-wide, including when validation details are disabled, while preserving application-specific exception mappings.

Documentation:

  • Document invalid-response logging behavior, privacy safeguards, configuration effects, and production logging guidance.

Tests:

  • Add comprehensive coverage for body-free response-validation logging, schema paths, required properties, mappings, disabled logging, escaping, truncation, and Connexion filters.

Connexion logs the validator's message on invalid responses, with the
whole response body, and FOCA's handler logged it again in the traceback.
Filter out Connexion's message and log the operation and the path of the
failed keyword in the schema, from the specification only.

Exceptions that apps haven't mapped already get problem details in FOCA's
format; the tests of that stay.

Closes #616

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds a dedicated invalid-response error handler that preserves client-facing problem details while ensuring logs contain only specification-derived validation context, and filters Connexion’s duplicate body-bearing messages process-wide; documentation and comprehensive tests cover the new behavior.

Sequence diagram for body-free invalid response handling

sequenceDiagram
    participant Handler as Response handler
    participant Connexion as Connexion
    participant Filter as Validation log filter
    participant Logger as FOCA logger
    participant Client

    Connexion->>Handler: NonConformingResponse
    Handler->>Filter: Filter connexion.decorators.validation record
    Filter-->>Connexion: Drop body-bearing validation message
    Handler->>Logger: _response_validation_error(exception)
    Logger->>Logger: _shorten(message, max_detail_length)
    Logger-->>Handler: Log operation and schema-derived error
    Handler->>Client: _response(exception, problem, conf)
Loading

File-Level Changes

Change Details Files
Handle invalid response validation through a body-free, specification-derived error path.
  • Register a dedicated NonConformingResponse handler that logs the operation, schema failure path, and missing required properties without response content or traceback.
  • Preserve existing problem resolution, headers, client responses, and application-specific exception mappings.
  • Shorten and escape the single log line according to configured logging and detail limits, with logging disabled under logging=none.
foca/errors/exceptions.py
Filter Connexion response-validation messages process-wide to prevent duplicate body leakage.
  • Add a response-specific validation logger filter independent of validation_details.
  • Retain request-validation filtering behavior while updating filter registration and test isolation.
foca/errors/exceptions.py
tests/errors/test_errors.py
docs/configuration/exceptions.md
Document the security and operational behavior for invalid response logging.
  • Explain body-free logs, default problem responses, logging modes, process-wide filtering, and the DEBUG logger caveat.
  • Provide an example of the resulting specification-derived log line.
docs/configuration/exceptions.md
Add comprehensive coverage for invalid response handling and logging guarantees.
  • Test invalid bodies, nested items, dynamic keys, root schemas, headers, and nonconforming exceptions.
  • Verify required-property reporting, mappings, disabled logging, truncation, escaping, process-wide filtering, and absence of body data.
tests/errors/test_errors.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 4, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #671   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           57        57           
  Lines         7405      7431   +26     
=========================================
+ Hits          7405      7431   +26     
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 4, 2026 04:31

@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/exceptions.py" line_range="477" />
<code_context>
+            message = f"{message}: missing {', '.join(missing)}"
+        return message
+    if isinstance(exc, NonConformingResponseHeaders):
+        return str(exc.detail)
+    return str(exc.title)
+
</code_context>
<issue_to_address>
**Secrets appear in validation logs**

When a response header contains sensitive data and fails schema validation, `_response_validation_error` returns `exc.detail` for `NonConformingResponseHeaders`, and Connexion's detail can include the rejected header value, so the logger records secrets carried in response headers.

Avoid returning the raw validation detail for header failures when it can include the rejected value.

Also at `foca/errors/exceptions.py:478`.
</issue_to_address>

### Comment 2
<location path="foca/errors/exceptions.py" line_range="157" />
<code_context>
+
+    app.add_error_handler(NonConformingResponse, _response_validation_handler)
+    # Added once per process (`addFilter()` skips filters already added)
+    logging.getLogger(_VALIDATION_LOGGER).addFilter(_drop_response_validation_records)
     if _conf.validation_details:

</code_context>
<issue_to_address>
**Other apps lose validation logs**

When app A registers FOCA's handler while app B in the same process handles an invalid response without registering it, the process-wide `_drop_response_validation_records` filter drops app B's invalid-response record, but only app A has FOCA's replacement handler, so app B's invalid response has no validation diagnostic in the logs.

Scope the filter to the app whose replacement handler is registered so other apps retain their invalid-response records.
</issue_to_address>

### Comment 3
<location path="tests/errors/test_errors.py" line_range="631-632" />
<code_context>
+        (message,) = logged
+        assert error in message
+        assert path.lstrip("/") in message
+        assert BODY_VALUE not in message
+        assert BODY_VALUE not in caplog.text
+        assert "\n" not in message
+
</code_context>
<issue_to_address>
**Other body data can leak**

When the logger emits response data other than `BODY_VALUE`, when a regression logs response content other than `BODY_VALUE`, `test_logs_without_body` passes because lines 631–632 only search for that sentinel; logging `{"name": 1}` from the `/get_invalid_body` payload still satisfies both assertions.

Assert that the response’s non-sentinel values and keys are absent from the captured logs too.
</issue_to_address>

### Comment 4
<location path="tests/errors/test_errors.py" line_range="633" />
<code_context>
+        assert path.lstrip("/") in message
+        assert BODY_VALUE not in message
+        assert BODY_VALUE not in caplog.text
+        assert "\n" not in message
+
+    def test_required_names_missing(self) -> None:
</code_context>
<issue_to_address>
**Escaping is never exercised**

When a response schema contains a newline in a path component, when a schema path contains a newline and the handler stops escaping log values, `test_logs_without_body` still passes: line 633 checks for newlines, but every tested schema path and fixed error string is newline-free.

Exercise a validation error whose schema path contains a newline and assert that its logged form is escaped.
</issue_to_address>

Linked issues

#616 feat(errors): default details, quieter logs · 6 of 6 met

# Requirement Status Notes
1 Unmapped Connexion and Werkzeug exceptions produce FOCA problem responses with their status ✅ Met The existing _resolve_problem() derives details from an exception's status when it has no mapping; TestHandler checks these responses.
2 Unmapped exceptions keep their headers ✅ Met _response() passes the exception to _build_headers(), and TestHandler covers headers such as Allow, Retry-After, and WWW-Authenticate.
3 App mappings still win ✅ Met The new response-validation mapping test checks that an application mapping controls both the response and logged problem details.
4 Failed response validation logs contain no response body ✅ Met The new tests check that the body value is absent from both the handler log and captured Connexion logs.
5 Tests achieve 100% coverage ✅ Met The PR verification reports 100% coverage.
6 Document the behavior in docs/configuration/exceptions.md ✅ Met The new “Invalid responses” section describes body-free logging, filtering, and logging configuration.

Sourcery assessment

Approval pending. 4 findings to address first.

Blocking findings: foca/errors/exceptions.py:477, foca/errors/exceptions.py:157, tests/errors/test_errors.py:632, tests/errors/test_errors.py:633


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

Comment thread foca/errors/exceptions.py Resolved
Comment thread foca/errors/exceptions.py Resolved
Comment thread tests/errors/test_errors.py Resolved
Comment thread tests/errors/test_errors.py Resolved
@uniqueg
uniqueg merged commit 05c6eab into dev Nov 4, 2026
56 checks passed
@uniqueg
uniqueg deleted the feat/616-default-problem-details branch November 4, 2026 06:15
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): default details, quieter logs

1 participant