diff --git a/README.md b/README.md
index 4e8a85d..489e6c6 100644
--- a/README.md
+++ b/README.md
@@ -5,6 +5,8 @@ Pure non-blocking (fiber based) strictly typed full-featured PHP driver for NATS
## Features
- [NATS Core](https://docs.nats.io/nats-concepts/core-nats)
- [Connection](#connection)
+ - [Authentication](#authentication)
+ - [Connect and ping](#connect-and-ping)
- [Publish-Subscribe](#pub-sub)
- [Queues](#queues)
- [Request-Reply](#request-reply)
@@ -65,7 +67,8 @@ The library implements the full functionality of NATS Core, including pub-sub, q
`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 order until one accepts the connection;
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`, `jwt`, `nkey`, `client_name`:
+e.g. `connection_timeout` (seconds, fractions allowed), `request_timeout`, `verbose`, `no_responders`, `ping`, `token`, `jwt`, `nkey`, `credentials_file`, `jwt_file`, `nkey_file`, `client_name`.
+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
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.
+
+```php
+connect(new TimeoutCancellation(5));
+} catch (Nats\Exception\AuthorizationViolation $e) {
+ exit('Wrong credentials: ' . $e->getMessage());
+}
+
+$nc->subscribe('foo.>', static function (Nats\Delivery $delivery): void {
+ dump($delivery->message->payload);
+});
+
+$rtt = $nc->ping(); // The subscription is active on the server now.
+dump("Round trip: {$rtt}s");
+```
+
#### Pub-Sub
```php
diff --git a/compose.yaml b/compose.yaml
index f7ccaec..183e4d3 100644
--- a/compose.yaml
+++ b/compose.yaml
@@ -25,5 +25,10 @@ services:
volumes:
- ./docker/nats/jwt-server.conf:/etc/jwt-server.conf
+ # Token authentication: nats-server refuses a token next to the users of accounts, so it runs on its own.
+ nats-token:
+ image: nats
+ command: --name nats-token -p 4222 --auth T0k3n
+
nats-cli:
image: bitnamilegacy/natscli:latest
diff --git a/docker/nats/server.conf b/docker/nats/server.conf
index 7f33440..25c14cc 100644
--- a/docker/nats/server.conf
+++ b/docker/nats/server.conf
@@ -17,6 +17,8 @@ accounts: {
subscribe: ["allowed.>", "_INBOX.>"]
}
},
+ # Used by the tests of the uri credentials: a user without a password (nats://nopass:@host), not a token.
+ { user: nopass },
# Used by the tests of the NKey authentication, the seed is in tests/NkeyAuthTest.php.
{ nkey: UAANT3HVY2YJTAZ64BOYWU36YUE77A26VOBWQQTLFUYIUHMJBZCYXCGW }
]
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index deeef1f..116b749 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -13,6 +13,7 @@
>
+
diff --git a/src/Client.php b/src/Client.php
index 01a54c5..fa39b48 100644
--- a/src/Client.php
+++ b/src/Client.php
@@ -86,6 +86,30 @@ public static function default(): self
return new self(Config::default());
}
+ /**
+ * Connects to the server unless the client is already connected. Every call that needs the connection
+ * establishes it on demand, so calling this is optional: it makes network and authentication errors
+ * surface at startup rather than from the first publish or subscribe.
+ *
+ * @throws NatsException
+ */
+ public function connect(?Cancellation $cancellation = null): void
+ {
+ $this->connection($cancellation);
+ }
+
+ /**
+ * Sends PING and waits for the server to answer with PONG, connecting first if needed. Once it returns,
+ * the server has processed everything this client sent before, e.g. the subscriptions are active.
+ *
+ * @return float the round-trip time in seconds
+ * @throws NatsException
+ */
+ public function ping(?Cancellation $cancellation = null): float
+ {
+ return $this->connection($cancellation)->ping($cancellation);
+ }
+
/**
* @param ?non-empty-string $domain
* @throws NatsException
diff --git a/src/Config.php b/src/Config.php
index 5750c70..e51ed37 100644
--- a/src/Config.php
+++ b/src/Config.php
@@ -36,6 +36,11 @@
* @param ?non-empty-string $jetStreamDomain
* @param non-empty-string $clientName
* @param ?float $requestTimeout in seconds, the default timeout of {@see Client::request()} and {@see Client::requestMany()}, null for none
+ * @param ?non-empty-string $token the authorization token, exclusive with a user and a password
+ * @param ?non-empty-string $credentialsFile the path to a user credentials file (`.creds`) holding both the JWT and the NKey seed,
+ * read on every connection attempt; exclusive with the other JWT and NKey options
+ * @param ?non-empty-string $jwtFile the path to a file holding the user JWT, bare or decorated, read on every connection attempt; exclusive with $jwt
+ * @param ?non-empty-string $nkeyFile the path to a file holding the NKey user seed, bare or decorated, read on every connection attempt; exclusive with $nkey
* @throws \InvalidArgumentException
*/
public function __construct(
@@ -58,9 +63,31 @@ public function __construct(
public ?string $jetStreamDomain = null,
public string $clientName = self::DEFAULT_CLIENT_NAME,
public ?float $requestTimeout = null,
+ #[\SensitiveParameter]
+ public ?string $token = null,
+ public ?string $credentialsFile = null,
+ public ?string $jwtFile = null,
+ public ?string $nkeyFile = null,
) {
Validate::duration($connectionTimeout, 'connection timeout');
+ // nats-server itself refuses to have a token next to users, so both of them here are a mistake.
+ if ($token !== null && ($user !== null || $password !== null)) {
+ throw new \InvalidArgumentException('A token cannot be combined with a user and a password.');
+ }
+
+ if ($credentialsFile !== null && ($jwt !== null || $jwtFile !== null || $nkey !== null || $nkeyFile !== null)) {
+ throw new \InvalidArgumentException('A credentials file already holds the JWT and the NKey seed: it cannot be combined with the other JWT and NKey options.');
+ }
+
+ if ($jwt !== null && $jwtFile !== null) {
+ throw new \InvalidArgumentException('Only one of the JWT and the JWT file can be set.');
+ }
+
+ if ($nkey !== null && $nkeyFile !== null) {
+ throw new \InvalidArgumentException('Only one of the NKey seed and the NKey file can be set.');
+ }
+
if ($requestTimeout !== null) {
Validate::duration($requestTimeout, 'request timeout');
}
@@ -102,6 +129,11 @@ public static function fromURI(#[\SensitiveParameter] string $uri): self
jetStreamDomain: $query->jetStreamDomain,
clientName: $query->clientName ?? self::DEFAULT_CLIENT_NAME,
requestTimeout: $query->requestTimeout,
+ // nats://token@host, as in nats.go; the token option takes precedence.
+ token: $query->token ?? $parsed->token,
+ credentialsFile: $query->credentialsFile,
+ jwtFile: $query->jwtFile,
+ nkeyFile: $query->nkeyFile,
);
}
@@ -122,6 +154,10 @@ public static function fromURI(#[\SensitiveParameter] string $uri): self
* jetstream_domain?: non-empty-string,
* client_name?: non-empty-string,
* request_timeout?: float,
+ * token?: non-empty-string,
+ * credentials_file?: non-empty-string,
+ * jwt_file?: non-empty-string,
+ * nkey_file?: non-empty-string,
* } $options
* @throws \InvalidArgumentException
*/
@@ -143,6 +179,10 @@ public static function fromArray(#[\SensitiveParameter] array $options): self
jetStreamDomain: $options['jetstream_domain'] ?? null,
clientName: $options['client_name'] ?? self::DEFAULT_CLIENT_NAME,
requestTimeout: $options['request_timeout'] ?? null,
+ token: $options['token'] ?? null,
+ credentialsFile: $options['credentials_file'] ?? null,
+ jwtFile: $options['jwt_file'] ?? null,
+ nkeyFile: $options['nkey_file'] ?? null,
);
}
}
diff --git a/src/Exception/InvalidCredentials.php b/src/Exception/InvalidCredentials.php
new file mode 100644
index 0000000..06b8039
--- /dev/null
+++ b/src/Exception/InvalidCredentials.php
@@ -0,0 +1,14 @@
+credentialsFile !== null) {
+ $contents = self::read($config->credentialsFile);
+
+ return new self(
+ jwt: self::jwt($contents, $config->credentialsFile),
+ keypair: KeyPair::fromSeed(self::seed($contents, $config->credentialsFile)),
+ );
+ }
+
+ $jwt = $config->jwtFile !== null ? self::jwt(self::read($config->jwtFile), $config->jwtFile) : $config->jwt;
+
+ $seed = $config->nkeyFile !== null ? self::seed(self::read($config->nkeyFile), $config->nkeyFile) : $config->nkey;
+
+ return new self(
+ jwt: $jwt,
+ keypair: $seed !== null ? KeyPair::fromSeed($seed) : null,
+ );
+ }
+
+ /**
+ * @param non-empty-string $path
+ * @throws InvalidCredentials
+ */
+ private static function read(string $path): string
+ {
+ // The files are a few hundred bytes: a blocking read is cheaper than a filesystem driver.
+ // The last error is cleared first, so that an earlier unrelated one is not reported as the reason.
+ error_clear_last();
+ $contents = @file_get_contents($path);
+
+ if ($contents === false) {
+ throw new InvalidCredentials(\sprintf(
+ "The credentials file '%s' cannot be read: %s.",
+ $path,
+ error_get_last()['message'] ?? 'unknown error',
+ ));
+ }
+
+ return $contents;
+ }
+
+ /**
+ * @param non-empty-string $path
+ * @return non-empty-string the first decorated block, or the whole file if it has none
+ * @throws InvalidCredentials
+ */
+ private static function jwt(#[\SensitiveParameter] string $contents, string $path): string
+ {
+ $jwt = self::blocks($contents)[0] ?? trim($contents);
+
+ if ($jwt === '') {
+ throw new InvalidCredentials("The credentials file '{$path}' holds no user JWT.");
+ }
+
+ return $jwt;
+ }
+
+ /**
+ * @param non-empty-string $path
+ * @return non-empty-string the second decorated block, or the first line that looks like a seed
+ * @throws InvalidCredentials
+ */
+ private static function seed(#[\SensitiveParameter] string $contents, string $path): string
+ {
+ $blocks = self::blocks($contents);
+
+ // A creds file holds the JWT first and the seed second, a seed file holds only the seed.
+ if (\count($blocks) > 1) {
+ return $blocks[1];
+ }
+
+ foreach (explode("\n", $contents) as $line) {
+ $line = trim($line);
+
+ // Operator, account and user seeds, as nats-io/jwt looks for them: KeyPair then accepts the user ones only.
+ if (preg_match('/^S[OAU]/', $line) === 1) {
+ return $line;
+ }
+ }
+
+ throw new InvalidCredentials("The credentials file '{$path}' holds no NKey seed.");
+ }
+
+ /**
+ * @return list
+ */
+ private static function blocks(#[\SensitiveParameter] string $contents): array
+ {
+ preg_match_all(self::DECORATED_BLOCK, $contents, $matches);
+
+ /** @var list */
+ return $matches[1];
+ }
+}
diff --git a/src/Internal/Connection/Query.php b/src/Internal/Connection/Query.php
index 82da1d4..88b0e81 100644
--- a/src/Internal/Connection/Query.php
+++ b/src/Internal/Connection/Query.php
@@ -21,6 +21,10 @@
* @param ?non-empty-string $clientName
* @param ?non-empty-string $jwt
* @param ?non-empty-string $nkey
+ * @param ?non-empty-string $token
+ * @param ?non-empty-string $credentialsFile
+ * @param ?non-empty-string $jwtFile
+ * @param ?non-empty-string $nkeyFile
*/
private function __construct(
public ?bool $verbose = null,
@@ -37,6 +41,11 @@ private function __construct(
public ?string $jwt = null,
#[\SensitiveParameter]
public ?string $nkey = null,
+ #[\SensitiveParameter]
+ public ?string $token = null,
+ public ?string $credentialsFile = null,
+ public ?string $jwtFile = null,
+ public ?string $nkeyFile = null,
) {}
public static function parse(#[\SensitiveParameter] string $query): self
@@ -56,6 +65,10 @@ public static function parse(#[\SensitiveParameter] string $query): self
clientName: self::string($options, 'client_name'),
jwt: self::string($options, 'jwt'),
nkey: self::string($options, 'nkey'),
+ token: self::string($options, 'token'),
+ credentialsFile: self::string($options, 'credentials_file'),
+ jwtFile: self::string($options, 'jwt_file'),
+ nkeyFile: self::string($options, 'nkey_file'),
);
}
diff --git a/src/Internal/Connection/SocketConnection.php b/src/Internal/Connection/SocketConnection.php
index 98480ff..b7bef55 100644
--- a/src/Internal/Connection/SocketConnection.php
+++ b/src/Internal/Connection/SocketConnection.php
@@ -17,8 +17,8 @@
use Thesis\Nats\Exception\ConnectionWasClosed;
use Thesis\Nats\Exception\ServerIsNotAvailable;
use Thesis\Nats\Internal\Hooks;
-use Thesis\Nats\Internal\Nkey\KeyPair;
use Thesis\Nats\Internal\Protocol;
+use function Amp\async;
use function Thesis\Package\version;
/**
@@ -48,6 +48,14 @@ final class SocketConnection implements Connection
*/
private ?DeferredFuture $handshake = null;
+ /**
+ * One entry per PING written after the handshake, in the order the server answers them with PONG:
+ * the deferred of a {@see ping()} that waits for its PONG, null for a keep-alive PING nobody waits for.
+ *
+ * @var \SplQueue>
+ */
+ private readonly \SplQueue $pongs;
+
/**
* Completed once the reader stops, with the error the server sent right before closing the connection, if any.
*
@@ -56,13 +64,13 @@ final class SocketConnection implements Connection
private readonly DeferredFuture $termination;
/**
- * @param ?KeyPair $keypair the NKey of the user: the server gets its public key and the nonce signed with the secret one,
- * the seed itself never leaves the client
+ * @param Credentials $credentials the JWT and the NKey of the user: the server gets the public key and the nonce
+ * signed with the secret one, the seed itself never leaves the client
*/
public function __construct(
private readonly Config $config,
private readonly Socket $socket,
- private readonly ?KeyPair $keypair = null,
+ private readonly Credentials $credentials,
) {
$this->framer = new Framer($this->socket);
$this->hooks = new Hooks\ConcurrentProvider();
@@ -72,6 +80,10 @@ public function __construct(
$queue = new \SplQueue();
$this->queue = $queue;
+ /** @var \SplQueue> $pongs */
+ $pongs = new \SplQueue();
+ $this->pongs = $pongs;
+
/** @var DeferredFuture\Throwable> $termination */
$termination = new DeferredFuture();
$this->termination = $termination;
@@ -107,6 +119,13 @@ public function execute(Protocol\Frame|array $frames, ?Cancellation $cancellatio
/** @var list> $acks */
$acks = [];
+ foreach ($frames as $frame) {
+ if ($frame instanceof Protocol\Ping) {
+ // Its PONG must not be taken for the one a ping() call waits for.
+ $this->pongs->push(null);
+ }
+ }
+
if ($this->config->verbose) {
foreach ($frames as $frame) {
if (self::isAcknowledged($frame)) {
@@ -150,6 +169,34 @@ public function execute(Protocol\Frame|array $frames, ?Cancellation $cancellatio
}
}
+ public function ping(?Cancellation $cancellation = null): float
+ {
+ /** @var DeferredFuture $pong */
+ $pong = new DeferredFuture();
+ // A cancelled ping leaves its deferred in the queue for its PONG, which may never come once the connection is closed.
+ $pong->getFuture()->ignore();
+ $this->pongs->push($pong);
+
+ $start = hrtime(true);
+
+ // The write waits for room in the socket buffer, which a stalled peer may never free: it runs on its own,
+ // so that the cancellation bounds it too. A cancelled write still completes in the background,
+ // keeping its PING in line with the deferred above, or fails together with the connection.
+ $framer = $this->framer;
+ $write = async(static fn() => $framer->writeFrame(Protocol\Ping::Frame));
+ $write->ignore();
+
+ try {
+ $write->await($cancellation);
+ } catch (StreamException $e) {
+ throw $this->closedWhileWriting($e);
+ }
+
+ $pong->getFuture()->await($cancellation);
+
+ return (hrtime(true) - $start) / 1e9;
+ }
+
/**
* Reads INFO, sends CONNECT and waits for the server to answer the PING that follows it.
*
@@ -174,6 +221,7 @@ private function handshake(Cancellation $cancellation): void
/** @var DeferredFuture $handshake */
$handshake = new DeferredFuture();
$this->handshake = $handshake;
+ $keypair = $this->credentials->keypair;
try {
$this->connect(new Protocol\Connect(
@@ -182,14 +230,15 @@ private function handshake(Cancellation $cancellation): void
tlsRequired: false,
name: $this->config->clientName,
version: version(self::PACKAGE_NAME),
+ authToken: $this->config->token,
user: $this->config->user,
pass: $this->config->password,
- sig: $this->keypair !== null && $frame->nonce !== null && $frame->nonce !== '' ? $this->keypair->sign($frame->nonce) : null,
- jwt: $this->config->jwt,
+ sig: $keypair !== null && $frame->nonce !== null && $frame->nonce !== '' ? $keypair->sign($frame->nonce) : null,
+ jwt: $this->credentials->jwt,
// The server rejects no_responders without headers: the no responders status is a header.
noResponders: $this->config->noResponders && $this->info->allowHeaders,
headers: $this->info->allowHeaders,
- nkey: $this->keypair?->publicKey,
+ nkey: $keypair?->publicKey,
), $cancellation);
// In non-verbose mode the server does not acknowledge CONNECT: it stays silent on success and answers
@@ -235,6 +284,7 @@ public function close(): void
$this->state = ConnectionState::GracefulClosed;
$this->socket->close();
self::failPending($this->queue, new ConnectionWasClosed());
+ self::failPongs($this->pongs, new ConnectionWasClosed());
$this->hooks->dispatch(Hooks\ConnectionClosed::Event);
}
@@ -242,6 +292,7 @@ private function run(): void
{
$framer = $this->framer;
$queue = $this->queue;
+ $pongs = $this->pongs;
$hooks = $this->hooks;
$socket = $this->socket;
$termination = $this->termination;
@@ -251,6 +302,7 @@ private function run(): void
EventLoop::queue(static function () use (
$framer,
$queue,
+ $pongs,
$hooks,
$socket,
$termination,
@@ -283,9 +335,13 @@ private function run(): void
continue;
}
- if ($frame instanceof Protocol\Pong && $handshake !== null) {
- $handshake->complete();
- $handshake = null;
+ if ($frame instanceof Protocol\Pong) {
+ if ($handshake !== null) {
+ $handshake->complete();
+ $handshake = null;
+ } elseif (!$pongs->isEmpty()) {
+ $pongs->shift()?->complete();
+ }
}
$event = match (true) {
@@ -313,6 +369,7 @@ private function run(): void
} finally {
// Nothing acknowledges the commands still awaiting +OK any more.
self::failPending($queue, $error ?? new ConnectionWasClosed());
+ self::failPongs($pongs, $error ?? new ConnectionWasClosed());
if ($state !== ConnectionState::GracefulClosed) { // @phpstan-ignore notIdentical.alwaysTrue
$state = ConnectionState::Closed;
@@ -380,6 +437,16 @@ private static function isAcknowledged(Protocol\Frame $frame): bool
return !$frame instanceof Protocol\Ping && !$frame instanceof Protocol\Pong;
}
+ /**
+ * @param \SplQueue> $pongs
+ */
+ private static function failPongs(\SplQueue $pongs, \Throwable $e): void
+ {
+ while (!$pongs->isEmpty()) {
+ $pongs->shift()?->error($e);
+ }
+ }
+
/**
* @param \SplQueue> $queue
*/
diff --git a/src/Internal/Connection/SocketConnectionFactory.php b/src/Internal/Connection/SocketConnectionFactory.php
index 7844049..87b0e12 100644
--- a/src/Internal/Connection/SocketConnectionFactory.php
+++ b/src/Internal/Connection/SocketConnectionFactory.php
@@ -10,7 +10,6 @@
use Amp\Socket\SocketConnector;
use Thesis\Nats\Config;
use Thesis\Nats\Exception\ServerIsNotAvailable;
-use Thesis\Nats\Internal\Nkey\KeyPair;
/**
* @internal
@@ -39,13 +38,14 @@ public static function fromConfig(Config $config): self
public function connect(): Connection
{
- // A malformed seed is rejected before the socket is opened: otherwise the server would be left waiting for CONNECT.
- $keypair = $this->config->nkey !== null ? KeyPair::fromSeed($this->config->nkey) : null;
+ // 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);
$connection = new SocketConnection(
$this->config,
$this->createSocket(),
- $keypair,
+ $credentials,
);
try {
diff --git a/src/Internal/Connection/Uri.php b/src/Internal/Connection/Uri.php
index b5b7040..6d02a4e 100644
--- a/src/Internal/Connection/Uri.php
+++ b/src/Internal/Connection/Uri.php
@@ -7,6 +7,7 @@
/**
* Parses `[scheme://][user[:password]@]host[:port][,host[:port]...][/][?query]`.
* Every host may repeat the scheme and the credentials, as nats.go server lists do (`nats://u:p@a:4222,nats://u:p@b:4222`).
+ * The userinfo without a colon is a token, as in nats.go (`nats://token@host`); `user:@host` is a user with an empty password.
*
* @internal
*/
@@ -26,11 +27,13 @@
* @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
*/
private function __construct(
public array $urls,
public ?string $user,
public ?string $password,
+ public ?string $token,
public Query $query,
) {}
@@ -92,9 +95,9 @@ public static function parse(#[\SensitiveParameter] string $uri): self
$urls[] = self::server($server);
}
- [$user, $password] = $credentials ?? [null, null];
+ [$user, $password, $token] = $credentials ?? [null, null, null];
- return new self($urls, $user, $password, $query);
+ return new self($urls, $user, $password, $token, $query);
}
/**
@@ -122,10 +125,17 @@ private static function scheme(string $uri): ?array
}
/**
- * @return array{?non-empty-string, ?non-empty-string}
+ * @return array{?non-empty-string, ?non-empty-string, ?non-empty-string} the user, the password and the token
*/
private static function credentials(#[\SensitiveParameter] string $userinfo): array
{
+ // Only the presence of the colon tells a token from a user: an empty password decodes to nothing as well.
+ if (!str_contains($userinfo, ':')) {
+ $token = rawurldecode($userinfo);
+
+ return [null, null, $token !== '' ? $token : null];
+ }
+
[$user, $password] = self::split($userinfo, ':');
$user = rawurldecode($user);
$password = rawurldecode($password);
@@ -133,6 +143,7 @@ private static function credentials(#[\SensitiveParameter] string $userinfo): ar
return [
$user !== '' ? $user : null,
$password !== '' ? $password : null,
+ null,
];
}
diff --git a/tests/AuthenticationTest.php b/tests/AuthenticationTest.php
new file mode 100644
index 0000000..42c0ff1
--- /dev/null
+++ b/tests/AuthenticationTest.php
@@ -0,0 +1,259 @@
+ */
+ private array $files = [];
+
+ #[\Override]
+ protected function tearDown(): void
+ {
+ parent::tearDown();
+
+ foreach ($this->files as $file) {
+ @unlink($file);
+ }
+ }
+
+ public function testConnectsWithTokenAsUserOfUri(): void
+ {
+ // nats://token@host: a user without a password is a token, as in nats.go.
+ $config = Config::fromURI($this->tokenDsn());
+
+ self::assertNotNull($config->token);
+ self::assertNull($config->user);
+
+ self::assertPublishesAndReceives($this->clientWithConfig($config));
+ }
+
+ public function testConnectsWithTokenOption(): void
+ {
+ $token = Config::fromURI($this->tokenDsn())->token;
+ self::assertNotNull($token);
+
+ $config = Config::fromURI("nats://{$this->tokenAddress()}?token={$token}");
+ self::assertSame($token, $config->token);
+
+ self::assertPublishesAndReceives($this->clientWithConfig($config));
+ }
+
+ public function testUserWithEmptyPasswordIsNotToken(): void
+ {
+ // The colon makes it a user with an empty password, as the server knows it, not the token "nopass".
+ $config = Config::fromURI("nats://nopass:@{$this->natsAddress()}");
+
+ self::assertSame('nopass', $config->user);
+ self::assertNull($config->token);
+
+ self::assertPublishesAndReceives($this->clientWithConfig($config));
+ }
+
+ public function testWrongTokenIsRejectedOnConnect(): void
+ {
+ $client = $this->clientWithConfig(new Config(urls: [$this->tokenAddress()], token: 'wrong'));
+
+ self::expectException(AuthorizationViolation::class);
+
+ $client->connect(new TimeoutCancellation(5));
+ }
+
+ #[RequiresPhpExtension('sodium')]
+ public function testConnectsWithCredentialsFile(): void
+ {
+ [$jwt, $seed] = $this->jwtCredentials();
+
+ $client = $this->clientWithConfig(new Config(
+ urls: $this->jwtConfig()->urls,
+ credentialsFile: $this->file(self::decoratedCredentials($jwt, $seed)),
+ ));
+
+ self::assertSame(-1, $client->jetStream()->accountInfo()->limits->maxMemory);
+ }
+
+ #[RequiresPhpExtension('sodium')]
+ public function testConnectsWithJwtAndNkeyFiles(): void
+ {
+ [$jwt, $seed] = $this->jwtCredentials();
+
+ // A bare JWT and a seed decorated as nsc writes it, both are accepted.
+ $client = $this->clientWithConfig(Config::fromURI(\sprintf(
+ 'nats://%s?jwt_file=%s&nkey_file=%s',
+ $this->jwtConfig()->urls[0],
+ rawurlencode($this->file("{$jwt}\n")),
+ rawurlencode($this->file("-----BEGIN USER NKEY SEED-----\n{$seed}\n------END USER NKEY SEED------\n")),
+ )));
+
+ self::assertSame(-1, $client->jetStream()->accountInfo()->limits->maxMemory);
+ }
+
+ #[RequiresPhpExtension('sodium')]
+ public function testCredentialsFileIsReadOnEveryConnectionAttempt(): void
+ {
+ [$jwt, $seed] = $this->jwtCredentials();
+ $file = $this->file(self::decoratedCredentials($jwt, self::UNKNOWN_SEED));
+
+ $client = $this->clientWithConfig(new Config(urls: $this->jwtConfig()->urls, credentialsFile: $file));
+
+ try {
+ $client->connect(new TimeoutCancellation(5));
+ self::fail('The seed does not match the JWT, connect must fail.');
+ } catch (AuthorizationViolation) {
+ }
+
+ // The rotated credentials are picked up by the next attempt of the same client.
+ file_put_contents($file, self::decoratedCredentials($jwt, $seed));
+
+ $client->connect(new TimeoutCancellation(5));
+ self::assertSame(-1, $client->jetStream()->accountInfo()->limits->maxMemory);
+ }
+
+ public function testMissingCredentialsFileFailsBeforeConnecting(): void
+ {
+ $server = listen('127.0.0.1:0');
+ $address = $server->getAddress()->toString();
+ \assert($address !== '');
+
+ $accepted = async($server->accept(...));
+
+ $client = $this->clientWithConfig(new Config(
+ urls: [$address],
+ credentialsFile: \sprintf('%s/%s.creds', sys_get_temp_dir(), Id\generateUniqueId()),
+ ));
+
+ try {
+ $client->connect(new TimeoutCancellation(5));
+ self::fail('The credentials file does not exist, connect must fail.');
+ } catch (InvalidCredentials $e) {
+ self::assertStringContainsString('cannot be read', $e->getMessage());
+ }
+
+ $server->close();
+ // Nothing has been connected to the server.
+ self::assertNull($accepted->await(new TimeoutCancellation(1)));
+ }
+
+ public function testCredentialsFileWithoutSeedIsRejected(): void
+ {
+ [$jwt] = $this->jwtCredentials();
+
+ $client = $this->clientWithConfig(new Config(
+ urls: $this->jwtConfig()->urls,
+ credentialsFile: $this->file("-----BEGIN NATS USER JWT-----\n{$jwt}\n------END NATS USER JWT------\n"),
+ ));
+
+ self::expectException(InvalidCredentials::class);
+ self::expectExceptionMessage('holds no NKey seed');
+
+ $client->connect(new TimeoutCancellation(5));
+ }
+
+ private static function assertPublishesAndReceives(Client $client): void
+ {
+ $client->connect(new TimeoutCancellation(5));
+
+ $subject = Id\generateUniqueId();
+ $deliveries = $client->subscribeIterator($subject);
+ $client->publish($subject, new Message('ok'));
+
+ foreach ($deliveries as $delivery) {
+ self::assertSame('ok', $delivery->message->payload);
+
+ $deliveries->stop();
+ }
+ }
+
+ /**
+ * @param non-empty-string $jwt
+ * @param non-empty-string $seed
+ * @return non-empty-string a user credentials file in the format of nsc
+ */
+ private static function decoratedCredentials(string $jwt, string $seed): string
+ {
+ return <<jwtConfig();
+
+ return [
+ $config->jwt ?? self::fail('The JWT dsn has no jwt.'),
+ $config->nkey ?? self::fail('The JWT dsn has no nkey.'),
+ ];
+ }
+
+ /**
+ * @return non-empty-string the path of a temporary file with the given contents, removed in tearDown
+ */
+ private function file(string $contents): string
+ {
+ $file = tempnam(sys_get_temp_dir(), 'nats');
+ \assert($file !== false);
+
+ file_put_contents($file, $contents);
+
+ return $this->files[] = $file;
+ }
+
+ /**
+ * @return non-empty-string
+ */
+ private function tokenDsn(): string
+ {
+ $dsn = getenv('THESIS_NATS_TOKEN_DSN');
+ if (!\is_string($dsn) || $dsn === '') {
+ self::markTestSkipped('THESIS_NATS_TOKEN_DSN must be set.');
+ }
+
+ return $dsn;
+ }
+
+ /**
+ * @return non-empty-string
+ */
+ private function tokenAddress(): string
+ {
+ return Config::fromURI($this->tokenDsn())->urls[0];
+ }
+}
diff --git a/tests/ClientTest.php b/tests/ClientTest.php
index 6b0e49f..59209a1 100644
--- a/tests/ClientTest.php
+++ b/tests/ClientTest.php
@@ -11,6 +11,7 @@
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DoesNotPerformAssertions;
use Revolt\EventLoop;
+use Thesis\Nats\Exception\AuthorizationViolation;
use Thesis\Nats\Exception\ConnectionWasClosed;
use Thesis\Nats\Exception\FeatureIsNotSupported;
use Thesis\Nats\Exception\RequestHasNoResponders;
@@ -390,6 +391,146 @@ public function testConnectFailsWhenServerDoesNotAnswerHandshake(): void
}
}
+ public function testConnectEstablishesConnectionWithoutAnyCall(): void
+ {
+ $name = Id\generateUniqueId();
+ $client = $this->clientNamed($name);
+
+ self::assertFalse($this->isConnected($name));
+
+ $client->connect(new TimeoutCancellation(5));
+ self::assertTrue($this->isConnected($name));
+
+ // Connecting again reuses the connection.
+ $client->connect();
+ self::assertTrue($this->isConnected($name));
+ }
+
+ public function testConnectSurfacesAuthenticationErrors(): void
+ {
+ $client = $this->clientWithConfig(new Config(urls: [$this->natsAddress()], user: 'user', password: 'wrong'));
+
+ self::expectException(AuthorizationViolation::class);
+
+ $client->connect(new TimeoutCancellation(5));
+ }
+
+ public function testPingMakesSubscriptionVisibleToOtherClients(): void
+ {
+ $subscriber = $this->client();
+ $publisher = new Client($this->config());
+ $subject = Id\generateUniqueId();
+
+ try {
+ $deliveries = $subscriber->subscribeIterator($subject);
+
+ // SUB is not acknowledged: only the PONG proves the server has processed it.
+ $rtt = $subscriber->ping(new TimeoutCancellation(5));
+ self::assertGreaterThan(0, $rtt);
+
+ $publisher->publish($subject, new Message('ok'));
+
+ foreach ($deliveries as $delivery) {
+ self::assertSame('ok', $delivery->message->payload);
+
+ $deliveries->stop();
+ }
+ } finally {
+ $publisher->stop();
+ }
+ }
+
+ public function testPingCancellationBoundsBlockedWrite(): void
+ {
+ $proxy = PausableProxy::start($this->natsAddress());
+
+ try {
+ $client = $this->clientWithUrls([$proxy->address]);
+ $client->connect(new TimeoutCancellation(5));
+
+ // The proxy stops reading from the client: the socket buffers fill up and the writes queue behind them.
+ $proxy->pause();
+
+ $subject = Id\generateUniqueId();
+ $payload = str_repeat('x', 512 * 1024);
+ $flood = async(static function () use (
+ $client,
+ $subject,
+ $payload,
+ ): void {
+ for ($i = 0; $i < 64; ++$i) {
+ $client->publish($subject, new Message($payload));
+ }
+ });
+ $flood->ignore();
+ delay(0.1);
+
+ $ping = async(static fn() => $client->ping(new TimeoutCancellation(0.05)));
+ delay(0.3);
+
+ // The PING has not been written yet, the cancellation must still end the wait.
+ self::assertTrue($ping->isComplete());
+
+ self::expectException(CancelledException::class);
+ $ping->await();
+ } finally {
+ $proxy->stop();
+ }
+ }
+
+ public function testPingWaitsForItsOwnPong(): void
+ {
+ $server = listen('127.0.0.1:0');
+ $address = $server->getAddress()->toString();
+ \assert($address !== '');
+
+ $peer = async(static function () use ($server): Socket {
+ $peer = $server->accept() ?? self::fail('The client has not connected.');
+ $peer->write("INFO {\"server_id\":\"fake\",\"version\":\"2.12.0\",\"headers\":true,\"max_payload\":1048576}\r\n");
+
+ // CONNECT and the handshake PING.
+ $buffer = '';
+
+ while (!str_contains($buffer, "PING\r\n")) {
+ $buffer .= $peer->read() ?? self::fail('The client has closed the connection.');
+ }
+
+ $peer->write("PONG\r\n");
+
+ return $peer;
+ });
+
+ $client = $this->clientWithConfig(new Config(urls: [$address], connectionTimeout: 5, ping: 300, maxPings: 100));
+ $client->connect(new TimeoutCancellation(5));
+ $peer = $peer->await(new TimeoutCancellation(1));
+
+ try {
+ // The keep-alive PING is sent and left unanswered.
+ delay(0.4);
+
+ $ping = async($client->ping(...));
+ delay(0.05);
+
+ // This PONG answers the keep-alive PING sent earlier, not the one of ping().
+ $peer->write("PONG\r\n");
+ delay(0.05);
+ self::assertFalse($ping->isComplete());
+
+ $peer->write("PONG\r\n");
+ $ping->await(new TimeoutCancellation(1));
+
+ // A ping waiting for its PONG fails once the connection is gone.
+ $ping = async($client->ping(...));
+ delay(0.05);
+ $peer->close();
+
+ self::expectException(ConnectionWasClosed::class);
+ $ping->await(new TimeoutCancellation(1));
+ } finally {
+ $server->close();
+ }
+ }
+
public function testConnectsWithServerListInNatsGoForm(): void
{
// Every server repeats its scheme and credentials, the first one is down and the second has no port, as nats.go accepts it.
diff --git a/tests/ConfigTest.php b/tests/ConfigTest.php
index dc65a59..27517fe 100644
--- a/tests/ConfigTest.php
+++ b/tests/ConfigTest.php
@@ -283,6 +283,36 @@ final class ConfigTest extends TestCase
new Config(urls: ['h1:4222', 'h2:4222'], user: 'user', password: 'p,ass'),
],
)]
+ #[TestWith(
+ [
+ 'nats://s3cr%40t@h1:4222,nats://s3cr%40t@h2',
+ new Config(urls: ['h1:4222', 'h2:4222'], token: 's3cr@t'),
+ ],
+ )]
+ #[TestWith(
+ [
+ 'nats://ignored@127.0.0.1:4222?token=s3cr3t',
+ new Config(token: 's3cr3t'),
+ ],
+ )]
+ #[TestWith(
+ [
+ 'nats://127.0.0.1:4222?credentials_file=%2Fetc%2Fnats%2Fuser.creds',
+ new Config(credentialsFile: '/etc/nats/user.creds'),
+ ],
+ )]
+ #[TestWith(
+ [
+ 'nats://127.0.0.1:4222?jwt_file=/user.jwt&nkey_file=/user.nk&credentials_file=',
+ new Config(jwtFile: '/user.jwt', nkeyFile: '/user.nk'),
+ ],
+ )]
+ #[TestWith(
+ [
+ 'nats://alice:@h1:4222,nats://alice:@h2',
+ new Config(urls: ['h1:4222', 'h2:4222'], user: 'alice'),
+ ],
+ )]
public function testFromURI(string $uri, Config $config): void
{
self::assertEquals($config, Config::fromURI($uri));
@@ -311,6 +341,12 @@ public function testFromURI(string $uri, Config $config): void
#[TestWith(['nats://[::1'])]
#[TestWith(['nats://[::1]4222'])]
#[TestWith(['nats://h1:4222/path'])]
+ #[TestWith(['nats://user:pass@h1:4222?token=s3cr3t'])]
+ #[TestWith(['nats://h1:4222?credentials_file=/user.creds&jwt=x'])]
+ #[TestWith(['nats://h1:4222?credentials_file=/user.creds&nkey_file=/user.nk'])]
+ #[TestWith(['nats://h1:4222?jwt=x&jwt_file=/user.jwt'])]
+ #[TestWith(['nats://h1:4222?nkey=x&nkey_file=/user.nk'])]
+ #[TestWith(['nats://alice@h1:4222,nats://alice:@h2:4222'])]
public function testFromURIRejectsInvalidUri(string $uri): void
{
$this->expectException(\InvalidArgumentException::class);
@@ -366,6 +402,18 @@ public function testFromArrayWithRequestTimeout(): void
self::assertEquals(new Config(requestTimeout: 0.5), Config::fromArray(['request_timeout' => 0.5]));
}
+ public function testFromArrayWithAuthenticationFiles(): void
+ {
+ self::assertEquals(
+ new Config(token: 's3cr3t', jwtFile: '/user.jwt', nkeyFile: '/user.nk'),
+ Config::fromArray(['token' => 's3cr3t', 'jwt_file' => '/user.jwt', 'nkey_file' => '/user.nk']),
+ );
+ self::assertEquals(
+ new Config(credentialsFile: '/user.creds'),
+ Config::fromArray(['credentials_file' => '/user.creds']),
+ );
+ }
+
#[TestWith([0.0])]
#[TestWith([-1.0])]
#[TestWith([INF])]