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
71 changes: 70 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
<?php
Expand All @@ -81,6 +84,72 @@ $nc = new Nats\Client(Nats\Config::fromURI('nats://user:p%40ss@nats-1:4222,nats-
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.

```php
<?php

declare(strict_types=1);

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

use Thesis\Nats;

// A user and a password.
$nc = new Nats\Client(Nats\Config::fromURI('nats://user:Pswd1@127.0.0.1:4222'));

// A token: nats://s3cr3t@127.0.0.1:4222 or the token option.
$nc = new Nats\Client(new Nats\Config(token: 's3cr3t'));

// An NKey: the server gets the public key derived from the seed and the nonce signed with it, the seed never leaves the client.
$nc = new Nats\Client(new Nats\Config(nkey: 'SUAD3LTGPJHBFPJMOTGX6OIF6YDL2FZ2IGYQIOFORBGSLGYSF2PJWGWGFU'));

// A user credentials file generated by nsc, holding both the JWT and the NKey seed.
$nc = new Nats\Client(new Nats\Config(credentialsFile: '/etc/nats/user.creds'));

// The JWT and the seed in separate files, bare or decorated as nsc writes them; any of them may be passed inline instead (jwt, nkey).
$nc = new Nats\Client(Nats\Config::fromURI('nats://127.0.0.1:4222?jwt_file=/etc/nats/user.jwt&nkey_file=/etc/nats/user.nk'));
```

The files are read on every connection attempt, so rotated credentials are picked up by the next connection. A file that cannot be read
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`.

#### Connect and ping

The client connects lazily, on the first call that needs the server. Call `connect()` to establish the connection at startup instead,
so that an unavailable server or wrong credentials fail right away rather than on the first publish. `ping()` sends `PING` and waits for `PONG`:
once it returns, the server has processed everything the client sent before (e.g. a subscription is active for the other clients), and it returns the round-trip time in seconds.

```php
<?php

declare(strict_types=1);

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

use Amp\TimeoutCancellation;
use Thesis\Nats;

$nc = new Nats\Client(Nats\Config::fromURI('nats://user:Pswd1@127.0.0.1:4222'));

try {
$nc->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
Expand Down
5 changes: 5 additions & 0 deletions compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 2 additions & 0 deletions docker/nats/server.conf
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
]
Expand Down
1 change: 1 addition & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
>
<php>
<env name="THESIS_NATS_DSN" value="tcp://user:Pswd1@nats:4222?no_responders=true" />
<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
24 changes: 24 additions & 0 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
40 changes: 40 additions & 0 deletions src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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');
}
Expand Down Expand Up @@ -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,
);
}

Expand All @@ -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
*/
Expand All @@ -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,
);
}
}
14 changes: 14 additions & 0 deletions src/Exception/InvalidCredentials.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;

/**
* A credentials, JWT or NKey seed file cannot be read or holds no credentials.
*
* @api
*/
final class InvalidCredentials extends NatsException {}
8 changes: 8 additions & 0 deletions src/Internal/Connection/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ interface Connection
*/
public function execute(Protocol\Frame|array $frames, ?Cancellation $cancellation = null): void;

/**
* Sends PING and waits for its PONG: the server has then processed everything written before it.
*
* @return float the round-trip time in seconds
* @throws NatsException
*/
public function ping(?Cancellation $cancellation = null): float;

public Hooks\Provider $hooks { get; }

/**
Expand Down
Loading
Loading