From 54a17861ffe1f3cf2654e6291b66281119c5aa99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Wed, 30 Sep 2026 20:17:52 +0200 Subject: [PATCH 01/16] feat: add named merchant storage and project bindings --- app/Credentials/MerchantName.php | 17 ++ app/Credentials/MerchantStore.php | 183 +++++++++++++++ app/Credentials/ProjectMerchantFile.php | 82 +++++++ .../Credentials/MerchantStoreTest.php | 220 ++++++++++++++++++ .../Credentials/ProjectMerchantFileTest.php | 53 +++++ tests/Unit/Credentials/MerchantNameTest.php | 17 ++ 6 files changed, 572 insertions(+) create mode 100644 app/Credentials/MerchantName.php create mode 100644 app/Credentials/MerchantStore.php create mode 100644 app/Credentials/ProjectMerchantFile.php create mode 100644 tests/Integration/Credentials/MerchantStoreTest.php create mode 100644 tests/Integration/Credentials/ProjectMerchantFileTest.php create mode 100644 tests/Unit/Credentials/MerchantNameTest.php diff --git a/app/Credentials/MerchantName.php b/app/Credentials/MerchantName.php new file mode 100644 index 0000000..ca4ff77 --- /dev/null +++ b/app/Credentials/MerchantName.php @@ -0,0 +1,17 @@ + 64 || preg_match('/\A[a-z][a-z0-9]*(?:-[a-z0-9]+)*\z/D', $name) !== 1) { + throw new CredentialException('Merchant names must contain 1-64 lowercase ASCII letters, digits or single separating hyphens, starting with a letter.'); + } + + return $name; + } +} diff --git a/app/Credentials/MerchantStore.php b/app/Credentials/MerchantStore.php new file mode 100644 index 0000000..057d693 --- /dev/null +++ b/app/Credentials/MerchantStore.php @@ -0,0 +1,183 @@ +} */ +final readonly class MerchantStore +{ + public function __construct(private string $path) {} + + public static function inHome(HomeDirectory $home): self + { + return new self(rtrim($home->path(), DIRECTORY_SEPARATOR).'/.config/quickpay-cli/config.json'); + } + + public function path(): string + { + return $this->path; + } + + /** @return MerchantConfig */ + public function read(): array + { + if (! file_exists($this->path) && ! is_link($this->path)) { + return ['default_merchant' => null, 'merchants' => []]; + } + + $contents = is_file($this->path) ? @file_get_contents($this->path) : false; + if ($contents === false) { + throw new CredentialException('Quickpay CLI merchant configuration cannot be read.'); + } + + try { + $config = json_decode($contents, flags: JSON_THROW_ON_ERROR); + } catch (JsonException) { + throw new CredentialException('Quickpay CLI merchant configuration is invalid JSON.'); + } + + if ($config instanceof stdClass && property_exists($config, 'api_key')) { + throw new CredentialException('Unsupported single-key configuration. Add merchants again with quickpay merchants:add after removing this unsupported file.'); + } + + if (! $config instanceof stdClass + || count(get_object_vars($config)) !== 2 + || ! property_exists($config, 'default_merchant') + || ! isset($config->merchants) + || ! $config->merchants 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) { + MerchantName::validate((string) $name); + if (! $merchant instanceof stdClass + || count(get_object_vars($merchant)) !== 1 + || ! isset($merchant->api_key) + || ! is_string($merchant->api_key) + || trim($merchant->api_key) === '') { + throw new CredentialException('Quickpay CLI merchant configuration contains an invalid credential.'); + } + $this->validateLabel((string) $name, $merchant->api_key); + $merchants[$name] = ['api_key' => $merchant->api_key]; + } + + 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]; + } + + public function add(string $name, string $apiKey, bool $replace = false): void + { + MerchantName::validate($name); + $apiKey = trim($apiKey); + if ($apiKey === '') { + throw new CredentialException('API key cannot be empty.'); + } + $this->validateLabel($name, $apiKey); + + $this->mutate(function (array $config) use ($name, $apiKey, $replace): array { + if (isset($config['merchants'][$name]) && ! $replace) { + throw new CredentialException('Merchant is already saved. Use --replace to replace its credential.'); + } + if ($config['merchants'] === []) { + $config['default_merchant'] = $name; + } + $config['merchants'][$name] = ['api_key' => $apiKey]; + + return $config; + }); + } + + public function select(string $name): void + { + MerchantName::validate($name); + $this->mutate(function (array $config) use ($name): array { + $this->requireMerchant($config, $name); + $config['default_merchant'] = $name; + + return $config; + }); + } + + public function remove(string $name): void + { + MerchantName::validate($name); + $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; + }); + } + + private function validateLabel(string $name, string $apiKey): void + { + if (CredentialRedactor::containsSensitiveValue($name, $apiKey)) { + 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 + { + $directory = dirname($this->path); + 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($this->path.'.lock', 'c'); + if ($lock === false) { + throw new CredentialException('Unable to lock merchant credentials.'); + } + + $temporary = ''; + try { + if (! @chmod($this->path.'.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($this->path).'.'); + 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, $this->path)) { + 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..30aad01 --- /dev/null +++ b/app/Credentials/ProjectMerchantFile.php @@ -0,0 +1,82 @@ +directory(); + while (true) { + $path = $directory.'/.quickpay-cli.json'; + if (file_exists($path) || is_link($path)) { + return ['merchant' => $this->read($path), 'path' => $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); + } + } + } + + 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 + { + $contents = is_file($path) ? @file_get_contents($path) : false; + if ($contents === false) { + throw new CredentialException('Project merchant binding cannot be read.'); + } + try { + $config = json_decode($contents, flags: JSON_THROW_ON_ERROR); + } catch (JsonException) { + throw new CredentialException('Project merchant binding is invalid JSON.'); + } + if (! $config instanceof stdClass || count(get_object_vars($config)) !== 1 || ! isset($config->merchant) || ! is_string($config->merchant)) { + throw new CredentialException('Project merchant binding must contain only a merchant name.'); + } + + return MerchantName::validate($config->merchant); + } +} diff --git a/tests/Integration/Credentials/MerchantStoreTest.php b/tests/Integration/Credentials/MerchantStoreTest.php new file mode 100644 index 0000000..e6d19a7 --- /dev/null +++ b/tests/Integration/Credentials/MerchantStoreTest.php @@ -0,0 +1,220 @@ +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'], 'shop-b' => ['api_key' => 'fake-secret-b']], + ]); +}); + +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('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'], 'shop-b' => ['api_key' => 'fake-replacement']], + ]); +}); + +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}}}', + 'empty key' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":" "}}}', + 'invalid name' => '{"default_merchant":null,"merchants":{"../a":{"api_key":"fake-key"}}}', + 'dangling default' => '{"default_merchant":"shop-a","merchants":{}}', + 'old shape' => '{"api_key":"fake-legacy"}', + 'secret label' => '{"default_merchant":null,"merchants":{"secret-name":{"api_key":"secret"}}}', +]); + +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(file_get_contents($old))->toBe('{"api_key":"fake-legacy"}'); +}); + +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"}}}'); + 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'); + } +}); diff --git a/tests/Integration/Credentials/ProjectMerchantFileTest.php b/tests/Integration/Credentials/ProjectMerchantFileTest.php new file mode 100644 index 0000000..d848b10 --- /dev/null +++ b/tests/Integration/Credentials/ProjectMerchantFileTest.php @@ -0,0 +1,53 @@ +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(['merchant' => 'shop-a', 'path' => $this->tempDirectory.'/.quickpay-cli.json']); + $child->save('shop-b'); + expect($child->find())->toBe(['merchant' => 'shop-b', 'path' => $this->tempDirectory.'/nested/.quickpay-cli.json']) + ->and($parent->find()['merchant'])->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); + 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":"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(); +}); diff --git a/tests/Unit/Credentials/MerchantNameTest.php b/tests/Unit/Credentials/MerchantNameTest.php new file mode 100644 index 0000000..78d350d --- /dev/null +++ b/tests/Unit/Credentials/MerchantNameTest.php @@ -0,0 +1,17 @@ +toBe($name); +})->with(['one letter' => 'a', 'maximum' => str_repeat('a', 64), 'shop' => 'shop-a1']); + +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), 'uppercase' => 'Shop-a', + 'numeric' => '12345', 'leading hyphen' => '-shop', 'trailing hyphen' => 'shop-', + 'double hyphen' => 'shop--a', 'traversal' => '../shop', 'slash' => 'shop/a', + 'backslash' => 'shop\\a', 'space' => 'shop a', 'newline' => "shop\na", 'escape' => "shop\x1ba", +]); From 1ad9ec513a8ad38b1cf581f84d3ef74fd00d4d6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Wed, 30 Sep 2026 20:40:45 +0200 Subject: [PATCH 02/16] feat: replace single-key authentication with merchant selection --- AGENTS.md | 14 +- README.md | 56 +++- app/Commands/Authentication/AuthCommand.php | 94 ------ app/Commands/Authentication/LoginCommand.php | 60 ---- app/Commands/Authentication/LogoutCommand.php | 36 --- .../Merchants/ActiveMerchantCommand.php | 69 +++++ app/Commands/Merchants/AddMerchantCommand.php | 53 ++++ .../Merchants/ListMerchantsCommand.php | 36 +++ .../Merchants/RemoveMerchantCommand.php | 30 ++ .../Merchants/SelectMerchantCommand.php | 65 ++++ app/Console/AuthenticatedCommand.php | 12 +- app/Credentials/ApiKey.php | 12 + app/Credentials/ApiKeyResolver.php | 32 +- app/Credentials/CredentialFile.php | 111 ------- app/Providers/AppServiceProvider.php | 8 +- app/Quickpay/AuthenticatedQuickpayFactory.php | 4 +- app/Quickpay/MerchantAuthenticationCheck.php | 24 ++ tests/Feature/ApplicationIdentityTest.php | 8 +- tests/Feature/CommandHelpTest.php | 7 + .../Commands/Api/ApiRequestCommandTest.php | 8 + .../AuthenticationCommandsTest.php | 291 ------------------ .../Callbacks/ReplayCallbackCommandTest.php | 8 + .../Callbacks/WatchCallbacksCommandTest.php | 8 + .../Merchants/MerchantCommandsTest.php | 283 +++++++++++++++++ .../Payments/CreatePaymentCommandTest.php | 8 + .../Payments/CreatePaymentLinkCommandTest.php | 8 + .../Payments/GetPaymentCommandTest.php | 8 + .../Payments/ListPaymentsCommandTest.php | 20 +- .../Payments/PaymentMutationCommandsTest.php | 8 + .../AuthenticatedQuickpayFactoryTest.php | 34 ++ .../MerchantAuthenticationCheckTest.php | 13 + .../Credentials/CredentialFileTest.php | 70 ----- tests/Unit/Credentials/ApiKeyResolverTest.php | 94 ++++-- 33 files changed, 870 insertions(+), 722 deletions(-) delete mode 100644 app/Commands/Authentication/AuthCommand.php delete mode 100644 app/Commands/Authentication/LoginCommand.php delete mode 100644 app/Commands/Authentication/LogoutCommand.php create mode 100644 app/Commands/Merchants/ActiveMerchantCommand.php create mode 100644 app/Commands/Merchants/AddMerchantCommand.php create mode 100644 app/Commands/Merchants/ListMerchantsCommand.php create mode 100644 app/Commands/Merchants/RemoveMerchantCommand.php create mode 100644 app/Commands/Merchants/SelectMerchantCommand.php delete mode 100644 app/Credentials/CredentialFile.php create mode 100644 app/Quickpay/MerchantAuthenticationCheck.php delete mode 100644 tests/Feature/Commands/Authentication/AuthenticationCommandsTest.php create mode 100644 tests/Feature/Commands/Merchants/MerchantCommandsTest.php create mode 100644 tests/Feature/Quickpay/AuthenticatedQuickpayFactoryTest.php create mode 100644 tests/Feature/Quickpay/MerchantAuthenticationCheckTest.php delete mode 100644 tests/Integration/Credentials/CredentialFileTest.php diff --git a/AGENTS.md b/AGENTS.md index bb68ebc..8c80f89 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,7 @@ 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. @@ -74,9 +74,15 @@ 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. +- 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/README.md b/README.md index ecbc576..7066881 100644 --- a/README.md +++ b/README.md @@ -35,13 +35,20 @@ Install the bundled skill for coding agents: skills add tehwave/quickpay-cli ``` -Authenticate with a Quickpay merchant API key: +Save access to each merchant once. The CLI privately prompts for its API key: ```bash -quickpay login +quickpay merchants:add shop-a ``` -For automation, supply the API key through `QUICKPAY_API_KEY`. +Credentials are stored in `~/.config/quickpay-cli/config.json` with a `0700` +directory and `0600` file. Merchant names are local labels you choose, not verified +Quickpay account names or merchant IDs. Names contain 1-64 lowercase ASCII +letters, digits or single separating hyphens, starting with a letter. + +For automation, supply the API key through `QUICKPAY_API_KEY`. It cannot be +combined with `--merchant` or a project binding; unset it before selecting a +saved merchant. ## Usage @@ -55,6 +62,49 @@ Use `--help` to explore any command and its options: quickpay callbacks:watch --help ``` +### Select a merchant + +```bash +quickpay merchants:add shop-b +quickpay merchants:list +quickpay merchants:select shop-a +quickpay merchants:select # Interactive picker +quickpay merchants:active # Local configuration, no API request +quickpay merchants:active --check --json # Verify API access for automation +quickpay payments:list --merchant=shop-b +``` + +The first saved merchant becomes the global default. Adding another merchant +keeps that default. Select a different default with `merchants:select`, or use +`--merchant` for one payment, callback or raw API command. + +Bind the current project without changing the global default: + +```bash +quickpay merchants:select shop-b --local +``` + +Run this from the project root. It writes `.quickpay-cli.json` containing only +`{"merchant":"shop-b"}`. Commands search the current directory and its parents +for the nearest binding. Ignore this file in Git when the selection is specific +to one developer. The selection order is an explicit `--merchant`, then the +nearest project binding, then the global default. Unknown names and invalid +bindings fail without silently switching to another merchant. + +`merchants:active` reports configuration. Add `--check` to verify the key against +Quickpay; a missing or rejected credential exits non-zero. `--json` keeps the +status machine-readable, with diagnostics on stderr. + +Rotate a saved key with `quickpay merchants:add shop-a --replace`. The old key +remains intact if validation fails. `quickpay merchants:remove shop-a` removes +only local access, never the remote account. Removing the default leaves no +default; it does not select another saved merchant. Any binding to a removed +merchant will fail until you select a valid one. + +This pre-v1 change replaces `login`, `logout` and `auth`. The old +`~/.config/quickpay/config.json` is not read or migrated. Add each merchant again +with `merchants:add`; after setup, you may remove the old file yourself. + ### Watch for callbacks and relay them ```bash 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/Merchants/ActiveMerchantCommand.php b/app/Commands/Merchants/ActiveMerchantCommand.php new file mode 100644 index 0000000..479781b --- /dev/null +++ b/app/Commands/Merchants/ActiveMerchantCommand.php @@ -0,0 +1,69 @@ +option('merchant'); + $key = $resolver->resolve(is_string($merchant) ? $merchant : null); + } catch (CredentialException $exception) { + return $this->failure($exception->getMessage()); + } + $requested = (bool) $this->option('check'); + $error = null; + if ($requested) { + if ($key === null) { + $error = 'No Quickpay credentials found. Run quickpay merchants:add first.'; + } else { + try { + $check->check($key); + } catch (QuickpayRequestException|UnexpectedValueException $exception) { + $error = $key->redact($exception->getMessage()); + } + } + } + $authenticated = $requested ? $error === null : null; + $status = [ + 'merchant' => $key?->merchant(), + 'selection_source' => $key?->selectionSource(), + 'credential_source' => $key?->source(), + 'configured' => $key !== null, + 'checked' => $requested, + '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'] ?? 'not associated with a saved merchant')); + $this->line('Selection source: '.($status['selection_source'] ?? 'none')); + $this->line('Credential source: '.($status['credential_source'] ?? 'none')); + $this->line('Credentials configured: '.($status['configured'] ? 'yes' : 'no')); + $this->line('API base URL: '.$status['api_base_url']); + $this->line('API version: '.$status['api_version']); + $this->line('API access: '.($requested ? ($authenticated ? 'verified' : 'failed') : 'not checked')); + } + + return $error === null ? self::SUCCESS : $this->failure($error); + } +} diff --git a/app/Commands/Merchants/AddMerchantCommand.php b/app/Commands/Merchants/AddMerchantCommand.php new file mode 100644 index 0000000..eb33c2a --- /dev/null +++ b/app/Commands/Merchants/AddMerchantCommand.php @@ -0,0 +1,53 @@ +argument('name')); + $config = $store->read(); + if (isset($config['merchants'][$name]) && ! $this->option('replace')) { + return $this->failure('Merchant is already saved. Use --replace to replace its credential.'); + } + 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'); + if ($credential->appearsIn($name)) { + return $this->failure('Merchant name must not contain the API key.'); + } + $check->check($credential); + $store->add($name, $apiKey, (bool) $this->option('replace')); + $this->info('Merchant saved: '.$name); + + 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..a850fd5 --- /dev/null +++ b/app/Commands/Merchants/ListMerchantsCommand.php @@ -0,0 +1,36 @@ +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], $names); + if ($this->option('json')) { + $this->getOutput()->write(JsonOutput::value($rows, '')); + } elseif ($rows === []) { + $this->line('No saved merchants. Run quickpay merchants:add first.'); + } else { + $this->table(['Merchant', 'Global default'], array_map(fn (array $row): array => [$row['name'], $row['default'] ? 'yes' : ''], $rows)); + } + + return self::SUCCESS; + } +} diff --git a/app/Commands/Merchants/RemoveMerchantCommand.php b/app/Commands/Merchants/RemoveMerchantCommand.php new file mode 100644 index 0000000..7791b35 --- /dev/null +++ b/app/Commands/Merchants/RemoveMerchantCommand.php @@ -0,0 +1,30 @@ +remove((string) $this->argument('name')); + } catch (CredentialException $exception) { + return $this->failure($exception->getMessage()); + } + $this->info('Saved merchant removed.'); + 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..01dc3d6 --- /dev/null +++ b/app/Commands/Merchants/SelectMerchantCommand.php @@ -0,0 +1,65 @@ +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.'); + } + $name = MerchantName::validate($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); + } + + return self::SUCCESS; + } catch (CredentialException $exception) { + return $this->failure($exception->getMessage()); + } + } +} diff --git a/app/Console/AuthenticatedCommand.php b/app/Console/AuthenticatedCommand.php index 2df5719..2cf2868 100644 --- a/app/Console/AuthenticatedCommand.php +++ b/app/Console/AuthenticatedCommand.php @@ -10,21 +10,29 @@ use App\Quickpay\QuickpayResponse; use Closure; use InvalidArgumentException; +use Symfony\Component\Console\Input\InputOption; use UnexpectedValueException; abstract class AuthenticatedCommand extends BaseCommand { + 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('No Quickpay credentials found. Run quickpay merchants:add first.'); } try { diff --git a/app/Credentials/ApiKey.php b/app/Credentials/ApiKey.php index 291d699..ecfe203 100644 --- a/app/Credentials/ApiKey.php +++ b/app/Credentials/ApiKey.php @@ -10,6 +10,8 @@ public function __construct( private string $value, private string $source, + private ?string $merchant = null, + private ?string $selectionSource = null, ) { if (trim($value) === '') { throw new InvalidArgumentException('Quickpay API key must not be empty.'); @@ -26,6 +28,16 @@ public function source(): string return $this->source; } + 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..f4b3aa6 100644 --- a/app/Credentials/ApiKeyResolver.php +++ b/app/Credentials/ApiKeyResolver.php @@ -2,23 +2,43 @@ 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.'); + } + $binding = $merchant === null ? $this->project->find() : null; + if ($environmentKey !== null && $binding !== 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', null, 'environment'); } - $storedKey = $this->file->read(); + $config = $this->store->read(); + $source = $merchant !== null ? 'explicit' : ($binding !== null ? 'project' : 'default'); + $name = $merchant ?? $binding['merchant'] ?? $config['default_merchant']; + if ($name === null) { + return null; + } + if (! isset($config['merchants'][$name])) { + throw new CredentialException('Selected merchant is not saved. Run quickpay merchants:list to see saved names.'); + } - return $storedKey === null ? null : new ApiKey($storedKey, 'config file'); + return new ApiKey($config['merchants'][$name]['api_key'], 'config file', $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/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/AuthenticatedQuickpayFactory.php b/app/Quickpay/AuthenticatedQuickpayFactory.php index ba8d660..b554f90 100644 --- a/app/Quickpay/AuthenticatedQuickpayFactory.php +++ b/app/Quickpay/AuthenticatedQuickpayFactory.php @@ -14,9 +14,9 @@ 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); } 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/tests/Feature/ApplicationIdentityTest.php b/tests/Feature/ApplicationIdentityTest.php index c99386d..1118faf 100644 --- a/tests/Feature/ApplicationIdentityTest.php +++ b/tests/Feature/ApplicationIdentityTest.php @@ -19,11 +19,13 @@ expect($commands)->toBe([ 'about', 'api', - 'auth', - 'login', - 'logout', 'callbacks:replay', 'callbacks:watch', + 'merchants:active', + 'merchants:add', + 'merchants:list', + 'merchants:remove', + 'merchants:select', 'payments:cancel', 'payments:capture', 'payments:create', diff --git a/tests/Feature/CommandHelpTest.php b/tests/Feature/CommandHelpTest.php index 23b7c5b..5e46131 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,8 @@ ->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']); diff --git a/tests/Feature/Commands/Api/ApiRequestCommandTest.php b/tests/Feature/Commands/Api/ApiRequestCommandTest.php index f195384..06fdbdf 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,10 @@ public function isTty(): bool }); afterEach(function () { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { + $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); + } + 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..0ec9ee3 100644 --- a/tests/Feature/Commands/Callbacks/ReplayCallbackCommandTest.php +++ b/tests/Feature/Commands/Callbacks/ReplayCallbackCommandTest.php @@ -4,6 +4,7 @@ use App\Callbacks\Resolution\PrivateKeyResolver; use App\Commands\Callbacks\ReplayCallbackCommand; use App\Credentials\EnvironmentVariables; +use App\Credentials\ProjectMerchantFile; use App\Quickpay\QuickpayClient; use Illuminate\Http\Client\Factory; use Illuminate\Http\Client\Request; @@ -11,6 +12,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 +22,10 @@ }); afterEach(function () { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { + $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); + } + rmdir($this->merchantProjectDirectory); foreach ([ 'QUICKPAY_API_KEY' => $this->originalApiKey, 'QUICKPAY_PRIVATE_KEY' => $this->originalPrivateKey, diff --git a/tests/Feature/Commands/Callbacks/WatchCallbacksCommandTest.php b/tests/Feature/Commands/Callbacks/WatchCallbacksCommandTest.php index b2986f0..a4fb032 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,10 @@ }); afterEach(function () { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { + $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); + } + rmdir($this->merchantProjectDirectory); foreach ([ 'QUICKPAY_API_KEY' => $this->originalApiKey, 'QUICKPAY_PRIVATE_KEY' => $this->originalPrivateKey, diff --git a/tests/Feature/Commands/Merchants/MerchantCommandsTest.php b/tests/Feature/Commands/Merchants/MerchantCommandsTest.php new file mode 100644 index 0000000..44ca0e0 --- /dev/null +++ b/tests/Feature/Commands/Merchants/MerchantCommandsTest.php @@ -0,0 +1,283 @@ + $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()]; +} + +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); + 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('adds a merchant after a private credential check', function (): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['msg' => 'pong', 'scope' => 'merchant', 'version' => 'v10', 'params' => []])]); + $this->artisan('merchants:add', ['name' => 'shop-a']) + ->expectsQuestion('API key', ' fake-secret-a ') + ->expectsOutputToContain('Merchant saved: shop-a') + ->doesntExpectOutputToContain('fake-secret-a')->assertExitCode(0); + expect($this->store->read()['merchants']['shop-a']['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('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', 'path' => '../secret', 'uppercase' => 'Shop-a']); + +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('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('sanitizes authentication errors on stderr', function (string $form): void { + $this->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('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('lists only sorted names and the global default', function (): void { + $this->store->add('shop-b', 'fake-secret-b'); + $this->store->add('shop-a', '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' => 'shop-a', 'default' => false], ['name' => 'shop-b', 'default' => true]]); + 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('selects saved merchants globally without re-entering credentials', function (): void { + $this->store->add('shop-a', 'fake-secret-a'); + $this->store->add('shop-b', 'fake-secret-b'); + $this->artisan('merchants:select', ['name' => 'shop-b'])->assertExitCode(0); + expect($this->store->read()['default_merchant'])->toBe('shop-b'); + 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->artisan('merchants:select')->expectsChoice('Select merchant', $selection, ['shop-a', 'shop-b', 'Cancel'])->assertExitCode(0); + expect($this->store->read()['default_merchant'])->toBe($selection === 'Cancel' ? 'shop-a' : 'shop-b'); + Http::assertNothingSent(); +})->with(['selection' => 'shop-b', 'cancel' => 'Cancel']); + +it('selects a project merchant without changing the 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-b', '--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('shop-b') + ->and($this->store->read()['default_merchant'])->toBe('shop-a'); + mkdir($this->tempDirectory.'/other'); + chdir($this->tempDirectory.'/other'); + [$exit, $output] = merchantCommandResult(ActiveMerchantCommand::class, ['--json' => true]); + expect(json_decode($output, true)['merchant'])->toBe('shop-a'); + Http::assertNothingSent(); +}); + +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]]]); + +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, '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')->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('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(); + 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('shop-a', 'fake-secret-a'); + $this->store->add('shop-b', 'fake-secret-b'); + [$exit, $output, $errors] = merchantCommandResult(ActiveMerchantCommand::class, ['--merchant' => 'shop-b', '--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('shop-b'); + 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('removes only the named credential without choosing another default', function (): void { + $this->store->add('shop-a', 'fake-secret-a'); + $this->store->add('shop-b', 'fake-secret-b'); + $this->artisan('merchants:remove', ['name' => 'shop-a'])->assertExitCode(0); + expect($this->store->read())->toBe(['default_merchant' => null, 'merchants' => ['shop-b' => ['api_key' => 'fake-secret-b']]]); + $this->artisan('merchants:remove', ['name' => 'shop-missing'])->assertExitCode(1); + $this->artisan('merchants:remove', ['name' => 'shop-b'])->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/Payments/CreatePaymentCommandTest.php b/tests/Feature/Commands/Payments/CreatePaymentCommandTest.php index 5a5d701..68957a5 100644 --- a/tests/Feature/Commands/Payments/CreatePaymentCommandTest.php +++ b/tests/Feature/Commands/Payments/CreatePaymentCommandTest.php @@ -1,16 +1,24 @@ 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 () { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { + $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); + } + 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..a5549d5 100644 --- a/tests/Feature/Commands/Payments/CreatePaymentLinkCommandTest.php +++ b/tests/Feature/Commands/Payments/CreatePaymentLinkCommandTest.php @@ -1,16 +1,24 @@ 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 () { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { + $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); + } + 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..b6135b1 100644 --- a/tests/Feature/Commands/Payments/GetPaymentCommandTest.php +++ b/tests/Feature/Commands/Payments/GetPaymentCommandTest.php @@ -1,16 +1,24 @@ 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 () { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { + $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); + } + 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..a4d6824 100644 --- a/tests/Feature/Commands/Payments/ListPaymentsCommandTest.php +++ b/tests/Feature/Commands/Payments/ListPaymentsCommandTest.php @@ -2,18 +2,26 @@ 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 () { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { + $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); + } + rmdir($this->merchantProjectDirectory); if ($this->originalApiKey === false) { putenv('QUICKPAY_API_KEY'); } else { @@ -355,15 +363,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..6cb9a61 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,10 @@ public function isTty(): bool }); afterEach(function () { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { + $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); + } + rmdir($this->merchantProjectDirectory); if ($this->originalApiKey === false) { putenv('QUICKPAY_API_KEY'); } else { 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..c07baa4 --- /dev/null +++ b/tests/Feature/Quickpay/MerchantAuthenticationCheckTest.php @@ -0,0 +1,13 @@ + Http::response(['scope' => 'user'])]); + expect(fn () => (new MerchantAuthenticationCheck(app(AuthenticatedQuickpayFactory::class)))->check(new ApiKey('fake-key', 'provided'))) + ->toThrow(UnexpectedValueException::class, 'merchant'); + Http::assertSentCount(1); +}); 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/Unit/Credentials/ApiKeyResolverTest.php b/tests/Unit/Credentials/ApiKeyResolverTest.php index 3d89e19..27e83ac 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); + 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(); }); From c30fd2ca593baca6169813ebdfb026f706f972ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Wed, 30 Sep 2026 20:55:19 +0200 Subject: [PATCH 03/16] feat: identify selected merchants in payment and callback output --- README.md | 10 + SECURITY.md | 19 +- app/Commands/Api/ApiRequestCommand.php | 1 + .../Callbacks/WatchCallbacksCommand.php | 1 + .../AbstractPaymentMutationCommand.php | 12 +- app/Console/AuthenticatedCommand.php | 14 ++ .../Console/AuthenticatedCommandTest.php | 193 ++++++++++++++++++ 7 files changed, 246 insertions(+), 4 deletions(-) create mode 100644 tests/Feature/Console/AuthenticatedCommandTest.php diff --git a/README.md b/README.md index 7066881..2c7a569 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,12 @@ to one developer. The selection order is an explicit `--merchant`, then the nearest project binding, then the global default. Unknown names and invalid bindings fail without silently switching to another merchant. +Each invocation resolves its merchant once. A running callback watcher stays +attached to that merchant when another command changes selection or removes the +saved credential. Mutation confirmations and watcher startup show the saved +label and credential source; payment confirmations also show the API's merchant +ID when available. These messages go to stderr in JSON mode. + `merchants:active` reports configuration. Add `--check` to verify the key against Quickpay; a missing or rejected credential exits non-zero. `--json` keeps the status machine-readable, with diagnostics on stderr. @@ -119,6 +125,10 @@ 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. +An explicit `QUICKPAY_PRIVATE_KEY` must belong to the selected merchant. Without +that override, the CLI fetches the signing key through the same merchant's API +access and keeps it only in memory. + ```bash quickpay callbacks:replay --to= diff --git a/SECURITY.md b/SECURITY.md index 526e6d8..4af9e03 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -39,6 +39,22 @@ 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 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. + ## Local callback forwarding `callbacks:replay` and `callbacks:watch` send a signed payment resource to the @@ -53,7 +69,8 @@ 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 `--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/Commands/Api/ApiRequestCommand.php b/app/Commands/Api/ApiRequestCommand.php index 0aefc25..de57ea7 100644 --- a/app/Commands/Api/ApiRequestCommand.php +++ b/app/Commands/Api/ApiRequestCommand.php @@ -48,6 +48,7 @@ public function handle( ); if ($request->mutation) { + $this->writeMerchantContext($authenticated); $this->writeSafetyLine("Quickpay API request: {$request->method}"); if (! $confirmation->approve( diff --git a/app/Commands/Callbacks/WatchCallbacksCommand.php b/app/Commands/Callbacks/WatchCallbacksCommand.php index 4170558..6f854bb 100644 --- a/app/Commands/Callbacks/WatchCallbacksCommand.php +++ b/app/Commands/Callbacks/WatchCallbacksCommand.php @@ -55,6 +55,7 @@ function (AuthenticatedQuickpay $authenticated) use ($watch): int { $interval = $this->interval(); $deliveryAttempts = $this->deliveryAttempts(); $apiKey = $authenticated->apiKey->value(); + $this->writeMerchantContext($authenticated); if ($request->paymentId !== null || $request->orderId !== null) { $this->info(ResponseBodySanitizer::terminalLine( diff --git a/app/Commands/Payments/AbstractPaymentMutationCommand.php b/app/Commands/Payments/AbstractPaymentMutationCommand.php index b18407c..f6d5f56 100644 --- a/app/Commands/Payments/AbstractPaymentMutationCommand.php +++ b/app/Commands/Payments/AbstractPaymentMutationCommand.php @@ -39,11 +39,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 +89,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 +104,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; } diff --git a/app/Console/AuthenticatedCommand.php b/app/Console/AuthenticatedCommand.php index 2cf2868..edfa01f 100644 --- a/app/Console/AuthenticatedCommand.php +++ b/app/Console/AuthenticatedCommand.php @@ -11,6 +11,7 @@ use Closure; use InvalidArgumentException; use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; use UnexpectedValueException; abstract class AuthenticatedCommand extends BaseCommand @@ -46,4 +47,17 @@ protected function responseFailure(QuickpayResponse $response, string $apiKey): { return $this->failure(ResponseBodySanitizer::terminalLine($response->errorSummary(), $apiKey)); } + + protected function writeMerchantContext(AuthenticatedQuickpay $authenticated): void + { + $output = $this->input->hasOption('json') && $this->input->getOption('json') + ? $this->getOutput()->getErrorStyle() + : $this->getOutput(); + foreach ([ + 'Merchant: '.($authenticated->apiKey->merchant() ?? 'not associated with a saved merchant'), + 'Credential source: '.$authenticated->apiKey->source(), + ] as $message) { + $output->writeln($authenticated->safeLine($message), OutputInterface::OUTPUT_RAW); + } + } } diff --git a/tests/Feature/Console/AuthenticatedCommandTest.php b/tests/Feature/Console/AuthenticatedCommandTest.php new file mode 100644 index 0000000..493e280 --- /dev/null +++ b/tests/Feature/Console/AuthenticatedCommandTest.php @@ -0,0 +1,193 @@ +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('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]); From 0ef1a4eb589e4deda1da151fdad1ca8f5c939377 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Wed, 30 Sep 2026 21:10:59 +0200 Subject: [PATCH 04/16] docs: rename the bundled skill to quickpay-cli --- AGENTS.md | 4 +- CONTRIBUTING.md | 2 +- README.md | 6 +- skills/{quickpay => quickpay-cli}/SKILL.md | 78 ++++++++++++++++------ tests/Architecture/SkillContractTest.php | 24 +++++++ tests/Feature/CommandHelpTest.php | 9 +++ 6 files changed, 99 insertions(+), 24 deletions(-) rename skills/{quickpay => quickpay-cli}/SKILL.md (58%) create mode 100644 tests/Architecture/SkillContractTest.php diff --git a/AGENTS.md b/AGENTS.md index 8c80f89..2ce2f04 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ 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 @@ -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. 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 2c7a569..b90ac09 100644 --- a/README.md +++ b/README.md @@ -29,12 +29,16 @@ Quickpay CLI requires PHP 8.4 or newer. composer global require tehwave/quickpay-cli ``` -Install the bundled skill for coding agents: +Install the bundled [quickpay-cli skill](skills/quickpay-cli/SKILL.md) for coding agents: ```bash skills add tehwave/quickpay-cli ``` +If you previously installed this project's skill as `quickpay`, remove that +installed copy and run the installation command again. Check its origin before +removal so an unrelated Quickpay skill stays intact. + Save access to each merchant once. The CLI privately prompts for its API key: ```bash diff --git a/skills/quickpay/SKILL.md b/skills/quickpay-cli/SKILL.md similarity index 58% rename from skills/quickpay/SKILL.md rename to skills/quickpay-cli/SKILL.md index 4d9b484..43442e6 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,53 @@ 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 `shop-a` 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. 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 and malformed or stale bindings 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` 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. ## 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=shop-a --check --json +quickpay payments:get 884201 --merchant=shop-a --json +quickpay payments:capture 884201 2500 --merchant=shop-a --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 +69,30 @@ 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] +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 +136,8 @@ 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. A watcher +keeps the merchant and key resolved at startup even if saved selection changes. ## Raw API guardrails @@ -119,4 +155,6 @@ 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. +- Use the same `--merchant` for readiness checks, payment inspection and any explicitly authorized mutation. 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/CommandHelpTest.php b/tests/Feature/CommandHelpTest.php index 5e46131..2b28eed 100644 --- a/tests/Feature/CommandHelpTest.php +++ b/tests/Feature/CommandHelpTest.php @@ -30,3 +30,12 @@ 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); + } +}); From 271ebaa94e587837f14c1676679b3aafbd729e6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Wed, 30 Sep 2026 22:00:11 +0200 Subject: [PATCH 05/16] fix: reject ambiguous merchant configuration and secret labels --- app/Credentials/MerchantConfigurationJson.php | 35 +++++++++++++++++++ app/Credentials/MerchantStore.php | 16 +++++++-- app/Credentials/ProjectMerchantFile.php | 2 +- .../Merchants/MerchantCommandsTest.php | 23 ++++++++++++ .../Credentials/MerchantStoreTest.php | 20 +++++++++++ .../Credentials/ProjectMerchantFileTest.php | 2 ++ .../MerchantConfigurationJsonTest.php | 17 +++++++++ 7 files changed, 112 insertions(+), 3 deletions(-) create mode 100644 app/Credentials/MerchantConfigurationJson.php create mode 100644 tests/Unit/Credentials/MerchantConfigurationJsonTest.php diff --git a/app/Credentials/MerchantConfigurationJson.php b/app/Credentials/MerchantConfigurationJson.php new file mode 100644 index 0000000..58b1f83 --- /dev/null +++ b/app/Credentials/MerchantConfigurationJson.php @@ -0,0 +1,35 @@ + $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 = array_key_last($objects); + if (! is_string($name) || $scope === null || isset($objects[$scope][$name])) { + throw new JsonException('Ambiguous configuration contains duplicate JSON properties.'); + } + $objects[$scope][$name] = true; + } + } + + return $decoded; + } +} diff --git a/app/Credentials/MerchantStore.php b/app/Credentials/MerchantStore.php index 057d693..99b8922 100644 --- a/app/Credentials/MerchantStore.php +++ b/app/Credentials/MerchantStore.php @@ -36,7 +36,7 @@ public function read(): array } try { - $config = json_decode($contents, flags: JSON_THROW_ON_ERROR); + $config = MerchantConfigurationJson::decode($contents); } catch (JsonException) { throw new CredentialException('Quickpay CLI merchant configuration is invalid JSON.'); } @@ -64,9 +64,9 @@ public function read(): array || trim($merchant->api_key) === '') { throw new CredentialException('Quickpay CLI merchant configuration contains an invalid credential.'); } - $this->validateLabel((string) $name, $merchant->api_key); $merchants[$name] = ['api_key' => $merchant->api_key]; } + $this->validateLabels($merchants); if ($config->default_merchant !== null && ! isset($merchants[$config->default_merchant])) { throw new CredentialException('Quickpay CLI default merchant is not saved.'); @@ -92,6 +92,7 @@ public function add(string $name, string $apiKey, bool $replace = false): void $config['default_merchant'] = $name; } $config['merchants'][$name] = ['api_key' => $apiKey]; + $this->validateLabels($config['merchants']); return $config; }); @@ -129,6 +130,17 @@ private function validateLabel(string $name, string $apiKey): void } } + /** @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 ($merchants as $name => $merchant) { + foreach ($merchants as $credential) { + $this->validateLabel($name, $credential['api_key']); + } + } + } + /** @param MerchantConfig $config */ private function requireMerchant(array $config, string $name): void { diff --git a/app/Credentials/ProjectMerchantFile.php b/app/Credentials/ProjectMerchantFile.php index 30aad01..d30fdeb 100644 --- a/app/Credentials/ProjectMerchantFile.php +++ b/app/Credentials/ProjectMerchantFile.php @@ -69,7 +69,7 @@ private function read(string $path): string throw new CredentialException('Project merchant binding cannot be read.'); } try { - $config = json_decode($contents, flags: JSON_THROW_ON_ERROR); + $config = MerchantConfigurationJson::decode($contents); } catch (JsonException) { throw new CredentialException('Project merchant binding is invalid JSON.'); } diff --git a/tests/Feature/Commands/Merchants/MerchantCommandsTest.php b/tests/Feature/Commands/Merchants/MerchantCommandsTest.php index 44ca0e0..64a5933 100644 --- a/tests/Feature/Commands/Merchants/MerchantCommandsTest.php +++ b/tests/Feature/Commands/Merchants/MerchantCommandsTest.php @@ -281,3 +281,26 @@ public function isTty(): bool expect(getenv('QUICKPAY_API_KEY'))->toBe('fake-environment'); Http::assertNothingSent(); }); + +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"},"sh\\u006fp-a":{"api_key":"fake-last"}}}'; + 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('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"},"fake-secret-a":{"api_key":"fake-secret-b"}}}'); + [$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(); +}); diff --git a/tests/Integration/Credentials/MerchantStoreTest.php b/tests/Integration/Credentials/MerchantStoreTest.php index e6d19a7..f1ce816 100644 --- a/tests/Integration/Credentials/MerchantStoreTest.php +++ b/tests/Integration/Credentials/MerchantStoreTest.php @@ -58,6 +58,15 @@ ]); }); +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'); @@ -89,8 +98,19 @@ 'dangling default' => '{"default_merchant":"shop-a","merchants":{}}', 'old shape' => '{"api_key":"fake-legacy"}', 'secret label' => '{"default_merchant":null,"merchants":{"secret-name":{"api_key":"secret"}}}', + 'duplicate merchant' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first"},"shop-a":{"api_key":"fake-last"}}}', + 'escaped duplicate merchant' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first"},"sh\\u006fp-a":{"api_key":"fake-last"}}}', + 'duplicate key' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","api_key":"fake-last"}}}', + 'duplicate default' => '{"default_merchant":"shop-a","default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-first"}}}', ]); +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); diff --git a/tests/Integration/Credentials/ProjectMerchantFileTest.php b/tests/Integration/Credentials/ProjectMerchantFileTest.php index d848b10..7f80e40 100644 --- a/tests/Integration/Credentials/ProjectMerchantFileTest.php +++ b/tests/Integration/Credentials/ProjectMerchantFileTest.php @@ -41,6 +41,8 @@ 'secret' => '{"merchant":"shop-a","api_key":"fake-secret"}', 'url' => '{"merchant":"shop-a","url":"https://other.test"}', 'headers' => '{"merchant":"shop-a","headers":{}}', 'invalid name' => '{"merchant":"Shop-a"}', + 'duplicate selector' => '{"merchant":"shop-a","merchant":"shop-b"}', + 'escaped duplicate selector' => '{"merchant":"shop-a","merch\\u0061nt":"shop-b"}', ]); it('rejects a directory masquerading as a project file', function (): void { diff --git a/tests/Unit/Credentials/MerchantConfigurationJsonTest.php b/tests/Unit/Credentials/MerchantConfigurationJsonTest.php new file mode 100644 index 0000000..5c8b18a --- /dev/null +++ b/tests/Unit/Credentials/MerchantConfigurationJsonTest.php @@ -0,0 +1,17 @@ +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}]', +]); From fa0233cf371ec1d69958fd1e5ce5184751d9524e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Thu, 1 Oct 2026 17:12:22 +0200 Subject: [PATCH 06/16] Test bundled filesystem path validation Extend the distribution contract coverage for the packaged binary by asserting that the bundled Flysystem rejects malformed paths while still normalizing valid paths as expected. This also captures the related Flysystem lockfile update that the new assertions depend on. --- composer.lock | 12 ++++----- .../Architecture/DistributionContractTest.php | 25 +++++++++++++++++++ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/composer.lock b/composer.lock index 28c9ce3..ad9245f 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", 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'], +]); From ee409db38c748680eca71a1586d231fe7b2b50cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Mon, 23 Nov 2026 12:03:12 +0100 Subject: [PATCH 07/16] refactor: split merchant command tests and tidy credential handling Split the merchant command feature tests into one file per command with shared helpers in tests/Pest.php, simplify the merchant and credential code paths, and trim the README and bundled skill. Co-Authored-By: Claude Opus 5.5 --- README.md | 160 +++------ app/Callbacks/Signing/CallbackEnvelope.php | 1 - .../Signing/CallbackEnvelopeFactory.php | 2 - .../Watching/CallbackWatchRunner.php | 1 - app/Commands/Api/ApiRequestCommand.php | 11 - .../Merchants/ActiveMerchantCommand.php | 43 ++- app/Commands/Merchants/AddMerchantCommand.php | 9 +- .../Merchants/ListMerchantsCommand.php | 12 +- .../Merchants/SelectMerchantCommand.php | 14 +- .../AbstractPaymentMutationCommand.php | 12 - app/Console/AuthenticatedCommand.php | 14 +- app/Credentials/ApiKeyResolver.php | 17 +- app/Credentials/MerchantConfigurationJson.php | 4 +- app/Credentials/MerchantName.php | 4 +- app/Credentials/MerchantStore.php | 23 +- app/Credentials/ProjectMerchantFile.php | 7 +- app/Quickpay/AuthenticatedQuickpay.php | 10 - app/Quickpay/QuickpayClient.php | 20 -- skills/quickpay-cli/SKILL.md | 14 +- .../Commands/Api/ApiRequestCommandTest.php | 3 - .../Callbacks/ReplayCallbackCommandTest.php | 3 - .../Callbacks/WatchCallbacksCommandTest.php | 3 - .../Merchants/ActiveMerchantCommandTest.php | 81 +++++ .../Merchants/AddMerchantCommandTest.php | 83 +++++ .../Merchants/ListMerchantsCommandTest.php | 27 ++ .../Merchants/MerchantCommandsTest.php | 306 ------------------ .../Merchants/RemoveMerchantCommandTest.php | 22 ++ .../Merchants/SelectMerchantCommandTest.php | 60 ++++ .../Payments/CreatePaymentCommandTest.php | 3 - .../Payments/CreatePaymentLinkCommandTest.php | 3 - .../Payments/GetPaymentCommandTest.php | 3 - .../Payments/ListPaymentsCommandTest.php | 3 - .../Payments/PaymentMutationCommandsTest.php | 3 - tests/Feature/Quickpay/QuickpayClientTest.php | 8 +- .../Credentials/ProjectMerchantFileTest.php | 8 +- tests/Pest.php | 45 +++ tests/Unit/Credentials/MerchantNameTest.php | 15 +- 37 files changed, 483 insertions(+), 574 deletions(-) create mode 100644 tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php create mode 100644 tests/Feature/Commands/Merchants/AddMerchantCommandTest.php create mode 100644 tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php delete mode 100644 tests/Feature/Commands/Merchants/MerchantCommandsTest.php create mode 100644 tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php create mode 100644 tests/Feature/Commands/Merchants/SelectMerchantCommandTest.php diff --git a/README.md b/README.md index b90ac09..bfe9b3c 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,154 +19,88 @@ 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 [quickpay-cli skill](skills/quickpay-cli/SKILL.md) for coding agents: - -```bash -skills add tehwave/quickpay-cli -``` - -If you previously installed this project's skill as `quickpay`, remove that -installed copy and run the installation command again. Check its origin before -removal so an unrelated Quickpay skill stays intact. +## Authentication -Save access to each merchant once. The CLI privately prompts for its API key: +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 -quickpay merchants:add shop-a +quickpay merchants:add "My Website" ``` -Credentials are stored in `~/.config/quickpay-cli/config.json` with a `0700` -directory and `0600` file. Merchant names are local labels you choose, not verified -Quickpay account names or merchant IDs. Names contain 1-64 lowercase ASCII -letters, digits or single separating hyphens, starting with a letter. +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. -For automation, supply the API key through `QUICKPAY_API_KEY`. It cannot be -combined with `--merchant` or a project binding; unset it before selecting a -saved merchant. - -## Usage +## Merchants ```bash -quickpay list +quickpay merchants:add "My Other Website" +quickpay merchants:select "My Other Website" +quickpay merchants:active --check +quickpay payments:list --merchant="My Website" ``` -Use `--help` to explore any command and its options: +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`. -```bash -quickpay callbacks:watch --help -``` +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`. -### Select a merchant +## Payments ```bash -quickpay merchants:add shop-b -quickpay merchants:list -quickpay merchants:select shop-a -quickpay merchants:select # Interactive picker -quickpay merchants:active # Local configuration, no API request -quickpay merchants:active --check --json # Verify API access for automation -quickpay payments:list --merchant=shop-b +quickpay payments:list +quickpay payments:get --json +quickpay payments:link 1000 ``` -The first saved merchant becomes the global default. Adding another merchant -keeps that default. Select a different default with `merchants:select`, or use -`--merchant` for one payment, callback or raw API command. - -Bind the current project without changing the global default: - -```bash -quickpay merchants:select shop-b --local -``` - -Run this from the project root. It writes `.quickpay-cli.json` containing only -`{"merchant":"shop-b"}`. Commands search the current directory and its parents -for the nearest binding. Ignore this file in Git when the selection is specific -to one developer. The selection order is an explicit `--merchant`, then the -nearest project binding, then the global default. Unknown names and invalid -bindings fail without silently switching to another merchant. - -Each invocation resolves its merchant once. A running callback watcher stays -attached to that merchant when another command changes selection or removes the -saved credential. Mutation confirmations and watcher startup show the saved -label and credential source; payment confirmations also show the API's merchant -ID when available. These messages go to stderr in JSON mode. +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. -`merchants:active` reports configuration. Add `--check` to verify the key against -Quickpay; a missing or rejected credential exits non-zero. `--json` keeps the -status machine-readable, with diagnostics on stderr. +Run `quickpay list` for all commands or `quickpay --help` for options. -Rotate a saved key with `quickpay merchants:add shop-a --replace`. The old key -remains intact if validation fails. `quickpay merchants:remove shop-a` removes -only local access, never the remote account. Removing the default leaves no -default; it does not select another saved merchant. Any binding to a removed -merchant will fail until you select a valid one. - -This pre-v1 change replaces `login`, `logout` and `auth`. The old -`~/.config/quickpay/config.json` is not read or migrated. Add each merchant again -with `merchants:add`; after setup, you may remove the old file yourself. - -### Watch for callbacks and relay them +## Local callbacks ```bash quickpay callbacks:watch --to=http://127.0.0.1:8000/quickpay/callback ``` -Leave the watcher running while testing the payment flow. It signs and sends -payment updates to your local callback handler. - -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. - -An explicit `QUICKPAY_PRIVATE_KEY` must belong to the selected merchant. Without -that override, the CLI fetches the signing key through the same merchant's API -access and keeps it only in memory. +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 -quickpay callbacks:replay --to= +quickpay callbacks:replay --to=http://127.0.0.1:8000/quickpay/callback ``` -## Development +## For agents + +Install the bundled [quickpay-cli skill](skills/quickpay-cli/SKILL.md): ```bash -composer install -composer check -composer verify +skills add tehwave/quickpay-cli ``` -`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. - -Maintainers should follow [RELEASING.md](RELEASING.md) for versioned releases. - -## Security - -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. - -## Credits - -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/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 de57ea7..fef1c48 100644 --- a/app/Commands/Api/ApiRequestCommand.php +++ b/app/Commands/Api/ApiRequestCommand.php @@ -101,17 +101,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/Merchants/ActiveMerchantCommand.php b/app/Commands/Merchants/ActiveMerchantCommand.php index 479781b..b1cdbd4 100644 --- a/app/Commands/Merchants/ActiveMerchantCommand.php +++ b/app/Commands/Merchants/ActiveMerchantCommand.php @@ -4,6 +4,7 @@ use App\Console\AuthenticatedCommand; use App\Console\Output\JsonOutput; +use App\Credentials\ApiKey; use App\Credentials\ApiKeyResolver; use App\Credentials\Exceptions\CredentialException; use App\Quickpay\Exceptions\QuickpayRequestException; @@ -27,31 +28,22 @@ public function handle(ApiKeyResolver $resolver, MerchantAuthenticationCheck $ch } catch (CredentialException $exception) { return $this->failure($exception->getMessage()); } - $requested = (bool) $this->option('check'); - $error = null; - if ($requested) { - if ($key === null) { - $error = 'No Quickpay credentials found. Run quickpay merchants:add first.'; - } else { - try { - $check->check($key); - } catch (QuickpayRequestException|UnexpectedValueException $exception) { - $error = $key->redact($exception->getMessage()); - } - } - } - $authenticated = $requested ? $error === null : null; + + $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, - 'checked' => $requested, + '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 { @@ -61,9 +53,28 @@ public function handle(ApiKeyResolver $resolver, MerchantAuthenticationCheck $ch $this->line('Credentials configured: '.($status['configured'] ? 'yes' : 'no')); $this->line('API base URL: '.$status['api_base_url']); $this->line('API version: '.$status['api_version']); - $this->line('API access: '.($requested ? ($authenticated ? 'verified' : 'failed') : 'not checked')); + $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 'No Quickpay credentials found. Run quickpay merchants:add first.'; + } + + 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 index eb33c2a..dac72e3 100644 --- a/app/Commands/Merchants/AddMerchantCommand.php +++ b/app/Commands/Merchants/AddMerchantCommand.php @@ -15,7 +15,7 @@ class AddMerchantCommand extends BaseCommand { protected $signature = 'merchants:add - {name : Local merchant name, for example shop-a} + {name : Local merchant name, for example "My Website"} {--replace : Replace this saved merchant credential after validation}'; protected $description = 'Validate and save API access to an existing Quickpay merchant'; @@ -23,24 +23,31 @@ class AddMerchantCommand extends BaseCommand public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, StdinTerminalDetector $terminal): int { $credential = null; + try { $name = MerchantName::validate((string) $this->argument('name')); $config = $store->read(); + if (isset($config['merchants'][$name]) && ! $this->option('replace')) { return $this->failure('Merchant is already saved. Use --replace to replace its credential.'); } + 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'); if ($credential->appearsIn($name)) { return $this->failure('Merchant name must not contain the API key.'); } + $check->check($credential); $store->add($name, $apiKey, (bool) $this->option('replace')); $this->info('Merchant saved: '.$name); diff --git a/app/Commands/Merchants/ListMerchantsCommand.php b/app/Commands/Merchants/ListMerchantsCommand.php index a850fd5..7425f3c 100644 --- a/app/Commands/Merchants/ListMerchantsCommand.php +++ b/app/Commands/Merchants/ListMerchantsCommand.php @@ -20,15 +20,23 @@ public function handle(MerchantStore $store): int } 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], $names); + $rows = array_map(fn (string $name): array => [ + 'name' => $name, + 'default' => $config['default_merchant'] === $name, + ], $names); + if ($this->option('json')) { $this->getOutput()->write(JsonOutput::value($rows, '')); } elseif ($rows === []) { $this->line('No saved merchants. Run quickpay merchants:add first.'); } else { - $this->table(['Merchant', 'Global default'], array_map(fn (array $row): array => [$row['name'], $row['default'] ? 'yes' : ''], $rows)); + $this->table(['Merchant', 'Global default'], array_map(fn (array $row): array => [ + $row['name'], + $row['default'] ? 'yes' : '', + ], $rows)); } return self::SUCCESS; diff --git a/app/Commands/Merchants/SelectMerchantCommand.php b/app/Commands/Merchants/SelectMerchantCommand.php index 01dc3d6..7b4059f 100644 --- a/app/Commands/Merchants/SelectMerchantCommand.php +++ b/app/Commands/Merchants/SelectMerchantCommand.php @@ -6,7 +6,6 @@ use App\Console\Terminal\StdinTerminalDetector; use App\Credentials\EnvironmentVariables; use App\Credentials\Exceptions\CredentialException; -use App\Credentials\MerchantName; use App\Credentials\MerchantStore; use App\Credentials\ProjectMerchantFile; @@ -24,31 +23,38 @@ public function handle(MerchantStore $store, ProjectMerchantFile $project, Envir if ($environment->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') { + $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.'); } - $name = MerchantName::validate($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); diff --git a/app/Commands/Payments/AbstractPaymentMutationCommand.php b/app/Commands/Payments/AbstractPaymentMutationCommand.php index f6d5f56..a9df855 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. @@ -136,17 +135,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/Console/AuthenticatedCommand.php b/app/Console/AuthenticatedCommand.php index edfa01f..154229a 100644 --- a/app/Console/AuthenticatedCommand.php +++ b/app/Console/AuthenticatedCommand.php @@ -50,14 +50,20 @@ protected function responseFailure(QuickpayResponse $response, string $apiKey): protected function writeMerchantContext(AuthenticatedQuickpay $authenticated): void { - $output = $this->input->hasOption('json') && $this->input->getOption('json') - ? $this->getOutput()->getErrorStyle() - : $this->getOutput(); foreach ([ 'Merchant: '.($authenticated->apiKey->merchant() ?? 'not associated with a saved merchant'), 'Credential source: '.$authenticated->apiKey->source(), ] as $message) { - $output->writeln($authenticated->safeLine($message), OutputInterface::OUTPUT_RAW); + $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/ApiKeyResolver.php b/app/Credentials/ApiKeyResolver.php index f4b3aa6..641d4b1 100644 --- a/app/Credentials/ApiKeyResolver.php +++ b/app/Credentials/ApiKeyResolver.php @@ -17,24 +17,33 @@ 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.'); } - $binding = $merchant === null ? $this->project->find() : null; - if ($environmentKey !== null && $binding !== null) { + + $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', null, 'environment'); } $config = $this->store->read(); - $source = $merchant !== null ? 'explicit' : ($binding !== null ? 'project' : 'default'); - $name = $merchant ?? $binding['merchant'] ?? $config['default_merchant']; + $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('Selected merchant is not saved. Run quickpay merchants:list to see saved names.'); } diff --git a/app/Credentials/MerchantConfigurationJson.php b/app/Credentials/MerchantConfigurationJson.php index 58b1f83..cbc4a48 100644 --- a/app/Credentials/MerchantConfigurationJson.php +++ b/app/Credentials/MerchantConfigurationJson.php @@ -22,8 +22,8 @@ public static function decode(string $contents): mixed array_pop($objects); } elseif ($token[0] === '"' && ($tokens[$index + 1] ?? null) === ':') { $name = json_decode($token, flags: JSON_THROW_ON_ERROR); - $scope = array_key_last($objects); - if (! is_string($name) || $scope === null || isset($objects[$scope][$name])) { + $scope = count($objects) - 1; + if (isset($objects[$scope][$name])) { throw new JsonException('Ambiguous configuration contains duplicate JSON properties.'); } $objects[$scope][$name] = true; diff --git a/app/Credentials/MerchantName.php b/app/Credentials/MerchantName.php index ca4ff77..1e62e43 100644 --- a/app/Credentials/MerchantName.php +++ b/app/Credentials/MerchantName.php @@ -8,8 +8,8 @@ final class MerchantName { public static function validate(string $name): string { - if (strlen($name) > 64 || preg_match('/\A[a-z][a-z0-9]*(?:-[a-z0-9]+)*\z/D', $name) !== 1) { - throw new CredentialException('Merchant names must contain 1-64 lowercase ASCII letters, digits or single separating hyphens, starting with a letter.'); + if (strlen($name) > 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; diff --git a/app/Credentials/MerchantStore.php b/app/Credentials/MerchantStore.php index 99b8922..641f320 100644 --- a/app/Credentials/MerchantStore.php +++ b/app/Credentials/MerchantStore.php @@ -48,8 +48,7 @@ public function read(): array if (! $config instanceof stdClass || count(get_object_vars($config)) !== 2 || ! property_exists($config, 'default_merchant') - || ! isset($config->merchants) - || ! $config->merchants instanceof stdClass + || ! ($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.'); } @@ -59,8 +58,7 @@ public function read(): array MerchantName::validate((string) $name); if (! $merchant instanceof stdClass || count(get_object_vars($merchant)) !== 1 - || ! isset($merchant->api_key) - || ! is_string($merchant->api_key) + || ! is_string($merchant->api_key ?? null) || trim($merchant->api_key) === '') { throw new CredentialException('Quickpay CLI merchant configuration contains an invalid credential.'); } @@ -82,8 +80,6 @@ public function add(string $name, string $apiKey, bool $replace = false): void if ($apiKey === '') { throw new CredentialException('API key cannot be empty.'); } - $this->validateLabel($name, $apiKey); - $this->mutate(function (array $config) use ($name, $apiKey, $replace): array { if (isset($config['merchants'][$name]) && ! $replace) { throw new CredentialException('Merchant is already saved. Use --replace to replace its credential.'); @@ -100,7 +96,6 @@ public function add(string $name, string $apiKey, bool $replace = false): void public function select(string $name): void { - MerchantName::validate($name); $this->mutate(function (array $config) use ($name): array { $this->requireMerchant($config, $name); $config['default_merchant'] = $name; @@ -111,7 +106,6 @@ public function select(string $name): void public function remove(string $name): void { - MerchantName::validate($name); $this->mutate(function (array $config) use ($name): array { $this->requireMerchant($config, $name); unset($config['merchants'][$name]); @@ -123,20 +117,15 @@ public function remove(string $name): void }); } - private function validateLabel(string $name, string $apiKey): void - { - if (CredentialRedactor::containsSensitiveValue($name, $apiKey)) { - throw new CredentialException('Merchant name must not contain the API key.'); - } - } - /** @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 ($merchants as $name => $merchant) { + foreach (array_keys($merchants) as $name) { foreach ($merchants as $credential) { - $this->validateLabel($name, $credential['api_key']); + if (CredentialRedactor::containsSensitiveValue($name, $credential['api_key'])) { + throw new CredentialException('Merchant name must not contain the API key.'); + } } } } diff --git a/app/Credentials/ProjectMerchantFile.php b/app/Credentials/ProjectMerchantFile.php index d30fdeb..ab317e8 100644 --- a/app/Credentials/ProjectMerchantFile.php +++ b/app/Credentials/ProjectMerchantFile.php @@ -10,14 +10,13 @@ { public function __construct(private ?string $directory = null) {} - /** @return array{merchant: string, path: string}|null */ - public function find(): ?array + public function find(): ?string { $directory = $this->directory(); while (true) { $path = $directory.'/.quickpay-cli.json'; if (file_exists($path) || is_link($path)) { - return ['merchant' => $this->read($path), 'path' => $path]; + return $this->read($path); } $parent = dirname($directory); if ($parent === $directory) { @@ -73,7 +72,7 @@ private function read(string $path): string } catch (JsonException) { throw new CredentialException('Project merchant binding is invalid JSON.'); } - if (! $config instanceof stdClass || count(get_object_vars($config)) !== 1 || ! isset($config->merchant) || ! is_string($config->merchant)) { + if (! $config instanceof stdClass || count(get_object_vars($config)) !== 1 || ! is_string($config->merchant ?? null)) { throw new CredentialException('Project merchant binding must contain only a merchant name.'); } 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/QuickpayClient.php b/app/Quickpay/QuickpayClient.php index d74a87a..b4bac0b 100644 --- a/app/Quickpay/QuickpayClient.php +++ b/app/Quickpay/QuickpayClient.php @@ -56,26 +56,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 diff --git a/skills/quickpay-cli/SKILL.md b/skills/quickpay-cli/SKILL.md index 43442e6..37a4d97 100644 --- a/skills/quickpay-cli/SKILL.md +++ b/skills/quickpay-cli/SKILL.md @@ -19,12 +19,14 @@ 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 `shop-a` are local labels, not verified merchant IDs. `merchants:list` lists +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. Only change persistent selection when the -user asks for it; prefer `--merchant=` for one command. +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, @@ -58,9 +60,9 @@ Existing users add their merchants again; no automatic migration occurs. Safe capture example, only after inspection and explicit authorization: ```bash -quickpay merchants:active --merchant=shop-a --check --json -quickpay payments:get 884201 --merchant=shop-a --json -quickpay payments:capture 884201 2500 --merchant=shop-a --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. diff --git a/tests/Feature/Commands/Api/ApiRequestCommandTest.php b/tests/Feature/Commands/Api/ApiRequestCommandTest.php index 06fdbdf..a79493a 100644 --- a/tests/Feature/Commands/Api/ApiRequestCommandTest.php +++ b/tests/Feature/Commands/Api/ApiRequestCommandTest.php @@ -23,9 +23,6 @@ public function isTty(): bool }); afterEach(function () { - foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { - $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); - } rmdir($this->merchantProjectDirectory); if ($this->originalApiKey === false) { putenv('QUICKPAY_API_KEY'); diff --git a/tests/Feature/Commands/Callbacks/ReplayCallbackCommandTest.php b/tests/Feature/Commands/Callbacks/ReplayCallbackCommandTest.php index 0ec9ee3..f6640e7 100644 --- a/tests/Feature/Commands/Callbacks/ReplayCallbackCommandTest.php +++ b/tests/Feature/Commands/Callbacks/ReplayCallbackCommandTest.php @@ -22,9 +22,6 @@ }); afterEach(function () { - foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { - $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); - } rmdir($this->merchantProjectDirectory); foreach ([ 'QUICKPAY_API_KEY' => $this->originalApiKey, diff --git a/tests/Feature/Commands/Callbacks/WatchCallbacksCommandTest.php b/tests/Feature/Commands/Callbacks/WatchCallbacksCommandTest.php index a4fb032..b3b023f 100644 --- a/tests/Feature/Commands/Callbacks/WatchCallbacksCommandTest.php +++ b/tests/Feature/Commands/Callbacks/WatchCallbacksCommandTest.php @@ -29,9 +29,6 @@ }); afterEach(function () { - foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { - $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); - } rmdir($this->merchantProjectDirectory); foreach ([ 'QUICKPAY_API_KEY' => $this->originalApiKey, diff --git a/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php b/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php new file mode 100644 index 0000000..3b7308c --- /dev/null +++ b/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php @@ -0,0 +1,81 @@ +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, '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')->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('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(); + 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"},"sh\\u006fp-a":{"api_key":"fake-last"}}}'; + 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]); diff --git a/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php new file mode 100644 index 0000000..2788e02 --- /dev/null +++ b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php @@ -0,0 +1,83 @@ + 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('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', '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('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(); +}); diff --git a/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php b/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php new file mode 100644 index 0000000..3b22462 --- /dev/null +++ b/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php @@ -0,0 +1,27 @@ +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], ['name' => 'My Website', 'default' => true]]); + 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"},"fake-secret-a":{"api_key":"fake-secret-b"}}}'); + [$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(); +}); diff --git a/tests/Feature/Commands/Merchants/MerchantCommandsTest.php b/tests/Feature/Commands/Merchants/MerchantCommandsTest.php deleted file mode 100644 index 64a5933..0000000 --- a/tests/Feature/Commands/Merchants/MerchantCommandsTest.php +++ /dev/null @@ -1,306 +0,0 @@ - $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()]; -} - -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); - 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('adds a merchant after a private credential check', function (): void { - Http::fake(['https://api.quickpay.net/ping' => Http::response(['msg' => 'pong', 'scope' => 'merchant', 'version' => 'v10', 'params' => []])]); - $this->artisan('merchants:add', ['name' => 'shop-a']) - ->expectsQuestion('API key', ' fake-secret-a ') - ->expectsOutputToContain('Merchant saved: shop-a') - ->doesntExpectOutputToContain('fake-secret-a')->assertExitCode(0); - expect($this->store->read()['merchants']['shop-a']['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('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', 'path' => '../secret', 'uppercase' => 'Shop-a']); - -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('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('sanitizes authentication errors on stderr', function (string $form): void { - $this->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('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('lists only sorted names and the global default', function (): void { - $this->store->add('shop-b', 'fake-secret-b'); - $this->store->add('shop-a', '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' => 'shop-a', 'default' => false], ['name' => 'shop-b', 'default' => true]]); - 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('selects saved merchants globally without re-entering credentials', function (): void { - $this->store->add('shop-a', 'fake-secret-a'); - $this->store->add('shop-b', 'fake-secret-b'); - $this->artisan('merchants:select', ['name' => 'shop-b'])->assertExitCode(0); - expect($this->store->read()['default_merchant'])->toBe('shop-b'); - 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->artisan('merchants:select')->expectsChoice('Select merchant', $selection, ['shop-a', 'shop-b', 'Cancel'])->assertExitCode(0); - expect($this->store->read()['default_merchant'])->toBe($selection === 'Cancel' ? 'shop-a' : 'shop-b'); - Http::assertNothingSent(); -})->with(['selection' => 'shop-b', 'cancel' => 'Cancel']); - -it('selects a project merchant without changing the 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-b', '--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('shop-b') - ->and($this->store->read()['default_merchant'])->toBe('shop-a'); - mkdir($this->tempDirectory.'/other'); - chdir($this->tempDirectory.'/other'); - [$exit, $output] = merchantCommandResult(ActiveMerchantCommand::class, ['--json' => true]); - expect(json_decode($output, true)['merchant'])->toBe('shop-a'); - Http::assertNothingSent(); -}); - -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]]]); - -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, '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')->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('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(); - 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('shop-a', 'fake-secret-a'); - $this->store->add('shop-b', 'fake-secret-b'); - [$exit, $output, $errors] = merchantCommandResult(ActiveMerchantCommand::class, ['--merchant' => 'shop-b', '--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('shop-b'); - 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('removes only the named credential without choosing another default', function (): void { - $this->store->add('shop-a', 'fake-secret-a'); - $this->store->add('shop-b', 'fake-secret-b'); - $this->artisan('merchants:remove', ['name' => 'shop-a'])->assertExitCode(0); - expect($this->store->read())->toBe(['default_merchant' => null, 'merchants' => ['shop-b' => ['api_key' => 'fake-secret-b']]]); - $this->artisan('merchants:remove', ['name' => 'shop-missing'])->assertExitCode(1); - $this->artisan('merchants:remove', ['name' => 'shop-b'])->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(); -}); - -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"},"sh\\u006fp-a":{"api_key":"fake-last"}}}'; - 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('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"},"fake-secret-a":{"api_key":"fake-secret-b"}}}'); - [$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(); -}); diff --git a/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php b/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php new file mode 100644 index 0000000..25a3d7b --- /dev/null +++ b/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php @@ -0,0 +1,22 @@ +store->add('My Other Website', 'fake-secret-a'); + $this->store->add('My Website', 'fake-secret-b'); + $this->artisan('merchants:remove', ['name' => 'My Other Website'])->assertExitCode(0); + expect($this->store->read())->toBe(['default_merchant' => null, 'merchants' => ['My Website' => ['api_key' => 'fake-secret-b']]]); + $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..001c71d --- /dev/null +++ b/tests/Feature/Commands/Merchants/SelectMerchantCommandTest.php @@ -0,0 +1,60 @@ +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('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/Payments/CreatePaymentCommandTest.php b/tests/Feature/Commands/Payments/CreatePaymentCommandTest.php index 68957a5..5bb7f58 100644 --- a/tests/Feature/Commands/Payments/CreatePaymentCommandTest.php +++ b/tests/Feature/Commands/Payments/CreatePaymentCommandTest.php @@ -15,9 +15,6 @@ }); afterEach(function () { - foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { - $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); - } rmdir($this->merchantProjectDirectory); if ($this->originalApiKey === false) { putenv('QUICKPAY_API_KEY'); diff --git a/tests/Feature/Commands/Payments/CreatePaymentLinkCommandTest.php b/tests/Feature/Commands/Payments/CreatePaymentLinkCommandTest.php index a5549d5..1865b22 100644 --- a/tests/Feature/Commands/Payments/CreatePaymentLinkCommandTest.php +++ b/tests/Feature/Commands/Payments/CreatePaymentLinkCommandTest.php @@ -15,9 +15,6 @@ }); afterEach(function () { - foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { - $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); - } rmdir($this->merchantProjectDirectory); if ($this->originalApiKey === false) { putenv('QUICKPAY_API_KEY'); diff --git a/tests/Feature/Commands/Payments/GetPaymentCommandTest.php b/tests/Feature/Commands/Payments/GetPaymentCommandTest.php index b6135b1..cf9eb5c 100644 --- a/tests/Feature/Commands/Payments/GetPaymentCommandTest.php +++ b/tests/Feature/Commands/Payments/GetPaymentCommandTest.php @@ -15,9 +15,6 @@ }); afterEach(function () { - foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { - $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); - } rmdir($this->merchantProjectDirectory); if ($this->originalApiKey === false) { putenv('QUICKPAY_API_KEY'); diff --git a/tests/Feature/Commands/Payments/ListPaymentsCommandTest.php b/tests/Feature/Commands/Payments/ListPaymentsCommandTest.php index a4d6824..998cb02 100644 --- a/tests/Feature/Commands/Payments/ListPaymentsCommandTest.php +++ b/tests/Feature/Commands/Payments/ListPaymentsCommandTest.php @@ -18,9 +18,6 @@ }); afterEach(function () { - foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { - $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); - } rmdir($this->merchantProjectDirectory); if ($this->originalApiKey === false) { putenv('QUICKPAY_API_KEY'); diff --git a/tests/Feature/Commands/Payments/PaymentMutationCommandsTest.php b/tests/Feature/Commands/Payments/PaymentMutationCommandsTest.php index 6cb9a61..b70bdc0 100644 --- a/tests/Feature/Commands/Payments/PaymentMutationCommandsTest.php +++ b/tests/Feature/Commands/Payments/PaymentMutationCommandsTest.php @@ -25,9 +25,6 @@ public function isTty(): bool }); afterEach(function () { - foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->merchantProjectDirectory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) { - $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname()); - } rmdir($this->merchantProjectDirectory); if ($this->originalApiKey === false) { putenv('QUICKPAY_API_KEY'); diff --git a/tests/Feature/Quickpay/QuickpayClientTest.php b/tests/Feature/Quickpay/QuickpayClientTest.php index ec17b0d..b7cae0f 100644 --- a/tests/Feature/Quickpay/QuickpayClientTest.php +++ b/tests/Feature/Quickpay/QuickpayClientTest.php @@ -26,11 +26,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']); + $response = $client->raw($method, '/resources', ['page' => 2], ['name' => 'Example']); expect($response->successful())->toBeTrue(); @@ -53,7 +53,7 @@ ->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++; @@ -63,7 +63,7 @@ $client = new QuickpayClient(app(Factory::class), 'secret'); - 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']); diff --git a/tests/Integration/Credentials/ProjectMerchantFileTest.php b/tests/Integration/Credentials/ProjectMerchantFileTest.php index 7f80e40..2808d6f 100644 --- a/tests/Integration/Credentials/ProjectMerchantFileTest.php +++ b/tests/Integration/Credentials/ProjectMerchantFileTest.php @@ -20,10 +20,10 @@ $parent = new ProjectMerchantFile($this->tempDirectory); $child = new ProjectMerchantFile($this->tempDirectory.'/nested'); $parent->save('shop-a'); - expect($child->find())->toBe(['merchant' => 'shop-a', 'path' => $this->tempDirectory.'/.quickpay-cli.json']); + expect($child->find())->toBe('shop-a'); $child->save('shop-b'); - expect($child->find())->toBe(['merchant' => 'shop-b', 'path' => $this->tempDirectory.'/nested/.quickpay-cli.json']) - ->and($parent->find()['merchant'])->toBe('shop-a') + 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([]); }); @@ -40,7 +40,7 @@ '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":"Shop-a"}', + '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"}', ]); 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/MerchantNameTest.php b/tests/Unit/Credentials/MerchantNameTest.php index 78d350d..7224dbb 100644 --- a/tests/Unit/Credentials/MerchantNameTest.php +++ b/tests/Unit/Credentials/MerchantNameTest.php @@ -5,13 +5,22 @@ it('accepts exact bounded merchant names', function (string $name): void { expect(MerchantName::validate($name))->toBe($name); -})->with(['one letter' => 'a', 'maximum' => str_repeat('a', 64), 'shop' => 'shop-a1']); +})->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('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), 'uppercase' => 'Shop-a', + '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', 'space' => 'shop a', 'newline' => "shop\na", 'escape' => "shop\x1ba", + 'backslash' => 'shop\\a', 'newline' => "shop\na", 'escape' => "shop\x1ba", ]); From 57d61280751f284a1332a7f1e4b1117e2a08ca87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Mon, 23 Nov 2026 14:14:14 +0100 Subject: [PATCH 08/16] fix: harden merchant selection from review findings - Make the duplicate-property scan in merchant configuration JSON immune to regex backtracking limits and reject the file if it fails - Reject project merchant bindings not owned by the current user - Refuse merchants:add --replace for a merchant that is not saved - Point to merchants:select when no default merchant is selected, and say so after merchants:remove clears the default - Warn after merchants:add that the old single-key config file is unused and can be deleted, without reading it - Print the merchant context for payments:create and payments:link - Name the binding file in binding errors and give stale bindings their own message - Show "Merchant: none" in merchants:active without credentials and drop the constant API base URL and version lines from its human output Co-Authored-By: Claude Opus 5.5 --- SECURITY.md | 3 ++- .../Merchants/ActiveMerchantCommand.php | 6 ++--- app/Commands/Merchants/AddMerchantCommand.php | 16 +++++++++++- .../Merchants/RemoveMerchantCommand.php | 4 +++ .../Payments/CreatePaymentCommand.php | 1 + .../Payments/CreatePaymentLinkCommand.php | 1 + app/Console/AuthenticatedCommand.php | 5 +++- app/Credentials/ApiKeyResolver.php | 5 +++- app/Credentials/MerchantConfigurationJson.php | 6 ++++- app/Credentials/MerchantStore.php | 24 +++++++++++++++-- app/Credentials/ProjectMerchantFile.php | 26 +++++++++++++++---- skills/quickpay-cli/SKILL.md | 8 +++--- .../Merchants/ActiveMerchantCommandTest.php | 10 +++++++ .../Merchants/AddMerchantCommandTest.php | 22 ++++++++++++++++ .../Merchants/RemoveMerchantCommandTest.php | 3 ++- .../Console/AuthenticatedCommandTest.php | 15 +++++++++++ .../Credentials/MerchantStoreTest.php | 12 +++++++++ .../Credentials/ProjectMerchantFileTest.php | 9 ++++++- tests/Unit/Credentials/ApiKeyResolverTest.php | 2 +- .../MerchantConfigurationJsonTest.php | 13 ++++++++++ 20 files changed, 169 insertions(+), 22 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 4af9e03..23e9fee 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -48,7 +48,8 @@ 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 fail without selecting another merchant. A non-empty +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 diff --git a/app/Commands/Merchants/ActiveMerchantCommand.php b/app/Commands/Merchants/ActiveMerchantCommand.php index b1cdbd4..72c404d 100644 --- a/app/Commands/Merchants/ActiveMerchantCommand.php +++ b/app/Commands/Merchants/ActiveMerchantCommand.php @@ -47,12 +47,10 @@ public function handle(ApiKeyResolver $resolver, MerchantAuthenticationCheck $ch if ($this->option('json')) { $this->getOutput()->write(JsonOutput::value($status, '')); } else { - $this->line('Merchant: '.($status['merchant'] ?? 'not associated with a saved merchant')); + $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')); $this->line('Credentials configured: '.($status['configured'] ? 'yes' : 'no')); - $this->line('API base URL: '.$status['api_base_url']); - $this->line('API version: '.$status['api_version']); $this->line('API access: '.match ($authenticated) { true => 'verified', false => 'failed', @@ -66,7 +64,7 @@ public function handle(ApiKeyResolver $resolver, MerchantAuthenticationCheck $ch private function authenticationError(?ApiKey $key, MerchantAuthenticationCheck $check): ?string { if ($key === null) { - return 'No Quickpay credentials found. Run quickpay merchants:add first.'; + return self::NO_MERCHANT_SELECTED; } try { diff --git a/app/Commands/Merchants/AddMerchantCommand.php b/app/Commands/Merchants/AddMerchantCommand.php index dac72e3..3a994cc 100644 --- a/app/Commands/Merchants/AddMerchantCommand.php +++ b/app/Commands/Merchants/AddMerchantCommand.php @@ -3,6 +3,7 @@ namespace App\Commands\Merchants; use App\Console\BaseCommand; +use App\Console\Output\ResponseBodySanitizer; use App\Console\Terminal\StdinTerminalDetector; use App\Credentials\ApiKey; use App\Credentials\Exceptions\CredentialException; @@ -28,10 +29,15 @@ public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, $name = MerchantName::validate((string) $this->argument('name')); $config = $store->read(); - if (isset($config['merchants'][$name]) && ! $this->option('replace')) { + $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.'); + } + if (! $this->input->isInteractive() || ! $terminal->isTty()) { return $this->failure('Adding a merchant requires an interactive terminal. Use QUICKPAY_API_KEY for automation.'); } @@ -52,6 +58,14 @@ public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, $store->add($name, $apiKey, (bool) $this->option('replace')); $this->info('Merchant saved: '.$name); + $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/RemoveMerchantCommand.php b/app/Commands/Merchants/RemoveMerchantCommand.php index 7791b35..5a8475d 100644 --- a/app/Commands/Merchants/RemoveMerchantCommand.php +++ b/app/Commands/Merchants/RemoveMerchantCommand.php @@ -17,10 +17,14 @@ public function handle(MerchantStore $store, EnvironmentVariables $environment): { try { $store->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.'); } 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 154229a..69d4a5a 100644 --- a/app/Console/AuthenticatedCommand.php +++ b/app/Console/AuthenticatedCommand.php @@ -16,6 +16,9 @@ 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(); @@ -33,7 +36,7 @@ protected function withQuickpay(AuthenticatedQuickpayFactory $quickpay, Closure } if ($authenticated === null) { - return $this->failure('No Quickpay credentials found. Run quickpay merchants:add first.'); + return $this->failure(self::NO_MERCHANT_SELECTED); } try { diff --git a/app/Credentials/ApiKeyResolver.php b/app/Credentials/ApiKeyResolver.php index 641d4b1..b4b7b07 100644 --- a/app/Credentials/ApiKeyResolver.php +++ b/app/Credentials/ApiKeyResolver.php @@ -45,7 +45,10 @@ public function resolve(?string $merchant = null): ?ApiKey } if (! isset($config['merchants'][$name])) { - throw new CredentialException('Selected merchant is not saved. Run quickpay merchants:list to see saved names.'); + 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.', + }); } return new ApiKey($config['merchants'][$name]['api_key'], 'config file', $name, $source); diff --git a/app/Credentials/MerchantConfigurationJson.php b/app/Credentials/MerchantConfigurationJson.php index cbc4a48..cd50a53 100644 --- a/app/Credentials/MerchantConfigurationJson.php +++ b/app/Credentials/MerchantConfigurationJson.php @@ -12,7 +12,11 @@ public static function decode(string $contents): mixed // Native decoding discards duplicate fields. Inspect complete JSON string // tokens per object so escaped names collide, but quoted values do not. - preg_match_all('/"(?:[^"\\\\]|\\\\.)*"|[{}:]/s', $contents, $matches); + // Possessive quantifiers keep long strings within PCRE limits, and a + // failed scan rejects the file instead of skipping the duplicate check. + if (preg_match_all('/"(?:[^"\\\\]++|\\\\.)*+"|[{}:]/s', $contents, $matches) === false) { + throw new JsonException('Configuration could not be checked for duplicate JSON properties.'); + } $tokens = $matches[0]; $objects = []; foreach ($tokens as $index => $token) { diff --git a/app/Credentials/MerchantStore.php b/app/Credentials/MerchantStore.php index 641f320..ff711a5 100644 --- a/app/Credentials/MerchantStore.php +++ b/app/Credentials/MerchantStore.php @@ -11,11 +11,16 @@ /** @phpstan-type MerchantConfig array{default_merchant: ?string, merchants: array} */ final readonly class MerchantStore { - public function __construct(private string $path) {} + public function __construct( + private string $path, + private ?string $legacyPath = null, + ) {} public static function inHome(HomeDirectory $home): self { - return new self(rtrim($home->path(), DIRECTORY_SEPARATOR).'/.config/quickpay-cli/config.json'); + $home = rtrim($home->path(), DIRECTORY_SEPARATOR); + + return new self($home.'/.config/quickpay-cli/config.json', $home.'/.config/quickpay/config.json'); } public function path(): string @@ -23,6 +28,18 @@ 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 + { + return $this->legacyPath !== null && (file_exists($this->legacyPath) || is_link($this->legacyPath)) + ? $this->legacyPath + : null; + } + /** @return MerchantConfig */ public function read(): array { @@ -84,6 +101,9 @@ public function add(string $name, string $apiKey, bool $replace = false): void 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.'); + } if ($config['merchants'] === []) { $config['default_merchant'] = $name; } diff --git a/app/Credentials/ProjectMerchantFile.php b/app/Credentials/ProjectMerchantFile.php index ab317e8..7eb90b2 100644 --- a/app/Credentials/ProjectMerchantFile.php +++ b/app/Credentials/ProjectMerchantFile.php @@ -2,13 +2,18 @@ namespace App\Credentials; +use App\Console\Output\ResponseBodySanitizer; use App\Credentials\Exceptions\CredentialException; use JsonException; use stdClass; final readonly class ProjectMerchantFile { - public function __construct(private ?string $directory = null) {} + /** @param ?int $owner Expected binding owner; defaults to the effective user where POSIX is available. */ + public function __construct( + private ?string $directory = null, + private ?int $owner = null, + ) {} public function find(): ?string { @@ -63,19 +68,30 @@ private function directory(): string private function read(string $path): string { + $location = ResponseBodySanitizer::terminalLine($path, ''); $contents = is_file($path) ? @file_get_contents($path) : false; if ($contents === false) { - throw new CredentialException('Project merchant binding cannot be read.'); + 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. + $owner = $this->owner ?? (function_exists('posix_geteuid') ? posix_geteuid() : null); + if ($owner !== null && @fileowner($path) !== $owner) { + throw new CredentialException("Project merchant binding {$location} is not owned by the current user."); } try { $config = MerchantConfigurationJson::decode($contents); } catch (JsonException) { - throw new CredentialException('Project merchant binding is invalid JSON.'); + throw new CredentialException("Project merchant binding {$location} is invalid JSON."); } if (! $config instanceof stdClass || count(get_object_vars($config)) !== 1 || ! is_string($config->merchant ?? null)) { - throw new CredentialException('Project merchant binding must contain only a merchant name.'); + throw new CredentialException("Project merchant binding {$location} must contain only a merchant name."); } - return MerchantName::validate($config->merchant); + try { + return MerchantName::validate($config->merchant); + } catch (CredentialException $exception) { + throw new CredentialException("Project merchant binding {$location}: {$exception->getMessage()}"); + } } } diff --git a/skills/quickpay-cli/SKILL.md b/skills/quickpay-cli/SKILL.md index 37a4d97..53baabf 100644 --- a/skills/quickpay-cli/SKILL.md +++ b/skills/quickpay-cli/SKILL.md @@ -35,15 +35,17 @@ and keep that same explicit selection for inspection and execution. Plain Selection is an explicit `--merchant`, then the nearest `.quickpay-cli.json` found from the working directory upwards, then the global default. Unknown -names and malformed or stale bindings fail without falling back. A non-empty +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` and private -human input; a rejected key preserves existing access. Removing the default +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. diff --git a/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php b/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php index 3b7308c..77ae048 100644 --- a/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php @@ -34,6 +34,16 @@ 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]); diff --git a/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php index 2788e02..3742566 100644 --- a/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php @@ -1,6 +1,7 @@ method() === 'GET' && $request->header('Authorization') === ['Basic '.base64_encode(':fake-secret-a')]); }); +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()); @@ -33,6 +46,15 @@ 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)]); diff --git a/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php b/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php index 25a3d7b..a995d24 100644 --- a/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php @@ -5,7 +5,8 @@ it('removes only the named credential without choosing another default', function (): void { $this->store->add('My Other Website', 'fake-secret-a'); $this->store->add('My Website', 'fake-secret-b'); - $this->artisan('merchants:remove', ['name' => 'My Other Website'])->assertExitCode(0); + $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']]]); $this->artisan('merchants:remove', ['name' => 'shop-missing'])->assertExitCode(1); $this->artisan('merchants:remove', ['name' => 'My Website'])->assertExitCode(0); diff --git a/tests/Feature/Console/AuthenticatedCommandTest.php b/tests/Feature/Console/AuthenticatedCommandTest.php index 493e280..559b958 100644 --- a/tests/Feature/Console/AuthenticatedCommandTest.php +++ b/tests/Feature/Console/AuthenticatedCommandTest.php @@ -7,6 +7,8 @@ use App\Commands\Callbacks\WatchCallbacksCommand; use App\Commands\Payments\CancelPaymentCommand; use App\Commands\Payments\CapturePaymentCommand; +use App\Commands\Payments\CreatePaymentCommand; +use App\Commands\Payments\CreatePaymentLinkCommand; use App\Commands\Payments\RefundPaymentCommand; use App\Console\Terminal\StdinTerminalDetector; use App\Credentials\ApiKeyResolver; @@ -124,6 +126,19 @@ public function isTty(): bool 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), diff --git a/tests/Integration/Credentials/MerchantStoreTest.php b/tests/Integration/Credentials/MerchantStoreTest.php index f1ce816..c998ee8 100644 --- a/tests/Integration/Credentials/MerchantStoreTest.php +++ b/tests/Integration/Credentials/MerchantStoreTest.php @@ -47,6 +47,14 @@ expect(file_get_contents($this->path))->toBe($before); })->with(['duplicate' => ['shop-a', 'fake-new'], 'empty key' => ['shop-b', ' '], 'secret label' => ['secret-name', 'secret']]); +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'); @@ -118,7 +126,11 @@ $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 { diff --git a/tests/Integration/Credentials/ProjectMerchantFileTest.php b/tests/Integration/Credentials/ProjectMerchantFileTest.php index 2808d6f..4934863 100644 --- a/tests/Integration/Credentials/ProjectMerchantFileTest.php +++ b/tests/Integration/Credentials/ProjectMerchantFileTest.php @@ -33,7 +33,7 @@ $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); + 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([ @@ -45,6 +45,13 @@ 'escaped duplicate selector' => '{"merchant":"shop-a","merch\\u0061nt":"shop-b"}', ]); +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 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); diff --git a/tests/Unit/Credentials/ApiKeyResolverTest.php b/tests/Unit/Credentials/ApiKeyResolverTest.php index 27e83ac..8ebc050 100644 --- a/tests/Unit/Credentials/ApiKeyResolverTest.php +++ b/tests/Unit/Credentials/ApiKeyResolverTest.php @@ -55,7 +55,7 @@ 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); + expect(fn () => $this->resolver->resolve())->toThrow(CredentialException::class, '.quickpay-cli.json'); expect(fn () => $this->resolver->resolve('shop-b'))->toThrow(CredentialException::class); }); diff --git a/tests/Unit/Credentials/MerchantConfigurationJsonTest.php b/tests/Unit/Credentials/MerchantConfigurationJsonTest.php index 5c8b18a..2d5096b 100644 --- a/tests/Unit/Credentials/MerchantConfigurationJsonTest.php +++ b/tests/Unit/Credentials/MerchantConfigurationJsonTest.php @@ -14,4 +14,17 @@ '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); + } +}); From b3b5d476855b43371a1684ad063b22046f47a878 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Mon, 23 Nov 2026 14:37:41 +0100 Subject: [PATCH 09/16] feat: add read and write access flags to saved merchants Each saved merchant stores read and write flags. QuickpayClient refuses any request they block before sending it: GET is a read and every other method is a write. Capture, refund, cancel and raw mutations check access before inspecting a payment or asking for confirmation. The credential check behind merchants:add and merchants:active --check is exempt. merchants:add takes --no-read and --no-write, and the new merchants:access command shows or changes the flags. Blocking works anywhere; allowing requests again needs an interactive terminal and a confirmation. merchants:list and merchants:active report the flags. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 + README.md | 19 +++++ SECURITY.md | 10 +++ app/Commands/Api/ApiRequestCommand.php | 1 + .../Merchants/ActiveMerchantCommand.php | 5 ++ app/Commands/Merchants/AddMerchantCommand.php | 18 ++++- .../Merchants/ListMerchantsCommand.php | 22 ++++- .../Merchants/SetMerchantAccessCommand.php | 79 ++++++++++++++++++ .../AbstractPaymentMutationCommand.php | 4 + app/Console/AuthenticatedCommand.php | 3 +- app/Credentials/ApiKey.php | 6 ++ app/Credentials/ApiKeyResolver.php | 6 +- .../Exceptions/MerchantAccessException.php | 20 +++++ app/Credentials/MerchantAccess.php | 42 ++++++++++ app/Credentials/MerchantStore.php | 50 ++++++++++-- app/Quickpay/AuthenticatedQuickpayFactory.php | 2 +- app/Quickpay/MerchantAuthenticationCheck.php | 2 +- app/Quickpay/QuickpayClient.php | 38 ++++++++- skills/quickpay-cli/SKILL.md | 13 ++- tests/Feature/ApplicationIdentityTest.php | 1 + .../Resolution/PaymentLocatorTest.php | 13 +-- .../Watching/CallbackWatchRunnerTest.php | 5 +- .../Callbacks/ReplayCallbackCommandTest.php | 3 +- .../Merchants/ActiveMerchantCommandTest.php | 26 +++++- .../Merchants/AddMerchantCommandTest.php | 23 ++++++ .../Merchants/ListMerchantsCommandTest.php | 20 ++++- .../Merchants/RemoveMerchantCommandTest.php | 2 +- .../SetMerchantAccessCommandTest.php | 69 ++++++++++++++++ .../Console/AuthenticatedCommandTest.php | 65 +++++++++++++++ .../MerchantAuthenticationCheckTest.php | 3 +- .../Quickpay/Payments/PaymentServicesTest.php | 7 +- tests/Feature/Quickpay/QuickpayClientTest.php | 65 +++++++++++++-- .../Credentials/MerchantStoreTest.php | 81 ++++++++++++++++--- tests/Unit/Credentials/MerchantAccessTest.php | 37 +++++++++ 34 files changed, 705 insertions(+), 59 deletions(-) create mode 100644 app/Commands/Merchants/SetMerchantAccessCommand.php create mode 100644 app/Credentials/Exceptions/MerchantAccessException.php create mode 100644 app/Credentials/MerchantAccess.php create mode 100644 tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php create mode 100644 tests/Unit/Credentials/MerchantAccessTest.php diff --git a/AGENTS.md b/AGENTS.md index 2ce2f04..fbdc141 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -81,6 +81,10 @@ validation, and the locked-dependency audit. 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 `read` and `write` flags that `QuickpayClient` enforces + before sending: `GET` is a read, every other method a write. Commands that + inspect or confirm before mutating check them first. Allowing requests needs + an interactive terminal; `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 diff --git a/README.md b/README.md index bfe9b3c..de30852 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,25 @@ 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`. +### Read-only merchants + +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 merchants:add "My Website" --no-write +quickpay merchants:access "My Website" --no-write +quickpay merchants:access "My Website" --write +``` + +`--no-read` blocks `GET` requests the same way. A blocked request stops before +anything reaches Quickpay. Allowing requests again asks you to confirm in an +interactive terminal, so a script or agent can't lift a block on its own. +Capture, refund and cancel need both reads and writes, because they show you the +payment before asking to continue. A key in `QUICKPAY_API_KEY` always has full +access. + ## Payments ```bash diff --git a/SECURITY.md b/SECURITY.md index 23e9fee..d71cacc 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -56,6 +56,16 @@ 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 `read` and `write` flags. `QuickpayClient` +refuses any request they block before sending it: `GET` is a read and every +other method is a write. Capture, refund, cancel and raw mutations check the +flags before inspecting a payment or asking for confirmation. The credential +check behind `merchants:add` and `merchants:active --check` is exempt, because it +reads no merchant data. Blocking works anywhere; allowing requests again needs +an interactive terminal and a confirmation. A key from `QUICKPAY_API_KEY` has +full access. The flags are a local guardrail, not Quickpay permissions: anyone +who can edit the configuration file can change them. + ## Local callback forwarding `callbacks:replay` and `callbacks:watch` send a signed payment resource to the diff --git a/app/Commands/Api/ApiRequestCommand.php b/app/Commands/Api/ApiRequestCommand.php index fef1c48..aaa74f0 100644 --- a/app/Commands/Api/ApiRequestCommand.php +++ b/app/Commands/Api/ApiRequestCommand.php @@ -46,6 +46,7 @@ public function handle( $this->option('data-json'), (array) $this->option('header'), ); + $authenticated->client->authorize($request->method); if ($request->mutation) { $this->writeMerchantContext($authenticated); diff --git a/app/Commands/Merchants/ActiveMerchantCommand.php b/app/Commands/Merchants/ActiveMerchantCommand.php index 72c404d..3921cbf 100644 --- a/app/Commands/Merchants/ActiveMerchantCommand.php +++ b/app/Commands/Merchants/ActiveMerchantCommand.php @@ -37,6 +37,8 @@ public function handle(ApiKeyResolver $resolver, MerchantAuthenticationCheck $ch 'selection_source' => $key?->selectionSource(), 'credential_source' => $key?->source(), 'configured' => $key !== null, + 'read' => $key?->access()->read, + 'write' => $key?->access()->write, 'checked' => $checkRequested, 'authenticated' => $authenticated, 'api_base_url' => QuickpayClient::BASE_URL, @@ -50,6 +52,9 @@ public function handle(ApiKeyResolver $resolver, MerchantAuthenticationCheck $ch $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()->isFull()) { + $this->line('Access: '.$key->access()->label()); + } $this->line('Credentials configured: '.($status['configured'] ? 'yes' : 'no')); $this->line('API access: '.match ($authenticated) { true => 'verified', diff --git a/app/Commands/Merchants/AddMerchantCommand.php b/app/Commands/Merchants/AddMerchantCommand.php index 3a994cc..ceac376 100644 --- a/app/Commands/Merchants/AddMerchantCommand.php +++ b/app/Commands/Merchants/AddMerchantCommand.php @@ -7,10 +7,12 @@ use App\Console\Terminal\StdinTerminalDetector; use App\Credentials\ApiKey; use App\Credentials\Exceptions\CredentialException; +use App\Credentials\MerchantAccess; use App\Credentials\MerchantName; use App\Credentials\MerchantStore; use App\Quickpay\Exceptions\QuickpayRequestException; use App\Quickpay\MerchantAuthenticationCheck; +use Symfony\Component\Console\Input\InputOption; use UnexpectedValueException; class AddMerchantCommand extends BaseCommand @@ -21,6 +23,13 @@ class AddMerchantCommand extends BaseCommand protected $description = 'Validate and save API access to an existing Quickpay merchant'; + public function __construct() + { + parent::__construct(); + $this->addOption('read', null, InputOption::VALUE_NEGATABLE, 'Allow read requests (GET). Allowed by default; --replace keeps the saved setting'); + $this->addOption('write', null, InputOption::VALUE_NEGATABLE, 'Allow write requests (POST, PUT, PATCH, DELETE). Allowed by default; --replace keeps the saved setting'); + } + public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, StdinTerminalDetector $terminal): int { $credential = null; @@ -49,14 +58,19 @@ public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, return $this->failure('API key cannot be empty.'); } - $credential = new ApiKey($apiKey, 'provided'); + $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); - $store->add($name, $apiKey, (bool) $this->option('replace')); + $read = $this->option('read'); + $write = $this->option('write'); + $access = $store->add($name, $apiKey, (bool) $this->option('replace'), is_bool($read) ? $read : null, is_bool($write) ? $write : null); $this->info('Merchant saved: '.$name); + if (! $access->isFull()) { + $this->line('Access: '.$access->label()); + } $legacy = $store->leftoverLegacyCredential(); if ($legacy !== null) { diff --git a/app/Commands/Merchants/ListMerchantsCommand.php b/app/Commands/Merchants/ListMerchantsCommand.php index 7425f3c..64e7e47 100644 --- a/app/Commands/Merchants/ListMerchantsCommand.php +++ b/app/Commands/Merchants/ListMerchantsCommand.php @@ -5,6 +5,7 @@ use App\Console\BaseCommand; use App\Console\Output\JsonOutput; use App\Credentials\Exceptions\CredentialException; +use App\Credentials\MerchantAccess; use App\Credentials\MerchantStore; class ListMerchantsCommand extends BaseCommand @@ -26,6 +27,8 @@ public function handle(MerchantStore $store): int $rows = array_map(fn (string $name): array => [ 'name' => $name, 'default' => $config['default_merchant'] === $name, + 'read' => $config['merchants'][$name]['read'], + 'write' => $config['merchants'][$name]['write'], ], $names); if ($this->option('json')) { @@ -33,10 +36,21 @@ public function handle(MerchantStore $store): int } elseif ($rows === []) { $this->line('No saved merchants. Run quickpay merchants:add first.'); } else { - $this->table(['Merchant', 'Global default'], array_map(fn (array $row): array => [ - $row['name'], - $row['default'] ? 'yes' : '', - ], $rows)); + // Access is shown only for merchants that block requests. + $restricted = array_map(function (array $row): ?string { + $access = new MerchantAccess($row['read'], $row['write']); + + return $access->isFull() ? null : $access->label(); + }, $rows); + $showAccess = array_filter($restricted) !== []; + $this->table( + ['Merchant', 'Global default', ...($showAccess ? ['Access'] : [])], + array_map(fn (array $row, ?string $access): array => [ + $row['name'], + $row['default'] ? 'yes' : '', + ...($showAccess ? [$access ?? ''] : []), + ], $rows, $restricted), + ); } return self::SUCCESS; diff --git a/app/Commands/Merchants/SetMerchantAccessCommand.php b/app/Commands/Merchants/SetMerchantAccessCommand.php new file mode 100644 index 0000000..cef5d23 --- /dev/null +++ b/app/Commands/Merchants/SetMerchantAccessCommand.php @@ -0,0 +1,79 @@ +addOption('read', null, InputOption::VALUE_NEGATABLE, 'Allow read requests (GET); --no-read blocks them. Allowing needs an interactive terminal'); + $this->addOption('write', null, InputOption::VALUE_NEGATABLE, 'Allow write requests (POST, PUT, PATCH, DELETE); --no-write blocks them. Allowing needs an interactive terminal'); + } + + public function handle(MerchantStore $store, StdinTerminalDetector $terminal): int + { + try { + $name = MerchantName::validate((string) $this->argument('name')); + $config = $store->read(); + if (! isset($config['merchants'][$name])) { + return $this->failure('Merchant is not saved. Run quickpay merchants:list to see saved names.'); + } + + $read = $this->flag('read'); + $write = $this->flag('write'); + if ($read === null && $write === null) { + $saved = $config['merchants'][$name]; + $this->line($this->summary($name, new MerchantAccess($saved['read'], $saved['write']))); + + return self::SUCCESS; + } + + // Blocking requests is always safe. Allowing them needs a person at + // the keyboard, so an automated caller cannot lift a block itself. + $allowing = array_keys(array_filter(['read' => $read, 'write' => $write], fn (?bool $flag): bool => $flag === true)); + if ($allowing !== []) { + if (! $this->input->isInteractive() || ! $terminal->isTty()) { + return $this->failure('Allowing requests for a merchant requires an interactive terminal.'); + } + + if (! $this->confirm('Allow '.implode(' and ', $allowing).' requests for '.$name.'?', false)) { + $this->line('Cancelled.'); + + return self::SUCCESS; + } + } + + $this->info($this->summary($name, $store->changeAccess($name, $read, $write))); + + return self::SUCCESS; + } catch (CredentialException $exception) { + return $this->failure($exception->getMessage()); + } + } + + private function flag(string $name): ?bool + { + $value = $this->option($name); + + return is_bool($value) ? $value : null; + } + + 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 a9df855..47cc61e 100644 --- a/app/Commands/Payments/AbstractPaymentMutationCommand.php +++ b/app/Commands/Payments/AbstractPaymentMutationCommand.php @@ -27,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(); diff --git a/app/Console/AuthenticatedCommand.php b/app/Console/AuthenticatedCommand.php index 69d4a5a..d4182f6 100644 --- a/app/Console/AuthenticatedCommand.php +++ b/app/Console/AuthenticatedCommand.php @@ -4,6 +4,7 @@ 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; @@ -41,7 +42,7 @@ protected function withQuickpay(AuthenticatedQuickpayFactory $quickpay, Closure try { return $callback($authenticated); - } catch (InvalidArgumentException|QuickpayRequestException|UnexpectedValueException $exception) { + } catch (InvalidArgumentException|MerchantAccessException|QuickpayRequestException|UnexpectedValueException $exception) { return $this->failure($authenticated->safeLine($exception->getMessage())); } } diff --git a/app/Credentials/ApiKey.php b/app/Credentials/ApiKey.php index ecfe203..db13ead 100644 --- a/app/Credentials/ApiKey.php +++ b/app/Credentials/ApiKey.php @@ -10,6 +10,7 @@ public function __construct( private string $value, private string $source, + private MerchantAccess $access, private ?string $merchant = null, private ?string $selectionSource = null, ) { @@ -28,6 +29,11 @@ public function source(): string return $this->source; } + public function access(): MerchantAccess + { + return $this->access; + } + public function merchant(): ?string { return $this->merchant; diff --git a/app/Credentials/ApiKeyResolver.php b/app/Credentials/ApiKeyResolver.php index b4b7b07..2b52e63 100644 --- a/app/Credentials/ApiKeyResolver.php +++ b/app/Credentials/ApiKeyResolver.php @@ -29,7 +29,7 @@ public function resolve(?string $merchant = null): ?ApiKey } if ($environmentKey !== null) { - return new ApiKey($environmentKey, 'environment', null, 'environment'); + return new ApiKey($environmentKey, 'environment', MerchantAccess::full(), null, 'environment'); } $config = $this->store->read(); @@ -51,6 +51,8 @@ public function resolve(?string $merchant = null): ?ApiKey }); } - return new ApiKey($config['merchants'][$name]['api_key'], 'config file', $name, $source); + $saved = $config['merchants'][$name]; + + return new ApiKey($saved['api_key'], 'config file', new MerchantAccess($saved['read'], $saved['write']), $name, $source); } } diff --git a/app/Credentials/Exceptions/MerchantAccessException.php b/app/Credentials/Exceptions/MerchantAccessException.php new file mode 100644 index 0000000..775ca15 --- /dev/null +++ b/app/Credentials/Exceptions/MerchantAccessException.php @@ -0,0 +1,20 @@ +read : $this->write; + } + + public function isFull(): bool + { + return $this->read && $this->write; + } + + public function label(): string + { + return match (true) { + $this->read && $this->write => 'read and write', + $this->read => 'read-only', + $this->write => 'write-only', + default => 'no API access', + }; + } +} diff --git a/app/Credentials/MerchantStore.php b/app/Credentials/MerchantStore.php index ff711a5..69bf18b 100644 --- a/app/Credentials/MerchantStore.php +++ b/app/Credentials/MerchantStore.php @@ -8,7 +8,10 @@ use JsonException; use stdClass; -/** @phpstan-type MerchantConfig array{default_merchant: ?string, merchants: array} */ +/** + * @phpstan-type SavedMerchant array{api_key: string, read: bool, write: bool} + * @phpstan-type MerchantConfig array{default_merchant: ?string, merchants: array} + */ final readonly class MerchantStore { public function __construct( @@ -74,12 +77,16 @@ public function read(): array foreach (get_object_vars($config->merchants) as $name => $merchant) { MerchantName::validate((string) $name); if (! $merchant instanceof stdClass - || count(get_object_vars($merchant)) !== 1 || ! is_string($merchant->api_key ?? null) || trim($merchant->api_key) === '') { throw new CredentialException('Quickpay CLI merchant configuration contains an invalid credential.'); } - $merchants[$name] = ['api_key' => $merchant->api_key]; + if (count(get_object_vars($merchant)) !== 3 + || ! is_bool($merchant->read ?? null) + || ! is_bool($merchant->write ?? null)) { + throw new CredentialException('Quickpay CLI merchant configuration needs exactly an API key and true or false read and write access flags for each merchant.'); + } + $merchants[$name] = ['api_key' => $merchant->api_key, 'read' => $merchant->read, 'write' => $merchant->write]; } $this->validateLabels($merchants); @@ -90,14 +97,20 @@ public function read(): array return ['default_merchant' => $config->default_merchant, 'merchants' => $merchants]; } - public function add(string $name, string $apiKey, bool $replace = false): void + /** + * Saves a credential and returns the access it was saved with. A null flag + * keeps the replaced merchant's flag, or allows that kind of request for a + * new merchant. + */ + public function add(string $name, string $apiKey, bool $replace = false, ?bool $read = null, ?bool $write = null): MerchantAccess { MerchantName::validate($name); $apiKey = trim($apiKey); if ($apiKey === '') { throw new CredentialException('API key cannot be empty.'); } - $this->mutate(function (array $config) use ($name, $apiKey, $replace): array { + $access = null; + $this->mutate(function (array $config) use ($name, $apiKey, $replace, $read, $write, &$access): array { if (isset($config['merchants'][$name]) && ! $replace) { throw new CredentialException('Merchant is already saved. Use --replace to replace its credential.'); } @@ -107,11 +120,16 @@ public function add(string $name, string $apiKey, bool $replace = false): void if ($config['merchants'] === []) { $config['default_merchant'] = $name; } - $config['merchants'][$name] = ['api_key' => $apiKey]; + $existing = $config['merchants'][$name] ?? null; + $access = new MerchantAccess($read ?? $existing['read'] ?? true, $write ?? $existing['write'] ?? true); + $config['merchants'][$name] = ['api_key' => $apiKey, 'read' => $access->read, 'write' => $access->write]; $this->validateLabels($config['merchants']); return $config; }); + + /** @var MerchantAccess $access */ + return $access; } public function select(string $name): void @@ -124,6 +142,24 @@ public function select(string $name): void }); } + /** Changes the given flags under the store lock; a null flag is kept. */ + public function changeAccess(string $name, ?bool $read = null, ?bool $write = null): MerchantAccess + { + MerchantName::validate($name); + $access = null; + $this->mutate(function (array $config) use ($name, $read, $write, &$access): array { + $this->requireMerchant($config, $name); + $saved = $config['merchants'][$name]; + $access = new MerchantAccess($read ?? $saved['read'], $write ?? $saved['write']); + $config['merchants'][$name] = [...$saved, 'read' => $access->read, 'write' => $access->write]; + + return $config; + }); + + /** @var MerchantAccess $access */ + return $access; + } + public function remove(string $name): void { $this->mutate(function (array $config) use ($name): array { @@ -137,7 +173,7 @@ public function remove(string $name): void }); } - /** @param array $merchants */ + /** @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. diff --git a/app/Quickpay/AuthenticatedQuickpayFactory.php b/app/Quickpay/AuthenticatedQuickpayFactory.php index b554f90..b845365 100644 --- a/app/Quickpay/AuthenticatedQuickpayFactory.php +++ b/app/Quickpay/AuthenticatedQuickpayFactory.php @@ -23,7 +23,7 @@ public function resolve(?string $merchant = null): ?AuthenticatedQuickpay 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 index 22bb68f..bf6436d 100644 --- a/app/Quickpay/MerchantAuthenticationCheck.php +++ b/app/Quickpay/MerchantAuthenticationCheck.php @@ -13,7 +13,7 @@ public function __construct(private AuthenticatedQuickpayFactory $quickpay) {} public function check(ApiKey $apiKey): void { - $response = $this->quickpay->from($apiKey)->client->get('/ping'); + $response = $this->quickpay->from($apiKey)->client->ping(); if (! $response->successful()) { throw new QuickpayRequestException('Authentication check failed: '.ResponseBodySanitizer::terminalLine($response->errorSummary(), $apiKey->value())); } diff --git a/app/Quickpay/QuickpayClient.php b/app/Quickpay/QuickpayClient.php index b4bac0b..9641092 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 read and write + * access remain centralized so raw API access cannot weaken the same guarantees + * used by first-class commands. */ final readonly class QuickpayClient { @@ -24,8 +27,35 @@ public function __construct( private Factory $http, private string $apiKey, + private MerchantAccess $access, ) {} + /** + * Fails before any request the merchant's access flags do not allow. + * + * 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); + } + } + + /** + * Verifies the credential itself. + * + * It is exempt from the access flags because it reads no merchant data, so + * a merchant that blocks reads can still be checked. + */ + public function ping(): QuickpayResponse + { + return $this->send('GET', '/ping'); + } + /** * @param array $query * @param array $data @@ -63,6 +93,8 @@ public function put(string $path, array $query = [], array $data = [], array $he */ 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.'); } @@ -84,6 +116,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/skills/quickpay-cli/SKILL.md b/skills/quickpay-cli/SKILL.md index 53baabf..61bb1ca 100644 --- a/skills/quickpay-cli/SKILL.md +++ b/skills/quickpay-cli/SKILL.md @@ -50,6 +50,15 @@ 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. +Each saved merchant can block reads (`GET`) or writes (`POST`, `PUT`, `PATCH`, +`DELETE`). `merchants:active --json` reports `read` and `write`. A blocked +request fails with "does not allow read requests" or "does not allow write +requests" before anything is sent. That block is the user's decision: stop and +report it. Never lift or bypass it by running `merchants:access` with `--read` +or `--write`, re-adding the merchant, editing configuration files, or switching +to another merchant or to `QUICKPAY_API_KEY`. Add a block with `--no-read` or +`--no-write` 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. @@ -73,7 +82,8 @@ For a refund or cancellation, use the same inspect → verify → explicit autho ```text quickpay about -quickpay merchants:add [--replace] +quickpay merchants:add [--replace] [--no-read] [--no-write] +quickpay merchants:access [--read|--no-read] [--write|--no-write] quickpay merchants:list [--json] quickpay merchants:select [] [--local] quickpay merchants:active [--merchant=name] [--check] [--json] @@ -161,4 +171,5 @@ Do not use full URLs, hosts, schemes, `..`, backslashes, or fragments. The CLI o - A raw `GET` needs no `--yes`; a raw `POST`, `PUT`, `PATCH`, or `DELETE` does. - `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 `write` in `merchants:active --merchant= --json` before planning a mutation. Capture, refund and cancel need both `read` and `write`. - Use the same `--merchant` for readiness checks, payment inspection and any explicitly authorized mutation. diff --git a/tests/Feature/ApplicationIdentityTest.php b/tests/Feature/ApplicationIdentityTest.php index 1118faf..8f0fef2 100644 --- a/tests/Feature/ApplicationIdentityTest.php +++ b/tests/Feature/ApplicationIdentityTest.php @@ -21,6 +21,7 @@ 'api', 'callbacks:replay', 'callbacks:watch', + 'merchants:access', 'merchants:active', 'merchants:add', 'merchants:list', 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/Commands/Callbacks/ReplayCallbackCommandTest.php b/tests/Feature/Commands/Callbacks/ReplayCallbackCommandTest.php index f6640e7..ae505a4 100644 --- a/tests/Feature/Commands/Callbacks/ReplayCallbackCommandTest.php +++ b/tests/Feature/Commands/Callbacks/ReplayCallbackCommandTest.php @@ -4,6 +4,7 @@ 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; @@ -33,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/Merchants/ActiveMerchantCommandTest.php b/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php index 77ae048..13220ed 100644 --- a/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php @@ -18,10 +18,10 @@ [$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, 'checked' => false, 'authenticated' => null, + 'configured' => true, 'read' => true, 'write' => true, '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')->assertExitCode(0); + $this->artisan('merchants:active')->expectsOutputToContain('shop-a')->expectsOutputToContain('not checked')->doesntExpectOutputToContain('Access:')->assertExitCode(0); Http::assertNothingSent(); }); @@ -49,7 +49,8 @@ [$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['credential_source'])->toBe('environment')->and($data['authenticated'])->toBeNull() + ->and($data['read'])->toBeTrue()->and($data['write'])->toBeTrue(); Http::assertNothingSent(); }); @@ -81,7 +82,7 @@ $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"},"sh\\u006fp-a":{"api_key":"fake-last"}}}'; + : '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","read":true,"write":true},"sh\\u006fp-a":{"api_key":"fake-last","read":true,"write":true}}}'; file_put_contents($path, $contents); Http::fake(['*' => Http::response(['scope' => 'merchant'])]); [$exit, $output, $errors] = merchantCommandResult(ActiveMerchantCommand::class, ['--check' => true, '--json' => true]); @@ -89,3 +90,20 @@ ->and(file_get_contents($path))->toBe($contents); Http::assertNothingSent(); })->with(['store' => false, 'project' => true]); + +it('reports restricted access and still verifies a merchant that blocks reads', function (): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); + $this->store->add('shop-a', 'fake-secret-a', read: false); + [$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'])->toBeFalse()->and($data['write'])->toBeTrue() + ->and($data['authenticated'])->toBeTrue(); + $this->artisan('merchants:active')->expectsOutputToContain('Access: write-only')->assertExitCode(0); + Http::assertSentCount(1); +}); + +it('reports no access flags 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['read'])->toBeNull()->and($data['write'])->toBeNull(); +}); diff --git a/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php index 3742566..b6bd54c 100644 --- a/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php @@ -103,3 +103,26 @@ public function isTty(): bool ->expectsOutputToContain('Unable to connect to Quickpay')->doesntExpectOutputToContain('fake-secret-a')->assertExitCode(1); expect(file_exists($this->store->path()))->toBeFalse(); }); + +it('saves access flags given when adding a merchant', 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' => true, 'write' => true], null], + 'read-only' => [['--no-write' => true], ['read' => true, 'write' => false], 'read-only'], + 'write-only' => [['--no-read' => true], ['read' => false, 'write' => true], 'write-only'], + 'none' => [['--no-read' => true, '--no-write' => true], ['read' => false, 'write' => false], 'no API access'], +]); + +it('keeps access flags when replacing a credential', function (): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); + $this->store->add('shop-a', 'fake-original', write: false); + $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' => true, 'write' => false]); +}); diff --git a/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php b/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php index 3b22462..a658eae 100644 --- a/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php +++ b/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php @@ -8,7 +8,7 @@ $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], ['name' => 'My Website', 'default' => true]]); + ->toBe([['name' => 'My Other Website', 'default' => false, 'read' => true, 'write' => true], ['name' => 'My Website', 'default' => true, 'read' => true, 'write' => true]]); Http::assertNothingSent(); }); @@ -19,9 +19,25 @@ }); 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"},"fake-secret-a":{"api_key":"fake-secret-b"}}}'); + file_put_contents($this->store->path(), '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-secret-a","read":true,"write":true},"fake-secret-a":{"api_key":"fake-secret-b","read":true,"write":true}}}'); [$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 for merchants that block requests', function (): void { + $this->store->add('shop-a', 'fake-secret-a'); + $this->store->add('shop-b', 'fake-secret-b', write: false); + $this->store->add('shop-c', 'fake-secret-c', read: false); + [$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' => true, 'write' => true], + ['name' => 'shop-b', 'default' => false, 'read' => true, 'write' => false], + ['name' => 'shop-c', 'default' => false, 'read' => false, 'write' => true], + ]); + [$exit, $output] = merchantCommandResult(ListMerchantsCommand::class); + expect($exit)->toBe(0)->and($output)->toContain('Access')->toContain('read-only')->toContain('write-only') + ->not->toContain('read and write'); + Http::assertNothingSent(); +}); diff --git a/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php b/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php index a995d24..98e1588 100644 --- a/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php @@ -7,7 +7,7 @@ $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']]]); + expect($this->store->read())->toBe(['default_merchant' => null, 'merchants' => ['My Website' => ['api_key' => 'fake-secret-b', 'read' => true, 'write' => true]]]); $this->artisan('merchants:remove', ['name' => 'shop-missing'])->assertExitCode(1); $this->artisan('merchants:remove', ['name' => 'My Website'])->assertExitCode(0); expect($this->store->read()['merchants'])->toBe([]); diff --git a/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php b/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php new file mode 100644 index 0000000..adac565 --- /dev/null +++ b/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php @@ -0,0 +1,69 @@ +store->add('shop-a', 'fake-secret-a'); + $this->artisan('merchants:access', ['name' => 'shop-a', ...$flags, '--no-interaction' => true]) + ->expectsOutputToContain('Access for shop-a: '.$label)->assertExitCode(0); + expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-secret-a', ...$saved]); + Http::assertNothingSent(); +})->with([ + 'block writes' => [['--no-write' => true], ['read' => true, 'write' => false], 'read-only'], + 'block reads' => [['--no-read' => true], ['read' => false, 'write' => true], 'write-only'], + 'block both' => [['--no-read' => true, '--no-write' => true], ['read' => false, 'write' => false], 'no API access'], +]); + +it('allows blocked requests again only after an interactive confirmation', function (array $flags, string $question, array $saved): void { + $this->store->add('shop-a', 'fake-secret-a', read: false, write: false); + $this->artisan('merchants:access', ['name' => 'shop-a', ...$flags]) + ->expectsConfirmation($question, 'yes')->assertExitCode(0); + expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-secret-a', ...$saved]); +})->with([ + 'writes' => [['--write' => true], 'Allow write requests for shop-a?', ['read' => false, 'write' => true]], + 'both' => [['--read' => true, '--write' => true], 'Allow read and write requests for shop-a?', ['read' => true, 'write' => true]], + 'reads while blocking writes' => [['--read' => true, '--no-write' => true], 'Allow read requests for shop-a?', ['read' => true, 'write' => false]], +]); + +it('leaves access unchanged when the confirmation is declined', function (): void { + $this->store->add('shop-a', 'fake-secret-a', write: false); + $before = file_get_contents($this->store->path()); + $this->artisan('merchants:access', ['name' => 'shop-a', '--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', write: false); + $before = file_get_contents($this->store->path()); + $this->artisan('merchants:access', ['name' => 'shop-a', '--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', write: false); + $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, '--no-write' => 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/Console/AuthenticatedCommandTest.php b/tests/Feature/Console/AuthenticatedCommandTest.php index 559b958..c8f3870 100644 --- a/tests/Feature/Console/AuthenticatedCommandTest.php +++ b/tests/Feature/Console/AuthenticatedCommandTest.php @@ -206,3 +206,68 @@ public function run(?string $paymentId, ?string $orderId, CallbackTarget $target 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', write: false); + 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("does not allow write requests, 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', write: false); + 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('blocks reads for a write-only merchant without retrying', function (string $command, array $arguments): void { + $this->store->add('shop-w', 'fake-secret-w', read: false); + Http::fake(); + $this->artisan($command, [...$arguments, '--merchant' => 'shop-w']) + ->expectsOutputToContain('does not allow read requests')->assertExitCode(1); + Http::assertNothingSent(); +})->with([ + 'get' => ['payments:get', ['id' => '42']], + 'list' => ['payments:list', []], + 'raw GET' => ['api', ['method' => 'GET', 'path' => '/payments/42']], + 'capture inspects the payment first' => ['payments:capture', ['id' => '42', 'amount' => '1250', '--yes' => true]], + 'replay' => ['callbacks:replay', ['payment-id' => '42', '--to' => 'http://localhost/callback']], + 'scoped watch' => ['callbacks:watch', ['payment-id' => '42', '--to' => 'http://localhost/callback']], + 'account-wide watch' => ['callbacks:watch', ['--to' => 'http://localhost/callback']], +]); + +it('still writes through a write-only merchant', function (): void { + $this->store->add('shop-w', 'fake-secret-w', read: false); + Http::fake(['https://api.quickpay.net/payments' => Http::response('{"id":42}')]); + $this->artisan('payments:create', ['order-id' => 'order-42', '--merchant' => 'shop-w', '--json' => true])->assertExitCode(0); + Http::assertSentCount(1); + Http::assertSent(fn (Request $request): bool => $request->method() === 'POST' + && $request->header('Authorization') === ['Basic '.base64_encode(':fake-secret-w')]); +}); diff --git a/tests/Feature/Quickpay/MerchantAuthenticationCheckTest.php b/tests/Feature/Quickpay/MerchantAuthenticationCheckTest.php index c07baa4..4b5787e 100644 --- a/tests/Feature/Quickpay/MerchantAuthenticationCheckTest.php +++ b/tests/Feature/Quickpay/MerchantAuthenticationCheckTest.php @@ -1,13 +1,14 @@ Http::response(['scope' => 'user'])]); - expect(fn () => (new MerchantAuthenticationCheck(app(AuthenticatedQuickpayFactory::class)))->check(new ApiKey('fake-key', 'provided'))) + 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 b7cae0f..22cdb55 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(); @@ -29,7 +31,7 @@ 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'); + $client = new QuickpayClient(app(Factory::class), 'secret', MerchantAccess::full()); $response = $client->raw($method, '/resources', ['page' => 2], ['name' => 'Example']); expect($response->successful())->toBeTrue(); @@ -46,7 +48,7 @@ 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() @@ -61,7 +63,7 @@ throw new ConnectionException('Mutation failed'); }); - $client = new QuickpayClient(app(Factory::class), 'secret'); + $client = new QuickpayClient(app(Factory::class), 'secret', MerchantAccess::full()); expect(fn () => $client->raw($method, '/resources', data: ['name' => 'Example'])) ->toThrow(QuickpayRequestException::class); @@ -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,52 @@ ->and($exception->getPrevious())->toBeNull(); } }); + +it('sends nothing when merchant access blocks the method', function (bool $read, bool $write, string $method, string $kind): void { + Http::fake(); + $client = new QuickpayClient(app(Factory::class), 'test-secret', new MerchantAccess($read, $write)); + + expect(fn () => $client->raw($method, '/payments/42', data: ['amount' => 1000])) + ->toThrow(MerchantAccessException::class, "does not allow {$kind} requests, so the ".strtoupper($method).' request was not sent.'); + Http::assertNothingSent(); +})->with([ + 'read-only POST' => [true, false, 'POST', 'write'], + 'read-only PUT' => [true, false, 'PUT', 'write'], + 'read-only PATCH' => [true, false, 'PATCH', 'write'], + 'read-only DELETE' => [true, false, 'delete', 'write'], + 'write-only GET' => [false, true, 'GET', 'read'], + 'no access GET' => [false, false, 'GET', 'read'], + 'no access POST' => [false, false, 'POST', 'write'], +]); + +it('applies merchant access 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(true, false)); + $writeOnly = new QuickpayClient(app(Factory::class), 'test-secret', new MerchantAccess(false, true)); + + expect($readOnly->get('/payments/42')->successful())->toBeTrue() + ->and(fn () => $readOnly->post('/payments'))->toThrow(MerchantAccessException::class) + ->and(fn () => $readOnly->put('/payments/42/link'))->toThrow(MerchantAccessException::class) + ->and($writeOnly->post('/payments')->successful())->toBeTrue() + ->and(fn () => $writeOnly->get('/payments/42'))->toThrow(MerchantAccessException::class); + expect(Http::recorded())->toHaveCount(2) + ->and(Http::recorded()[0][0]->method())->toBe('GET') + ->and(Http::recorded()[1][0]->method())->toBe('POST'); +}); + +it('checks credentials with ping even when merchant access blocks every request', function (): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); + $client = new QuickpayClient(app(Factory::class), 'test-secret', new MerchantAccess(false, false)); + + expect($client->ping()->successful())->toBeTrue() + ->and(fn () => $client->get('/ping'))->toThrow(MerchantAccessException::class) + ->and(fn () => $client->raw('GET', '/ping'))->toThrow(MerchantAccessException::class); + Http::assertSentCount(1); + Http::assertSent(fn (Request $request): bool => $request->method() === 'GET' + && $request->url() === 'https://api.quickpay.net/ping' + && $request->header('Authorization') === ['Basic '.base64_encode(':test-secret')]); +}); + +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/MerchantStoreTest.php b/tests/Integration/Credentials/MerchantStoreTest.php index c998ee8..2b0529c 100644 --- a/tests/Integration/Credentials/MerchantStoreTest.php +++ b/tests/Integration/Credentials/MerchantStoreTest.php @@ -25,7 +25,7 @@ $store->add('shop-b', 'fake-secret-b'); expect($store->read())->toBe([ 'default_merchant' => 'shop-a', - 'merchants' => ['shop-a' => ['api_key' => 'fake-secret-a'], 'shop-b' => ['api_key' => 'fake-secret-b']], + 'merchants' => ['shop-a' => ['api_key' => 'fake-secret-a', 'read' => true, 'write' => true], 'shop-b' => ['api_key' => 'fake-secret-b', 'read' => true, 'write' => true]], ]); }); @@ -62,7 +62,7 @@ $store->add('shop-b', ' fake-replacement ', true); expect($store->read())->toBe([ 'default_merchant' => 'shop-a', - 'merchants' => ['shop-a' => ['api_key' => 'fake-secret-a'], 'shop-b' => ['api_key' => 'fake-replacement']], + 'merchants' => ['shop-a' => ['api_key' => 'fake-secret-a', 'read' => true, 'write' => true], 'shop-b' => ['api_key' => 'fake-replacement', 'read' => true, 'write' => true]], ]); }); @@ -100,18 +100,77 @@ })->with([ 'broken' => '{broken', 'root list' => '[]', 'missing' => '{}', 'merchant list' => '{"default_merchant":null,"merchants":[]}', - 'numeric key' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":123}}}', - 'empty key' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":" "}}}', - 'invalid name' => '{"default_merchant":null,"merchants":{"../a":{"api_key":"fake-key"}}}', + 'numeric key' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":123,"read":true,"write":true}}}', + 'empty key' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":" ","read":true,"write":true}}}', + 'invalid name' => '{"default_merchant":null,"merchants":{"../a":{"api_key":"fake-key","read":true,"write":true}}}', 'dangling default' => '{"default_merchant":"shop-a","merchants":{}}', 'old shape' => '{"api_key":"fake-legacy"}', - 'secret label' => '{"default_merchant":null,"merchants":{"secret-name":{"api_key":"secret"}}}', - 'duplicate merchant' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first"},"shop-a":{"api_key":"fake-last"}}}', - 'escaped duplicate merchant' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first"},"sh\\u006fp-a":{"api_key":"fake-last"}}}', - 'duplicate key' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","api_key":"fake-last"}}}', - 'duplicate default' => '{"default_merchant":"shop-a","default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-first"}}}', + 'secret label' => '{"default_merchant":null,"merchants":{"secret-name":{"api_key":"secret","read":true,"write":true}}}', + 'duplicate merchant' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","read":true,"write":true},"shop-a":{"api_key":"fake-last","read":true,"write":true}}}', + 'escaped duplicate merchant' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","read":true,"write":true},"sh\\u006fp-a":{"api_key":"fake-last","read":true,"write":true}}}', + 'duplicate key' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","api_key":"fake-last","read":true,"write":true}}}', + 'duplicate default' => '{"default_merchant":"shop-a","default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-first","read":true,"write":true}}}', + 'missing access flags' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key"}}}', + 'missing write flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","read":true}}}', + 'string access flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","read":"true","write":true}}}', + 'null access flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","read":true,"write":null}}}', + 'extra merchant field' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","read":true,"write":true,"note":"x"}}}', + 'duplicate access flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","write":false,"read":true,"write":true}}}', ]); +it('explains missing access flags 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, 'read and write access flags'); +}); + +it('saves access flags 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', write: false); + $store->add('shop-c', 'fake-secret-c', read: false); + expect($store->read()['merchants'])->toBe([ + 'shop-a' => ['api_key' => 'fake-secret-a', 'read' => true, 'write' => true], + 'shop-b' => ['api_key' => 'fake-secret-b', 'read' => true, 'write' => false], + 'shop-c' => ['api_key' => 'fake-secret-c', 'read' => false, 'write' => true], + ]); +}); + +it('keeps access flags when replacing a credential unless new flags are given', function (): void { + $store = new MerchantStore($this->path); + $store->add('shop-a', 'fake-original', write: false); + $store->add('shop-a', 'fake-replacement', true); + expect($store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'read' => true, 'write' => false]); + $store->add('shop-a', 'fake-second', true, read: false); + expect($store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-second', 'read' => false, 'write' => false]); +}); + +it('changes only the given access flags 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'); + $access = $store->changeAccess('shop-a', write: false); + expect([$access->read, $access->write])->toBe([true, false]); + $access = $store->changeAccess('shop-a', read: false); + expect([$access->read, $access->write])->toBe([false, false]) + ->and($store->read())->toBe([ + 'default_merchant' => 'shop-a', + 'merchants' => [ + 'shop-a' => ['api_key' => 'fake-secret-a', 'read' => false, 'write' => false], + 'shop-b' => ['api_key' => 'fake-secret-b', 'read' => true, 'write' => true], + ], + ]); +}); + +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, write: false))->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); @@ -220,7 +279,7 @@ $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"}}}'); + file_put_contents($this->path.'.replacement', '{"default_merchant":"shop-c","merchants":{"shop-c":{"api_key":"fake-secret-c","read":true,"write":true}}}'); rename($this->path.'.replacement', $this->path); flock($lock, LOCK_UN); expect(fgets($pipes[1]))->toBe("done\n") diff --git a/tests/Unit/Credentials/MerchantAccessTest.php b/tests/Unit/Credentials/MerchantAccessTest.php new file mode 100644 index 0000000..38e57b4 --- /dev/null +++ b/tests/Unit/Credentials/MerchantAccessTest.php @@ -0,0 +1,37 @@ +allows($method))->toBe($allowed); +})->with([ + 'read-only GET' => [true, false, 'GET', true], + 'read-only lowercase get' => [true, false, 'get', true], + 'read-only POST' => [true, false, 'POST', false], + 'read-only PUT' => [true, false, 'put', false], + 'read-only PATCH' => [true, false, 'PATCH', false], + 'read-only DELETE' => [true, false, 'DELETE', false], + 'read-only unknown method' => [true, false, 'OPTIONS', false], + 'write-only GET' => [false, true, 'GET', false], + 'write-only POST' => [false, true, 'POST', true], + 'write-only DELETE' => [false, true, 'DELETE', true], + 'no access GET' => [false, false, 'GET', false], + 'no access POST' => [false, false, 'POST', false], + 'full GET' => [true, true, 'GET', true], + 'full PUT' => [true, true, 'PUT', true], +]); + +it('names each access combination', function (bool $read, bool $write, string $label, bool $full): void { + $access = new MerchantAccess($read, $write); + expect($access->label())->toBe($label)->and($access->isFull())->toBe($full); +})->with([ + 'full' => [true, true, 'read and write', true], + 'read-only' => [true, false, 'read-only', false], + 'write-only' => [false, true, 'write-only', false], + 'none' => [false, false, 'no API access', false], +]); + +it('grants full access by default only through the named constructor', function (): void { + $access = MerchantAccess::full(); + expect([$access->read, $access->write])->toBe([true, true]); +}); From 25142f97b8a50a7515041393b7ce37354ba581eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Mon, 23 Nov 2026 17:18:14 +0100 Subject: [PATCH 10/16] feat: warn when QUICKPAY_PRIVATE_KEY signs callbacks for a saved merchant callbacks:watch and callbacks:replay now print a warning when the QUICKPAY_PRIVATE_KEY override is set while a saved merchant is selected, since the override may belong to a different merchant than the one in use. The warning goes to stderr in --json mode and is skipped for the QUICKPAY_API_KEY environment key, where pairing the two is deliberate. Also records the branch in the CHANGELOG, with the removed login, logout and auth commands and the old config file marked as breaking. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 17 ++++++ README.md | 5 ++ SECURITY.md | 4 +- .../Resolution/PrivateKeyResolver.php | 18 ++++++ .../Callbacks/ReplayCallbackCommand.php | 28 +++++---- .../Callbacks/WatchCallbacksCommand.php | 8 ++- skills/quickpay-cli/SKILL.md | 4 +- .../Console/AuthenticatedCommandTest.php | 58 +++++++++++++++++++ 8 files changed, 128 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bf34ef6..95b9c1f 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 and write access flags for each saved merchant, set with `merchants:add --no-read` or `--no-write` and changed with `merchants:access`. Blocked requests fail before anything is sent. +- 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`. + +### 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/README.md b/README.md index de30852..689095b 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,11 @@ To send a payment's current resource once: quickpay callbacks:replay --to=http://127.0.0.1:8000/quickpay/callback ``` +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. + ## For agents Install the bundled [quickpay-cli skill](skills/quickpay-cli/SKILL.md): diff --git a/SECURITY.md b/SECURITY.md index d71cacc..2d5c216 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -81,7 +81,9 @@ 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. A manually supplied -`QUICKPAY_PRIVATE_KEY` must belong to the selected merchant. +`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/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 6f854bb..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'), @@ -56,6 +58,10 @@ function (AuthenticatedQuickpay $authenticated) use ($watch): int { $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/skills/quickpay-cli/SKILL.md b/skills/quickpay-cli/SKILL.md index 61bb1ca..7c1bbb4 100644 --- a/skills/quickpay-cli/SKILL.md +++ b/skills/quickpay-cli/SKILL.md @@ -150,7 +150,9 @@ 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. An explicit override must belong to the selected merchant. A watcher +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 diff --git a/tests/Feature/Console/AuthenticatedCommandTest.php b/tests/Feature/Console/AuthenticatedCommandTest.php index c8f3870..2eb9122 100644 --- a/tests/Feature/Console/AuthenticatedCommandTest.php +++ b/tests/Feature/Console/AuthenticatedCommandTest.php @@ -4,6 +4,7 @@ use App\Callbacks\Watching\CallbackWatcher; use App\Callbacks\Watching\CallbackWatcherFactory; use App\Commands\Api\ApiRequestCommand; +use App\Commands\Callbacks\ReplayCallbackCommand; use App\Commands\Callbacks\WatchCallbacksCommand; use App\Commands\Payments\CancelPaymentCommand; use App\Commands\Payments\CapturePaymentCommand; @@ -271,3 +272,60 @@ public function run(?string $paymentId, ?string $orderId, CallbackTarget $target Http::assertSent(fn (Request $request): bool => $request->method() === 'POST' && $request->header('Authorization') === ['Basic '.base64_encode(':fake-secret-w')]); }); + +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]); From 4d5a2520ac2370ee96af6ca5277de44dcfa91292 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Mon, 23 Nov 2026 17:22:34 +0100 Subject: [PATCH 11/16] chore: update Symfony to patched releases for security advisories composer audit flagged seven advisories in symfony/http-foundation, symfony/http-kernel and symfony/mime. This moves them to 7.4.23, 7.4.23 and 7.4.22, with their dependencies, within the existing constraints. Co-Authored-By: Claude Opus 5.5 --- composer.lock | 176 +++++++++++++++++++++++++------------------------- 1 file changed, 88 insertions(+), 88 deletions(-) diff --git a/composer.lock b/composer.lock index ad9245f..220c325 100644 --- a/composer.lock +++ b/composer.lock @@ -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", From 49d1e134e0ba35ee6198220569946a695902db15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Mon, 23 Nov 2026 18:18:20 +0100 Subject: [PATCH 12/16] fix: confirm every lifted access block and fail blocked watches early - merchants:add --replace now asks before a --read or --write flag lifts a saved block, and prints the access whenever it changes. - merchants:access only asks when a flag lifts a block, so scripts can block with --read --no-write. Allowing what is already allowed is dropped, so it cannot undo a block saved in the meantime. A declined allow still applies the blocks requested with it. - callbacks:watch checks read access before announcing the watch. - The label for both flags off is now "reads and writes blocked", so it no longer contradicts the credential check. - README and SECURITY.md say that a running callbacks:watch keeps the flags it started with. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- SECURITY.md | 6 ++- .../Callbacks/WatchCallbacksCommand.php | 3 ++ app/Commands/Merchants/AddMerchantCommand.php | 30 +++++++++-- .../Merchants/SetMerchantAccessCommand.php | 51 +++++++++++++------ app/Credentials/MerchantAccess.php | 16 +++++- .../Merchants/AddMerchantCommandTest.php | 31 ++++++++++- .../SetMerchantAccessCommandTest.php | 20 +++++++- .../Console/AuthenticatedCommandTest.php | 3 +- tests/Unit/Credentials/MerchantAccessTest.php | 2 +- 10 files changed, 138 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 689095b..75c386f 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,9 @@ quickpay merchants:access "My Website" --write ``` `--no-read` blocks `GET` requests the same way. A blocked request stops before -anything reaches Quickpay. Allowing requests again asks you to confirm in an +anything reaches Quickpay. A change applies to commands you start afterwards, so +restart a running `callbacks:watch`. Allowing requests again, with +`merchants:access` or `merchants:add --replace`, asks you to confirm in an interactive terminal, so a script or agent can't lift a block on its own. Capture, refund and cancel need both reads and writes, because they show you the payment before asking to continue. A key in `QUICKPAY_API_KEY` always has full diff --git a/SECURITY.md b/SECURITY.md index 2d5c216..49f23fd 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -61,8 +61,10 @@ refuses any request they block before sending it: `GET` is a read and every other method is a write. Capture, refund, cancel and raw mutations check the flags before inspecting a payment or asking for confirmation. The credential check behind `merchants:add` and `merchants:active --check` is exempt, because it -reads no merchant data. Blocking works anywhere; allowing requests again needs -an interactive terminal and a confirmation. A key from `QUICKPAY_API_KEY` has +reads no merchant data. Blocking works anywhere; allowing requests again, with +`merchants:access` or `merchants:add --replace`, needs an interactive terminal +and a confirmation. Flags are read when a command starts, so a running +`callbacks:watch` keeps the access it started with. A key from `QUICKPAY_API_KEY` has full access. The flags are a local guardrail, not Quickpay permissions: anyone who can edit the configuration file can change them. diff --git a/app/Commands/Callbacks/WatchCallbacksCommand.php b/app/Commands/Callbacks/WatchCallbacksCommand.php index 0efe791..03f8192 100644 --- a/app/Commands/Callbacks/WatchCallbacksCommand.php +++ b/app/Commands/Callbacks/WatchCallbacksCommand.php @@ -57,6 +57,9 @@ function (AuthenticatedQuickpay $authenticated) use ($watch, $privateKeys): int $interval = $this->interval(); $deliveryAttempts = $this->deliveryAttempts(); $apiKey = $authenticated->apiKey->value(); + // Watching only polls with GET. Checking first keeps a merchant + // that blocks reads from announcing a watch it cannot run. + $authenticated->client->authorize('GET'); $this->writeMerchantContext($authenticated); $warning = $privateKeys->overrideWarning($authenticated->apiKey); if ($warning !== null) { diff --git a/app/Commands/Merchants/AddMerchantCommand.php b/app/Commands/Merchants/AddMerchantCommand.php index ceac376..cf1ebc6 100644 --- a/app/Commands/Merchants/AddMerchantCommand.php +++ b/app/Commands/Merchants/AddMerchantCommand.php @@ -51,6 +51,23 @@ public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, return $this->failure('Adding a merchant requires an interactive terminal. Use QUICKPAY_API_KEY for automation.'); } + $read = $this->flag('read'); + $write = $this->flag('write'); + $lifting = []; + if ($saved) { + // A replacement keeps the saved flags, so lifting one of their + // blocks asks first, the same way merchants:access does. + $current = $config['merchants'][$name]; + $lifting = (new MerchantAccess($current['read'], $current['write']))->lifts($read, $write); + $read = $read === true && ! in_array('read', $lifting, true) ? null : $read; + $write = $write === true && ! in_array('write', $lifting, true) ? null : $write; + if ($lifting !== [] && ! $this->confirm('Allow '.implode(' and ', $lifting).' requests for '.$name.'?', false)) { + $this->line('Cancelled.'); + + return self::SUCCESS; + } + } + $answer = $this->secret('API key'); $apiKey = is_string($answer) ? trim($answer) : ''; @@ -64,11 +81,9 @@ public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, } $check->check($credential); - $read = $this->option('read'); - $write = $this->option('write'); - $access = $store->add($name, $apiKey, (bool) $this->option('replace'), is_bool($read) ? $read : null, is_bool($write) ? $write : null); + $access = $store->add($name, $apiKey, (bool) $this->option('replace'), $read, $write); $this->info('Merchant saved: '.$name); - if (! $access->isFull()) { + if (! $access->isFull() || $lifting !== []) { $this->line('Access: '.$access->label()); } @@ -85,4 +100,11 @@ public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, return $this->failure($credential?->redact($exception->getMessage()) ?? $exception->getMessage()); } } + + private function flag(string $name): ?bool + { + $value = $this->option($name); + + return is_bool($value) ? $value : null; + } } diff --git a/app/Commands/Merchants/SetMerchantAccessCommand.php b/app/Commands/Merchants/SetMerchantAccessCommand.php index cef5d23..c54d80e 100644 --- a/app/Commands/Merchants/SetMerchantAccessCommand.php +++ b/app/Commands/Merchants/SetMerchantAccessCommand.php @@ -33,30 +33,41 @@ public function handle(MerchantStore $store, StdinTerminalDetector $terminal): i return $this->failure('Merchant is not saved. Run quickpay merchants:list to see saved names.'); } - $read = $this->flag('read'); - $write = $this->flag('write'); - if ($read === null && $write === null) { - $saved = $config['merchants'][$name]; - $this->line($this->summary($name, new MerchantAccess($saved['read'], $saved['write']))); - - return self::SUCCESS; - } - - // Blocking requests is always safe. Allowing them needs a person at - // the keyboard, so an automated caller cannot lift a block itself. - $allowing = array_keys(array_filter(['read' => $read, 'write' => $write], fn (?bool $flag): bool => $flag === true)); - if ($allowing !== []) { + $saved = $config['merchants'][$name]; + $current = new MerchantAccess($saved['read'], $saved['write']); + // Blocking requests is always safe. Lifting a block needs a person + // at the keyboard, so an automated caller cannot lift one itself. + $lifting = $current->lifts($this->flag('read'), $this->flag('write')); + // Allowing what is already allowed is dropped, not saved, so it can + // never undo a block that another command saves in the meantime. + $read = $this->change('read', $lifting); + $write = $this->change('write', $lifting); + + if ($lifting !== []) { if (! $this->input->isInteractive() || ! $terminal->isTty()) { return $this->failure('Allowing requests for a merchant requires an interactive terminal.'); } - if (! $this->confirm('Allow '.implode(' and ', $allowing).' requests for '.$name.'?', false)) { - $this->line('Cancelled.'); + if (! $this->confirm('Allow '.implode(' and ', $lifting).' requests for '.$name.'?', false)) { + // A declined allow still applies any block that was asked for. + $read = $read === true ? null : $read; + $write = $write === true ? null : $write; + if ($read === null && $write === null) { + $this->line('Cancelled.'); + + return self::SUCCESS; + } - return self::SUCCESS; + $this->line(ucfirst(implode(' and ', $lifting)).' requests stay blocked.'); } } + if ($read === null && $write === null) { + $this->line($this->summary($name, $current)); + + return self::SUCCESS; + } + $this->info($this->summary($name, $store->changeAccess($name, $read, $write))); return self::SUCCESS; @@ -72,6 +83,14 @@ private function flag(string $name): ?bool return is_bool($value) ? $value : null; } + /** @param list $lifting */ + private function change(string $name, array $lifting): ?bool + { + $flag = $this->flag($name); + + return $flag === true && ! in_array($name, $lifting, true) ? null : $flag; + } + private function summary(string $name, MerchantAccess $access): string { return "Access for {$name}: {$access->label()}"; diff --git a/app/Credentials/MerchantAccess.php b/app/Credentials/MerchantAccess.php index fa7a23d..03ebdb1 100644 --- a/app/Credentials/MerchantAccess.php +++ b/app/Credentials/MerchantAccess.php @@ -30,13 +30,27 @@ public function isFull(): bool return $this->read && $this->write; } + /** + * The request types a change would allow again. Allowing what is already + * allowed lifts nothing, so it never needs a person to confirm it. + * + * @return list + */ + public function lifts(?bool $read, ?bool $write): array + { + return array_keys(array_filter([ + 'read' => $read === true && ! $this->read, + 'write' => $write === true && ! $this->write, + ])); + } + public function label(): string { return match (true) { $this->read && $this->write => 'read and write', $this->read => 'read-only', $this->write => 'write-only', - default => 'no API access', + default => 'reads and writes blocked', }; } } diff --git a/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php index b6bd54c..1846e00 100644 --- a/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php @@ -116,7 +116,7 @@ public function isTty(): bool 'default' => [[], ['read' => true, 'write' => true], null], 'read-only' => [['--no-write' => true], ['read' => true, 'write' => false], 'read-only'], 'write-only' => [['--no-read' => true], ['read' => false, 'write' => true], 'write-only'], - 'none' => [['--no-read' => true, '--no-write' => true], ['read' => false, 'write' => false], 'no API access'], + 'none' => [['--no-read' => true, '--no-write' => true], ['read' => false, 'write' => false], 'reads and writes blocked'], ]); it('keeps access flags when replacing a credential', function (): void { @@ -126,3 +126,32 @@ public function isTty(): bool ->expectsQuestion('API key', 'fake-replacement')->expectsOutputToContain('Access: read-only')->assertExitCode(0); expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'read' => true, 'write' => false]); }); + +it('asks before a replacement lifts a saved block', function (): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); + $this->store->add('shop-a', 'fake-original', write: false); + $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true, '--write' => true]) + ->expectsConfirmation('Allow write requests for shop-a?', 'yes') + ->expectsQuestion('API key', 'fake-replacement') + ->expectsOutputToContain('Access: read and write')->assertExitCode(0); + expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'read' => true, 'write' => true]); +}); + +it('keeps the saved merchant when lifting a block is declined', function (): void { + $this->store->add('shop-a', 'fake-original', read: false, write: false); + $before = file_get_contents($this->store->path()); + $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true, '--read' => true]) + ->expectsConfirmation('Allow read requests for shop-a?', 'no') + ->expectsOutputToContain('Cancelled.')->assertExitCode(0); + expect(file_get_contents($this->store->path()))->toBe($before); + Http::assertNothingSent(); +}); + +it('does not ask when a replacement allows what is already allowed', function (): void { + Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); + $this->store->add('shop-a', 'fake-original', write: false); + $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true, '--read' => 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' => true, 'write' => false]); +}); diff --git a/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php b/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php index adac565..83d73e7 100644 --- a/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php +++ b/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php @@ -12,9 +12,27 @@ })->with([ 'block writes' => [['--no-write' => true], ['read' => true, 'write' => false], 'read-only'], 'block reads' => [['--no-read' => true], ['read' => false, 'write' => true], 'write-only'], - 'block both' => [['--no-read' => true, '--no-write' => true], ['read' => false, 'write' => false], 'no API access'], + 'block both' => [['--no-read' => true, '--no-write' => true], ['read' => false, 'write' => false], 'reads and writes blocked'], + 'block writes while keeping reads' => [['--read' => true, '--no-write' => true], ['read' => true, 'write' => false], 'read-only'], ]); +it('allows what is already allowed without asking or writing', function (): void { + $this->store->add('shop-a', 'fake-secret-a', write: false); + $before = file_get_contents($this->store->path()); + $this->artisan('merchants:access', ['name' => 'shop-a', '--read' => true, '--no-interaction' => true]) + ->expectsOutputToContain('Access for shop-a: read-only')->assertExitCode(0); + expect(file_get_contents($this->store->path()))->toBe($before); +}); + +it('still applies a requested block when allowing is declined', function (): void { + $this->store->add('shop-a', 'fake-secret-a', read: false); + $this->artisan('merchants:access', ['name' => 'shop-a', '--read' => true, '--no-write' => true]) + ->expectsConfirmation('Allow read requests for shop-a?', 'no') + ->expectsOutputToContain('Read requests stay blocked.') + ->expectsOutputToContain('Access for shop-a: reads and writes blocked')->assertExitCode(0); + expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-secret-a', 'read' => false, 'write' => false]); +}); + it('allows blocked requests again only after an interactive confirmation', function (array $flags, string $question, array $saved): void { $this->store->add('shop-a', 'fake-secret-a', read: false, write: false); $this->artisan('merchants:access', ['name' => 'shop-a', ...$flags]) diff --git a/tests/Feature/Console/AuthenticatedCommandTest.php b/tests/Feature/Console/AuthenticatedCommandTest.php index 2eb9122..7ea2eee 100644 --- a/tests/Feature/Console/AuthenticatedCommandTest.php +++ b/tests/Feature/Console/AuthenticatedCommandTest.php @@ -252,7 +252,8 @@ public function run(?string $paymentId, ?string $orderId, CallbackTarget $target $this->store->add('shop-w', 'fake-secret-w', read: false); Http::fake(); $this->artisan($command, [...$arguments, '--merchant' => 'shop-w']) - ->expectsOutputToContain('does not allow read requests')->assertExitCode(1); + ->expectsOutputToContain('does not allow read requests') + ->doesntExpectOutputToContain('Watching')->assertExitCode(1); Http::assertNothingSent(); })->with([ 'get' => ['payments:get', ['id' => '42']], diff --git a/tests/Unit/Credentials/MerchantAccessTest.php b/tests/Unit/Credentials/MerchantAccessTest.php index 38e57b4..1a755ee 100644 --- a/tests/Unit/Credentials/MerchantAccessTest.php +++ b/tests/Unit/Credentials/MerchantAccessTest.php @@ -28,7 +28,7 @@ 'full' => [true, true, 'read and write', true], 'read-only' => [true, false, 'read-only', false], 'write-only' => [false, true, 'write-only', false], - 'none' => [false, false, 'no API access', false], + 'none' => [false, false, 'reads and writes blocked', false], ]); it('grants full access by default only through the named constructor', function (): void { From 4233f52b8ffdd774b7ff97a13991c71edc7c6e9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Mon, 23 Nov 2026 18:27:42 +0100 Subject: [PATCH 13/16] refactor: reduce merchant access flags to write protection Blocking reads protected little and cost a lot: capture, refund, cancel and callbacks all need reads, and most access edge cases came from it. Saved merchants now carry a single write flag, and a read-only merchant may send only GET. - Removes --read and --no-read from merchants:add and merchants:access. - The saved config is {"api_key": ..., "write": bool}; a read flag is rejected like any other extra field. - merchants:list and merchants:active report write only. - Drops the ping exemption and the read check in callbacks:watch, which only existed for merchants that blocked reads. - Blocked writes now fail with "The selected merchant is read-only". Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 8 +-- CHANGELOG.md | 2 +- README.md | 12 ++-- SECURITY.md | 19 +++--- .../Callbacks/WatchCallbacksCommand.php | 3 - .../Merchants/ActiveMerchantCommand.php | 3 +- app/Commands/Merchants/AddMerchantCommand.php | 33 ++++------ .../Merchants/ListMerchantsCommand.php | 16 ++--- .../Merchants/SetMerchantAccessCommand.php | 65 ++++++------------ app/Credentials/ApiKeyResolver.php | 2 +- .../Exceptions/MerchantAccessException.php | 5 +- app/Credentials/MerchantAccess.php | 38 ++--------- app/Credentials/MerchantStore.php | 29 ++++---- app/Quickpay/MerchantAuthenticationCheck.php | 2 +- app/Quickpay/QuickpayClient.php | 17 +---- skills/quickpay-cli/SKILL.md | 21 +++--- .../Merchants/ActiveMerchantCommandTest.php | 18 ++--- .../Merchants/AddMerchantCommandTest.php | 32 +++++---- .../Merchants/ListMerchantsCommandTest.php | 14 ++-- .../Merchants/RemoveMerchantCommandTest.php | 2 +- .../SetMerchantAccessCommandTest.php | 49 ++++++-------- .../Console/AuthenticatedCommandTest.php | 28 +------- tests/Feature/Quickpay/QuickpayClientTest.php | 43 +++--------- .../Credentials/MerchantStoreTest.php | 66 +++++++++---------- tests/Unit/Credentials/MerchantAccessTest.php | 44 +++++-------- 25 files changed, 201 insertions(+), 370 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fbdc141..61ccd46 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -81,10 +81,10 @@ validation, and the locked-dependency audit. 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 `read` and `write` flags that `QuickpayClient` enforces - before sending: `GET` is a read, every other method a write. Commands that - inspect or confirm before mutating check them first. Allowing requests needs - an interactive terminal; `QUICKPAY_API_KEY` has full access. +- Saved merchants carry a `write` flag that `QuickpayClient` enforces before + sending: a read-only merchant may send only `GET`. Commands that inspect or + confirm before mutating check it first. Allowing writes needs an interactive + terminal; `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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 95b9c1f..19ae501 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - 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 and write access flags for each saved merchant, set with `merchants:add --no-read` or `--no-write` and changed with `merchants:access`. Blocked requests fail before anything is sent. +- Read-only merchants. `merchants:add --no-write` or `merchants:access --no-write` blocks every request except `GET` before anything is sent, and `merchants:access --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. diff --git a/README.md b/README.md index 75c386f..3b0f704 100644 --- a/README.md +++ b/README.md @@ -70,14 +70,10 @@ quickpay merchants:access "My Website" --no-write quickpay merchants:access "My Website" --write ``` -`--no-read` blocks `GET` requests the same way. A blocked request stops before -anything reaches Quickpay. A change applies to commands you start afterwards, so -restart a running `callbacks:watch`. Allowing requests again, with -`merchants:access` or `merchants:add --replace`, asks you to confirm in an -interactive terminal, so a script or agent can't lift a block on its own. -Capture, refund and cancel need both reads and writes, because they show you the -payment before asking to continue. A key in `QUICKPAY_API_KEY` always has full -access. +A blocked request stops before anything reaches Quickpay. Allowing writes again, +with `merchants:access` or `merchants:add --replace`, asks you to confirm in an +interactive terminal, so a script or agent can't lift the protection on its own. +A key in `QUICKPAY_API_KEY` always has full access. ## Payments diff --git a/SECURITY.md b/SECURITY.md index 49f23fd..01eb993 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -56,17 +56,14 @@ 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 `read` and `write` flags. `QuickpayClient` -refuses any request they block before sending it: `GET` is a read and every -other method is a write. Capture, refund, cancel and raw mutations check the -flags before inspecting a payment or asking for confirmation. The credential -check behind `merchants:add` and `merchants:active --check` is exempt, because it -reads no merchant data. Blocking works anywhere; allowing requests again, with -`merchants:access` or `merchants:add --replace`, needs an interactive terminal -and a confirmation. Flags are read when a command starts, so a running -`callbacks:watch` keeps the access it started with. A key from `QUICKPAY_API_KEY` has -full access. The flags are a local guardrail, not Quickpay permissions: anyone -who can edit the configuration file can change them. +Each saved merchant also stores a `write` 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; allowing +writes again, with `merchants:access` or `merchants:add --replace`, needs an +interactive terminal and a confirmation. A key from `QUICKPAY_API_KEY` has full +access. The flag is a local guardrail, not a Quickpay permission: anyone who can +edit the configuration file can change it. ## Local callback forwarding diff --git a/app/Commands/Callbacks/WatchCallbacksCommand.php b/app/Commands/Callbacks/WatchCallbacksCommand.php index 03f8192..0efe791 100644 --- a/app/Commands/Callbacks/WatchCallbacksCommand.php +++ b/app/Commands/Callbacks/WatchCallbacksCommand.php @@ -57,9 +57,6 @@ function (AuthenticatedQuickpay $authenticated) use ($watch, $privateKeys): int $interval = $this->interval(); $deliveryAttempts = $this->deliveryAttempts(); $apiKey = $authenticated->apiKey->value(); - // Watching only polls with GET. Checking first keeps a merchant - // that blocks reads from announcing a watch it cannot run. - $authenticated->client->authorize('GET'); $this->writeMerchantContext($authenticated); $warning = $privateKeys->overrideWarning($authenticated->apiKey); if ($warning !== null) { diff --git a/app/Commands/Merchants/ActiveMerchantCommand.php b/app/Commands/Merchants/ActiveMerchantCommand.php index 3921cbf..385e7e5 100644 --- a/app/Commands/Merchants/ActiveMerchantCommand.php +++ b/app/Commands/Merchants/ActiveMerchantCommand.php @@ -37,7 +37,6 @@ public function handle(ApiKeyResolver $resolver, MerchantAuthenticationCheck $ch 'selection_source' => $key?->selectionSource(), 'credential_source' => $key?->source(), 'configured' => $key !== null, - 'read' => $key?->access()->read, 'write' => $key?->access()->write, 'checked' => $checkRequested, 'authenticated' => $authenticated, @@ -52,7 +51,7 @@ public function handle(ApiKeyResolver $resolver, MerchantAuthenticationCheck $ch $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()->isFull()) { + if ($key !== null && ! $key->access()->write) { $this->line('Access: '.$key->access()->label()); } $this->line('Credentials configured: '.($status['configured'] ? 'yes' : 'no')); diff --git a/app/Commands/Merchants/AddMerchantCommand.php b/app/Commands/Merchants/AddMerchantCommand.php index cf1ebc6..c677f26 100644 --- a/app/Commands/Merchants/AddMerchantCommand.php +++ b/app/Commands/Merchants/AddMerchantCommand.php @@ -26,7 +26,6 @@ class AddMerchantCommand extends BaseCommand public function __construct() { parent::__construct(); - $this->addOption('read', null, InputOption::VALUE_NEGATABLE, 'Allow read requests (GET). Allowed by default; --replace keeps the saved setting'); $this->addOption('write', null, InputOption::VALUE_NEGATABLE, 'Allow write requests (POST, PUT, PATCH, DELETE). Allowed by default; --replace keeps the saved setting'); } @@ -51,17 +50,16 @@ public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, return $this->failure('Adding a merchant requires an interactive terminal. Use QUICKPAY_API_KEY for automation.'); } - $read = $this->flag('read'); - $write = $this->flag('write'); - $lifting = []; - if ($saved) { - // A replacement keeps the saved flags, so lifting one of their - // blocks asks first, the same way merchants:access does. - $current = $config['merchants'][$name]; - $lifting = (new MerchantAccess($current['read'], $current['write']))->lifts($read, $write); - $read = $read === true && ! in_array('read', $lifting, true) ? null : $read; - $write = $write === true && ! in_array('write', $lifting, true) ? null : $write; - if ($lifting !== [] && ! $this->confirm('Allow '.implode(' and ', $lifting).' requests for '.$name.'?', false)) { + $write = $this->option('write'); + $write = is_bool($write) ? $write : null; + $lifting = false; + if ($saved && $write === true) { + // A replacement keeps the saved flag, so making a read-only + // merchant writable asks first, the same way merchants:access does. + // Allowing what is already allowed is dropped rather than saved. + $lifting = ! $config['merchants'][$name]['write']; + $write = $lifting ? true : null; + if ($lifting && ! $this->confirm('Allow write requests for '.$name.'?', false)) { $this->line('Cancelled.'); return self::SUCCESS; @@ -81,9 +79,9 @@ public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, } $check->check($credential); - $access = $store->add($name, $apiKey, (bool) $this->option('replace'), $read, $write); + $access = $store->add($name, $apiKey, (bool) $this->option('replace'), $write); $this->info('Merchant saved: '.$name); - if (! $access->isFull() || $lifting !== []) { + if (! $access->write || $lifting) { $this->line('Access: '.$access->label()); } @@ -100,11 +98,4 @@ public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, return $this->failure($credential?->redact($exception->getMessage()) ?? $exception->getMessage()); } } - - private function flag(string $name): ?bool - { - $value = $this->option($name); - - return is_bool($value) ? $value : null; - } } diff --git a/app/Commands/Merchants/ListMerchantsCommand.php b/app/Commands/Merchants/ListMerchantsCommand.php index 64e7e47..185f59c 100644 --- a/app/Commands/Merchants/ListMerchantsCommand.php +++ b/app/Commands/Merchants/ListMerchantsCommand.php @@ -27,7 +27,6 @@ public function handle(MerchantStore $store): int $rows = array_map(fn (string $name): array => [ 'name' => $name, 'default' => $config['default_merchant'] === $name, - 'read' => $config['merchants'][$name]['read'], 'write' => $config['merchants'][$name]['write'], ], $names); @@ -36,20 +35,15 @@ public function handle(MerchantStore $store): int } elseif ($rows === []) { $this->line('No saved merchants. Run quickpay merchants:add first.'); } else { - // Access is shown only for merchants that block requests. - $restricted = array_map(function (array $row): ?string { - $access = new MerchantAccess($row['read'], $row['write']); - - return $access->isFull() ? null : $access->label(); - }, $rows); - $showAccess = array_filter($restricted) !== []; + // Access is shown only when a merchant is read-only. + $showAccess = in_array(false, array_column($rows, 'write'), true); $this->table( ['Merchant', 'Global default', ...($showAccess ? ['Access'] : [])], - array_map(fn (array $row, ?string $access): array => [ + array_map(fn (array $row): array => [ $row['name'], $row['default'] ? 'yes' : '', - ...($showAccess ? [$access ?? ''] : []), - ], $rows, $restricted), + ...($showAccess ? [$row['write'] ? '' : (new MerchantAccess(false))->label()] : []), + ], $rows), ); } diff --git a/app/Commands/Merchants/SetMerchantAccessCommand.php b/app/Commands/Merchants/SetMerchantAccessCommand.php index c54d80e..834e9f6 100644 --- a/app/Commands/Merchants/SetMerchantAccessCommand.php +++ b/app/Commands/Merchants/SetMerchantAccessCommand.php @@ -15,13 +15,12 @@ class SetMerchantAccessCommand extends BaseCommand protected $signature = 'merchants:access {name : Saved merchant name}'; - protected $description = 'Show or change which Quickpay requests a saved merchant may send'; + protected $description = 'Show or change whether a saved merchant may send write requests'; public function __construct() { parent::__construct(); - $this->addOption('read', null, InputOption::VALUE_NEGATABLE, 'Allow read requests (GET); --no-read blocks them. Allowing needs an interactive terminal'); - $this->addOption('write', null, InputOption::VALUE_NEGATABLE, 'Allow write requests (POST, PUT, PATCH, DELETE); --no-write blocks them. Allowing needs an interactive terminal'); + $this->addOption('write', null, InputOption::VALUE_NEGATABLE, 'Allow write requests (POST, PUT, PATCH, DELETE); --no-write makes the merchant read-only. Allowing needs an interactive terminal'); } public function handle(MerchantStore $store, StdinTerminalDetector $terminal): int @@ -33,42 +32,31 @@ public function handle(MerchantStore $store, StdinTerminalDetector $terminal): i return $this->failure('Merchant is not saved. Run quickpay merchants:list to see saved names.'); } - $saved = $config['merchants'][$name]; - $current = new MerchantAccess($saved['read'], $saved['write']); - // Blocking requests is always safe. Lifting a block needs a person - // at the keyboard, so an automated caller cannot lift one itself. - $lifting = $current->lifts($this->flag('read'), $this->flag('write')); - // Allowing what is already allowed is dropped, not saved, so it can - // never undo a block that another command saves in the meantime. - $read = $this->change('read', $lifting); - $write = $this->change('write', $lifting); + $current = new MerchantAccess($config['merchants'][$name]['write']); + $write = $this->option('write'); + // Allowing what is already allowed changes nothing, so it is not + // saved and cannot undo a block saved in the meantime. + if (! is_bool($write) || ($write && $current->write)) { + $this->line($this->summary($name, $current)); - if ($lifting !== []) { + 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 ($write) { if (! $this->input->isInteractive() || ! $terminal->isTty()) { - return $this->failure('Allowing requests for a merchant requires an interactive terminal.'); + return $this->failure('Allowing write requests requires an interactive terminal.'); } - if (! $this->confirm('Allow '.implode(' and ', $lifting).' requests for '.$name.'?', false)) { - // A declined allow still applies any block that was asked for. - $read = $read === true ? null : $read; - $write = $write === true ? null : $write; - if ($read === null && $write === null) { - $this->line('Cancelled.'); - - return self::SUCCESS; - } + if (! $this->confirm('Allow write requests for '.$name.'?', false)) { + $this->line('Cancelled.'); - $this->line(ucfirst(implode(' and ', $lifting)).' requests stay blocked.'); + return self::SUCCESS; } } - if ($read === null && $write === null) { - $this->line($this->summary($name, $current)); - - return self::SUCCESS; - } - - $this->info($this->summary($name, $store->changeAccess($name, $read, $write))); + $this->info($this->summary($name, $store->changeAccess($name, $write))); return self::SUCCESS; } catch (CredentialException $exception) { @@ -76,21 +64,6 @@ public function handle(MerchantStore $store, StdinTerminalDetector $terminal): i } } - private function flag(string $name): ?bool - { - $value = $this->option($name); - - return is_bool($value) ? $value : null; - } - - /** @param list $lifting */ - private function change(string $name, array $lifting): ?bool - { - $flag = $this->flag($name); - - return $flag === true && ! in_array($name, $lifting, true) ? null : $flag; - } - private function summary(string $name, MerchantAccess $access): string { return "Access for {$name}: {$access->label()}"; diff --git a/app/Credentials/ApiKeyResolver.php b/app/Credentials/ApiKeyResolver.php index 2b52e63..3541429 100644 --- a/app/Credentials/ApiKeyResolver.php +++ b/app/Credentials/ApiKeyResolver.php @@ -53,6 +53,6 @@ public function resolve(?string $merchant = null): ?ApiKey $saved = $config['merchants'][$name]; - return new ApiKey($saved['api_key'], 'config file', new MerchantAccess($saved['read'], $saved['write']), $name, $source); + return new ApiKey($saved['api_key'], 'config file', new MerchantAccess($saved['write']), $name, $source); } } diff --git a/app/Credentials/Exceptions/MerchantAccessException.php b/app/Credentials/Exceptions/MerchantAccessException.php index 775ca15..99bb103 100644 --- a/app/Credentials/Exceptions/MerchantAccessException.php +++ b/app/Credentials/Exceptions/MerchantAccessException.php @@ -3,7 +3,7 @@ namespace App\Credentials\Exceptions; /** - * A request the selected merchant's access flags do not allow. + * A write request from a read-only merchant. * * It deliberately is not a QuickpayRequestException: callback polling retries * those, and a blocked request must stop the command instead. @@ -13,8 +13,7 @@ final class MerchantAccessException extends CredentialException public static function blocked(string $method): self { $method = strtoupper($method); - $kind = $method === 'GET' ? 'read' : 'write'; - return new self("The selected merchant does not allow {$kind} requests, so the {$method} request was not sent."); + return new self("The selected merchant is read-only, so the {$method} request was not sent."); } } diff --git a/app/Credentials/MerchantAccess.php b/app/Credentials/MerchantAccess.php index 03ebdb1..8c1811f 100644 --- a/app/Credentials/MerchantAccess.php +++ b/app/Credentials/MerchantAccess.php @@ -3,54 +3,30 @@ namespace App\Credentials; /** - * Which Quickpay requests a saved merchant may send. + * Whether a saved merchant may send write requests. * - * GET is a read. Every other method is a write, so an unknown or future - * method is blocked for a read-only merchant instead of slipping through. + * GET is a read and always allowed. Every other method is a write, so an + * unknown or future method is blocked for a read-only merchant instead of + * slipping through. */ final readonly class MerchantAccess { public function __construct( - public bool $read, public bool $write, ) {} public static function full(): self { - return new self(true, true); + return new self(true); } public function allows(string $method): bool { - return strtoupper($method) === 'GET' ? $this->read : $this->write; - } - - public function isFull(): bool - { - return $this->read && $this->write; - } - - /** - * The request types a change would allow again. Allowing what is already - * allowed lifts nothing, so it never needs a person to confirm it. - * - * @return list - */ - public function lifts(?bool $read, ?bool $write): array - { - return array_keys(array_filter([ - 'read' => $read === true && ! $this->read, - 'write' => $write === true && ! $this->write, - ])); + return strtoupper($method) === 'GET' || $this->write; } public function label(): string { - return match (true) { - $this->read && $this->write => 'read and write', - $this->read => 'read-only', - $this->write => 'write-only', - default => 'reads and writes blocked', - }; + return $this->write ? 'read and write' : 'read-only'; } } diff --git a/app/Credentials/MerchantStore.php b/app/Credentials/MerchantStore.php index 69bf18b..d02557d 100644 --- a/app/Credentials/MerchantStore.php +++ b/app/Credentials/MerchantStore.php @@ -9,7 +9,7 @@ use stdClass; /** - * @phpstan-type SavedMerchant array{api_key: string, read: bool, write: bool} + * @phpstan-type SavedMerchant array{api_key: string, write: bool} * @phpstan-type MerchantConfig array{default_merchant: ?string, merchants: array} */ final readonly class MerchantStore @@ -81,12 +81,10 @@ public function read(): array || trim($merchant->api_key) === '') { throw new CredentialException('Quickpay CLI merchant configuration contains an invalid credential.'); } - if (count(get_object_vars($merchant)) !== 3 - || ! is_bool($merchant->read ?? null) - || ! is_bool($merchant->write ?? null)) { - throw new CredentialException('Quickpay CLI merchant configuration needs exactly an API key and true or false read and write access flags for each merchant.'); + if (count(get_object_vars($merchant)) !== 2 || ! is_bool($merchant->write ?? null)) { + throw new CredentialException('Quickpay CLI merchant configuration needs exactly an API key and a true or false write flag for each merchant.'); } - $merchants[$name] = ['api_key' => $merchant->api_key, 'read' => $merchant->read, 'write' => $merchant->write]; + $merchants[$name] = ['api_key' => $merchant->api_key, 'write' => $merchant->write]; } $this->validateLabels($merchants); @@ -102,7 +100,7 @@ public function read(): array * keeps the replaced merchant's flag, or allows that kind of request for a * new merchant. */ - public function add(string $name, string $apiKey, bool $replace = false, ?bool $read = null, ?bool $write = null): MerchantAccess + public function add(string $name, string $apiKey, bool $replace = false, ?bool $write = null): MerchantAccess { MerchantName::validate($name); $apiKey = trim($apiKey); @@ -110,7 +108,7 @@ public function add(string $name, string $apiKey, bool $replace = false, ?bool $ throw new CredentialException('API key cannot be empty.'); } $access = null; - $this->mutate(function (array $config) use ($name, $apiKey, $replace, $read, $write, &$access): array { + $this->mutate(function (array $config) use ($name, $apiKey, $replace, $write, &$access): array { if (isset($config['merchants'][$name]) && ! $replace) { throw new CredentialException('Merchant is already saved. Use --replace to replace its credential.'); } @@ -121,8 +119,8 @@ public function add(string $name, string $apiKey, bool $replace = false, ?bool $ $config['default_merchant'] = $name; } $existing = $config['merchants'][$name] ?? null; - $access = new MerchantAccess($read ?? $existing['read'] ?? true, $write ?? $existing['write'] ?? true); - $config['merchants'][$name] = ['api_key' => $apiKey, 'read' => $access->read, 'write' => $access->write]; + $access = new MerchantAccess($write ?? $existing['write'] ?? true); + $config['merchants'][$name] = ['api_key' => $apiKey, 'write' => $access->write]; $this->validateLabels($config['merchants']); return $config; @@ -142,16 +140,15 @@ public function select(string $name): void }); } - /** Changes the given flags under the store lock; a null flag is kept. */ - public function changeAccess(string $name, ?bool $read = null, ?bool $write = null): MerchantAccess + /** Sets the write flag under the store lock. */ + public function changeAccess(string $name, bool $write): MerchantAccess { MerchantName::validate($name); $access = null; - $this->mutate(function (array $config) use ($name, $read, $write, &$access): array { + $this->mutate(function (array $config) use ($name, $write, &$access): array { $this->requireMerchant($config, $name); - $saved = $config['merchants'][$name]; - $access = new MerchantAccess($read ?? $saved['read'], $write ?? $saved['write']); - $config['merchants'][$name] = [...$saved, 'read' => $access->read, 'write' => $access->write]; + $access = new MerchantAccess($write); + $config['merchants'][$name] = [...$config['merchants'][$name], 'write' => $write]; return $config; }); diff --git a/app/Quickpay/MerchantAuthenticationCheck.php b/app/Quickpay/MerchantAuthenticationCheck.php index bf6436d..22bb68f 100644 --- a/app/Quickpay/MerchantAuthenticationCheck.php +++ b/app/Quickpay/MerchantAuthenticationCheck.php @@ -13,7 +13,7 @@ public function __construct(private AuthenticatedQuickpayFactory $quickpay) {} public function check(ApiKey $apiKey): void { - $response = $this->quickpay->from($apiKey)->client->ping(); + $response = $this->quickpay->from($apiKey)->client->get('/ping'); if (! $response->successful()) { throw new QuickpayRequestException('Authentication check failed: '.ResponseBodySanitizer::terminalLine($response->errorSummary(), $apiKey->value())); } diff --git a/app/Quickpay/QuickpayClient.php b/app/Quickpay/QuickpayClient.php index 9641092..4550dd5 100644 --- a/app/Quickpay/QuickpayClient.php +++ b/app/Quickpay/QuickpayClient.php @@ -14,8 +14,8 @@ * Owns every HTTP invariant required by the Quickpay API boundary. * * Callers provide relative paths and business payloads only. Authentication, - * origin, API version, JSON headers, timeout, and the merchant's read and write - * access remain centralized so raw API access cannot weaken the same guarantees + * 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 @@ -31,7 +31,7 @@ public function __construct( ) {} /** - * Fails before any request the merchant's access flags do not allow. + * 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. @@ -45,17 +45,6 @@ public function authorize(string $method): void } } - /** - * Verifies the credential itself. - * - * It is exempt from the access flags because it reads no merchant data, so - * a merchant that blocks reads can still be checked. - */ - public function ping(): QuickpayResponse - { - return $this->send('GET', '/ping'); - } - /** * @param array $query * @param array $data diff --git a/skills/quickpay-cli/SKILL.md b/skills/quickpay-cli/SKILL.md index 7c1bbb4..1e4fc17 100644 --- a/skills/quickpay-cli/SKILL.md +++ b/skills/quickpay-cli/SKILL.md @@ -50,14 +50,13 @@ 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. -Each saved merchant can block reads (`GET`) or writes (`POST`, `PUT`, `PATCH`, -`DELETE`). `merchants:active --json` reports `read` and `write`. A blocked -request fails with "does not allow read requests" or "does not allow write -requests" before anything is sent. That block is the user's decision: stop and -report it. Never lift or bypass it by running `merchants:access` with `--read` -or `--write`, re-adding the merchant, editing configuration files, or switching -to another merchant or to `QUICKPAY_API_KEY`. Add a block with `--no-read` or -`--no-write` only when the user asks. +A saved merchant can be read-only: it may send `GET` requests but no writes +(`POST`, `PUT`, `PATCH`, `DELETE`). `merchants:active --json` reports `write`. 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 --write`, re-adding the merchant, editing configuration files, +or switching to another merchant or to `QUICKPAY_API_KEY`. Make a merchant +read-only with `--no-write` only when the user asks. ## Safety workflow @@ -82,8 +81,8 @@ For a refund or cancellation, use the same inspect → verify → explicit autho ```text quickpay about -quickpay merchants:add [--replace] [--no-read] [--no-write] -quickpay merchants:access [--read|--no-read] [--write|--no-write] +quickpay merchants:add [--replace] [--no-write] +quickpay merchants:access [--write|--no-write] quickpay merchants:list [--json] quickpay merchants:select [] [--local] quickpay merchants:active [--merchant=name] [--check] [--json] @@ -173,5 +172,5 @@ Do not use full URLs, hosts, schemes, `..`, backslashes, or fragments. The CLI o - A raw `GET` needs no `--yes`; a raw `POST`, `PUT`, `PATCH`, or `DELETE` does. - `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 `write` in `merchants:active --merchant= --json` before planning a mutation. Capture, refund and cancel need both `read` and `write`. +- Check `write` 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/Feature/Commands/Merchants/ActiveMerchantCommandTest.php b/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php index 13220ed..557096a 100644 --- a/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php @@ -18,7 +18,7 @@ [$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' => true, 'write' => true, 'checked' => false, 'authenticated' => null, + 'configured' => true, 'write' => true, '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); @@ -50,7 +50,7 @@ $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'])->toBeTrue()->and($data['write'])->toBeTrue(); + ->and($data['write'])->toBeTrue(); Http::assertNothingSent(); }); @@ -82,7 +82,7 @@ $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":true,"write":true},"sh\\u006fp-a":{"api_key":"fake-last","read":true,"write":true}}}'; + : '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","write":true},"sh\\u006fp-a":{"api_key":"fake-last","write":true}}}'; file_put_contents($path, $contents); Http::fake(['*' => Http::response(['scope' => 'merchant'])]); [$exit, $output, $errors] = merchantCommandResult(ActiveMerchantCommand::class, ['--check' => true, '--json' => true]); @@ -91,19 +91,19 @@ Http::assertNothingSent(); })->with(['store' => false, 'project' => true]); -it('reports restricted access and still verifies a merchant that blocks reads', function (): void { +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', read: false); + $this->store->add('shop-a', 'fake-secret-a', write: false); [$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'])->toBeFalse()->and($data['write'])->toBeTrue() + expect($exit)->toBe(0)->and($errors)->toBe('')->and($data['write'])->toBeFalse() ->and($data['authenticated'])->toBeTrue(); - $this->artisan('merchants:active')->expectsOutputToContain('Access: write-only')->assertExitCode(0); + $this->artisan('merchants:active')->expectsOutputToContain('Access: read-only')->assertExitCode(0); Http::assertSentCount(1); }); -it('reports no access flags when no credential is configured', function (): void { +it('reports no write 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['read'])->toBeNull()->and($data['write'])->toBeNull(); + expect($exit)->toBe(0)->and($data)->not->toHaveKey('read')->and($data['write'])->toBeNull(); }); diff --git a/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php index 1846e00..4a3035c 100644 --- a/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php @@ -104,7 +104,7 @@ public function isTty(): bool expect(file_exists($this->store->path()))->toBeFalse(); }); -it('saves access flags given when adding a merchant', function (array $flags, array $saved, ?string $label): void { +it('saves the write flag given when adding a merchant', 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'); @@ -113,35 +113,33 @@ public function isTty(): bool expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-secret-a', ...$saved]); Http::assertSentCount(1); })->with([ - 'default' => [[], ['read' => true, 'write' => true], null], - 'read-only' => [['--no-write' => true], ['read' => true, 'write' => false], 'read-only'], - 'write-only' => [['--no-read' => true], ['read' => false, 'write' => true], 'write-only'], - 'none' => [['--no-read' => true, '--no-write' => true], ['read' => false, 'write' => false], 'reads and writes blocked'], + 'default' => [[], ['write' => true], null], + 'read-only' => [['--no-write' => true], ['write' => false], 'read-only'], ]); -it('keeps access flags when replacing a credential', function (): void { +it('keeps the write flag when replacing a credential', function (): void { Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); $this->store->add('shop-a', 'fake-original', write: false); $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' => true, 'write' => false]); + expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'write' => false]); }); -it('asks before a replacement lifts a saved block', function (): void { +it('asks before a replacement makes a read-only merchant writable', function (): void { Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); $this->store->add('shop-a', 'fake-original', write: false); $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true, '--write' => true]) ->expectsConfirmation('Allow write requests for shop-a?', 'yes') ->expectsQuestion('API key', 'fake-replacement') ->expectsOutputToContain('Access: read and write')->assertExitCode(0); - expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'read' => true, 'write' => true]); + expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'write' => true]); }); -it('keeps the saved merchant when lifting a block is declined', function (): void { - $this->store->add('shop-a', 'fake-original', read: false, write: false); +it('keeps the saved merchant when allowing writes is declined', function (): void { + $this->store->add('shop-a', 'fake-original', write: false); $before = file_get_contents($this->store->path()); - $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true, '--read' => true]) - ->expectsConfirmation('Allow read requests for shop-a?', 'no') + $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true, '--write' => true]) + ->expectsConfirmation('Allow write requests for shop-a?', 'no') ->expectsOutputToContain('Cancelled.')->assertExitCode(0); expect(file_get_contents($this->store->path()))->toBe($before); Http::assertNothingSent(); @@ -149,9 +147,9 @@ public function isTty(): bool it('does not ask when a replacement allows what is already allowed', function (): void { Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); - $this->store->add('shop-a', 'fake-original', write: false); - $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true, '--read' => true]) + $this->store->add('shop-a', 'fake-original'); + $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true, '--write' => 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' => true, 'write' => false]); + ->doesntExpectOutputToContain('Access:')->assertExitCode(0); + expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'write' => true]); }); diff --git a/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php b/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php index a658eae..d1af1b5 100644 --- a/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php +++ b/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php @@ -8,7 +8,7 @@ $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' => true, 'write' => true], ['name' => 'My Website', 'default' => true, 'read' => true, 'write' => true]]); + ->toBe([['name' => 'My Other Website', 'default' => false, 'write' => true], ['name' => 'My Website', 'default' => true, 'write' => true]]); Http::assertNothingSent(); }); @@ -19,25 +19,23 @@ }); 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":true,"write":true},"fake-secret-a":{"api_key":"fake-secret-b","read":true,"write":true}}}'); + file_put_contents($this->store->path(), '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-secret-a","write":true},"fake-secret-a":{"api_key":"fake-secret-b","write":true}}}'); [$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 for merchants that block requests', function (): void { +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', write: false); - $this->store->add('shop-c', 'fake-secret-c', read: false); [$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' => true, 'write' => true], - ['name' => 'shop-b', 'default' => false, 'read' => true, 'write' => false], - ['name' => 'shop-c', 'default' => false, 'read' => false, 'write' => true], + ['name' => 'shop-a', 'default' => true, 'write' => true], + ['name' => 'shop-b', 'default' => false, 'write' => false], ]); [$exit, $output] = merchantCommandResult(ListMerchantsCommand::class); - expect($exit)->toBe(0)->and($output)->toContain('Access')->toContain('read-only')->toContain('write-only') + 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 index 98e1588..73d902e 100644 --- a/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php @@ -7,7 +7,7 @@ $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' => true, 'write' => true]]]); + expect($this->store->read())->toBe(['default_merchant' => null, 'merchants' => ['My Website' => ['api_key' => 'fake-secret-b', 'write' => true]]]); $this->artisan('merchants:remove', ['name' => 'shop-missing'])->assertExitCode(1); $this->artisan('merchants:remove', ['name' => 'My Website'])->assertExitCode(0); expect($this->store->read()['merchants'])->toBe([]); diff --git a/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php b/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php index 83d73e7..5d3cd4c 100644 --- a/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php +++ b/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php @@ -1,48 +1,37 @@ store->add('shop-a', 'fake-secret-a'); - $this->artisan('merchants:access', ['name' => 'shop-a', ...$flags, '--no-interaction' => true]) - ->expectsOutputToContain('Access for shop-a: '.$label)->assertExitCode(0); - expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-secret-a', ...$saved]); + $this->artisan('merchants:access', ['name' => 'shop-a', '--no-write' => 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', 'write' => false]); Http::assertNothingSent(); -})->with([ - 'block writes' => [['--no-write' => true], ['read' => true, 'write' => false], 'read-only'], - 'block reads' => [['--no-read' => true], ['read' => false, 'write' => true], 'write-only'], - 'block both' => [['--no-read' => true, '--no-write' => true], ['read' => false, 'write' => false], 'reads and writes blocked'], - 'block writes while keeping reads' => [['--read' => true, '--no-write' => true], ['read' => true, 'write' => false], 'read-only'], -]); +}); it('allows what is already allowed without asking or writing', function (): void { - $this->store->add('shop-a', 'fake-secret-a', write: false); + $this->store->add('shop-a', 'fake-secret-a'); $before = file_get_contents($this->store->path()); - $this->artisan('merchants:access', ['name' => 'shop-a', '--read' => true, '--no-interaction' => true]) - ->expectsOutputToContain('Access for shop-a: read-only')->assertExitCode(0); + $this->artisan('merchants:access', ['name' => 'shop-a', '--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('still applies a requested block when allowing is declined', function (): void { - $this->store->add('shop-a', 'fake-secret-a', read: false); - $this->artisan('merchants:access', ['name' => 'shop-a', '--read' => true, '--no-write' => true]) - ->expectsConfirmation('Allow read requests for shop-a?', 'no') - ->expectsOutputToContain('Read requests stay blocked.') - ->expectsOutputToContain('Access for shop-a: reads and writes blocked')->assertExitCode(0); - expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-secret-a', 'read' => false, 'write' => false]); +it('allows writes again only after an interactive confirmation', function (): void { + $this->store->add('shop-a', 'fake-secret-a', write: false); + $this->artisan('merchants:access', ['name' => 'shop-a', '--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', 'write' => true]); }); -it('allows blocked requests again only after an interactive confirmation', function (array $flags, string $question, array $saved): void { - $this->store->add('shop-a', 'fake-secret-a', read: false, write: false); - $this->artisan('merchants:access', ['name' => 'shop-a', ...$flags]) - ->expectsConfirmation($question, 'yes')->assertExitCode(0); - expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-secret-a', ...$saved]); -})->with([ - 'writes' => [['--write' => true], 'Allow write requests for shop-a?', ['read' => false, 'write' => true]], - 'both' => [['--read' => true, '--write' => true], 'Allow read and write requests for shop-a?', ['read' => true, 'write' => true]], - 'reads while blocking writes' => [['--read' => true, '--no-write' => true], 'Allow read requests for shop-a?', ['read' => true, 'write' => false]], -]); +it('has no option to block reads', function (string $command): void { + expect(Artisan::all()[$command]->getDefinition()->hasOption('read'))->toBeFalse() + ->and(Artisan::all()[$command]->getDefinition()->hasNegation('no-read'))->toBeFalse(); +})->with(['merchants:access', 'merchants:add']); it('leaves access unchanged when the confirmation is declined', function (): void { $this->store->add('shop-a', 'fake-secret-a', write: false); diff --git a/tests/Feature/Console/AuthenticatedCommandTest.php b/tests/Feature/Console/AuthenticatedCommandTest.php index 7ea2eee..16eb54e 100644 --- a/tests/Feature/Console/AuthenticatedCommandTest.php +++ b/tests/Feature/Console/AuthenticatedCommandTest.php @@ -216,7 +216,7 @@ public function run(?string $paymentId, ?string $orderId, CallbackTarget $target $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("does not allow write requests, so the {$method} request was not sent") + ->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([ @@ -248,32 +248,6 @@ public function run(?string $paymentId, ?string $orderId, CallbackTarget $target '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('blocks reads for a write-only merchant without retrying', function (string $command, array $arguments): void { - $this->store->add('shop-w', 'fake-secret-w', read: false); - Http::fake(); - $this->artisan($command, [...$arguments, '--merchant' => 'shop-w']) - ->expectsOutputToContain('does not allow read requests') - ->doesntExpectOutputToContain('Watching')->assertExitCode(1); - Http::assertNothingSent(); -})->with([ - 'get' => ['payments:get', ['id' => '42']], - 'list' => ['payments:list', []], - 'raw GET' => ['api', ['method' => 'GET', 'path' => '/payments/42']], - 'capture inspects the payment first' => ['payments:capture', ['id' => '42', 'amount' => '1250', '--yes' => true]], - 'replay' => ['callbacks:replay', ['payment-id' => '42', '--to' => 'http://localhost/callback']], - 'scoped watch' => ['callbacks:watch', ['payment-id' => '42', '--to' => 'http://localhost/callback']], - 'account-wide watch' => ['callbacks:watch', ['--to' => 'http://localhost/callback']], -]); - -it('still writes through a write-only merchant', function (): void { - $this->store->add('shop-w', 'fake-secret-w', read: false); - Http::fake(['https://api.quickpay.net/payments' => Http::response('{"id":42}')]); - $this->artisan('payments:create', ['order-id' => 'order-42', '--merchant' => 'shop-w', '--json' => true])->assertExitCode(0); - Http::assertSentCount(1); - Http::assertSent(fn (Request $request): bool => $request->method() === 'POST' - && $request->header('Authorization') === ['Basic '.base64_encode(':fake-secret-w')]); -}); - 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' => []]), diff --git a/tests/Feature/Quickpay/QuickpayClientTest.php b/tests/Feature/Quickpay/QuickpayClientTest.php index 22cdb55..9f6f0e9 100644 --- a/tests/Feature/Quickpay/QuickpayClientTest.php +++ b/tests/Feature/Quickpay/QuickpayClientTest.php @@ -108,49 +108,26 @@ } }); -it('sends nothing when merchant access blocks the method', function (bool $read, bool $write, string $method, string $kind): void { +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($read, $write)); + $client = new QuickpayClient(app(Factory::class), 'test-secret', new MerchantAccess(false)); expect(fn () => $client->raw($method, '/payments/42', data: ['amount' => 1000])) - ->toThrow(MerchantAccessException::class, "does not allow {$kind} requests, so the ".strtoupper($method).' request was not sent.'); + ->toThrow(MerchantAccessException::class, 'is read-only, so the '.strtoupper($method).' request was not sent.'); Http::assertNothingSent(); -})->with([ - 'read-only POST' => [true, false, 'POST', 'write'], - 'read-only PUT' => [true, false, 'PUT', 'write'], - 'read-only PATCH' => [true, false, 'PATCH', 'write'], - 'read-only DELETE' => [true, false, 'delete', 'write'], - 'write-only GET' => [false, true, 'GET', 'read'], - 'no access GET' => [false, false, 'GET', 'read'], - 'no access POST' => [false, false, 'POST', 'write'], -]); - -it('applies merchant access to first-class requests', function (): void { +})->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(true, false)); - $writeOnly = new QuickpayClient(app(Factory::class), 'test-secret', new MerchantAccess(false, true)); + $readOnly = new QuickpayClient(app(Factory::class), 'test-secret', new MerchantAccess(false)); 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) - ->and($writeOnly->post('/payments')->successful())->toBeTrue() - ->and(fn () => $writeOnly->get('/payments/42'))->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('POST'); -}); - -it('checks credentials with ping even when merchant access blocks every request', function (): void { - Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); - $client = new QuickpayClient(app(Factory::class), 'test-secret', new MerchantAccess(false, false)); - - expect($client->ping()->successful())->toBeTrue() - ->and(fn () => $client->get('/ping'))->toThrow(MerchantAccessException::class) - ->and(fn () => $client->raw('GET', '/ping'))->toThrow(MerchantAccessException::class); - Http::assertSentCount(1); - Http::assertSent(fn (Request $request): bool => $request->method() === 'GET' - && $request->url() === 'https://api.quickpay.net/ping' - && $request->header('Authorization') === ['Basic '.base64_encode(':test-secret')]); + ->and(Http::recorded()[1][0]->method())->toBe('GET'); }); it('never treats blocked access as a retryable request failure', function (): void { diff --git a/tests/Integration/Credentials/MerchantStoreTest.php b/tests/Integration/Credentials/MerchantStoreTest.php index 2b0529c..adcbbe8 100644 --- a/tests/Integration/Credentials/MerchantStoreTest.php +++ b/tests/Integration/Credentials/MerchantStoreTest.php @@ -25,7 +25,7 @@ $store->add('shop-b', 'fake-secret-b'); expect($store->read())->toBe([ 'default_merchant' => 'shop-a', - 'merchants' => ['shop-a' => ['api_key' => 'fake-secret-a', 'read' => true, 'write' => true], 'shop-b' => ['api_key' => 'fake-secret-b', 'read' => true, 'write' => true]], + 'merchants' => ['shop-a' => ['api_key' => 'fake-secret-a', 'write' => true], 'shop-b' => ['api_key' => 'fake-secret-b', 'write' => true]], ]); }); @@ -62,7 +62,7 @@ $store->add('shop-b', ' fake-replacement ', true); expect($store->read())->toBe([ 'default_merchant' => 'shop-a', - 'merchants' => ['shop-a' => ['api_key' => 'fake-secret-a', 'read' => true, 'write' => true], 'shop-b' => ['api_key' => 'fake-replacement', 'read' => true, 'write' => true]], + 'merchants' => ['shop-a' => ['api_key' => 'fake-secret-a', 'write' => true], 'shop-b' => ['api_key' => 'fake-replacement', 'write' => true]], ]); }); @@ -100,65 +100,61 @@ })->with([ 'broken' => '{broken', 'root list' => '[]', 'missing' => '{}', 'merchant list' => '{"default_merchant":null,"merchants":[]}', - 'numeric key' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":123,"read":true,"write":true}}}', - 'empty key' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":" ","read":true,"write":true}}}', - 'invalid name' => '{"default_merchant":null,"merchants":{"../a":{"api_key":"fake-key","read":true,"write":true}}}', + 'numeric key' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":123,"write":true}}}', + 'empty key' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":" ","write":true}}}', + 'invalid name' => '{"default_merchant":null,"merchants":{"../a":{"api_key":"fake-key","write":true}}}', '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":true,"write":true}}}', - 'duplicate merchant' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","read":true,"write":true},"shop-a":{"api_key":"fake-last","read":true,"write":true}}}', - 'escaped duplicate merchant' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","read":true,"write":true},"sh\\u006fp-a":{"api_key":"fake-last","read":true,"write":true}}}', - 'duplicate key' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","api_key":"fake-last","read":true,"write":true}}}', - 'duplicate default' => '{"default_merchant":"shop-a","default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-first","read":true,"write":true}}}', - 'missing access flags' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key"}}}', - 'missing write flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","read":true}}}', - 'string access flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","read":"true","write":true}}}', - 'null access flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","read":true,"write":null}}}', - 'extra merchant field' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","read":true,"write":true,"note":"x"}}}', - 'duplicate access flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","write":false,"read":true,"write":true}}}', + 'secret label' => '{"default_merchant":null,"merchants":{"secret-name":{"api_key":"secret","write":true}}}', + 'duplicate merchant' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","write":true},"shop-a":{"api_key":"fake-last","write":true}}}', + 'escaped duplicate merchant' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","write":true},"sh\\u006fp-a":{"api_key":"fake-last","write":true}}}', + 'duplicate key' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","api_key":"fake-last","write":true}}}', + 'duplicate default' => '{"default_merchant":"shop-a","default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-first","write":true}}}', + 'missing write flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key"}}}', + 'string write flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","write":"true"}}}', + 'read flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","read":true,"write":true}}}', + 'null write flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","write":null}}}', + 'extra merchant field' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","write":true,"note":"x"}}}', + 'duplicate write flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","write":false,"write":true}}}', ]); -it('explains missing access flags without revealing the credential', function (): void { +it('explains a missing write 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, 'read and write access flags'); + ->toThrow(CredentialException::class, 'a true or false write flag'); }); -it('saves access flags for a new merchant and defaults to full access', function (): void { +it('saves the write 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', write: false); - $store->add('shop-c', 'fake-secret-c', read: false); expect($store->read()['merchants'])->toBe([ - 'shop-a' => ['api_key' => 'fake-secret-a', 'read' => true, 'write' => true], - 'shop-b' => ['api_key' => 'fake-secret-b', 'read' => true, 'write' => false], - 'shop-c' => ['api_key' => 'fake-secret-c', 'read' => false, 'write' => true], + 'shop-a' => ['api_key' => 'fake-secret-a', 'write' => true], + 'shop-b' => ['api_key' => 'fake-secret-b', 'write' => false], ]); }); -it('keeps access flags when replacing a credential unless new flags are given', function (): void { +it('keeps the write flag when replacing a credential unless a new one is given', function (): void { $store = new MerchantStore($this->path); $store->add('shop-a', 'fake-original', write: false); $store->add('shop-a', 'fake-replacement', true); - expect($store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'read' => true, 'write' => false]); - $store->add('shop-a', 'fake-second', true, read: false); - expect($store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-second', 'read' => false, 'write' => false]); + expect($store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'write' => false]); + $store->add('shop-a', 'fake-second', true, write: true); + expect($store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-second', 'write' => true]); }); -it('changes only the given access flags and keeps the credential', function (): void { +it('changes only the write 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'); - $access = $store->changeAccess('shop-a', write: false); - expect([$access->read, $access->write])->toBe([true, false]); - $access = $store->changeAccess('shop-a', read: false); - expect([$access->read, $access->write])->toBe([false, false]) + expect($store->changeAccess('shop-a', true)->write)->toBeTrue() + ->and($store->changeAccess('shop-a', false)->write)->toBeFalse() ->and($store->read())->toBe([ 'default_merchant' => 'shop-a', 'merchants' => [ - 'shop-a' => ['api_key' => 'fake-secret-a', 'read' => false, 'write' => false], - 'shop-b' => ['api_key' => 'fake-secret-b', 'read' => true, 'write' => true], + 'shop-a' => ['api_key' => 'fake-secret-a', 'write' => false], + 'shop-b' => ['api_key' => 'fake-secret-b', 'write' => true], ], ]); }); @@ -279,7 +275,7 @@ $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":true,"write":true}}}'); + file_put_contents($this->path.'.replacement', '{"default_merchant":"shop-c","merchants":{"shop-c":{"api_key":"fake-secret-c","write":true}}}'); rename($this->path.'.replacement', $this->path); flock($lock, LOCK_UN); expect(fgets($pipes[1]))->toBe("done\n") diff --git a/tests/Unit/Credentials/MerchantAccessTest.php b/tests/Unit/Credentials/MerchantAccessTest.php index 1a755ee..541d614 100644 --- a/tests/Unit/Credentials/MerchantAccessTest.php +++ b/tests/Unit/Credentials/MerchantAccessTest.php @@ -2,36 +2,28 @@ use App\Credentials\MerchantAccess; -it('treats GET as a read and every other method as a write', function (bool $read, bool $write, string $method, bool $allowed): void { - expect((new MerchantAccess($read, $write))->allows($method))->toBe($allowed); +it('always allows GET and blocks every other method for a read-only merchant', function (bool $write, string $method, bool $allowed): void { + expect((new MerchantAccess($write))->allows($method))->toBe($allowed); })->with([ - 'read-only GET' => [true, false, 'GET', true], - 'read-only lowercase get' => [true, false, 'get', true], - 'read-only POST' => [true, false, 'POST', false], - 'read-only PUT' => [true, false, 'put', false], - 'read-only PATCH' => [true, false, 'PATCH', false], - 'read-only DELETE' => [true, false, 'DELETE', false], - 'read-only unknown method' => [true, false, 'OPTIONS', false], - 'write-only GET' => [false, true, 'GET', false], - 'write-only POST' => [false, true, 'POST', true], - 'write-only DELETE' => [false, true, 'DELETE', true], - 'no access GET' => [false, false, 'GET', false], - 'no access POST' => [false, false, 'POST', false], - 'full GET' => [true, true, 'GET', true], - 'full PUT' => [true, true, 'PUT', true], + 'read-only GET' => [false, 'GET', true], + 'read-only lowercase get' => [false, 'get', true], + 'read-only POST' => [false, 'POST', false], + 'read-only PUT' => [false, 'put', false], + 'read-only PATCH' => [false, 'PATCH', false], + 'read-only DELETE' => [false, 'DELETE', false], + 'read-only unknown method' => [false, 'OPTIONS', false], + 'full GET' => [true, 'GET', true], + 'full PUT' => [true, 'PUT', true], + 'full DELETE' => [true, 'DELETE', true], ]); -it('names each access combination', function (bool $read, bool $write, string $label, bool $full): void { - $access = new MerchantAccess($read, $write); - expect($access->label())->toBe($label)->and($access->isFull())->toBe($full); +it('names the access', function (bool $write, string $label): void { + expect((new MerchantAccess($write))->label())->toBe($label); })->with([ - 'full' => [true, true, 'read and write', true], - 'read-only' => [true, false, 'read-only', false], - 'write-only' => [false, true, 'write-only', false], - 'none' => [false, false, 'reads and writes blocked', false], + 'full' => [true, 'read and write'], + 'read-only' => [false, 'read-only'], ]); -it('grants full access by default only through the named constructor', function (): void { - $access = MerchantAccess::full(); - expect([$access->read, $access->write])->toBe([true, true]); +it('grants full access through the named constructor', function (): void { + expect(MerchantAccess::full()->write)->toBeTrue(); }); From e76cf73882c73f265ab6647275979e168c220a84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Mon, 23 Nov 2026 18:32:56 +0100 Subject: [PATCH 14/16] refactor: name merchant write protection read-only --no-write came from Symfony's negation of a write option, which is not what anyone looks for. The protection now uses the common read-only name. - merchants:add --read-only and merchants:access --read-only make a merchant read-only. - merchants:access --read-write allows writes again after a confirmation in an interactive terminal; giving both flags fails. - merchants:add --replace keeps a read-only merchant read-only, so merchants:access is the only way to allow writes again. - The saved config and the JSON output use read_only. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 6 +- CHANGELOG.md | 2 +- README.md | 13 ++-- SECURITY.md | 8 +- .../Merchants/ActiveMerchantCommand.php | 4 +- app/Commands/Merchants/AddMerchantCommand.php | 30 +------- .../Merchants/ListMerchantsCommand.php | 6 +- .../Merchants/SetMerchantAccessCommand.php | 30 ++++---- app/Credentials/ApiKeyResolver.php | 2 +- app/Credentials/MerchantAccess.php | 10 +-- app/Credentials/MerchantStore.php | 32 ++++---- skills/quickpay-cli/SKILL.md | 12 +-- .../Merchants/ActiveMerchantCommandTest.php | 14 ++-- .../Merchants/AddMerchantCommandTest.php | 40 +++------- .../Merchants/ListMerchantsCommandTest.php | 10 +-- .../Merchants/RemoveMerchantCommandTest.php | 2 +- .../SetMerchantAccessCommandTest.php | 44 +++++++---- .../Console/AuthenticatedCommandTest.php | 4 +- tests/Feature/Quickpay/QuickpayClientTest.php | 4 +- .../Credentials/MerchantStoreTest.php | 75 ++++++++++--------- tests/Unit/Credentials/MerchantAccessTest.php | 34 ++++----- 21 files changed, 180 insertions(+), 202 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 61ccd46..53efbac 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -81,10 +81,10 @@ validation, and the locked-dependency audit. 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 `write` flag that `QuickpayClient` enforces before +- 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. Allowing writes needs an interactive - terminal; `QUICKPAY_API_KEY` has full access. + confirm before mutating check it first. Only `merchants:access --read-write` + lifts it, in an interactive terminal; `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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 19ae501..64509e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - 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 --no-write` or `merchants:access --no-write` blocks every request except `GET` before anything is sent, and `merchants:access --write` allows writes again after a confirmation. +- 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. diff --git a/README.md b/README.md index 3b0f704..19c5c3c 100644 --- a/README.md +++ b/README.md @@ -65,14 +65,15 @@ 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 merchants:add "My Website" --no-write -quickpay merchants:access "My Website" --no-write -quickpay merchants:access "My Website" --write +quickpay merchants:add "My Website" --read-only +quickpay merchants:access "My Website" --read-only +quickpay merchants:access "My Website" --read-write ``` -A blocked request stops before anything reaches Quickpay. Allowing writes again, -with `merchants:access` or `merchants:add --replace`, asks you to confirm in an -interactive terminal, so a script or agent can't lift the protection on its own. +A blocked request stops before anything reaches Quickpay. Replacing the key with +`merchants:add --replace` keeps the merchant read-only. `--read-write` asks you to +confirm in an interactive terminal, so a script or agent can't lift the +protection on its own. A key in `QUICKPAY_API_KEY` always has full access. ## Payments diff --git a/SECURITY.md b/SECURITY.md index 01eb993..b3c6868 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -56,12 +56,12 @@ 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 `write` flag. For a read-only merchant, +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; allowing -writes again, with `merchants:access` or `merchants:add --replace`, needs an -interactive terminal and a confirmation. A key from `QUICKPAY_API_KEY` has full +asking for confirmation. Making a merchant read-only works anywhere, and +`merchants:add --replace` keeps it read-only. Only `merchants:access --read-write` +allows writes again, and it needs an interactive terminal and a confirmation. A key from `QUICKPAY_API_KEY` has full access. The flag is a local guardrail, not a Quickpay permission: anyone who can edit the configuration file can change it. diff --git a/app/Commands/Merchants/ActiveMerchantCommand.php b/app/Commands/Merchants/ActiveMerchantCommand.php index 385e7e5..8efb851 100644 --- a/app/Commands/Merchants/ActiveMerchantCommand.php +++ b/app/Commands/Merchants/ActiveMerchantCommand.php @@ -37,7 +37,7 @@ public function handle(ApiKeyResolver $resolver, MerchantAuthenticationCheck $ch 'selection_source' => $key?->selectionSource(), 'credential_source' => $key?->source(), 'configured' => $key !== null, - 'write' => $key?->access()->write, + 'read_only' => $key?->access()->readOnly, 'checked' => $checkRequested, 'authenticated' => $authenticated, 'api_base_url' => QuickpayClient::BASE_URL, @@ -51,7 +51,7 @@ public function handle(ApiKeyResolver $resolver, MerchantAuthenticationCheck $ch $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()->write) { + if ($key !== null && $key->access()->readOnly) { $this->line('Access: '.$key->access()->label()); } $this->line('Credentials configured: '.($status['configured'] ? 'yes' : 'no')); diff --git a/app/Commands/Merchants/AddMerchantCommand.php b/app/Commands/Merchants/AddMerchantCommand.php index c677f26..6f13d66 100644 --- a/app/Commands/Merchants/AddMerchantCommand.php +++ b/app/Commands/Merchants/AddMerchantCommand.php @@ -12,23 +12,17 @@ use App\Credentials\MerchantStore; use App\Quickpay\Exceptions\QuickpayRequestException; use App\Quickpay\MerchantAuthenticationCheck; -use Symfony\Component\Console\Input\InputOption; use UnexpectedValueException; class AddMerchantCommand extends BaseCommand { protected $signature = 'merchants:add {name : Local merchant name, for example "My Website"} - {--replace : Replace this saved merchant credential after validation}'; + {--replace : Replace this saved merchant credential after validation} + {--read-only : Block write requests (POST, PUT, PATCH, DELETE). --replace keeps a read-only merchant read-only}'; protected $description = 'Validate and save API access to an existing Quickpay merchant'; - public function __construct() - { - parent::__construct(); - $this->addOption('write', null, InputOption::VALUE_NEGATABLE, 'Allow write requests (POST, PUT, PATCH, DELETE). Allowed by default; --replace keeps the saved setting'); - } - public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, StdinTerminalDetector $terminal): int { $credential = null; @@ -50,22 +44,6 @@ public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, return $this->failure('Adding a merchant requires an interactive terminal. Use QUICKPAY_API_KEY for automation.'); } - $write = $this->option('write'); - $write = is_bool($write) ? $write : null; - $lifting = false; - if ($saved && $write === true) { - // A replacement keeps the saved flag, so making a read-only - // merchant writable asks first, the same way merchants:access does. - // Allowing what is already allowed is dropped rather than saved. - $lifting = ! $config['merchants'][$name]['write']; - $write = $lifting ? true : null; - if ($lifting && ! $this->confirm('Allow write requests for '.$name.'?', false)) { - $this->line('Cancelled.'); - - return self::SUCCESS; - } - } - $answer = $this->secret('API key'); $apiKey = is_string($answer) ? trim($answer) : ''; @@ -79,9 +57,9 @@ public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, } $check->check($credential); - $access = $store->add($name, $apiKey, (bool) $this->option('replace'), $write); + $access = $store->add($name, $apiKey, (bool) $this->option('replace'), (bool) $this->option('read-only')); $this->info('Merchant saved: '.$name); - if (! $access->write || $lifting) { + if ($access->readOnly) { $this->line('Access: '.$access->label()); } diff --git a/app/Commands/Merchants/ListMerchantsCommand.php b/app/Commands/Merchants/ListMerchantsCommand.php index 185f59c..56881e1 100644 --- a/app/Commands/Merchants/ListMerchantsCommand.php +++ b/app/Commands/Merchants/ListMerchantsCommand.php @@ -27,7 +27,7 @@ public function handle(MerchantStore $store): int $rows = array_map(fn (string $name): array => [ 'name' => $name, 'default' => $config['default_merchant'] === $name, - 'write' => $config['merchants'][$name]['write'], + 'read_only' => $config['merchants'][$name]['read_only'], ], $names); if ($this->option('json')) { @@ -36,13 +36,13 @@ public function handle(MerchantStore $store): int $this->line('No saved merchants. Run quickpay merchants:add first.'); } else { // Access is shown only when a merchant is read-only. - $showAccess = in_array(false, array_column($rows, 'write'), true); + $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['write'] ? '' : (new MerchantAccess(false))->label()] : []), + ...($showAccess ? [$row['read_only'] ? (new MerchantAccess(readOnly: true))->label() : ''] : []), ], $rows), ); } diff --git a/app/Commands/Merchants/SetMerchantAccessCommand.php b/app/Commands/Merchants/SetMerchantAccessCommand.php index 834e9f6..265e7df 100644 --- a/app/Commands/Merchants/SetMerchantAccessCommand.php +++ b/app/Commands/Merchants/SetMerchantAccessCommand.php @@ -8,35 +8,35 @@ use App\Credentials\MerchantAccess; use App\Credentials\MerchantName; use App\Credentials\MerchantStore; -use Symfony\Component\Console\Input\InputOption; class SetMerchantAccessCommand extends BaseCommand { protected $signature = 'merchants:access - {name : Saved merchant name}'; + {name : Saved merchant name} + {--read-only : Block write requests (POST, PUT, PATCH, DELETE)} + {--read-write : Allow write requests again. Needs an interactive terminal}'; - protected $description = 'Show or change whether a saved merchant may send write requests'; - - public function __construct() - { - parent::__construct(); - $this->addOption('write', null, InputOption::VALUE_NEGATABLE, 'Allow write requests (POST, PUT, PATCH, DELETE); --no-write makes the merchant read-only. Allowing needs an interactive terminal'); - } + protected $description = 'Show or change whether a saved merchant is read-only'; public function handle(MerchantStore $store, StdinTerminalDetector $terminal): int { try { $name = MerchantName::validate((string) $this->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]['write']); - $write = $this->option('write'); + $current = new MerchantAccess($config['merchants'][$name]['read_only']); // Allowing what is already allowed changes nothing, so it is not - // saved and cannot undo a block saved in the meantime. - if (! is_bool($write) || ($write && $current->write)) { + // saved and cannot undo a protection saved in the meantime. + if (! $readOnly && (! $readWrite || ! $current->readOnly)) { $this->line($this->summary($name, $current)); return self::SUCCESS; @@ -44,7 +44,7 @@ public function handle(MerchantStore $store, StdinTerminalDetector $terminal): i // Making a merchant read-only is always safe. Allowing writes again // needs a person at the keyboard, so an automated caller cannot. - if ($write) { + if ($readWrite) { if (! $this->input->isInteractive() || ! $terminal->isTty()) { return $this->failure('Allowing write requests requires an interactive terminal.'); } @@ -56,7 +56,7 @@ public function handle(MerchantStore $store, StdinTerminalDetector $terminal): i } } - $this->info($this->summary($name, $store->changeAccess($name, $write))); + $this->info($this->summary($name, $store->changeAccess($name, $readOnly))); return self::SUCCESS; } catch (CredentialException $exception) { diff --git a/app/Credentials/ApiKeyResolver.php b/app/Credentials/ApiKeyResolver.php index 3541429..0892738 100644 --- a/app/Credentials/ApiKeyResolver.php +++ b/app/Credentials/ApiKeyResolver.php @@ -53,6 +53,6 @@ public function resolve(?string $merchant = null): ?ApiKey $saved = $config['merchants'][$name]; - return new ApiKey($saved['api_key'], 'config file', new MerchantAccess($saved['write']), $name, $source); + return new ApiKey($saved['api_key'], 'config file', new MerchantAccess($saved['read_only']), $name, $source); } } diff --git a/app/Credentials/MerchantAccess.php b/app/Credentials/MerchantAccess.php index 8c1811f..e9641bf 100644 --- a/app/Credentials/MerchantAccess.php +++ b/app/Credentials/MerchantAccess.php @@ -3,7 +3,7 @@ namespace App\Credentials; /** - * Whether a saved merchant may send write requests. + * Whether a saved merchant is read-only. * * GET is a read and always allowed. Every other method is a write, so an * unknown or future method is blocked for a read-only merchant instead of @@ -12,21 +12,21 @@ final readonly class MerchantAccess { public function __construct( - public bool $write, + public bool $readOnly, ) {} public static function full(): self { - return new self(true); + return new self(readOnly: false); } public function allows(string $method): bool { - return strtoupper($method) === 'GET' || $this->write; + return strtoupper($method) === 'GET' || ! $this->readOnly; } public function label(): string { - return $this->write ? 'read and write' : 'read-only'; + return $this->readOnly ? 'read-only' : 'read and write'; } } diff --git a/app/Credentials/MerchantStore.php b/app/Credentials/MerchantStore.php index d02557d..ddf4fb0 100644 --- a/app/Credentials/MerchantStore.php +++ b/app/Credentials/MerchantStore.php @@ -9,7 +9,7 @@ use stdClass; /** - * @phpstan-type SavedMerchant array{api_key: string, write: bool} + * @phpstan-type SavedMerchant array{api_key: string, read_only: bool} * @phpstan-type MerchantConfig array{default_merchant: ?string, merchants: array} */ final readonly class MerchantStore @@ -81,10 +81,10 @@ public function read(): array || 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->write ?? null)) { - throw new CredentialException('Quickpay CLI merchant configuration needs exactly an API key and a true or false write flag for each merchant.'); + 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, 'write' => $merchant->write]; + $merchants[$name] = ['api_key' => $merchant->api_key, 'read_only' => $merchant->read_only]; } $this->validateLabels($merchants); @@ -96,11 +96,11 @@ public function read(): array } /** - * Saves a credential and returns the access it was saved with. A null flag - * keeps the replaced merchant's flag, or allows that kind of request for a - * new merchant. + * 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 $write = null): MerchantAccess + public function add(string $name, string $apiKey, bool $replace = false, bool $readOnly = false): MerchantAccess { MerchantName::validate($name); $apiKey = trim($apiKey); @@ -108,7 +108,7 @@ public function add(string $name, string $apiKey, bool $replace = false, ?bool $ throw new CredentialException('API key cannot be empty.'); } $access = null; - $this->mutate(function (array $config) use ($name, $apiKey, $replace, $write, &$access): array { + $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.'); } @@ -119,8 +119,8 @@ public function add(string $name, string $apiKey, bool $replace = false, ?bool $ $config['default_merchant'] = $name; } $existing = $config['merchants'][$name] ?? null; - $access = new MerchantAccess($write ?? $existing['write'] ?? true); - $config['merchants'][$name] = ['api_key' => $apiKey, 'write' => $access->write]; + $access = new MerchantAccess($readOnly || ($existing['read_only'] ?? false)); + $config['merchants'][$name] = ['api_key' => $apiKey, 'read_only' => $access->readOnly]; $this->validateLabels($config['merchants']); return $config; @@ -140,15 +140,15 @@ public function select(string $name): void }); } - /** Sets the write flag under the store lock. */ - public function changeAccess(string $name, bool $write): MerchantAccess + /** 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, $write, &$access): array { + $this->mutate(function (array $config) use ($name, $readOnly, &$access): array { $this->requireMerchant($config, $name); - $access = new MerchantAccess($write); - $config['merchants'][$name] = [...$config['merchants'][$name], 'write' => $write]; + $access = new MerchantAccess($readOnly); + $config['merchants'][$name] = [...$config['merchants'][$name], 'read_only' => $readOnly]; return $config; }); diff --git a/skills/quickpay-cli/SKILL.md b/skills/quickpay-cli/SKILL.md index 1e4fc17..8cb58b3 100644 --- a/skills/quickpay-cli/SKILL.md +++ b/skills/quickpay-cli/SKILL.md @@ -51,12 +51,12 @@ 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 `write`. A +(`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 --write`, re-adding the merchant, editing configuration files, +`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 `--no-write` only when the user asks. +read-only with `--read-only` only when the user asks. ## Safety workflow @@ -81,8 +81,8 @@ For a refund or cancellation, use the same inspect → verify → explicit autho ```text quickpay about -quickpay merchants:add [--replace] [--no-write] -quickpay merchants:access [--write|--no-write] +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] @@ -172,5 +172,5 @@ Do not use full URLs, hosts, schemes, `..`, backslashes, or fragments. The CLI o - A raw `GET` needs no `--yes`; a raw `POST`, `PUT`, `PATCH`, or `DELETE` does. - `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 `write` in `merchants:active --merchant= --json` before planning a mutation. +- 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/Feature/Commands/Merchants/ActiveMerchantCommandTest.php b/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php index 557096a..8c8e6d3 100644 --- a/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/ActiveMerchantCommandTest.php @@ -18,7 +18,7 @@ [$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, 'write' => true, 'checked' => false, 'authenticated' => null, + '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); @@ -50,7 +50,7 @@ $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['write'])->toBeTrue(); + ->and($data['read_only'])->toBeFalse(); Http::assertNothingSent(); }); @@ -82,7 +82,7 @@ $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","write":true},"sh\\u006fp-a":{"api_key":"fake-last","write":true}}}'; + : '{"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]); @@ -93,17 +93,17 @@ 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', write: false); + $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['write'])->toBeFalse() + 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 write flag when no credential is configured', function (): void { +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('read')->and($data['write'])->toBeNull(); + 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 index 4a3035c..829d9cf 100644 --- a/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php @@ -104,7 +104,7 @@ public function isTty(): bool expect(file_exists($this->store->path()))->toBeFalse(); }); -it('saves the write flag given when adding a merchant', function (array $flags, array $saved, ?string $label): void { +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'); @@ -113,43 +113,23 @@ public function isTty(): bool expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-secret-a', ...$saved]); Http::assertSentCount(1); })->with([ - 'default' => [[], ['write' => true], null], - 'read-only' => [['--no-write' => true], ['write' => false], 'read-only'], + 'default' => [[], ['read_only' => false], null], + 'read-only' => [['--read-only' => true], ['read_only' => true], 'read-only'], ]); -it('keeps the write flag when replacing a credential', function (): void { +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', write: false); + $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', 'write' => false]); + expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'read_only' => true]); }); -it('asks before a replacement makes a read-only merchant writable', function (): void { - Http::fake(['https://api.quickpay.net/ping' => Http::response(['scope' => 'merchant'])]); - $this->store->add('shop-a', 'fake-original', write: false); - $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true, '--write' => true]) - ->expectsConfirmation('Allow write requests for shop-a?', 'yes') - ->expectsQuestion('API key', 'fake-replacement') - ->expectsOutputToContain('Access: read and write')->assertExitCode(0); - expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'write' => true]); -}); - -it('keeps the saved merchant when allowing writes is declined', function (): void { - $this->store->add('shop-a', 'fake-original', write: false); - $before = file_get_contents($this->store->path()); - $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true, '--write' => true]) - ->expectsConfirmation('Allow write requests for shop-a?', 'no') - ->expectsOutputToContain('Cancelled.')->assertExitCode(0); - expect(file_get_contents($this->store->path()))->toBe($before); - Http::assertNothingSent(); -}); - -it('does not ask when a replacement allows what is already allowed', function (): void { +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, '--write' => true]) + $this->artisan('merchants:add', ['name' => 'shop-a', '--replace' => true, '--read-only' => true]) ->expectsQuestion('API key', 'fake-replacement') - ->doesntExpectOutputToContain('Access:')->assertExitCode(0); - expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-replacement', 'write' => true]); + ->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 index d1af1b5..14ac053 100644 --- a/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php +++ b/tests/Feature/Commands/Merchants/ListMerchantsCommandTest.php @@ -8,7 +8,7 @@ $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, 'write' => true], ['name' => 'My Website', 'default' => true, 'write' => true]]); + ->toBe([['name' => 'My Other Website', 'default' => false, 'read_only' => false], ['name' => 'My Website', 'default' => true, 'read_only' => false]]); Http::assertNothingSent(); }); @@ -19,7 +19,7 @@ }); 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","write":true},"fake-secret-a":{"api_key":"fake-secret-b","write":true}}}'); + 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'); @@ -28,11 +28,11 @@ 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', write: false); + $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, 'write' => true], - ['name' => 'shop-b', 'default' => false, 'write' => false], + ['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') diff --git a/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php b/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php index 73d902e..9af8540 100644 --- a/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/RemoveMerchantCommandTest.php @@ -7,7 +7,7 @@ $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', 'write' => true]]]); + 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([]); diff --git a/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php b/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php index 5d3cd4c..c4a3cfa 100644 --- a/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php +++ b/tests/Feature/Commands/Merchants/SetMerchantAccessCommandTest.php @@ -6,37 +6,49 @@ it('makes a merchant read-only without an interactive terminal', function (): void { $this->store->add('shop-a', 'fake-secret-a'); - $this->artisan('merchants:access', ['name' => 'shop-a', '--no-write' => true, '--no-interaction' => true]) + $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', 'write' => false]); + 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', '--write' => true, '--no-interaction' => true]) + $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', write: false); - $this->artisan('merchants:access', ['name' => 'shop-a', '--write' => true]) + $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', 'write' => true]); + expect($this->store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-secret-a', 'read_only' => false]); }); -it('has no option to block reads', function (string $command): void { - expect(Artisan::all()[$command]->getDefinition()->hasOption('read'))->toBeFalse() - ->and(Artisan::all()[$command]->getDefinition()->hasNegation('no-read'))->toBeFalse(); -})->with(['merchants:access', 'merchants:add']); +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', write: 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', '--write' => true]) + $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); @@ -52,15 +64,15 @@ public function isTty(): bool } }); } - $this->store->add('shop-a', 'fake-secret-a', write: 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', '--write' => true, '--no-interaction' => ! $tty]) + $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', write: 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', '--no-interaction' => true]) ->expectsOutputToContain('Access for shop-a: read-only')->assertExitCode(0); @@ -70,7 +82,7 @@ public function isTty(): bool 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, '--no-write' => true])->assertExitCode(1); + $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/Console/AuthenticatedCommandTest.php b/tests/Feature/Console/AuthenticatedCommandTest.php index 16eb54e..fcede9c 100644 --- a/tests/Feature/Console/AuthenticatedCommandTest.php +++ b/tests/Feature/Console/AuthenticatedCommandTest.php @@ -209,7 +209,7 @@ public function run(?string $paymentId, ?string $orderId, CallbackTarget $target })->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', write: false); + $this->store->add('shop-r', 'fake-secret-r', readOnly: true); Http::fake(); $command = new $class; $command->setLaravel(app()); @@ -232,7 +232,7 @@ public function run(?string $paymentId, ?string $orderId, CallbackTarget $target ]); 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', write: false); + $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), diff --git a/tests/Feature/Quickpay/QuickpayClientTest.php b/tests/Feature/Quickpay/QuickpayClientTest.php index 9f6f0e9..613e30f 100644 --- a/tests/Feature/Quickpay/QuickpayClientTest.php +++ b/tests/Feature/Quickpay/QuickpayClientTest.php @@ -110,7 +110,7 @@ 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(false)); + $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.'); @@ -119,7 +119,7 @@ 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(false)); + $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() diff --git a/tests/Integration/Credentials/MerchantStoreTest.php b/tests/Integration/Credentials/MerchantStoreTest.php index adcbbe8..4eb08e0 100644 --- a/tests/Integration/Credentials/MerchantStoreTest.php +++ b/tests/Integration/Credentials/MerchantStoreTest.php @@ -25,7 +25,7 @@ $store->add('shop-b', 'fake-secret-b'); expect($store->read())->toBe([ 'default_merchant' => 'shop-a', - 'merchants' => ['shop-a' => ['api_key' => 'fake-secret-a', 'write' => true], 'shop-b' => ['api_key' => 'fake-secret-b', 'write' => true]], + 'merchants' => ['shop-a' => ['api_key' => 'fake-secret-a', 'read_only' => false], 'shop-b' => ['api_key' => 'fake-secret-b', 'read_only' => false]], ]); }); @@ -62,7 +62,7 @@ $store->add('shop-b', ' fake-replacement ', true); expect($store->read())->toBe([ 'default_merchant' => 'shop-a', - 'merchants' => ['shop-a' => ['api_key' => 'fake-secret-a', 'write' => true], 'shop-b' => ['api_key' => 'fake-replacement', 'write' => true]], + 'merchants' => ['shop-a' => ['api_key' => 'fake-secret-a', 'read_only' => false], 'shop-b' => ['api_key' => 'fake-replacement', 'read_only' => false]], ]); }); @@ -100,61 +100,68 @@ })->with([ 'broken' => '{broken', 'root list' => '[]', 'missing' => '{}', 'merchant list' => '{"default_merchant":null,"merchants":[]}', - 'numeric key' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":123,"write":true}}}', - 'empty key' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":" ","write":true}}}', - 'invalid name' => '{"default_merchant":null,"merchants":{"../a":{"api_key":"fake-key","write":true}}}', + '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","write":true}}}', - 'duplicate merchant' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","write":true},"shop-a":{"api_key":"fake-last","write":true}}}', - 'escaped duplicate merchant' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","write":true},"sh\\u006fp-a":{"api_key":"fake-last","write":true}}}', - 'duplicate key' => '{"default_merchant":"shop-a","merchants":{"shop-a":{"api_key":"fake-first","api_key":"fake-last","write":true}}}', - 'duplicate default' => '{"default_merchant":"shop-a","default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-first","write":true}}}', - 'missing write flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key"}}}', - 'string write flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","write":"true"}}}', - 'read flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","read":true,"write":true}}}', - 'null write flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","write":null}}}', - 'extra merchant field' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","write":true,"note":"x"}}}', - 'duplicate write flag' => '{"default_merchant":null,"merchants":{"shop-a":{"api_key":"fake-key","write":false,"write":true}}}', + '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 write flag without revealing the credential', function (): void { +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 write flag'); + ->toThrow(CredentialException::class, 'a true or false read_only flag'); }); -it('saves the write flag for a new merchant and defaults to full access', function (): void { +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', write: false); + $store->add('shop-b', 'fake-secret-b', readOnly: true); expect($store->read()['merchants'])->toBe([ - 'shop-a' => ['api_key' => 'fake-secret-a', 'write' => true], - 'shop-b' => ['api_key' => 'fake-secret-b', 'write' => false], + 'shop-a' => ['api_key' => 'fake-secret-a', 'read_only' => false], + 'shop-b' => ['api_key' => 'fake-secret-b', 'read_only' => true], ]); }); -it('keeps the write flag when replacing a credential unless a new one is given', function (): void { +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', write: false); + $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', 'write' => false]); - $store->add('shop-a', 'fake-second', true, write: true); - expect($store->read()['merchants']['shop-a'])->toBe(['api_key' => 'fake-second', 'write' => 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('changes only the write flag and keeps the credential', function (): void { +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', true)->write)->toBeTrue() - ->and($store->changeAccess('shop-a', false)->write)->toBeFalse() + 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', 'write' => false], - 'shop-b' => ['api_key' => 'fake-secret-b', 'write' => true], + 'shop-a' => ['api_key' => 'fake-secret-a', 'read_only' => true], + 'shop-b' => ['api_key' => 'fake-secret-b', 'read_only' => false], ], ]); }); @@ -163,7 +170,7 @@ $store = new MerchantStore($this->path); $store->add('shop-a', 'fake-secret-a'); $before = file_get_contents($this->path); - expect(fn () => $store->changeAccess($name, write: false))->toThrow(CredentialException::class); + 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']); @@ -275,7 +282,7 @@ $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","write":true}}}'); + 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") diff --git a/tests/Unit/Credentials/MerchantAccessTest.php b/tests/Unit/Credentials/MerchantAccessTest.php index 541d614..479310d 100644 --- a/tests/Unit/Credentials/MerchantAccessTest.php +++ b/tests/Unit/Credentials/MerchantAccessTest.php @@ -2,28 +2,28 @@ use App\Credentials\MerchantAccess; -it('always allows GET and blocks every other method for a read-only merchant', function (bool $write, string $method, bool $allowed): void { - expect((new MerchantAccess($write))->allows($method))->toBe($allowed); +it('always allows GET and blocks every other method for a read-only merchant', function (bool $readOnly, string $method, bool $allowed): void { + expect((new MerchantAccess($readOnly))->allows($method))->toBe($allowed); })->with([ - 'read-only GET' => [false, 'GET', true], - 'read-only lowercase get' => [false, 'get', true], - 'read-only POST' => [false, 'POST', false], - 'read-only PUT' => [false, 'put', false], - 'read-only PATCH' => [false, 'PATCH', false], - 'read-only DELETE' => [false, 'DELETE', false], - 'read-only unknown method' => [false, 'OPTIONS', false], - 'full GET' => [true, 'GET', true], - 'full PUT' => [true, 'PUT', true], - 'full DELETE' => [true, 'DELETE', true], + '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 $write, string $label): void { - expect((new MerchantAccess($write))->label())->toBe($label); +it('names the access', function (bool $readOnly, string $label): void { + expect((new MerchantAccess($readOnly))->label())->toBe($label); })->with([ - 'full' => [true, 'read and write'], - 'read-only' => [false, 'read-only'], + 'full' => [false, 'read and write'], + 'read-only' => [true, 'read-only'], ]); it('grants full access through the named constructor', function (): void { - expect(MerchantAccess::full()->write)->toBeTrue(); + expect(MerchantAccess::full()->readOnly)->toBeFalse(); }); From 45199a2e4779a8b7297c3e751a442965b5ed8947 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Mon, 23 Nov 2026 19:21:52 +0100 Subject: [PATCH 15/16] fix: guard merchant names, bindings and notices from review findings Applied by a code review run that was stopped before it reported its findings; every change passes the full test suite. - merchants:add refuses a name that differs from a saved one only in capitalization, in the command and under the store lock. - A symlinked .quickpay-cli.json owned by another user is refused, not only the file it points to. - merchants:add notes when QUICKPAY_API_KEY will still override saved merchants, and merchants:select says when a project binding still wins in the current folder. - Config errors say when a file repeats a property. - Docs cover re-adding a read-only merchant, what .quickpay-cli.json holds, and removing the old quickpay skill folder. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 ++- CHANGELOG.md | 2 +- README.md | 14 +++++++---- SECURITY.md | 10 ++++---- app/Commands/Merchants/AddMerchantCommand.php | 12 +++++++++- .../Merchants/SelectMerchantCommand.php | 20 ++++++++++++++++ app/Credentials/MerchantName.php | 19 +++++++++++++++ app/Credentials/MerchantStore.php | 6 ++++- app/Credentials/ProjectMerchantFile.php | 7 ++++-- .../Merchants/AddMerchantCommandTest.php | 16 ++++++++++++- .../Merchants/SelectMerchantCommandTest.php | 14 +++++++++++ .../Credentials/MerchantStoreTest.php | 10 ++++++++ .../Credentials/ProjectMerchantFileTest.php | 24 +++++++++++++++++++ tests/Unit/Credentials/MerchantNameTest.php | 9 +++++++ 14 files changed, 151 insertions(+), 15 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 53efbac..c38f675 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -84,7 +84,8 @@ validation, and the locked-dependency audit. - 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; `QUICKPAY_API_KEY` has full access. + 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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 64509e2..af2798d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Changed -- The bundled agent skill is renamed from `quickpay` to `quickpay-cli`. +- 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 diff --git a/README.md b/README.md index 19c5c3c..5305480 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,8 @@ 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. 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 @@ -71,10 +73,10 @@ quickpay merchants:access "My Website" --read-write ``` A blocked request stops before anything reaches Quickpay. Replacing the key with -`merchants:add --replace` keeps the merchant read-only. `--read-write` asks you to -confirm in an interactive terminal, so a script or agent can't lift the -protection on its own. -A key in `QUICKPAY_API_KEY` always has full access. +`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 a script or agent can't lift +the protection on its own. A key in `QUICKPAY_API_KEY` always has full access. ## Payments @@ -119,6 +121,10 @@ Install the bundled [quickpay-cli skill](skills/quickpay-cli/SKILL.md): skills add tehwave/quickpay-cli ``` +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. + ## Contributing See [CONTRIBUTING.md](CONTRIBUTING.md), [RELEASING.md](RELEASING.md), and diff --git a/SECURITY.md b/SECURITY.md index b3c6868..ac96dac 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -60,10 +60,12 @@ 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. Only `merchants:access --read-write` -allows writes again, and it needs an interactive terminal and a confirmation. A key from `QUICKPAY_API_KEY` has full -access. The flag is a local guardrail, not a Quickpay permission: anyone who can -edit the configuration file can change it. +`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: anyone who can edit the configuration file can change it. ## Local callback forwarding diff --git a/app/Commands/Merchants/AddMerchantCommand.php b/app/Commands/Merchants/AddMerchantCommand.php index 6f13d66..bbafe12 100644 --- a/app/Commands/Merchants/AddMerchantCommand.php +++ b/app/Commands/Merchants/AddMerchantCommand.php @@ -6,6 +6,7 @@ use App\Console\Output\ResponseBodySanitizer; use App\Console\Terminal\StdinTerminalDetector; use App\Credentials\ApiKey; +use App\Credentials\EnvironmentVariables; use App\Credentials\Exceptions\CredentialException; use App\Credentials\MerchantAccess; use App\Credentials\MerchantName; @@ -23,7 +24,7 @@ class AddMerchantCommand extends BaseCommand protected $description = 'Validate and save API access to an existing Quickpay merchant'; - public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, StdinTerminalDetector $terminal): int + public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, StdinTerminalDetector $terminal, EnvironmentVariables $environment): int { $credential = null; @@ -40,6 +41,11 @@ public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, 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.'); } @@ -63,6 +69,10 @@ public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, $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 saved merchants until you unset it.'); + } + $legacy = $store->leftoverLegacyCredential(); if ($legacy !== null) { $this->warn(ResponseBodySanitizer::terminalLine( diff --git a/app/Commands/Merchants/SelectMerchantCommand.php b/app/Commands/Merchants/SelectMerchantCommand.php index 7b4059f..8b68633 100644 --- a/app/Commands/Merchants/SelectMerchantCommand.php +++ b/app/Commands/Merchants/SelectMerchantCommand.php @@ -61,6 +61,7 @@ public function handle(MerchantStore $store, ProjectMerchantFile $project, Envir } else { $store->select($name); $this->info('Global default merchant selected: '.$name); + $this->explainProjectOverride($project, $name); } return self::SUCCESS; @@ -68,4 +69,23 @@ public function handle(MerchantStore $store, ProjectMerchantFile $project, Envir 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. + */ + private function explainProjectOverride(ProjectMerchantFile $project, string $name): 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) { + $this->comment("Commands in this folder still use {$bound} from the nearest .quickpay-cli.json."); + } + } } diff --git a/app/Credentials/MerchantName.php b/app/Credentials/MerchantName.php index 1e62e43..fd618c6 100644 --- a/app/Credentials/MerchantName.php +++ b/app/Credentials/MerchantName.php @@ -14,4 +14,23 @@ public static function validate(string $name): string 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 index ddf4fb0..b2ab856 100644 --- a/app/Credentials/MerchantStore.php +++ b/app/Credentials/MerchantStore.php @@ -58,7 +58,7 @@ public function read(): array try { $config = MerchantConfigurationJson::decode($contents); } catch (JsonException) { - throw new CredentialException('Quickpay CLI merchant configuration is invalid JSON.'); + throw new CredentialException('Quickpay CLI merchant configuration is invalid JSON or repeats a property.'); } if ($config instanceof stdClass && property_exists($config, 'api_key')) { @@ -115,6 +115,10 @@ public function add(string $name, string $apiKey, bool $replace = false, bool $r 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; } diff --git a/app/Credentials/ProjectMerchantFile.php b/app/Credentials/ProjectMerchantFile.php index 7eb90b2..c91392d 100644 --- a/app/Credentials/ProjectMerchantFile.php +++ b/app/Credentials/ProjectMerchantFile.php @@ -75,14 +75,17 @@ private function read(string $path): string } // Upward discovery reaches shared directories such as /tmp. Another // user's binding must not steer which saved merchant this user runs. + // 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 ?? (function_exists('posix_geteuid') ? posix_geteuid() : null); - if ($owner !== null && @fileowner($path) !== $owner) { + $link = is_link($path) ? @lstat($path) : null; + if ($owner !== null && (@fileowner($path) !== $owner || ($link !== null && ($link === false || $link['uid'] !== $owner)))) { throw new CredentialException("Project merchant binding {$location} is not owned by the current user."); } try { $config = MerchantConfigurationJson::decode($contents); } catch (JsonException) { - throw new CredentialException("Project merchant binding {$location} is invalid JSON."); + 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."); diff --git a/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php index 829d9cf..c315f56 100644 --- a/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php @@ -18,6 +18,20 @@ && $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') + : $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'; @@ -36,7 +50,7 @@ $this->artisan('merchants:add', ['name' => $name])->assertExitCode(1); Http::assertNothingSent(); expect(file_get_contents($this->store->path()))->toBe($before); -})->with(['duplicate' => 'shop-a', 'path' => '../secret', 'leading space' => ' My Website']); +})->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' => []])]); diff --git a/tests/Feature/Commands/Merchants/SelectMerchantCommandTest.php b/tests/Feature/Commands/Merchants/SelectMerchantCommandTest.php index 001c71d..784abdb 100644 --- a/tests/Feature/Commands/Merchants/SelectMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/SelectMerchantCommandTest.php @@ -43,6 +43,20 @@ 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('rejects environment overrides before changing selection', function (bool $named): void { $this->store->add('shop-a', 'fake-secret-a'); putenv('QUICKPAY_API_KEY=fake-environment'); diff --git a/tests/Integration/Credentials/MerchantStoreTest.php b/tests/Integration/Credentials/MerchantStoreTest.php index 4eb08e0..7d41552 100644 --- a/tests/Integration/Credentials/MerchantStoreTest.php +++ b/tests/Integration/Credentials/MerchantStoreTest.php @@ -47,6 +47,16 @@ 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'); diff --git a/tests/Integration/Credentials/ProjectMerchantFileTest.php b/tests/Integration/Credentials/ProjectMerchantFileTest.php index 4934863..4f21b14 100644 --- a/tests/Integration/Credentials/ProjectMerchantFileTest.php +++ b/tests/Integration/Credentials/ProjectMerchantFileTest.php @@ -45,6 +45,12 @@ '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; @@ -52,6 +58,24 @@ ->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); diff --git a/tests/Unit/Credentials/MerchantNameTest.php b/tests/Unit/Credentials/MerchantNameTest.php index 7224dbb..9c22755 100644 --- a/tests/Unit/Credentials/MerchantNameTest.php +++ b/tests/Unit/Credentials/MerchantNameTest.php @@ -15,6 +15,15 @@ '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([ From 2dbf9195193d1dbc6afe865ced3cc0192d4aa76d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20J=C3=B8rgensen?= Date: Mon, 23 Nov 2026 19:44:57 +0100 Subject: [PATCH 16/16] fix: close review findings on bindings, home lookup and raw headers - Project bindings are checked against the current user even without the posix extension, using the owner of a temporary file the process creates; if that fails, no binding is trusted. - A binding's owner is checked before it is read, and bindings over 4 KB are refused unread. - The home folder is looked up only when saved merchants are used, so a missing HOME is an ordinary error and QUICKPAY_API_KEY runs work. - Raw requests refuse X-HTTP-Method-Override, X-HTTP-Method and X-Method-Override, so a read-only GET cannot become a write. - merchants:select warns when the project binding names a merchant that is no longer saved, instead of saying it is still used. - The QUICKPAY_API_KEY notice in merchants:add says that --merchant and project bindings fail while it is set. - Config errors for single-key files and invalid stored names give the file's path. - The README read-only example no longer re-adds a saved merchant, and the docs call the confirmation a guardrail, not a lock. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++- SECURITY.md | 4 +- app/Commands/Merchants/AddMerchantCommand.php | 2 +- .../Merchants/SelectMerchantCommand.php | 16 ++++- app/Credentials/MerchantStore.php | 68 ++++++++++++++----- app/Credentials/ProjectMerchantFile.php | 52 +++++++++++--- app/Quickpay/Raw/RawApiHeaderParser.php | 15 ++++ .../Merchants/AddMerchantCommandTest.php | 2 +- .../Merchants/SelectMerchantCommandTest.php | 11 +++ .../Console/AuthenticatedCommandTest.php | 21 ++++++ .../Credentials/MerchantStoreTest.php | 24 +++++++ .../Credentials/ProjectMerchantFileTest.php | 24 +++++++ .../Quickpay/Raw/RawApiHeaderParserTest.php | 5 ++ 13 files changed, 217 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 5305480..5f0ad40 100644 --- a/README.md +++ b/README.md @@ -67,16 +67,18 @@ 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 merchants:add "My Website" --read-only quickpay merchants:access "My Website" --read-only quickpay merchants:access "My Website" --read-write +quickpay merchants:add "My Shop" --read-only ``` 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 a script or agent can't lift -the protection on its own. A key in `QUICKPAY_API_KEY` always has full access. +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 diff --git a/SECURITY.md b/SECURITY.md index ac96dac..e4ab1ae 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -65,7 +65,9 @@ asking for confirmation. Making a merchant read-only works anywhere, and 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: anyone who can edit the configuration file can change it. +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 diff --git a/app/Commands/Merchants/AddMerchantCommand.php b/app/Commands/Merchants/AddMerchantCommand.php index bbafe12..4b0372f 100644 --- a/app/Commands/Merchants/AddMerchantCommand.php +++ b/app/Commands/Merchants/AddMerchantCommand.php @@ -70,7 +70,7 @@ public function handle(MerchantStore $store, MerchantAuthenticationCheck $check, } if ($environment->get('QUICKPAY_API_KEY') !== null) { - $this->comment('QUICKPAY_API_KEY is set, so commands use it instead of saved merchants until you unset it.'); + $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(); diff --git a/app/Commands/Merchants/SelectMerchantCommand.php b/app/Commands/Merchants/SelectMerchantCommand.php index 8b68633..ac17465 100644 --- a/app/Commands/Merchants/SelectMerchantCommand.php +++ b/app/Commands/Merchants/SelectMerchantCommand.php @@ -61,7 +61,7 @@ public function handle(MerchantStore $store, ProjectMerchantFile $project, Envir } else { $store->select($name); $this->info('Global default merchant selected: '.$name); - $this->explainProjectOverride($project, $name); + $this->explainProjectOverride($project, $name, array_keys($config['merchants'])); } return self::SUCCESS; @@ -73,8 +73,10 @@ public function handle(MerchantStore $store, ProjectMerchantFile $project, Envir /** * 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): void + private function explainProjectOverride(ProjectMerchantFile $project, string $name, array $saved): void { try { $bound = $project->find(); @@ -84,8 +86,16 @@ private function explainProjectOverride(ProjectMerchantFile $project, string $na return; } - if ($bound !== null && $bound !== $name) { + 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/Credentials/MerchantStore.php b/app/Credentials/MerchantStore.php index b2ab856..d04ff1d 100644 --- a/app/Credentials/MerchantStore.php +++ b/app/Credentials/MerchantStore.php @@ -2,6 +2,7 @@ namespace App\Credentials; +use App\Console\Output\ResponseBodySanitizer; use App\Credentials\Exceptions\CredentialException; use App\Credentials\Redaction\CredentialRedactor; use Closure; @@ -14,21 +15,40 @@ */ final readonly class MerchantStore { - public function __construct( - private string $path, - private ?string $legacyPath = null, - ) {} + /** @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 { - $home = rtrim($home->path(), DIRECTORY_SEPARATOR); + $base = fn (): string => rtrim($home->path(), DIRECTORY_SEPARATOR); - return new self($home.'/.config/quickpay-cli/config.json', $home.'/.config/quickpay/config.json'); + 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; + return ($this->path)(); } /** @@ -38,19 +58,22 @@ public function path(): string */ public function leftoverLegacyCredential(): ?string { - return $this->legacyPath !== null && (file_exists($this->legacyPath) || is_link($this->legacyPath)) - ? $this->legacyPath + $legacyPath = ($this->legacyPath)(); + + return $legacyPath !== null && (file_exists($legacyPath) || is_link($legacyPath)) + ? $legacyPath : null; } /** @return MerchantConfig */ public function read(): array { - if (! file_exists($this->path) && ! is_link($this->path)) { + $path = $this->path(); + if (! file_exists($path) && ! is_link($path)) { return ['default_merchant' => null, 'merchants' => []]; } - $contents = is_file($this->path) ? @file_get_contents($this->path) : false; + $contents = is_file($path) ? @file_get_contents($path) : false; if ($contents === false) { throw new CredentialException('Quickpay CLI merchant configuration cannot be read.'); } @@ -62,7 +85,9 @@ public function read(): array } if ($config instanceof stdClass && property_exists($config, 'api_key')) { - throw new CredentialException('Unsupported single-key configuration. Add merchants again with quickpay merchants:add after removing this unsupported file.'); + $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 @@ -75,7 +100,13 @@ public function read(): array $merchants = []; foreach (get_object_vars($config->merchants) as $name => $merchant) { - MerchantName::validate((string) $name); + 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) === '') { @@ -198,20 +229,21 @@ private function requireMerchant(array $config, string $name): void /** @param Closure(MerchantConfig): MerchantConfig $change */ private function mutate(Closure $change): void { - $directory = dirname($this->path); + $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($this->path.'.lock', 'c'); + $lock = @fopen($file.'.lock', 'c'); if ($lock === false) { throw new CredentialException('Unable to lock merchant credentials.'); } $temporary = ''; try { - if (! @chmod($this->path.'.lock', 0600) || ! flock($lock, LOCK_EX)) { + if (! @chmod($file.'.lock', 0600) || ! flock($lock, LOCK_EX)) { throw new CredentialException('Unable to lock merchant credentials.'); } $config = $change($this->read()); @@ -219,12 +251,12 @@ private function mutate(Closure $change): void '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($this->path).'.'); + $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, $this->path)) { + if (@file_put_contents($temporary, $json) === false || ! @chmod($temporary, 0600) || ! @rename($temporary, $file)) { throw new CredentialException('Unable to store merchant credentials atomically.'); } $temporary = ''; diff --git a/app/Credentials/ProjectMerchantFile.php b/app/Credentials/ProjectMerchantFile.php index c91392d..c487d59 100644 --- a/app/Credentials/ProjectMerchantFile.php +++ b/app/Credentials/ProjectMerchantFile.php @@ -9,7 +9,10 @@ final readonly class ProjectMerchantFile { - /** @param ?int $owner Expected binding owner; defaults to the effective user where POSIX is available. */ + /** A binding holds one short merchant name, so anything larger is refused unread. */ + private const MAX_BYTES = 4096; + + /** @param ?int $owner Expected binding owner; defaults to the current user. */ public function __construct( private ?string $directory = null, private ?int $owner = null, @@ -55,6 +58,32 @@ public function save(string $merchant): void } } + /** + * 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(); @@ -69,19 +98,26 @@ private function directory(): string private function read(string $path): string { $location = ResponseBodySanitizer::terminalLine($path, ''); - $contents = is_file($path) ? @file_get_contents($path) : false; - if ($contents === false) { + 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. - // 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 ?? (function_exists('posix_geteuid') ? posix_geteuid() : null); + // 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 ($owner !== null && (@fileowner($path) !== $owner || ($link !== null && ($link === false || $link['uid'] !== $owner)))) { + 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) { 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/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php index c315f56..7876f24 100644 --- a/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/AddMerchantCommandTest.php @@ -27,7 +27,7 @@ ->expectsQuestion('API key', 'fake-secret-a') ->expectsOutputToContain('Merchant saved: My Website'); $environment - ? $command->expectsOutputToContain('QUICKPAY_API_KEY is set') + ? $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]); diff --git a/tests/Feature/Commands/Merchants/SelectMerchantCommandTest.php b/tests/Feature/Commands/Merchants/SelectMerchantCommandTest.php index 784abdb..dcccbb5 100644 --- a/tests/Feature/Commands/Merchants/SelectMerchantCommandTest.php +++ b/tests/Feature/Commands/Merchants/SelectMerchantCommandTest.php @@ -57,6 +57,17 @@ 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'); diff --git a/tests/Feature/Console/AuthenticatedCommandTest.php b/tests/Feature/Console/AuthenticatedCommandTest.php index fcede9c..d74966e 100644 --- a/tests/Feature/Console/AuthenticatedCommandTest.php +++ b/tests/Feature/Console/AuthenticatedCommandTest.php @@ -14,6 +14,7 @@ use App\Console\Terminal\StdinTerminalDetector; use App\Credentials\ApiKeyResolver; use App\Credentials\EnvironmentVariables; +use App\Credentials\HomeDirectory; use App\Credentials\MerchantStore; use App\Credentials\ProjectMerchantFile; use App\Quickpay\QuickpayClient; @@ -304,3 +305,23 @@ public function run(?string $paymentId, ?string $orderId, CallbackTarget $target 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/Integration/Credentials/MerchantStoreTest.php b/tests/Integration/Credentials/MerchantStoreTest.php index 7d41552..3d6e19b 100644 --- a/tests/Integration/Credentials/MerchantStoreTest.php +++ b/tests/Integration/Credentials/MerchantStoreTest.php @@ -322,3 +322,27 @@ 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 index 4f21b14..a3380b9 100644 --- a/tests/Integration/Credentials/ProjectMerchantFileTest.php +++ b/tests/Integration/Credentials/ProjectMerchantFileTest.php @@ -84,3 +84,27 @@ 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/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']);