Skip to content

Commit 345408d

Browse files
wtnclaude
andcommitted
Truncate close frame reasons to fit in a control frame.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a8c595d commit 345408d

3 files changed

Lines changed: 36 additions & 0 deletions

File tree

‎lib/protocol/websocket/close_frame.rb‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ module WebSocket
1212
class CloseFrame < Frame
1313
OPCODE = 0x8
1414
FORMAT = "na*"
15+
MAXIMUM_REASON_LENGTH = 123
1516

1617
# Unpack the frame data into a close code and reason.
1718
# @returns [Tuple(Integer, String)] The close code and reason.
@@ -45,6 +46,7 @@ def unpack
4546

4647
# Pack a close code and reason into the frame data.
4748
# If code is missing, reason is ignored.
49+
# The reason is truncated to 123 bytes.
4850
# @parameter code [Integer | Nil] The close code.
4951
# @parameter reason [String | Nil] The close reason.
5052
def pack(code = nil, reason = nil)
@@ -53,6 +55,10 @@ def pack(code = nil, reason = nil)
5355
reason = reason.encode(Encoding::UTF_8)
5456
end
5557

58+
if reason and reason.bytesize > MAXIMUM_REASON_LENGTH
59+
reason = reason.byteslice(0, MAXIMUM_REASON_LENGTH).scrub("")
60+
end
61+
5662
super([code, reason].pack(FORMAT))
5763
else
5864
super()

‎test/protocol/websocket/close_frame.rb‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,25 @@
3030

3131
expect(frame.payload).to be == "\x03\xE8Hello World".b
3232
end
33+
34+
it "truncates the reason to fit in a control frame" do
35+
frame.pack(1000, "x" * 200)
36+
37+
expect(frame.payload.bytesize).to be == 125
38+
39+
code, reason = frame.unpack
40+
expect(code).to be == 1000
41+
expect(reason).to be == "x" * 123
42+
end
43+
44+
it "doesn't split a multibyte character when truncating the reason" do
45+
frame.pack(1000, ("x" * 122) + "é")
46+
47+
expect(frame.payload.bytesize).to be == 124
48+
49+
code, reason = frame.unpack
50+
expect(reason).to be == "x" * 122
51+
end
3352
end
3453

3554
with "#unpack" do

‎test/protocol/websocket/connection.rb‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,17 @@
6969
expect(connection).to be(:closed?)
7070
end
7171

72+
it "truncates a long error message to fit in the close frame" do
73+
connection.close_write(RuntimeError.new("x" * 200))
74+
75+
frame = client.read_frame
76+
expect(frame).to be_a(Protocol::WebSocket::CloseFrame)
77+
78+
code, reason = frame.unpack
79+
expect(code).to be == Protocol::WebSocket::Error::INTERNAL_ERROR
80+
expect(reason).to be == "x" * 123
81+
end
82+
7283
it "is not closed when close_write succeeds" do
7384
connection.close_write
7485

0 commit comments

Comments
 (0)