diff --git a/CHANGELOG.md b/CHANGELOG.md index 467e24c74..a09281b76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,9 @@ The format is based on Keep a Changelog. - `php qt install:debugbar` copies the toolbar files through the local filesystem. It used the application's default storage, so with `fs.default` set to `dropbox` or `gdrive` it looked for the local files in the cloud and failed. Its message for an installation that is already complete reads "The debug bar is already installed" (#691) - The `@method` annotations of the `Cache` facade declare the PSR-16 types the adapters have, so static analysis and IDEs report `cache()->get(42)`, which throws a `TypeError` at runtime. The `*Multiple()` methods document integer keys and `InvalidCacheKeyException` (#691) - `MemcachedAdapter::set()` handles the TTL as PSR-16 and the other adapters do. A TTL of zero, or a `DateInterval` in the past, removes the item: Memcached read the resulting `0` as "never expires" and kept it. A TTL of more than 30 days is sent as an absolute time: Memcached reads a longer number of seconds as a Unix timestamp, so the item expired at once although `set()` returned `true` (#692) +- The Dropbox and Google Drive storage adapters refresh an expired access token at most once per request. The request after the refresh called the same method again without a limit, so a 401 that came back after the refresh, or a 401 from the token request itself, repeated the requests without end. When the retried request or the token request fails, the adapter throws its `Exception`. The retried request keeps its HTTP method; it was always sent as `POST` (#694) +- Dropbox refreshes the access token only for a 401 without a body or with an error tagged `invalid_access_token` or `expired_access_token`. It refreshed for every 401 with an error tag, such as `no_account` or a missing permission, and an error body that was plain text raised a `TypeError`. Any other 401 now throws the adapter's `Exception` (#694) +- The `Exception` of a failed Dropbox or Google Drive request carries a plain text error body as it is, and the HTTP client's error when the response has no body; a text body was JSON encoded, and an error body that was plain text raised a `TypeError` in the check for an expired access token (#694) ## [3.1.2] - 2026-11-19 diff --git a/src/Storage/Adapters/Dropbox/DropboxApp.php b/src/Storage/Adapters/Dropbox/DropboxApp.php index 771a2f56a..260b959e6 100644 --- a/src/Storage/Adapters/Dropbox/DropboxApp.php +++ b/src/Storage/Adapters/Dropbox/DropboxApp.php @@ -230,22 +230,25 @@ public function path(string $name): array } /** - * Checks if the access token need refresh + * Checks if the access token needs a refresh: a 401 with no body, or with an object whose + * error has the tag of an invalid or expired token; any other body is not a token error */ - private function accessTokenNeedsRefresh(int $code, ?object $message = null): bool + private function accessTokenNeedsRefresh(int $code, mixed $message = null): bool { if ($code !== self::INVALID_TOKEN_ERROR_CODE) { return false; } - if (isset($message->error)) { - $error = (array) $message->error; + if ($message === null || $message === '') { + return true; + } - if (!isset($error['.tag']) && !in_array($error['.tag'], self::ACCESS_TOKEN_STATUS)) { - return false; - } + if (!is_object($message) || !isset($message->error)) { + return false; } - return true; + $error = (array) $message->error; + + return isset($error['.tag']) && in_array($error['.tag'], self::ACCESS_TOKEN_STATUS, true); } } diff --git a/src/Storage/Adapters/GoogleDrive/GoogleDriveApp.php b/src/Storage/Adapters/GoogleDrive/GoogleDriveApp.php index 20a274559..8549f2f23 100644 --- a/src/Storage/Adapters/GoogleDrive/GoogleDriveApp.php +++ b/src/Storage/Adapters/GoogleDrive/GoogleDriveApp.php @@ -180,9 +180,9 @@ public function getFileInfo(string $fileId, bool $media = false, array $params = } /** - * Checks if the access token need refresh + * Checks if the access token needs a refresh: every 401, whatever the body is */ - private function accessTokenNeedsRefresh(int $code, ?object $message = null): bool + private function accessTokenNeedsRefresh(int $code, mixed $message = null): bool { return $code === self::INVALID_TOKEN_ERROR_CODE; } diff --git a/src/Storage/Traits/CloudAppTrait.php b/src/Storage/Traits/CloudAppTrait.php index e270938f8..29f67e027 100644 --- a/src/Storage/Traits/CloudAppTrait.php +++ b/src/Storage/Traits/CloudAppTrait.php @@ -20,6 +20,12 @@ */ trait CloudAppTrait { + /** + * Set while the access token is being refreshed: the token request and the retried + * request may not start another refresh, so a request refreshes the token at most once + */ + private bool $refreshingAccessToken = false; + /** * @inheritDoc * @param array|string|null $data @@ -38,35 +44,42 @@ public function sendRequest(string $uri, $data = null, array $headers = [], stri $errors = $this->httpClient->getErrors(); $responseBody = $this->httpClient->getResponseBody(); - if ($errors) { - $code = $errors['code']; - - if ($this->accessTokenNeedsRefresh($code, $responseBody)) { - $prevUrl = $this->httpClient->url(); + if (!$errors) { + return $responseBody; + } - if (empty($prevUrl)) { - throw new Exception('Cannot retry request: original URL is not available.', E_ERROR); - } + if (!$this->refreshingAccessToken && $this->accessTokenNeedsRefresh($errors['code'], $responseBody)) { + $this->refreshingAccessToken = true; - $prevData = $this->httpClient->getData(); - $prevHeaders = $this->httpClient->getRequestHeaders(); + try { + $accessToken = $this->fetchAccessTokenByRefreshToken($this->tokenService->getRefreshToken()); - $refreshToken = $this->tokenService->getRefreshToken(); + $headers['Authorization'] = 'Bearer ' . $accessToken; - $accessToken = $this->fetchAccessTokenByRefreshToken($refreshToken); + return $this->sendRequest($uri, $data, $headers, $method); + } finally { + $this->refreshingAccessToken = false; + } + } - $prevHeaders['Authorization'] = 'Bearer ' . $accessToken; + throw new Exception($this->errorMessage($responseBody, $errors), E_ERROR); + } - $responseBody = $this->sendRequest($prevUrl, $prevData, $prevHeaders); + /** + * The message of a failed request: a text body as it is, the client's error + * when there is no body, and any other body as JSON + * @param array $errors + */ + private function errorMessage(mixed $responseBody, array $errors): string + { + if (is_string($responseBody) && $responseBody !== '') { + return $responseBody; + } - } else { - throw new Exception( - json_encode($responseBody ?? $errors) ?: '', - E_ERROR - ); - } + if ($responseBody === null || $responseBody === '') { + return json_encode($errors) ?: ''; } - return $responseBody; + return json_encode($responseBody) ?: ''; } } diff --git a/tests/Unit/Storage/Adapters/Dropbox/DropboxAppTest.php b/tests/Unit/Storage/Adapters/Dropbox/DropboxAppTest.php index b12901e17..b9a00ee7d 100644 --- a/tests/Unit/Storage/Adapters/Dropbox/DropboxAppTest.php +++ b/tests/Unit/Storage/Adapters/Dropbox/DropboxAppTest.php @@ -2,9 +2,11 @@ namespace Quantum\Tests\Unit\Storage\Adapters\Dropbox; -use Quantum\Storage\Adapters\Dropbox\DropboxApp; use Quantum\Tests\Unit\Storage\HttpClientTestCase; +use Quantum\Storage\Adapters\Dropbox\DropboxApp; +use PHPUnit\Framework\Attributes\DataProvider; use Quantum\Tests\Unit\AppTestCase; +use Exception; class DropboxAppTest extends AppTestCase { @@ -126,11 +128,12 @@ public function testDropboxSendRequest(): void $this->assertEquals((object) $this->profileDataResponse, $response); } - public function testDropboxRequestWithAccessTokenExpired(): void + #[DataProvider('tokenErrorProvider')] + public function testDropboxRequestWithAccessTokenExpired(string $tag): void { $this->currentErrors = ['code' => 401]; - $this->currentResponse = (object) $this->errorResponse; + $this->currentResponse = (object) ['error' => (object) ['.tag' => $tag], 'error_summary' => $tag . '/...']; $response = $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); @@ -139,6 +142,131 @@ public function testDropboxRequestWithAccessTokenExpired(): void $this->assertEquals((object) $this->profileDataResponse, $response); } + public static function tokenErrorProvider(): array + { + return [ + 'expired access token' => ['expired_access_token'], + 'invalid access token' => ['invalid_access_token'], + ]; + } + + #[DataProvider('noBodyProvider')] + public function testDropboxRefreshesTheTokenWhenTheUnauthorizedErrorHasNoBody(mixed $body): void + { + $this->responseQueue = [ + ['body' => $body, 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'new_tok'], 'errors' => []], + ['body' => (object) $this->profileDataResponse, 'errors' => []], + ]; + + $response = $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); + + $this->assertEquals((object) $this->profileDataResponse, $response); + $this->assertCount(3, $this->sentMethods); + } + + public static function noBodyProvider(): array + { + return [ + 'empty body' => [''], + 'no body' => [null], + ]; + } + + #[DataProvider('otherUnauthorizedBodyProvider')] + public function testDropboxDoesNotRefreshTheTokenForAnotherUnauthorizedError(mixed $body): void + { + $this->responseQueue = [ + ['body' => $body, 'errors' => ['code' => 401]], + ]; + + try { + $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); + $this->fail('The error was not thrown'); + } catch (Exception) { + $this->assertCount(1, $this->sentMethods); + } + } + + public static function otherUnauthorizedBodyProvider(): array + { + return [ + 'another error tag' => [(object) ['error' => (object) ['.tag' => 'no_account']]], + 'an error without a tag' => [(object) ['error' => (object) ['reason' => 'unknown']]], + 'an object without an error' => [(object) ['message' => 'Unauthorized']], + 'an error that is a string' => [(object) ['error' => 'invalid_grant']], + 'a text body' => ['Error in call to API function "users/get_account": Bad request'], + 'an array body' => [['error' => ['.tag' => 'expired_access_token']]], + 'a number body' => [401], + ]; + } + + public function testDropboxThrowsTheTextOfATextErrorAsItIs(): void + { + $text = 'Error in call to API function "users/get_account": Bad request'; + + $this->responseQueue = [ + ['body' => $text, 'errors' => ['code' => 401]], + ]; + + try { + $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); + $this->fail('The error was not thrown'); + } catch (Exception $e) { + $this->assertSame($text, $e->getMessage()); + } + } + + public function testDropboxThrowsTheClientErrorWhenAnErrorHasNoBody(): void + { + $errors = ['code' => 500, 'message' => 'HTTP/1.1 500 Internal Server Error']; + + $this->responseQueue = [ + ['body' => '', 'errors' => $errors], + ]; + + try { + $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); + $this->fail('The error was not thrown'); + } catch (Exception $e) { + $this->assertSame(json_encode($errors), $e->getMessage()); + } + } + + public function testDropboxRefreshesTheTokenOnlyOnceWhenTheRetryFailsAgain(): void + { + $expired = (object) ['error' => (object) ['.tag' => 'expired_access_token']]; + + $this->responseQueue = [ + ['body' => $expired, 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'new_tok'], 'errors' => []], + ['body' => $expired, 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'newer_tok'], 'errors' => []], + ['body' => (object) $this->profileDataResponse, 'errors' => []], + ]; + + try { + $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2'); + $this->fail('The error was not thrown'); + } catch (Exception) { + $this->assertCount(3, $this->sentMethods); + } + } + + public function testDropboxRetryKeepsTheMethodOfTheRequest(): void + { + $this->responseQueue = [ + ['body' => (object) ['error' => (object) ['.tag' => 'expired_access_token']], 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'new_tok'], 'errors' => []], + ['body' => (object) $this->profileDataResponse, 'errors' => []], + ]; + + $response = $this->dropboxApp->sendRequest('https://api.dropboxapi.com/2/users/get_account2', null, [], 'GET'); + + $this->assertEquals((object) $this->profileDataResponse, $response); + $this->assertSame(['GET', 'POST', 'GET'], $this->sentMethods); + } + public function testDropboxPathNormalizer(): void { $this->assertEquals(['path' => '/message.txt'], $this->dropboxApp->path('/message.txt')); diff --git a/tests/Unit/Storage/Adapters/GoogleDrive/GoogleDriveAppTest.php b/tests/Unit/Storage/Adapters/GoogleDrive/GoogleDriveAppTest.php index 58d7f8f43..dcbc42617 100644 --- a/tests/Unit/Storage/Adapters/GoogleDrive/GoogleDriveAppTest.php +++ b/tests/Unit/Storage/Adapters/GoogleDrive/GoogleDriveAppTest.php @@ -5,6 +5,7 @@ use Quantum\Storage\Adapters\GoogleDrive\GoogleDriveApp; use Quantum\Tests\Unit\Storage\HttpClientTestCase; use Quantum\Tests\Unit\AppTestCase; +use Exception; class GoogleDriveAppTest extends AppTestCase { @@ -119,4 +120,79 @@ public function testGoogleDriveRequestWithAccessTokenExpired(): void $this->assertEquals((object) $this->fileMetadataResponse, $response); } + public function testGoogleDriveRequestWithATextBodyOnAnExpiredTokenRefreshesTheToken(): void + { + $this->currentErrors = ['code' => 401]; + + $this->currentResponse = 'Unauthorized'; + + $response = $this->googleDriveApp->sendRequest(GoogleDriveApp::FILE_METADATA_URL . '/' . $this->fileMetadataResponse['id']); + + $this->assertEquals((object) $this->fileMetadataResponse, $response); + } + + public function testGoogleDriveRequestWithATextErrorThrowsTheText(): void + { + $this->responseQueue = [ + ['body' => 'Internal Server Error', 'errors' => ['code' => 500]], + ]; + + try { + $this->googleDriveApp->sendRequest(GoogleDriveApp::FILE_METADATA_URL . '/' . $this->fileMetadataResponse['id']); + $this->fail('The error was not thrown'); + } catch (Exception $e) { + $this->assertSame('Internal Server Error', $e->getMessage()); + } + } + + public function testGoogleDriveRefreshesTheTokenOnlyOnceWhenTheRetryFailsAgain(): void + { + $this->responseQueue = [ + ['body' => 'Unauthorized', 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'new_tok'], 'errors' => []], + ['body' => 'Unauthorized', 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'newer_tok'], 'errors' => []], + ['body' => (object) $this->fileMetadataResponse, 'errors' => []], + ]; + + try { + $this->googleDriveApp->sendRequest(GoogleDriveApp::FILE_METADATA_URL . '/' . $this->fileMetadataResponse['id']); + $this->fail('The error was not thrown'); + } catch (Exception $e) { + $this->assertSame('Unauthorized', $e->getMessage()); + $this->assertCount(3, $this->sentMethods); + } + } + + public function testGoogleDriveDoesNotRefreshAgainWhenTheTokenRequestIsUnauthorized(): void + { + $this->responseQueue = [ + ['body' => (object) $this->errorResponse, 'errors' => ['code' => 401]], + ['body' => (object) ['error' => 'invalid_client'], 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'new_tok'], 'errors' => []], + ['body' => (object) $this->fileMetadataResponse, 'errors' => []], + ]; + + try { + $this->googleDriveApp->sendRequest(GoogleDriveApp::FILE_METADATA_URL . '/' . $this->fileMetadataResponse['id']); + $this->fail('The error was not thrown'); + } catch (Exception $e) { + $this->assertStringContainsString('invalid_client', $e->getMessage()); + $this->assertCount(2, $this->sentMethods); + } + } + + public function testGoogleDriveRetryKeepsTheMethodOfTheRequest(): void + { + $this->responseQueue = [ + ['body' => (object) $this->errorResponse, 'errors' => ['code' => 401]], + ['body' => (object) ['access_token' => 'new_tok'], 'errors' => []], + ['body' => (object) $this->fileMetadataResponse, 'errors' => []], + ]; + + $response = $this->googleDriveApp->sendRequest(GoogleDriveApp::FILE_METADATA_URL . '/' . $this->fileMetadataResponse['id'], null, [], 'GET'); + + $this->assertEquals((object) $this->fileMetadataResponse, $response); + $this->assertSame(['GET', 'POST', 'GET'], $this->sentMethods); + } } diff --git a/tests/Unit/Storage/HttpClientTestCase.php b/tests/Unit/Storage/HttpClientTestCase.php index 51202ecdc..0d62bdc64 100644 --- a/tests/Unit/Storage/HttpClientTestCase.php +++ b/tests/Unit/Storage/HttpClientTestCase.php @@ -19,6 +19,17 @@ trait HttpClientTestCase protected $options; + /** + * Responses for the next requests, in order: each ['body' => ..., 'errors' => [...]]. + * When it is empty, a request answers with $currentResponse and $currentErrors. + */ + protected array $responseQueue = []; + + /** + * The HTTP method of every request sent, in order + */ + protected array $sentMethods = []; + protected function mockHttpClient() { $httpClientMock = Mockery::mock(HttpClient::class); @@ -28,7 +39,10 @@ protected function mockHttpClient() return $httpClientMock; }); - $httpClientMock->shouldReceive('setMethod')->andReturnSelf(); + $httpClientMock->shouldReceive('setMethod')->andReturnUsing(function ($method) use ($httpClientMock) { + $this->sentMethods[] = $method; + return $httpClientMock; + }); $httpClientMock->shouldReceive('setHeaders')->andReturnSelf(); @@ -47,6 +61,13 @@ protected function mockHttpClient() }); $httpClientMock->shouldReceive('start')->andReturnUsing(function () use ($httpClientMock) { + if ($this->responseQueue !== []) { + $next = array_shift($this->responseQueue); + $this->response[$this->url]['body'] = $next['body']; + $this->response[$this->url]['errors'] = $next['errors']; + return $httpClientMock; + } + $this->response[$this->url]['body'] = $this->currentResponse; $this->response[$this->url]['errors'] = $this->currentErrors; $this->currentResponse = [];