Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
19 changes: 11 additions & 8 deletions src/Storage/Adapters/Dropbox/DropboxApp.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
4 changes: 2 additions & 2 deletions src/Storage/Adapters/GoogleDrive/GoogleDriveApp.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
55 changes: 34 additions & 21 deletions src/Storage/Traits/CloudAppTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -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, mixed>|string|null $data
Expand All @@ -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<int|string, mixed> $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) ?: '';
}
}
134 changes: 131 additions & 3 deletions tests/Unit/Storage/Adapters/Dropbox/DropboxAppTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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');

Expand All @@ -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'));
Expand Down
76 changes: 76 additions & 0 deletions tests/Unit/Storage/Adapters/GoogleDrive/GoogleDriveAppTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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);
}
}
Loading
Loading