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
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Call [SkirRPC](https://skir.build/docs/skirrpc) services from Laravel through ge

- Generate typed RPC clients from Skir schemas with the [client generation guide](docs/generating-clients.md).
- Use standard PHP objects, [Laravel Data](docs/laravel-data.md), or [Simple Data Objects](docs/simple-data-objects.md).
- Configure the server URL and endpoint with the [configuration guide](docs/configuration.md).
- Configure the server URL, endpoint, and authentication with the [configuration guide](docs/configuration.md).
- [Handle failures and test without network requests](docs/error-handling-and-testing.md).

## Quick start
Expand Down Expand Up @@ -71,6 +71,16 @@ SKIR_CLIENT_BASE_URL=https://api.example.test
SKIR_CLIENT_ENDPOINT=/api/skir
```

If the server expects a credential, configure it in the same file. For example, to send a shared secret in a custom header:

```dotenv
SKIR_CLIENT_AUTH_TYPE=header
SKIR_CLIENT_AUTH_HEADER=X-Internal-Token
SKIR_CLIENT_AUTH_TOKEN=your-shared-secret
```

Every request then carries `X-Internal-Token: your-shared-secret`. Bearer, basic, and custom authentication are covered in the [configuration guide](docs/configuration.md#authentication).

Call the service through the generated typed client:

```php
Expand Down
9 changes: 9 additions & 0 deletions config/skir-client.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@
'endpoint' => env('SKIR_CLIENT_ENDPOINT', '/'),
'format' => env('SKIR_CLIENT_FORMAT', 'dense'),

'auth' => [
// null (no authentication), header, bearer, or basic
'type' => env('SKIR_CLIENT_AUTH_TYPE'),
'header' => env('SKIR_CLIENT_AUTH_HEADER', 'Authorization'),
'token' => env('SKIR_CLIENT_AUTH_TOKEN'),
'username' => env('SKIR_CLIENT_AUTH_USERNAME'),
'password' => env('SKIR_CLIENT_AUTH_PASSWORD'),
],

'generator' => [
'node' => env('SKIR_CLIENT_NODE', 'node'),
'skir_bin' => env('SKIR_CLIENT_SKIR_BIN', base_path('node_modules/skir/dist/compiler.js')),
Expand Down
74 changes: 74 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,78 @@ $client = new SkirClient('https://api.example.test', '/api/skir', WireFormat::Re

Readable JSON is meant for humans and is not safe for persistence. Binary is not part of the SkirRPC wire protocol; generated classes offer `toBytes()` and `fromBytes()` when you need it outside RPC.

## Authentication

The client sends no credentials by default. Set `SKIR_CLIENT_AUTH_TYPE` to `header`, `bearer`, or `basic` to authenticate every request. The package uses Saloon's built-in authenticators, so the request is authenticated the same way any Saloon connector would be.

### Custom HTTP header

Send a shared secret in a header of your choice:

```dotenv
SKIR_CLIENT_AUTH_TYPE=header
SKIR_CLIENT_AUTH_HEADER=X-Internal-Token
SKIR_CLIENT_AUTH_TOKEN=your-shared-secret
```

Every SkirRPC request now includes:

```http
X-Internal-Token: your-shared-secret
```

`SKIR_CLIENT_AUTH_HEADER` defaults to `Authorization`, so leaving it out sends the raw token in the `Authorization` header.

To rotate the secret, have the server accept both the current and the next value, update `SKIR_CLIENT_AUTH_TOKEN`, and refresh the configuration cache with `php artisan config:cache` if you use it. The client always sends a single token.

### Bearer token

```dotenv
SKIR_CLIENT_AUTH_TYPE=bearer
SKIR_CLIENT_AUTH_TOKEN=your-token
```

This sends `Authorization: Bearer your-token`.

### Basic authentication

```dotenv
SKIR_CLIENT_AUTH_TYPE=basic
SKIR_CLIENT_AUTH_USERNAME=admin
SKIR_CLIENT_AUTH_PASSWORD=secret
```

When an auth type is set but a credential it needs is empty, resolving the client throws `SkirClientException`. The client never falls back to an unauthenticated request. An unknown auth type also throws.

### Without the container

Pass any Saloon authenticator to `withAuthenticator()`:

```php
use Saloon\Http\Auth\HeaderAuthenticator;
use Skir\Client\SkirClient;

$client = (new SkirClient('https://api.example.test', '/api/skir'))
->withAuthenticator(new HeaderAuthenticator(config('services.internal.token'), 'X-Internal-Token'));
```

### Custom authentication

For anything else, implement `Saloon\Contracts\Authenticator` and attach it to the container-resolved client in your `AppServiceProvider`:

```php
use App\Http\Auth\SignedRequestAuthenticator;
use Skir\Client\SkirClient;

public function register(): void
{
$this->app->extend(
SkirClient::class,
fn (SkirClient $client) => $client->withAuthenticator(new SignedRequestAuthenticator()),
);
}
```

Use `Saloon\Http\Auth\MultiAuthenticator` to combine several authenticators, for example to send two headers.

See [Generating clients](generating-clients.md) for the typed generation workflow and [Error handling and testing](error-handling-and-testing.md) for transport failure handling and mocks.
3 changes: 2 additions & 1 deletion docs/error-handling-and-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ Only these cases throw `SkirClientException`:

- a failed HTTP response;
- a successful response that cannot be decoded (the `SkirRuntimeException` is available as the previous exception);
- resolving the client from the container without a configured base URL.
- resolving the client from the container without a configured base URL;
- resolving the client with an unsupported `auth.type`, or with an auth type whose credential is empty.

A `SkirRuntimeException` thrown while encoding the request propagates directly. DNS, connection, and TLS failures propagate as `Saloon\Exceptions\Request\FatalRequestException` and have no response.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,16 @@ SKIR_CLIENT_ENDPOINT=/api/skir
endpoint path in the base URL.

`SKIR_CLIENT_FORMAT` is `dense` (default) or `readable`; readable JSON is for debugging only.

Authentication is off unless `SKIR_CLIENT_AUTH_TYPE` is set:

| `SKIR_CLIENT_AUTH_TYPE` | Also set | Sends |
|---|---|---|
| `header` | `SKIR_CLIENT_AUTH_TOKEN`, `SKIR_CLIENT_AUTH_HEADER` (default `Authorization`) | `<header>: <token>` |
| `bearer` | `SKIR_CLIENT_AUTH_TOKEN` | `Authorization: Bearer <token>` |
| `basic` | `SKIR_CLIENT_AUTH_USERNAME`, `SKIR_CLIENT_AUTH_PASSWORD` | `Authorization: Basic ...` |

A missing credential or unknown type throws `SkirClientException` on resolve. For custom schemes, implement
`Saloon\Contracts\Authenticator` and attach it with
`$this->app->extend(SkirClient::class, fn ($client) => $client->withAuthenticator(...))`. Never commit
credentials; keep them in `.env`.
8 changes: 5 additions & 3 deletions src/Commands/GenerateClientCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Skir\Client\Commands;

use Illuminate\Console\Command;
use Skir\Client\SkirClientServiceProvider;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

Expand All @@ -19,9 +20,10 @@ final class GenerateClientCommand extends Command

public function handle(): int
{
$root = (string) ($this->option('root') ?: config('skir-client.generator.root'));
$skirBin = (string) ($this->option('skir-bin') ?: config('skir-client.generator.skir_bin'));
$node = (string) ($this->option('node') ?: config('skir-client.generator.node', 'node'));
$key = SkirClientServiceProvider::configKey();
$root = (string) ($this->option('root') ?: config("{$key}.generator.root"));
$skirBin = (string) ($this->option('skir-bin') ?: config("{$key}.generator.skir_bin"));
$node = (string) ($this->option('node') ?: config("{$key}.generator.node", 'node'));

if (! is_dir($root)) {
$this->error("Skir project root does not exist: {$root}");
Expand Down
14 changes: 12 additions & 2 deletions src/Exceptions/SkirClientException.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,19 @@ public static function invalidResponse(MethodDescriptor $method, Throwable $prev
);
}

public static function missingBaseUrl(): self
public static function missingBaseUrl(string $configKey = 'skir-client'): self
{
return new self('Set [skir-client.base_url] (SKIR_CLIENT_BASE_URL) to the SkirRPC server URL.');
return new self("Set [{$configKey}.base_url] (SKIR_CLIENT_BASE_URL) to the SkirRPC server URL.");
}

public static function unsupportedAuthType(string $type): self
{
return new self("Skir client auth type [{$type}] is not supported. Use [header], [bearer], or [basic].");
}

public static function missingAuthCredential(string $configKey, string $env): self
{
return new self("Set [{$configKey}] ({$env}) to use the configured Skir client authentication.");
}

public static function unsupportedFormat(string $format): self
Expand Down
8 changes: 8 additions & 0 deletions src/SkirClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Skir\Client;

use Saloon\Contracts\Authenticator;
use Saloon\Http\Faking\MockClient;
use Skir\Client\Exceptions\SkirClientException;
use Skir\Client\Http\SkirConnector;
Expand Down Expand Up @@ -31,6 +32,13 @@ public function withMockClient(MockClient $mockClient): self
return $this;
}

public function withAuthenticator(Authenticator $authenticator): self
{
$this->connector->authenticate($authenticator);

return $this;
}

public function invoke(MethodDescriptor $descriptor, mixed $request): mixed
{
$response = $this->connector->send(
Expand Down
61 changes: 56 additions & 5 deletions src/SkirClientServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,50 @@
namespace Skir\Client;

use Illuminate\Support\ServiceProvider;
use Saloon\Contracts\Authenticator;
use Saloon\Http\Auth\BasicAuthenticator;
use Saloon\Http\Auth\HeaderAuthenticator;
use Saloon\Http\Auth\TokenAuthenticator;
use Skir\Client\Commands\GenerateClientCommand;
use Skir\Client\Exceptions\SkirClientException;

final class SkirClientServiceProvider extends ServiceProvider
{
private static string $configKey = 'skir-client';

public static function useConfig(string $key): void
{
self::$configKey = $key;
}

public static function configKey(): string
{
return self::$configKey;
}

public function register(): void
{
$this->mergeConfigFrom(__DIR__.'/../config/skir-client.php', 'skir-client');

$this->app->bind(SkirClient::class, function (): SkirClient {
$baseUrl = config('skir-client.base_url');
$key = self::$configKey;
$baseUrl = config("{$key}.base_url");

if (! is_string($baseUrl) || $baseUrl === '') {
throw SkirClientException::missingBaseUrl();
throw SkirClientException::missingBaseUrl($key);
}

$format = (string) config('skir-client.format');
$format = (string) config("{$key}.format", 'dense');

return new SkirClient(
$client = new SkirClient(
$baseUrl,
(string) config('skir-client.endpoint'),
(string) config("{$key}.endpoint", '/'),
WireFormat::tryFrom($format) ?? throw SkirClientException::unsupportedFormat($format),
);

$authenticator = $this->authenticator($key);

return $authenticator === null ? $client : $client->withAuthenticator($authenticator);
});
}

Expand All @@ -43,4 +64,34 @@ public function boot(): void
]);
}
}

private function authenticator(string $key): ?Authenticator
{
$type = config("{$key}.auth.type");

return match ($type) {
null, '' => null,
'header' => new HeaderAuthenticator(
$this->credential($key, 'token', 'SKIR_CLIENT_AUTH_TOKEN'),
$this->credential($key, 'header', 'SKIR_CLIENT_AUTH_HEADER'),
),
'bearer' => new TokenAuthenticator($this->credential($key, 'token', 'SKIR_CLIENT_AUTH_TOKEN')),
'basic' => new BasicAuthenticator(
$this->credential($key, 'username', 'SKIR_CLIENT_AUTH_USERNAME'),
$this->credential($key, 'password', 'SKIR_CLIENT_AUTH_PASSWORD'),
),
default => throw SkirClientException::unsupportedAuthType((string) $type),
};
}

private function credential(string $key, string $field, string $env): string
{
$value = config("{$key}.auth.{$field}");

if (! is_string($value) || $value === '') {
throw SkirClientException::missingAuthCredential("{$key}.auth.{$field}", $env);
}

return $value;
}
}
Loading
Loading