From 32306e920958dd6a4ee2597f699482123e22356c Mon Sep 17 00:00:00 2001 From: JonPurvis Date: Mon, 16 Nov 2026 22:45:03 +0000 Subject: [PATCH 1/4] fix invalid token error --- app/Commands/BaseCommand.php | 21 +++++++ tests/Feature/UnauthorizedResponseTest.php | 67 ++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 tests/Feature/UnauthorizedResponseTest.php diff --git a/app/Commands/BaseCommand.php b/app/Commands/BaseCommand.php index 76b2b7af..c86d53b9 100644 --- a/app/Commands/BaseCommand.php +++ b/app/Commands/BaseCommand.php @@ -3,6 +3,7 @@ namespace App\Commands; use App\Client\Connector; +use App\Cloud; use App\Concerns\HasAClient; use App\Concerns\Validates; use App\Exceptions\CommandExitException; @@ -25,6 +26,7 @@ use ReflectionClass; use ReflectionNamedType; use RuntimeException; +use Saloon\Exceptions\Request\Statuses\UnauthorizedException; use Saloon\PaginationPlugin\Paginator; use Spatie\LaravelData\Attributes\DataCollectionOf; use Spatie\LaravelData\Data; @@ -211,6 +213,10 @@ public function run(InputInterface $input, OutputInterface $output): int } catch (UnreadableResponseException $e) { $this->outputError($e->getMessage()); + return self::FAILURE; + } catch (UnauthorizedException $e) { + $this->outputError($this->unauthorizedMessage($e)); + return self::FAILURE; } catch (RuntimeException $e) { if ($this->wantsJson()) { @@ -223,6 +229,21 @@ public function run(InputInterface $input, OutputInterface $output): int } } + /** + * A revoked or expired token surfaces on whichever request happens first, so + * every command needs the same guidance rather than a Saloon stack trace. + */ + protected function unauthorizedMessage(UnauthorizedException $e): string + { + $reason = $e->getResponse()->json('message') ?: 'Unauthorized'; + + $fix = Cloud::apiTokenFromEnvironment() + ? 'Check the token in '.Cloud::API_TOKEN_ENV_VAR.', or unset it to use your stored tokens.' + : 'Run `cloud auth` to sign in again, or `cloud auth:token --add --token=` to save a new token.'; + + return "Laravel Cloud rejected your API token ({$reason}). {$fix}"; + } + protected function ensureInteractive(string $message): void { if (! $this->isInteractive()) { diff --git a/tests/Feature/UnauthorizedResponseTest.php b/tests/Feature/UnauthorizedResponseTest.php new file mode 100644 index 00000000..dc8abb7c --- /dev/null +++ b/tests/Feature/UnauthorizedResponseTest.php @@ -0,0 +1,67 @@ +set('cloud.api_token', null); + + $this->mockConfig = Mockery::mock(ConfigRepository::class); + $this->mockConfig->shouldReceive('apiTokens')->andReturn(collect(['revoked-token'])); + $this->app->instance(ConfigRepository::class, $this->mockConfig); +}); + +afterEach(function () { + MockClient::destroyGlobal(); +}); + +function unauthorizedException(): UnauthorizedException +{ + $connector = new Connector('revoked-token'); + $connector->withMockClient(new MockClient([ + GetOrganizationRequest::class => MockResponse::make(['message' => 'Invalid API token'], 401), + ])); + + try { + $connector->send(new GetOrganizationRequest); + } catch (UnauthorizedException $e) { + return $e; + } + + throw new RuntimeException('Expected the request to be rejected.'); +} + +function unauthorizedMessage(): string +{ + $method = new ReflectionMethod(Usage::class, 'unauthorizedMessage'); + + return $method->invoke(app(Usage::class), unauthorizedException()); +} + +it('fails cleanly instead of throwing when the API rejects the token', function () { + MockClient::global([ + GetUsageRequest::class => MockResponse::make(['message' => 'Invalid API token'], 401), + ]); + + $this->artisan('usage', ['--no-interaction' => true])->assertFailed(); +}); + +it('tells the user to sign in again when a stored token is rejected', function () { + expect(unauthorizedMessage()) + ->toContain('Invalid API token') + ->toContain('cloud auth'); +}); + +it('points at the environment variable when that token is rejected', function () { + config()->set('cloud.api_token', 'revoked-env-token'); + + expect(unauthorizedMessage()) + ->toContain('Invalid API token') + ->toContain('LARAVEL_CLOUD_TOKEN'); +}); From 61abe669913c4687dfd46fe2edb61c07ca1a2b54 Mon Sep 17 00:00:00 2001 From: jp Date: Mon, 16 Nov 2026 23:02:58 +0000 Subject: [PATCH 2/4] Refactor unauthorized message handling in BaseCommand Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- app/Commands/BaseCommand.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/Commands/BaseCommand.php b/app/Commands/BaseCommand.php index c86d53b9..5f328318 100644 --- a/app/Commands/BaseCommand.php +++ b/app/Commands/BaseCommand.php @@ -235,7 +235,9 @@ public function run(InputInterface $input, OutputInterface $output): int */ protected function unauthorizedMessage(UnauthorizedException $e): string { - $reason = $e->getResponse()->json('message') ?: 'Unauthorized'; + $body = json_decode($e->getResponse()->body(), true); + $reason = is_array($body) ? ($body['message'] ?? null) : null; + $reason = is_string($reason) && $reason !== '' ? $reason : 'Unauthorized'; $fix = Cloud::apiTokenFromEnvironment() ? 'Check the token in '.Cloud::API_TOKEN_ENV_VAR.', or unset it to use your stored tokens.' From 94d995ed85f8901855e1066222f13769ba620fef Mon Sep 17 00:00:00 2001 From: JonPurvis Date: Mon, 16 Nov 2026 23:08:17 +0000 Subject: [PATCH 3/4] amend guidance --- app/Commands/BaseCommand.php | 8 ++++- tests/Feature/UnauthorizedResponseTest.php | 40 ++++++++++++++++++---- 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/app/Commands/BaseCommand.php b/app/Commands/BaseCommand.php index 5f328318..dddc25fd 100644 --- a/app/Commands/BaseCommand.php +++ b/app/Commands/BaseCommand.php @@ -239,7 +239,13 @@ protected function unauthorizedMessage(UnauthorizedException $e): string $reason = is_array($body) ? ($body['message'] ?? null) : null; $reason = is_string($reason) && $reason !== '' ? $reason : 'Unauthorized'; - $fix = Cloud::apiTokenFromEnvironment() + // auth:token --list checks the environment token and stored tokens together, + // so the variable being set doesn't mean it was the token that failed. + $envToken = Cloud::apiTokenFromEnvironment(); + $usesEnvironmentToken = $envToken !== null + && $e->getResponse()->getPendingRequest()->headers()->get('Authorization') === 'Bearer '.$envToken; + + $fix = $usesEnvironmentToken ? 'Check the token in '.Cloud::API_TOKEN_ENV_VAR.', or unset it to use your stored tokens.' : 'Run `cloud auth` to sign in again, or `cloud auth:token --add --token=` to save a new token.'; diff --git a/tests/Feature/UnauthorizedResponseTest.php b/tests/Feature/UnauthorizedResponseTest.php index dc8abb7c..181288fc 100644 --- a/tests/Feature/UnauthorizedResponseTest.php +++ b/tests/Feature/UnauthorizedResponseTest.php @@ -21,11 +21,11 @@ MockClient::destroyGlobal(); }); -function unauthorizedException(): UnauthorizedException +function unauthorizedException(string $token = 'revoked-token', array|string $body = ['message' => 'Invalid API token']): UnauthorizedException { - $connector = new Connector('revoked-token'); + $connector = new Connector($token); $connector->withMockClient(new MockClient([ - GetOrganizationRequest::class => MockResponse::make(['message' => 'Invalid API token'], 401), + GetOrganizationRequest::class => MockResponse::make($body, 401), ])); try { @@ -37,11 +37,11 @@ function unauthorizedException(): UnauthorizedException throw new RuntimeException('Expected the request to be rejected.'); } -function unauthorizedMessage(): string +function unauthorizedMessage(UnauthorizedException $e): string { $method = new ReflectionMethod(Usage::class, 'unauthorizedMessage'); - return $method->invoke(app(Usage::class), unauthorizedException()); + return $method->invoke(app(Usage::class), $e); } it('fails cleanly instead of throwing when the API rejects the token', function () { @@ -52,8 +52,26 @@ function unauthorizedMessage(): string $this->artisan('usage', ['--no-interaction' => true])->assertFailed(); }); +it('fails cleanly when the 401 body is not JSON', function () { + MockClient::global([ + GetUsageRequest::class => MockResponse::make('Unauthorized', 401), + ]); + + $this->artisan('usage', ['--no-interaction' => true])->assertFailed(); +}); + +it('falls back to a generic reason when the 401 body has no usable message', function (array|string $body) { + expect(unauthorizedMessage(unauthorizedException(body: $body))) + ->toContain('(Unauthorized)') + ->toContain('cloud auth'); +})->with([ + 'html' => 'Unauthorized', + 'empty' => '', + 'non-string message' => [['message' => ['nested' => 'value']]], +]); + it('tells the user to sign in again when a stored token is rejected', function () { - expect(unauthorizedMessage()) + expect(unauthorizedMessage(unauthorizedException())) ->toContain('Invalid API token') ->toContain('cloud auth'); }); @@ -61,7 +79,15 @@ function unauthorizedMessage(): string it('points at the environment variable when that token is rejected', function () { config()->set('cloud.api_token', 'revoked-env-token'); - expect(unauthorizedMessage()) + expect(unauthorizedMessage(unauthorizedException('revoked-env-token'))) ->toContain('Invalid API token') ->toContain('LARAVEL_CLOUD_TOKEN'); }); + +it('blames the stored token, not the environment variable, when only the stored token is rejected', function () { + config()->set('cloud.api_token', 'valid-env-token'); + + expect(unauthorizedMessage(unauthorizedException('revoked-token'))) + ->toContain('cloud auth') + ->not->toContain('LARAVEL_CLOUD_TOKEN'); +}); From 1ebdc23e0db30795e284edbd2093bd6f995dc2dc Mon Sep 17 00:00:00 2001 From: JonPurvis Date: Mon, 16 Nov 2026 23:18:39 +0000 Subject: [PATCH 4/4] address testing feedback --- tests/Feature/UnauthorizedResponseTest.php | 68 ++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/tests/Feature/UnauthorizedResponseTest.php b/tests/Feature/UnauthorizedResponseTest.php index 181288fc..569d463f 100644 --- a/tests/Feature/UnauthorizedResponseTest.php +++ b/tests/Feature/UnauthorizedResponseTest.php @@ -5,6 +5,7 @@ use App\Client\Resources\Usage\GetUsageRequest; use App\Commands\Usage; use App\ConfigRepository; +use Illuminate\Support\Facades\Artisan; use Saloon\Exceptions\Request\Statuses\UnauthorizedException; use Saloon\Http\Faking\MockClient; use Saloon\Http\Faking\MockResponse; @@ -44,6 +45,55 @@ function unauthorizedMessage(UnauthorizedException $e): string return $method->invoke(app(Usage::class), $e); } +/** + * Headless errors are written straight to STDERR with fwrite, which Artisan's + * test output never sees, so intercept the raw streams themselves. + */ +class CapturesStream extends php_user_filter +{ + /** @var array */ + public static array $captured = []; + + public function filter($in, $out, &$consumed, bool $closing): int + { + while ($bucket = stream_bucket_make_writeable($in)) { + self::$captured[$this->params] = (self::$captured[$this->params] ?? '').$bucket->data; + $consumed += $bucket->datalen; + } + + // Nothing is passed on, so captured output doesn't leak into the test run's own. + return PSFS_PASS_ON; + } +} + +/** + * @return array{exitCode: int, stdout: string, stderr: string} + */ +function runCapturingOutput(string $command, array $parameters): array +{ + if (! in_array('captures-stream', stream_get_filters(), true)) { + stream_filter_register('captures-stream', CapturesStream::class); + } + + CapturesStream::$captured = []; + $stdout = stream_filter_append(STDOUT, 'captures-stream', STREAM_FILTER_WRITE, 'stdout'); + $stderr = stream_filter_append(STDERR, 'captures-stream', STREAM_FILTER_WRITE, 'stderr'); + + try { + $exitCode = Artisan::call($command, $parameters); + } finally { + stream_filter_remove($stdout); + stream_filter_remove($stderr); + } + + return [ + 'exitCode' => $exitCode, + // Prompts and command output go through Artisan's buffer; anything else would hit STDOUT directly. + 'stdout' => Artisan::output().(CapturesStream::$captured['stdout'] ?? ''), + 'stderr' => CapturesStream::$captured['stderr'] ?? '', + ]; +} + it('fails cleanly instead of throwing when the API rejects the token', function () { MockClient::global([ GetUsageRequest::class => MockResponse::make(['message' => 'Invalid API token'], 401), @@ -52,6 +102,24 @@ function unauthorizedMessage(UnauthorizedException $e): string $this->artisan('usage', ['--no-interaction' => true])->assertFailed(); }); +it('writes the error as JSON to stderr and nothing to stdout when running headless', function (array $flags) { + MockClient::global([ + GetUsageRequest::class => MockResponse::make(['message' => 'Invalid API token'], 401), + ]); + + $result = runCapturingOutput('usage', $flags); + + expect($result['exitCode'])->toBe(1) + ->and($result['stdout'])->toBe('') + ->and(json_decode($result['stderr'], true, flags: JSON_THROW_ON_ERROR))->toBe([ + 'error' => true, + 'message' => 'Laravel Cloud rejected your API token (Invalid API token). Run `cloud auth` to sign in again, or `cloud auth:token --add --token=` to save a new token.', + ]); +})->with([ + '--json' => [['--json' => true]], + '--no-interaction' => [['--no-interaction' => true]], +]); + it('fails cleanly when the 401 body is not JSON', function () { MockClient::global([ GetUsageRequest::class => MockResponse::make('Unauthorized', 401),