Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 54 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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
<?php
Expand Down Expand Up @@ -119,6 +121,53 @@ The files are read on every connection attempt, so rotated credentials are picke
or holds no credentials throws `Nats\Exception\InvalidCredentials` before anything is sent to the server, a malformed seed throws `Nats\Exception\InvalidNKey`.
NKey authentication requires `ext-sodium`.

#### TLS

Without TLS options the client still upgrades the connection to TLS when the server requires it, verifying the server certificate against the system authorities, as nats.go does.
`Nats\TlsConfig` (or the `tls://` scheme, or any `tls_*` uri option) requires TLS: a server that does not offer it fails with `Nats\Exception\TlsIsNotAvailable`.
It sets the authorities to trust (`caFile`), the client certificate for the servers that verify the clients (`certFile`, `keyFile`, `keyPassphrase` for an encrypted key),
the name the server certificate is checked against and sent in SNI (`serverName`, the host of the server by default; a server the cluster announces by its IP address is checked against the name of the one that announced it, or against its own address if that one is an address too),
and `handshakeFirst` for the servers configured with `handshake_first`, which expect the TLS handshake before they send INFO. A certificate that does not verify fails with `Nats\Exception\TlsHandshakeFailed`.

```php
<?php

declare(strict_types=1);

require_once __DIR__ . '/vendor/autoload.php';

use Thesis\Nats;

// A server certificate signed by a private authority.
$nc = new Nats\Client(Nats\Config::fromURI('tls://nats.internal:4222?tls_ca_file=/etc/nats/ca.pem'));

// A server that verifies the clients (mutual TLS).
$nc = new Nats\Client(new Nats\Config(
urls: ['nats.internal:4222'],
tls: new Nats\TlsConfig(
caFile: '/etc/nats/ca.pem',
certFile: '/etc/nats/client-cert.pem',
keyFile: '/etc/nats/client-key.pem',
),
));

// A server with handshake_first, reached by its address.
$nc = new Nats\Client(new Nats\Config(
urls: ['10.0.0.5:4222'],
tls: new Nats\TlsConfig(caFile: '/etc/nats/ca.pem', serverName: 'nats.internal', handshakeFirst: true),
));

try {
$nc->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,
Expand Down
23 changes: 23 additions & 0 deletions compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
7 changes: 7 additions & 0 deletions docker/nats/mtls-server.conf
Original file line number Diff line number Diff line change
@@ -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
}
6 changes: 6 additions & 0 deletions docker/nats/tls-first-server.conf
Original file line number Diff line number Diff line change
@@ -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
}
7 changes: 7 additions & 0 deletions docker/nats/tls-server.conf
Original file line number Diff line number Diff line change
@@ -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
11 changes: 11 additions & 0 deletions docker/nats/tls/ca.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
-----BEGIN CERTIFICATE-----
MIIBkjCCATmgAwIBAgIUWqwDDdsF+vBaLPaVhDmZPe8fsucwCgYIKoZIzj0EAwIw
HjEcMBoGA1UEAwwTdGhlc2lzLW5hdHMgdGVzdCBDQTAgFw0yNjExMTExMjU3NDBa
GA8yMTI2MTAxODEyNTc0MFowHjEcMBoGA1UEAwwTdGhlc2lzLW5hdHMgdGVzdCBD
QTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABP2w4IqpFvF43gGdUAn+m0kyu3uH
THluRN1OB3JLUZZrNaZmNnMFP/f7VNK/9LWh1n3zEX1PZqodxaBsuOLcMf6jUzBR
MB0GA1UdDgQWBBROEd2hvIBCMk2kqQ0dT7OfqXIzBDAfBgNVHSMEGDAWgBROEd2h
vIBCMk2kqQ0dT7OfqXIzBDAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0cA
MEQCIBnyizXihXM/Vlg1X53wvtlyKZiJwdrMdpAMMKCLvOGKAiB1N8Tmg+u2WXV8
2gr7UMe1Obzb6K6aOFr6CKsvg0c5VA==
-----END CERTIFICATE-----
11 changes: 11 additions & 0 deletions docker/nats/tls/client-cert.pem
Original file line number Diff line number Diff line change
@@ -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-----
7 changes: 7 additions & 0 deletions docker/nats/tls/client-key-encrypted.pem
Original file line number Diff line number Diff line change
@@ -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-----
5 changes: 5 additions & 0 deletions docker/nats/tls/client-key.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgGJxC2PVy3Cu95y8q
9KexoKhFLWJBtbLCZpnvs5NI10WhRANCAAQuizr6Pt1Q0EDm2oIPoMYPKt7rlFxk
jn9o+g+vKBhwAHGq68c2Pz6lVYaNrwRSLN+XR5gyVpxyhig2SMzDuAcD
-----END PRIVATE KEY-----
12 changes: 12 additions & 0 deletions docker/nats/tls/server-cert.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
-----BEGIN CERTIFICATE-----
MIIBzjCCAXWgAwIBAgIUUY5P6yO/67YPk16xFNcFoU4JxsgwCgYIKoZIzj0EAwIw
HjEcMBoGA1UEAwwTdGhlc2lzLW5hdHMgdGVzdCBDQTAgFw0yNjExMTExMjU3NDBa
GA8yMTI2MTAxODEyNTc0MFowEzERMA8GA1UEAwwIbmF0cy10bHMwWTATBgcqhkjO
PQIBBggqhkjOPQMBBwNCAATgnVIR3JZQI02uAQsWiXsq5qrlxwPWVDLZFrQvqUtP
2lb6ZRGQAn9xtfLNk5G1T2ayXJF+JDdHgcLQhknCoQq2o4GZMIGWMD8GA1UdEQQ4
MDaCCG5hdHMtdGxzggluYXRzLW10bHOCDm5hdHMtdGxzLWZpcnN0gglsb2NhbGhv
c3SHBH8AAAEwEwYDVR0lBAwwCgYIKwYBBQUHAwEwHQYDVR0OBBYEFBstKevXt7AY
qCmwWdKl6mGdd5xXMB8GA1UdIwQYMBaAFE4R3aG8gEIyTaSpDR1Ps5+pcjMEMAoG
CCqGSM49BAMCA0cAMEQCIBfZzVbGZAksZpRdfINdZlsy5JubgsrQk0nOEUP7HPyr
AiAq9d9l6FmrkRQJYQOO0KwXVupHnQjZ3k845tVNY1tXJQ==
-----END CERTIFICATE-----
5 changes: 5 additions & 0 deletions docker/nats/tls/server-key.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgU9vExqXCZepH7dFE
v6ophJ/CXdblitRicDWDUqbOn86hRANCAATgnVIR3JZQI02uAQsWiXsq5qrlxwPW
VDLZFrQvqUtP2lb6ZRGQAn9xtfLNk5G1T2ayXJF+JDdHgcLQhknCoQq2
-----END PRIVATE KEY-----
4 changes: 4 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
<php>
<env name="THESIS_NATS_DSN" value="tcp://user:Pswd1@nats:4222?no_responders=true" />
<env name="THESIS_NATS_CLUSTER_DSN" value="nats://nats-cluster-1:4222,nats://nats-cluster-2:4222" />
<env name="THESIS_NATS_TLS_DSN" value="tls://nats-tls:4222" />
<env name="THESIS_NATS_TLS_MONITORING_URL" value="http://nats-tls:8222" />
<env name="THESIS_NATS_MTLS_DSN" value="tls://nats-mtls:4222" />
<env name="THESIS_NATS_TLS_FIRST_DSN" value="tls://nats-tls-first:4222" />
<env name="THESIS_NATS_TOKEN_DSN" value="nats://T0k3n@nats-token:4222" />
<env name="THESIS_NATS_JWT_DSN" value="tcp://nats-jwt:4222?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJlZDI1NTE5LW5rZXkifQ.eyJqdGkiOiJVT1VSVldRTkpBSUgzSUhBSFRKQ1hOSEFFWTc2RzdXNEtBVlNQRUpZUDNQTTIyWEFDTTJBIiwiaWF0IjoxNzYxMjI0MDE4LCJpc3MiOiJBQlg1TVlTUUpCMlNWUUlXREo2SEZSWkxOM1ZMVzJQRkpOVDNHUDRDTUZHN0xRQ1M1SjM0RUdKSiIsIm5hbWUiOiJ1c2VyX25rZXkiLCJzdWIiOiJVRFBCNlRYV1VRMzNQUkhURjJGSlRQRVJISE43NldIS0VVWURNTEtRWlgyTTZIWUFHUkYySkpTWSIsIm5hdHMiOnsicHViIjp7fSwic3ViIjp7fSwic3VicyI6LTEsImRhdGEiOi0xLCJwYXlsb2FkIjotMSwidHlwZSI6InVzZXIiLCJ2ZXJzaW9uIjoyfX0.4D2PgQMgWzuIhy0LvE0Fy-w84I1AfEdXIb94nrVAkb_s_AdPOoCrQUANsGODLnXb_hel24vo7bATiCUeco1xDQ&amp;nkey=SUADBUTF4FNCHZ7O4BXK35KYAMMDRZFL2DOXCNRGHLQOC5HPJB6TOCTDCQ" />
</php>
Expand Down
31 changes: 31 additions & 0 deletions src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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');

Expand Down Expand Up @@ -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,
);
}

Expand Down Expand Up @@ -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
*/
Expand Down Expand Up @@ -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,
);
}
}
15 changes: 15 additions & 0 deletions src/Exception/TlsHandshakeFailed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Thesis\Nats\Exception;

use Thesis\Nats\NatsException;

/**
* The TLS handshake with the server failed: e.g. its certificate is not trusted or does not match its name,
* or the server requires a client certificate the client does not have.
*
* @api
*/
final class TlsHandshakeFailed extends NatsException {}
14 changes: 14 additions & 0 deletions src/Exception/TlsIsNotAvailable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace Thesis\Nats\Exception;

use Thesis\Nats\NatsException;

/**
* The client requires TLS, but the server does not offer it.
*
* @api
*/
final class TlsIsNotAvailable extends NatsException {}
3 changes: 1 addition & 2 deletions src/Internal/Connection/ConnectionFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,8 @@ interface ConnectionFactory
/**
* Connects to the server and completes the handshake.
*
* @param non-empty-string $url `host:port`
* @throws ServerIsNotAvailable if the server cannot be reached or does not complete the handshake in time
* @throws \Exception
*/
public function connect(string $url): Connection;
public function connect(Server $server): Connection;
}
Loading
Loading