Skip to content

WebSocket close reasons can be truncated inside a UTF-8 character #125

Open

Description

@Rajatendu1

On main 851b0080cacb03ec38da828160681c64f8d0b29c, WebSocket.close() constructs the close frame with reason.encode("utf-8")[:123]. This keeps the control frame within the byte limit but can split a multibyte character, producing an invalid UTF-8 close reason.

For example, await socket.close(1000, "é" * 62) sends a 123-byte reason ending in the first byte of the final character. A local server that unmasks the close frame and decodes payload[2:] gets UnicodeDecodeError at byte 122. "😀" * 31 and "a" * 122 + "é" also reproduce it. ASCII reasons and multibyte reasons ending on a complete-character boundary are controls that pass.

RFC 6455 section 5.5.1 specifies UTF-8 data after the close code, and section 8.1 requires a peer to fail the connection for invalid UTF-8. Thus a normal application close can become a protocol failure. The same byte slicing appears in _fail().

Validation used Python 3.13.17 on Linux and a local asyncio TCP server, with no external service. The existing 19 WebSocket tests pass when run in isolation. Eight additional close-reason cases against unchanged source produce three failures and five passing controls. These are isolated networking tests, not the repository's complete checks, installed-package test-plugin validation, or mobile tests. The active feat/runtime branch has the same WebSocket source.

Would a fix that preserves the existing truncation behavior but cuts only at complete UTF-8 boundaries be welcome? If so, could you assign this to me before I prepare a PR, following the contribution guide?

This was found during source review and reproduced with constructed examples, not a production incident. AI assistance was used for investigation and local reproduction. No production-source changes have been made.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions