diff --git a/README.md b/README.md
index 3c587b5..e517caf 100644
--- a/README.md
+++ b/README.md
@@ -6,6 +6,7 @@ Pure non-blocking (fiber based) strictly typed full-featured PHP driver for NATS
- [NATS Core](https://docs.nats.io/nats-concepts/core-nats)
- [Connection](#connection)
- [Authentication](#authentication)
+ - [TLS](#tls)
- [Connect and ping](#connect-and-ping)
- [Reconnect](#reconnect)
- [Publish-Subscribe](#pub-sub)
@@ -64,11 +65,12 @@ The library implements the full functionality of NATS Core, including pub-sub, q
#### Connection
-`Nats\Config::fromURI()` takes `[scheme://][user[:password]@]host[:port][,host[:port]...][?options]`. The scheme is `nats://` (`tcp://` is an alias, and it may be omitted),
-`tls://`, `ws://` and `wss://` are rejected as not supported yet. A host without a port connects to `4222`, an IPv6 host goes in brackets (`[::1]:4222`),
+`Nats\Config::fromURI()` takes `[scheme://][user[:password]@]host[:port][,host[:port]...][?options]`. The scheme is `nats://` (`tcp://` is an alias, and it may be omitted)
+or `tls://`, which requires TLS (see [TLS](#tls)); `ws://` and `wss://` are rejected as not supported yet. A host without a port connects to `4222`, an IPv6 host goes in brackets (`[::1]:4222`),
and the credentials are percent-encoded like in any url (`p%40ss` for `p@ss`). The servers of a list are tried in a random order (in the given one with `noRandomize`, `no_randomize=true` in the uri) until one accepts the connection, see [Reconnect](#reconnect);
each one may repeat the scheme and the credentials, as in nats.go (`nats://u:p@h1:4222,nats://u:p@h2:4222`): one user is sent to every server, so different credentials are rejected. The options are the snake_case names of the `Nats\Config` parameters,
-e.g. `connection_timeout` (seconds, fractions allowed), `request_timeout`, `verbose`, `no_responders`, `ping`, `token`, `jwt`, `nkey`, `credentials_file`, `jwt_file`, `nkey_file`, `client_name`, `allow_reconnect`, `max_reconnects` (negative for no limit), `reconnect_wait`, `reconnect_jitter`, `reconnect_buffer_size`, `no_randomize`.
+e.g. `connection_timeout` (seconds, fractions allowed), `request_timeout`, `verbose`, `no_responders`, `ping`, `token`, `jwt`, `nkey`, `credentials_file`, `jwt_file`, `nkey_file`, `client_name`, `allow_reconnect`, `max_reconnects` (negative for no limit), `reconnect_wait`, `reconnect_jitter`, `reconnect_buffer_size`, `no_randomize`,
+and the TLS ones `tls_ca_file`, `tls_cert_file`, `tls_key_file`, `tls_key_passphrase`, `tls_verify`, `tls_server_name`, `tls_handshake_first`.
Userinfo without a colon is a token, as in nats.go (`nats://s3cr3t@host`), while `nats://alice:@host` is the user `alice` with an empty password, see [Authentication](#authentication):
```php
@@ -87,8 +89,8 @@ dump($nc->jetStream()->accountInfo());
#### Authentication
-The client supports every authentication method of nats-server except TLS certificates: a user and a password, a token,
-an NKey seed, and a JWT signed with the NKey of the user. Only one way to pass each of them may be set, e.g. `jwt` or `jwtFile`, and a token cannot be combined with a user.
+The client supports every authentication method of nats-server: a user and a password, a token,
+an NKey seed, a JWT signed with the NKey of the user, and a TLS client certificate (see [TLS](#tls)). Only one way to pass each of them may be set, e.g. `jwt` or `jwtFile`, and a token cannot be combined with a user.
```php
connect();
+} catch (Nats\Exception\TlsHandshakeFailed $e) {
+ exit('The server certificate is not trusted: ' . $e->getMessage());
+}
+```
+
+`verifyPeer: false` (`tls_verify=false`) skips the verification of the server certificate and is meant for testing only.
+A server that refuses the client certificate, or its absence, closes the connection after the handshake: PHP does not report its TLS alert,
+so `connect()` fails with `Nats\Exception\ConnectionIsNotAvailable` that says so.
+
#### Connect and ping
The client connects lazily, on the first call that needs the server. Call `connect()` to establish the connection at startup instead,
diff --git a/compose.yaml b/compose.yaml
index d77aa40..cf0163d 100644
--- a/compose.yaml
+++ b/compose.yaml
@@ -39,5 +39,28 @@ services:
image: nats
command: --name nats-cluster-2 -p 4222 --cluster_name test --cluster nats://0.0.0.0:6222 --routes nats://nats-cluster-1:6222
+ # TLS with the self-signed certificates of docker/nats/tls: offered (with the monitoring to tell the TLS connections),
+ # verifying the clients, and with the handshake before INFO.
+ nats-tls:
+ image: nats
+ command: -c /etc/nats/tls-server.conf --name nats-tls -p 4222 -m 8222
+ volumes:
+ - ./docker/nats/tls-server.conf:/etc/nats/tls-server.conf
+ - ./docker/nats/tls:/etc/nats/tls
+
+ nats-mtls:
+ image: nats
+ command: -c /etc/nats/mtls-server.conf --name nats-mtls -p 4222
+ volumes:
+ - ./docker/nats/mtls-server.conf:/etc/nats/mtls-server.conf
+ - ./docker/nats/tls:/etc/nats/tls
+
+ nats-tls-first:
+ image: nats
+ command: -c /etc/nats/tls-first-server.conf --name nats-tls-first -p 4222
+ volumes:
+ - ./docker/nats/tls-first-server.conf:/etc/nats/tls-first-server.conf
+ - ./docker/nats/tls:/etc/nats/tls
+
nats-cli:
image: bitnamilegacy/natscli:latest
diff --git a/composer.json b/composer.json
index eff7c9a..5eb701d 100644
--- a/composer.json
+++ b/composer.json
@@ -24,7 +24,7 @@
"amphp/byte-stream": "^2.1",
"amphp/parser": "^1.1",
"amphp/pipeline": "^1.2",
- "amphp/socket": "^2.3.1",
+ "amphp/socket": "^2.4",
"cuyz/valinor": "^1.15 || ^2.3",
"revolt/event-loop": "^1.0.8",
"thesis/package-version": "^0.1.2",
diff --git a/docker/nats/mtls-server.conf b/docker/nats/mtls-server.conf
new file mode 100644
index 0000000..e233f33
--- /dev/null
+++ b/docker/nats/mtls-server.conf
@@ -0,0 +1,7 @@
+# TLS that verifies the client certificates against the test CA.
+tls {
+ cert_file: "/etc/nats/tls/server-cert.pem"
+ key_file: "/etc/nats/tls/server-key.pem"
+ ca_file: "/etc/nats/tls/ca.pem"
+ verify: true
+}
diff --git a/docker/nats/tls-first-server.conf b/docker/nats/tls-first-server.conf
new file mode 100644
index 0000000..204ca1f
--- /dev/null
+++ b/docker/nats/tls-first-server.conf
@@ -0,0 +1,6 @@
+# TLS that the clients start before the server sends INFO.
+tls {
+ cert_file: "/etc/nats/tls/server-cert.pem"
+ key_file: "/etc/nats/tls/server-key.pem"
+ handshake_first: true
+}
diff --git a/docker/nats/tls-server.conf b/docker/nats/tls-server.conf
new file mode 100644
index 0000000..7b4ccba
--- /dev/null
+++ b/docker/nats/tls-server.conf
@@ -0,0 +1,7 @@
+# TLS with the self-signed test CA, offered rather than required: the clients are not verified,
+# and the plain ones are accepted too.
+tls {
+ cert_file: "/etc/nats/tls/server-cert.pem"
+ key_file: "/etc/nats/tls/server-key.pem"
+}
+allow_non_tls: true
diff --git a/docker/nats/tls/ca.pem b/docker/nats/tls/ca.pem
new file mode 100644
index 0000000..6e51073
--- /dev/null
+++ b/docker/nats/tls/ca.pem
@@ -0,0 +1,11 @@
+-----BEGIN CERTIFICATE-----
+MIIBkjCCATmgAwIBAgIUWqwDDdsF+vBaLPaVhDmZPe8fsucwCgYIKoZIzj0EAwIw
+HjEcMBoGA1UEAwwTdGhlc2lzLW5hdHMgdGVzdCBDQTAgFw0yNjExMTExMjU3NDBa
+GA8yMTI2MTAxODEyNTc0MFowHjEcMBoGA1UEAwwTdGhlc2lzLW5hdHMgdGVzdCBD
+QTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABP2w4IqpFvF43gGdUAn+m0kyu3uH
+THluRN1OB3JLUZZrNaZmNnMFP/f7VNK/9LWh1n3zEX1PZqodxaBsuOLcMf6jUzBR
+MB0GA1UdDgQWBBROEd2hvIBCMk2kqQ0dT7OfqXIzBDAfBgNVHSMEGDAWgBROEd2h
+vIBCMk2kqQ0dT7OfqXIzBDAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0cA
+MEQCIBnyizXihXM/Vlg1X53wvtlyKZiJwdrMdpAMMKCLvOGKAiB1N8Tmg+u2WXV8
+2gr7UMe1Obzb6K6aOFr6CKsvg0c5VA==
+-----END CERTIFICATE-----
diff --git a/docker/nats/tls/client-cert.pem b/docker/nats/tls/client-cert.pem
new file mode 100644
index 0000000..4a125fe
--- /dev/null
+++ b/docker/nats/tls/client-cert.pem
@@ -0,0 +1,11 @@
+-----BEGIN CERTIFICATE-----
+MIIBmzCCAUGgAwIBAgIUUY5P6yO/67YPk16xFNcFoU4JxskwCgYIKoZIzj0EAwIw
+HjEcMBoGA1UEAwwTdGhlc2lzLW5hdHMgdGVzdCBDQTAgFw0yNjExMTExMjU3NDBa
+GA8yMTI2MTAxODEyNTc0MFowIjEgMB4GA1UEAwwXdGhlc2lzLW5hdHMgdGVzdCBj
+bGllbnQwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQuizr6Pt1Q0EDm2oIPoMYP
+Kt7rlFxkjn9o+g+vKBhwAHGq68c2Pz6lVYaNrwRSLN+XR5gyVpxyhig2SMzDuAcD
+o1cwVTATBgNVHSUEDDAKBggrBgEFBQcDAjAdBgNVHQ4EFgQU4xaCgu6d0C/UIYlS
+IzF2gBD1rwAwHwYDVR0jBBgwFoAUThHdobyAQjJNpKkNHU+zn6lyMwQwCgYIKoZI
+zj0EAwIDSAAwRQIhAP/yQUmPN00r0yFqWarFZ02FxZXIxVxxuvbAndBbZqTsAiAe
+i5n8O/0fCUE/dfc42qr9EXXaJuUvmMYynMgJtcXpaA==
+-----END CERTIFICATE-----
diff --git a/docker/nats/tls/client-key-encrypted.pem b/docker/nats/tls/client-key-encrypted.pem
new file mode 100644
index 0000000..d145c25
--- /dev/null
+++ b/docker/nats/tls/client-key-encrypted.pem
@@ -0,0 +1,7 @@
+-----BEGIN ENCRYPTED PRIVATE KEY-----
+MIHsMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAcBAgWCx0qAD14iAICCAAw
+DAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEOX1ta+/AUIUXjNFHeQYeakEgZBM
+xfUv1UUkYVUTPIU/3lsqUpXa3/ykIwzz6Ti9OkIUrflWQr7yvjoYX2RFGNU2VLqj
+8mjVorxIfHnZGo2eH+reL7Vzet/vgWZKjoGGDqe659j1ydONlR09A5wX+oGblHFy
+ynnvm/WwGNwS9QhOSnWTRh27KP+LP61rM8WFy0T67TqlpK46Rl5mZoJH8Tl6O/4=
+-----END ENCRYPTED PRIVATE KEY-----
diff --git a/docker/nats/tls/client-key.pem b/docker/nats/tls/client-key.pem
new file mode 100644
index 0000000..e30772c
--- /dev/null
+++ b/docker/nats/tls/client-key.pem
@@ -0,0 +1,5 @@
+-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgGJxC2PVy3Cu95y8q
+9KexoKhFLWJBtbLCZpnvs5NI10WhRANCAAQuizr6Pt1Q0EDm2oIPoMYPKt7rlFxk
+jn9o+g+vKBhwAHGq68c2Pz6lVYaNrwRSLN+XR5gyVpxyhig2SMzDuAcD
+-----END PRIVATE KEY-----
diff --git a/docker/nats/tls/server-cert.pem b/docker/nats/tls/server-cert.pem
new file mode 100644
index 0000000..b47c28b
--- /dev/null
+++ b/docker/nats/tls/server-cert.pem
@@ -0,0 +1,12 @@
+-----BEGIN CERTIFICATE-----
+MIIBzjCCAXWgAwIBAgIUUY5P6yO/67YPk16xFNcFoU4JxsgwCgYIKoZIzj0EAwIw
+HjEcMBoGA1UEAwwTdGhlc2lzLW5hdHMgdGVzdCBDQTAgFw0yNjExMTExMjU3NDBa
+GA8yMTI2MTAxODEyNTc0MFowEzERMA8GA1UEAwwIbmF0cy10bHMwWTATBgcqhkjO
+PQIBBggqhkjOPQMBBwNCAATgnVIR3JZQI02uAQsWiXsq5qrlxwPWVDLZFrQvqUtP
+2lb6ZRGQAn9xtfLNk5G1T2ayXJF+JDdHgcLQhknCoQq2o4GZMIGWMD8GA1UdEQQ4
+MDaCCG5hdHMtdGxzggluYXRzLW10bHOCDm5hdHMtdGxzLWZpcnN0gglsb2NhbGhv
+c3SHBH8AAAEwEwYDVR0lBAwwCgYIKwYBBQUHAwEwHQYDVR0OBBYEFBstKevXt7AY
+qCmwWdKl6mGdd5xXMB8GA1UdIwQYMBaAFE4R3aG8gEIyTaSpDR1Ps5+pcjMEMAoG
+CCqGSM49BAMCA0cAMEQCIBfZzVbGZAksZpRdfINdZlsy5JubgsrQk0nOEUP7HPyr
+AiAq9d9l6FmrkRQJYQOO0KwXVupHnQjZ3k845tVNY1tXJQ==
+-----END CERTIFICATE-----
diff --git a/docker/nats/tls/server-key.pem b/docker/nats/tls/server-key.pem
new file mode 100644
index 0000000..be1a520
--- /dev/null
+++ b/docker/nats/tls/server-key.pem
@@ -0,0 +1,5 @@
+-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgU9vExqXCZepH7dFE
+v6ophJ/CXdblitRicDWDUqbOn86hRANCAATgnVIR3JZQI02uAQsWiXsq5qrlxwPW
+VDLZFrQvqUtP2lb6ZRGQAn9xtfLNk5G1T2ayXJF+JDdHgcLQhknCoQq2
+-----END PRIVATE KEY-----
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index ed5a153..bb6e8b7 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -14,6 +14,10 @@
+
+
+
+
diff --git a/src/Config.php b/src/Config.php
index cca4e9b..b6cd8cf 100644
--- a/src/Config.php
+++ b/src/Config.php
@@ -53,6 +53,8 @@
* @param float $reconnectJitter in seconds, the upper bound of a random delay added to the pause, so that the clients do not reconnect at once
* @param non-negative-int $reconnectBufferSize in bytes, the publishes buffered while reconnecting, 0 to fail them instead
* @param bool $noRandomize whether to try the servers in the given order instead of a random one
+ * @param ?TlsConfig $tls the TLS options, with which TLS is required; without them the connection is upgraded to TLS
+ * only when the server requires it, verifying its certificate against the system authorities
* @throws \InvalidArgumentException
*/
public function __construct(
@@ -86,6 +88,7 @@ public function __construct(
public float $reconnectJitter = self::DEFAULT_RECONNECT_JITTER,
public int $reconnectBufferSize = self::DEFAULT_RECONNECT_BUFFER_SIZE,
public bool $noRandomize = false,
+ public ?TlsConfig $tls = null,
) {
Validate::duration($connectionTimeout, 'connection timeout');
@@ -178,6 +181,16 @@ public static function fromURI(#[\SensitiveParameter] string $uri): self
reconnectJitter: $query->reconnectJitter ?? self::DEFAULT_RECONNECT_JITTER,
reconnectBufferSize: $query->reconnectBufferSize ?? self::DEFAULT_RECONNECT_BUFFER_SIZE,
noRandomize: $query->noRandomize ?? false,
+ // tls:// or any of the TLS options requires TLS.
+ tls: $parsed->tls || $query->hasTls() ? new TlsConfig(
+ caFile: $query->tlsCaFile,
+ certFile: $query->tlsCertFile,
+ keyFile: $query->tlsKeyFile,
+ keyPassphrase: $query->tlsKeyPassphrase,
+ verifyPeer: $query->tlsVerify ?? true,
+ serverName: $query->tlsServerName,
+ handshakeFirst: $query->tlsHandshakeFirst ?? false,
+ ) : null,
);
}
@@ -208,6 +221,15 @@ public static function fromURI(#[\SensitiveParameter] string $uri): self
* reconnect_jitter?: float,
* reconnect_buffer_size?: non-negative-int,
* no_randomize?: bool,
+ * tls?: array{
+ * ca_file?: non-empty-string,
+ * cert_file?: non-empty-string,
+ * key_file?: non-empty-string,
+ * key_passphrase?: non-empty-string,
+ * verify_peer?: bool,
+ * server_name?: non-empty-string,
+ * handshake_first?: bool,
+ * },
* } $options
* @throws \InvalidArgumentException
*/
@@ -239,6 +261,15 @@ public static function fromArray(#[\SensitiveParameter] array $options): self
reconnectJitter: $options['reconnect_jitter'] ?? self::DEFAULT_RECONNECT_JITTER,
reconnectBufferSize: $options['reconnect_buffer_size'] ?? self::DEFAULT_RECONNECT_BUFFER_SIZE,
noRandomize: $options['no_randomize'] ?? false,
+ tls: isset($options['tls']) ? new TlsConfig(
+ caFile: $options['tls']['ca_file'] ?? null,
+ certFile: $options['tls']['cert_file'] ?? null,
+ keyFile: $options['tls']['key_file'] ?? null,
+ keyPassphrase: $options['tls']['key_passphrase'] ?? null,
+ verifyPeer: $options['tls']['verify_peer'] ?? true,
+ serverName: $options['tls']['server_name'] ?? null,
+ handshakeFirst: $options['tls']['handshake_first'] ?? false,
+ ) : null,
);
}
}
diff --git a/src/Exception/TlsHandshakeFailed.php b/src/Exception/TlsHandshakeFailed.php
new file mode 100644
index 0000000..0b6d327
--- /dev/null
+++ b/src/Exception/TlsHandshakeFailed.php
@@ -0,0 +1,15 @@
+ */
- private ConcurrentIterator $iterator;
+ private readonly Writer $writer;
- public function __construct(Socket $socket)
- {
+ private readonly Protocol\Parser $parser;
+
+ /** @var \SplQueue the frames parsed but not read yet */
+ private readonly \SplQueue $frames;
+
+ private bool $eof = false;
+
+ /** The bytes read after the startup frame, not parsed yet. */
+ private string $unparsed = '';
+
+ public function __construct(
+ private readonly Socket $socket,
+ ) {
$this->writer = new Writer($socket);
- /** @var Queue $queue */
- $queue = new Queue();
- $this->iterator = $queue->iterate();
+ /** @var \SplQueue $frames */
+ $frames = new \SplQueue();
+ $this->frames = $frames;
+ $this->parser = new Protocol\Parser($frames->push(...));
+ }
- EventLoop::queue(static function () use (
- $socket,
- $queue,
- ): void {
- $parser = new Protocol\Parser($queue->push(...));
+ /**
+ * Reads the first line the server sends (INFO), and nothing past it: whatever came along stays unparsed,
+ * so that the plain bytes are never taken for the ones that come after the upgrade to TLS, see {@see hasUnread()}.
+ *
+ * @return ?Protocol\Frame null once the peer has closed the connection
+ * @throws \Throwable
+ */
+ public function readStartupFrame(?Cancellation $cancellation = null): ?Protocol\Frame
+ {
+ $buffer = $this->unparsed;
+ $this->unparsed = '';
- try {
- while (($bytes = $socket->read()) !== null) {
- $parser->push($bytes);
+ try {
+ while (!str_contains($buffer, "\r\n")) {
+ if (\strlen($buffer) > self::MAX_STARTUP_LINE) {
+ throw new \UnexpectedValueException('The startup frame of the nats server is too long.');
}
- $parser->cancel();
- $queue->complete();
- } catch (\Throwable $e) {
- $queue->error($e);
+ $bytes = $this->socket->read($cancellation);
+
+ if ($bytes === null) {
+ $this->eof = true;
+ $this->socket->close();
+
+ return null;
+ }
+
+ $buffer .= $bytes;
}
+ } catch (CancelledException $e) {
+ $this->unparsed = $buffer;
+
+ throw $e;
+ } catch (\Throwable $e) {
+ $this->eof = true;
+ $this->socket->close();
+
+ throw $e;
+ }
- $socket->close();
- });
+ $end = (int) strpos($buffer, "\r\n");
+ $this->unparsed = substr($buffer, $end + 2);
+ $this->parse(substr($buffer, 0, $end + 2));
+
+ return $this->frames->isEmpty()
+ ? throw new \UnexpectedValueException('The startup line of the nats server is not a frame of its own.')
+ : $this->frames->shift();
+ }
+
+ /**
+ * Whether anything has been received but not read yet.
+ */
+ public function hasUnread(): bool
+ {
+ return $this->unparsed !== '' || !$this->frames->isEmpty();
}
+ /**
+ * @return ?Protocol\Frame null once the peer has closed the connection
+ * @throws \Throwable
+ */
public function readFrame(?Cancellation $cancellation = null): ?Protocol\Frame
{
- return $this->iterator->continue($cancellation)
- ? $this->iterator->getValue()
- : null;
+ while ($this->frames->isEmpty()) {
+ if ($this->unparsed !== '') {
+ [$bytes, $this->unparsed] = [$this->unparsed, ''];
+ $this->parse($bytes);
+
+ continue;
+ }
+
+ if ($this->eof) {
+ return null;
+ }
+
+ try {
+ $bytes = $this->socket->read($cancellation);
+
+ if ($bytes === null) {
+ $this->eof = true;
+ $this->parser->cancel();
+ $this->socket->close();
+
+ continue;
+ }
+ } catch (CancelledException $e) {
+ // Nothing has been read: the next call reads on.
+ throw $e;
+ } catch (\Throwable $e) {
+ $this->eof = true;
+ $this->socket->close();
+
+ throw $e;
+ }
+
+ $this->parse($bytes);
+ }
+
+ return $this->frames->shift();
}
/**
@@ -69,4 +156,19 @@ public function writeFrame(Protocol\Frame|iterable $frames): void
$this->writer->write([...$frames]);
$this->writer->flush();
}
+
+ /**
+ * @throws \Throwable
+ */
+ private function parse(string $bytes): void
+ {
+ try {
+ $this->parser->push($bytes);
+ } catch (\Throwable $e) {
+ $this->eof = true;
+ $this->socket->close();
+
+ throw $e;
+ }
+ }
}
diff --git a/src/Internal/Connection/Query.php b/src/Internal/Connection/Query.php
index a3c9991..8167145 100644
--- a/src/Internal/Connection/Query.php
+++ b/src/Internal/Connection/Query.php
@@ -29,6 +29,11 @@
* @param ?float $reconnectWait non-negative and finite
* @param ?float $reconnectJitter non-negative and finite
* @param ?non-negative-int $reconnectBufferSize
+ * @param ?non-empty-string $tlsCaFile
+ * @param ?non-empty-string $tlsCertFile
+ * @param ?non-empty-string $tlsKeyFile
+ * @param ?non-empty-string $tlsKeyPassphrase
+ * @param ?non-empty-string $tlsServerName
*/
private function __construct(
public ?bool $verbose = null,
@@ -56,8 +61,30 @@ private function __construct(
public ?float $reconnectJitter = null,
public ?int $reconnectBufferSize = null,
public ?bool $noRandomize = null,
+ public ?string $tlsCaFile = null,
+ public ?string $tlsCertFile = null,
+ public ?string $tlsKeyFile = null,
+ #[\SensitiveParameter]
+ public ?string $tlsKeyPassphrase = null,
+ public ?bool $tlsVerify = null,
+ public ?string $tlsServerName = null,
+ public ?bool $tlsHandshakeFirst = null,
) {}
+ /**
+ * Whether any of the TLS options is given.
+ */
+ public function hasTls(): bool
+ {
+ return $this->tlsCaFile !== null
+ || $this->tlsCertFile !== null
+ || $this->tlsKeyFile !== null
+ || $this->tlsKeyPassphrase !== null
+ || $this->tlsVerify !== null
+ || $this->tlsServerName !== null
+ || $this->tlsHandshakeFirst !== null;
+ }
+
public static function parse(#[\SensitiveParameter] string $query): self
{
parse_str($query, $options);
@@ -85,6 +112,13 @@ public static function parse(#[\SensitiveParameter] string $query): self
reconnectJitter: self::nonNegativeFloat($options, 'reconnect_jitter'),
reconnectBufferSize: self::nonNegativeInt($options, 'reconnect_buffer_size'),
noRandomize: self::bool($options, 'no_randomize'),
+ tlsCaFile: self::string($options, 'tls_ca_file'),
+ tlsCertFile: self::string($options, 'tls_cert_file'),
+ tlsKeyFile: self::string($options, 'tls_key_file'),
+ tlsKeyPassphrase: self::string($options, 'tls_key_passphrase'),
+ tlsVerify: self::bool($options, 'tls_verify'),
+ tlsServerName: self::string($options, 'tls_server_name'),
+ tlsHandshakeFirst: self::bool($options, 'tls_handshake_first'),
);
}
diff --git a/src/Internal/Connection/ReconnectingConnection.php b/src/Internal/Connection/ReconnectingConnection.php
index 26972cd..d70ead0 100644
--- a/src/Internal/Connection/ReconnectingConnection.php
+++ b/src/Internal/Connection/ReconnectingConnection.php
@@ -82,7 +82,7 @@ public function start(): void
foreach ($this->pool->servers() as $server) {
try {
- $connection = $this->factory->connect($server->url);
+ $connection = $this->factory->connect($server);
} catch (ServerIsNotAvailable $e) {
$errors[$server->url] = $e;
@@ -355,7 +355,7 @@ private function reconnect(): void
}
try {
- $connection = $this->factory->connect($server->url);
+ $connection = $this->factory->connect($server);
} catch (\Throwable $e) {
$error = $e;
diff --git a/src/Internal/Connection/Server.php b/src/Internal/Connection/Server.php
index 69f7e08..49b119c 100644
--- a/src/Internal/Connection/Server.php
+++ b/src/Internal/Connection/Server.php
@@ -20,12 +20,40 @@ final class Server
/**
* @param non-empty-string $url `host:port`
* @param bool $implicit whether the server was announced by the cluster rather than configured
+ * @param ?non-empty-string $tlsName the name to verify the server certificate against instead of the host:
+ * a server announced by its IP address is verified against the name of the one that announced it
*/
public function __construct(
public readonly string $url,
public readonly bool $implicit,
+ public readonly ?string $tlsName = null,
) {}
+ /**
+ * @return non-empty-string the host without the port, an IPv6 address without the brackets
+ */
+ public function host(): string
+ {
+ $colon = strrpos($this->url, ':');
+ $host = $colon !== false ? substr($this->url, 0, $colon) : $this->url;
+ $host = trim($host, '[]');
+
+ return $host !== '' ? $host : $this->url;
+ }
+
+ /**
+ * @return non-empty-string the name the server certificate is expected to have
+ */
+ public function tlsName(): string
+ {
+ return $this->tlsName ?? $this->host();
+ }
+
+ public function hasIpAddress(): bool
+ {
+ return filter_var($this->host(), FILTER_VALIDATE_IP) !== false;
+ }
+
/**
* @return bool whether the attempt failed with the same kind of error as the previous one
*/
diff --git a/src/Internal/Connection/ServerPool.php b/src/Internal/Connection/ServerPool.php
index 7f9d252..89995b7 100644
--- a/src/Internal/Connection/ServerPool.php
+++ b/src/Internal/Connection/ServerPool.php
@@ -33,7 +33,7 @@ public function __construct(
private readonly ?int $maxReconnects,
) {
foreach ($urls as $url) {
- $this->add($url, implicit: false);
+ $this->add(new Server($url, implicit: false));
}
if ($this->randomize) {
@@ -112,7 +112,14 @@ public function discover(array $urls): bool
foreach (array_keys($announced) as $url) {
$new = $new || !isset($this->known[$url]);
- $this->add($url, implicit: true);
+ $server = new Server($url, implicit: true);
+
+ // A certificate is issued for a name rather than for the address the cluster announces, as nats.go assumes:
+ // the server is verified against the name the announcing one is known by. Without such a name
+ // (the current server is an address itself) every server is verified against its own address.
+ $this->add($current !== null && $server->hasIpAddress() && ($current->tlsName !== null || !$current->hasIpAddress())
+ ? new Server($url, implicit: true, tlsName: $current->tlsName())
+ : $server);
}
if ($new && $this->randomize) {
@@ -131,13 +138,10 @@ public function urls(): array
return array_map(static fn(Server $server): string => $server->url, $this->servers);
}
- /**
- * @param non-empty-string $url
- */
- private function add(string $url, bool $implicit): void
+ private function add(Server $server): void
{
- $this->servers[] = new Server($url, $implicit);
- $this->known[$url] = true;
+ $this->servers[] = $server;
+ $this->known[$server->url] = true;
}
/**
diff --git a/src/Internal/Connection/SocketConnection.php b/src/Internal/Connection/SocketConnection.php
index 083656e..cf2bf43 100644
--- a/src/Internal/Connection/SocketConnection.php
+++ b/src/Internal/Connection/SocketConnection.php
@@ -10,14 +10,19 @@
use Amp\DeferredFuture;
use Amp\Future;
use Amp\Socket\Socket;
+use Amp\Socket\SocketException;
+use Amp\Socket\TlsState;
use Amp\TimeoutCancellation;
use Revolt\EventLoop;
use Thesis\Nats\Config;
use Thesis\Nats\Exception\ConnectionIsNotAvailable;
use Thesis\Nats\Exception\ConnectionWasClosed;
use Thesis\Nats\Exception\ServerIsNotAvailable;
+use Thesis\Nats\Exception\TlsHandshakeFailed;
+use Thesis\Nats\Exception\TlsIsNotAvailable;
use Thesis\Nats\Internal\Hooks;
use Thesis\Nats\Internal\Protocol;
+use Thesis\Nats\NatsException;
use function Amp\async;
use function Thesis\Package\version;
@@ -105,6 +110,16 @@ public function startup(): void
\sprintf('The nats server did not complete the handshake within %s seconds.', $timeout),
previous: $e,
);
+ } catch (ConnectionIsNotAvailable $e) {
+ // The TLS alert the server sends before closing is not reported by PHP: the client sees a bare close.
+ if ($this->socket->getTlsState() === TlsState::Enabled) {
+ throw new ConnectionIsNotAvailable(
+ 'The nats server closed the TLS connection during the handshake: it may not accept the client certificate, or its absence.',
+ previous: $e,
+ );
+ }
+
+ throw $e;
}
if (($interval = $this->config->ping) !== null) {
@@ -204,7 +219,13 @@ public function ping(?Cancellation $cancellation = null): float
*/
private function handshake(Cancellation $cancellation): void
{
- $frame = $this->framer->readFrame($cancellation) ?? throw new ConnectionIsNotAvailable();
+ $tls = $this->config->tls;
+
+ if ($tls?->handshakeFirst === true) {
+ $this->secure($cancellation);
+ }
+
+ $frame = $this->framer->readStartupFrame($cancellation) ?? throw new ConnectionIsNotAvailable();
if (!$frame instanceof Protocol\ServerInfo) {
throw new \UnexpectedValueException(
@@ -212,6 +233,22 @@ private function handshake(Cancellation $cancellation): void
);
}
+ if ($tls !== null && !$tls->handshakeFirst && $frame->tlsRequired !== true && $frame->tlsAvailable !== true) {
+ throw new TlsIsNotAvailable('The client requires TLS, but the nats server does not offer it.');
+ }
+
+ // The server that requires TLS gets it without the TLS options too, as nats.go does. Nothing reads the socket
+ // until the reader starts, so the upgrade does not race with it.
+ if ($this->socket->getTlsState() === TlsState::Disabled && ($tls !== null || $frame->tlsRequired === true)) {
+ // The server says nothing else before the handshake: plain bytes past INFO would be taken
+ // for the encrypted ones (e.g. an injected PONG for the answer to CONNECT).
+ if ($this->framer->hasUnread()) {
+ throw new TlsHandshakeFailed('The nats server sent unexpected plain data before the TLS handshake.');
+ }
+
+ $this->secure($cancellation);
+ }
+
if ($this->state !== ConnectionState::Alive) {
$this->run();
}
@@ -227,7 +264,7 @@ private function handshake(Cancellation $cancellation): void
$this->connect(new Protocol\Connect(
verbose: $this->config->verbose,
pedantic: $this->config->pedantic,
- tlsRequired: false,
+ tlsRequired: $this->socket->getTlsState() === TlsState::Enabled,
name: $this->config->clientName,
version: version(self::PACKAGE_NAME),
// Asks the server for the INFO updates: the servers of the cluster and the lame duck mode notification.
@@ -246,7 +283,15 @@ private function handshake(Cancellation $cancellation): void
// In non-verbose mode the server does not acknowledge CONNECT: it stays silent on success and answers
// with -ERR (e.g. Authorization Violation) before closing the socket on failure. A PING forces a reply
// (PONG or -ERR), so that the errors surface from here instead of being lost, the same way nats.go does it.
- $this->framer->writeFrame(Protocol\Ping::Frame);
+ try {
+ $this->framer->writeFrame(Protocol\Ping::Frame);
+ } catch (StreamException $e) {
+ // The server's own error (e.g. Authorization Violation) wins, as when the write gets through.
+ $closed = $this->closedWhileWriting($e);
+
+ throw $closed->getPrevious() instanceof NatsException ? $closed->getPrevious() : new ConnectionIsNotAvailable(previous: $closed);
+ }
+
$handshake->getFuture()->await($cancellation);
} finally {
$this->handshake = null;
@@ -254,6 +299,19 @@ private function handshake(Cancellation $cancellation): void
}
}
+ /**
+ * @throws TlsHandshakeFailed
+ */
+ private function secure(Cancellation $cancellation): void
+ {
+ // A cancelled handshake is let through: it is the connection timeout, not a TLS failure.
+ try {
+ $this->socket->setupTls($cancellation);
+ } catch (SocketException|StreamException $e) {
+ throw new TlsHandshakeFailed("The TLS handshake with the nats server failed: {$e->getMessage()}", previous: $e);
+ }
+ }
+
/**
* The server closes the socket right after sending a fatal error, often in the middle of a write: amp shuts
* the writing side down only, so the reader still gets the error, and the write fails with the server's reason
diff --git a/src/Internal/Connection/SocketConnectionFactory.php b/src/Internal/Connection/SocketConnectionFactory.php
index 3f5c14b..e356389 100644
--- a/src/Internal/Connection/SocketConnectionFactory.php
+++ b/src/Internal/Connection/SocketConnectionFactory.php
@@ -4,11 +4,14 @@
namespace Thesis\Nats\Internal\Connection;
+use Amp\Socket\Certificate;
+use Amp\Socket\ClientTlsContext;
use Amp\Socket\ConnectContext;
use Amp\Socket\DnsSocketConnector;
use Amp\Socket\SocketConnector;
use Thesis\Nats\Config;
use Thesis\Nats\Exception\ServerIsNotAvailable;
+use Thesis\Nats\TlsConfig;
/**
* @internal
@@ -35,14 +38,18 @@ public static function fromConfig(Config $config): self
return new self($config, $context, new DnsSocketConnector());
}
- public function connect(string $url): Connection
+ public function connect(Server $server): Connection
{
// The credentials are read and a malformed seed is rejected before the socket is opened:
// otherwise the server would be left waiting for CONNECT.
$credentials = Credentials::fromConfig($this->config);
+ // The socket starts unencrypted: the context is applied once the connection is upgraded to TLS,
+ // which happens without TLS options too when the server requires it.
+ $context = $this->context->withTlsContext(self::tlsContext($this->config->tls ?? new TlsConfig(), $server));
+
try {
- $socket = $this->connector->connect($url, $this->context);
+ $socket = $this->connector->connect($server->url, $context);
} catch (\Throwable $e) {
throw new ServerIsNotAvailable($e->getMessage(), previous: $e);
}
@@ -60,4 +67,22 @@ public function connect(string $url): Connection
return $connection;
}
+
+ private static function tlsContext(TlsConfig $config, Server $server): ClientTlsContext
+ {
+ $context = new ClientTlsContext($config->serverName ?? $server->tlsName())
+ ->withCaFile($config->caFile);
+
+ if (!$config->verifyPeer) {
+ $context = $context
+ ->withoutPeerVerification()
+ ->withoutPeerNameVerification();
+ }
+
+ if ($config->certFile !== null) {
+ $context = $context->withCertificate(new Certificate($config->certFile, $config->keyFile, $config->keyPassphrase));
+ }
+
+ return $context;
+ }
}
diff --git a/src/Internal/Connection/Uri.php b/src/Internal/Connection/Uri.php
index 6d02a4e..283d561 100644
--- a/src/Internal/Connection/Uri.php
+++ b/src/Internal/Connection/Uri.php
@@ -16,18 +16,20 @@
private const string DEFAULT_SCHEME = 'nats';
private const string DEFAULT_HOST = '127.0.0.1';
private const int DEFAULT_PORT = 4222;
+ private const string TLS_SCHEME = 'tls';
/** @var list */
- private const array SCHEMES = ['nats', 'tcp'];
+ private const array SCHEMES = ['nats', 'tcp', self::TLS_SCHEME];
/** @var list */
- private const array UNSUPPORTED_SCHEMES = ['tls', 'ws', 'wss'];
+ private const array UNSUPPORTED_SCHEMES = ['ws', 'wss'];
/**
* @param non-empty-list $urls in the `host:port` form, an IPv6 host in brackets
* @param ?non-empty-string $user
* @param ?non-empty-string $password
* @param ?non-empty-string $token
+ * @param bool $tls whether the scheme is `tls`
*/
private function __construct(
public array $urls,
@@ -35,6 +37,7 @@ private function __construct(
public ?string $password,
public ?string $token,
public Query $query,
+ public bool $tls,
) {}
/**
@@ -97,7 +100,7 @@ public static function parse(#[\SensitiveParameter] string $uri): self
[$user, $password, $token] = $credentials ?? [null, null, null];
- return new self($urls, $user, $password, $token, $query);
+ return new self($urls, $user, $password, $token, $query, $scheme === self::TLS_SCHEME);
}
/**
diff --git a/src/TlsConfig.php b/src/TlsConfig.php
new file mode 100644
index 0000000..530e87c
--- /dev/null
+++ b/src/TlsConfig.php
@@ -0,0 +1,47 @@
+expectException(\InvalidArgumentException::class);
@@ -472,4 +512,34 @@ public function testRequestTimeoutMustBePositive(float $timeout): void
$this->expectException(\InvalidArgumentException::class);
new Config(requestTimeout: $timeout);
}
+
+ public function testFromArrayWithTls(): void
+ {
+ self::assertEquals(
+ new Config(tls: new TlsConfig(caFile: '/ca.pem', certFile: '/client.pem', keyFile: '/client.key', keyPassphrase: 'secret', verifyPeer: false, serverName: 'nats.local', handshakeFirst: true)),
+ Config::fromArray(['tls' => [
+ 'ca_file' => '/ca.pem',
+ 'cert_file' => '/client.pem',
+ 'key_file' => '/client.key',
+ 'key_passphrase' => 'secret',
+ 'verify_peer' => false,
+ 'server_name' => 'nats.local',
+ 'handshake_first' => true,
+ ]]),
+ );
+ self::assertEquals(new Config(tls: new TlsConfig()), Config::fromArray(['tls' => []]));
+ self::assertNull(Config::fromArray([])->tls);
+ }
+
+ public function testTlsKeyRequiresCertificate(): void
+ {
+ $this->expectException(\InvalidArgumentException::class);
+ new TlsConfig(keyFile: '/client.key');
+ }
+
+ public function testTlsKeyPassphraseRequiresCertificate(): void
+ {
+ $this->expectException(\InvalidArgumentException::class);
+ new TlsConfig(keyPassphrase: 'secret');
+ }
}
diff --git a/tests/Internal/Connection/FramerTest.php b/tests/Internal/Connection/FramerTest.php
index 9287c8a..c797cda 100644
--- a/tests/Internal/Connection/FramerTest.php
+++ b/tests/Internal/Connection/FramerTest.php
@@ -16,6 +16,7 @@
use Thesis\Nats\Internal\Protocol\Ping;
use Thesis\Nats\Internal\Protocol\Pong;
use Thesis\Nats\Internal\Protocol\Pub;
+use Thesis\Nats\Internal\Protocol\ServerInfo;
use Thesis\Nats\Internal\Protocol\Sub;
#[CoversClass(Framer::class)]
@@ -59,6 +60,52 @@ public function testReadFrame(array $responses, array $frames): void
for ($i = 0; $i < \count($frames); ++$i) {
self::assertEquals($frames[$i], $framer->readFrame());
}
+
+ self::assertNull($framer->readFrame());
+ self::assertNull($framer->readFrame());
+ }
+
+ public function testStartupFrameLeavesWhatCameAlongUnparsed(): void
+ {
+ $socket = $this->createMock(Socket::class);
+ $socket
+ ->expects(self::exactly(2))
+ ->method('read')
+ ->willReturnOnConsecutiveCalls('INFO {"version":', "\"2.12.0\"}\r\nPONG\r\nPI");
+
+ $framer = new Framer($socket);
+
+ self::assertInstanceOf(ServerInfo::class, $framer->readStartupFrame());
+ self::assertTrue($framer->hasUnread());
+ self::assertSame(Pong::Frame, $framer->readFrame());
+ }
+
+ public function testStartupFrameAloneLeavesNothingUnread(): void
+ {
+ $socket = $this->createMock(Socket::class);
+ $socket
+ ->expects(self::once())
+ ->method('read')
+ ->willReturn("INFO {\"version\":\"2.12.0\"}\r\n");
+
+ $framer = new Framer($socket);
+
+ self::assertInstanceOf(ServerInfo::class, $framer->readStartupFrame());
+ self::assertFalse($framer->hasUnread());
+ }
+
+ public function testReadsTheSocketOnlyForTheAskedFrame(): void
+ {
+ $socket = $this->createMock(Socket::class);
+ $socket
+ ->expects(self::once())
+ ->method('read')
+ ->willReturn("INFO {\"version\":\"2.12.0\"}\r\n");
+
+ $framer = new Framer($socket);
+
+ // Nothing reads the socket after the frame, so it can be upgraded to TLS.
+ self::assertInstanceOf(ServerInfo::class, $framer->readFrame());
}
public function testWriteFrame(): void
diff --git a/tests/Internal/Connection/ServerPoolTest.php b/tests/Internal/Connection/ServerPoolTest.php
index 7022aa9..d4ee769 100644
--- a/tests/Internal/Connection/ServerPoolTest.php
+++ b/tests/Internal/Connection/ServerPoolTest.php
@@ -90,4 +90,49 @@ public function testRandomizedPoolKeepsAllServers(): void
self::assertSame($expected, $shuffled);
}
+
+ public function testServerAnnouncedByAddressIsVerifiedAgainstTheNameOfTheAnnouncingOne(): void
+ {
+ $pool = new ServerPool(['nats.example.com:4222'], randomize: false, maxReconnects: null);
+ $pool->discover(['10.0.0.2:4222', '[fd00::3]:4222', 'nats-2.example.com:4222']);
+
+ self::assertSame(
+ ['nats.example.com', 'nats.example.com', 'nats.example.com', 'nats-2.example.com'],
+ array_map(static fn(Server $server): string => $server->tlsName(), $pool->servers()),
+ );
+ }
+
+ public function testServerAnnouncedByAddressIsVerifiedAgainstItsOwnAddressWithoutAName(): void
+ {
+ $pool = new ServerPool(['127.0.0.2:4222'], randomize: false, maxReconnects: null);
+ $pool->discover(['127.0.0.1:4222']);
+
+ self::assertSame(
+ ['127.0.0.2', '127.0.0.1'],
+ array_map(static fn(Server $server): string => $server->tlsName(), $pool->servers()),
+ );
+ }
+
+ public function testInheritedNameIsPassedOnByTheServerKnownByAddress(): void
+ {
+ $pool = new ServerPool(['nats.example.com:4222'], randomize: false, maxReconnects: null);
+ $pool->discover(['10.0.0.2:4222']);
+
+ // The client moves to the server known by address, which announces another one.
+ $pool->use($pool->servers()[1] ?? self::fail('The server is not discovered.'));
+ $pool->discover(['10.0.0.3:4222']);
+
+ self::assertSame(
+ ['10.0.0.2:4222' => 'nats.example.com', 'nats.example.com:4222' => 'nats.example.com', '10.0.0.3:4222' => 'nats.example.com'],
+ array_combine($pool->urls(), array_map(static fn(Server $server): string => $server->tlsName(), $pool->servers())),
+ );
+ }
+
+ public function testServerHost(): void
+ {
+ self::assertSame('nats.example.com', new Server('nats.example.com:4222', implicit: false)->host());
+ self::assertSame('::1', new Server('[::1]:4222', implicit: false)->host());
+ self::assertTrue(new Server('[::1]:4222', implicit: false)->hasIpAddress());
+ self::assertFalse(new Server('nats.example.com:4222', implicit: false)->hasIpAddress());
+ }
}
diff --git a/tests/TlsTest.php b/tests/TlsTest.php
new file mode 100644
index 0000000..a9a7352
--- /dev/null
+++ b/tests/TlsTest.php
@@ -0,0 +1,360 @@
+ */
+ private array $clients = [];
+
+ /** @var list */
+ private array $proxies = [];
+
+ #[\Override]
+ protected function tearDown(): void
+ {
+ foreach ($this->clients as $client) {
+ $client->stop();
+ }
+
+ foreach ($this->proxies as $proxy) {
+ $proxy->kill();
+ }
+
+ parent::tearDown();
+ }
+
+ public function testConnectsOverTls(): void
+ {
+ $name = Id\generateUniqueId();
+ $client = $this->tlsClient(self::env('THESIS_NATS_TLS_DSN') . '?tls_ca_file=' . self::ca() . "&client_name={$name}");
+
+ $this->assertRoundTrip($client);
+ self::assertNotNull($this->tlsVersion($name), 'The connection is not encrypted.');
+ }
+
+ public function testPlainClientStaysPlainWhenTlsIsOnlyOffered(): void
+ {
+ $name = Id\generateUniqueId();
+ $client = $this->tlsClient(str_replace('tls://', 'nats://', self::env('THESIS_NATS_TLS_DSN')) . "?client_name={$name}");
+
+ $this->assertRoundTrip($client);
+ self::assertNull($this->tlsVersion($name));
+ }
+
+ public function testUntrustedServerCertificateIsRefused(): void
+ {
+ // Without the test CA the self-signed certificate is checked against the system authorities.
+ $client = $this->tlsClient(self::env('THESIS_NATS_TLS_DSN'));
+
+ $this->expectException(TlsHandshakeFailed::class);
+ $this->expectExceptionMessageMatches('/certificate verify failed/');
+
+ $client->connect();
+ }
+
+ public function testUnverifiedServerIsAcceptedWithoutVerification(): void
+ {
+ $client = $this->tlsClient(self::env('THESIS_NATS_TLS_DSN') . '?tls_verify=false');
+
+ $this->assertRoundTrip($client);
+ }
+
+ public function testServerCertificateIsVerifiedAgainstTheServerName(): void
+ {
+ // The certificate is issued for the names of the servers, not for their address.
+ $address = $this->address(self::env('THESIS_NATS_TLS_DSN'));
+
+ $mismatched = $this->tlsClientWithConfig(new Config(urls: [$address], tls: new TlsConfig(caFile: self::ca())));
+
+ try {
+ $mismatched->connect();
+ self::fail('The certificate of another name is accepted.');
+ } catch (TlsHandshakeFailed $e) {
+ self::assertStringContainsString('did not match expected name', $e->getMessage());
+ }
+
+ $named = $this->tlsClientWithConfig(new Config(urls: [$address], tls: new TlsConfig(caFile: self::ca(), serverName: 'nats-tls')));
+
+ $this->assertRoundTrip($named);
+ }
+
+ public function testClientRequiringTlsRefusesServerWithoutIt(): void
+ {
+ $client = $this->tlsClientWithConfig(new Config(urls: Config::fromURI(self::env('THESIS_NATS_DSN'))->urls, tls: new TlsConfig()));
+
+ $this->expectException(TlsIsNotAvailable::class);
+
+ $client->connect();
+ }
+
+ public function testServerRequiringTlsGetsItWithoutTheOptions(): void
+ {
+ // The plain uri is upgraded, verifying the certificate as usual: the system authorities do not know the test CA.
+ $client = $this->tlsClient(str_replace('tls://', 'nats://', self::env('THESIS_NATS_MTLS_DSN')));
+
+ $this->expectException(TlsHandshakeFailed::class);
+ $this->expectExceptionMessageMatches('/certificate verify failed/');
+
+ $client->connect();
+ }
+
+ public function testClientCertificate(): void
+ {
+ $client = $this->tlsClient(self::env('THESIS_NATS_MTLS_DSN') . '?' . http_build_query([
+ 'tls_ca_file' => self::ca(),
+ 'tls_cert_file' => self::CERTIFICATES . '/client-cert.pem',
+ 'tls_key_file' => self::CERTIFICATES . '/client-key.pem',
+ ]));
+
+ $this->assertRoundTrip($client);
+ }
+
+ public function testEncryptedClientKey(): void
+ {
+ $client = $this->tlsClientWithConfig(new Config(
+ urls: Config::fromURI(self::env('THESIS_NATS_MTLS_DSN'))->urls,
+ tls: new TlsConfig(
+ caFile: self::ca(),
+ certFile: self::CERTIFICATES . '/client-cert.pem',
+ keyFile: self::CERTIFICATES . '/client-key-encrypted.pem',
+ keyPassphrase: 'Pswd1',
+ ),
+ ));
+
+ $this->assertRoundTrip($client);
+ }
+
+ public function testServerVerifyingClientsRefusesClientWithoutCertificate(): void
+ {
+ $client = $this->tlsClientWithConfig(new Config(
+ urls: Config::fromURI(self::env('THESIS_NATS_MTLS_DSN'))->urls,
+ connectionTimeout: 2,
+ allowReconnect: false,
+ tls: new TlsConfig(caFile: self::ca()),
+ ));
+
+ $this->expectException(ConnectionIsNotAvailable::class);
+ $this->expectExceptionMessageMatches('/client certificate/');
+
+ $client->connect();
+ }
+
+ public function testHandshakeFirst(): void
+ {
+ $client = $this->tlsClient(self::env('THESIS_NATS_TLS_FIRST_DSN') . '?tls_handshake_first=true&tls_ca_file=' . self::ca());
+
+ $this->assertRoundTrip($client);
+ }
+
+ public function testHandshakeFirstFailsWithServerSendingInfoFirst(): void
+ {
+ // The server answers the TLS handshake with its plain INFO.
+ $client = $this->tlsClient(self::env('THESIS_NATS_TLS_DSN') . '?tls_handshake_first=true&tls_ca_file=' . self::ca());
+
+ $this->expectException(TlsHandshakeFailed::class);
+
+ $client->connect();
+ }
+
+ public function testServerExpectingHandshakeFirstDoesNotAnswerTheUsualOrder(): void
+ {
+ $client = $this->tlsClient(self::env('THESIS_NATS_TLS_FIRST_DSN') . '?connection_timeout=1&tls_ca_file=' . self::ca());
+
+ $this->expectException(ServerIsNotAvailable::class);
+
+ $client->connect();
+ }
+
+ public function testPlainDataBeforeTheHandshakeIsRefused(): void
+ {
+ // A man in the middle appends a plain PONG to INFO: taken for the encrypted answer to CONNECT,
+ // it would make the client report a connection the server has not accepted.
+ $upstream = $this->address(self::env('THESIS_NATS_TLS_DSN'));
+ $server = listen('127.0.0.1:0');
+ $address = $server->getAddress()->toString();
+ self::assertNotSame('', $address);
+
+ $future = async(static function () use ($server, $upstream): void {
+ $client = $server->accept() ?? throw new \LogicException('The proxy is closed.');
+ $nats = connect($upstream);
+
+ $client->write(($nats->read() ?? '') . "PONG\r\n");
+
+ $forward = async(static function () use ($client, $nats): void {
+ while (($chunk = $client->read()) !== null) {
+ $nats->write($chunk);
+ }
+
+ $nats->close();
+ });
+ $forward->ignore();
+
+ while (($chunk = $nats->read()) !== null) {
+ $client->write($chunk);
+ }
+
+ $client->close();
+ });
+ $future->ignore();
+
+ $client = $this->tlsClientWithConfig(new Config(
+ urls: [$address],
+ allowReconnect: false,
+ tls: new TlsConfig(caFile: self::ca(), serverName: 'nats-tls'),
+ ));
+
+ try {
+ $client->connect();
+ self::fail('The plain data is accepted.');
+ } catch (TlsHandshakeFailed $e) {
+ self::assertStringContainsString('unexpected plain data', $e->getMessage());
+ } finally {
+ $server->close();
+ }
+ }
+
+ public function testReconnectsOverTls(): void
+ {
+ $proxy = PausableProxy::start($this->address(self::env('THESIS_NATS_TLS_DSN')));
+ $this->proxies[] = $proxy;
+
+ $client = $this->tlsClientWithConfig(new Config(
+ urls: [$proxy->address],
+ reconnectWait: 0.1,
+ tls: new TlsConfig(caFile: self::ca(), serverName: 'nats-tls'),
+ ));
+
+ /** @var DeferredFuture $reconnected */
+ $reconnected = new DeferredFuture();
+ $client->onReconnect(static fn() => $reconnected->complete());
+
+ $subject = Id\generateUniqueId();
+ $deliveries = $client->subscribeIterator($subject);
+ $client->ping();
+
+ $proxy->disconnect();
+ $reconnected->getFuture()->await(new TimeoutCancellation(5));
+
+ // The subscription is restored on the new TLS connection.
+ $client->publish($subject, new Message('after'));
+
+ foreach ($deliveries as $delivery) {
+ self::assertSame('after', $delivery->message->payload);
+ $deliveries->stop();
+ }
+ }
+
+ private function assertRoundTrip(Client $client): void
+ {
+ $subject = Id\generateUniqueId();
+ $deliveries = $client->subscribeIterator($subject);
+ $client->publish($subject, new Message('secret'));
+
+ foreach ($deliveries as $delivery) {
+ self::assertSame('secret', $delivery->message->payload);
+ $deliveries->stop();
+ }
+ }
+
+ /**
+ * @param non-empty-string $uri
+ */
+ private function tlsClient(string $uri): Client
+ {
+ return $this->tlsClientWithConfig(Config::fromURI($uri));
+ }
+
+ private function tlsClientWithConfig(Config $config): Client
+ {
+ $client = new Client($config);
+ $this->clients[] = $client;
+
+ return $client;
+ }
+
+ /**
+ * @param non-empty-string $dsn
+ * @return non-empty-string the `ip:port` of the server
+ */
+ private function address(string $dsn): string
+ {
+ $url = Config::fromURI($dsn)->urls[0];
+ $colon = (int) strrpos($url, ':');
+
+ $address = gethostbyname(substr($url, 0, $colon)) . substr($url, $colon);
+ self::assertNotSame('', $address);
+
+ return $address;
+ }
+
+ /**
+ * @param non-empty-string $name
+ * @return ?non-empty-string the TLS version of the client connection to nats-tls, null for a plain one
+ */
+ private function tlsVersion(string $name): ?string
+ {
+ $connz = file_get_contents(self::env('THESIS_NATS_TLS_MONITORING_URL') . '/connz?limit=1024');
+ self::assertIsString($connz);
+
+ /** @var array{connections?: list} $connz */
+ $connz = json_decode($connz, true, flags: JSON_THROW_ON_ERROR);
+
+ foreach ($connz['connections'] ?? [] as $connection) {
+ if (($connection['name'] ?? null) === $name) {
+ return $connection['tls_version'] ?? null;
+ }
+ }
+
+ self::fail("The client {$name} is not connected.");
+ }
+
+ /**
+ * @return non-empty-string
+ */
+ private static function ca(): string
+ {
+ return self::CERTIFICATES . '/ca.pem';
+ }
+
+ /**
+ * @param non-empty-string $name
+ * @return non-empty-string
+ */
+ private static function env(string $name): string
+ {
+ $value = getenv($name);
+ if (!\is_string($value) || $value === '') {
+ self::markTestSkipped("{$name} must be set.");
+ }
+
+ return $value;
+ }
+}