Repository navigation
fix(errors): log invalid responses without bodies - #671
Conversation
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]>
Reviewer's GuideAdds 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 handlingsequenceDiagram
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)
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 #671 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 57 57
Lines 7405 7431 +26
=========================================
+ Hits 7405 7431 +26
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/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
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
validation_detailsis, and a new handler forNonConformingResponselogs one line: the operation, the schema path of the failed keyword and, forrequired, 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.dev:_resolve_problem()gives unmapped Connexion and Werkzeug exceptions their status and phrase, and_build_headers()keeps their headers, with tests inTestBuildProblemandTestBuildHeaders. No change needed, so apps can drop their mappings when they switch.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 pytestwith MongoDB 7.0: 3398 passed, 1 skipped, 100% coverage.Declined review findings
DEBUGrecords with bodies inextrafields (connexion.apis.abstract): unrelated to failed responses and existing behaviour; the docs say to keep that logger aboveDEBUGin production.writeOnlyand 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:
Enhancements:
Documentation:
Tests: