-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathNetworkSocketTest.php
More file actions
709 lines (597 loc) · 19.7 KB
/
NetworkSocketTest.php
File metadata and controls
709 lines (597 loc) · 19.7 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
<?php declare(strict_types=1);
namespace hollodotme\FastCGI\Tests\Integration\NetworkSocket;
use Exception;
use hollodotme\FastCGI\Client;
use hollodotme\FastCGI\Exceptions\ConnectException;
use hollodotme\FastCGI\Exceptions\ReadFailedException;
use hollodotme\FastCGI\Exceptions\TimedoutException;
use hollodotme\FastCGI\Exceptions\WriteFailedException;
use hollodotme\FastCGI\Interfaces\ProvidesResponseData;
use hollodotme\FastCGI\RequestContents\UrlEncodedFormData;
use hollodotme\FastCGI\Requests\GetRequest;
use hollodotme\FastCGI\Requests\PostRequest;
use hollodotme\FastCGI\SocketConnections\Defaults;
use hollodotme\FastCGI\SocketConnections\NetworkSocket;
use hollodotme\FastCGI\Sockets\SocketCollection;
use hollodotme\FastCGI\Tests\Traits\SocketDataProviding;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Constraint\RegularExpression;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use RuntimeException;
use SebastianBergmann\RecursionContext\InvalidArgumentException;
use Throwable;
use function preg_match;
final class NetworkSocketTest extends TestCase
{
use SocketDataProviding;
/** @var NetworkSocket */
private $connection;
/** @var Client */
private $client;
protected function setUp() : void
{
$this->connection = new NetworkSocket( $this->getNetworkSocketHost(), $this->getNetworkSocketPort() );
$this->client = new Client();
}
protected function tearDown() : void
{
unset( $this->connection, $this->client );
}
private function getWorkerPath( string $workerFile ) : string
{
return sprintf( '%s/Workers/%s', dirname( __DIR__ ), $workerFile );
}
/**
* @throws Exception
* @throws ConnectException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testCanSendAsyncRequestAndReceiveSocketId() : void
{
$content = new UrlEncodedFormData( ['test-key' => 'unit'] );
$request = new PostRequest( $this->getWorkerPath( 'worker.php' ), $content );
$socketId = $this->client->sendAsyncRequest( $this->connection, $request );
self::assertGreaterThanOrEqual( 1, $socketId );
self::assertLessThanOrEqual( 65535, $socketId );
}
/**
* @throws Exception
* @throws Throwable
* @throws ConnectException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testCanSendAsyncRequestAndReadResponse() : void
{
$content = new UrlEncodedFormData( ['test-key' => 'unit'] );
$request = new PostRequest( $this->getWorkerPath( 'worker.php' ), $content );
$expectedResponse =
"X-Powered-By: PHP/7.1.0\r\nX-Custom: Header\r\nContent-type: text/html; charset=UTF-8\r\n\r\nunit";
$socketId = $this->client->sendAsyncRequest( $this->connection, $request );
$response = $this->client->readResponse( $socketId );
self::assertEquals( $expectedResponse, $response->getOutput() );
self::assertSame( 'unit', $response->getBody() );
self::assertGreaterThan( 0, $response->getDuration() );
}
/**
* @throws Exception
* @throws Throwable
* @throws ConnectException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testCanSendSyncRequestAndReceiveResponse() : void
{
$content = new UrlEncodedFormData( ['test-key' => 'unit'] );
$request = new PostRequest( $this->getWorkerPath( 'worker.php' ), $content );
$expectedResponse =
"X-Powered-By: PHP/7.1.0\r\nX-Custom: Header\r\nContent-type: text/html; charset=UTF-8\r\n\r\nunit";
$response = $this->client->sendRequest( $this->connection, $request );
self::assertEquals( $expectedResponse, $response->getOutput() );
self::assertSame( 'unit', $response->getBody() );
self::assertGreaterThan( 0, $response->getDuration() );
}
/**
* @throws Exception
* @throws Throwable
* @throws ConnectException
* @throws ReadFailedException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testCanReceiveResponseInCallback() : void
{
$content = new UrlEncodedFormData( ['test-key' => 'unit'] );
$request = new PostRequest( $this->getWorkerPath( 'worker.php' ), $content );
$unitTest = $this;
$request->addResponseCallbacks(
static function ( ProvidesResponseData $response ) use ( $unitTest )
{
$unitTest->assertSame( 'unit', $response->getBody() );
}
);
$this->client->sendAsyncRequest( $this->connection, $request );
$this->client->waitForResponses();
}
/**
* @throws Exception
* @throws Throwable
* @throws ConnectException
* @throws ReadFailedException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testCanHandleExceptionsInFailureCallback() : void
{
$content = new UrlEncodedFormData( ['test-key' => 'unit'] );
$request = new PostRequest( $this->getWorkerPath( 'worker.php' ), $content );
$unitTest = $this;
$request->addResponseCallbacks(
static function ()
{
throw new RuntimeException( 'Response callback threw exception.' );
}
);
$request->addFailureCallbacks(
static function ( Throwable $throwable ) use ( $unitTest )
{
$unitTest->assertInstanceOf( RuntimeException::class, $throwable );
$unitTest->assertSame( 'Response callback threw exception.', $throwable->getMessage() );
}
);
$this->client->sendAsyncRequest( $this->connection, $request );
$this->client->waitForResponses();
}
/**
* @throws Exception
* @throws AssertionFailedError
* @throws ConnectException
* @throws ReadFailedException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testCanCheckForSocketIdsHavingResponses() : void
{
$content = new UrlEncodedFormData( ['test-key' => 'unit'] );
$request = new PostRequest( $this->getWorkerPath( 'worker.php' ), $content );
$socketId = $this->client->sendAsyncRequest( $this->connection, $request );
usleep( 60000 );
self::assertTrue( $this->client->hasResponse( $socketId ) );
self::assertEquals( [$socketId], $this->client->getSocketIdsHavingResponse() );
}
/**
* @throws Exception
* @throws ConnectException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testCanReadResponses() : void
{
$content = new UrlEncodedFormData( ['test-key' => 'unit'] );
$request = new PostRequest( $this->getWorkerPath( 'worker.php' ), $content );
$socketIdOne = $this->client->sendAsyncRequest( $this->connection, $request );
$request->setContent( new UrlEncodedFormData( ['test-key' => 'test'] ) );
$socketIdTwo = $this->client->sendAsyncRequest( $this->connection, $request );
usleep( 110000 );
$socketIds = [$socketIdOne, $socketIdTwo];
self::assertEquals( $socketIds, $this->client->getSocketIdsHavingResponse() );
$expectedBodies = ['unit' => 'unit', 'test' => 'test'];
foreach ( $this->client->readResponses( null, ...$socketIds ) as $response )
{
self::assertContains( $response->getBody(), $expectedBodies );
unset( $expectedBodies[ $response->getBody() ] );
}
}
/**
* @throws Exception
* @throws Throwable
* @throws ConnectException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testReadingSyncResponseCanTimeOut() : void
{
$connection = new NetworkSocket(
$this->getNetworkSocketHost(),
$this->getNetworkSocketPort(),
Defaults::CONNECT_TIMEOUT,
100
);
$content = new UrlEncodedFormData( ['test-key' => 'unit'] );
$request = new PostRequest( $this->getWorkerPath( 'sleepWorker.php' ), $content );
$response = $this->client->sendRequest( $connection, $request );
self::assertSame( 'unit - 0', $response->getBody() );
$content = new UrlEncodedFormData( ['sleep' => 1, 'test-key' => 'unit'] );
$request = new PostRequest( $this->getWorkerPath( 'sleepWorker.php' ), $content );
$this->expectException( TimedoutException::class );
/** @noinspection UnusedFunctionResultInspection */
$this->client->sendRequest( $connection, $request );
}
/**
* @throws Exception
* @throws ConnectException
* @throws ReadFailedException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testCanHandleReadyResponses() : void
{
$content = new UrlEncodedFormData( ['test-key' => 'unit'] );
$request = new PostRequest( $this->getWorkerPath( 'worker.php' ), $content );
$unitTest = $this;
$request->addResponseCallbacks(
static function ( ProvidesResponseData $response ) use ( $unitTest )
{
$unitTest->assertSame( 'unit', $response->getBody() );
}
);
$this->client->sendAsyncRequest( $this->connection, $request );
while ( $this->client->hasUnhandledResponses() )
{
$this->client->handleReadyResponses();
}
}
/**
* @throws ConnectException
* @throws TimedoutException
* @throws WriteFailedException
* @throws ReadFailedException
*/
public function testCanReadReadyResponses() : void
{
$content = new UrlEncodedFormData( ['test-key' => 'unit'] );
$request = new PostRequest( $this->getWorkerPath( 'worker.php' ), $content );
$this->client->sendAsyncRequest( $this->connection, $request );
while ( $this->client->hasUnhandledResponses() )
{
foreach ( $this->client->readReadyResponses() as $response )
{
echo $response->getBody();
}
}
$this->expectOutputString( 'unit' );
}
/**
* @throws Exception
* @throws ConnectException
* @throws ReadFailedException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testCanWaitForResponse() : void
{
$content = new UrlEncodedFormData( ['test-key' => 'unit'] );
$request = new PostRequest( $this->getWorkerPath( 'worker.php' ), $content );
$unitTest = $this;
$request->addResponseCallbacks(
static function ( ProvidesResponseData $response ) use ( $unitTest )
{
$unitTest->assertSame( 'unit', $response->getBody() );
}
);
$socketId = $this->client->sendAsyncRequest( $this->connection, $request );
$this->client->waitForResponse( $socketId );
}
/**
* @throws Exception
* @throws AssertionFailedError
* @throws \PHPUnit\Framework\Exception
* @throws ConnectException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testReadResponsesSkipsUnknownSocketIds() : void
{
$content = new UrlEncodedFormData( ['test-key' => 'unit'] );
$request = new PostRequest( $this->getWorkerPath( 'worker.php' ), $content );
$socketIds = [];
$socketIds[] = $this->client->sendAsyncRequest( $this->connection, $request );
$socketIds[] = 12345;
sleep( 1 );
foreach ( $this->client->readResponses( null, ...$socketIds ) as $response )
{
echo $response->getBody();
}
self::assertFalse( $this->client->hasUnhandledResponses() );
$this->expectOutputString( 'unit' );
}
/**
* @throws Exception
* @throws Throwable
* @throws ConnectException
* @throws ReadFailedException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testCanReceiveBufferInPassThroughCallback() : void
{
$data = [
'test-key' => str_repeat( 'test-first-key', 5000 ),
'test-second-key' => 'test-second-key',
'test-third-key' => str_repeat( 'test-third-key', 5000 ),
];
$content = new UrlEncodedFormData( $data );
$request = new PostRequest( $this->getWorkerPath( 'worker.php' ), $content );
$unitTest = $this;
$passCounter = 0;
$request->addPassThroughCallbacks(
static function ( $buffer ) use ( $unitTest, $data, &$passCounter )
{
if ( 0 === $passCounter++ )
{
# The first key is large enough to be dumped immediately with all headers
$unitTest->assertStringContainsString( $data['test-key'], $buffer );
return;
}
# The second key is too small to be dumped,
# hence the second packet will show both second AND third keys
$unitTest->assertStringNotContainsString( $data['test-key'], $buffer );
$unitTest->assertStringContainsString( $data['test-second-key'], $buffer );
$unitTest->assertStringContainsString( $data['test-third-key'], $buffer );
}
);
$this->client->sendAsyncRequest( $this->connection, $request );
$this->client->waitForResponses();
}
/**
* @param int $length
*
* @throws Throwable
* @throws WriteFailedException
*
* @dataProvider contentLengthProvider
*/
public function testCanGetLengthOfSentContent( int $length ) : void
{
$content = new UrlEncodedFormData(['test' => str_repeat( 'a', $length )]);
$request = new PostRequest( $this->getWorkerPath( 'lengthWorker.php' ), $content );
$request->setContentType( '*/*' );
$result = $this->client->sendRequest( $this->connection, $request );
self::assertEquals( $length + 5, $result->getBody() );
}
/**
* @return array<array<string, int>>
*/
public function contentLengthProvider() : array
{
return [
[
'length' => 1024,
],
[
'length' => 2048,
],
[
'length' => 4096,
],
[
'length' => 8192,
],
[
'length' => 16384,
],
[
'length' => 32768,
],
[
'length' => 65535,
],
[
'length' => 65536,
],
[
'length' => 131072,
],
[
'length' => 262144,
],
[
'length' => 524288,
],
];
}
/**
* @param string $scriptFilename
*
* @throws ConnectException
* @throws AssertionFailedError
* @throws Throwable
* @throws TimedoutException
* @throws WriteFailedException
* @dataProvider invalidScriptFileNamesProvider
*/
public function testRequestingAnUnknownScriptPathThrowsException( string $scriptFilename ) : void
{
$request = new GetRequest( $scriptFilename );
$response = $this->client->sendRequest( $this->connection, $request );
self::assertSame( '404 Not Found', $response->getHeaderLine( 'Status' ) );
self::assertSame( "File not found.\n", $response->getBody() );
$this->assertMatchesRegExp( "#^Primary script unknown\n?$#", $response->getError() );
}
/**
* @param string $pattern
* @param string $string
* @param string $message
*
* @throws ExpectationFailedException
* @throws InvalidArgumentException
*/
private function assertMatchesRegExp( string $pattern, string $string, string $message = '' ) : void
{
self::assertThat( $string, new RegularExpression( $pattern ), $message );
}
/**
* @return array<array<string, string>>
*/
public function invalidScriptFileNamesProvider() : array
{
return [
[
'scriptFilename' => '/unknown/script.php',
],
[
# Existing script filenames containing path traversals do not work either
'scriptFilename' => dirname( __DIR__ ) . '/../Integration/Workers/worker.php',
],
];
}
/**
* @throws ExpectationFailedException
* @throws InvalidArgumentException
* @throws Throwable
* @throws ConnectException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testNotAllowedFileNameExtensionRespondsWithAccessDeniedHeader() : void
{
$request = new GetRequest( $this->getWorkerPath( 'worker.php7' ) );
$response = $this->client->sendRequest( $this->connection, $request );
self::assertSame( '403 Forbidden', $response->getHeaderLine( 'Status' ) );
$this->assertMatchesRegExp(
'#^Access to the script .+ has been denied \(see security\.limit_extensions\)$#',
$response->getError()
);
self::assertSame( "Access denied.\n", $response->getBody() );
}
/**
* @throws ConnectException
* @throws Throwable
* @throws TimedoutException
* @throws WriteFailedException
* @throws ExpectationFailedException
* @throws InvalidArgumentException
*/
public function testUnaccessibleScriptRespondsWithAccessDeniedHeader() : void
{
$scriptPath = $this->getWorkerPath( 'inaccessibleWorker.php' );
$this->makeFileUnaccessible( $scriptPath );
$request = new GetRequest( $scriptPath );
$response = $this->client->sendRequest( $this->connection, $request );
$this->makeFileAccessible( $scriptPath );
$expectedStatus = [
'403 Forbidden',
'404 Not Found',
];
$expectedErrors = [
'#^Unable to open primary script\: .+ \(Permission denied\)$#',
'#^Unable to open primary script\: .+ \(Operation not permitted\)$#',
];
$expectedBodies = [
"Access denied.\n",
"No input file specified.\n",
];
self::assertContains( $response->getHeaderLine( 'Status' ), $expectedStatus );
$errorMatched = false;
foreach ( $expectedErrors as $errorPattern )
{
$errorMatched = $errorMatched || (bool)preg_match( $errorPattern, $response->getError() );
}
self::assertTrue( $errorMatched );
self::assertContains( $response->getBody(), $expectedBodies );
}
private function makeFileUnaccessible( string $filepath ) : void
{
chmod( $filepath, 0200 );
}
private function makeFileAccessible( string $filepath ) : void
{
chmod( $filepath, 0755 );
}
/**
* @throws ConnectException
* @throws ReadFailedException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testCanGetErrorBufferInPassThroughCallback() : void
{
$expectecOutputRegExp = "#^ERROR: Primary script unknown\n?$#";
$request = new GetRequest( '/not/existing.php' );
$request->addPassThroughCallbacks(
static function (
/** @noinspection PhpUnusedParameterInspection */
string $outputBuffer,
string $errorBuffer
)
{
if ( '' !== $errorBuffer )
{
echo 'ERROR: ' . $errorBuffer;
}
}
);
$socketId = $this->client->sendAsyncRequest( $this->connection, $request );
$this->client->handleResponse( $socketId );
$this->expectOutputRegex( $expectecOutputRegExp );
}
/**
* @throws ConnectException
* @throws ReadFailedException
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testCanGetErrorInResponseCallback() : void
{
$unitTest = $this;
$request = new GetRequest( '/not/existing.php' );
$request->addResponseCallbacks(
static function ( ProvidesResponseData $response ) use ( $unitTest )
{
$unitTest->assertSame( 'Primary script unknown', $response->getError() );
}
);
$socketId = $this->client->sendAsyncRequest( $this->connection, $request );
$this->client->handleResponse( $socketId );
}
/**
* @throws ConnectException
* @throws ExpectationFailedException
* @throws InvalidArgumentException
* @throws Throwable
* @throws TimedoutException
* @throws WriteFailedException
*/
public function testCanGetErrorOutputFromWorkerUsingErrorLog() : void
{
$request = new GetRequest( $this->getWorkerPath( 'errorLogWorker.php' ) );
$response = $this->client->sendRequest( $this->connection, $request );
$expectedError = "#^PHP message: ERROR1\n\n?"
. "PHP message: ERROR2\n\n?"
. "PHP message: ERROR3\n\n?"
. "PHP message: ERROR4\n\n?"
. "PHP message: ERROR5\n\n?$#";
$this->assertMatchesRegExp( $expectedError, $response->getError() );
}
/**
* @throws ConnectException
* @throws ExpectationFailedException
* @throws Throwable
* @throws TimedoutException
* @throws WriteFailedException
* @throws InvalidArgumentException
*/
public function testSuccessiveRequestsShouldUseSameSocket() : void
{
$request = new GetRequest( $this->getWorkerPath( 'sleepWorker.php' ) );
$sockets = (new ReflectionClass( $this->client ))->getProperty( 'sockets' );
$sockets->setAccessible( true );
self::assertCount( 0, $sockets->getValue( $this->client ) );
/** @noinspection UnusedFunctionResultInspection */
$this->client->sendRequest( $this->connection, $request );
/** @var SocketCollection $socketCollection */
$socketCollection = $sockets->getValue( $this->client );
$firstSocket = $socketCollection->getIdleSocket( $this->connection );
for ( $i = 0; $i < 5; $i++ )
{
/** @noinspection UnusedFunctionResultInspection */
$this->client->sendRequest( $this->connection, $request );
}
$lastSocket = $socketCollection->getIdleSocket( $this->connection );
self::assertSame( $firstSocket, $lastSocket );
self::assertCount( 1, $sockets->getValue( $this->client ) );
}
}