Skip to content

Conversation

@bwcgn
Copy link

@bwcgn bwcgn commented Nov 19, 2025

Fix: Handle invalid UTF-8 in FastAPI middleware headers

Problem

The FastAPI middleware could crash with a UnicodeDecodeError when processing HTTP headers containing invalid UTF-8 byte sequences. This occurred in both request and response header processing where .decode() was called without error handling.

Solution

Added errors='replace' parameter to all .decode() calls for header keys and values. Invalid UTF-8 bytes are now replaced with the Unicode replacement character (�) instead of raising an exception.

Changes

  • Updated request header decoding (line 18-19)
  • Updated response header decoding (line 58-59)
  • Both now use .decode('utf-8', errors='replace')

Impact

  • Prevents crashes when processing malformed or non-UTF-8 headers
  • Maintains observability even with invalid header data
  • No breaking changes to existing functionality

@dynatrace-cla-bot
Copy link

dynatrace-cla-bot commented Nov 19, 2025

CLA assistant check
All committers have signed the CLA.

@sonarqubecloud
Copy link

@bwcgn
Copy link
Author

bwcgn commented Nov 23, 2025

@dlopes7 Can this be patched? :)

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.

2 participants