-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebSocketFrameCodecTest.php
More file actions
299 lines (254 loc) · 12 KB
/
Copy pathWebSocketFrameCodecTest.php
File metadata and controls
299 lines (254 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
<?php
declare(strict_types=1);
namespace IDCT\NATS\Tests\Unit;
use IDCT\NATS\Exception\ProtocolException;
use IDCT\NATS\Transport\WebSocketFrameCodec;
use PHPUnit\Framework\TestCase;
final class WebSocketFrameCodecTest extends TestCase
{
/**
* Verifies a masked client frame round-trips through decode() (#31).
*/
public function testEncodeMaskedFrameRoundTrips(): void
{
$encoded = WebSocketFrameCodec::encode(WebSocketFrameCodec::OP_BINARY, "PING\r\n", true, 'ABCD');
// FIN+binary, mask bit set, length 6.
self::assertSame(0x82, ord($encoded[0]));
self::assertSame(0x80 | 6, ord($encoded[1]));
$buffer = $encoded;
$frames = WebSocketFrameCodec::decode($buffer);
self::assertSame('', $buffer);
self::assertCount(1, $frames);
self::assertSame(WebSocketFrameCodec::OP_BINARY, $frames[0]['opcode']);
self::assertSame("PING\r\n", $frames[0]['payload']);
self::assertTrue($frames[0]['fin']);
}
/**
* Verifies the RFC 6455 §1.3 Sec-WebSocket-Accept example vector (#31).
*/
public function testAcceptKeyMatchesRfcExample(): void
{
self::assertSame(
's3pPLMBiTxaQ9kYGzzhZRbK+xOo=',
WebSocketFrameCodec::acceptKey('dGhlIHNhbXBsZSBub25jZQ=='),
);
}
/**
* Verifies decode() leaves an incomplete trailing frame in the buffer (#31).
*/
public function testDecodeKeepsIncompleteTrailingFrame(): void
{
$full = WebSocketFrameCodec::encode(WebSocketFrameCodec::OP_BINARY, 'hello', true, 'WXYZ');
// Feed everything but the last byte.
$buffer = substr($full, 0, -1);
$frames = WebSocketFrameCodec::decode($buffer);
self::assertSame([], $frames);
self::assertSame(substr($full, 0, -1), $buffer);
// Deliver the final byte; the frame now decodes.
$buffer .= substr($full, -1);
$frames = WebSocketFrameCodec::decode($buffer);
self::assertCount(1, $frames);
self::assertSame('hello', $frames[0]['payload']);
self::assertSame('', $buffer);
}
/**
* Verifies decode() returns multiple frames present in one buffer (#31).
*/
public function testDecodeReturnsMultipleFrames(): void
{
$buffer = WebSocketFrameCodec::encode(WebSocketFrameCodec::OP_BINARY, 'INFO {}', false)
. WebSocketFrameCodec::encode(WebSocketFrameCodec::OP_PING, 'hb', false)
. WebSocketFrameCodec::encode(WebSocketFrameCodec::OP_BINARY, '+OK', false);
$frames = WebSocketFrameCodec::decode($buffer);
self::assertCount(3, $frames);
self::assertSame('INFO {}', $frames[0]['payload']);
self::assertSame(WebSocketFrameCodec::OP_PING, $frames[1]['opcode']);
self::assertSame('+OK', $frames[2]['payload']);
}
/**
* Verifies an extended (16-bit length) unmasked server frame decodes (#31).
*/
public function testDecodeExtended16BitLengthFrame(): void
{
$payload = str_repeat('x', 300);
$buffer = WebSocketFrameCodec::encode(WebSocketFrameCodec::OP_BINARY, $payload, false);
// Length marker 126 + 2-byte length.
self::assertSame(126, ord($buffer[1]) & 0x7F);
$frames = WebSocketFrameCodec::decode($buffer);
self::assertCount(1, $frames);
self::assertSame($payload, $frames[0]['payload']);
}
/**
* Verifies a fragmented (FIN=0) data frame is reported with fin=false (#31).
*/
public function testDecodeReportsFragmentationFlag(): void
{
// Manually craft a non-final binary frame (FIN=0, opcode binary, unmasked, len 3).
$buffer = chr(WebSocketFrameCodec::OP_BINARY) . chr(3) . 'abc';
$frames = WebSocketFrameCodec::decode($buffer);
self::assertCount(1, $frames);
self::assertFalse($frames[0]['fin']);
self::assertSame('abc', $frames[0]['payload']);
}
/**
* Verifies permessage-deflate deflate/inflate round-trips (#61).
*/
public function testDeflateInflateRoundTrip(): void
{
$payload = str_repeat('NATS-over-websocket payload ', 20);
$compressed = WebSocketFrameCodec::deflate($payload);
self::assertNotSame($payload, $compressed);
self::assertLessThan(strlen($payload), strlen($compressed));
self::assertSame($payload, WebSocketFrameCodec::inflate($compressed));
}
/**
* Verifies a compressed frame carries RSV1 and decodes back to the original payload (#61).
*/
public function testCompressedFrameRoundTrip(): void
{
$payload = 'PUB orders.created 5\r\nhello\r\n';
$encoded = WebSocketFrameCodec::encode(
WebSocketFrameCodec::OP_BINARY,
WebSocketFrameCodec::deflate($payload),
true,
'MASK',
true,
);
// RSV1 bit set on the first byte.
self::assertSame(0x40, ord($encoded[0]) & 0x40);
$buffer = $encoded;
$frames = WebSocketFrameCodec::decode($buffer);
self::assertCount(1, $frames);
self::assertTrue($frames[0]['rsv1']);
self::assertSame($payload, WebSocketFrameCodec::inflate($frames[0]['payload']));
}
/**
* Verifies a non-4-byte mask key is rejected by encode() (#31).
*/
public function testEncodeRejectsBadMaskKey(): void
{
$this->expectException(ProtocolException::class);
WebSocketFrameCodec::encode(WebSocketFrameCodec::OP_BINARY, 'x', true, 'AB');
}
/**
* Verifies encode() uses a 64-bit length header for payloads > 65535 bytes (line 51),
* and that decode() correctly reassembles the same frame (lines 104-106).
*/
public function testEncode64BitLengthFrameRoundTrips(): void
{
// Payload is 65536 bytes — exactly one past the 16-bit threshold.
$payload = str_repeat('A', 65536);
$encoded = WebSocketFrameCodec::encode(WebSocketFrameCodec::OP_BINARY, $payload, false);
// Byte 1 must carry the 127 length marker (no mask bit since mask=false).
self::assertSame(127, ord($encoded[1]) & 0x7F);
// The 8-byte big-endian length starting at offset 2 must equal 65536.
/** @var array{1:int} $unpacked */
$unpacked = unpack('J', substr($encoded, 2, 8));
self::assertSame(65536, $unpacked[1]);
// Decode must reconstruct the original payload from the 64-bit-length frame.
$buffer = $encoded;
$frames = WebSocketFrameCodec::decode($buffer);
self::assertCount(1, $frames);
self::assertSame($payload, $frames[0]['payload']);
self::assertSame('', $buffer);
}
/**
* Verifies decode() halts and preserves the buffer when a 64-bit length header is incomplete
* (lines 100-101): the first 2 bytes say length=127 but fewer than 10 bytes are available.
*/
public function testDecode64BitLengthHeaderIncompleteWaits(): void
{
// 2-byte frame header with length marker 127, then only 3 of the required 8 length bytes.
// decode() needs at least offset(2) + 8 = 10 bytes to read the 64-bit length, so 5 bytes
// is not enough and the loop must break without consuming anything.
$buffer = pack('CC', 0x82, 127) . str_repeat("\x00", 3);
$original = $buffer;
$frames = WebSocketFrameCodec::decode($buffer);
self::assertSame([], $frames, 'No complete frame should be decoded');
self::assertSame($original, $buffer, 'Buffer must be left unchanged when header is incomplete');
}
/**
* Verifies decode() halts and preserves the buffer when a 16-bit length header is incomplete
* (line 93): the first 2 bytes say length=126 but only one of the two length bytes is present.
*/
public function testDecode16BitLengthHeaderIncompleteWaits(): void
{
// 2-byte frame header with length marker 126, then only 1 byte of the 2-byte length field.
$buffer = pack('CC', 0x82, 126) . "\x01";
$original = $buffer;
$frames = WebSocketFrameCodec::decode($buffer);
self::assertSame([], $frames, 'No complete frame should be decoded');
self::assertSame($original, $buffer, 'Buffer must not be consumed when 16-bit length is incomplete');
}
/**
* Verifies decode() throws when the declared payload length exceeds MAX_FRAME_PAYLOAD (line 110).
* We craft a 64-bit-length frame header with a length value of 64 MiB + 1.
*/
public function testDecodePayloadLengthOutOfBoundsThrows(): void
{
$this->expectException(ProtocolException::class);
$this->expectExceptionMessageMatches('/payload length out of bounds/');
// MAX_FRAME_PAYLOAD is 64 * 1024 * 1024 = 67108864. Use one byte over.
$tooLarge = 64 * 1024 * 1024 + 1;
// FIN+binary, 64-bit length marker, 8-byte big-endian length (no payload needed — decode
// throws before trying to read the payload).
$buffer = pack('CC', 0x82, 127) . pack('J', $tooLarge);
WebSocketFrameCodec::decode($buffer);
}
/**
* Verifies decode() halts and preserves the buffer when a masked frame has a complete header
* but its 4-byte mask key is not yet fully buffered (lines 115-116).
*/
public function testDecodeMaskedFrameWaitsForMaskKey(): void
{
// Craft a masked frame: FIN+binary, mask bit set, 7-bit length = 5.
// Full frame would be: 2 header + 4 mask key + 5 payload = 11 bytes.
// Provide header + only 2 of the 4 mask key bytes — not enough.
$buffer = pack('CC', 0x82, 0x80 | 5) . "\xAB\xCD";
$original = $buffer;
$frames = WebSocketFrameCodec::decode($buffer);
self::assertSame([], $frames, 'No frame decoded when mask key is incomplete');
self::assertSame($original, $buffer, 'Buffer unchanged when mask key bytes are missing');
}
/**
* Verifies inflate() throws a ProtocolException when the input is not valid DEFLATE data (line 175).
*
* PHPUnit's error handler is disabled so that the native PHP E_WARNING emitted by inflate_add()
* on a corrupt stream does not short-circuit into a test error; the ProtocolException thrown
* immediately after is what the test actually asserts.
*/
#[\PHPUnit\Framework\Attributes\WithoutErrorHandler]
public function testInflateInvalidDataThrows(): void
{
$this->expectException(ProtocolException::class);
$this->expectExceptionMessageMatches('/inflate compressed WebSocket frame/');
// Pass data that is definitely not a valid raw DEFLATE stream.
// inflate() appends \x00\x00\xff\xff before calling inflate_add; even so, this garbage
// is not valid and inflate_add returns false, triggering the ProtocolException.
WebSocketFrameCodec::inflate('this is not compressed data at all !!!!!!');
}
/**
* #100: a well-behaved error handler (one that respects the @ operator via error_reporting()) must
* NOT observe the native inflate_add() warning, so an application that promotes warnings to
* exceptions still receives the typed ProtocolException rather than an ErrorException leaking from
* inside the codec. Before the @ suppression this raised an ErrorException from the inflate_add()
* call, never reaching the ProtocolException.
*/
public function testInflateInvalidDataSuppressesNativeWarningForRespectfulHandlers(): void
{
set_error_handler(static function (int $errno, string $errstr): bool {
if ((error_reporting() & $errno) === 0) {
return false; // suppressed via @ — respect it, do not promote to an exception
}
throw new \ErrorException($errstr, 0, $errno);
});
try {
WebSocketFrameCodec::inflate('this is not compressed data at all !!!!!!');
self::fail('Expected a ProtocolException');
} catch (ProtocolException $e) {
self::assertStringContainsString('inflate compressed WebSocket frame', $e->getMessage());
} finally {
restore_error_handler();
}
}
}