Fix: validate event and id fields in format_sse_event to prevent SSE protocol injection#15651
Fix: validate event and id fields in format_sse_event to prevent SSE protocol injection#15651hemanthvnp wants to merge 2 commits into
Conversation
…protocol injection PR fastapi#15588 added validation to ServerSentEvent, but the public format_sse_event() function accepted multi-line values for event and id without raising an error. A newline in either field splits into extra SSE lines, allowing callers who pass user-supplied data directly to format_sse_event() to unintentionally inject arbitrary SSE fields. Reuse the existing _check_event_single_line and _check_id_valid helpers at the top of format_sse_event so the two entry points enforce the same rules. Add eight parametrised tests covering \n, \r, \r\n and \0 in both fields, plus an end-to-end injection scenario.
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
This PR strengthens Server-Sent Events (SSE) safety by validating event and id inputs in format_sse_event, and adds regression tests to ensure newline/null-character injection is rejected.
Changes:
- Add protocol-safety validation for
event(single-line) andid(single-line + no null chars) informat_sse_event. - Update
format_sse_eventdocumentation to reflect the validation rules. - Add tests covering multiline and null-character rejection cases.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| fastapi/sse.py | Documents and enforces validation rules for event/id in format_sse_event. |
| tests/test_sse.py | Adds validation tests ensuring malformed event/id values raise ValueError. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| _check_event_single_line(event) | ||
| _check_id_valid(id) |
| def test_format_sse_event_rejects_null_id(): | ||
| with pytest.raises(ValueError, match="null"): | ||
| format_sse_event(id="has\0null") |
|
Could a maintainer please add the appropriate label so the check-labels CI passes? Thank you! |
|
Closing this as I opened it prematurely based on a non-team-member reply. Will re-open once a team member confirms in the discussion. Apologies for the process misstep. |
Closes the gap left by #15588.
ServerSentEventalready validateseventandidfor newlines andnull characters, but the public
format_sse_event()function did notapply the same checks, allowing SSE protocol injection when
user-controlled input is passed directly: