diff --git a/README.md b/README.md index eb2c3e6..b7d6f78 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 diff --git a/config/skir-client.php b/config/skir-client.php index 0e85592..625b165 100644 --- a/config/skir-client.php +++ b/config/skir-client.php @@ -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')), diff --git a/docs/configuration.md b/docs/configuration.md index 6695dab..da8c669 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -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. diff --git a/docs/error-handling-and-testing.md b/docs/error-handling-and-testing.md index f84fd57..e70a6b2 100644 --- a/docs/error-handling-and-testing.md +++ b/docs/error-handling-and-testing.md @@ -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. diff --git a/resources/boost/skills/skir-client-development/references/generation-and-configuration.md b/resources/boost/skills/skir-client-development/references/generation-and-configuration.md index 0eb3660..d6a7d40 100644 --- a/resources/boost/skills/skir-client-development/references/generation-and-configuration.md +++ b/resources/boost/skills/skir-client-development/references/generation-and-configuration.md @@ -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`) | `
: ` | +| `bearer` | `SKIR_CLIENT_AUTH_TOKEN` | `Authorization: Bearer ` | +| `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`. diff --git a/src/Commands/GenerateClientCommand.php b/src/Commands/GenerateClientCommand.php index fde7f96..0bb1113 100644 --- a/src/Commands/GenerateClientCommand.php +++ b/src/Commands/GenerateClientCommand.php @@ -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; @@ -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}"); diff --git a/src/Exceptions/SkirClientException.php b/src/Exceptions/SkirClientException.php index 0584293..6bb1d37 100644 --- a/src/Exceptions/SkirClientException.php +++ b/src/Exceptions/SkirClientException.php @@ -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 diff --git a/src/SkirClient.php b/src/SkirClient.php index 535943b..9071de9 100644 --- a/src/SkirClient.php +++ b/src/SkirClient.php @@ -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; @@ -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( diff --git a/src/SkirClientServiceProvider.php b/src/SkirClientServiceProvider.php index b4e53d1..666d147 100644 --- a/src/SkirClientServiceProvider.php +++ b/src/SkirClientServiceProvider.php @@ -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); }); } @@ -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; + } } diff --git a/tests/Feature/SkirClientServiceProviderTest.php b/tests/Feature/SkirClientServiceProviderTest.php index a1c2a12..b2aabc6 100644 --- a/tests/Feature/SkirClientServiceProviderTest.php +++ b/tests/Feature/SkirClientServiceProviderTest.php @@ -5,11 +5,15 @@ namespace Skir\Client\Tests\Feature; use PHPUnit\Framework\Attributes\Test; +use Saloon\Contracts\Authenticator; use Saloon\Http\Faking\MockClient; use Saloon\Http\Faking\MockResponse; +use Saloon\Http\PendingRequest; +use Saloon\Http\Response; use Skir\Client\Exceptions\SkirClientException; use Skir\Client\Http\SkirRpcRequest; use Skir\Client\SkirClient; +use Skir\Client\SkirClientServiceProvider; use Skir\Client\Tests\TestCase; use Skir\Client\WireFormat; use Skir\Runtime\MethodDescriptor; @@ -84,4 +88,124 @@ public function it_rejects_an_unsupported_wire_format(): void app(SkirClient::class); } + + #[Test] + public function it_resolves_header_authentication_from_config(): void + { + config()->set('skir-client.base_url', 'https://example.com/api'); + config()->set('skir-client.auth.type', 'header'); + config()->set('skir-client.auth.header', 'X-Trackr-Internal-Token'); + config()->set('skir-client.auth.token', 'secret'); + + $this->assertSentHeader(app(SkirClient::class), 'X-Trackr-Internal-Token', 'secret'); + } + + #[Test] + public function it_resolves_bearer_authentication_from_config(): void + { + config()->set('skir-client.base_url', 'https://example.com/api'); + config()->set('skir-client.auth.type', 'bearer'); + config()->set('skir-client.auth.token', 'secret'); + + $this->assertSentHeader(app(SkirClient::class), 'Authorization', 'Bearer secret'); + } + + #[Test] + public function it_resolves_basic_authentication_from_config(): void + { + config()->set('skir-client.base_url', 'https://example.com/api'); + config()->set('skir-client.auth.type', 'basic'); + config()->set('skir-client.auth.username', 'admin'); + config()->set('skir-client.auth.password', 'hunter2'); + + $this->assertSentHeader(app(SkirClient::class), 'Authorization', 'Basic '.base64_encode('admin:hunter2')); + } + + #[Test] + public function it_rejects_an_unsupported_auth_type(): void + { + config()->set('skir-client.base_url', 'https://example.com/api'); + config()->set('skir-client.auth.type', 'digest'); + + $this->expectException(SkirClientException::class); + $this->expectExceptionMessage('Skir client auth type [digest] is not supported. Use [header], [bearer], or [basic].'); + + app(SkirClient::class); + } + + #[Test] + public function it_requires_a_token_when_authentication_is_configured(): void + { + config()->set('skir-client.base_url', 'https://example.com/api'); + config()->set('skir-client.auth.type', 'header'); + config()->set('skir-client.auth.token', null); + + $this->expectException(SkirClientException::class); + $this->expectExceptionMessage('Set [skir-client.auth.token] (SKIR_CLIENT_AUTH_TOKEN) to use the configured Skir client authentication.'); + + app(SkirClient::class); + } + + #[Test] + public function it_lets_the_application_add_a_custom_authenticator(): void + { + config()->set('skir-client.base_url', 'https://example.com/api'); + + app()->extend(SkirClient::class, fn (SkirClient $client): SkirClient => $client->withAuthenticator( + new class implements Authenticator + { + public function set(PendingRequest $pendingRequest): void + { + $pendingRequest->headers()->add('X-Custom', 'custom'); + } + }, + )); + + $this->assertSentHeader(app(SkirClient::class), 'X-Custom', 'custom'); + } + + #[Test] + public function it_reads_a_renamed_config_file(): void + { + SkirClientServiceProvider::useConfig('trackr-skir'); + config()->set('trackr-skir', [ + 'base_url' => 'https://trackr.example.com', + 'endpoint' => '/internal/skir', + 'format' => 'dense', + 'auth' => [ + 'type' => 'header', + 'header' => 'X-Trackr-Internal-Token', + 'token' => 'secret', + ], + ]); + + $client = app(SkirClient::class); + + $this->assertSentHeader($client, 'X-Trackr-Internal-Token', 'secret'); + } + + #[Test] + public function it_names_the_renamed_config_key_when_the_base_url_is_missing(): void + { + SkirClientServiceProvider::useConfig('trackr-skir'); + + $this->expectException(SkirClientException::class); + $this->expectExceptionMessage('Set [trackr-skir.base_url] (SKIR_CLIENT_BASE_URL) to the SkirRPC server URL.'); + + app(SkirClient::class); + } + + private function assertSentHeader(SkirClient $client, string $header, string $value): void + { + $mockClient = new MockClient([ + SkirRpcRequest::class => MockResponse::make('25', 200), + ]); + + $client->withMockClient($mockClient); + $client->invoke(new MethodDescriptor('Square', 1001, Type::float32(), Type::float32()), 5.0); + + $mockClient->assertSent(function (SkirRpcRequest $request, Response $response) use ($header, $value): bool { + return $response->getPendingRequest()->headers()->get($header) === $value; + }); + } } diff --git a/tests/Feature/SkirClientTest.php b/tests/Feature/SkirClientTest.php index e69209f..5922b3a 100644 --- a/tests/Feature/SkirClientTest.php +++ b/tests/Feature/SkirClientTest.php @@ -5,9 +5,11 @@ namespace Skir\Client\Tests\Feature; use PHPUnit\Framework\Attributes\Test; +use Saloon\Http\Auth\HeaderAuthenticator; use Saloon\Http\Faking\MockClient; use Saloon\Http\Faking\MockResponse; use Saloon\Http\Request; +use Saloon\Http\Response; use Skir\Client\Exceptions\SkirClientException; use Skir\Client\Http\SkirRpcRequest; use Skir\Client\SkirClient; @@ -161,4 +163,38 @@ public function it_can_exchange_readable_json(): void && $request->body()->all() === "RenameUser:1002:readable:{\n \"id\": 42,\n \"name\": \"Maxim\"\n}"; }); } + + #[Test] + public function it_sends_no_authentication_by_default(): void + { + $mockClient = new MockClient([ + SkirRpcRequest::class => MockResponse::make('25', 200), + ]); + + $client = new SkirClient('https://example.com/api'); + $client->withMockClient($mockClient); + $client->invoke(new MethodDescriptor('Square', 1001, Type::float32(), Type::float32()), 5.0); + + $mockClient->assertSent(function (Request $request, Response $response): bool { + return $response->getPendingRequest()->headers()->get('Authorization') === null; + }); + } + + #[Test] + public function it_applies_the_given_authenticator(): void + { + $mockClient = new MockClient([ + SkirRpcRequest::class => MockResponse::make('25', 200), + ]); + + $client = (new SkirClient('https://example.com/api')) + ->withAuthenticator(new HeaderAuthenticator('secret', 'X-Trackr-Internal-Token')) + ->withMockClient($mockClient); + + $client->invoke(new MethodDescriptor('Square', 1001, Type::float32(), Type::float32()), 5.0); + + $mockClient->assertSent(function (Request $request, Response $response): bool { + return $response->getPendingRequest()->headers()->get('X-Trackr-Internal-Token') === 'secret'; + }); + } } diff --git a/tests/TestCase.php b/tests/TestCase.php index 18ae4ff..dd9b1a6 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -9,6 +9,13 @@ abstract class TestCase extends Orchestra { + protected function tearDown(): void + { + SkirClientServiceProvider::useConfig('skir-client'); + + parent::tearDown(); + } + /** * @return array */