Skip to content

Commit 5dedc81

Browse files
authored
Enhance TLS handshake error message with additional details from previous exception (#385)
1 parent a3e8711 commit 5dedc81

File tree

2 files changed

+54
-2
lines changed

2 files changed

+54
-2
lines changed

src/Connection/DefaultConnectionFactory.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,10 +133,15 @@ public function create(Request $request, Cancellation $cancellation): Connection
133133
} catch (StreamException $streamException) {
134134
$socket->close();
135135

136+
$errorMessage = $streamException->getMessage();
137+
\preg_match('/error:[0-9a-f]*:[^:]*:[^:]*:(.+)$/i', $errorMessage, $matches);
138+
$errorMessage = \trim($matches[1] ?? \explode('():', $errorMessage, 2)[1] ?? $errorMessage);
139+
136140
throw new SocketException(\sprintf(
137-
"Connection to '%s' @ '%s' closed during TLS handshake",
141+
"Connection to '%s' @ '%s' closed during TLS handshake: %s",
138142
$authority,
139-
$socket->getRemoteAddress()->toString()
143+
$socket->getRemoteAddress()->toString(),
144+
$errorMessage,
140145
), 0, $streamException);
141146
} catch (CancelledException) {
142147
$socket->close();

test/ClientBadSslIntegrationTest.php

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Amp\Http\Client;
4+
5+
use Amp\PHPUnit\AsyncTestCase;
6+
7+
final class ClientBadSslIntegrationTest extends AsyncTestCase
8+
{
9+
private HttpClient $client;
10+
11+
protected function setUp(): void
12+
{
13+
parent::setUp();
14+
15+
$this->client = (new HttpClientBuilder)->retry(0)->build();
16+
}
17+
18+
public function testSelfSignedCertificate(): void
19+
{
20+
$request = new Request('https://self-signed.badssl.com/');
21+
22+
$this->expectException(SocketException::class);
23+
$this->expectExceptionMessageMatches("/^Connection to 'self-signed.badssl.com:443' @ '.+' closed during TLS handshake: certificate verify failed$/");
24+
25+
$this->client->request($request);
26+
}
27+
28+
public function testWrongHostCertificate(): void
29+
{
30+
$request = new Request('https://wrong.host.badssl.com/');
31+
32+
$this->expectException(SocketException::class);
33+
$this->expectExceptionMessageMatches("/^Connection to 'wrong.host.badssl.com:443' @ '.+' closed during TLS handshake: Peer certificate CN=`\*.badssl.com' did not match expected CN=`wrong.host.badssl.com'$/");
34+
35+
$this->client->request($request);
36+
}
37+
38+
public function testDhKeyTooSmall(): void
39+
{
40+
$request = new Request('https://dh512.badssl.com/');
41+
42+
$this->expectException(SocketException::class);
43+
$this->expectExceptionMessageMatches("/^Connection to 'dh512.badssl.com:443' @ '.+' closed during TLS handshake: dh key too small$/");
44+
45+
$this->client->request($request);
46+
}
47+
}

0 commit comments

Comments
 (0)