diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d19c503f..f1939720 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,10 +34,21 @@ jobs: php-version: '8.5' job-description: 'on macOS' + - operating-system: 'ubuntu-latest' + php-version: '8.6' + job-description: '(experimental)' + experimental: true + psalm: 'skip' + style-fix: 'none' + composer-require-checker-version: 'none' + composer-flags: '--ignore-platform-req=php+' + name: PHP ${{ matrix.php-version }} ${{ matrix.job-description }} runs-on: ${{ matrix.operating-system }} + continue-on-error: ${{ matrix.experimental == true }} + steps: - name: Set git to use LF run: | diff --git a/test/ClientBadSslIntegrationTest.php b/test/ClientBadSslIntegrationTest.php index 1c3b4223..3ba90a47 100644 --- a/test/ClientBadSslIntegrationTest.php +++ b/test/ClientBadSslIntegrationTest.php @@ -2,46 +2,108 @@ namespace Amp\Http\Client; +use Amp\Http\Client\Connection\DefaultConnectionFactory; +use Amp\Http\Client\Connection\UnlimitedConnectionPool; +use Amp\Http\Client\Support\LocalHttpBin; use Amp\PHPUnit\AsyncTestCase; +use Amp\Socket\ClientTlsContext; +use Amp\Socket\ConnectContext; +use Amp\Socket\ResourceSocket; +use Amp\Socket\ServerSocket; +use Revolt\EventLoop; +use function Amp\delay; +use function Amp\Socket\listen; final class ClientBadSslIntegrationTest extends AsyncTestCase { - private HttpClient $client; - - protected function setUp(): void - { - parent::setUp(); - - $this->client = (new HttpClientBuilder)->retry(0)->build(); - } - public function testSelfSignedCertificate(): void { - $request = new Request('https://self-signed.badssl.com/'); + $httpBin = LocalHttpBin::startSecureServer(); + $client = (new HttpClientBuilder)->retry(0)->build(); $this->expectException(TlsException::class); - $this->expectExceptionMessageMatches("/^Connection to 'self-signed.badssl.com:443' @ '.+' closed during TLS handshake: certificate verify failed$/"); + $this->expectExceptionMessageMatches("/^Connection to '127.0.0.1:\d+' @ '.+' closed during TLS handshake: certificate verify failed$/"); - $this->client->request($request); + try { + $client->request(new Request($httpBin->getServerUri())); + } finally { + $httpBin->stopServer(); + } } public function testWrongHostCertificate(): void { - $request = new Request('https://wrong.host.badssl.com/'); + $httpBin = LocalHttpBin::startSecureServer(); + $tlsContext = (new ClientTlsContext(''))->withoutPeerVerification()->withPeerNameVerification(); + $client = $this->buildClient($tlsContext); $this->expectException(TlsException::class); - $this->expectExceptionMessageMatches("/^Connection to 'wrong.host.badssl.com:443' @ '.+' closed during TLS handshake: Peer certificate .+ did not match expected .*`wrong.host.badssl.com'$/"); + $this->expectExceptionMessageMatches("/^Connection to '127.0.0.1:\d+' @ '.+' closed during TLS handshake: Peer certificate .+ did not match expected .*`127.0.0.1'$/"); - $this->client->request($request); + try { + $client->request(new Request($httpBin->getServerUri())); + } finally { + $httpBin->stopServer(); + } } + /** + * @requires OSFAMILY Linux + */ public function testDhKeyTooSmall(): void { - $request = new Request('https://dh512.badssl.com/'); + $server = $this->listenWithDhCipher(); + $tlsContext = (new ClientTlsContext('')) + ->withoutPeerVerification() + ->withoutPeerNameVerification() + ->withSecurityLevel(3); + $client = $this->buildClient($tlsContext); $this->expectException(TlsException::class); - $this->expectExceptionMessageMatches("/^Connection to 'dh512.badssl.com:443' @ '.+' closed during TLS handshake: dh key too small$/"); + $this->expectExceptionMessageMatches("/^Connection to '127.0.0.1:\d+' @ '.+' closed during TLS handshake: dh key too small$/"); + + try { + $client->request(new Request('https://' . $server->getAddress() . '/')); + } finally { + $server->close(); + } + } + + private function buildClient(ClientTlsContext $tlsContext): HttpClient + { + $connectContext = (new ConnectContext)->withTlsContext($tlsContext); + $connectionFactory = new DefaultConnectionFactory(connectContext: $connectContext); + + return (new HttpClientBuilder)->retry(0)->usingPool(new UnlimitedConnectionPool($connectionFactory))->build(); + } + + private function listenWithDhCipher(): ServerSocket + { + $server = listen('127.0.0.1:0'); + + $resource = $server->getResource(); + \stream_context_set_option($resource, 'ssl', 'local_cert', __DIR__ . '/tls/amphp.org.pem'); + \stream_context_set_option($resource, 'ssl', 'dh_param', __DIR__ . '/tls/dh2048.pem'); + \stream_context_set_option($resource, 'ssl', 'ciphers', 'DHE-RSA-AES128-GCM-SHA256'); + + EventLoop::queue(function () use ($server): void { + while ($socket = $server->accept()) { + $this->handshakeOverTls12($socket); + } + }); + + return $server; + } + + private function handshakeOverTls12(ResourceSocket $socket): void + { + $resource = $socket->getResource(); - $this->client->request($request); + do { + $result = @\stream_socket_enable_crypto($resource, true, \STREAM_CRYPTO_METHOD_TLSv1_2_SERVER); + if ($result === 0) { + delay(0.01); + } + } while ($result === 0); } } diff --git a/test/ClientHttpBinIntegrationTest.php b/test/ClientHttpBinIntegrationTest.php index 4e991fcc..efc0cd22 100644 --- a/test/ClientHttpBinIntegrationTest.php +++ b/test/ClientHttpBinIntegrationTest.php @@ -14,8 +14,7 @@ use Amp\Http\Client\Interceptor\DecompressResponse; use Amp\Http\Client\Interceptor\SetRequestHeaderIfUnset; use Amp\Http\Client\Interceptor\TooManyRedirectsException; -use Amp\Http\Cookie\RequestCookie; -use Amp\Http\Cookie\ResponseCookie; +use Amp\Http\Client\Support\LocalHttpBin; use Amp\Http\Http1\Rfc7230; use Amp\PHPUnit\AsyncTestCase; use Amp\Pipeline\Pipeline; @@ -39,6 +38,8 @@ class ClientHttpBinIntegrationTest extends AsyncTestCase private HttpClientBuilder $builder; + private LocalHttpBin $httpBin; + private ?\Closure $responseCallback = null; private ?string $rawHandler = null; @@ -146,7 +147,7 @@ public function testInvalidHeaders(): void public function testDefaultUserAgentSent(): void { - $uri = 'http://httpbin.org/user-agent'; + $uri = $this->httpBin->getServerUri('/user-agent'); $response = $this->executeRequest(new Request($uri)); @@ -160,7 +161,7 @@ public function testDefaultUserAgentSent(): void public function testDefaultUserAgentCanBeChanged(): void { - $uri = 'http://httpbin.org/user-agent'; + $uri = $this->httpBin->getServerUri('/user-agent'); $this->givenNetworkInterceptor(new SetRequestHeaderIfUnset('user-agent', 'amphp/http-client')); @@ -249,19 +250,9 @@ public function testHttp2Push(): void public function testGzipBomb(): void { - self::markTestSkipped('Run this manually'); - - $response = $this->client->request(new Request('https://blog.haschek.at/tools/bomb.php')); - - $sessionCookie = ResponseCookie::fromHeader($response->getHeader('set-cookie')); - $body = $response->getBody()->buffer(); - \preg_match('(bombme=[a-f0-9]+)', $body, $match); - - $request = new Request('https://blog.haschek.at/tools/bomb.php?' . $match[0]); - $request->setHeader('cookie', new RequestCookie($sessionCookie->getName(), $sessionCookie->getValue())); - $response = $this->client->request($request); + $response = $this->client->request(new Request($this->httpBin->getServerUri('/gzip-bomb'))); - $this->expectException(ParseException::class); + $this->expectException(StreamException::class); $this->expectExceptionMessageMatches('(Configured body size exceeded: \d+ bytes received, while the configured limit is 10485760 bytes)'); @@ -270,7 +261,7 @@ public function testGzipBomb(): void public function testCustomUserAgentSentIfAssigned(): void { - $uri = 'http://httpbin.org/user-agent'; + $uri = $this->httpBin->getServerUri('/user-agent'); $customUserAgent = 'test-user-agent'; $request = new Request($uri); @@ -290,7 +281,7 @@ public function testCustomUserAgentSentIfAssigned(): void public function testPostStringBody(): void { $body = 'zanzibar'; - $request = new Request('http://httpbin.org/post'); + $request = new Request($this->httpBin->getServerUri('/post')); $request->setMethod('POST'); $request->setBody($body); @@ -305,7 +296,7 @@ public function testPostStringBody(): void public function testPutStringBody(): void { - $uri = 'http://httpbin.org/put'; + $uri = $this->httpBin->getServerUri('/put'); $body = 'zanzibar'; $request = new Request($uri, "PUT"); @@ -327,7 +318,7 @@ public function testPutStringBody(): void */ public function testStatusCodeResponses($statusCode): void { - $response = $this->executeRequest(new Request("http://httpbin.org/status/{$statusCode}")); + $response = $this->executeRequest(new Request($this->httpBin->getServerUri("/status/{$statusCode}"))); self::assertInstanceOf(Response::class, $response); self::assertEquals($statusCode, $response->getStatus()); @@ -345,7 +336,9 @@ public function provideStatusCodes(): array public function testReason(): void { - $response = $this->executeRequest(new Request("http://httpbin.org/status/418")); + $this->givenRawServerResponse("HTTP/1.1 418 I'M A TEAPOT\r\ncontent-length: 0\r\n\r\n"); + + $response = $this->executeRequest($this->createRequest()); self::assertInstanceOf(Response::class, $response); @@ -357,11 +350,9 @@ public function testReason(): void public function testHttp2TeHeader(): void { - $this->markTestSkipped('3rd-party service no longer available'); - $this->client = $this->builder->followRedirects(0)->build(); - $request = new Request('https://http2.pro/api/v1', 'POST'); + $request = new Request($this->httpBin->getServerUri('/post'), 'POST'); $request->setBody('foobar'); $request->setProtocolVersions(['2']); $request->setHeader('te', 'gzip'); @@ -389,7 +380,7 @@ public function testRedirectWithFollow(): void { $this->client = $this->builder->followRedirects()->build(); - $this->givenRawServerResponse("HTTP/1.1 302 OK\r\nLocation: https://example.org/\r\n\r\n."); + $this->givenRawServerResponse("HTTP/1.1 302 OK\r\nLocation: {$this->httpBin->getServerUri('/')}\r\n\r\n."); $response = $this->executeRequest($this->createRequest()); @@ -400,7 +391,7 @@ public function testRedirectWithFollow(): void public function testClientAddsZeroContentLengthHeaderForEmptyBodiesOnPost(): void { - $uri = 'http://httpbin.org/post'; + $uri = $this->httpBin->getServerUri('/post'); $request = new Request($uri); $request->setMethod('POST'); @@ -412,7 +403,7 @@ public function testClientAddsZeroContentLengthHeaderForEmptyBodiesOnPost(): voi $body = $response->getBody()->buffer(); $result = \json_decode($body, true); - self::assertEquals('0', $result['headers']['Content-Length']); + self::assertEquals('0', $result['headers']['content-length']); } public function testFormEncodedBodyRequest(): void @@ -423,7 +414,7 @@ public function testFormEncodedBodyRequest(): void $body->addField('field1', $field1); $body->addField('field2', $field2); - $request = new Request('https://httpbin.org/post', "POST"); + $request = new Request($this->httpBin->getServerUri('/post'), "POST"); $request->setBody($body); $response = $this->executeRequest($request); @@ -434,12 +425,12 @@ public function testFormEncodedBodyRequest(): void self::assertEquals($field1, $result['form']['field1']); self::assertEquals($field2, $result['form']['field2']); - self::assertEquals('application/x-www-form-urlencoded', $result['headers']['Content-Type']); + self::assertEquals('application/x-www-form-urlencoded', $result['headers']['content-type']); } public function testFileBodyRequest(): void { - $uri = 'http://httpbin.org/post'; + $uri = $this->httpBin->getServerUri('/post'); $bodyPath = __DIR__ . '/fixture/answer.txt'; $body = StreamedContent::fromFile($bodyPath); @@ -469,7 +460,7 @@ public function testMultipartBodyRequest(): void $body->addFile('file1', $file1); $body->addFile('file2', $file2); - $request = new Request('http://httpbin.org/post', "POST"); + $request = new Request($this->httpBin->getServerUri('/post'), "POST"); $request->setBody($body); $response = $this->executeRequest($request); @@ -481,7 +472,7 @@ public function testMultipartBodyRequest(): void self::assertEquals($field1, $result['form']['field1']); self::assertStringEqualsFile($file1, $result['files']['file1']); self::assertStringEqualsFile($file2, $result['files']['file2']); - self::assertEquals('multipart/form-data; boundary=' . $boundary, $result['headers']['Content-Type']); + self::assertEquals('multipart/form-data; boundary=' . $boundary, $result['headers']['content-type']); } /** @@ -491,7 +482,7 @@ public function testGzipResponse(): void { $this->givenNetworkInterceptor(new DecompressResponse); - $response = $this->executeRequest(new Request('http://httpbin.org/gzip')); + $response = $this->executeRequest(new Request($this->httpBin->getServerUri('/gzip'))); self::assertEquals(200, $response->getStatus()); @@ -508,7 +499,7 @@ public function testDeflateResponse(): void { $this->givenNetworkInterceptor(new DecompressResponse); - $response = $this->executeRequest(new Request('http://httpbin.org/deflate')); + $response = $this->executeRequest(new Request($this->httpBin->getServerUri('/deflate'))); self::assertEquals(200, $response->getStatus()); @@ -581,7 +572,7 @@ public function testContentLengthBodyMismatchWithTooManyBytesSimple(): void $this->expectException(InvalidRequestException::class); $this->expectExceptionMessage("Body contained more bytes than specified in Content-Length, aborting request"); - $request = new Request("http://httpbin.org/post", "POST"); + $request = new Request($this->httpBin->getServerUri('/post'), "POST"); $request->setBody(StreamedContent::fromStream(new ReadableBuffer("foo"), 1)); $this->executeRequest($request); @@ -592,7 +583,7 @@ public function testContentLengthBodyMismatchWithTooManyBytesWith3ByteChunksAndL $this->expectException(InvalidRequestException::class); $this->expectExceptionMessage("Body contained more bytes than specified in Content-Length, aborting request"); - $request = new Request("http://httpbin.org/post", "POST"); + $request = new Request($this->httpBin->getServerUri('/post'), "POST"); $request->setBody(StreamedContent::fromStream(new ReadableIterableStream( Pipeline::fromIterable(["a", "b", "c"])->delay(0.5) ), 2)); @@ -605,7 +596,7 @@ public function testContentLengthBodyMismatchWithTooFewBytes(): void $this->expectException(InvalidRequestException::class); $this->expectExceptionMessage("Body contained fewer bytes than specified in Content-Length, aborting request"); - $request = new Request("http://httpbin.org/post", "POST"); + $request = new Request($this->httpBin->getServerUri('/post'), "POST"); $request->setBody(StreamedContent::fromStream(new ReadableBuffer("foo"), 42)); $this->executeRequest($request); @@ -613,21 +604,29 @@ public function testContentLengthBodyMismatchWithTooFewBytes(): void public function testHttp2SupportLargeResponseBody(): void { - $request = new Request('https://1906714720.rsc.cdn77.org/img/cdn77-test-3mb.jpg', 'GET'); + $this->client = $this->builder->usingPool(new UnlimitedConnectionPool(LocalHttpBin::untrustedConnectionFactory()))->build(); + + $httpsBin = LocalHttpBin::startSecureServer(); + + $request = new Request($httpsBin->getServerUri('/bytes/3000000'), 'GET'); $request->setTransferTimeout(100); $request->setBodySizeLimit(10000000000); - $response = $this->client->request($request); - $response->getBody()->buffer(); + try { + $response = $this->client->request($request); + $body = $response->getBody()->buffer(); + } finally { + $httpsBin->stopServer(); + } self::assertSame(200, $response->getStatus()); + self::assertSame('2', $response->getProtocolVersion()); + self::assertSame(3000000, \strlen($body)); } public function testHttp2UpgradeResponse(): void { - self::markTestSkipped('Returns 502 currently instead of upgrading the connection'); - - $request = new Request('http://nghttp2.org/'); + $request = new Request($this->httpBin->getServerUri('/')); $request->setHeader('connection', 'upgrade, http2-settings'); $request->setHeader('upgrade', 'h2c'); $request->setHeader('http2-settings', 'AAMAAABkAARAAAAAAAIAAAAA'); @@ -640,7 +639,7 @@ public function testHttp2UpgradeResponse(): void public function testHttp2PriorKnowledge(): void { - $request = new Request('http://nghttp2.org/'); + $request = new Request($this->httpBin->getServerUri('/')); $request->setProtocolVersions(['2']); $response = $this->executeRequest($request); @@ -651,7 +650,9 @@ public function testHttp2PriorKnowledge(): void public function testHttp2PriorKnowledgeUnsupported(): void { - $request = new Request('http://stackoverflow.com/'); + $this->givenRawServerResponse(''); + + $request = $this->createRequest(); $request->setProtocolVersions(['2']); $this->expectException(SocketException::class); @@ -665,7 +666,7 @@ public function testNoMemoryLeak(): void for ($i = 0; $i < 3; $i++) { $client = (new HttpClientBuilder())->build(); - $request = new Request('http://httpbin.org/'); + $request = new Request($this->httpBin->getServerUri('/')); $response = $client->request($request); $response->getBody()->buffer(); @@ -684,11 +685,7 @@ public function tearDown(): void { parent::tearDown(); - if (!isset($this->httpServer)) { - return; - } - - $this->httpServer->stop(); + $this->httpBin->stopServer(); if (isset($this->rawHandler)) { EventLoop::cancel($this->rawHandler); @@ -702,6 +699,8 @@ protected function setUp(): void $this->builder = (new HttpClientBuilder)->retry(0); $this->client = $this->builder->build(); + $this->httpBin = LocalHttpBin::startInsecureServer(); + $this->socket = listen(new InternetAddress('127.0.0.1', 0)); $this->socket->unreference(); diff --git a/test/Connection/ConnectionLimitingPoolTest.php b/test/Connection/ConnectionLimitingPoolTest.php index 9a119e79..70e9e449 100644 --- a/test/Connection/ConnectionLimitingPoolTest.php +++ b/test/Connection/ConnectionLimitingPoolTest.php @@ -8,6 +8,7 @@ use Amp\Http\Client\Request; use Amp\Http\Client\Response; use Amp\Http\Client\SocketException; +use Amp\Http\Client\Support\LocalHttpBin; use Amp\Http\Client\Trailers; use Amp\PHPUnit\AsyncTestCase; use Amp\Socket\InternetAddress; @@ -20,66 +21,82 @@ class ConnectionLimitingPoolTest extends AsyncTestCase { public function testSingleConnection(): void { + $httpBin = LocalHttpBin::startInsecureServer(); $client = (new HttpClientBuilder) ->usingPool(ConnectionLimitingPool::byAuthority(1)) ->build(); $this->setMinimumRuntime(2); - Future\await([ - async(function () use ($client) { - $response = $client->request(new Request('http://httpbin.org/delay/1')); - $response->getBody()->buffer(); - return $response; - }), - async(function () use ($client) { - $response = $client->request(new Request('http://httpbin.org/delay/1')); - $response->getBody()->buffer(); - return $response; - }), - ]); + try { + Future\await([ + async(function () use ($client, $httpBin) { + $response = $client->request(new Request($httpBin->getServerUri('/delay/1'))); + $response->getBody()->buffer(); + return $response; + }), + async(function () use ($client, $httpBin) { + $response = $client->request(new Request($httpBin->getServerUri('/delay/1'))); + $response->getBody()->buffer(); + return $response; + }), + ]); + } finally { + $httpBin->stopServer(); + } } public function testSingleConnectionDoNotUseBody(): void { + $httpBin = LocalHttpBin::startSecureServer(); $client = (new HttpClientBuilder) - ->usingPool(ConnectionLimitingPool::byAuthority(1)) + ->usingPool(ConnectionLimitingPool::byAuthority(1, LocalHttpBin::untrustedConnectionFactory())) ->build(); $this->setMinimumRuntime(2); - $r1 = new Request('https://httpbin.org/delay/1'); + $r1 = new Request($httpBin->getServerUri('/delay/1')); $r1->setProtocolVersions(['1.1']); - $r2 = new Request('https://httpbin.org/delay/1'); + $r2 = new Request($httpBin->getServerUri('/delay/1')); $r2->setProtocolVersions(['1.1']); - $future = async($client->request(...), $r1); - async($client->request(...), $r2); - - $future->await(); + try { + Future\await([ + async($client->request(...), $r1), + async($client->request(...), $r2), + ]); + } finally { + $httpBin->stopServer(); + } } public function testSingleConnectionDoNotUseBodyHttp2(): void { + $httpBin = LocalHttpBin::startSecureServer(); $client = (new HttpClientBuilder) - ->usingPool(ConnectionLimitingPool::byAuthority(1)) + ->usingPool(ConnectionLimitingPool::byAuthority(1, LocalHttpBin::untrustedConnectionFactory())) ->build(); $this->setMinimumRuntime(1); - $r1 = new Request('https://httpbin.org/delay/1'); + $r1 = new Request($httpBin->getServerUri('/delay/1')); $r1->setProtocolVersions(['2']); - $r2 = new Request('https://httpbin.org/delay/1'); + $r2 = new Request($httpBin->getServerUri('/delay/1')); $r2->setProtocolVersions(['2']); - $future = async($client->request(...), $r1); - async($client->request(...), $r2); - - $future->await(); + try { + Future\await([ + async($client->request(...), $r1), + async($client->request(...), $r2), + ]); + } finally { + $httpBin->stopServer(); + } } public function testTwoConnections(): void { + $httpBin = LocalHttpBin::startInsecureServer(); $client = (new HttpClientBuilder) ->usingPool(ConnectionLimitingPool::byAuthority(2)) ->build(); @@ -87,10 +104,14 @@ public function testTwoConnections(): void $this->setTimeout(6); $this->setMinimumRuntime(2); - Future\await([ - async(fn () => $client->request(new Request('http://httpbin.org/delay/2'))), - async(fn () => $client->request(new Request('http://httpbin.org/delay/2'))), - ]); + try { + Future\await([ + async(fn () => $client->request(new Request($httpBin->getServerUri('/delay/2')))), + async(fn () => $client->request(new Request($httpBin->getServerUri('/delay/2')))), + ]); + } finally { + $httpBin->stopServer(); + } } public function testWaitForConnectionToBecomeAvailable(): void diff --git a/test/Connection/StreamLimitingPoolTest.php b/test/Connection/StreamLimitingPoolTest.php index cbbf5e19..2f6ca0c1 100644 --- a/test/Connection/StreamLimitingPoolTest.php +++ b/test/Connection/StreamLimitingPoolTest.php @@ -5,6 +5,7 @@ use Amp\Future; use Amp\Http\Client\HttpClientBuilder; use Amp\Http\Client\Request; +use Amp\Http\Client\Support\LocalHttpBin; use Amp\PHPUnit\AsyncTestCase; use Amp\Sync\LocalKeyedMutex; use function Amp\async; @@ -13,15 +14,22 @@ class StreamLimitingPoolTest extends AsyncTestCase { public function testByHost(): void { + $httpBin = LocalHttpBin::startSecureServer(); + $connectionPool = new UnlimitedConnectionPool(LocalHttpBin::untrustedConnectionFactory()); + $client = (new HttpClientBuilder) - ->usingPool(StreamLimitingPool::byHost(new UnlimitedConnectionPool, new LocalKeyedMutex)) + ->usingPool(StreamLimitingPool::byHost($connectionPool, new LocalKeyedMutex)) ->build(); $this->setMinimumRuntime(2); - Future\await([ - async(fn () => $client->request(new Request('https://httpbin.org/delay/1'))), - async(fn () => $client->request(new Request('https://httpbin.org/delay/1'))), - ]); + try { + Future\await([ + async(fn () => $client->request(new Request($httpBin->getServerUri('/delay/1')))), + async(fn () => $client->request(new Request($httpBin->getServerUri('/delay/1')))), + ]); + } finally { + $httpBin->stopServer(); + } } } diff --git a/test/HttpClientBuilderTest.php b/test/HttpClientBuilderTest.php index 3462f519..f1f5bfa6 100644 --- a/test/HttpClientBuilderTest.php +++ b/test/HttpClientBuilderTest.php @@ -2,6 +2,7 @@ namespace Amp\Http\Client; +use Amp\Http\Client\Support\LocalHttpBin; use Amp\PHPUnit\AsyncTestCase; class HttpClientBuilderTest extends AsyncTestCase @@ -20,13 +21,20 @@ public function testUserInfoDeprecationAllow(): void { $client = (new HttpClientBuilder)->allowDeprecatedUriUserInfo()->build(); - $response = $client->request(new Request('http://foobar@amphp.org/amp')); + $httpBin = LocalHttpBin::startInsecureServer(); + $authority = $httpBin->getServerAuthority(); + + try { + $response = $client->request(new Request("http://foobar@{$authority}/redirect/status/200")); + } finally { + $httpBin->stopServer(); + } $this->assertTrue(true); // no exception $this->assertNotNull($response->getPreviousResponse()); $this->assertNull($response->getPreviousResponse()->getPreviousResponse()); - $this->assertSame('https://amphp.org/amp', (string) $response->getRequest()->getUri()); - $this->assertSame('http://amphp.org/amp', $response->getRequest()->getHeader('referer')); - $this->assertSame('http://foobar@amphp.org/amp', (string) $response->getPreviousResponse()->getRequest()->getUri()); + $this->assertSame("http://{$authority}/status/200", (string) $response->getRequest()->getUri()); + $this->assertSame("http://{$authority}/redirect/status/200", $response->getRequest()->getHeader('referer')); + $this->assertSame("http://foobar@{$authority}/redirect/status/200", (string) $response->getPreviousResponse()->getRequest()->getUri()); } } diff --git a/test/Support/LocalHttpBin.php b/test/Support/LocalHttpBin.php new file mode 100644 index 00000000..1d36e3e8 --- /dev/null +++ b/test/Support/LocalHttpBin.php @@ -0,0 +1,191 @@ +withDefaultCertificate($certificate); + + return self::startServer('https', (new BindContext())->withTlsContext($tlsContext)); + } + + public static function untrustedConnectionFactory(): ConnectionFactory + { + $tlsContext = (new ClientTlsContext(''))->withoutPeerVerification()->withoutPeerNameVerification(); + $connectContext = (new ConnectContext())->withTlsContext($tlsContext); + + return new DefaultConnectionFactory(connectContext: $connectContext); + } + + public function getServerUri(string $path = '/'): string + { + return $this->scheme . '://' . $this->getServerAuthority() . $path; + } + + public function getServerAuthority(): string + { + return $this->server->getServers()[0]->getAddress()->toString(); + } + + public function stopServer(): void + { + $this->server->stop(); + } + + public function handleRequest(Request $request): Response + { + $path = \trim($request->getUri()->getPath(), '/'); + [$route, $argument] = \explode('/', $path, 2) + [1 => '']; + + return match ($route) { + 'user-agent' => $this->makeJsonResponse(['user-agent' => $request->getHeader('user-agent')]), + 'post', 'put' => $this->echoRequestToResponse($request), + 'status' => new Response((int) $argument), + 'delay' => $this->delayedResponse((int) $argument), + 'bytes' => new Response(body: \str_repeat('.', (int) $argument)), + 'gzip' => $this->makeGZippedResponse('{"gzipped":true}'), + 'deflate' => $this->makeDeflateResponse('{"deflated":true}'), + 'gzip-bomb' => $this->makeGZippedResponse(\str_repeat("\0", 11534336)), // 11 MiB + 'redirect' => new Response(302, ['location' => $this->getServerUri('/' . $argument)]), + default => new Response(200), + }; + } + + private static function startServer(string $scheme, BindContext $bindContext): self + { + $logger = new NullLogger(); + $httpDriverFactory = new DefaultHttpDriverFactory($logger, allowHttp2Upgrade: true); + $server = SocketHttpServer::createForDirectAccess( + $logger, + enableCompression: false, + httpDriverFactory: $httpDriverFactory, + ); + $server->expose('127.0.0.1:0', $bindContext); + + $httpBin = new self($server, $scheme); + $server->start($httpBin, new DefaultErrorHandler()); + + return $httpBin; + } + + private function makeJsonResponse(array $data): Response + { + $body = \json_encode($data, \JSON_THROW_ON_ERROR); + + return new Response(200, ['content-type' => 'application/json'], $body); + } + + private function makeGZippedResponse(string $content): Response + { + $body = \gzencode($content); + + return new Response(200, ['content-encoding' => 'gzip'], $body); + } + + private function makeDeflateResponse(string $content): Response + { + $body = \gzcompress($content); + + return new Response(200, ['content-encoding' => 'deflate'], $body); + } + + private function echoRequestToResponse(Request $request): Response + { + try { + return $this->makeJsonResponse($this->echoRequest($request)); + } catch (ClientException) { + return new Response(400); + } + } + + private function delayedResponse(int $seconds): Response + { + delay($seconds, reference: false); + + return new Response(200); + } + + private function echoRequest(Request $request): array + { + $body = $request->getBody()->buffer(); + $contentType = $request->getHeader('content-type') ?? ''; + + $headers = []; + foreach ($request->getHeaders() as $name => $values) { + $headers[$name] = \implode(', ', $values); + } + + $form = []; + $files = []; + if ($contentType === 'application/x-www-form-urlencoded') { + \parse_str($body, $form); + } elseif (\preg_match('(^multipart/form-data; boundary=(.+)$)', $contentType, $match) === 1) { + [$form, $files] = $this->parseMultipart($body, $match[1]); + } + + return [ + 'data' => $body, + 'form' => $form, + 'files' => $files, + 'headers' => $headers, + ]; + } + + /** + * @return array{array, array} + */ + private function parseMultipart(string $body, string $boundary): array + { + $form = []; + $files = []; + + $parts = \explode('--' . $boundary, $body); + foreach ($parts as $part) { + if (!\str_contains($part, "\r\n\r\n")) { + continue; + } + + [$headers, $content] = \explode("\r\n\r\n", $part, 2); + $content = \substr($content, 0, -2); + + \preg_match('( name="([^"]+)")', $headers, $name); + if (\str_contains($headers, 'filename=')) { + $files[$name[1]] = $content; + } else { + $form[$name[1]] = $content; + } + } + return [$form, $files]; + } +} diff --git a/test/tls/dh2048.pem b/test/tls/dh2048.pem new file mode 100644 index 00000000..c0419053 --- /dev/null +++ b/test/tls/dh2048.pem @@ -0,0 +1,8 @@ +-----BEGIN DH PARAMETERS----- +MIIBCAKCAQEAyzouK8nA8xjTvxyAfy+Y/etGyG2DHbBYwQuLQkaNpFwQjYW2SMwM +NB/bug1P/YogspHEVBBYd4CXA2ZrNdgqLsy7uGrnlEXvSEdxY+LHfTYAkb7ONANE +PghQUAfy7n7TULkQZCdcOQaEBwNSB8N3cIGvQCsne82T4ewKDseNO8UC+Uw4QVEQ +OYgpIX1XSgMdtR+km/xe5F8p+EgxwaZI+Gw7TVyo/H6A9JnJrF+hKjXImrsrSB// +58WbR5tI6jfxhsmQV3V8/ryF9BSj2MJgKXct0ouCb1uzPNDo7cOs76jVZZF6jTPV +KTwUCCe8gR7ZVwgeFqnr65WtaCoK+aYpnwIBAg== +-----END DH PARAMETERS-----