Skip to content

Return no exception text or traceback from the FastAPI error handlers - #364

Merged
NormB merged 1 commit into
mainfrom
fix/stack-trace-exposure
Oct 15, 2026
Merged

NormB merged 1 commit into
mainfrom
fix/stack-trace-exposure

Conversation

@NormB

@NormB NormB commented Oct 15, 2026

Copy link
Copy Markdown
Owner

Fixes the four CodeQL py/stack-trace-exposure alerts (#125, #126, #127, #128) in both FastAPI reference apps.

  • base_api_exception_handler and unhandled_exception_handler no longer add a debug object (exception type, message, traceback) to the response when DEBUG=True. The body is the documented error schema with request_id, plus the X-Request-ID header; status codes are unchanged.
  • The traceback stays in the server log: the unhandled handler already logged it with exc_info; the base handler now logs it when DEBUG is set.
  • New tests/test_exception_handlers_no_leak.py in both apps (12 tests each). With the old handlers the five DEBUG=True cases failed because the body carried the exception text and traceback, and the base handler logged no traceback.
  • The two existing unit tests that required a traceback in DEBUG mode now require its absence.
  • CI runs the API-first app's tests directory (it had none before).

Local results: FastAPI unit tests 193 passed, 52 skipped, 44 deselected (was 181/52/44), coverage 81.30%; API-first 12 passed. ruff-format reformatted the touched Python files, as the pre-commit hook requires.

With DEBUG=True, base_api_exception_handler added the traceback and
unhandled_exception_handler added the exception type, message and
traceback to the JSON response (CodeQL py/stack-trace-exposure,
alerts 125-128). Both reference apps now return the documented error
body only: error, message, status_code, details where the exception
has them, and request_id, with the X-Request-ID header. The
traceback goes to the server log: the unhandled handler already
logged it, and the base handler now logs it when DEBUG is set.

New tests in both apps raise an exception and call each handler
inside the except block, with DEBUG on and off, and check that the
body holds no exception text or traceback, that it matches the
documented schema, and that the detail reaches the log. With the old
handlers, the five DEBUG=True cases fail. The two existing unit tests
that required a traceback in DEBUG mode now require its absence.

The API-first app had no tests; CI now runs its tests directory.
@NormB
NormB merged commit eee39e2 into main Oct 15, 2026
31 checks passed
@NormB
NormB deleted the fix/stack-trace-exposure branch October 15, 2026 14:54
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.

1 participant