diff --git a/AGENTS.md b/AGENTS.md index bb68ebc..c38f675 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,12 +7,12 @@ It targets Quickpay API v10. Composer and GitHub releases distribute the same tracked standalone PHAR without installing Laravel Zero at runtime. Use `php quickpay` when running from source. See `README.md` for the public -command reference and `skills/quickpay/SKILL.md` for the agent-facing usage +command reference and `skills/quickpay-cli/SKILL.md` for the agent-facing usage guide. ## Structure -- `app/Commands` — thin command adapters grouped by API, authentication, +- `app/Commands` — thin command adapters grouped by API, merchants, callbacks, and payments. - `app/Callbacks` — callback replay/watch workflows and their delivery, resolution, signing, and input capabilities. @@ -65,7 +65,7 @@ validation, and the locked-dependency audit. - Preserve raw API JSON in `--json` mode after sanitization. Keep machine-readable output on stdout and diagnostics or prompts on stderr. - Restore environment variables and other global state changed by a test. -- Update `README.md`, command help, and `skills/quickpay/SKILL.md` when a command +- Update `README.md`, command help, and `skills/quickpay-cli/SKILL.md` when a command or safety behavior changes. - Check current Quickpay documentation before changing API behavior; do not infer the remote contract solely from existing code. @@ -74,9 +74,20 @@ validation, and the locked-dependency audit. - Never expose an API key in output, errors, logs, fixtures, or command arguments. Preserve redaction of raw, Basic-auth, and encoded forms. -- Credentials come from a non-empty `QUICKPAY_API_KEY` before - `~/.config/quickpay/config.json`. Stored credentials use atomic writes, a - `0700` directory, and a `0600` file. +- Named credentials live in `~/.config/quickpay-cli/config.json`; never read or + migrate the old `~/.config/quickpay/config.json`. Stored credentials use locked + atomic writes, a `0700` directory, and a `0600` file. +- Stored selection is explicit `--merchant`, nearest `.quickpay-cli.json`, then + global default. Invalid or stale selection never falls back silently. +- A non-empty `QUICKPAY_API_KEY` bypasses saved storage when no explicit or + project selection exists; combining them fails before API requests. +- Saved merchants carry a `read_only` flag that `QuickpayClient` enforces before + sending: a read-only merchant may send only `GET`. Commands that inspect or + confirm before mutating check it first. Only `merchants:access --read-write` + lifts it, in an interactive terminal (removing and re-adding the merchant also + needs the key typed interactively); `QUICKPAY_API_KEY` has full access. +- Resolve credentials once per command, including long-running watchers. Plain + `merchants:active` is local status; `--check` verifies merchant API access. - The client owns the Quickpay host, authentication, API version, and JSON headers. Raw API input must not override them or escape the `api.quickpay.net` origin. diff --git a/CHANGELOG.md b/CHANGELOG.md index bf34ef6..af2798d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,23 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [Unreleased] +### Added + +- Named merchants. `merchants:add`, `merchants:list`, `merchants:select`, `merchants:active` and `merchants:remove` save and choose between several Quickpay merchants, and every authenticated command takes `--merchant`. +- Project merchant bindings. `merchants:select --local` writes `.quickpay-cli.json`, so commands in that folder and below use that merchant. +- Read-only merchants. `merchants:add --read-only` or `merchants:access --read-only` blocks every request except `GET` before anything is sent, and `merchants:access --read-write` allows writes again after a confirmation. +- Payment mutations, payment creation, raw mutations and callback watching name the merchant they use. +- `callbacks:watch` and `callbacks:replay` warn when `QUICKPAY_PRIVATE_KEY` is set while a saved merchant is selected. + +### Changed + +- The bundled agent skill is renamed from `quickpay` to `quickpay-cli`. Remove the old `quickpay` skill folder from your agent's skills directory, then run `skills add tehwave/quickpay-cli`. + +### Removed + +- **Breaking:** the `login`, `logout` and `auth` commands. Save a merchant with `quickpay merchants:add `, and use `merchants:active --check` instead of `auth --check`. +- **Breaking:** the single-key configuration in `~/.config/quickpay/config.json` is no longer read. Add your merchant again with `merchants:add`, then delete the old file. `merchants:add` reminds you while it still exists. + ## [0.2.0] - 2026-08-10 ### Fixed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b06ce84..6aacf65 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -50,7 +50,7 @@ alignment and the main structural boundaries. - Preserve original API JSON in `--json` mode unless credential sanitization is required. - Use integer minor units for amounts. -- Update the README, command help, and `skills/quickpay/SKILL.md` when the CLI +- Update the README, command help, and `skills/quickpay-cli/SKILL.md` when the CLI contract or safety workflow changes. - Check current Quickpay documentation before changing API behavior; do not infer the remote contract solely from existing code. diff --git a/README.md b/README.md index ecbc576..5f0ad40 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,7 @@ [![PHP 8.4+](https://img.shields.io/badge/PHP-8.4%2B-777BB4.svg)](https://www.php.net/) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE.md) -**Manage Quickpay payments and test callbacks from your terminal.** - -Create payment links, manage payments through the [Quickpay API](https://learn.quickpay.net/tech-talk/api/), use JSON output in scripts or for agents, and receive signed callbacks on localhost without a tunnel. +Manage Quickpay payments, create payment links, and relay signed callbacks to localhost without a tunnel. ## Features @@ -21,90 +19,119 @@ Create payment links, manage payments through the [Quickpay API](https://learn.q ⭐ If you like Quickpay CLI, [star it on GitHub](https://github.com/tehwave/quickpay-cli). It helps a lot! -## Installation +## Install -Quickpay CLI requires PHP 8.4 or newer. +Requires PHP 8.4 or newer. ```bash composer global require tehwave/quickpay-cli ``` -Install the bundled skill for coding agents: +## Authentication + +Sign in to [Quickpay Manager](https://manage.quickpay.net/) and select your merchant +account. Open [Settings > Integration](https://quickpay.net/helpdesk/integration-setup/) +and copy the API key under **API User**. Then run: ```bash -skills add tehwave/quickpay-cli +quickpay merchants:add "My Website" ``` -Authenticate with a Quickpay merchant API key: +Paste the key when prompted. Your input stays hidden, and the CLI saves the key in +`~/.config/quickpay-cli/config.json`. The first merchant becomes your default. + +## Merchants ```bash -quickpay login +quickpay merchants:add "My Other Website" +quickpay merchants:select "My Other Website" +quickpay merchants:active --check +quickpay payments:list --merchant="My Website" ``` -For automation, supply the API key through `QUICKPAY_API_KEY`. +To use a different merchant for a project, run +`quickpay merchants:select "My Website" --local` from the project folder. Commands in +that folder and its subfolders will use **My Website** instead of your default merchant. +You can still choose another merchant for a single command with `--merchant`. +The `.quickpay-cli.json` file holds only the merchant name, never a key. Add it to +`.gitignore` when the choice is yours alone. -## Usage +For scripts and CI, you can supply the API key through `QUICKPAY_API_KEY` +instead of saving a merchant. Use it outside folders with a project merchant +selected, and leave out `--merchant`. -```bash -quickpay list -``` +### Read-only merchants -Use `--help` to explore any command and its options: +Keep a merchant safe from changes by blocking its write requests. It can still +list and inspect payments, but it can't create, capture, refund or cancel them, +or send a raw `POST`, `PUT`, `PATCH` or `DELETE`: ```bash -quickpay callbacks:watch --help +quickpay merchants:access "My Website" --read-only +quickpay merchants:access "My Website" --read-write +quickpay merchants:add "My Shop" --read-only ``` -### Watch for callbacks and relay them +A blocked request stops before anything reaches Quickpay. Replacing the key with +`merchants:add --replace` keeps the merchant read-only, but removing it and adding +it again saves it with full access unless you pass `--read-only`. `--read-write` +asks you to confirm in an interactive terminal, so an unattended script can't +lift the protection. It is a guardrail, not a lock: a tool that drives a +terminal can still answer the prompt. A key in `QUICKPAY_API_KEY` always has +full access. + +## Payments ```bash -quickpay callbacks:watch --to=http://127.0.0.1:8000/quickpay/callback +quickpay payments:list +quickpay payments:get --json +quickpay payments:link 1000 ``` -Leave the watcher running while testing the payment flow. It signs and sends -payment updates to your local callback handler. +Amounts are in minor units: `1000` is DKK 10.00 for a DKK payment. +Capture, refund, cancel, and non-GET raw API requests require confirmation +or `--yes` when running unattended. -With no selector, the watcher forwards new operation callbacks for every -payment changed after it becomes ready. Pass a payment ID or `--order-id` to -narrow the watch to one payment. Existing operations are not replayed. The -watcher runs in the foreground and has no JSON mode. +Run `quickpay list` for all commands or `quickpay --help` for options. +## Local callbacks ```bash -quickpay callbacks:replay --to= +quickpay callbacks:watch --to=http://127.0.0.1:8000/quickpay/callback ``` -## Development +Leave it running while testing your payment flow. It forwards new operations +for all payments in the selected merchant account. Add a payment ID to watch +one payment. Existing operations are not replayed. + +To send a payment's current resource once: ```bash -composer install -composer check -composer verify +quickpay callbacks:replay --to=http://127.0.0.1:8000/quickpay/callback ``` -`composer check` runs tests, static analysis, and formatting checks. `composer -verify` additionally enforces coverage, validates package metadata, and audits -the locked dependencies. The test suite uses HTTP fakes and does not contact -Quickpay API. - -The versioned `builds/quickpay` PHAR is tracked so Packagist can install it -without Laravel Zero's dependency graph. Maintainers build it with Laravel -Zero's `app:build` command and commit it as described in `RELEASING.md`. - -See [CONTRIBUTING.md](CONTRIBUTING.md) before changing commands or security behavior. +Callbacks are signed with the merchant's private key, which the CLI fetches from +Quickpay. Set `QUICKPAY_PRIVATE_KEY` to use your own instead. Both commands warn +when it is set while a saved merchant is selected, because it may belong to +another merchant. -Maintainers should follow [RELEASING.md](RELEASING.md) for versioned releases. +## For agents -## Security +Install the bundled [quickpay-cli skill](skills/quickpay-cli/SKILL.md): -Quickpay CLI keeps API keys out of command arguments and asks for confirmation before changing a payment. - -See [SECURITY.md](SECURITY.md) to report a vulnerability. Never include credentials or merchant data in an issue. +```bash +skills add tehwave/quickpay-cli +``` -## Credits +If you installed the earlier `quickpay` skill, remove its folder from your agent's +skills directory first, so your agent stops using the removed `login` and `auth` +commands. -Created and maintained by [Peter 🌊 Jørgensen](https://peterchrjoergensen.dk). +## Contributing -Built with [Laravel Zero](https://laravel-zero.com/) and released under the [MIT License](LICENSE.md). +See [CONTRIBUTING.md](CONTRIBUTING.md), [RELEASING.md](RELEASING.md), and +[SECURITY.md](SECURITY.md). -Quickpay CLI is an independent open-source project. It is not affiliated with or endorsed by Quickpay. +Created by [Peter Jørgensen](https://peterchrjoergensen.dk). Built with +[Laravel Zero](https://laravel-zero.com/) and released under the [MIT License](LICENSE.md). +Independent of and not endorsed by Quickpay. diff --git a/SECURITY.md b/SECURITY.md index 526e6d8..e4ab1ae 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -39,6 +39,36 @@ Security-relevant areas include: - callback private-key retrieval and in-memory-only handling; - release artifact contents, checksums, and build provenance. +## Merchant credentials and selection + +Saved merchant API keys live in `~/.config/quickpay-cli/config.json`, with a +`0700` directory and `0600` file. Credential updates use a persistent sibling +lock and atomic file replacement. `.quickpay-cli.json` selects an already saved +merchant by its local label; it cannot provide credentials, API headers or URLs. +Neither a binding nor selecting a merchant authorizes a payment mutation. + +Explicit `--merchant` selection overrides a project binding and global default. +Malformed or stale bindings, and bindings owned by another user, fail without +selecting another merchant. A non-empty +`QUICKPAY_API_KEY` cannot be combined with an explicit or project selection. +Each command resolves its key once, so running watchers and inspect/confirm +workflows stay attached to the same credential even if local configuration +changes. Saved labels identify local configuration; actual merchant IDs come +from Quickpay resources, when available. + +Each saved merchant also stores a `read_only` flag. For a read-only merchant, +`QuickpayClient` refuses every method except `GET` before sending it. Capture, +refund, cancel and raw mutations check the flag before inspecting a payment or +asking for confirmation. Making a merchant read-only works anywhere, and +`merchants:add --replace` keeps it read-only. Writes are allowed again only by +`merchants:access --read-write`, which needs an interactive terminal and a +confirmation, or by removing the merchant and adding it again without +`--read-only`, which needs its API key typed into an interactive terminal. A key +from `QUICKPAY_API_KEY` has full access. The flag is a local guardrail, not a +Quickpay permission or a lock: a program that drives a pseudo-terminal can +answer the confirmation, and anyone who can edit the configuration file can +change it. + ## Local callback forwarding `callbacks:replay` and `callbacks:watch` send a signed payment resource to the @@ -53,7 +83,10 @@ API key, Basic authorization, or Quickpay API request headers to the callback destination. The account private key comes from a non-empty `QUICKPAY_PRIVATE_KEY` or the authenticated `/account/private-key` endpoint and is retained in process memory only. It is never written to the CLI config, -stdout, stderr, or local response summaries. +stdout, stderr, or local response summaries. A manually supplied +`QUICKPAY_PRIVATE_KEY` must belong to the selected merchant. Because nothing ties +it to one, `callbacks:watch` and `callbacks:replay` warn when it is set while a +saved merchant is selected. Because `--to` may name a public service, inspect it before running the command. The explicit destination is the authorization to POST the payment payload; the diff --git a/app/Callbacks/Resolution/PrivateKeyResolver.php b/app/Callbacks/Resolution/PrivateKeyResolver.php index 3f529b1..afe8958 100644 --- a/app/Callbacks/Resolution/PrivateKeyResolver.php +++ b/app/Callbacks/Resolution/PrivateKeyResolver.php @@ -2,6 +2,7 @@ namespace App\Callbacks\Resolution; +use App\Credentials\ApiKey; use App\Credentials\EnvironmentVariables; use App\Quickpay\QuickpayClient; @@ -28,4 +29,21 @@ public function resolve(QuickpayClient $quickpay): string return $this->fetcher->fetch($quickpay); } + + /** + * Explains an environment private key used with a saved merchant. + * + * The override is not tied to any merchant, so it may sign callbacks with + * another merchant's key. An environment API key is paired with it on + * purpose and gets no warning. + */ + public function overrideWarning(ApiKey $apiKey): ?string + { + $merchant = $apiKey->merchant(); + if ($merchant === null || $this->environment->get('QUICKPAY_PRIVATE_KEY') === null) { + return null; + } + + return "Warning: QUICKPAY_PRIVATE_KEY is set, so callbacks are signed with it instead of the account private key of {$merchant}. Unset it if it belongs to another merchant."; + } } diff --git a/app/Callbacks/Signing/CallbackEnvelope.php b/app/Callbacks/Signing/CallbackEnvelope.php index 4c43679..7dec7d8 100644 --- a/app/Callbacks/Signing/CallbackEnvelope.php +++ b/app/Callbacks/Signing/CallbackEnvelope.php @@ -18,6 +18,5 @@ public function __construct( public ?string $orderId, public string $body, public array $headers, - public ?string $operationId = null, ) {} } diff --git a/app/Callbacks/Signing/CallbackEnvelopeFactory.php b/app/Callbacks/Signing/CallbackEnvelopeFactory.php index 010255f..8250438 100644 --- a/app/Callbacks/Signing/CallbackEnvelopeFactory.php +++ b/app/Callbacks/Signing/CallbackEnvelopeFactory.php @@ -20,7 +20,6 @@ public function make( QuickpayResponse $response, string $apiKey, string $privateKey, - ?string $operationId = null, ): CallbackEnvelope { $resource = json_decode($response->rawBody); @@ -46,7 +45,6 @@ public function make( 'QuickPay-API-Version' => QuickpayClient::API_VERSION, 'QuickPay-Checksum-Sha256' => hash_hmac('sha256', $body, $privateKey), ], - operationId: $operationId, ); } diff --git a/app/Callbacks/Watching/CallbackWatchRunner.php b/app/Callbacks/Watching/CallbackWatchRunner.php index 937955c..f4f91de 100644 --- a/app/Callbacks/Watching/CallbackWatchRunner.php +++ b/app/Callbacks/Watching/CallbackWatchRunner.php @@ -219,7 +219,6 @@ private function deliverOperation( $payment, $apiKey, $privateKey, - $operationId, ); $attempt = 0; diff --git a/app/Commands/Api/ApiRequestCommand.php b/app/Commands/Api/ApiRequestCommand.php index 0aefc25..aaa74f0 100644 --- a/app/Commands/Api/ApiRequestCommand.php +++ b/app/Commands/Api/ApiRequestCommand.php @@ -46,8 +46,10 @@ public function handle( $this->option('data-json'), (array) $this->option('header'), ); + $authenticated->client->authorize($request->method); if ($request->mutation) { + $this->writeMerchantContext($authenticated); $this->writeSafetyLine("Quickpay API request: {$request->method}"); if (! $confirmation->approve( @@ -100,17 +102,6 @@ public function handle( }); } - private function writeSafetyLine(string $message): void - { - // Keep stdout machine-readable in JSON mode without hiding mutation - // summaries and confirmation prompts from the operator. - $output = $this->option('json') - ? $this->getOutput()->getErrorStyle() - : $this->getOutput(); - - $output->writeln($message, OutputInterface::OUTPUT_RAW); - } - private function confirmMutation(): bool { if (! $this->option('json')) { diff --git a/app/Commands/Authentication/AuthCommand.php b/app/Commands/Authentication/AuthCommand.php deleted file mode 100644 index c9f7bdd..0000000 --- a/app/Commands/Authentication/AuthCommand.php +++ /dev/null @@ -1,94 +0,0 @@ -resolve(); - } catch (CredentialException $exception) { - return $this->failure($exception->getMessage()); - } - - if (! $this->option('json')) { - $this->writeHumanStatusHeader($apiKey); - } - - if ($apiKey === null) { - if ($this->option('json')) { - $this->writeJsonStatus(null, null); - } else { - $this->line('Scope: not authenticated'); - $this->comment('Run quickpay login to store a merchant API key.'); - } - - return $this->option('check') ? self::FAILURE : self::SUCCESS; - } - - try { - $response = $quickpay->from($apiKey)->client->get('/ping'); - } catch (QuickpayRequestException $exception) { - return $this->failure($exception->getMessage()); - } - - if (! $response->successful()) { - return $this->failure('Authentication check failed: '.$apiKey->redact($response->errorSummary())); - } - - $scope = is_array($response->json) && is_string($response->json['scope'] ?? null) - ? $response->json['scope'] - : null; - - if ($scope === null || $scope === '') { - return $this->failure('Quickpay authentication check did not return an active scope.'); - } - - if ($apiKey->appearsIn($scope) - || preg_match('/\A[a-z][a-z0-9_-]{0,31}\z/D', $scope) !== 1) { - return $this->failure('Quickpay returned an invalid scope.'); - } - - if ($this->option('json')) { - $this->writeJsonStatus($apiKey, $scope); - } else { - $this->line("Scope: {$scope}"); - } - - return self::SUCCESS; - } - - private function writeHumanStatusHeader(?ApiKey $apiKey): void - { - $this->line('Credential source: '.($apiKey?->source() ?? 'none')); - $this->line('API base URL: '.QuickpayClient::BASE_URL); - $this->line('API version: '.QuickpayClient::API_VERSION); - } - - private function writeJsonStatus(?ApiKey $apiKey, ?string $scope): void - { - $this->getOutput()->write(JsonOutput::value([ - 'authenticated' => $scope !== null, - 'credential_source' => $apiKey?->source(), - 'api_base_url' => QuickpayClient::BASE_URL, - 'api_version' => QuickpayClient::API_VERSION, - 'scope' => $scope, - ], '')); - } -} diff --git a/app/Commands/Authentication/LoginCommand.php b/app/Commands/Authentication/LoginCommand.php deleted file mode 100644 index 87a8257..0000000 --- a/app/Commands/Authentication/LoginCommand.php +++ /dev/null @@ -1,60 +0,0 @@ -secret('API key'); - $apiKey = is_string($answer) ? trim($answer) : ''; - - if ($apiKey === '') { - return $this->failure('API key cannot be empty.'); - } - - $credential = new ApiKey($apiKey, 'provided'); - - try { - $response = $quickpay->from($credential)->client->get('/ping'); - } catch (QuickpayRequestException $exception) { - return $this->failure($exception->getMessage()); - } - - if (! $response->successful()) { - return $this->failure('Authentication failed: '.$credential->redact($response->errorSummary())); - } - - $scope = is_array($response->json) && is_string($response->json['scope'] ?? null) - ? $response->json['scope'] - : null; - - if ($scope !== 'merchant') { - return $this->failure('This credential does not have merchant scope. Only merchant API keys are supported.'); - } - - try { - $credentials->save($apiKey); - } catch (CredentialException $exception) { - return $this->failure($exception->getMessage()); - } - - $this->info('Credentials stored securely.'); - $this->line('Scope: merchant'); - $this->line('Version: '.QuickpayClient::API_VERSION); - - return self::SUCCESS; - } -} diff --git a/app/Commands/Authentication/LogoutCommand.php b/app/Commands/Authentication/LogoutCommand.php deleted file mode 100644 index 8d9556c..0000000 --- a/app/Commands/Authentication/LogoutCommand.php +++ /dev/null @@ -1,36 +0,0 @@ -forget(); - } catch (CredentialException $exception) { - return $this->failure($exception->getMessage()); - } - - if ($removed) { - $this->info('Stored credentials removed.'); - } else { - $this->line('No stored credentials found.'); - } - - if ($resolver->resolve()?->source() === 'environment') { - $this->comment('QUICKPAY_API_KEY is still active; unset it to fully log out.'); - } - - return self::SUCCESS; - } -} diff --git a/app/Commands/Callbacks/ReplayCallbackCommand.php b/app/Commands/Callbacks/ReplayCallbackCommand.php index 88be95e..886c339 100644 --- a/app/Commands/Callbacks/ReplayCallbackCommand.php +++ b/app/Commands/Callbacks/ReplayCallbackCommand.php @@ -5,6 +5,7 @@ use App\Callbacks\Input\CallbackRequest; use App\Callbacks\ReplayCallback; use App\Callbacks\ReplayResult; +use App\Callbacks\Resolution\PrivateKeyResolver; use App\Console\AuthenticatedCommand; use App\Console\Output\JsonOutput; use App\Console\Output\ResponseBodySanitizer; @@ -30,21 +31,26 @@ class ReplayCallbackCommand extends AuthenticatedCommand public function handle( AuthenticatedQuickpayFactory $quickpay, ReplayCallback $replay, + PrivateKeyResolver $privateKeys, ): int { return $this->withQuickpay( $quickpay, - fn (AuthenticatedQuickpay $authenticated): int => $this->present( - $replay->execute( - $authenticated->client, + function (AuthenticatedQuickpay $authenticated) use ($replay, $privateKeys): int { + $request = CallbackRequest::from( + $this->argument('payment-id'), + $this->option('order-id'), + $this->option('to'), + ); + $warning = $privateKeys->overrideWarning($authenticated->apiKey); + if ($warning !== null) { + $this->writeSafetyLine($authenticated->safeLine($warning)); + } + + return $this->present( + $replay->execute($authenticated->client, $authenticated->apiKey->value(), $request), $authenticated->apiKey->value(), - CallbackRequest::from( - $this->argument('payment-id'), - $this->option('order-id'), - $this->option('to'), - ), - ), - $authenticated->apiKey->value(), - ), + ); + }, ); } diff --git a/app/Commands/Callbacks/WatchCallbacksCommand.php b/app/Commands/Callbacks/WatchCallbacksCommand.php index 4170558..0efe791 100644 --- a/app/Commands/Callbacks/WatchCallbacksCommand.php +++ b/app/Commands/Callbacks/WatchCallbacksCommand.php @@ -3,6 +3,7 @@ namespace App\Commands\Callbacks; use App\Callbacks\Input\CallbackRequest; +use App\Callbacks\Resolution\PrivateKeyResolver; use App\Callbacks\WatchCallbacks; use App\Console\AuthenticatedCommand; use App\Console\Input\IntegerInput; @@ -43,10 +44,11 @@ class WatchCallbacksCommand extends AuthenticatedCommand public function handle( AuthenticatedQuickpayFactory $quickpay, WatchCallbacks $watch, + PrivateKeyResolver $privateKeys, ): int { return $this->withQuickpay( $quickpay, - function (AuthenticatedQuickpay $authenticated) use ($watch): int { + function (AuthenticatedQuickpay $authenticated) use ($watch, $privateKeys): int { $request = CallbackRequest::forWatch( $this->argument('payment-id'), $this->option('order-id'), @@ -55,6 +57,11 @@ function (AuthenticatedQuickpay $authenticated) use ($watch): int { $interval = $this->interval(); $deliveryAttempts = $this->deliveryAttempts(); $apiKey = $authenticated->apiKey->value(); + $this->writeMerchantContext($authenticated); + $warning = $privateKeys->overrideWarning($authenticated->apiKey); + if ($warning !== null) { + $this->writeSafetyLine($authenticated->safeLine($warning)); + } if ($request->paymentId !== null || $request->orderId !== null) { $this->info(ResponseBodySanitizer::terminalLine( diff --git a/app/Commands/Merchants/ActiveMerchantCommand.php b/app/Commands/Merchants/ActiveMerchantCommand.php new file mode 100644 index 0000000..8efb851 --- /dev/null +++ b/app/Commands/Merchants/ActiveMerchantCommand.php @@ -0,0 +1,82 @@ +option('merchant'); + $key = $resolver->resolve(is_string($merchant) ? $merchant : null); + } catch (CredentialException $exception) { + return $this->failure($exception->getMessage()); + } + + $checkRequested = (bool) $this->option('check'); + $error = $checkRequested ? $this->authenticationError($key, $check) : null; + $authenticated = $checkRequested ? $error === null : null; + $status = [ + 'merchant' => $key?->merchant(), + 'selection_source' => $key?->selectionSource(), + 'credential_source' => $key?->source(), + 'configured' => $key !== null, + 'read_only' => $key?->access()->readOnly, + 'checked' => $checkRequested, + 'authenticated' => $authenticated, + 'api_base_url' => QuickpayClient::BASE_URL, + 'api_version' => QuickpayClient::API_VERSION, + 'scope' => $authenticated === true ? 'merchant' : null, + ]; + + if ($this->option('json')) { + $this->getOutput()->write(JsonOutput::value($status, '')); + } else { + $this->line('Merchant: '.($status['merchant'] ?? ($key === null ? 'none' : 'not associated with a saved merchant'))); + $this->line('Selection source: '.($status['selection_source'] ?? 'none')); + $this->line('Credential source: '.($status['credential_source'] ?? 'none')); + if ($key !== null && $key->access()->readOnly) { + $this->line('Access: '.$key->access()->label()); + } + $this->line('Credentials configured: '.($status['configured'] ? 'yes' : 'no')); + $this->line('API access: '.match ($authenticated) { + true => 'verified', + false => 'failed', + null => 'not checked', + }); + } + + return $error === null ? self::SUCCESS : $this->failure($error); + } + + private function authenticationError(?ApiKey $key, MerchantAuthenticationCheck $check): ?string + { + if ($key === null) { + return self::NO_MERCHANT_SELECTED; + } + + try { + $check->check($key); + + return null; + } catch (QuickpayRequestException|UnexpectedValueException $exception) { + return $key->redact($exception->getMessage()); + } + } +} diff --git a/app/Commands/Merchants/AddMerchantCommand.php b/app/Commands/Merchants/AddMerchantCommand.php new file mode 100644 index 0000000..4b0372f --- /dev/null +++ b/app/Commands/Merchants/AddMerchantCommand.php @@ -0,0 +1,89 @@ +argument('name')); + $config = $store->read(); + + $saved = isset($config['merchants'][$name]); + if ($saved && ! $this->option('replace')) { + return $this->failure('Merchant is already saved. Use --replace to replace its credential.'); + } + + if (! $saved && $this->option('replace')) { + return $this->failure('Merchant is not saved, so there is no credential to replace. Run quickpay merchants:list to see saved names.'); + } + + $variant = MerchantName::caseVariant($name, array_keys($config['merchants'])); + if (! $saved && $variant !== null) { + return $this->failure("Merchant {$variant} is already saved with different capitalization. Use that name, or choose a clearly different one."); + } + + if (! $this->input->isInteractive() || ! $terminal->isTty()) { + return $this->failure('Adding a merchant requires an interactive terminal. Use QUICKPAY_API_KEY for automation.'); + } + + $answer = $this->secret('API key'); + $apiKey = is_string($answer) ? trim($answer) : ''; + + if ($apiKey === '') { + return $this->failure('API key cannot be empty.'); + } + + $credential = new ApiKey($apiKey, 'provided', MerchantAccess::full()); + if ($credential->appearsIn($name)) { + return $this->failure('Merchant name must not contain the API key.'); + } + + $check->check($credential); + $access = $store->add($name, $apiKey, (bool) $this->option('replace'), (bool) $this->option('read-only')); + $this->info('Merchant saved: '.$name); + if ($access->readOnly) { + $this->line('Access: '.$access->label()); + } + + if ($environment->get('QUICKPAY_API_KEY') !== null) { + $this->comment('QUICKPAY_API_KEY is set, so commands use it instead of your default merchant, and --merchant or a project binding fails. Unset it to use saved merchants.'); + } + + $legacy = $store->leftoverLegacyCredential(); + if ($legacy !== null) { + $this->warn(ResponseBodySanitizer::terminalLine( + "Quickpay CLI no longer uses {$legacy} from earlier versions. Delete it to remove the API key it may still contain.", + $apiKey, + )); + } + + return self::SUCCESS; + } catch (CredentialException|QuickpayRequestException|UnexpectedValueException $exception) { + return $this->failure($credential?->redact($exception->getMessage()) ?? $exception->getMessage()); + } + } +} diff --git a/app/Commands/Merchants/ListMerchantsCommand.php b/app/Commands/Merchants/ListMerchantsCommand.php new file mode 100644 index 0000000..56881e1 --- /dev/null +++ b/app/Commands/Merchants/ListMerchantsCommand.php @@ -0,0 +1,52 @@ +read(); + } catch (CredentialException $exception) { + return $this->failure($exception->getMessage()); + } + + $names = array_keys($config['merchants']); + sort($names, SORT_STRING); + $rows = array_map(fn (string $name): array => [ + 'name' => $name, + 'default' => $config['default_merchant'] === $name, + 'read_only' => $config['merchants'][$name]['read_only'], + ], $names); + + if ($this->option('json')) { + $this->getOutput()->write(JsonOutput::value($rows, '')); + } elseif ($rows === []) { + $this->line('No saved merchants. Run quickpay merchants:add first.'); + } else { + // Access is shown only when a merchant is read-only. + $showAccess = in_array(true, array_column($rows, 'read_only'), true); + $this->table( + ['Merchant', 'Global default', ...($showAccess ? ['Access'] : [])], + array_map(fn (array $row): array => [ + $row['name'], + $row['default'] ? 'yes' : '', + ...($showAccess ? [$row['read_only'] ? (new MerchantAccess(readOnly: true))->label() : ''] : []), + ], $rows), + ); + } + + return self::SUCCESS; + } +} diff --git a/app/Commands/Merchants/RemoveMerchantCommand.php b/app/Commands/Merchants/RemoveMerchantCommand.php new file mode 100644 index 0000000..5a8475d --- /dev/null +++ b/app/Commands/Merchants/RemoveMerchantCommand.php @@ -0,0 +1,34 @@ +remove((string) $this->argument('name')); + $config = $store->read(); + } catch (CredentialException $exception) { + return $this->failure($exception->getMessage()); + } + $this->info('Saved merchant removed.'); + if ($config['default_merchant'] === null && $config['merchants'] !== []) { + $this->comment('No global default merchant is selected. Run quickpay merchants:select to choose one.'); + } + if ($environment->get('QUICKPAY_API_KEY') !== null) { + $this->comment('QUICKPAY_API_KEY remains configured; unset it to stop using that credential.'); + } + + return self::SUCCESS; + } +} diff --git a/app/Commands/Merchants/SelectMerchantCommand.php b/app/Commands/Merchants/SelectMerchantCommand.php new file mode 100644 index 0000000..ac17465 --- /dev/null +++ b/app/Commands/Merchants/SelectMerchantCommand.php @@ -0,0 +1,101 @@ +get('QUICKPAY_API_KEY') !== null) { + return $this->failure('Unset QUICKPAY_API_KEY before selecting a saved merchant.'); + } + + $config = $store->read(); + $name = $this->argument('name'); + + if ($name === null) { + if ($config['merchants'] === []) { + return $this->failure('No saved merchants. Run quickpay merchants:add first.'); + } + + if (! $this->input->isInteractive() || ! $terminal->isTty()) { + return $this->failure('Specify a merchant name when selecting non-interactively.'); + } + + $names = array_keys($config['merchants']); + sort($names, SORT_STRING); + $name = $this->choice('Select merchant', [...$names, '[Cancel]']); + + if ($name === '[Cancel]') { + $this->line('Cancelled.'); + + return self::SUCCESS; + } + } + + if (! is_string($name)) { + return $this->failure('Select exactly one merchant name.'); + } + + if (! isset($config['merchants'][$name])) { + return $this->failure('Merchant is not saved. Run quickpay merchants:list to see saved names.'); + } + + if ($this->option('local')) { + $project->save($name); + $this->info('Project merchant selected: '.$name); + } else { + $store->select($name); + $this->info('Global default merchant selected: '.$name); + $this->explainProjectOverride($project, $name, array_keys($config['merchants'])); + } + + return self::SUCCESS; + } catch (CredentialException $exception) { + return $this->failure($exception->getMessage()); + } + } + + /** + * A project binding outranks the global default, so the new default does + * not apply here. Say so rather than imply it is now in use. + * + * @param list $saved + */ + private function explainProjectOverride(ProjectMerchantFile $project, string $name, array $saved): void + { + try { + $bound = $project->find(); + } catch (CredentialException) { + // The default is already saved. Commands here report the binding's + // problem themselves, so this notice is best effort. + return; + } + + if ($bound === null || $bound === $name) { + return; + } + + if (in_array($bound, $saved, true)) { + $this->comment("Commands in this folder still use {$bound} from the nearest .quickpay-cli.json."); + + return; + } + + $this->warn("Commands in this folder fail until you fix the nearest .quickpay-cli.json: it selects {$bound}, which is not saved."); + } +} diff --git a/app/Commands/Merchants/SetMerchantAccessCommand.php b/app/Commands/Merchants/SetMerchantAccessCommand.php new file mode 100644 index 0000000..265e7df --- /dev/null +++ b/app/Commands/Merchants/SetMerchantAccessCommand.php @@ -0,0 +1,71 @@ +argument('name')); + $readOnly = (bool) $this->option('read-only'); + $readWrite = (bool) $this->option('read-write'); + if ($readOnly && $readWrite) { + return $this->failure('Choose either --read-only or --read-write.'); + } + + $config = $store->read(); + if (! isset($config['merchants'][$name])) { + return $this->failure('Merchant is not saved. Run quickpay merchants:list to see saved names.'); + } + + $current = new MerchantAccess($config['merchants'][$name]['read_only']); + // Allowing what is already allowed changes nothing, so it is not + // saved and cannot undo a protection saved in the meantime. + if (! $readOnly && (! $readWrite || ! $current->readOnly)) { + $this->line($this->summary($name, $current)); + + return self::SUCCESS; + } + + // Making a merchant read-only is always safe. Allowing writes again + // needs a person at the keyboard, so an automated caller cannot. + if ($readWrite) { + if (! $this->input->isInteractive() || ! $terminal->isTty()) { + return $this->failure('Allowing write requests requires an interactive terminal.'); + } + + if (! $this->confirm('Allow write requests for '.$name.'?', false)) { + $this->line('Cancelled.'); + + return self::SUCCESS; + } + } + + $this->info($this->summary($name, $store->changeAccess($name, $readOnly))); + + return self::SUCCESS; + } catch (CredentialException $exception) { + return $this->failure($exception->getMessage()); + } + } + + private function summary(string $name, MerchantAccess $access): string + { + return "Access for {$name}: {$access->label()}"; + } +} diff --git a/app/Commands/Payments/AbstractPaymentMutationCommand.php b/app/Commands/Payments/AbstractPaymentMutationCommand.php index b18407c..47cc61e 100644 --- a/app/Commands/Payments/AbstractPaymentMutationCommand.php +++ b/app/Commands/Payments/AbstractPaymentMutationCommand.php @@ -12,7 +12,6 @@ use App\Quickpay\Payments\PaymentMutation; use Illuminate\Console\OutputStyle; use InvalidArgumentException; -use Symfony\Component\Console\Output\OutputInterface; /** * Executes payment mutations behind a shared inspect-and-confirm workflow. @@ -28,6 +27,10 @@ public function handle( PaymentPresenter $presenter, ): int { return $this->withQuickpay($quickpay, function (AuthenticatedQuickpay $authenticated) use ($confirmation, $presenter): int { + // Capture, refund, and cancel are POST requests. Checking access + // first keeps a read-only merchant from inspecting and prompting + // for a mutation it can never send. + $authenticated->client->authorize('POST'); $apiKey = $authenticated->apiKey->value(); $id = IntegerInput::positive($this->argument('id'), 'id'); $body = $this->mutationBody(); @@ -39,11 +42,11 @@ public function handle( body: $body, query: $query, headers: $headers, - confirm: function (array $payment) use ($apiKey, $body, $confirmation, $presenter): bool { + confirm: function (array $payment) use ($authenticated, $body, $confirmation, $presenter): bool { $this->writeMutationSummary( $payment, $body['amount'] ?? null, - $apiKey, + $authenticated, $presenter, ); @@ -89,9 +92,11 @@ abstract protected function mutationBody(): array; private function writeMutationSummary( array $payment, mixed $amount, - string $apiKey, + AuthenticatedQuickpay $authenticated, PaymentPresenter $presenter, ): void { + $this->writeMerchantContext($authenticated); + $apiKey = $authenticated->apiKey->value(); $fields = [ 'Payment ID' => $payment['id'] ?? null, 'Order ID' => $payment['order_id'] ?? null, @@ -102,6 +107,10 @@ private function writeMutationSummary( 'Operation' => $this->operation(), ]; + if (isset($payment['merchant_id'])) { + $fields = ['Merchant ID' => $payment['merchant_id'], ...$fields]; + } + if ($amount !== null) { $fields['Amount (minor units)'] = $amount; } @@ -130,17 +139,6 @@ private function callbackHeaders(): array return ['QuickPay-Callback-Url' => $callback]; } - private function writeSafetyLine(string $message): void - { - // JSON mode reserves stdout for the response document. Human safety - // context and prompts therefore move to stderr. - $output = $this->option('json') - ? $this->getOutput()->getErrorStyle() - : $this->getOutput(); - - $output->writeln($message, OutputInterface::OUTPUT_RAW); - } - private function confirmMutation(): bool { if (! $this->option('json')) { diff --git a/app/Commands/Payments/CreatePaymentCommand.php b/app/Commands/Payments/CreatePaymentCommand.php index 8bb24b4..839ee0b 100644 --- a/app/Commands/Payments/CreatePaymentCommand.php +++ b/app/Commands/Payments/CreatePaymentCommand.php @@ -43,6 +43,7 @@ public function handle(AuthenticatedQuickpayFactory $quickpay, PaymentPresenter 'order_id' => $orderId, 'currency' => $currency, ]; + $this->writeMerchantContext($authenticated); $result = $authenticated->payments->create($body); $payment = $result->data; diff --git a/app/Commands/Payments/CreatePaymentLinkCommand.php b/app/Commands/Payments/CreatePaymentLinkCommand.php index 6ad937a..f2af109 100644 --- a/app/Commands/Payments/CreatePaymentLinkCommand.php +++ b/app/Commands/Payments/CreatePaymentLinkCommand.php @@ -62,6 +62,7 @@ public function handle(AuthenticatedQuickpayFactory $quickpay, PaymentPresenter $body['auto_capture'] = true; } + $this->writeMerchantContext($authenticated); $result = $authenticated->payments->link($id, $body); $link = $result->data; $url = $link['url'] ?? null; diff --git a/app/Console/AuthenticatedCommand.php b/app/Console/AuthenticatedCommand.php index 2df5719..d4182f6 100644 --- a/app/Console/AuthenticatedCommand.php +++ b/app/Console/AuthenticatedCommand.php @@ -4,32 +4,45 @@ use App\Console\Output\ResponseBodySanitizer; use App\Credentials\Exceptions\CredentialException; +use App\Credentials\Exceptions\MerchantAccessException; use App\Quickpay\AuthenticatedQuickpay; use App\Quickpay\AuthenticatedQuickpayFactory; use App\Quickpay\Exceptions\QuickpayRequestException; use App\Quickpay\QuickpayResponse; use Closure; use InvalidArgumentException; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; use UnexpectedValueException; abstract class AuthenticatedCommand extends BaseCommand { + // Covers both an empty store and saved merchants without a global default. + protected const NO_MERCHANT_SELECTED = 'No merchant selected. Run quickpay merchants:add , or quickpay merchants:select to choose a saved default.'; + + public function __construct() + { + parent::__construct(); + $this->addOption('merchant', null, InputOption::VALUE_REQUIRED, 'Saved merchant to select for this command'); + } + /** @param Closure(AuthenticatedQuickpay): int $callback */ protected function withQuickpay(AuthenticatedQuickpayFactory $quickpay, Closure $callback): int { try { - $authenticated = $quickpay->resolve(); + $merchant = $this->option('merchant'); + $authenticated = $quickpay->resolve(is_string($merchant) ? $merchant : null); } catch (CredentialException $exception) { return $this->failure($exception->getMessage()); } if ($authenticated === null) { - return $this->failure('No Quickpay credentials found. Run quickpay login first.'); + return $this->failure(self::NO_MERCHANT_SELECTED); } try { return $callback($authenticated); - } catch (InvalidArgumentException|QuickpayRequestException|UnexpectedValueException $exception) { + } catch (InvalidArgumentException|MerchantAccessException|QuickpayRequestException|UnexpectedValueException $exception) { return $this->failure($authenticated->safeLine($exception->getMessage())); } } @@ -38,4 +51,23 @@ protected function responseFailure(QuickpayResponse $response, string $apiKey): { return $this->failure(ResponseBodySanitizer::terminalLine($response->errorSummary(), $apiKey)); } + + protected function writeMerchantContext(AuthenticatedQuickpay $authenticated): void + { + foreach ([ + 'Merchant: '.($authenticated->apiKey->merchant() ?? 'not associated with a saved merchant'), + 'Credential source: '.$authenticated->apiKey->source(), + ] as $message) { + $this->writeSafetyLine($authenticated->safeLine($message)); + } + } + + protected function writeSafetyLine(string $message): void + { + $output = $this->input->hasOption('json') && $this->input->getOption('json') + ? $this->getOutput()->getErrorStyle() + : $this->getOutput(); + + $output->writeln($message, OutputInterface::OUTPUT_RAW); + } } diff --git a/app/Credentials/ApiKey.php b/app/Credentials/ApiKey.php index 291d699..db13ead 100644 --- a/app/Credentials/ApiKey.php +++ b/app/Credentials/ApiKey.php @@ -10,6 +10,9 @@ public function __construct( private string $value, private string $source, + private MerchantAccess $access, + private ?string $merchant = null, + private ?string $selectionSource = null, ) { if (trim($value) === '') { throw new InvalidArgumentException('Quickpay API key must not be empty.'); @@ -26,6 +29,21 @@ public function source(): string return $this->source; } + public function access(): MerchantAccess + { + return $this->access; + } + + public function merchant(): ?string + { + return $this->merchant; + } + + public function selectionSource(): ?string + { + return $this->selectionSource; + } + public function redact(string $value): string { return CredentialRedactor::redact($value, $this->value); diff --git a/app/Credentials/ApiKeyResolver.php b/app/Credentials/ApiKeyResolver.php index db04fd1..0892738 100644 --- a/app/Credentials/ApiKeyResolver.php +++ b/app/Credentials/ApiKeyResolver.php @@ -2,23 +2,57 @@ namespace App\Credentials; +use App\Credentials\Exceptions\CredentialException; + final readonly class ApiKeyResolver { public function __construct( private EnvironmentVariables $environment, - private CredentialFile $file, + private MerchantStore $store, + private ProjectMerchantFile $project, ) {} - public function resolve(): ?ApiKey + public function resolve(?string $merchant = null): ?ApiKey { + if ($merchant !== null) { + MerchantName::validate($merchant); + } + $environmentKey = $this->environment->get('QUICKPAY_API_KEY'); + if ($environmentKey !== null && $merchant !== null) { + throw new CredentialException('Unset QUICKPAY_API_KEY before selecting a saved merchant.'); + } + + $projectMerchant = $merchant === null ? $this->project->find() : null; + if ($environmentKey !== null && $projectMerchant !== null) { + throw new CredentialException('Unset QUICKPAY_API_KEY before using a project merchant binding.'); + } if ($environmentKey !== null) { - return new ApiKey($environmentKey, 'environment'); + return new ApiKey($environmentKey, 'environment', MerchantAccess::full(), null, 'environment'); + } + + $config = $this->store->read(); + $source = match (true) { + $merchant !== null => 'explicit', + $projectMerchant !== null => 'project', + default => 'default', + }; + $name = $merchant ?? $projectMerchant ?? $config['default_merchant']; + + if ($name === null) { + return null; + } + + if (! isset($config['merchants'][$name])) { + throw new CredentialException(match ($source) { + 'project' => 'The nearest .quickpay-cli.json selects a merchant that is not saved. Run quickpay merchants:list to see saved names.', + default => 'Selected merchant is not saved. Run quickpay merchants:list to see saved names.', + }); } - $storedKey = $this->file->read(); + $saved = $config['merchants'][$name]; - return $storedKey === null ? null : new ApiKey($storedKey, 'config file'); + return new ApiKey($saved['api_key'], 'config file', new MerchantAccess($saved['read_only']), $name, $source); } } diff --git a/app/Credentials/CredentialFile.php b/app/Credentials/CredentialFile.php deleted file mode 100644 index fed547d..0000000 --- a/app/Credentials/CredentialFile.php +++ /dev/null @@ -1,111 +0,0 @@ -path(), DIRECTORY_SEPARATOR).'/.config/quickpay/config.json'); - } - - public function path(): string - { - return $this->path; - } - - public function exists(): bool - { - return is_file($this->path); - } - - public function read(): ?string - { - if (! $this->exists()) { - return null; - } - - $contents = @file_get_contents($this->path); - - if (! is_string($contents)) { - throw new CredentialException('Quickpay credential file is invalid or cannot be read.'); - } - - try { - $config = json_decode($contents, true, flags: JSON_THROW_ON_ERROR); - } catch (JsonException) { - throw new CredentialException('Quickpay credential file is invalid JSON.'); - } - - if (! is_array($config) - || ! isset($config['api_key']) - || ! is_string($config['api_key']) - || trim($config['api_key']) === '') { - throw new CredentialException('Quickpay credential file is invalid: expected a non-empty api_key string.'); - } - - return $config['api_key']; - } - - public function save(string $apiKey): void - { - $apiKey = trim($apiKey); - - if ($apiKey === '') { - throw new CredentialException('Unable to store Quickpay credentials: the API key is empty.'); - } - - $directory = dirname($this->path); - - if ((! is_dir($directory) && ! @mkdir($directory, 0700, true)) - || ! @chmod($directory, 0700)) { - throw new CredentialException('Unable to store Quickpay credentials: the config directory is not writable.'); - } - - if (is_dir($this->path)) { - throw new CredentialException('Unable to store Quickpay credentials atomically.'); - } - - $temporaryPath = @tempnam($directory, '.'.basename($this->path).'.'); - - if (! is_string($temporaryPath)) { - throw new CredentialException('Unable to store Quickpay credentials: a temporary file could not be created.'); - } - - try { - $json = json_encode(['api_key' => $apiKey], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL; - - if (@file_put_contents($temporaryPath, $json, LOCK_EX) === false - || ! @chmod($temporaryPath, 0600) - || ! @rename($temporaryPath, $this->path)) { - throw new CredentialException('Unable to store Quickpay credentials atomically.'); - } - - $temporaryPath = ''; - } catch (JsonException) { - throw new CredentialException('Unable to store Quickpay credentials.'); - } finally { - if ($temporaryPath !== '' && is_file($temporaryPath)) { - @unlink($temporaryPath); - } - } - } - - public function forget(): bool - { - if (! $this->exists()) { - return false; - } - - if (! @unlink($this->path)) { - throw new CredentialException('Unable to remove the stored Quickpay credential.'); - } - - return true; - } -} diff --git a/app/Credentials/Exceptions/MerchantAccessException.php b/app/Credentials/Exceptions/MerchantAccessException.php new file mode 100644 index 0000000..99bb103 --- /dev/null +++ b/app/Credentials/Exceptions/MerchantAccessException.php @@ -0,0 +1,19 @@ +readOnly; + } + + public function label(): string + { + return $this->readOnly ? 'read-only' : 'read and write'; + } +} diff --git a/app/Credentials/MerchantConfigurationJson.php b/app/Credentials/MerchantConfigurationJson.php new file mode 100644 index 0000000..cd50a53 --- /dev/null +++ b/app/Credentials/MerchantConfigurationJson.php @@ -0,0 +1,39 @@ + $token) { + if ($token === '{') { + $objects[] = []; + } elseif ($token === '}') { + array_pop($objects); + } elseif ($token[0] === '"' && ($tokens[$index + 1] ?? null) === ':') { + $name = json_decode($token, flags: JSON_THROW_ON_ERROR); + $scope = count($objects) - 1; + if (isset($objects[$scope][$name])) { + throw new JsonException('Ambiguous configuration contains duplicate JSON properties.'); + } + $objects[$scope][$name] = true; + } + } + + return $decoded; + } +} diff --git a/app/Credentials/MerchantName.php b/app/Credentials/MerchantName.php new file mode 100644 index 0000000..fd618c6 --- /dev/null +++ b/app/Credentials/MerchantName.php @@ -0,0 +1,36 @@ + 64 || preg_match('/\A[a-z][a-z0-9]*(?:[ -][a-z0-9]+)*\z/iD', $name) !== 1) { + throw new CredentialException('Merchant names must start with a letter and use 1-64 ASCII letters, digits, or single separating spaces or hyphens.'); + } + + return $name; + } + + /** + * Returns a saved name that differs from $name only in capitalization. + * + * Names match exactly, so "Shop" and "shop" would be two merchants that a + * mistyped --merchant silently confuses. A new name must not shadow one. + * + * @param array $saved + */ + public static function caseVariant(string $name, array $saved): ?string + { + foreach ($saved as $existing) { + if ($existing !== $name && strcasecmp($existing, $name) === 0) { + return $existing; + } + } + + return null; + } +} diff --git a/app/Credentials/MerchantStore.php b/app/Credentials/MerchantStore.php new file mode 100644 index 0000000..d04ff1d --- /dev/null +++ b/app/Credentials/MerchantStore.php @@ -0,0 +1,273 @@ +} + */ +final readonly class MerchantStore +{ + /** @var Closure(): string */ + private Closure $path; + + /** @var Closure(): ?string */ + private Closure $legacyPath; + + /** + * @param string|Closure(): string $path + * @param string|Closure(): ?string|null $legacyPath + */ + public function __construct(string|Closure $path, string|Closure|null $legacyPath = null) + { + $this->path = $path instanceof Closure ? $path : fn (): string => $path; + $this->legacyPath = $legacyPath instanceof Closure ? $legacyPath : fn (): ?string => $legacyPath; + } + + /** + * The home folder is looked up only when the configuration is used. A + * missing HOME then fails as an ordinary command error, and commands that + * never touch saved merchants, such as QUICKPAY_API_KEY runs, still work. + */ + public static function inHome(HomeDirectory $home): self + { + $base = fn (): string => rtrim($home->path(), DIRECTORY_SEPARATOR); + + return new self( + fn (): string => $base().'/.config/quickpay-cli/config.json', + fn (): string => $base().'/.config/quickpay/config.json', + ); + } + + public function path(): string + { + return ($this->path)(); + } + + /** + * Returns the pre-merchant credential path when that file still exists. + * + * It is never read or migrated; callers only tell the user it is unused. + */ + public function leftoverLegacyCredential(): ?string + { + $legacyPath = ($this->legacyPath)(); + + return $legacyPath !== null && (file_exists($legacyPath) || is_link($legacyPath)) + ? $legacyPath + : null; + } + + /** @return MerchantConfig */ + public function read(): array + { + $path = $this->path(); + if (! file_exists($path) && ! is_link($path)) { + return ['default_merchant' => null, 'merchants' => []]; + } + + $contents = is_file($path) ? @file_get_contents($path) : false; + if ($contents === false) { + throw new CredentialException('Quickpay CLI merchant configuration cannot be read.'); + } + + try { + $config = MerchantConfigurationJson::decode($contents); + } catch (JsonException) { + throw new CredentialException('Quickpay CLI merchant configuration is invalid JSON or repeats a property.'); + } + + if ($config instanceof stdClass && property_exists($config, 'api_key')) { + $location = ResponseBodySanitizer::terminalLine($path, ''); + + throw new CredentialException("Quickpay CLI merchant configuration {$location} uses the unsupported single-key format. Remove that file, then add merchants again with quickpay merchants:add ."); + } + + if (! $config instanceof stdClass + || count(get_object_vars($config)) !== 2 + || ! property_exists($config, 'default_merchant') + || ! ($config->merchants ?? null) instanceof stdClass + || ($config->default_merchant !== null && ! is_string($config->default_merchant))) { + throw new CredentialException('Quickpay CLI merchant configuration has an invalid structure.'); + } + + $merchants = []; + foreach (get_object_vars($config->merchants) as $name => $merchant) { + try { + MerchantName::validate((string) $name); + } catch (CredentialException $exception) { + $location = ResponseBodySanitizer::terminalLine($path, ''); + + throw new CredentialException("Quickpay CLI merchant configuration {$location} contains an invalid merchant name. {$exception->getMessage()}"); + } + if (! $merchant instanceof stdClass + || ! is_string($merchant->api_key ?? null) + || trim($merchant->api_key) === '') { + throw new CredentialException('Quickpay CLI merchant configuration contains an invalid credential.'); + } + if (count(get_object_vars($merchant)) !== 2 || ! is_bool($merchant->read_only ?? null)) { + throw new CredentialException('Quickpay CLI merchant configuration needs exactly an API key and a true or false read_only flag for each merchant.'); + } + $merchants[$name] = ['api_key' => $merchant->api_key, 'read_only' => $merchant->read_only]; + } + $this->validateLabels($merchants); + + if ($config->default_merchant !== null && ! isset($merchants[$config->default_merchant])) { + throw new CredentialException('Quickpay CLI default merchant is not saved.'); + } + + return ['default_merchant' => $config->default_merchant, 'merchants' => $merchants]; + } + + /** + * Saves a credential and returns the access it was saved with. A + * replacement keeps a read-only merchant read-only: only changeAccess can + * allow writes again. + */ + public function add(string $name, string $apiKey, bool $replace = false, bool $readOnly = false): MerchantAccess + { + MerchantName::validate($name); + $apiKey = trim($apiKey); + if ($apiKey === '') { + throw new CredentialException('API key cannot be empty.'); + } + $access = null; + $this->mutate(function (array $config) use ($name, $apiKey, $replace, $readOnly, &$access): array { + if (isset($config['merchants'][$name]) && ! $replace) { + throw new CredentialException('Merchant is already saved. Use --replace to replace its credential.'); + } + if (! isset($config['merchants'][$name]) && $replace) { + throw new CredentialException('Merchant is not saved, so there is no credential to replace. Run quickpay merchants:list to see saved names.'); + } + $variant = MerchantName::caseVariant($name, array_keys($config['merchants'])); + if (! isset($config['merchants'][$name]) && $variant !== null) { + throw new CredentialException("Merchant {$variant} is already saved with different capitalization. Use that name, or choose a clearly different one."); + } + if ($config['merchants'] === []) { + $config['default_merchant'] = $name; + } + $existing = $config['merchants'][$name] ?? null; + $access = new MerchantAccess($readOnly || ($existing['read_only'] ?? false)); + $config['merchants'][$name] = ['api_key' => $apiKey, 'read_only' => $access->readOnly]; + $this->validateLabels($config['merchants']); + + return $config; + }); + + /** @var MerchantAccess $access */ + return $access; + } + + public function select(string $name): void + { + $this->mutate(function (array $config) use ($name): array { + $this->requireMerchant($config, $name); + $config['default_merchant'] = $name; + + return $config; + }); + } + + /** Sets the read_only flag under the store lock. */ + public function changeAccess(string $name, bool $readOnly): MerchantAccess + { + MerchantName::validate($name); + $access = null; + $this->mutate(function (array $config) use ($name, $readOnly, &$access): array { + $this->requireMerchant($config, $name); + $access = new MerchantAccess($readOnly); + $config['merchants'][$name] = [...$config['merchants'][$name], 'read_only' => $readOnly]; + + return $config; + }); + + /** @var MerchantAccess $access */ + return $access; + } + + public function remove(string $name): void + { + $this->mutate(function (array $config) use ($name): array { + $this->requireMerchant($config, $name); + unset($config['merchants'][$name]); + if ($config['default_merchant'] === $name) { + $config['default_merchant'] = null; + } + + return $config; + }); + } + + /** @param array $merchants */ + private function validateLabels(array $merchants): void + { + // ponytail: quadratic check for the small registry; cache a multi-key matcher if large registries become common. + foreach (array_keys($merchants) as $name) { + foreach ($merchants as $credential) { + if (CredentialRedactor::containsSensitiveValue($name, $credential['api_key'])) { + throw new CredentialException('Merchant name must not contain the API key.'); + } + } + } + } + + /** @param MerchantConfig $config */ + private function requireMerchant(array $config, string $name): void + { + if (! isset($config['merchants'][$name])) { + throw new CredentialException('Merchant is not saved. Run quickpay merchants:list to see saved names.'); + } + } + + /** @param Closure(MerchantConfig): MerchantConfig $change */ + private function mutate(Closure $change): void + { + $file = $this->path(); + $directory = dirname($file); + if ((! is_dir($directory) && ! @mkdir($directory, 0700, true)) || ! @chmod($directory, 0700)) { + throw new CredentialException('Unable to store merchant credentials: the config directory is not writable.'); + } + + // ponytail: one lock for the small credential registry; split storage if write contention matters. + $lock = @fopen($file.'.lock', 'c'); + if ($lock === false) { + throw new CredentialException('Unable to lock merchant credentials.'); + } + + $temporary = ''; + try { + if (! @chmod($file.'.lock', 0600) || ! flock($lock, LOCK_EX)) { + throw new CredentialException('Unable to lock merchant credentials.'); + } + $config = $change($this->read()); + $json = json_encode([ + 'default_merchant' => $config['default_merchant'], + 'merchants' => (object) $config['merchants'], + ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL; + $path = @tempnam($directory, '.'.basename($file).'.'); + if ($path === false) { + throw new CredentialException('Unable to create a temporary merchant configuration.'); + } + $temporary = $path; + if (@file_put_contents($temporary, $json) === false || ! @chmod($temporary, 0600) || ! @rename($temporary, $file)) { + throw new CredentialException('Unable to store merchant credentials atomically.'); + } + $temporary = ''; + } catch (JsonException) { + throw new CredentialException('Unable to encode merchant credentials.'); + } finally { + if ($temporary !== '' && is_file($temporary)) { + @unlink($temporary); + } + flock($lock, LOCK_UN); + fclose($lock); + } + } +} diff --git a/app/Credentials/ProjectMerchantFile.php b/app/Credentials/ProjectMerchantFile.php new file mode 100644 index 0000000..c487d59 --- /dev/null +++ b/app/Credentials/ProjectMerchantFile.php @@ -0,0 +1,136 @@ +directory(); + while (true) { + $path = $directory.'/.quickpay-cli.json'; + if (file_exists($path) || is_link($path)) { + return $this->read($path); + } + $parent = dirname($directory); + if ($parent === $directory) { + return null; + } + $directory = $parent; + } + } + + public function save(string $merchant): void + { + MerchantName::validate($merchant); + $directory = $this->directory(); + $path = $directory.'/.quickpay-cli.json'; + if (file_exists($path) || is_link($path)) { + $this->read($path); + } + $temporary = @tempnam($directory, '..quickpay-cli.json.'); + if ($temporary === false) { + throw new CredentialException('Unable to create a temporary project merchant binding.'); + } + try { + $json = json_encode(['merchant' => $merchant], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL; + if (@file_put_contents($temporary, $json) === false || ! @rename($temporary, $path)) { + throw new CredentialException('Unable to save the project merchant binding atomically.'); + } + } finally { + if (is_file($temporary)) { + @unlink($temporary); + } + } + } + + /** + * The current user's ID, which every binding must be owned by. + * + * Without the posix extension, a temporary file this process creates is + * owned by the same user, so its owner stands in. If that cannot be read + * either, no binding is trusted. + */ + public static function currentUser(): int + { + return function_exists('posix_geteuid') ? posix_geteuid() : self::temporaryFileOwner(); + } + + public static function temporaryFileOwner(): int + { + $file = @tmpfile(); + $stat = $file === false ? false : @fstat($file); + if ($file !== false) { + fclose($file); + } + if ($stat === false) { + throw new CredentialException('Unable to check who owns project merchant bindings.'); + } + + return $stat['uid']; + } + + private function directory(): string + { + $directory = $this->directory ?? getcwd(); + $resolved = is_string($directory) ? realpath($directory) : false; + if ($resolved === false || ! is_dir($resolved)) { + throw new CredentialException('Unable to locate the current project directory.'); + } + + return $resolved; + } + + private function read(string $path): string + { + $location = ResponseBodySanitizer::terminalLine($path, ''); + if (! is_file($path)) { + throw new CredentialException("Project merchant binding {$location} cannot be read."); + } + // Upward discovery reaches shared directories such as /tmp. Another + // user's binding must not steer which saved merchant this user runs, + // so its owner is checked before anything is read. fileowner() follows + // symlinks, so a link another user planted to one of this user's + // bindings is checked by its own owner as well. + $owner = $this->owner ?? self::currentUser(); + $link = is_link($path) ? @lstat($path) : null; + if (@fileowner($path) !== $owner || ($link !== null && ($link === false || $link['uid'] !== $owner))) { + throw new CredentialException("Project merchant binding {$location} is not owned by the current user."); + } + $contents = @file_get_contents($path, false, null, 0, self::MAX_BYTES + 1); + if ($contents === false) { + throw new CredentialException("Project merchant binding {$location} cannot be read."); + } + if (strlen($contents) > self::MAX_BYTES) { + throw new CredentialException("Project merchant binding {$location} is too large to hold only a merchant name."); + } + try { + $config = MerchantConfigurationJson::decode($contents); + } catch (JsonException) { + throw new CredentialException("Project merchant binding {$location} is invalid JSON or repeats a property."); + } + if (! $config instanceof stdClass || count(get_object_vars($config)) !== 1 || ! is_string($config->merchant ?? null)) { + throw new CredentialException("Project merchant binding {$location} must contain only a merchant name."); + } + + try { + return MerchantName::validate($config->merchant); + } catch (CredentialException $exception) { + throw new CredentialException("Project merchant binding {$location}: {$exception->getMessage()}"); + } + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 21e8f1e..b184be2 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -6,9 +6,10 @@ use App\Console\Terminal\NativeStdinTerminalDetector; use App\Console\Terminal\StdinTerminalDetector; use App\Credentials\ApiKeyResolver; -use App\Credentials\CredentialFile; use App\Credentials\EnvironmentVariables; use App\Credentials\HomeDirectory; +use App\Credentials\MerchantStore; +use App\Credentials\ProjectMerchantFile; use App\Quickpay\AuthenticatedQuickpayFactory; use Illuminate\Support\ServiceProvider; use NunoMaduro\LaravelConsoleSummary\Contracts\DescriberContract; @@ -27,9 +28,10 @@ public function register(): void $this->app->singleton(EnvironmentVariables::class); $this->app->singleton(HomeDirectory::class); $this->app->singleton( - CredentialFile::class, - fn ($app): CredentialFile => CredentialFile::inHome($app->make(HomeDirectory::class)), + MerchantStore::class, + fn ($app): MerchantStore => MerchantStore::inHome($app->make(HomeDirectory::class)), ); + $this->app->singleton(ProjectMerchantFile::class); $this->app->singleton(ApiKeyResolver::class); $this->app->singleton(AuthenticatedQuickpayFactory::class); $this->app->singleton(StdinTerminalDetector::class, NativeStdinTerminalDetector::class); diff --git a/app/Quickpay/AuthenticatedQuickpay.php b/app/Quickpay/AuthenticatedQuickpay.php index d9fd3ad..e70eca0 100644 --- a/app/Quickpay/AuthenticatedQuickpay.php +++ b/app/Quickpay/AuthenticatedQuickpay.php @@ -14,18 +14,8 @@ public function __construct( public PaymentApi $payments, ) {} - public function safeJson(string $body): string - { - return ResponseBodySanitizer::json($body, $this->apiKey->value()); - } - public function safeLine(string $value): string { return ResponseBodySanitizer::terminalLine($value, $this->apiKey->value()); } - - public function safeText(string $value): string - { - return ResponseBodySanitizer::terminalText($value, $this->apiKey->value()); - } } diff --git a/app/Quickpay/AuthenticatedQuickpayFactory.php b/app/Quickpay/AuthenticatedQuickpayFactory.php index ba8d660..b845365 100644 --- a/app/Quickpay/AuthenticatedQuickpayFactory.php +++ b/app/Quickpay/AuthenticatedQuickpayFactory.php @@ -14,16 +14,16 @@ public function __construct( private ApiKeyResolver $credentials, ) {} - public function resolve(): ?AuthenticatedQuickpay + public function resolve(?string $merchant = null): ?AuthenticatedQuickpay { - $apiKey = $this->credentials->resolve(); + $apiKey = $this->credentials->resolve($merchant); return $apiKey === null ? null : $this->from($apiKey); } public function from(ApiKey $apiKey): AuthenticatedQuickpay { - $client = new QuickpayClient($this->http, $apiKey->value()); + $client = new QuickpayClient($this->http, $apiKey->value(), $apiKey->access()); return new AuthenticatedQuickpay( $client, diff --git a/app/Quickpay/MerchantAuthenticationCheck.php b/app/Quickpay/MerchantAuthenticationCheck.php new file mode 100644 index 0000000..22bb68f --- /dev/null +++ b/app/Quickpay/MerchantAuthenticationCheck.php @@ -0,0 +1,24 @@ +quickpay->from($apiKey)->client->get('/ping'); + if (! $response->successful()) { + throw new QuickpayRequestException('Authentication check failed: '.ResponseBodySanitizer::terminalLine($response->errorSummary(), $apiKey->value())); + } + if (! is_array($response->json) || ($response->json['scope'] ?? null) !== 'merchant') { + throw new UnexpectedValueException('Quickpay authentication check did not return a valid merchant scope.'); + } + } +} diff --git a/app/Quickpay/QuickpayClient.php b/app/Quickpay/QuickpayClient.php index d74a87a..4550dd5 100644 --- a/app/Quickpay/QuickpayClient.php +++ b/app/Quickpay/QuickpayClient.php @@ -2,6 +2,8 @@ namespace App\Quickpay; +use App\Credentials\Exceptions\MerchantAccessException; +use App\Credentials\MerchantAccess; use App\Quickpay\Exceptions\QuickpayRequestException; use Illuminate\Http\Client\Factory; use Illuminate\Http\Client\HttpClientException; @@ -12,8 +14,9 @@ * Owns every HTTP invariant required by the Quickpay API boundary. * * Callers provide relative paths and business payloads only. Authentication, - * origin, API version, JSON headers, and timeout remain centralized so raw API - * access cannot weaken the same guarantees used by first-class commands. + * origin, API version, JSON headers, timeout, and the merchant's write + * protection remain centralized so raw API access cannot weaken the same guarantees + * used by first-class commands. */ final readonly class QuickpayClient { @@ -24,8 +27,24 @@ public function __construct( private Factory $http, private string $apiKey, + private MerchantAccess $access, ) {} + /** + * Fails before a write request from a read-only merchant. + * + * Commands that inspect or confirm before mutating call this first, so a + * blocked mutation never fetches state or asks for confirmation. + * + * @throws MerchantAccessException + */ + public function authorize(string $method): void + { + if (! $this->access->allows($method)) { + throw MerchantAccessException::blocked($method); + } + } + /** * @param array $query * @param array $data @@ -56,26 +75,6 @@ public function put(string $path, array $query = [], array $data = [], array $he return $this->request('PUT', $path, $query, $data, $headers); } - /** - * @param array $query - * @param array $data - * @param array $headers - */ - public function patch(string $path, array $query = [], array $data = [], array $headers = []): QuickpayResponse - { - return $this->request('PATCH', $path, $query, $data, $headers); - } - - /** - * @param array $query - * @param array $data - * @param array $headers - */ - public function delete(string $path, array $query = [], array $data = [], array $headers = []): QuickpayResponse - { - return $this->request('DELETE', $path, $query, $data, $headers); - } - /** * @param array $query * @param array $data @@ -83,6 +82,8 @@ public function delete(string $path, array $query = [], array $data = [], array */ private function request(string $method, string $path, array $query = [], array $data = [], array $headers = []): QuickpayResponse { + $this->authorize($method); + if (parse_url($path, PHP_URL_SCHEME) !== null || str_starts_with($path, '//')) { throw new InvalidArgumentException('Quickpay request paths must be relative.'); } @@ -104,6 +105,8 @@ public function raw( array $headers = [], bool $hasData = false, ): QuickpayResponse { + $this->authorize($method); + if (parse_url($path, PHP_URL_SCHEME) !== null || str_starts_with($path, '//')) { throw new InvalidArgumentException('Quickpay request paths must be relative.'); } diff --git a/app/Quickpay/Raw/RawApiHeaderParser.php b/app/Quickpay/Raw/RawApiHeaderParser.php index e9b1c55..3e00208 100644 --- a/app/Quickpay/Raw/RawApiHeaderParser.php +++ b/app/Quickpay/Raw/RawApiHeaderParser.php @@ -15,6 +15,17 @@ final class RawApiHeaderParser 'accept-version', ]; + /** + * Headers that ask a server to treat a request as another method. The + * method argument alone decides what a request is, so a read-only + * merchant's GET can never be turned into a write. + */ + private const METHOD_OVERRIDE_HEADERS = [ + 'x-http-method-override', + 'x-http-method', + 'x-method-override', + ]; + /** * @param array $fields * @return array @@ -45,6 +56,10 @@ public static function parse(array $fields): array throw new InvalidArgumentException('Raw API header names and values must not contain invalid characters.'); } + if (in_array(strtolower($name), self::METHOD_OVERRIDE_HEADERS, true)) { + throw new InvalidArgumentException("The {$name} header cannot be sent. Pass the method you mean as the method argument."); + } + if (in_array(strtolower($name), self::PROTECTED_HEADERS, true)) { throw new InvalidArgumentException("The {$name} header cannot be overridden."); } diff --git a/composer.lock b/composer.lock index 28c9ce3..220c325 100644 --- a/composer.lock +++ b/composer.lock @@ -3132,16 +3132,16 @@ }, { "name": "league/flysystem", - "version": "3.35.2", + "version": "3.35.3", "source": { "type": "git", "url": "https://github.com/thephpleague/flysystem.git", - "reference": "b277b5dc3d56650b68904117124e79c851e12376" + "reference": "5fc8404762179ae514678487b23494fd69b2309c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/b277b5dc3d56650b68904117124e79c851e12376", - "reference": "b277b5dc3d56650b68904117124e79c851e12376", + "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/5fc8404762179ae514678487b23494fd69b2309c", + "reference": "5fc8404762179ae514678487b23494fd69b2309c", "shasum": "" }, "require": { @@ -3209,9 +3209,9 @@ ], "support": { "issues": "https://github.com/thephpleague/flysystem/issues", - "source": "https://github.com/thephpleague/flysystem/tree/3.35.2" + "source": "https://github.com/thephpleague/flysystem/tree/3.35.3" }, - "time": "2026-07-06T14:42:07+00:00" + "time": "2026-08-22T12:55:54+00:00" }, { "name": "league/flysystem-local", @@ -7054,16 +7054,16 @@ }, { "name": "symfony/deprecation-contracts", - "version": "v3.7.1", + "version": "v3.8.1", "source": { "type": "git", "url": "https://github.com/symfony/deprecation-contracts.git", - "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d" + "reference": "feb1edf4e546af3b85c5caebe8359a20db230ca3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/f3202fa1b5097b0af062dc978b32ecf63404e31d", - "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/feb1edf4e546af3b85c5caebe8359a20db230ca3", + "reference": "feb1edf4e546af3b85c5caebe8359a20db230ca3", "shasum": "" }, "require": { @@ -7076,7 +7076,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -7101,7 +7101,7 @@ "description": "A generic function and convention to trigger deprecation notices", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/deprecation-contracts/tree/v3.7.1" + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.8.1" }, "funding": [ { @@ -7121,20 +7121,20 @@ "type": "tidelift" } ], - "time": "2026-06-05T06:23:12+00:00" + "time": "2026-09-16T14:15:10+00:00" }, { "name": "symfony/error-handler", - "version": "v7.4.15", + "version": "v7.4.22", "source": { "type": "git", "url": "https://github.com/symfony/error-handler.git", - "reference": "d49f6a19f326db41ae7103bdc38e3eb35a791261" + "reference": "545852cfe9c4979c82389155b4d8d05f8864e4f1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/error-handler/zipball/d49f6a19f326db41ae7103bdc38e3eb35a791261", - "reference": "d49f6a19f326db41ae7103bdc38e3eb35a791261", + "url": "https://api.github.com/repos/symfony/error-handler/zipball/545852cfe9c4979c82389155b4d8d05f8864e4f1", + "reference": "545852cfe9c4979c82389155b4d8d05f8864e4f1", "shasum": "" }, "require": { @@ -7183,7 +7183,7 @@ "description": "Provides tools to manage errors and ease debugging PHP code", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/error-handler/tree/v7.4.15" + "source": "https://github.com/symfony/error-handler/tree/v7.4.22" }, "funding": [ { @@ -7203,20 +7203,20 @@ "type": "tidelift" } ], - "time": "2026-07-21T15:13:06+00:00" + "time": "2026-10-25T14:40:16+00:00" }, { "name": "symfony/event-dispatcher", - "version": "v7.4.15", + "version": "v7.4.17", "source": { "type": "git", "url": "https://github.com/symfony/event-dispatcher.git", - "reference": "336e7f3b9e95aba04f93ea9143920c2186abfbb9" + "reference": "d269974ee93c61d03620ffee358355bfdb471d66" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/336e7f3b9e95aba04f93ea9143920c2186abfbb9", - "reference": "336e7f3b9e95aba04f93ea9143920c2186abfbb9", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/d269974ee93c61d03620ffee358355bfdb471d66", + "reference": "d269974ee93c61d03620ffee358355bfdb471d66", "shasum": "" }, "require": { @@ -7268,7 +7268,7 @@ "description": "Provides tools that allow your application components to communicate with each other by dispatching events and listening to them", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/event-dispatcher/tree/v7.4.15" + "source": "https://github.com/symfony/event-dispatcher/tree/v7.4.17" }, "funding": [ { @@ -7288,20 +7288,20 @@ "type": "tidelift" } ], - "time": "2026-07-21T15:13:06+00:00" + "time": "2026-08-21T17:40:08+00:00" }, { "name": "symfony/event-dispatcher-contracts", - "version": "v3.7.1", + "version": "v3.8.1", "source": { "type": "git", "url": "https://github.com/symfony/event-dispatcher-contracts.git", - "reference": "c7de7a00ffb67842132da02ea92988a39ccd9f4e" + "reference": "658e29751424da3ef4758c60f769e59d1b2981eb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/c7de7a00ffb67842132da02ea92988a39ccd9f4e", - "reference": "c7de7a00ffb67842132da02ea92988a39ccd9f4e", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/658e29751424da3ef4758c60f769e59d1b2981eb", + "reference": "658e29751424da3ef4758c60f769e59d1b2981eb", "shasum": "" }, "require": { @@ -7315,7 +7315,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.7-dev" + "dev-main": "3.8-dev" } }, "autoload": { @@ -7348,7 +7348,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.7.1" + "source": "https://github.com/symfony/event-dispatcher-contracts/tree/v3.8.1" }, "funding": [ { @@ -7368,7 +7368,7 @@ "type": "tidelift" } ], - "time": "2026-06-05T06:23:12+00:00" + "time": "2026-09-16T14:15:10+00:00" }, { "name": "symfony/finder", @@ -7440,16 +7440,16 @@ }, { "name": "symfony/http-foundation", - "version": "v7.4.14", + "version": "v7.4.23", "source": { "type": "git", "url": "https://github.com/symfony/http-foundation.git", - "reference": "06db5ae1552177bf8572f8908839f12e3c06aed3" + "reference": "7fb73cffa06e2bcc2cb523fcccb1e8174106b206" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-foundation/zipball/06db5ae1552177bf8572f8908839f12e3c06aed3", - "reference": "06db5ae1552177bf8572f8908839f12e3c06aed3", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/7fb73cffa06e2bcc2cb523fcccb1e8174106b206", + "reference": "7fb73cffa06e2bcc2cb523fcccb1e8174106b206", "shasum": "" }, "require": { @@ -7498,7 +7498,7 @@ "description": "Defines an object-oriented layer for the HTTP specification", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/http-foundation/tree/v7.4.14" + "source": "https://github.com/symfony/http-foundation/tree/v7.4.23" }, "funding": [ { @@ -7518,20 +7518,20 @@ "type": "tidelift" } ], - "time": "2026-06-11T07:31:44+00:00" + "time": "2026-11-04T08:27:22+00:00" }, { "name": "symfony/http-kernel", - "version": "v7.4.14", + "version": "v7.4.23", "source": { "type": "git", "url": "https://github.com/symfony/http-kernel.git", - "reference": "e99af79b1e776646eda0e1c23b7b45c184ff99be" + "reference": "94c57f4c5c45a311d244a0aeadb72b14ee41d25d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-kernel/zipball/e99af79b1e776646eda0e1c23b7b45c184ff99be", - "reference": "e99af79b1e776646eda0e1c23b7b45c184ff99be", + "url": "https://api.github.com/repos/symfony/http-kernel/zipball/94c57f4c5c45a311d244a0aeadb72b14ee41d25d", + "reference": "94c57f4c5c45a311d244a0aeadb72b14ee41d25d", "shasum": "" }, "require": { @@ -7589,7 +7589,7 @@ "symfony/validator": "^6.4|^7.0|^8.0", "symfony/var-dumper": "^6.4|^7.0|^8.0", "symfony/var-exporter": "^6.4|^7.0|^8.0", - "twig/twig": "^3.12" + "twig/twig": "^3.12|^4.0" }, "type": "library", "autoload": { @@ -7617,7 +7617,7 @@ "description": "Provides a structured process for converting a Request into a Response", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/http-kernel/tree/v7.4.14" + "source": "https://github.com/symfony/http-kernel/tree/v7.4.23" }, "funding": [ { @@ -7637,20 +7637,20 @@ "type": "tidelift" } ], - "time": "2026-06-27T09:14:35+00:00" + "time": "2026-11-04T11:26:18+00:00" }, { "name": "symfony/mime", - "version": "v7.4.13", + "version": "v7.4.22", "source": { "type": "git", "url": "https://github.com/symfony/mime.git", - "reference": "a845722765c4f6b2ce88beaf4f4479975b186770" + "reference": "94a4c017435bc515f5ac80421a2c555fb9ca3676" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/mime/zipball/a845722765c4f6b2ce88beaf4f4479975b186770", - "reference": "a845722765c4f6b2ce88beaf4f4479975b186770", + "url": "https://api.github.com/repos/symfony/mime/zipball/94a4c017435bc515f5ac80421a2c555fb9ca3676", + "reference": "94a4c017435bc515f5ac80421a2c555fb9ca3676", "shasum": "" }, "require": { @@ -7674,7 +7674,7 @@ "symfony/process": "^6.4|^7.0|^8.0", "symfony/property-access": "^6.4|^7.0|^8.0", "symfony/property-info": "^6.4|^7.0|^8.0", - "symfony/serializer": "^6.4.3|^7.0.3|^8.0" + "symfony/serializer": "^6.4.44|^7.4.17|^8.1.5" }, "type": "library", "autoload": { @@ -7706,7 +7706,7 @@ "mime-type" ], "support": { - "source": "https://github.com/symfony/mime/tree/v7.4.13" + "source": "https://github.com/symfony/mime/tree/v7.4.22" }, "funding": [ { @@ -7726,7 +7726,7 @@ "type": "tidelift" } ], - "time": "2026-05-23T16:22:37+00:00" + "time": "2026-10-28T17:57:58+00:00" }, { "name": "symfony/polyfill-ctype", @@ -7895,16 +7895,16 @@ }, { "name": "symfony/polyfill-intl-idn", - "version": "v1.38.1", + "version": "v1.43.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-intl-idn.git", - "reference": "dc21118016c039a66235cf93d96b435ffb282412" + "reference": "533d68cf99c8f8ee2e8893c59ed59192e92cfd74" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/dc21118016c039a66235cf93d96b435ffb282412", - "reference": "dc21118016c039a66235cf93d96b435ffb282412", + "url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/533d68cf99c8f8ee2e8893c59ed59192e92cfd74", + "reference": "533d68cf99c8f8ee2e8893c59ed59192e92cfd74", "shasum": "" }, "require": { @@ -7958,7 +7958,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-intl-idn/tree/v1.38.1" + "source": "https://github.com/symfony/polyfill-intl-idn/tree/v1.43.0" }, "funding": [ { @@ -7978,20 +7978,20 @@ "type": "tidelift" } ], - "time": "2026-05-25T15:22:23+00:00" + "time": "2026-09-23T14:40:04+00:00" }, { "name": "symfony/polyfill-intl-normalizer", - "version": "v1.38.0", + "version": "v1.43.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-intl-normalizer.git", - "reference": "2d446c214bdbe5b71bde5011b060a05fece3ae6b" + "reference": "ebd57ccc7edb93d632e184efbe7693d2517bab3b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/2d446c214bdbe5b71bde5011b060a05fece3ae6b", - "reference": "2d446c214bdbe5b71bde5011b060a05fece3ae6b", + "url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/ebd57ccc7edb93d632e184efbe7693d2517bab3b", + "reference": "ebd57ccc7edb93d632e184efbe7693d2517bab3b", "shasum": "" }, "require": { @@ -8043,7 +8043,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.38.0" + "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.43.0" }, "funding": [ { @@ -8063,20 +8063,20 @@ "type": "tidelift" } ], - "time": "2026-05-25T13:48:31+00:00" + "time": "2026-09-23T22:02:09+00:00" }, { "name": "symfony/polyfill-mbstring", - "version": "v1.38.2", + "version": "v1.43.3", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-mbstring.git", - "reference": "d3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6" + "reference": "122889ed24dc000165bcbfd77ec412f15cbdfc6a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/d3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6", - "reference": "d3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/122889ed24dc000165bcbfd77ec412f15cbdfc6a", + "reference": "122889ed24dc000165bcbfd77ec412f15cbdfc6a", "shasum": "" }, "require": { @@ -8128,7 +8128,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.38.2" + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.43.3" }, "funding": [ { @@ -8148,20 +8148,20 @@ "type": "tidelift" } ], - "time": "2026-05-27T06:59:30+00:00" + "time": "2026-10-28T09:35:49+00:00" }, { "name": "symfony/polyfill-php80", - "version": "v1.37.0", + "version": "v1.43.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411" + "reference": "9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/dfb55726c3a76ea3b6459fcfda1ec2d80a682411", - "reference": "dfb55726c3a76ea3b6459fcfda1ec2d80a682411", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74", + "reference": "9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74", "shasum": "" }, "require": { @@ -8212,7 +8212,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php80/tree/v1.37.0" + "source": "https://github.com/symfony/polyfill-php80/tree/v1.43.0" }, "funding": [ { @@ -8232,20 +8232,20 @@ "type": "tidelift" } ], - "time": "2026-04-10T16:19:22+00:00" + "time": "2026-09-25T15:50:05+00:00" }, { "name": "symfony/polyfill-php83", - "version": "v1.41.0", + "version": "v1.43.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php83.git", - "reference": "5ea99087fb99c273a9b9236ed4c31e78b16103c6" + "reference": "80ccff923a8d61f73ebe9da0aa94e25232f004ce" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php83/zipball/5ea99087fb99c273a9b9236ed4c31e78b16103c6", - "reference": "5ea99087fb99c273a9b9236ed4c31e78b16103c6", + "url": "https://api.github.com/repos/symfony/polyfill-php83/zipball/80ccff923a8d61f73ebe9da0aa94e25232f004ce", + "reference": "80ccff923a8d61f73ebe9da0aa94e25232f004ce", "shasum": "" }, "require": { @@ -8292,7 +8292,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php83/tree/v1.41.0" + "source": "https://github.com/symfony/polyfill-php83/tree/v1.43.0" }, "funding": [ { @@ -8312,7 +8312,7 @@ "type": "tidelift" } ], - "time": "2026-07-01T12:47:55+00:00" + "time": "2026-09-25T15:50:05+00:00" }, { "name": "symfony/polyfill-php84", @@ -8396,16 +8396,16 @@ }, { "name": "symfony/polyfill-php85", - "version": "v1.41.0", + "version": "v1.44.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php85.git", - "reference": "255fab485aaa1006ed411040c42aecd7b5302d7a" + "reference": "94c794cb5ba51784bc259f11e9f128593297d8dc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/255fab485aaa1006ed411040c42aecd7b5302d7a", - "reference": "255fab485aaa1006ed411040c42aecd7b5302d7a", + "url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/94c794cb5ba51784bc259f11e9f128593297d8dc", + "reference": "94c794cb5ba51784bc259f11e9f128593297d8dc", "shasum": "" }, "require": { @@ -8452,7 +8452,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php85/tree/v1.41.0" + "source": "https://github.com/symfony/polyfill-php85/tree/v1.44.0" }, "funding": [ { @@ -8472,7 +8472,7 @@ "type": "tidelift" } ], - "time": "2026-07-01T12:47:55+00:00" + "time": "2026-10-30T15:20:09+00:00" }, { "name": "symfony/process", @@ -8893,16 +8893,16 @@ }, { "name": "symfony/var-dumper", - "version": "v7.4.15", + "version": "v7.4.22", "source": { "type": "git", "url": "https://github.com/symfony/var-dumper.git", - "reference": "04ba4add636a95ff437af3a5a9499bb1d6c6d4bd" + "reference": "6e6ff33ea8cf5df27f00a5561ebd5ee9bd7f1618" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/var-dumper/zipball/04ba4add636a95ff437af3a5a9499bb1d6c6d4bd", - "reference": "04ba4add636a95ff437af3a5a9499bb1d6c6d4bd", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/6e6ff33ea8cf5df27f00a5561ebd5ee9bd7f1618", + "reference": "6e6ff33ea8cf5df27f00a5561ebd5ee9bd7f1618", "shasum": "" }, "require": { @@ -8956,7 +8956,7 @@ "dump" ], "support": { - "source": "https://github.com/symfony/var-dumper/tree/v7.4.15" + "source": "https://github.com/symfony/var-dumper/tree/v7.4.22" }, "funding": [ { @@ -8976,7 +8976,7 @@ "type": "tidelift" } ], - "time": "2026-07-21T15:13:06+00:00" + "time": "2026-10-25T21:04:04+00:00" }, { "name": "ta-tikoma/phpunit-architecture-test", diff --git a/skills/quickpay/SKILL.md b/skills/quickpay-cli/SKILL.md similarity index 52% rename from skills/quickpay/SKILL.md rename to skills/quickpay-cli/SKILL.md index 4d9b484..8cb58b3 100644 --- a/skills/quickpay/SKILL.md +++ b/skills/quickpay-cli/SKILL.md @@ -1,5 +1,5 @@ --- -name: quickpay +name: quickpay-cli description: Use when an agent needs to work with Quickpay payments, payment links, callbacks, capture, refund, cancel, authentication, or safe raw API access through the Quickpay CLI. license: MIT metadata: @@ -14,22 +14,65 @@ Run `quickpay --version` before use. Installation and the complete human-facing ## Credentials -Have the human run interactive `quickpay login` themselves. Never request, print, store, or pass an API key in command arguments, headers, files, logs, or output. Use `quickpay auth --check --json` when automation must verify that a credential is active; plain `quickpay auth` remains a human-readable status command. The CLI uses a non-empty `QUICKPAY_API_KEY` before `~/.config/quickpay/config.json`; `quickpay logout` only removes the stored file. +Have the human run `quickpay merchants:add ` themselves to enter an API +key privately. Never request, print, store, or pass a key in command arguments, +headers, files, logs, or output. Do not read credential files to discover keys. + +Saved merchant access lives in `~/.config/quickpay-cli/config.json`. Names such +as `My Website` are local labels, not verified merchant IDs. `merchants:list` lists +saved names; `merchants:select ` changes the global default; +`merchants:select --local` writes only the selection to `.quickpay-cli.json` +in the current directory. `merchants:remove ` removes only local access, +never the remote Quickpay account. Quote names with spaces, for example +`quickpay merchants:add "My Website"`, and preserve their capitalization. +Only change persistent selection when the user asks for it; +prefer `--merchant=` for one command. + +Use `quickpay merchants:active --check --json` to verify API access for the +resolved credential. Add `--merchant=` when working with a saved merchant, +and keep that same explicit selection for inspection and execution. Plain +`merchants:active` reports local configuration without checking authentication. + +Selection is an explicit `--merchant`, then the nearest `.quickpay-cli.json` +found from the working directory upwards, then the global default. Unknown +names, malformed or stale bindings, and bindings owned by another user fail +without falling back. A non-empty +`QUICKPAY_API_KEY` works independently of saved storage when there is no explicit +or project selection. Combining that environment key with either selection +fails; report the conflict rather than silently changing the environment or +using another merchant. Environment-only access has no inferred saved label. + +The first saved merchant becomes the default; adding others keeps an established +default. Replacing a key requires `merchants:add --replace` for an +already saved name and private human input; a rejected key preserves existing +access. Removing the default +leaves no default, and bindings to removed names fail. The old `login`, `logout` +and `auth` commands and `~/.config/quickpay/config.json` are not supported. +Existing users add their merchants again; no automatic migration occurs. + +A saved merchant can be read-only: it may send `GET` requests but no writes +(`POST`, `PUT`, `PATCH`, `DELETE`). `merchants:active --json` reports `read_only`. A +blocked write fails with "is read-only" before anything is sent. That protection +is the user's decision: stop and report it. Never lift or bypass it by running +`merchants:access --read-write`, re-adding the merchant, editing configuration files, +or switching to another merchant or to `QUICKPAY_API_KEY`. Make a merchant +read-only with `--read-only` only when the user asks. ## Safety workflow - Treat `payments:list`, `payments:get`, and raw `api GET` as reads. Treat every other payment command and every non-`GET` raw API request as a mutation. - Prefer `--json` for automation. - Amounts use the smallest currency unit: `1000` is DKK 10.00. -- Before capture, refund, or cancel, run `quickpay payments:get --json`; verify payment ID, order, currency, state, accepted status, balance, and the requested amount. +- Before capture, refund, or cancel, run `quickpay payments:get --merchant= --json`; verify merchant identity, payment ID, order, currency, state, accepted status, balance, and the requested amount. Keep the same explicit merchant in subsequent commands. A saved label or project binding does not authorize a mutation. - Do not infer mutation permission from read access. Require the user's explicit authorization of the operation, payment ID, and amount before any mutation. - Use `--yes` only after that explicit authorization. It is required for unattended capture/refund/cancel and non-`GET` raw API requests; otherwise the CLI asks for an interactive confirmation. Safe capture example, only after inspection and explicit authorization: ```bash -quickpay payments:get 884201 --json -quickpay payments:capture 884201 2500 --yes --json +quickpay merchants:active --merchant="My Website" --check --json +quickpay payments:get 884201 --merchant="My Website" --json +quickpay payments:capture 884201 2500 --merchant="My Website" --yes --json ``` For a refund or cancellation, use the same inspect → verify → explicit authorization → execute sequence. If inspection is unavailable or the state/amount is wrong, stop and report it. @@ -38,26 +81,31 @@ For a refund or cancellation, use the same inspect → verify → explicit autho ```text quickpay about -quickpay login -quickpay auth [--check] [--json] -quickpay logout -quickpay payments:create [currency=DKK] [--field=key=value]... [--json] +quickpay merchants:add [--replace] [--read-only] +quickpay merchants:access [--read-only|--read-write] +quickpay merchants:list [--json] +quickpay merchants:select [] [--local] +quickpay merchants:active [--merchant=name] [--check] [--json] +quickpay merchants:remove +quickpay payments:create [currency=DKK] [--field=key=value]... [--merchant=name] [--json] quickpay payments:list [--accepted] [--state=value] [--order-id=value] [--created-after=value] [--created-before=value] [--page-size=20] - [--all] [--max-pages=100] [--json] -quickpay payments:get [--operations-size=value] [--json] + [--all] [--max-pages=100] [--merchant=name] [--json] +quickpay payments:get [--operations-size=value] [--merchant=name] [--json] quickpay payments:link [--continue-url=url] [--cancel-url=url] [--callback-url=url] [--language=value] [--payment-methods=value] - [--auto-capture] [--field=key=value]... [--json] -quickpay payments:capture [--synchronized] [--callback-url=url] [--yes] [--json] + [--auto-capture] [--field=key=value]... [--merchant=name] [--json] +quickpay payments:capture [--synchronized] [--callback-url=url] + [--merchant=name] [--yes] [--json] quickpay payments:refund [--vat-rate=value] [--synchronized] - [--callback-url=url] [--yes] [--json] -quickpay payments:cancel [--synchronized] [--callback-url=url] [--yes] [--json] -quickpay callbacks:replay [] --to=url [--order-id=value] [--json] + [--callback-url=url] [--merchant=name] [--yes] [--json] +quickpay payments:cancel [--synchronized] [--callback-url=url] [--merchant=name] [--yes] [--json] +quickpay callbacks:replay [] --to=url [--order-id=value] [--merchant=name] [--json] quickpay callbacks:watch [] --to=url [--order-id=value] [--interval=2] - [--delivery-attempts=5] + [--delivery-attempts=5] [--merchant=name] quickpay api [--query=key=value]... - [--data=key=value]... [--data-json='{}'] [--header='name:value']... [--yes] [--json] + [--data=key=value]... [--data-json='{}'] [--header='name:value']... + [--merchant=name] [--yes] [--json] ``` Without `--all`, `payments:list` returns one page and reports additional pages @@ -101,7 +149,10 @@ quickpay callbacks:replay --to= `QUICKPAY_PRIVATE_KEY` is an optional sensitive environment override; never ask the user to paste it into chat or place it in a command argument. Without it, the CLI retrieves the key through the authenticated API and retains it only -in memory. +in memory. An explicit override must belong to the selected merchant; the +callback commands warn when it is set while a saved merchant is selected. If +that warning appears, tell the user rather than unsetting the variable. A watcher +keeps the merchant and key resolved at startup even if saved selection changes. ## Raw API guardrails @@ -119,4 +170,7 @@ Do not use full URLs, hosts, schemes, `..`, backslashes, or fragments. The CLI o - Capture/refund positional order is ` `. - `--yes` is the non-interactive transport flag, not user authorization. - A raw `GET` needs no `--yes`; a raw `POST`, `PUT`, `PATCH`, or `DELETE` does. -- `quickpay auth` is for status; it must never be replaced with printing or testing a key in an argument. +- `quickpay merchants:active --check --json` checks API access; never replace it with printing or testing a key in an argument. +- `merchants:active` without `--check` does not prove that a credential works. +- Check `read_only` in `merchants:active --merchant= --json` before planning a mutation. +- Use the same `--merchant` for readiness checks, payment inspection and any explicitly authorized mutation. diff --git a/tests/Architecture/DistributionContractTest.php b/tests/Architecture/DistributionContractTest.php index 487fa5e..a21149e 100644 --- a/tests/Architecture/DistributionContractTest.php +++ b/tests/Architecture/DistributionContractTest.php @@ -1,5 +1,10 @@ and($composer['bin'])->toBe(['builds/quickpay']) ->and($box['exclude-dev-files'])->toBeFalse(); }); + +it('rejects malformed paths before the bundled filesystem dispatches them', function (string $path): void { + $adapter = Mockery::mock(FilesystemAdapter::class); + $adapter->allows('fileExists')->andReturn(false); + $filesystem = new Filesystem($adapter); + + expect(fn () => $filesystem->fileExists($path))->toThrow(CorruptedPathDetected::class); +})->with([ + 'malformed UTF-8 and ESC' => "folder/\x80\x1bfile", + 'malformed UTF-8 and newline' => "folder/\xff\nfile", + 'malformed UTF-8 alone' => "folder/\x80file", +]); + +it('preserves ordinary path normalization in the bundled filesystem', function (string $path, string $expected): void { + expect((new WhitespacePathNormalizer)->normalizePath($path))->toBe($expected); +})->with([ + 'backslashes and dot segments' => ['folder\\.\\file', 'folder/file'], + 'printable Unicode and spaces' => ['folder/my résumé.txt', 'folder/my résumé.txt'], + 'relative resolution' => ['folder/../file', 'file'], +]); diff --git a/tests/Architecture/SkillContractTest.php b/tests/Architecture/SkillContractTest.php new file mode 100644 index 0000000..5256f8d --- /dev/null +++ b/tests/Architecture/SkillContractTest.php @@ -0,0 +1,24 @@ +toBe(1); + $names[] = $matches[1]; + expect(basename(dirname($path)))->toBe($matches[1]); + } + expect($names)->toBe(['quickpay-cli']); +}); + +it('keeps documented skill paths resolvable', function (): void { + $root = dirname(__DIR__, 2); + foreach (['README.md', 'AGENTS.md', 'CONTRIBUTING.md'] as $document) { + preg_match_all('~skills/[a-z-]+/SKILL\.md~', file_get_contents($root.'/'.$document), $matches); + foreach ($matches[0] as $path) { + expect(is_file($root.'/'.$path), $document.' references '.$path)->toBeTrue(); + } + } +}); diff --git a/tests/Feature/ApplicationIdentityTest.php b/tests/Feature/ApplicationIdentityTest.php index c99386d..8f0fef2 100644 --- a/tests/Feature/ApplicationIdentityTest.php +++ b/tests/Feature/ApplicationIdentityTest.php @@ -19,11 +19,14 @@ expect($commands)->toBe([ 'about', 'api', - 'auth', - 'login', - 'logout', 'callbacks:replay', 'callbacks:watch', + 'merchants:access', + 'merchants:active', + 'merchants:add', + 'merchants:list', + 'merchants:remove', + 'merchants:select', 'payments:cancel', 'payments:capture', 'payments:create', diff --git a/tests/Feature/Callbacks/Resolution/PaymentLocatorTest.php b/tests/Feature/Callbacks/Resolution/PaymentLocatorTest.php index 7f1a121..cdf66b0 100644 --- a/tests/Feature/Callbacks/Resolution/PaymentLocatorTest.php +++ b/tests/Feature/Callbacks/Resolution/PaymentLocatorTest.php @@ -2,6 +2,7 @@ use App\Callbacks\Resolution\PaymentLocator; use App\Callbacks\Watching\CallbackPollingException; +use App\Credentials\MerchantAccess; use App\Quickpay\QuickpayClient; use Illuminate\Http\Client\Factory; use Illuminate\Http\Client\Request; @@ -18,7 +19,7 @@ 'https://api.quickpay.net/payments/43' => Http::response(['id' => 43, 'operations' => []]), ]); - $locator = new PaymentLocator(new QuickpayClient(app(Factory::class), 'api-key')); + $locator = new PaymentLocator(new QuickpayClient(app(Factory::class), 'api-key', MerchantAccess::full())); $payments = $locator->changedBetween( new DateTimeImmutable('2026-08-07T10:00:00+02:00'), new DateTimeImmutable('2026-08-07T10:00:05+02:00'), @@ -176,7 +177,7 @@ 'merchant_id' => 123, ])]); - $locator = new PaymentLocator(new QuickpayClient(app(Factory::class), 'api-key')); + $locator = new PaymentLocator(new QuickpayClient(app(Factory::class), 'api-key', MerchantAccess::full())); $payment = $locator->byId('42'); expect($payment->json['id'])->toBe(42); @@ -195,7 +196,7 @@ ]), ]); - $locator = new PaymentLocator(new QuickpayClient(app(Factory::class), 'api-key')); + $locator = new PaymentLocator(new QuickpayClient(app(Factory::class), 'api-key', MerchantAccess::full())); $payment = $locator->byOrderId('order-42'); expect($payment?->json['id'])->toBe(42); @@ -206,7 +207,7 @@ it('returns null for a missing order but rejects ambiguous or malformed lookup responses', function (array $response, ?string $message) { Http::fake(['https://api.quickpay.net/payments?*' => Http::response($response)]); - $locator = new PaymentLocator(new QuickpayClient(app(Factory::class), 'api-key')); + $locator = new PaymentLocator(new QuickpayClient(app(Factory::class), 'api-key', MerchantAccess::full())); if ($message === null) { expect($locator->byOrderId('order-42'))->toBeNull(); @@ -232,7 +233,7 @@ $retryAfter === null ? [] : ['Retry-After' => (string) $retryAfter], )]); - $locator = new PaymentLocator(new QuickpayClient(app(Factory::class), 'api-key')); + $locator = new PaymentLocator(new QuickpayClient(app(Factory::class), 'api-key', MerchantAccess::full())); try { $locator->byId('42'); @@ -251,5 +252,5 @@ function paymentLocator(): PaymentLocator { - return new PaymentLocator(new QuickpayClient(app(Factory::class), 'api-key')); + return new PaymentLocator(new QuickpayClient(app(Factory::class), 'api-key', MerchantAccess::full())); } diff --git a/tests/Feature/Callbacks/Watching/CallbackWatchRunnerTest.php b/tests/Feature/Callbacks/Watching/CallbackWatchRunnerTest.php index cdd0f43..f98529d 100644 --- a/tests/Feature/Callbacks/Watching/CallbackWatchRunnerTest.php +++ b/tests/Feature/Callbacks/Watching/CallbackWatchRunnerTest.php @@ -7,6 +7,7 @@ use App\Callbacks\Watching\CallbackDeliveryException; use App\Callbacks\Watching\CallbackWatcherFactory; use App\Callbacks\Watching\CallbackWatchRunner; +use App\Credentials\MerchantAccess; use App\Quickpay\QuickpayClient; use Illuminate\Http\Client\Factory; use Illuminate\Http\Client\Request; @@ -667,7 +668,7 @@ it('assembles the production watcher from the credential-scoped clients', function () { $watcher = (new CallbackWatcherFactory)->make( - new QuickpayClient(app(Factory::class), 'api-key'), + new QuickpayClient(app(Factory::class), 'api-key', MerchantAccess::full()), app(Factory::class), ); @@ -701,7 +702,7 @@ function callbackWatchRunner( $remaining = $polls; return new CallbackWatchRunner( - locator: new PaymentLocator(new QuickpayClient(app(Factory::class), 'api-key')), + locator: new PaymentLocator(new QuickpayClient(app(Factory::class), 'api-key', MerchantAccess::full())), envelopes: new CallbackEnvelopeFactory, forwarder: new CallbackForwarder(app(Factory::class)), sleep: function (int $seconds) use (&$sleeps): void { diff --git a/tests/Feature/CommandHelpTest.php b/tests/Feature/CommandHelpTest.php index 23b7c5b..2b28eed 100644 --- a/tests/Feature/CommandHelpTest.php +++ b/tests/Feature/CommandHelpTest.php @@ -1,5 +1,7 @@ artisan('help', ['command_name' => 'payments:capture']) ->expectsOutputToContain('positive integer in minor units') @@ -23,3 +25,17 @@ ->expectsOutputToContain('JSON object request body') ->assertExitCode(0); }); + +it('offers explicit merchant selection for every authenticated command', function (string $command): void { + expect(Artisan::call('help', ['command_name' => $command]))->toBe(0); + expect(Artisan::output())->toContain('--merchant')->toContain('Saved merchant to select for this command'); +})->with(['api', 'callbacks:replay', 'callbacks:watch', 'merchants:active', 'payments:cancel', 'payments:capture', 'payments:create', 'payments:get', 'payments:link', 'payments:list', 'payments:refund']); + +it('can resolve command references from the bundled agent skill', function (): void { + $skill = file_get_contents(base_path('skills/quickpay-cli/SKILL.md')); + preg_match_all('/^quickpay ([a-z][a-z:-]*)/m', $skill, $matches); + expect($matches[1])->not->toBeEmpty(); + foreach (array_unique($matches[1]) as $command) { + expect(Artisan::call('help', ['command_name' => $command]), $command)->toBe(0); + } +}); diff --git a/tests/Feature/Commands/Api/ApiRequestCommandTest.php b/tests/Feature/Commands/Api/ApiRequestCommandTest.php index f195384..a79493a 100644 --- a/tests/Feature/Commands/Api/ApiRequestCommandTest.php +++ b/tests/Feature/Commands/Api/ApiRequestCommandTest.php @@ -2,11 +2,15 @@ use App\Commands\Api\ApiRequestCommand; use App\Console\Terminal\StdinTerminalDetector; +use App\Credentials\ProjectMerchantFile; use Illuminate\Http\Client\Request; use Illuminate\Support\Facades\Http; use Symfony\Component\Console\Tester\CommandTester; beforeEach(function () { + $this->merchantProjectDirectory = sys_get_temp_dir().'/quickpay-test-project-'.bin2hex(random_bytes(8)); + mkdir($this->merchantProjectDirectory, 0700, true); + app()->instance(ProjectMerchantFile::class, new ProjectMerchantFile($this->merchantProjectDirectory)); $this->originalApiKey = getenv('QUICKPAY_API_KEY'); putenv('QUICKPAY_API_KEY=raw-api-secret'); app()->instance(StdinTerminalDetector::class, new class implements StdinTerminalDetector @@ -19,6 +23,7 @@ public function isTty(): bool }); afterEach(function () { + rmdir($this->merchantProjectDirectory); if ($this->originalApiKey === false) { putenv('QUICKPAY_API_KEY'); } else { diff --git a/tests/Feature/Commands/Authentication/AuthenticationCommandsTest.php b/tests/Feature/Commands/Authentication/AuthenticationCommandsTest.php deleted file mode 100644 index 67dc36f..0000000 --- a/tests/Feature/Commands/Authentication/AuthenticationCommandsTest.php +++ /dev/null @@ -1,291 +0,0 @@ -tempDirectory = sys_get_temp_dir().'/quickpay-commands-'.bin2hex(random_bytes(8)); - mkdir($this->tempDirectory, 0700, true); - $this->credentialPath = $this->tempDirectory.'/config.json'; - $this->originalApiKey = getenv('QUICKPAY_API_KEY'); - putenv('QUICKPAY_API_KEY'); - $file = new CredentialFile($this->credentialPath); - app()->instance(CredentialFile::class, $file); - app()->instance(ApiKeyResolver::class, new ApiKeyResolver(new EnvironmentVariables, $file)); -}); - -afterEach(function () { - if ($this->originalApiKey === false) { - putenv('QUICKPAY_API_KEY'); - } else { - putenv('QUICKPAY_API_KEY='.$this->originalApiKey); - } - - if (is_dir($this->tempDirectory)) { - $iterator = new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($this->tempDirectory, FilesystemIterator::SKIP_DOTS), - RecursiveIteratorIterator::CHILD_FIRST, - ); - - foreach ($iterator as $item) { - $item->isDir() ? rmdir($item->getPathname()) : unlink($item->getPathname()); - } - - rmdir($this->tempDirectory); - } -}); - -it('logs in after validating a merchant credential and never displays the key', function () { - Http::fake(['https://api.quickpay.net/ping' => Http::response([ - 'msg' => 'pong', - 'scope' => 'merchant', - 'version' => 'v10', - 'params' => [], - ])]); - - $this->artisan('login') - ->expectsQuestion('API key', ' merchant-secret ') - ->expectsOutputToContain('Credentials stored') - ->expectsOutputToContain('Scope: merchant') - ->expectsOutputToContain('Version: v10') - ->doesntExpectOutputToContain('merchant-secret') - ->assertExitCode(0); - - expect(json_decode(file_get_contents($this->credentialPath), true, flags: JSON_THROW_ON_ERROR)) - ->toBe(['api_key' => 'merchant-secret']); - - Http::assertSent(fn (Request $request): bool => $request->url() === 'https://api.quickpay.net/ping' - && $request->header('Authorization') === ['Basic '.base64_encode(':merchant-secret')]); -}); - -it('does not render a reflected credential from the successful login version field', function () { - Http::fake(['https://api.quickpay.net/ping' => Http::response([ - 'scope' => 'merchant', - 'version' => 'reflected-secret', - ])]); - - $this->artisan('login') - ->expectsQuestion('API key', 'reflected-secret') - ->expectsOutputToContain('Version: v10') - ->doesntExpectOutputToContain('reflected-secret') - ->assertExitCode(0); -}); - -it('rejects an empty login credential before making a request', function () { - Http::fake(); - - $this->artisan('login') - ->expectsQuestion('API key', ' ') - ->expectsOutputToContain('API key cannot be empty') - ->assertExitCode(1); - - Http::assertNothingSent(); - expect(file_exists($this->credentialPath))->toBeFalse(); -}); - -it('does not save login credentials rejected by quickpay', function () { - Http::fake(['https://api.quickpay.net/ping' => Http::response(['message' => 'Invalid API key rejected-secret'], 401)]); - - $this->artisan('login') - ->expectsQuestion('API key', 'rejected-secret') - ->expectsOutputToContain('HTTP 401') - ->doesntExpectOutputToContain('rejected-secret') - ->assertExitCode(1); - - expect(file_exists($this->credentialPath))->toBeFalse(); -}); - -it('rejects a valid login credential without merchant scope', function () { - Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'acquirer', 'version' => 'v10'])]); - - $this->artisan('login') - ->expectsQuestion('API key', 'non-merchant-secret') - ->expectsOutputToContain('merchant scope') - ->doesntExpectOutputToContain('non-merchant-secret') - ->assertExitCode(1); - - expect(file_exists($this->credentialPath))->toBeFalse(); -}); - -it('handles a login network failure without leaking the credential', function () { - Http::fake(fn () => throw new ConnectionException('Network failure for network-secret')); - - $this->artisan('login') - ->expectsQuestion('API key', 'network-secret') - ->expectsOutputToContain('Unable to connect to Quickpay') - ->doesntExpectOutputToContain('network-secret') - ->assertExitCode(1); - - expect(file_exists($this->credentialPath))->toBeFalse(); -}); - -it('shows unauthenticated status and a login hint when no credential exists', function () { - Http::fake(); - - $this->artisan('auth') - ->expectsOutputToContain('Credential source: none') - ->expectsOutputToContain('API base URL: https://api.quickpay.net') - ->expectsOutputToContain('API version: v10') - ->expectsOutputToContain('Scope: not authenticated') - ->expectsOutputToContain('quickpay login') - ->assertExitCode(0); - - Http::assertNothingSent(); -}); - -it('can fail an unauthenticated readiness check without contacting quickpay', function () { - Http::fake(); - - $this->artisan('auth', ['--check' => true]) - ->expectsOutputToContain('Scope: not authenticated') - ->assertExitCode(1); - - Http::assertNothingSent(); -}); - -it('writes unauthenticated status as json for automation', function () { - Http::fake(); - $command = new AuthCommand; - $command->setLaravel(app()); - $tester = new CommandTester($command); - - $status = $tester->execute(['--json' => true], ['capture_stderr_separately' => true]); - - expect($status)->toBe(0) - ->and(json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR))->toBe([ - 'authenticated' => false, - 'credential_source' => null, - 'api_base_url' => 'https://api.quickpay.net', - 'api_version' => 'v10', - 'scope' => null, - ]) - ->and($tester->getErrorOutput())->toBe(''); - - Http::assertNothingSent(); -}); - -it('shows the current authenticated scope without displaying the credential', function () { - file_put_contents($this->credentialPath, json_encode(['api_key' => 'stored-secret'], JSON_THROW_ON_ERROR)); - Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant', 'version' => 'v10'])]); - - $this->artisan('auth') - ->expectsOutputToContain('Credential source: config file') - ->expectsOutputToContain('API base URL: https://api.quickpay.net') - ->expectsOutputToContain('API version: v10') - ->expectsOutputToContain('Scope: merchant') - ->doesntExpectOutputToContain('stored-secret') - ->assertExitCode(0); -}); - -it('writes authenticated status as json and passes a readiness check', function () { - file_put_contents($this->credentialPath, json_encode(['api_key' => 'stored-secret'], JSON_THROW_ON_ERROR)); - Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant', 'version' => 'v10'])]); - $command = new AuthCommand; - $command->setLaravel(app()); - $tester = new CommandTester($command); - - $status = $tester->execute([ - '--json' => true, - '--check' => true, - ], ['capture_stderr_separately' => true]); - - expect($status)->toBe(0) - ->and(json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR))->toBe([ - 'authenticated' => true, - 'credential_source' => 'config file', - 'api_base_url' => 'https://api.quickpay.net', - 'api_version' => 'v10', - 'scope' => 'merchant', - ]) - ->and($tester->getErrorOutput())->toBe('') - ->and($tester->getDisplay())->not->toContain('stored-secret'); -}); - -it('does not render a reflected credential from a successful auth scope field', function () { - file_put_contents($this->credentialPath, json_encode(['api_key' => 'stored-secret'], JSON_THROW_ON_ERROR)); - Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'stored-secret', 'version' => 'v10'])]); - - $this->artisan('auth') - ->expectsOutputToContain('Quickpay returned an invalid scope') - ->doesntExpectOutputToContain('stored-secret') - ->assertExitCode(1); -}); - -it('reports auth api errors safely and exits non-zero', function () { - putenv('QUICKPAY_API_KEY=environment-secret'); - Http::fake(['https://api.quickpay.net/ping' => Http::response(['message' => 'Invalid API key environment-secret'], 401)]); - - $this->artisan('auth') - ->expectsOutputToContain('Credential source: environment') - ->expectsOutputToContain('Invalid API key [redacted]') - ->doesntExpectOutputToContain('environment-secret') - ->assertExitCode(1); -}); - -it('routes command failures to stderr', function () { - putenv('QUICKPAY_API_KEY=stderr-secret'); - Http::fake(['https://api.quickpay.net/ping' => Http::response(['message' => 'Invalid API key'], 401)]); - - $command = new AuthCommand; - $command->setLaravel(app()); - $tester = new CommandTester($command); - - $status = $tester->execute([], ['capture_stderr_separately' => true]); - - expect($status)->toBe(1) - ->and($tester->getErrorOutput())->toContain('Authentication check failed: HTTP 401:') - ->toContain('Invalid API key') - ->and($tester->getDisplay())->not->toContain('Authentication check failed'); -}); - -it('reports auth network errors safely and exits non-zero', function () { - putenv('QUICKPAY_API_KEY=environment-secret'); - Http::fake(fn () => throw new ConnectionException('Failure for environment-secret')); - - $this->artisan('auth') - ->expectsOutputToContain('Unable to connect to Quickpay') - ->doesntExpectOutputToContain('environment-secret') - ->assertExitCode(1); -}); - -it('logs out by deleting the stored config credential', function () { - file_put_contents($this->credentialPath, json_encode(['api_key' => 'stored-secret'], JSON_THROW_ON_ERROR)); - Http::fake(); - - $this->artisan('logout') - ->expectsOutputToContain('Stored credentials removed') - ->doesntExpectOutputToContain('stored-secret') - ->assertExitCode(0); - - expect(file_exists($this->credentialPath))->toBeFalse(); - Http::assertNothingSent(); -}); - -it('treats logout without stored credentials as a successful no-op', function () { - Http::fake(); - - $this->artisan('logout') - ->expectsOutputToContain('No stored credentials found') - ->assertExitCode(0); -}); - -it('explains that an environment credential remains active after logout', function () { - file_put_contents($this->credentialPath, json_encode(['api_key' => 'stored-secret'], JSON_THROW_ON_ERROR)); - putenv('QUICKPAY_API_KEY=environment-secret'); - Http::fake(); - - $this->artisan('logout') - ->expectsOutputToContain('Stored credentials removed') - ->expectsOutputToContain('QUICKPAY_API_KEY is still active') - ->doesntExpectOutputToContain('environment-secret') - ->doesntExpectOutputToContain('stored-secret') - ->assertExitCode(0); - - expect(file_exists($this->credentialPath))->toBeFalse(); -}); diff --git a/tests/Feature/Commands/Callbacks/ReplayCallbackCommandTest.php b/tests/Feature/Commands/Callbacks/ReplayCallbackCommandTest.php index fa7ee8d..ae505a4 100644 --- a/tests/Feature/Commands/Callbacks/ReplayCallbackCommandTest.php +++ b/tests/Feature/Commands/Callbacks/ReplayCallbackCommandTest.php @@ -4,6 +4,8 @@ use App\Callbacks\Resolution\PrivateKeyResolver; use App\Commands\Callbacks\ReplayCallbackCommand; use App\Credentials\EnvironmentVariables; +use App\Credentials\MerchantAccess; +use App\Credentials\ProjectMerchantFile; use App\Quickpay\QuickpayClient; use Illuminate\Http\Client\Factory; use Illuminate\Http\Client\Request; @@ -11,6 +13,9 @@ use Symfony\Component\Console\Tester\CommandTester; beforeEach(function () { + $this->merchantProjectDirectory = sys_get_temp_dir().'/quickpay-test-project-'.bin2hex(random_bytes(8)); + mkdir($this->merchantProjectDirectory, 0700, true); + app()->instance(ProjectMerchantFile::class, new ProjectMerchantFile($this->merchantProjectDirectory)); $this->originalApiKey = getenv('QUICKPAY_API_KEY'); $this->originalPrivateKey = getenv('QUICKPAY_PRIVATE_KEY'); putenv('QUICKPAY_API_KEY=replay-api-secret'); @@ -18,6 +23,7 @@ }); afterEach(function () { + rmdir($this->merchantProjectDirectory); foreach ([ 'QUICKPAY_API_KEY' => $this->originalApiKey, 'QUICKPAY_PRIVATE_KEY' => $this->originalPrivateKey, @@ -28,7 +34,7 @@ it('resolves an environment private key through the stateless provider without contacting Quickpay', function () { Http::fake(); - $quickpay = new QuickpayClient(app(Factory::class), 'api-key'); + $quickpay = new QuickpayClient(app(Factory::class), 'api-key', MerchantAccess::full()); $resolver = new PrivateKeyResolver(new AccountPrivateKeyFetcher, new EnvironmentVariables); expect($resolver->resolve($quickpay))->toBe('replay-private-key'); diff --git a/tests/Feature/Commands/Callbacks/WatchCallbacksCommandTest.php b/tests/Feature/Commands/Callbacks/WatchCallbacksCommandTest.php index b2986f0..b3b023f 100644 --- a/tests/Feature/Commands/Callbacks/WatchCallbacksCommandTest.php +++ b/tests/Feature/Commands/Callbacks/WatchCallbacksCommandTest.php @@ -11,6 +11,7 @@ use App\Commands\Payments\CapturePaymentCommand; use App\Commands\Payments\CreatePaymentLinkCommand; use App\Commands\Payments\RefundPaymentCommand; +use App\Credentials\ProjectMerchantFile; use App\Quickpay\QuickpayClient; use Illuminate\Contracts\Console\Kernel; use Illuminate\Http\Client\Factory; @@ -18,6 +19,9 @@ use Symfony\Component\Console\Tester\CommandTester; beforeEach(function () { + $this->merchantProjectDirectory = sys_get_temp_dir().'/quickpay-test-project-'.bin2hex(random_bytes(8)); + mkdir($this->merchantProjectDirectory, 0700, true); + app()->instance(ProjectMerchantFile::class, new ProjectMerchantFile($this->merchantProjectDirectory)); $this->originalApiKey = getenv('QUICKPAY_API_KEY'); $this->originalPrivateKey = getenv('QUICKPAY_PRIVATE_KEY'); putenv('QUICKPAY_API_KEY=watch-api-key'); @@ -25,6 +29,7 @@ }); afterEach(function () { + rmdir($this->merchantProjectDirectory); foreach ([ 'QUICKPAY_API_KEY' => $this->originalApiKey, 'QUICKPAY_PRIVATE_KEY' => $this->originalPrivateKey, diff --git a/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php b/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php new file mode 100644 index 0000000..8c8e6d3 --- /dev/null +++ b/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php @@ -0,0 +1,109 @@ +store->add('shop-a', 'fake/secret'); + Http::fake(['*' => Http::response(['message' => 'Rejected '.$form], 401)]); + [$exit, $stdout, $stderr] = merchantCommandResult(ActiveMerchantCommand::class, ['--check' => true, '--json' => true]); + expect($exit)->toBe(1)->and($stderr)->toContain('[redacted]') + ->and($stdout.$stderr)->not->toContain('fake/secret')->not->toContain($form); + expect(json_decode($stdout, true, flags: JSON_THROW_ON_ERROR)['authenticated'])->toBeFalse(); +})->with(['raw' => 'fake/secret', 'basic' => 'Basic '.base64_encode(':fake/secret'), 'url encoded' => 'fake%2Fsecret']); + +it('reports configuration without claiming unverified authentication', function (): void { + $this->store->add('shop-a', 'fake-secret-a'); + [$exit, $output, $errors] = merchantCommandResult(ActiveMerchantCommand::class, ['--json' => true]); + expect($exit)->toBe(0)->and($errors)->toBe('')->and(json_decode($output, true, flags: JSON_THROW_ON_ERROR))->toBe([ + 'merchant' => 'shop-a', 'selection_source' => 'default', 'credential_source' => 'config file', + 'configured' => true, 'read_only' => false, 'checked' => false, 'authenticated' => null, + 'api_base_url' => 'https://api.quickpay.net', 'api_version' => 'v10', 'scope' => null, + ]); + $this->artisan('merchants:active')->expectsOutputToContain('shop-a')->expectsOutputToContain('not checked')->doesntExpectOutputToContain('Access:')->assertExitCode(0); + Http::assertNothingSent(); +}); + +it('reports absent credentials and fails only a requested readiness check', function (): void { + [$exit, $output] = merchantCommandResult(ActiveMerchantCommand::class, ['--json' => true]); + expect($exit)->toBe(0)->and(json_decode($output, true)['configured'])->toBeFalse(); + [$exit, $output, $errors] = merchantCommandResult(ActiveMerchantCommand::class, ['--json' => true, '--check' => true]); + expect($exit)->toBe(1)->and($errors)->toContain('merchants:add') + ->and(json_decode($output, true)['authenticated'])->toBeFalse(); + Http::assertNothingSent(); +}); + +it('points to merchant selection when saved merchants have no default', function (): void { + $this->store->add('shop-a', 'fake-secret-a'); + $this->store->add('shop-b', 'fake-secret-b'); + $this->store->remove('shop-a'); + [$exit, $output, $errors] = merchantCommandResult(ActiveMerchantCommand::class, ['--check' => true]); + expect($exit)->toBe(1)->and($output)->toContain('Merchant: none')->not->toContain('API version') + ->and($errors)->toContain('merchants:select'); + Http::assertNothingSent(); +}); + +it('reports environment-only credentials without inferring a merchant label', function (): void { + putenv('QUICKPAY_API_KEY=fake-environment'); + [$exit, $output] = merchantCommandResult(ActiveMerchantCommand::class, ['--json' => true]); + $data = json_decode($output, true); + expect($exit)->toBe(0)->and($data['merchant'])->toBeNull()->and($data['selection_source'])->toBe('environment') + ->and($data['credential_source'])->toBe('environment')->and($data['authenticated'])->toBeNull() + ->and($data['read_only'])->toBeFalse(); + Http::assertNothingSent(); +}); + +it('checks the same explicitly selected key and keeps JSON stdout clean', function (): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['msg' => 'pong', 'scope' => 'merchant', 'version' => 'v10', 'params' => []])]); + $this->store->add('My Other Website', 'fake-secret-a'); + $this->store->add('My Website', 'fake-secret-b'); + [$exit, $output, $errors] = merchantCommandResult(ActiveMerchantCommand::class, ['--merchant' => 'My Website', '--check' => true, '--json' => true]); + $data = json_decode($output, true, flags: JSON_THROW_ON_ERROR); + expect($exit)->toBe(0)->and($errors)->toBe('')->and($data['authenticated'])->toBeTrue() + ->and($data['checked'])->toBeTrue()->and($data['scope'])->toBe('merchant')->and($data['merchant'])->toBe('My Website'); + Http::assertSentCount(1); + Http::assertSent(fn (Request $request): bool => $request->header('Authorization') === ['Basic '.base64_encode(':fake-secret-b')]); +}); + +it('fails invalid selection before writing status or making requests', function (bool $environment): void { + $this->store->add('shop-a', 'fake-secret-a'); + if ($environment) { + putenv('QUICKPAY_API_KEY=fake-environment'); + } + [$exit, $output, $errors] = merchantCommandResult(ActiveMerchantCommand::class, ['--merchant' => $environment ? 'shop-a' : 'shop-missing', '--json' => true]); + expect($exit)->toBe(1)->and($output)->toBe('')->and($errors)->not->toBe(''); + Http::assertNothingSent(); +})->with(['unknown' => false, 'conflict' => true]); + +it('rejects ambiguous configuration before checking API access', function (bool $project): void { + $this->store->add('shop-a', 'fake-first'); + $this->store->add('shop-b', 'fake-last'); + $path = $project ? getcwd().'/.quickpay-cli.json' : $this->store->path(); + $contents = $project + ? '{"merchant":"shop-a","merch\\u0061nt":"shop-b"}' + : '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","read_only":false},"sh\\u006fp-a":{"api_key":"fake-last","read_only":false}}}'; + file_put_contents($path, $contents); + Http::fake(['*' => Http::response(['scope' => 'merchant'])]); + [$exit, $output, $errors] = merchantCommandResult(ActiveMerchantCommand::class, ['--check' => true, '--json' => true]); + expect($exit)->toBe(1)->and($output)->toBe('')->and($errors)->not->toBe('') + ->and(file_get_contents($path))->toBe($contents); + Http::assertNothingSent(); +})->with(['store' => false, 'project' => true]); + +it('reports and still verifies a read-only merchant', function (): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); + $this->store->add('shop-a', 'fake-secret-a', readOnly: true); + [$exit, $output, $errors] = merchantCommandResult(ActiveMerchantCommand::class, ['--check' => true, '--json' => true]); + $data = json_decode($output, true, flags: JSON_THROW_ON_ERROR); + expect($exit)->toBe(0)->and($errors)->toBe('')->and($data['read_only'])->toBeTrue() + ->and($data['authenticated'])->toBeTrue(); + $this->artisan('merchants:active')->expectsOutputToContain('Access: read-only')->assertExitCode(0); + Http::assertSentCount(1); +}); + +it('reports no read_only flag when no credential is configured', function (): void { + [$exit, $output] = merchantCommandResult(ActiveMerchantCommand::class, ['--json' => true]); + $data = json_decode($output, true, flags: JSON_THROW_ON_ERROR); + expect($exit)->toBe(0)->and($data)->not->toHaveKey('write')->and($data['read_only'])->toBeNull(); +}); diff --git a/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php new file mode 100644 index 0000000..7876f24 --- /dev/null +++ b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php @@ -0,0 +1,149 @@ + Http::response(['msg' => 'pong', 'scope' => 'merchant', 'version' => 'v10', 'params' => []])]); + $this->artisan('merchants:add', ['name' => 'My Website']) + ->expectsQuestion('API key', ' fake-secret-a ') + ->expectsOutputToContain('Merchant saved: My Website') + ->doesntExpectOutputToContain('fake-secret-a')->assertExitCode(0); + expect($this->store->read()['merchants']['My Website']['api_key'])->toBe('fake-secret-a'); + Http::assertSentCount(1); + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://api.quickpay.net/ping' + && $request->method() === 'GET' && $request->header('Authorization') === ['Basic '.base64_encode(':fake-secret-a')]); +}); + +it('says when QUICKPAY_API_KEY still takes precedence over the saved merchant', function (bool $environment): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); + if ($environment) { + putenv('QUICKPAY_API_KEY=fake-environment'); + } + $command = $this->artisan('merchants:add', ['name' => 'My Website']) + ->expectsQuestion('API key', 'fake-secret-a') + ->expectsOutputToContain('Merchant saved: My Website'); + $environment + ? $command->expectsOutputToContain('QUICKPAY_API_KEY is set, so commands use it instead of your default merchant, and --merchant or a project binding fails.') + : $command->doesntExpectOutputToContain('QUICKPAY_API_KEY'); + $command->doesntExpectOutputToContain('fake-environment')->assertExitCode(0); +})->with(['environment key' => true, 'no environment key' => false]); + +it('tells upgraders that the old credential file is unused without reading it', function (): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); + $legacy = $this->tempDirectory.'/legacy-config.json'; + file_put_contents($legacy, '{"api_key":"fake-legacy-secret"}'); + $this->app->instance(MerchantStore::class, new MerchantStore($this->store->path(), $legacy)); + $this->artisan('merchants:add', ['name' => 'My Website']) + ->expectsQuestion('API key', 'fake-secret-a') + ->expectsOutputToContain('no longer uses') + ->doesntExpectOutputToContain('fake-legacy-secret')->assertExitCode(0); + expect(file_get_contents($legacy))->toBe('{"api_key":"fake-legacy-secret"}'); +}); + +it('rejects duplicate and invalid names before prompting', function (string $name): void { + $this->store->add('shop-a', 'fake-original'); + $before = file_get_contents($this->store->path()); + $this->artisan('merchants:add', ['name' => $name])->assertExitCode(1); + Http::assertNothingSent(); + expect(file_get_contents($this->store->path()))->toBe($before); +})->with(['duplicate' => 'shop-a', 'case variant' => 'Shop-A', 'path' => '../secret', 'leading space' => ' My Website']); + +it('replaces a credential only after successful validation', function (): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['msg' => 'pong', 'scope' => 'merchant', 'version' => 'v10', 'params' => []])]); + $this->store->add('shop-a', 'fake-original'); + $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true]) + ->expectsQuestion('API key', 'fake-replacement')->assertExitCode(0); + expect($this->store->read()['merchants']['shop-a']['api_key'])->toBe('fake-replacement'); +}); + +it('refuses to replace an unsaved merchant before prompting', function (): void { + $this->store->add('My Website', 'fake-original'); + $before = file_get_contents($this->store->path()); + $this->artisan('merchants:add', ['name' => 'My Webiste', '--replace' => true]) + ->expectsOutputToContain('not saved')->assertExitCode(1); + Http::assertNothingSent(); + expect(file_get_contents($this->store->path()))->toBe($before); +}); + +it('preserves the original credential after a rejected replacement', function (): void { + $this->store->add('shop-a', 'fake-original'); + Http::fake(['*' => Http::response(['message' => 'fake-rejected'], 401)]); + $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true]) + ->expectsQuestion('API key', 'fake-rejected')->doesntExpectOutputToContain('fake-rejected')->assertExitCode(1); + expect($this->store->read()['merchants']['shop-a']['api_key'])->toBe('fake-original'); +}); + +it('requires interactive input before requesting credentials', function (bool $interactive): void { + if ($interactive) { + app()->instance(StdinTerminalDetector::class, new class implements StdinTerminalDetector + { + public function isTty(): bool + { + return false; + } + }); + } + $this->artisan('merchants:add', ['name' => 'shop-a', '--no-interaction' => ! $interactive])->assertExitCode(1); + Http::assertNothingSent(); + expect(file_exists($this->store->path()))->toBeFalse(); +})->with(['not interactive' => false, 'not a tty' => true]); + +it('rejects blank keys and secret labels before HTTP', function (string $name, string $key): void { + $this->artisan('merchants:add', ['name' => $name])->expectsQuestion('API key', $key)->assertExitCode(1); + Http::assertNothingSent(); + expect(file_exists($this->store->path()))->toBeFalse(); +})->with(['blank' => ['shop-a', ' '], 'label' => ['secret-name', 'secret']]); + +it('rejects malformed merchant scope without saving or reflecting secrets', function (mixed $response): void { + Http::fake(['*' => Http::response($response)]); + $this->artisan('merchants:add', ['name' => 'shop-a'])->expectsQuestion('API key', 'fake-secret-a') + ->doesntExpectOutputToContain('fake-secret-a')->assertExitCode(1); + expect(file_exists($this->store->path()))->toBeFalse(); +})->with(['non-json' => 'not json', 'missing' => [[]], 'other scope' => [['scope' => 'user']], 'reflected' => [['scope' => 'fake-secret-a']]]); + +it('does not render a reflected version after successful validation', function (): void { + Http::fake(['*' => Http::response(['scope' => 'merchant', 'version' => 'fake-secret-a'])]); + $this->artisan('merchants:add', ['name' => 'shop-a'])->expectsQuestion('API key', 'fake-secret-a') + ->doesntExpectOutputToContain('fake-secret-a')->assertExitCode(0); +}); + +it('handles network failure without leaking or storing credentials', function (): void { + Http::fake(fn () => throw new ConnectionException('Network failure fake-secret-a')); + $this->artisan('merchants:add', ['name' => 'shop-a'])->expectsQuestion('API key', 'fake-secret-a') + ->expectsOutputToContain('Unable to connect to Quickpay')->doesntExpectOutputToContain('fake-secret-a')->assertExitCode(1); + expect(file_exists($this->store->path()))->toBeFalse(); +}); + +it('saves a merchant as read-only when asked', function (array $flags, array $saved, ?string $label): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); + $command = $this->artisan('merchants:add', ['name' => 'shop-a', ...$flags]) + ->expectsQuestion('API key', 'fake-secret-a'); + $label === null ? $command->doesntExpectOutputToContain('Access:') : $command->expectsOutputToContain('Access: '.$label); + $command->assertExitCode(0)->run(); + expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-secret-a', ...$saved]); + Http::assertSentCount(1); +})->with([ + 'default' => [[], ['read_only' => false], null], + 'read-only' => [['--read-only' => true], ['read_only' => true], 'read-only'], +]); + +it('keeps a read-only merchant read-only when replacing its credential', function (): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); + $this->store->add('shop-a', 'fake-original', readOnly: true); + $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true]) + ->expectsQuestion('API key', 'fake-replacement')->expectsOutputToContain('Access: read-only')->assertExitCode(0); + expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'read_only' => true]); +}); + +it('makes a merchant read-only when replacing its credential with the flag', function (): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); + $this->store->add('shop-a', 'fake-original'); + $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true, '--read-only' => true]) + ->expectsQuestion('API key', 'fake-replacement') + ->expectsOutputToContain('Access: read-only')->assertExitCode(0); + expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'read_only' => true]); +}); diff --git a/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php b/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php new file mode 100644 index 0000000..14ac053 --- /dev/null +++ b/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php @@ -0,0 +1,41 @@ +store->add('My Website', 'fake-secret-b'); + $this->store->add('My Other Website', 'fake-secret-a'); + [$exit, $output, $errors] = merchantCommandResult(ListMerchantsCommand::class, ['--json' => true]); + expect($exit)->toBe(0)->and($errors)->toBe('')->and(json_decode($output, true, flags: JSON_THROW_ON_ERROR)) + ->toBe([['name' => 'My Other Website', 'default' => false, 'read_only' => false], ['name' => 'My Website', 'default' => true, 'read_only' => false]]); + Http::assertNothingSent(); +}); + +it('lists an empty store without contacting Quickpay', function (): void { + [$exit, $output] = merchantCommandResult(ListMerchantsCommand::class, ['--json' => true]); + expect($exit)->toBe(0)->and($output)->toBe('[]'); + Http::assertNothingSent(); +}); + +it('never lists labels that expose another saved API key', function (): void { + file_put_contents($this->store->path(), '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-secret-a","read_only":false},"fake-secret-a":{"api_key":"fake-secret-b","read_only":false}}}'); + [$exit, $output, $errors] = merchantCommandResult(ListMerchantsCommand::class, ['--json' => true]); + expect($exit)->toBe(1)->and($output)->toBe('') + ->and($errors)->not->toContain('fake-secret-a', 'fake-secret-b'); + Http::assertNothingSent(); +}); + +it('shows access only when a merchant is read-only', function (): void { + $this->store->add('shop-a', 'fake-secret-a'); + $this->store->add('shop-b', 'fake-secret-b', readOnly: true); + [$exit, $output] = merchantCommandResult(ListMerchantsCommand::class, ['--json' => true]); + expect($exit)->toBe(0)->and(json_decode($output, true, flags: JSON_THROW_ON_ERROR))->toBe([ + ['name' => 'shop-a', 'default' => true, 'read_only' => false], + ['name' => 'shop-b', 'default' => false, 'read_only' => true], + ]); + [$exit, $output] = merchantCommandResult(ListMerchantsCommand::class); + expect($exit)->toBe(0)->and($output)->toContain('Access')->toContain('read-only') + ->not->toContain('read and write'); + Http::assertNothingSent(); +}); diff --git a/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php b/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php new file mode 100644 index 0000000..9af8540 --- /dev/null +++ b/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php @@ -0,0 +1,23 @@ +store->add('My Other Website', 'fake-secret-a'); + $this->store->add('My Website', 'fake-secret-b'); + $this->artisan('merchants:remove', ['name' => 'My Other Website']) + ->expectsOutputToContain('merchants:select')->assertExitCode(0); + expect($this->store->read())->toBe(['default_merchant' => null, 'merchants' => ['My Website' => ['api_key' => 'fake-secret-b', 'read_only' => false]]]); + $this->artisan('merchants:remove', ['name' => 'shop-missing'])->assertExitCode(1); + $this->artisan('merchants:remove', ['name' => 'My Website'])->assertExitCode(0); + expect($this->store->read()['merchants'])->toBe([]); + Http::assertNothingSent(); +}); + +it('explains that environment credentials remain after local removal', function (): void { + $this->store->add('shop-a', 'fake-secret-a'); + putenv('QUICKPAY_API_KEY=fake-environment'); + $this->artisan('merchants:remove', ['name' => 'shop-a'])->expectsOutputToContain('QUICKPAY_API_KEY remains configured')->assertExitCode(0); + expect(getenv('QUICKPAY_API_KEY'))->toBe('fake-environment'); + Http::assertNothingSent(); +}); diff --git a/tests/Feature/Commands/Merchants/SelectMerchantCommandTest.php b/tests/Feature/Commands/Merchants/SelectMerchantCommandTest.php new file mode 100644 index 0000000..dcccbb5 --- /dev/null +++ b/tests/Feature/Commands/Merchants/SelectMerchantCommandTest.php @@ -0,0 +1,85 @@ +store->add('My Other Website', 'fake-secret-a'); + $this->store->add('My Website', 'fake-secret-b'); + $this->artisan('merchants:select', ['name' => 'My Website'])->assertExitCode(0); + expect($this->store->read()['default_merchant'])->toBe('My Website'); + Http::assertNothingSent(); +}); + +it('rejects multiple merchant names without changing selection', function (): void { + $this->store->add('shop-a', 'fake-secret-a'); + $before = file_get_contents($this->store->path()); + $this->artisan('merchants:select', ['name' => ['shop-a', 'shop-b']])->assertExitCode(1); + expect(file_get_contents($this->store->path()))->toBe($before); + Http::assertNothingSent(); +}); + +it('offers a sorted merchant picker with cancellation', function (string $selection): void { + $this->store->add('shop-a', 'fake-secret-a'); + $this->store->add('shop-b', 'fake-secret-b'); + $this->store->add('Cancel', 'fake-cancel-key'); + $this->artisan('merchants:select')->expectsChoice('Select merchant', $selection, ['Cancel', 'shop-a', 'shop-b', '[Cancel]'])->assertExitCode(0); + expect($this->store->read()['default_merchant'])->toBe($selection === '[Cancel]' ? 'shop-a' : $selection); + Http::assertNothingSent(); +})->with(['selection' => 'shop-b', 'merchant named Cancel' => 'Cancel', 'cancel' => '[Cancel]']); + +it('selects a project merchant without changing the global default', function (): void { + $this->store->add('My Other Website', 'fake-secret-a'); + $this->store->add('My Website', 'fake-secret-b'); + $this->artisan('merchants:select', ['name' => 'My Website', '--local' => true])->assertExitCode(0); + chdir($this->tempDirectory.'/project/nested'); + [$exit, $output] = merchantCommandResult(ActiveMerchantCommand::class, ['--json' => true]); + expect($exit)->toBe(0)->and(json_decode($output, true)['merchant'])->toBe('My Website') + ->and($this->store->read()['default_merchant'])->toBe('My Other Website'); + mkdir($this->tempDirectory.'/other'); + chdir($this->tempDirectory.'/other'); + [$exit, $output] = merchantCommandResult(ActiveMerchantCommand::class, ['--json' => true]); + expect(json_decode($output, true)['merchant'])->toBe('My Other Website'); + Http::assertNothingSent(); +}); + +it('says when a project binding still outranks the new global default', function (): void { + $this->store->add('shop-a', 'fake-secret-a'); + $this->store->add('shop-b', 'fake-secret-b'); + $this->artisan('merchants:select', ['name' => 'shop-a', '--local' => true])->assertExitCode(0); + $this->artisan('merchants:select', ['name' => 'shop-b']) + ->expectsOutputToContain('Global default merchant selected: shop-b') + ->expectsOutputToContain('Commands in this folder still use shop-a from the nearest .quickpay-cli.json.') + ->assertExitCode(0); + $this->artisan('merchants:select', ['name' => 'shop-a']) + ->doesntExpectOutputToContain('still use') + ->assertExitCode(0); + Http::assertNothingSent(); +}); + +it('warns when the project binding names a merchant that is no longer saved', function (): void { + $this->store->add('shop-a', 'fake-secret-a'); + $this->store->add('shop-b', 'fake-secret-b'); + $this->artisan('merchants:select', ['name' => 'shop-a', '--local' => true])->assertExitCode(0); + $this->store->remove('shop-a'); + $this->artisan('merchants:select', ['name' => 'shop-b']) + ->expectsOutputToContain('Commands in this folder fail until you fix the nearest .quickpay-cli.json: it selects shop-a, which is not saved.') + ->doesntExpectOutputToContain('still use') + ->assertExitCode(0); +}); + +it('rejects environment overrides before changing selection', function (bool $named): void { + $this->store->add('shop-a', 'fake-secret-a'); + putenv('QUICKPAY_API_KEY=fake-environment'); + $before = file_get_contents($this->store->path()); + $this->artisan('merchants:select', $named ? ['name' => 'shop-a'] : []) + ->expectsOutputToContain('QUICKPAY_API_KEY')->assertExitCode(1); + expect(file_get_contents($this->store->path()))->toBe($before); + Http::assertNothingSent(); +})->with(['named' => true, 'picker' => false]); + +it('rejects empty unknown and unattended picker selections', function (array $arguments): void { + $this->artisan('merchants:select', $arguments)->assertExitCode(1); + expect(file_exists($this->store->path()))->toBeFalse(); + Http::assertNothingSent(); +})->with(['empty' => [[]], 'unknown' => [['name' => 'shop-missing']], 'unattended' => [['--no-interaction' => true]]]); diff --git a/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php b/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php new file mode 100644 index 0000000..c4a3cfa --- /dev/null +++ b/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php @@ -0,0 +1,88 @@ +store->add('shop-a', 'fake-secret-a'); + $this->artisan('merchants:access', ['name' => 'shop-a', '--read-only' => true, '--no-interaction' => true]) + ->expectsOutputToContain('Access for shop-a: read-only')->assertExitCode(0); + expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-secret-a', 'read_only' => true]); + Http::assertNothingSent(); +}); + +it('allows what is already allowed without asking or writing', function (): void { + $this->store->add('shop-a', 'fake-secret-a'); + $before = file_get_contents($this->store->path()); + $this->artisan('merchants:access', ['name' => 'shop-a', '--read-write' => true, '--no-interaction' => true]) + ->expectsOutputToContain('Access for shop-a: read and write')->assertExitCode(0); + expect(file_get_contents($this->store->path()))->toBe($before); +}); + +it('allows writes again only after an interactive confirmation', function (): void { + $this->store->add('shop-a', 'fake-secret-a', readOnly: true); + $this->artisan('merchants:access', ['name' => 'shop-a', '--read-write' => true]) + ->expectsConfirmation('Allow write requests for shop-a?', 'yes') + ->expectsOutputToContain('Access for shop-a: read and write')->assertExitCode(0); + expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-secret-a', 'read_only' => false]); +}); + +it('names the protection read-only', function (string $command, array $options): void { + $definition = Artisan::all()[$command]->getDefinition(); + $flags = array_keys(array_filter($definition->getOptions(), fn ($option): bool => in_array($option->getName(), ['read-only', 'read-write', 'write', 'read'], true))); + expect($flags)->toBe($options)->and($definition->hasNegation('write'))->toBeFalse(); +})->with([ + 'access' => ['merchants:access', ['read-only', 'read-write']], + 'add allows no writes again' => ['merchants:add', ['read-only']], +]); + +it('refuses both flags at once without writing', function (): void { + $this->store->add('shop-a', 'fake-secret-a', readOnly: true); + $before = file_get_contents($this->store->path()); + $this->artisan('merchants:access', ['name' => 'shop-a', '--read-only' => true, '--read-write' => true]) + ->expectsOutputToContain('Choose either --read-only or --read-write.')->assertExitCode(1); + expect(file_get_contents($this->store->path()))->toBe($before); +}); + +it('leaves access unchanged when the confirmation is declined', function (): void { + $this->store->add('shop-a', 'fake-secret-a', readOnly: true); + $before = file_get_contents($this->store->path()); + $this->artisan('merchants:access', ['name' => 'shop-a', '--read-write' => true]) + ->expectsConfirmation('Allow write requests for shop-a?', 'no') + ->expectsOutputToContain('Cancelled')->assertExitCode(0); + expect(file_get_contents($this->store->path()))->toBe($before); +}); + +it('refuses to allow requests without an interactive terminal', function (bool $tty): void { + if ($tty) { + app()->instance(StdinTerminalDetector::class, new class implements StdinTerminalDetector + { + public function isTty(): bool + { + return false; + } + }); + } + $this->store->add('shop-a', 'fake-secret-a', readOnly: true); + $before = file_get_contents($this->store->path()); + $this->artisan('merchants:access', ['name' => 'shop-a', '--read-write' => true, '--no-interaction' => ! $tty]) + ->expectsOutputToContain('interactive terminal')->assertExitCode(1); + expect(file_get_contents($this->store->path()))->toBe($before); +})->with(['not interactive' => false, 'not a tty' => true]); + +it('shows the current access when no flag is given', function (): void { + $this->store->add('shop-a', 'fake-secret-a', readOnly: true); + $before = file_get_contents($this->store->path()); + $this->artisan('merchants:access', ['name' => 'shop-a', '--no-interaction' => true]) + ->expectsOutputToContain('Access for shop-a: read-only')->assertExitCode(0); + expect(file_get_contents($this->store->path()))->toBe($before); +}); + +it('rejects unsaved and invalid names without writing', function (string $name): void { + $this->store->add('shop-a', 'fake-secret-a'); + $before = file_get_contents($this->store->path()); + $this->artisan('merchants:access', ['name' => $name, '--read-only' => true])->assertExitCode(1); + expect(file_get_contents($this->store->path()))->toBe($before); + Http::assertNothingSent(); +})->with(['unsaved' => 'shop-b', 'invalid' => '../shop-a']); diff --git a/tests/Feature/Commands/Payments/CreatePaymentCommandTest.php b/tests/Feature/Commands/Payments/CreatePaymentCommandTest.php index 5a5d701..5bb7f58 100644 --- a/tests/Feature/Commands/Payments/CreatePaymentCommandTest.php +++ b/tests/Feature/Commands/Payments/CreatePaymentCommandTest.php @@ -1,16 +1,21 @@ merchantProjectDirectory = sys_get_temp_dir().'/quickpay-test-project-'.bin2hex(random_bytes(8)); + mkdir($this->merchantProjectDirectory, 0700, true); + app()->instance(ProjectMerchantFile::class, new ProjectMerchantFile($this->merchantProjectDirectory)); $this->originalApiKey = getenv('QUICKPAY_API_KEY'); putenv('QUICKPAY_API_KEY=create-secret'); }); afterEach(function () { + rmdir($this->merchantProjectDirectory); if ($this->originalApiKey === false) { putenv('QUICKPAY_API_KEY'); } else { diff --git a/tests/Feature/Commands/Payments/CreatePaymentLinkCommandTest.php b/tests/Feature/Commands/Payments/CreatePaymentLinkCommandTest.php index 5a206d0..1865b22 100644 --- a/tests/Feature/Commands/Payments/CreatePaymentLinkCommandTest.php +++ b/tests/Feature/Commands/Payments/CreatePaymentLinkCommandTest.php @@ -1,16 +1,21 @@ merchantProjectDirectory = sys_get_temp_dir().'/quickpay-test-project-'.bin2hex(random_bytes(8)); + mkdir($this->merchantProjectDirectory, 0700, true); + app()->instance(ProjectMerchantFile::class, new ProjectMerchantFile($this->merchantProjectDirectory)); $this->originalApiKey = getenv('QUICKPAY_API_KEY'); putenv('QUICKPAY_API_KEY=link-secret'); }); afterEach(function () { + rmdir($this->merchantProjectDirectory); if ($this->originalApiKey === false) { putenv('QUICKPAY_API_KEY'); } else { diff --git a/tests/Feature/Commands/Payments/GetPaymentCommandTest.php b/tests/Feature/Commands/Payments/GetPaymentCommandTest.php index 1449896..cf9eb5c 100644 --- a/tests/Feature/Commands/Payments/GetPaymentCommandTest.php +++ b/tests/Feature/Commands/Payments/GetPaymentCommandTest.php @@ -1,16 +1,21 @@ merchantProjectDirectory = sys_get_temp_dir().'/quickpay-test-project-'.bin2hex(random_bytes(8)); + mkdir($this->merchantProjectDirectory, 0700, true); + app()->instance(ProjectMerchantFile::class, new ProjectMerchantFile($this->merchantProjectDirectory)); $this->originalApiKey = getenv('QUICKPAY_API_KEY'); putenv('QUICKPAY_API_KEY=get-secret'); }); afterEach(function () { + rmdir($this->merchantProjectDirectory); if ($this->originalApiKey === false) { putenv('QUICKPAY_API_KEY'); } else { diff --git a/tests/Feature/Commands/Payments/ListPaymentsCommandTest.php b/tests/Feature/Commands/Payments/ListPaymentsCommandTest.php index 20eca2b..998cb02 100644 --- a/tests/Feature/Commands/Payments/ListPaymentsCommandTest.php +++ b/tests/Feature/Commands/Payments/ListPaymentsCommandTest.php @@ -2,18 +2,23 @@ use App\Commands\Payments\ListPaymentsCommand; use App\Credentials\ApiKeyResolver; -use App\Credentials\CredentialFile; use App\Credentials\EnvironmentVariables; +use App\Credentials\MerchantStore; +use App\Credentials\ProjectMerchantFile; use Illuminate\Http\Client\Request; use Illuminate\Support\Facades\Http; use Symfony\Component\Console\Tester\CommandTester; beforeEach(function () { + $this->merchantProjectDirectory = sys_get_temp_dir().'/quickpay-test-project-'.bin2hex(random_bytes(8)); + mkdir($this->merchantProjectDirectory, 0700, true); + app()->instance(ProjectMerchantFile::class, new ProjectMerchantFile($this->merchantProjectDirectory)); $this->originalApiKey = getenv('QUICKPAY_API_KEY'); putenv('QUICKPAY_API_KEY=list-secret'); }); afterEach(function () { + rmdir($this->merchantProjectDirectory); if ($this->originalApiKey === false) { putenv('QUICKPAY_API_KEY'); } else { @@ -355,15 +360,15 @@ [['--max-pages' => 'nope'], 'max-pages'], ]); -it('fails safely with a login hint when credentials are missing', function () { +it('fails safely with a merchant setup hint when credentials are missing', function () { putenv('QUICKPAY_API_KEY'); - $file = new CredentialFile(sys_get_temp_dir().'/missing-quickpay-'.bin2hex(random_bytes(6)).'.json'); - app()->instance(CredentialFile::class, $file); - app()->instance(ApiKeyResolver::class, new ApiKeyResolver(new EnvironmentVariables, $file)); + $file = new MerchantStore(sys_get_temp_dir().'/missing-quickpay-'.bin2hex(random_bytes(6)).'.json'); + app()->instance(MerchantStore::class, $file); + app()->instance(ApiKeyResolver::class, new ApiKeyResolver(new EnvironmentVariables, $file, app(ProjectMerchantFile::class))); Http::fake(); $this->artisan('payments:list') - ->expectsOutputToContain('quickpay login') + ->expectsOutputToContain('quickpay merchants:add ') ->assertExitCode(1); Http::assertNothingSent(); diff --git a/tests/Feature/Commands/Payments/PaymentMutationCommandsTest.php b/tests/Feature/Commands/Payments/PaymentMutationCommandsTest.php index 3d81cf9..b70bdc0 100644 --- a/tests/Feature/Commands/Payments/PaymentMutationCommandsTest.php +++ b/tests/Feature/Commands/Payments/PaymentMutationCommandsTest.php @@ -4,11 +4,15 @@ use App\Commands\Payments\CapturePaymentCommand; use App\Commands\Payments\RefundPaymentCommand; use App\Console\Terminal\StdinTerminalDetector; +use App\Credentials\ProjectMerchantFile; use Illuminate\Http\Client\Request; use Illuminate\Support\Facades\Http; use Symfony\Component\Console\Tester\CommandTester; beforeEach(function () { + $this->merchantProjectDirectory = sys_get_temp_dir().'/quickpay-test-project-'.bin2hex(random_bytes(8)); + mkdir($this->merchantProjectDirectory, 0700, true); + app()->instance(ProjectMerchantFile::class, new ProjectMerchantFile($this->merchantProjectDirectory)); $this->originalApiKey = getenv('QUICKPAY_API_KEY'); putenv('QUICKPAY_API_KEY=mutation-secret'); app()->instance(StdinTerminalDetector::class, new class implements StdinTerminalDetector @@ -21,6 +25,7 @@ public function isTty(): bool }); afterEach(function () { + rmdir($this->merchantProjectDirectory); if ($this->originalApiKey === false) { putenv('QUICKPAY_API_KEY'); } else { diff --git a/tests/Feature/Console/AuthenticatedCommandTest.php b/tests/Feature/Console/AuthenticatedCommandTest.php new file mode 100644 index 0000000..d74966e --- /dev/null +++ b/tests/Feature/Console/AuthenticatedCommandTest.php @@ -0,0 +1,327 @@ +directory = sys_get_temp_dir().'/quickpay-command-selection-'.bin2hex(random_bytes(8)); + mkdir($this->directory, 0700, true); + $this->originalApiKey = getenv('QUICKPAY_API_KEY'); + $this->originalPrivateKey = getenv('QUICKPAY_PRIVATE_KEY'); + putenv('QUICKPAY_API_KEY'); + putenv('QUICKPAY_PRIVATE_KEY=fake-signing-key'); + $this->store = new MerchantStore($this->directory.'/config.json'); + $this->store->add('shop-a', 'fake-secret-a'); + $this->store->add('shop-b', 'fake-secret-b'); + $this->project = new ProjectMerchantFile($this->directory); + app()->instance(MerchantStore::class, $this->store); + app()->instance(ProjectMerchantFile::class, $this->project); + app()->instance(ApiKeyResolver::class, new ApiKeyResolver(new EnvironmentVariables, $this->store, $this->project)); + app()->instance(StdinTerminalDetector::class, new class implements StdinTerminalDetector + { + public function isTty(): bool + { + return true; + } + }); + Http::preventStrayRequests(); +}); + +afterEach(function (): void { + foreach (['QUICKPAY_API_KEY' => $this->originalApiKey, 'QUICKPAY_PRIVATE_KEY' => $this->originalPrivateKey] as $name => $value) { + $value === false ? putenv($name) : putenv($name.'='.$value); + } + foreach (glob($this->directory.'/*') as $file) { + unlink($file); + } + rmdir($this->directory); +}); + +it('identifies the selected merchant in payment confirmation without changing response JSON', function (string $class, string $operation, array $arguments, bool $json, bool $yes): void { + $raw = '{"id":42,"state":"processed","custom":"unchanged"}'; + Http::fake([ + 'https://api.quickpay.net/payments/42' => Http::response(['id' => 42, 'merchant_id' => 123, 'order_id' => 'order-42', 'currency' => 'DKK', 'state' => 'authorized', 'accepted' => true, 'balance' => 2000]), + 'https://api.quickpay.net/payments/42/'.$operation => Http::response($raw), + ]); + $command = new $class; + $command->setLaravel(app()); + $tester = new CommandTester($command); + $tester->setInputs(['yes']); + $exit = $tester->execute([...$arguments, '--merchant' => 'shop-b', '--json' => $json, '--yes' => $yes], ['capture_stderr_separately' => true]); + $summary = $json ? $tester->getErrorOutput() : $tester->getDisplay(); + expect($exit)->toBe(0)->and($summary)->toContain('Merchant: shop-b')->toContain('Credential source: config file')->toContain('Merchant ID: 123'); + if ($json) { + expect($tester->getDisplay())->toBe($raw); + } + $requests = Http::recorded(); + expect($requests)->toHaveCount(2)->and($requests[0][0]->method())->toBe('GET')->and($requests[1][0]->method())->toBe('POST'); + foreach ($requests as [$request]) { + expect($request->header('Authorization'))->toBe(['Basic '.base64_encode(':fake-secret-b')]); + } +})->with([ + 'capture JSON yes' => [CapturePaymentCommand::class, 'capture', ['id' => '42', 'amount' => '1250'], true, true], + 'capture JSON confirmation' => [CapturePaymentCommand::class, 'capture', ['id' => '42', 'amount' => '1250'], true, false], + 'capture human confirmation' => [CapturePaymentCommand::class, 'capture', ['id' => '42', 'amount' => '1250'], false, false], + 'refund JSON yes' => [RefundPaymentCommand::class, 'refund', ['id' => '42', 'amount' => '1250'], true, true], + 'cancel JSON yes' => [CancelPaymentCommand::class, 'cancel', ['id' => '42'], true, true], +]); + +it('keeps the inspected merchant pinned when its saved credential changes before mutation', function (): void { + $store = $this->store; + Http::fake(function (Request $request) use ($store) { + if ($request->method() === 'GET') { + $store->select('shop-a'); + $store->remove('shop-b'); + } + + return Http::response(['id' => 42, 'merchant_id' => 123, 'state' => 'processed']); + }); + $this->artisan('payments:capture', ['id' => '42', 'amount' => '1250', '--merchant' => 'shop-b', '--yes' => true, '--json' => true])->assertExitCode(0); + Http::assertSentCount(2); + foreach (Http::recorded() as [$request]) { + expect($request->header('Authorization'))->toBe(['Basic '.base64_encode(':fake-secret-b')]); + } +}); + +it('never mutates after declining a selected merchant confirmation', function (): void { + Http::fake(['*' => Http::response(['id' => 42, 'merchant_id' => 123])]); + $command = new CapturePaymentCommand; + $command->setLaravel(app()); + $tester = new CommandTester($command); + $tester->setInputs(['no']); + expect($tester->execute(['id' => '42', 'amount' => '1250', '--merchant' => 'shop-b', '--json' => true], ['capture_stderr_separately' => true]))->toBe(0) + ->and($tester->getDisplay())->toBe('')->and($tester->getErrorOutput())->toContain('Merchant: shop-b')->toContain('Cancelled'); + Http::assertSentCount(1); + Http::assertNotSent(fn (Request $request): bool => $request->method() !== 'GET'); +}); + +it('identifies a selected merchant before confirming a raw mutation', function (): void { + $raw = '{"id":42,"state":"captured"}'; + Http::fake(['*' => Http::response($raw)]); + $command = new ApiRequestCommand; + $command->setLaravel(app()); + $tester = new CommandTester($command); + $tester->setInputs(['yes']); + expect($tester->execute(['method' => 'POST', 'path' => '/payments/42/capture', '--merchant' => 'shop-b', '--json' => true], ['capture_stderr_separately' => true]))->toBe(0) + ->and($tester->getDisplay())->toBe($raw)->and($tester->getErrorOutput())->toContain('Merchant: shop-b')->toContain('Credential source: config file')->toContain('Continue?'); + expect(strpos($tester->getErrorOutput(), 'Merchant:'))->toBeLessThan(strpos($tester->getErrorOutput(), 'Continue?')); + Http::assertSent(fn (Request $request): bool => $request->header('Authorization') === ['Basic '.base64_encode(':fake-secret-b')]); +}); + +it('identifies the selected merchant before creating remote payment state', function (string $class, array $arguments, string $path, string $raw): void { + Http::fake(['https://api.quickpay.net'.$path => Http::response($raw)]); + $command = new $class; + $command->setLaravel(app()); + $tester = new CommandTester($command); + expect($tester->execute([...$arguments, '--merchant' => 'shop-b', '--json' => true], ['capture_stderr_separately' => true]))->toBe(0) + ->and($tester->getDisplay())->toBe($raw) + ->and($tester->getErrorOutput())->toContain('Merchant: shop-b')->toContain('Credential source: config file'); +})->with([ + 'create' => [CreatePaymentCommand::class, ['order-id' => 'order-42'], '/payments', '{"id":42}'], + 'link' => [CreatePaymentLinkCommand::class, ['id' => '42', 'amount' => '1000'], '/payments/42/link', '{"url":"https://payment.quickpay.net/link/abc"}'], +]); + +it('selects the same saved key for every other authenticated command family', function (string $command, array $arguments, string $path, mixed $body): void { + Http::fake([ + 'https://api.quickpay.net'.$path.'*' => Http::response($body), + 'http://localhost/callback' => Http::response('', 204), + ]); + $this->artisan($command, [...$arguments, '--merchant' => 'shop-b', '--json' => true])->assertExitCode(0); + Http::assertSent(fn (Request $request): bool => str_starts_with($request->url(), 'https://api.quickpay.net'.$path) + && $request->header('Authorization') === ['Basic '.base64_encode(':fake-secret-b')]); + Http::assertNotSent(fn (Request $request): bool => $request->url() === 'http://localhost/callback' && $request->hasHeader('Authorization')); +})->with([ + 'create' => ['payments:create', ['order-id' => 'order-42'], '/payments', ['id' => 42]], + 'get' => ['payments:get', ['id' => '42'], '/payments/42', ['id' => 42]], + 'link' => ['payments:link', ['id' => '42', 'amount' => '1000'], '/payments/42/link', ['url' => 'https://payment.quickpay.net/link/abc']], + 'list' => ['payments:list', [], '/payments', [['id' => 42]]], + 'raw GET' => ['api', ['method' => 'GET', 'path' => '/payments/42'], '/payments/42', ['id' => 42]], + 'replay' => ['callbacks:replay', ['payment-id' => '42', '--to' => 'http://localhost/callback'], '/payments/42', ['id' => 42, 'merchant_id' => 123, 'order_id' => 'order-42', 'operations' => []]], +]); + +it('rejects unresolved or conflicting merchant selection before HTTP', function (string $command, array $arguments, bool $environment): void { + if ($environment) { + putenv('QUICKPAY_API_KEY=fake-environment'); + } + Http::fake(); + $this->artisan($command, [...$arguments, '--merchant' => $environment ? 'shop-b' : 'shop-missing'])->assertExitCode(1); + Http::assertNothingSent(); +})->with([ + 'capture unknown' => ['payments:capture', ['id' => '42', 'amount' => '1250', '--yes' => true], false], + 'raw conflict' => ['api', ['method' => 'POST', 'path' => '/payments/42/capture', '--yes' => true], true], + 'watch unknown' => ['callbacks:watch', ['--to' => 'http://localhost/callback'], false], + 'replay conflict' => ['callbacks:replay', ['payment-id' => '42', '--to' => 'http://localhost/callback'], true], +]); + +it('keeps scoped and account-wide watchers pinned after selection and removal', function (bool $scoped): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); + app()->instance(CallbackWatcherFactory::class, new class($this->store) extends CallbackWatcherFactory + { + public function __construct(private MerchantStore $store) {} + + public function make(QuickpayClient $quickpay, Factory $http): CallbackWatcher + { + return new class($quickpay, $this->store) implements CallbackWatcher + { + public function __construct(private QuickpayClient $quickpay, private MerchantStore $store) {} + + public function run(?string $paymentId, ?string $orderId, CallbackTarget $target, string $apiKey, string $privateKey, int $interval, int $deliveryAttempts, Closure $observer): void + { + $this->store->select('shop-a'); + $this->store->remove('shop-b'); + $this->quickpay->get('/ping'); + $this->quickpay->get('/ping'); + if ($paymentId === null) { + $observer('watching-all', ['ready_at' => '2026-09-30T10:00:00+00:00']); + } + } + }; + } + }); + $command = new WatchCallbacksCommand; + $command->setLaravel(app()); + $tester = new CommandTester($command); + expect($tester->execute(['--merchant' => 'shop-b', '--to' => 'http://localhost/callback', ...($scoped ? ['payment-id' => '42'] : [])]))->toBe(0) + ->and($tester->getDisplay())->toContain('Merchant: shop-b')->toContain('Credential source: config file'); + Http::assertSentCount(2); + foreach (Http::recorded() as [$request]) { + expect($request->header('Authorization'))->toBe(['Basic '.base64_encode(':fake-secret-b')]); + } +})->with(['scoped' => true, 'account-wide' => false]); + +it('blocks writes for a read-only merchant before any request or confirmation', function (string $class, array $arguments, string $method): void { + $this->store->add('shop-r', 'fake-secret-r', readOnly: true); + Http::fake(); + $command = new $class; + $command->setLaravel(app()); + $tester = new CommandTester($command); + $exit = $tester->execute([...$arguments, '--merchant' => 'shop-r'], ['capture_stderr_separately' => true]); + expect($exit)->toBe(1) + ->and(preg_replace('/\s+/', ' ', $tester->getErrorOutput()))->toContain("is read-only, so the {$method} request was not sent") + ->and($tester->getDisplay().$tester->getErrorOutput())->not->toContain('Continue?')->not->toContain('fake-secret-r'); + Http::assertNothingSent(); +})->with([ + 'capture' => [CapturePaymentCommand::class, ['id' => '42', 'amount' => '1250'], 'POST'], + 'refund' => [RefundPaymentCommand::class, ['id' => '42', 'amount' => '1250'], 'POST'], + 'cancel' => [CancelPaymentCommand::class, ['id' => '42'], 'POST'], + 'create' => [CreatePaymentCommand::class, ['order-id' => 'order-42'], 'POST'], + 'link' => [CreatePaymentLinkCommand::class, ['id' => '42', 'amount' => '1000'], 'PUT'], + 'raw POST' => [ApiRequestCommand::class, ['method' => 'POST', 'path' => '/payments/42/capture'], 'POST'], + 'raw PUT' => [ApiRequestCommand::class, ['method' => 'put', 'path' => '/payments/42/link'], 'PUT'], + 'raw PATCH' => [ApiRequestCommand::class, ['method' => 'PATCH', 'path' => '/payments/42'], 'PATCH'], + 'raw DELETE' => [ApiRequestCommand::class, ['method' => 'DELETE', 'path' => '/payments/42/link'], 'DELETE'], +]); + +it('still reads through a read-only merchant', function (string $command, array $arguments, string $path, mixed $body): void { + $this->store->add('shop-r', 'fake-secret-r', readOnly: true); + Http::fake([ + 'https://api.quickpay.net'.$path.'*' => Http::response($body), + 'http://localhost/callback' => Http::response('', 204), + ]); + $this->artisan($command, [...$arguments, '--merchant' => 'shop-r', '--json' => true])->assertExitCode(0); + Http::assertSent(fn (Request $request): bool => str_starts_with($request->url(), 'https://api.quickpay.net'.$path) + && $request->method() === 'GET'); + Http::assertNotSent(fn (Request $request): bool => str_starts_with($request->url(), 'https://api.quickpay.net') && $request->method() !== 'GET'); +})->with([ + 'get' => ['payments:get', ['id' => '42'], '/payments/42', ['id' => 42]], + 'list' => ['payments:list', [], '/payments', [['id' => 42]]], + 'raw GET' => ['api', ['method' => 'GET', 'path' => '/payments/42'], '/payments/42', ['id' => 42]], + 'replay to a local handler' => ['callbacks:replay', ['payment-id' => '42', '--to' => 'http://localhost/callback'], '/payments/42', ['id' => 42, 'merchant_id' => 123, 'order_id' => 'order-42', 'operations' => []]], +]); + +it('warns when QUICKPAY_PRIVATE_KEY signs replayed callbacks for a saved merchant', function (bool $json): void { + Http::fake([ + 'https://api.quickpay.net/payments/42*' => Http::response(['id' => 42, 'merchant_id' => 123, 'order_id' => 'order-42', 'operations' => []]), + 'http://localhost/callback' => Http::response('', 204), + ]); + $command = new ReplayCallbackCommand; + $command->setLaravel(app()); + $tester = new CommandTester($command); + $exit = $tester->execute(['payment-id' => '42', '--to' => 'http://localhost/callback', '--merchant' => 'shop-b', '--json' => $json], ['capture_stderr_separately' => true]); + $warnings = $json ? $tester->getErrorOutput() : $tester->getDisplay(); + expect($exit)->toBe(0) + ->and($warnings)->toContain('Warning: QUICKPAY_PRIVATE_KEY is set, so callbacks are signed with it instead of the account private key of shop-b. Unset it if it belongs to another merchant.') + ->and($tester->getDisplay().$tester->getErrorOutput())->not->toContain('fake-signing-key'); + if ($json) { + expect(json_decode($tester->getDisplay(), true, flags: JSON_THROW_ON_ERROR)['success'])->toBeTrue(); + } + Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/account/private-key')); +})->with(['human' => false, 'JSON' => true]); + +it('warns before watching when QUICKPAY_PRIVATE_KEY signs callbacks for a saved merchant', function (): void { + app()->instance(CallbackWatcherFactory::class, new class extends CallbackWatcherFactory + { + public function __construct() {} + + public function make(QuickpayClient $quickpay, Factory $http): CallbackWatcher + { + return new class implements CallbackWatcher + { + public function run(?string $paymentId, ?string $orderId, CallbackTarget $target, string $apiKey, string $privateKey, int $interval, int $deliveryAttempts, Closure $observer): void {} + }; + } + }); + $this->artisan('callbacks:watch', ['payment-id' => '42', '--to' => 'http://localhost/callback']) + ->expectsOutputToContain('Merchant: shop-a') + ->expectsOutputToContain('Warning: QUICKPAY_PRIVATE_KEY is set, so callbacks are signed with it instead of the account private key of shop-a.') + ->assertExitCode(0); + Http::assertNothingSent(); +}); + +it('does not warn about the private key when it cannot belong to another saved merchant', function (bool $environmentApiKey): void { + if ($environmentApiKey) { + putenv('QUICKPAY_API_KEY=fake-environment'); + } else { + putenv('QUICKPAY_PRIVATE_KEY'); + } + Http::fake([ + 'https://api.quickpay.net/payments/42*' => Http::response(['id' => 42, 'merchant_id' => 123, 'order_id' => 'order-42', 'operations' => []]), + 'https://api.quickpay.net/account/private-key' => Http::response(['private_key' => 'fake-account-signing-key']), + 'http://localhost/callback' => Http::response('', 204), + ]); + $command = new ReplayCallbackCommand; + $command->setLaravel(app()); + $tester = new CommandTester($command); + expect($tester->execute(['payment-id' => '42', '--to' => 'http://localhost/callback'], ['capture_stderr_separately' => true]))->toBe(0) + ->and($tester->getDisplay().$tester->getErrorOutput())->not->toContain('QUICKPAY_PRIVATE_KEY'); +})->with(['environment API key' => true, 'saved merchant fetching its own key' => false]); + +it('uses QUICKPAY_API_KEY and reports a clean error when no home folder is set', function (): void { + $saved = ['HOME' => getenv('HOME'), 'USERPROFILE' => getenv('USERPROFILE')]; + putenv('HOME'); + putenv('USERPROFILE'); + putenv('QUICKPAY_API_KEY=fake-environment'); + try { + $store = MerchantStore::inHome(new HomeDirectory(new EnvironmentVariables)); + app()->instance(MerchantStore::class, $store); + app()->instance(ApiKeyResolver::class, new ApiKeyResolver(new EnvironmentVariables, $store, $this->project)); + Http::fake(['https://api.quickpay.net/ping' => Http::response(['msg' => 'pong'])]); + $this->artisan('api', ['method' => 'GET', 'path' => '/ping', '--json' => true])->assertExitCode(0); + Http::assertSentCount(1); + $this->artisan('merchants:list')->expectsOutputToContain('Unable to locate the home directory')->assertExitCode(1); + } finally { + foreach ($saved as $name => $value) { + $value === false ? putenv($name) : putenv("{$name}={$value}"); + } + } +}); diff --git a/tests/Feature/Quickpay/AuthenticatedQuickpayFactoryTest.php b/tests/Feature/Quickpay/AuthenticatedQuickpayFactoryTest.php new file mode 100644 index 0000000..3965447 --- /dev/null +++ b/tests/Feature/Quickpay/AuthenticatedQuickpayFactoryTest.php @@ -0,0 +1,34 @@ +add('shop-a', 'fake-secret-a'); + $store->add('shop-b', 'fake-secret-b'); + $factory = new AuthenticatedQuickpayFactory(Http::getFacadeRoot(), new ApiKeyResolver(new EnvironmentVariables, $store, new ProjectMerchantFile($directory))); + $authenticated = $factory->resolve('shop-b'); + $store->remove('shop-b'); + Http::fake(['*' => Http::response(['scope' => 'merchant'])]); + $authenticated->client->get('/ping'); + expect($authenticated->apiKey->merchant())->toBe('shop-b')->and($authenticated->apiKey->selectionSource())->toBe('explicit'); + Http::assertSent(fn (Request $request): bool => $request->header('Authorization') === ['Basic '.base64_encode(':fake-secret-b')]); + } finally { + $original === false ? putenv('QUICKPAY_API_KEY') : putenv('QUICKPAY_API_KEY='.$original); + foreach (glob($directory.'/*') as $file) { + unlink($file); + } + rmdir($directory); + } +}); diff --git a/tests/Feature/Quickpay/MerchantAuthenticationCheckTest.php b/tests/Feature/Quickpay/MerchantAuthenticationCheckTest.php new file mode 100644 index 0000000..4b5787e --- /dev/null +++ b/tests/Feature/Quickpay/MerchantAuthenticationCheckTest.php @@ -0,0 +1,14 @@ + Http::response(['scope' => 'user'])]); + expect(fn () => (new MerchantAuthenticationCheck(app(AuthenticatedQuickpayFactory::class)))->check(new ApiKey('fake-key', 'provided', MerchantAccess::full()))) + ->toThrow(UnexpectedValueException::class, 'merchant'); + Http::assertSentCount(1); +}); diff --git a/tests/Feature/Quickpay/Payments/PaymentServicesTest.php b/tests/Feature/Quickpay/Payments/PaymentServicesTest.php index df8a00f..cdd7707 100644 --- a/tests/Feature/Quickpay/Payments/PaymentServicesTest.php +++ b/tests/Feature/Quickpay/Payments/PaymentServicesTest.php @@ -1,5 +1,6 @@ Http::response([['id' => 2]]), ]); - $api = new PaymentApi(new QuickpayClient(app(Factory::class), 'api-key')); + $api = new PaymentApi(new QuickpayClient(app(Factory::class), 'api-key', MerchantAccess::full())); expect((new PaymentPaginator($api))->all(['page_size' => 1], 2)) ->toBe([['id' => 1], ['id' => 2]]); @@ -27,7 +28,7 @@ it('fetches context before confirmation and never mutates when declined', function (): void { Http::fake(['https://api.quickpay.net/payments/42' => Http::response(['id' => 42])]); - $api = new PaymentApi(new QuickpayClient(app(Factory::class), 'api-key')); + $api = new PaymentApi(new QuickpayClient(app(Factory::class), 'api-key', MerchantAccess::full())); $result = (new PaymentMutation($api))->execute( id: 42, @@ -48,7 +49,7 @@ 'https://api.quickpay.net/payments/42' => Http::response(['id' => 42]), 'https://api.quickpay.net/payments/42/capture' => Http::response(['id' => 42, 'state' => 'processed']), ]); - $api = new PaymentApi(new QuickpayClient(app(Factory::class), 'api-key')); + $api = new PaymentApi(new QuickpayClient(app(Factory::class), 'api-key', MerchantAccess::full())); $result = (new PaymentMutation($api))->execute( id: 42, diff --git a/tests/Feature/Quickpay/QuickpayClientTest.php b/tests/Feature/Quickpay/QuickpayClientTest.php index ec17b0d..613e30f 100644 --- a/tests/Feature/Quickpay/QuickpayClientTest.php +++ b/tests/Feature/Quickpay/QuickpayClientTest.php @@ -1,5 +1,7 @@ Http::response(['scope' => 'merchant'])]); - $client = new QuickpayClient(app(Factory::class), 'test-secret'); + $client = new QuickpayClient(app(Factory::class), 'test-secret', MerchantAccess::full()); $response = $client->get('/ping', ['probe' => 'yes'], [], ['X-Test' => 'allowed']); expect($response->successful())->toBeTrue(); @@ -26,11 +28,11 @@ }); }); -it('supports each required http method without retrying mutations', function (string $method) { +it('supports each raw http method without retrying mutations', function (string $method) { Http::fake(['https://api.quickpay.net/resources*' => Http::response(['ok' => true])]); - $client = new QuickpayClient(app(Factory::class), 'secret'); - $response = $client->{strtolower($method)}('/resources', ['page' => 2], ['name' => 'Example']); + $client = new QuickpayClient(app(Factory::class), 'secret', MerchantAccess::full()); + $response = $client->raw($method, '/resources', ['page' => 2], ['name' => 'Example']); expect($response->successful())->toBeTrue(); @@ -46,14 +48,14 @@ return Http::response(['ok' => true]); }); - $client = new QuickpayClient(app(Factory::class), 'secret'); + $client = new QuickpayClient(app(Factory::class), 'secret', MerchantAccess::full()); $client->get('/ping'); expect($requestOptions)->toBeArray() ->and($requestOptions['timeout'] ?? null)->toBe(30); }); -it('does not retry a failed mutation', function (string $method) { +it('does not retry a failed raw mutation', function (string $method) { $attempts = 0; Http::fake(function () use (&$attempts) { $attempts++; @@ -61,9 +63,9 @@ throw new ConnectionException('Mutation failed'); }); - $client = new QuickpayClient(app(Factory::class), 'secret'); + $client = new QuickpayClient(app(Factory::class), 'secret', MerchantAccess::full()); - expect(fn () => $client->{strtolower($method)}('/resources', data: ['name' => 'Example'])) + expect(fn () => $client->raw($method, '/resources', data: ['name' => 'Example'])) ->toThrow(QuickpayRequestException::class); expect($attempts)->toBe(1); })->with(['POST', 'PUT', 'PATCH', 'DELETE']); @@ -71,7 +73,7 @@ it('rejects unvalidated absolute urls', function () { Http::fake(); - $client = new QuickpayClient(app(Factory::class), 'secret'); + $client = new QuickpayClient(app(Factory::class), 'secret', MerchantAccess::full()); expect(fn () => $client->get('https://example.com/payments')) ->toThrow(InvalidArgumentException::class, 'relative'); @@ -82,7 +84,7 @@ it('prevents mixed-case extra headers from overriding request security', function (string $header) { Http::fake(); - $client = new QuickpayClient(app(Factory::class), 'secret'); + $client = new QuickpayClient(app(Factory::class), 'secret', MerchantAccess::full()); expect(fn () => $client->get('/ping', headers: [$header => 'override'])) ->toThrow(InvalidArgumentException::class, 'cannot be overridden'); @@ -93,7 +95,7 @@ it('turns connection failures into a safe exception', function () { Http::fake(fn () => throw new ConnectionException('Failed using test-secret')); - $client = new QuickpayClient(app(Factory::class), 'test-secret'); + $client = new QuickpayClient(app(Factory::class), 'test-secret', MerchantAccess::full()); try { $client->get('/ping'); @@ -105,3 +107,29 @@ ->and($exception->getPrevious())->toBeNull(); } }); + +it('sends no write request from a read-only merchant', function (string $method): void { + Http::fake(); + $client = new QuickpayClient(app(Factory::class), 'test-secret', new MerchantAccess(readOnly: true)); + + expect(fn () => $client->raw($method, '/payments/42', data: ['amount' => 1000])) + ->toThrow(MerchantAccessException::class, 'is read-only, so the '.strtoupper($method).' request was not sent.'); + Http::assertNothingSent(); +})->with(['POST', 'PUT', 'PATCH', 'delete']); + +it('applies write protection to first-class requests', function (): void { + Http::fake(['https://api.quickpay.net/payments*' => Http::response(['id' => 42])]); + $readOnly = new QuickpayClient(app(Factory::class), 'test-secret', new MerchantAccess(readOnly: true)); + + expect($readOnly->get('/payments/42')->successful())->toBeTrue() + ->and($readOnly->raw('GET', '/payments/42')->successful())->toBeTrue() + ->and(fn () => $readOnly->post('/payments'))->toThrow(MerchantAccessException::class) + ->and(fn () => $readOnly->put('/payments/42/link'))->toThrow(MerchantAccessException::class); + expect(Http::recorded())->toHaveCount(2) + ->and(Http::recorded()[0][0]->method())->toBe('GET') + ->and(Http::recorded()[1][0]->method())->toBe('GET'); +}); + +it('never treats blocked access as a retryable request failure', function (): void { + expect(is_subclass_of(MerchantAccessException::class, QuickpayRequestException::class))->toBeFalse(); +}); diff --git a/tests/Integration/Credentials/CredentialFileTest.php b/tests/Integration/Credentials/CredentialFileTest.php deleted file mode 100644 index 68fd57c..0000000 --- a/tests/Integration/Credentials/CredentialFileTest.php +++ /dev/null @@ -1,70 +0,0 @@ -tempDirectory = sys_get_temp_dir().'/quickpay-file-'.bin2hex(random_bytes(8)); - mkdir($this->tempDirectory, 0700, true); - $this->path = $this->tempDirectory.'/nested/config.json'; -}); - -afterEach(function (): void { - if (! is_dir($this->tempDirectory)) { - return; - } - - $iterator = new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($this->tempDirectory, FilesystemIterator::SKIP_DOTS), - RecursiveIteratorIterator::CHILD_FIRST, - ); - - foreach ($iterator as $item) { - $item->isDir() ? rmdir($item->getPathname()) : unlink($item->getPathname()); - } - - rmdir($this->tempDirectory); -}); - -it('atomically persists and reads a credential with restrictive modes', function (): void { - $file = new CredentialFile($this->path); - $file->save('stored-secret'); - clearstatcache(true, $this->path); - - expect($file->read())->toBe('stored-secret') - ->and(fileperms(dirname($this->path)) & 0777)->toBe(0700) - ->and(fileperms($this->path) & 0777)->toBe(0600) - ->and(glob(dirname($this->path).'/.config.json.*'))->toBe([]); -}); - -it('rejects malformed credential files', function (string $contents): void { - mkdir(dirname($this->path), 0700, true); - file_put_contents($this->path, $contents); - - expect(fn (): ?string => (new CredentialFile($this->path))->read()) - ->toThrow(CredentialException::class, 'Quickpay credential file is invalid'); -})->with([ - '{"api_key":', - '{"other":"value"}', - '{"api_key":123}', - '{"api_key":""}', -]); - -it('forgets only the stored credential', function (): void { - $file = new CredentialFile($this->path); - $file->save('stored-key'); - - expect($file->forget())->toBeTrue() - ->and($file->forget())->toBeFalse(); -}); - -it('never includes the credential in persistence errors', function (): void { - mkdir($this->path, 0700, true); - - try { - (new CredentialFile($this->path))->save('highly-sensitive-key'); - $this->fail('Expected credential storage to fail.'); - } catch (CredentialException $exception) { - expect($exception->getMessage())->not->toContain('highly-sensitive-key'); - } -}); diff --git a/tests/Integration/Credentials/MerchantStoreTest.php b/tests/Integration/Credentials/MerchantStoreTest.php new file mode 100644 index 0000000..3d6e19b --- /dev/null +++ b/tests/Integration/Credentials/MerchantStoreTest.php @@ -0,0 +1,348 @@ +tempDirectory = sys_get_temp_dir().'/quickpay-merchants-'.bin2hex(random_bytes(8)); + mkdir($this->tempDirectory, 0700, true); + $this->path = $this->tempDirectory.'/nested/config.json'; +}); + +afterEach(function (): void { + $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->tempDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST); + foreach ($files as $file) { + $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); + } + rmdir($this->tempDirectory); +}); + +it('keeps the first default when adding another merchant', function (): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-secret-a'); + $store->add('shop-b', 'fake-secret-b'); + expect($store->read())->toBe([ + 'default_merchant' => 'shop-a', + 'merchants' => ['shop-a' => ['api_key' => 'fake-secret-a', 'read_only' => false], 'shop-b' => ['api_key' => 'fake-secret-b', 'read_only' => false]], + ]); +}); + +it('does not silently choose a default after removing it', function (): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-secret-a'); + $store->add('shop-b', 'fake-secret-b'); + $store->remove('shop-a'); + $store->add('shop-c', 'fake-secret-c'); + expect($store->read()['default_merchant'])->toBeNull() + ->and(array_keys($store->read()['merchants']))->toBe(['shop-b', 'shop-c']); +}); + +it('retains existing credentials on duplicate or invalid additions', function (string $name, string $key): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-original'); + $before = file_get_contents($this->path); + expect(fn () => $store->add($name, $key))->toThrow(CredentialException::class); + expect(file_get_contents($this->path))->toBe($before); +})->with(['duplicate' => ['shop-a', 'fake-new'], 'empty key' => ['shop-b', ' '], 'secret label' => ['secret-name', 'secret']]); + +it('rejects a new name that differs from a saved one only in capitalization', function (): void { + $store = new MerchantStore($this->path); + $store->add('My Website', 'fake-original'); + $before = file_get_contents($this->path); + expect(fn () => $store->add('my website', 'fake-new'))->toThrow(CredentialException::class, 'different capitalization'); + expect(file_get_contents($this->path))->toBe($before); + $store->add('My Website', 'fake-replacement', true); + expect($store->read()['merchants']['My Website']['api_key'])->toBe('fake-replacement'); +}); + +it('does not treat a replacement of an unsaved merchant as an addition', function (): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-original'); + $before = file_get_contents($this->path); + expect(fn () => $store->add('shop-b', 'fake-new', true))->toThrow(CredentialException::class, 'not saved'); + expect(file_get_contents($this->path))->toBe($before); +}); + +it('replaces only the explicitly named credential', function (): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-secret-a'); + $store->add('shop-b', 'fake-secret-b'); + $store->add('shop-b', ' fake-replacement ', true); + expect($store->read())->toBe([ + 'default_merchant' => 'shop-a', + 'merchants' => ['shop-a' => ['api_key' => 'fake-secret-a', 'read_only' => false], 'shop-b' => ['api_key' => 'fake-replacement', 'read_only' => false]], + ]); +}); + +it('rejects labels colliding with any saved credential without changing storage', function (bool $incomingKey): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-secret-a'); + $before = file_get_contents($this->path); + expect(fn () => $store->add($incomingKey ? 'shop-b' : 'fake-secret-a', $incomingKey ? 'shop-a' : 'fake-secret-b')) + ->toThrow(CredentialException::class); + expect(file_get_contents($this->path))->toBe($before); +})->with(['new label contains old key' => false, 'new key matches old label' => true]); + +it('writes object-shaped empty storage and restrictive modes', function (): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-secret-a'); + $store->remove('shop-a'); + clearstatcache(); + $decoded = json_decode(file_get_contents($this->path), flags: JSON_THROW_ON_ERROR); + expect($decoded->merchants)->toBeInstanceOf(stdClass::class) + ->and($decoded->default_merchant)->toBeNull() + ->and(fileperms(dirname($this->path)) & 0777)->toBe(0700) + ->and(fileperms($this->path) & 0777)->toBe(0600) + ->and(fileperms($this->path.'.lock') & 0777)->toBe(0600) + ->and(glob(dirname($this->path).'/.config.json.*'))->toBe([]); +}); + +it('rejects invalid storage without treating it as empty', function (string $contents): void { + mkdir(dirname($this->path), 0700, true); + file_put_contents($this->path, $contents); + $store = new MerchantStore($this->path); + foreach ([fn () => $store->read(), fn () => $store->add('shop-a', 'fake-new'), fn () => $store->select('shop-a'), fn () => $store->remove('shop-a')] as $action) { + expect($action)->toThrow(CredentialException::class); + expect(file_get_contents($this->path))->toBe($contents); + } +})->with([ + 'broken' => '{broken', 'root list' => '[]', 'missing' => '{}', + 'merchant list' => '{"default_merchant":null,"merchants":[]}', + 'numeric key' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":123,"read_only":false}}}', + 'empty key' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":" ","read_only":false}}}', + 'invalid name' => '{"default_merchant":null,"merchants":{"../a":{"api_key":"fake-key","read_only":false}}}', + 'dangling default' => '{"default_merchant":"shop-a","merchants":{}}', + 'old shape' => '{"api_key":"fake-legacy"}', + 'secret label' => '{"default_merchant":null,"merchants":{"secret-name":{"api_key":"secret","read_only":false}}}', + 'duplicate merchant' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","read_only":false},"shop-a":{"api_key":"fake-last","read_only":false}}}', + 'escaped duplicate merchant' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","read_only":false},"sh\\u006fp-a":{"api_key":"fake-last","read_only":false}}}', + 'duplicate key' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","api_key":"fake-last","read_only":false}}}', + 'duplicate default' => '{"default_merchant":"shop-a","default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-first","read_only":false}}}', + 'missing read_only flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key"}}}', + 'string read_only flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","read_only":"true"}}}', + 'write flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","write":true}}}', + 'null read_only flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","read_only":null}}}', + 'extra merchant field' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","read_only":false,"note":"x"}}}', + 'duplicate read_only flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","read_only":true,"read_only":false}}}', +]); + +it('explains a missing read_only flag without revealing the credential', function (): void { + mkdir(dirname($this->path), 0700, true); + file_put_contents($this->path, '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-secret-a"}}}'); + expect(fn () => (new MerchantStore($this->path))->read()) + ->toThrow(CredentialException::class, 'a true or false read_only flag'); +}); + +it('saves the read_only flag for a new merchant and defaults to full access', function (): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-secret-a'); + $store->add('shop-b', 'fake-secret-b', readOnly: true); + expect($store->read()['merchants'])->toBe([ + 'shop-a' => ['api_key' => 'fake-secret-a', 'read_only' => false], + 'shop-b' => ['api_key' => 'fake-secret-b', 'read_only' => true], + ]); +}); + +it('keeps a read-only merchant read-only when replacing its credential', function (): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-original', readOnly: true); + $store->add('shop-a', 'fake-replacement', true); + expect($store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'read_only' => true]); + $store->add('shop-a', 'fake-second', true, readOnly: false); + expect($store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-second', 'read_only' => true]); +}); + +it('makes a merchant read-only when replacing its credential with the flag', function (): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-original'); + expect($store->add('shop-a', 'fake-replacement', true, readOnly: true)->readOnly)->toBeTrue() + ->and($store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'read_only' => true]); +}); + +it('changes only the read_only flag and keeps the credential', function (): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-secret-a'); + $store->add('shop-b', 'fake-secret-b'); + expect($store->changeAccess('shop-a', false)->readOnly)->toBeFalse() + ->and($store->changeAccess('shop-a', true)->readOnly)->toBeTrue() + ->and($store->read())->toBe([ + 'default_merchant' => 'shop-a', + 'merchants' => [ + 'shop-a' => ['api_key' => 'fake-secret-a', 'read_only' => true], + 'shop-b' => ['api_key' => 'fake-secret-b', 'read_only' => false], + ], + ]); +}); + +it('refuses to change access for an unsaved merchant without writing', function (string $name): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-secret-a'); + $before = file_get_contents($this->path); + expect(fn () => $store->changeAccess($name, readOnly: true))->toThrow(CredentialException::class); + expect(file_get_contents($this->path))->toBe($before); +})->with(['unsaved' => 'shop-b', 'invalid' => '../shop-a']); + +it('does not mistake quoted key-like credential content for JSON properties', function (): void { + $key = 'fake-{"same":1,"same":2}-[]'; + $store = new MerchantStore($this->path); + $store->add('shop-a', $key); + expect($store->read()['merchants']['shop-a']['api_key'])->toBe($key); +}); + +it('does not read old namespaced storage', function (): void { + $old = $this->tempDirectory.'/.config/quickpay/config.json'; + mkdir(dirname($old), 0700, true); + file_put_contents($old, '{"api_key":"fake-legacy"}'); + $store = MerchantStore::inHome(new HomeDirectory(new EnvironmentVariables, $this->tempDirectory)); + expect($store->path())->toBe($this->tempDirectory.'/.config/quickpay-cli/config.json') + ->and($store->read())->toBe(['default_merchant' => null, 'merchants' => []]) + ->and($store->leftoverLegacyCredential())->toBe($old) + ->and(file_get_contents($old))->toBe('{"api_key":"fake-legacy"}'); + unlink($old); + expect($store->leftoverLegacyCredential())->toBeNull() + ->and((new MerchantStore($this->path))->leftoverLegacyCredential())->toBeNull(); +}); + +it('rejects unknown select and remove targets', function (): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-secret-a'); + $store->add('shop-b', 'fake-secret-b'); + $before = file_get_contents($this->path); + expect(fn () => $store->select('shop-c'))->toThrow(CredentialException::class); + expect(fn () => $store->remove('shop-c'))->toThrow(CredentialException::class); + expect(file_get_contents($this->path))->toBe($before); + $store->select('shop-b'); + $store->remove('shop-a'); + expect($store->read()['default_merchant'])->toBe('shop-b'); +}); + +it('preserves simultaneous writer updates', function (): void { + $store = new MerchantStore($this->path); + $store->add('initial', 'fake-initial'); + $script = $this->tempDirectory.'/writer.php'; + file_put_contents($script, <<<'PHP' + add($name, 'fake-key-'.$name); + } + PHP); + $processes = []; + try { + foreach (['left', 'right'] as $name) { + $process = proc_open([PHP_BINARY, $script, base_path('vendor/autoload.php'), $this->path, $name], [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); + $processes[] = [$process, $pipes]; + stream_set_timeout($pipes[1], 5); + expect(fgets($pipes[1]))->toBe("ready\n"); + } + foreach ($processes as [$process, $pipes]) { + fwrite($pipes[0], "go\n"); + fclose($pipes[0]); + } + foreach ($processes as [$process, $pipes]) { + stream_get_contents($pipes[1]); + expect(stream_get_meta_data($pipes[1])['timed_out'])->toBeFalse(); + expect(proc_close($process))->toBe(0); + } + $saved = $store->read()['merchants']; + expect($saved)->toHaveCount(31); + foreach (['left', 'right'] as $name) { + for ($i = 0; $i < 15; $i++) { + expect($saved[$name.'-'.$i]['api_key'])->toBe('fake-key-'.$name.'-'.$i); + } + } + } finally { + foreach ($processes as [$process, $pipes]) { + if (is_resource($process)) { + proc_terminate($process); + proc_close($process); + } + foreach ($pipes as $pipe) { + if (is_resource($pipe)) { + fclose($pipe); + } + } + } + } +}); + +it('waits on a stable lock during replacement', function (): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-secret-a'); + $lock = fopen($this->path.'.lock', 'c'); + flock($lock, LOCK_EX); + $script = $this->tempDirectory.'/locked-writer.php'; + file_put_contents($script, <<<'PHP' + add('shop-b', 'fake-secret-b'); + echo "done\n"; + PHP); + $process = proc_open([PHP_BINARY, $script, base_path('vendor/autoload.php'), $this->path], [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); + try { + stream_set_timeout($pipes[1], 5); + expect(fgets($pipes[1]))->toBe("ready\n"); + $read = [$pipes[1]]; + $write = $except = []; + expect(stream_select($read, $write, $except, 0, 50000))->toBe(0); + file_put_contents($this->path.'.replacement', '{"default_merchant":"shop-c","merchants":{"shop-c":{"api_key":"fake-secret-c","read_only":false}}}'); + rename($this->path.'.replacement', $this->path); + flock($lock, LOCK_UN); + expect(fgets($pipes[1]))->toBe("done\n") + ->and(proc_close($process))->toBe(0) + ->and(array_keys($store->read()['merchants']))->toBe(['shop-c', 'shop-b']); + } finally { + flock($lock, LOCK_UN); + fclose($lock); + if (is_resource($process)) { + proc_terminate($process); + proc_close($process); + } + foreach ($pipes as $pipe) { + if (is_resource($pipe)) { + fclose($pipe); + } + } + } +}); + +it('keeps persistence errors free of credentials', function (): void { + mkdir($this->path, 0700, true); + try { + (new MerchantStore($this->path))->add('shop-a', 'fake-sensitive'); + $this->fail('Expected persistence to fail'); + } catch (CredentialException $exception) { + expect($exception->getMessage())->not->toContain('fake-sensitive'); + } +}); + +it('looks up the home folder only when the configuration is used', function (): void { + $saved = ['HOME' => getenv('HOME'), 'USERPROFILE' => getenv('USERPROFILE')]; + putenv('HOME'); + putenv('USERPROFILE'); + try { + $store = MerchantStore::inHome(new HomeDirectory(new EnvironmentVariables)); + expect(fn () => $store->read())->toThrow(CredentialException::class, 'Unable to locate the home directory'); + } finally { + foreach ($saved as $name => $value) { + $value === false ? putenv($name) : putenv("{$name}={$value}"); + } + } +}); + +it('names the file in configuration errors that point at stored content', function (string $contents, string $message): void { + mkdir(dirname($this->path), 0700, true); + file_put_contents($this->path, $contents); + expect(fn () => (new MerchantStore($this->path))->read()) + ->toThrow(CredentialException::class, "Quickpay CLI merchant configuration {$this->path} {$message}"); +})->with([ + 'single-key file' => ['{"api_key":"fake-key"}', 'uses the unsupported single-key format'], + 'invalid merchant name' => ['{"default_merchant":null,"merchants":{" shop":{"api_key":"fake-key","read_only":false}}}', 'contains an invalid merchant name. Merchant names must start with a letter'], +]); diff --git a/tests/Integration/Credentials/ProjectMerchantFileTest.php b/tests/Integration/Credentials/ProjectMerchantFileTest.php new file mode 100644 index 0000000..a3380b9 --- /dev/null +++ b/tests/Integration/Credentials/ProjectMerchantFileTest.php @@ -0,0 +1,110 @@ +tempDirectory = sys_get_temp_dir().'/quickpay-project-'.bin2hex(random_bytes(8)); + mkdir($this->tempDirectory.'/nested', 0700, true); + $this->tempDirectory = realpath($this->tempDirectory); +}); + +afterEach(function (): void { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->tempDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { + $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); + } + rmdir($this->tempDirectory); +}); + +it('resolves the nearest binding from nested directories', function (): void { + $parent = new ProjectMerchantFile($this->tempDirectory); + $child = new ProjectMerchantFile($this->tempDirectory.'/nested'); + $parent->save('shop-a'); + expect($child->find())->toBe('shop-a'); + $child->save('shop-b'); + expect($child->find())->toBe('shop-b') + ->and($parent->find())->toBe('shop-a') + ->and(json_decode(file_get_contents($this->tempDirectory.'/nested/.quickpay-cli.json'), true))->toBe(['merchant' => 'shop-b']) + ->and(glob($this->tempDirectory.'/nested/..quickpay-cli.json.*'))->toBe([]); +}); + +it('rejects malformed nearest bindings without falling back or overwriting', function (string $contents): void { + (new ProjectMerchantFile($this->tempDirectory))->save('shop-a'); + $path = $this->tempDirectory.'/nested/.quickpay-cli.json'; + file_put_contents($path, $contents); + $file = new ProjectMerchantFile($this->tempDirectory.'/nested'); + expect(fn () => $file->find())->toThrow(CredentialException::class, $path); + expect(fn () => $file->save('shop-b'))->toThrow(CredentialException::class); + expect(file_get_contents($path))->toBe($contents); +})->with([ + 'broken' => '{broken', 'list' => '[]', 'numeric' => '{"merchant":123}', 'missing' => '{}', + 'secret' => '{"merchant":"shop-a","api_key":"fake-secret"}', + 'url' => '{"merchant":"shop-a","url":"https://other.test"}', + 'headers' => '{"merchant":"shop-a","headers":{}}', 'invalid name' => '{"merchant":" My Website"}', + 'duplicate selector' => '{"merchant":"shop-a","merchant":"shop-b"}', + 'escaped duplicate selector' => '{"merchant":"shop-a","merch\\u0061nt":"shop-b"}', +]); + +it('names a repeated property as the possible cause of an unreadable binding', function (): void { + file_put_contents($this->tempDirectory.'/.quickpay-cli.json', '{"merchant":"shop-a","merchant":"shop-b"}'); + expect(fn () => (new ProjectMerchantFile($this->tempDirectory))->find()) + ->toThrow(CredentialException::class, 'repeats a property'); +}); + +it('rejects an ancestor binding owned by another user', function (): void { + (new ProjectMerchantFile($this->tempDirectory))->save('shop-a'); + $otherUser = fileowner($this->tempDirectory.'/.quickpay-cli.json') + 1; + expect(fn () => (new ProjectMerchantFile($this->tempDirectory.'/nested', $otherUser))->find()) + ->toThrow(CredentialException::class, 'not owned by the current user'); +}); + +it('rejects a binding symlink owned by another user even when its target matches', function (): void { + // A root-owned target stands in for "this user's file": the link itself is + // owned by the test user, so only an lstat owner check can reject it. + $target = '/etc/hosts'; + symlink($target, $this->tempDirectory.'/.quickpay-cli.json'); + expect(fn () => (new ProjectMerchantFile($this->tempDirectory.'/nested', fileowner($target)))->find()) + ->toThrow(CredentialException::class, 'not owned by the current user'); +})->skip(fn (): bool => ! is_file('/etc/hosts') + || ! function_exists('posix_geteuid') + || fileowner('/etc/hosts') === posix_geteuid(), 'needs a readable file owned by another user'); + +it('accepts a binding symlink owned by the current user', function (): void { + mkdir($this->tempDirectory.'/real'); + (new ProjectMerchantFile($this->tempDirectory.'/real'))->save('shop-a'); + symlink($this->tempDirectory.'/real/.quickpay-cli.json', $this->tempDirectory.'/.quickpay-cli.json'); + expect((new ProjectMerchantFile($this->tempDirectory.'/nested'))->find())->toBe('shop-a'); +}); + +it('rejects a directory masquerading as a project file', function (): void { + mkdir($this->tempDirectory.'/nested/.quickpay-cli.json'); + expect(fn () => (new ProjectMerchantFile($this->tempDirectory.'/nested'))->find())->toThrow(CredentialException::class); +}); + +it('returns no selection when no binding exists', function (): void { + expect((new ProjectMerchantFile($this->tempDirectory))->find())->toBeNull(); +}); + +it('finds the current user without the posix extension', function (): void { + $probe = $this->tempDirectory.'/probe'; + touch($probe); + expect(ProjectMerchantFile::temporaryFileOwner())->toBe(fileowner($probe)) + ->and(ProjectMerchantFile::currentUser())->toBe(fileowner($probe)); +}); + +it('checks the owner before reading a binding', function (): void { + // An unreadable file shows the order: reading first would fail with + // "cannot be read" before the owner was ever checked. + $path = $this->tempDirectory.'/.quickpay-cli.json'; + file_put_contents($path, '{"merchant":"shop-a"}'); + chmod($path, 0000); + $otherUser = fileowner($path) + 1; + expect(fn () => (new ProjectMerchantFile($this->tempDirectory.'/nested', $otherUser))->find()) + ->toThrow(CredentialException::class, 'not owned by the current user'); +})->skip(fn (): bool => function_exists('posix_geteuid') && posix_geteuid() === 0, 'root can read any file'); + +it('refuses an oversized binding without parsing it', function (): void { + file_put_contents($this->tempDirectory.'/.quickpay-cli.json', '{"merchant":"shop-a"}'.str_repeat(' ', 4096)); + expect(fn () => (new ProjectMerchantFile($this->tempDirectory.'/nested'))->find()) + ->toThrow(CredentialException::class, 'too large to hold only a merchant name'); +}); diff --git a/tests/Pest.php b/tests/Pest.php index 79339d1..286841c 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1,5 +1,50 @@ extend(TestCase::class)->in('Feature', 'Integration'); + +pest()->beforeEach(function (): void { + $this->tempDirectory = sys_get_temp_dir().'/quickpay-merchant-command-'.bin2hex(random_bytes(8)); + mkdir($this->tempDirectory.'/project/nested', 0700, true); + $this->originalDirectory = getcwd(); + $this->originalApiKey = getenv('QUICKPAY_API_KEY'); + putenv('QUICKPAY_API_KEY'); + chdir($this->tempDirectory.'/project'); + $this->store = new MerchantStore($this->tempDirectory.'/config.json'); + $this->project = new ProjectMerchantFile; + app()->instance(MerchantStore::class, $this->store); + app()->instance(ProjectMerchantFile::class, $this->project); + app()->instance(ApiKeyResolver::class, new ApiKeyResolver(new EnvironmentVariables, $this->store, $this->project)); + app()->instance(StdinTerminalDetector::class, new class implements StdinTerminalDetector + { + public function isTty(): bool + { + return true; + } + }); + Http::preventStrayRequests(); +})->afterEach(function (): void { + chdir($this->originalDirectory); + $this->originalApiKey === false ? putenv('QUICKPAY_API_KEY') : putenv('QUICKPAY_API_KEY='.$this->originalApiKey); + app('files')->deleteDirectory($this->tempDirectory); +})->in('Feature/Commands/Merchants'); + +/** @param class-string $class */ +function merchantCommandResult(string $class, array $input = []): array +{ + $command = new $class; + $command->setLaravel(app()); + $tester = new CommandTester($command); + $exit = $tester->execute($input, ['capture_stderr_separately' => true]); + + return [$exit, $tester->getDisplay(), $tester->getErrorOutput()]; +} diff --git a/tests/Unit/Credentials/ApiKeyResolverTest.php b/tests/Unit/Credentials/ApiKeyResolverTest.php index 3d89e19..8ebc050 100644 --- a/tests/Unit/Credentials/ApiKeyResolverTest.php +++ b/tests/Unit/Credentials/ApiKeyResolverTest.php @@ -1,54 +1,86 @@ credentialPath = sys_get_temp_dir().'/quickpay-resolver-'.bin2hex(random_bytes(8)).'.json'; + $this->tempDirectory = sys_get_temp_dir().'/quickpay-resolver-'.bin2hex(random_bytes(8)); + mkdir($this->tempDirectory, 0700, true); $this->originalApiKey = getenv('QUICKPAY_API_KEY'); putenv('QUICKPAY_API_KEY'); + $this->store = new MerchantStore($this->tempDirectory.'/config.json'); + $this->project = new ProjectMerchantFile($this->tempDirectory); + $this->resolver = new ApiKeyResolver(new EnvironmentVariables, $this->store, $this->project); }); afterEach(function (): void { - $this->originalApiKey === false - ? putenv('QUICKPAY_API_KEY') - : putenv('QUICKPAY_API_KEY='.$this->originalApiKey); - - if (is_file($this->credentialPath)) { - unlink($this->credentialPath); + $this->originalApiKey === false ? putenv('QUICKPAY_API_KEY') : putenv('QUICKPAY_API_KEY='.$this->originalApiKey); + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->tempDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { + $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); } + rmdir($this->tempDirectory); }); -it('prefers a non-empty environment key without reading malformed storage', function (): void { - file_put_contents($this->credentialPath, '{malformed'); - putenv('QUICKPAY_API_KEY=environment-key'); +it('returns environment context without reading malformed saved storage', function (): void { + file_put_contents($this->store->path(), '{malformed'); + putenv('QUICKPAY_API_KEY=fake-environment'); + $key = $this->resolver->resolve(); + expect($key?->value())->toBe('fake-environment')->and($key?->source())->toBe('environment') + ->and($key?->merchant())->toBeNull()->and($key?->selectionSource())->toBe('environment'); +}); - $key = (new ApiKeyResolver( - new EnvironmentVariables, - new CredentialFile($this->credentialPath), - ))->resolve(); +it('uses the default only without explicit or project selection', function (): void { + $this->store->add('shop-a', 'fake-secret-a'); + $this->store->add('shop-b', 'fake-secret-b'); + expect($this->resolver->resolve()?->merchant())->toBe('shop-a') + ->and($this->resolver->resolve()?->selectionSource())->toBe('default'); + $this->project->save('shop-b'); + $key = $this->resolver->resolve(); + expect($key?->value())->toBe('fake-secret-b')->and($key?->selectionSource())->toBe('project'); + $key = $this->resolver->resolve('shop-a'); + expect($key?->merchant())->toBe('shop-a')->and($key?->source())->toBe('config file') + ->and($key?->selectionSource())->toBe('explicit'); +}); - expect($key?->value())->toBe('environment-key') - ->and($key?->source())->toBe('environment'); +it('bypasses malformed projects for an explicit selection', function (): void { + $this->store->add('shop-a', 'fake-secret-a'); + file_put_contents($this->tempDirectory.'/.quickpay-cli.json', '{broken'); + expect($this->resolver->resolve('shop-a')?->value())->toBe('fake-secret-a'); + expect(fn () => $this->resolver->resolve())->toThrow(CredentialException::class); }); -it('falls back to a stored key and reports its source', function (): void { - file_put_contents($this->credentialPath, json_encode(['api_key' => 'stored-key'], JSON_THROW_ON_ERROR)); - putenv('QUICKPAY_API_KEY='); +it('rejects stale project and unknown explicit selections', function (): void { + $this->store->add('shop-a', 'fake-secret-a'); + $this->project->save('shop-b'); + expect(fn () => $this->resolver->resolve())->toThrow(CredentialException::class, '.quickpay-cli.json'); + expect(fn () => $this->resolver->resolve('shop-b'))->toThrow(CredentialException::class); +}); - $key = (new ApiKeyResolver( - new EnvironmentVariables, - new CredentialFile($this->credentialPath), - ))->resolve(); +it('rejects environment and explicit selection together', function (): void { + putenv('QUICKPAY_API_KEY=fake-environment'); + file_put_contents($this->store->path(), '{malformed'); + expect(fn () => $this->resolver->resolve('shop-a'))->toThrow(CredentialException::class, 'QUICKPAY_API_KEY'); +}); + +it('rejects environment and project selection together', function (): void { + putenv('QUICKPAY_API_KEY=fake-environment'); + $this->project->save('shop-a'); + expect(fn () => $this->resolver->resolve())->toThrow(CredentialException::class, 'QUICKPAY_API_KEY'); +}); - expect($key?->value())->toBe('stored-key') - ->and($key?->source())->toBe('config file'); +it('ignores an empty environment override', function (): void { + putenv('QUICKPAY_API_KEY='); + $this->store->add('shop-a', 'fake-secret-a'); + expect($this->resolver->resolve()?->source())->toBe('config file'); }); -it('returns null when neither credential source is present', function (): void { - expect((new ApiKeyResolver( - new EnvironmentVariables, - new CredentialFile($this->credentialPath), - ))->resolve())->toBeNull(); +it('returns no credential for an absent or null default', function (): void { + expect($this->resolver->resolve())->toBeNull(); + $this->store->add('shop-a', 'fake-secret-a'); + $this->store->add('shop-b', 'fake-secret-b'); + $this->store->remove('shop-a'); + expect($this->resolver->resolve())->toBeNull(); }); diff --git a/tests/Unit/Credentials/MerchantAccessTest.php b/tests/Unit/Credentials/MerchantAccessTest.php new file mode 100644 index 0000000..479310d --- /dev/null +++ b/tests/Unit/Credentials/MerchantAccessTest.php @@ -0,0 +1,29 @@ +allows($method))->toBe($allowed); +})->with([ + 'read-only GET' => [true, 'GET', true], + 'read-only lowercase get' => [true, 'get', true], + 'read-only POST' => [true, 'POST', false], + 'read-only PUT' => [true, 'put', false], + 'read-only PATCH' => [true, 'PATCH', false], + 'read-only DELETE' => [true, 'DELETE', false], + 'read-only unknown method' => [true, 'OPTIONS', false], + 'full GET' => [false, 'GET', true], + 'full PUT' => [false, 'PUT', true], + 'full DELETE' => [false, 'DELETE', true], +]); + +it('names the access', function (bool $readOnly, string $label): void { + expect((new MerchantAccess($readOnly))->label())->toBe($label); +})->with([ + 'full' => [false, 'read and write'], + 'read-only' => [true, 'read-only'], +]); + +it('grants full access through the named constructor', function (): void { + expect(MerchantAccess::full()->readOnly)->toBeFalse(); +}); diff --git a/tests/Unit/Credentials/MerchantConfigurationJsonTest.php b/tests/Unit/Credentials/MerchantConfigurationJsonTest.php new file mode 100644 index 0000000..2d5096b --- /dev/null +++ b/tests/Unit/Credentials/MerchantConfigurationJsonTest.php @@ -0,0 +1,30 @@ +left->id)->toBe(1)->and($decoded->right->id)->toBe(2) + ->and($decoded->text)->toBe('{"id":1,"id":2}'); +}); + +it('rejects equivalent duplicate properties within an object', function (string $json): void { + expect(fn () => MerchantConfigurationJson::decode($json))->toThrow(JsonException::class); +})->with([ + 'plain' => '{"merchant":"shop-a","merchant":"shop-b"}', + 'escaped' => '{"merchant":"shop-a","merch\\u0061nt":"shop-b"}', + 'nested in array' => '[{"id":1,"id":2}]', + 'after a long value' => '{"merchant":"'.str_repeat('a', 20000).'","merchant":"shop-b"}', + 'after a long escaped value' => '{"merchant":"'.str_repeat('a\\"', 20000).'","merchant":"shop-b"}', +]); + +it('rejects configuration it cannot scan for duplicate properties', function (): void { + $limit = ini_get('pcre.backtrack_limit'); + ini_set('pcre.backtrack_limit', '1'); + try { + expect(fn () => MerchantConfigurationJson::decode('{"merchant":"'.str_repeat('a\\"', 1000).'"}')) + ->toThrow(JsonException::class); + } finally { + ini_set('pcre.backtrack_limit', (string) $limit); + } +}); diff --git a/tests/Unit/Credentials/MerchantNameTest.php b/tests/Unit/Credentials/MerchantNameTest.php new file mode 100644 index 0000000..9c22755 --- /dev/null +++ b/tests/Unit/Credentials/MerchantNameTest.php @@ -0,0 +1,35 @@ +toBe($name); +})->with([ + 'one letter' => 'a', + 'maximum' => str_repeat('a', 64), + 'shop' => 'shop-a1', + 'uppercase' => 'Shop-A', + 'readable name' => 'My Website', + 'hyphenated name' => 'My Website-2', + 'cancel label' => 'Cancel', +]); + +it('finds a saved name that differs only in capitalization', function (string $name, array $saved, ?string $variant): void { + expect(MerchantName::caseVariant($name, $saved))->toBe($variant); +})->with([ + 'case variant' => ['my website', ['My Website', 'shop-b'], 'My Website'], + 'exact name is not a variant' => ['My Website', ['My Website'], null], + 'different name' => ['shop-c', ['shop-a', 'shop-b'], null], + 'empty store' => ['shop-a', [], null], +]); + +it('rejects unsafe merchant names without echoing input', function (string $name): void { + expect(fn () => MerchantName::validate($name))->toThrow(CredentialException::class); +})->with([ + 'empty' => '', 'too long' => str_repeat('a', 65), + 'leading space' => ' My Website', 'trailing space' => 'My Website ', 'double space' => 'My Website', + 'numeric' => '12345', 'leading hyphen' => '-shop', 'trailing hyphen' => 'shop-', + 'double hyphen' => 'shop--a', 'traversal' => '../shop', 'slash' => 'shop/a', + 'backslash' => 'shop\\a', 'newline' => "shop\na", 'escape' => "shop\x1ba", +]); diff --git a/tests/Unit/Quickpay/Raw/RawApiHeaderParserTest.php b/tests/Unit/Quickpay/Raw/RawApiHeaderParserTest.php index 04fbb88..89f2bf4 100644 --- a/tests/Unit/Quickpay/Raw/RawApiHeaderParserTest.php +++ b/tests/Unit/Quickpay/Raw/RawApiHeaderParserTest.php @@ -28,3 +28,8 @@ 'leading control in name' => "\tX-Test:value", 'trailing control in value' => "X-Test:value\r", ]); + +it('refuses headers that would change the request method', function (string $header) { + expect(fn () => RawApiHeaderParser::parse([$header.':DELETE'])) + ->toThrow(InvalidArgumentException::class, 'cannot be sent'); +})->with(['X-HTTP-Method-Override', 'x-http-method-override', 'X-HTTP-Method', 'X-Method-Override']);