From 508809534a4a85bd1e7828322aca8f41cbd813a1 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Tue, 28 Jul 2026 18:44:09 +0530 Subject: [PATCH 01/12] fix(vcs): serialize installation token refresh with a lock Concurrent requests hitting an expired installation token each called refreshTokens() with the same refresh token. Providers rotate refresh tokens, so the second call replays an already-used one and the reuse detection revokes the whole token family, leaving the installation unable to refresh even though it is still connected. Serialize refreshes per installation with a lock document, following the existing vcsCommentLocks pattern, and re-read the installation inside the lock so a request that waited picks up the token the holder wrote instead of exchanging the rotated one again. Also persist the rotated pair before the identity lookup that followed it. That lookup is a separate provider call, and letting it fail first discarded a pair the provider had already rotated to, stranding the row with a refresh token that no longer worked. --- src/Appwrite/Vcs/InstallationTokens.php | 79 +++++++++--- tests/unit/Vcs/InstallationTokensTest.php | 142 ++++++++++++++-------- 2 files changed, 152 insertions(+), 69 deletions(-) diff --git a/src/Appwrite/Vcs/InstallationTokens.php b/src/Appwrite/Vcs/InstallationTokens.php index 974ee2260f..5d75dcc166 100644 --- a/src/Appwrite/Vcs/InstallationTokens.php +++ b/src/Appwrite/Vcs/InstallationTokens.php @@ -4,6 +4,7 @@ namespace Appwrite\Vcs; use Appwrite\Auth\OAuth2; use Appwrite\Extend\Exception; +use Utopia\Console; use Utopia\Database\Database; use Utopia\Database\DateTime; use Utopia\Database\Document; @@ -45,41 +46,80 @@ class InstallationTokens throw new Exception(Exception::GENERAL_PROVIDER_FAILURE, 'This installation has no refresh token on file. Please reconnect it.'); } - try { - $oauth2->refreshTokens($refreshToken); - } catch (\Throwable) { + // Providers rotate refresh tokens: two requests exchanging the same one revokes the family. + // The comment lock collection is reused here, it holds nothing but ids, and the prefix + // keeps these apart from the provider comment ids stored alongside them. + $lock = 'installation-' . $installation->getId(); + $authorization = $dbForPlatform->getAuthorization(); + $acquired = false; + $retries = 0; + + while ($retries < 9) { + $retries++; + + try { + $authorization->skip(fn () => $dbForPlatform->createDocument('vcsCommentLocks', new Document(['$id' => $lock]))); + $acquired = true; + break; + } catch (\Throwable $err) { + if ($retries >= 9) { + Console::warning('Error creating vcs installation lock for ' . $installation->getId() . ': ' . $err->getMessage()); + } + + \sleep(1); + } + } + + if (!$acquired) { + // The holder outlasted our wait. Reuse its token if it landed, never replay ours. $current = $this->getCurrentInstallation($dbForPlatform, $installation); - if (!$current->isEmpty() && !empty($current->getAttribute('personalAccessToken')) && !$this->isExpired($current->getAttribute('personalAccessTokenExpiry'))) { + if ($this->isUsable($current)) { return $current; } + throw new Exception(Exception::GENERAL_RESOURCE_LOCKED); + } + + try { + // The lock holder may have refreshed already. + $current = $this->getCurrentInstallation($dbForPlatform, $installation); + + if ($this->isUsable($current)) { + return $current; + } + + return $this->exchange($installation, $dbForPlatform, $oauth2); + } finally { + $authorization->skip(fn () => $dbForPlatform->deleteDocument('vcsCommentLocks', $lock)); + } + } + + protected function exchange(Document $installation, Database $dbForPlatform, OAuth2 $oauth2): Document + { + try { + $oauth2->refreshTokens($installation->getAttribute('personalRefreshToken')); + } catch (\Throwable) { throw new Exception(Exception::GENERAL_PROVIDER_FAILURE, 'Failed to refresh OAuth2 access token. Please reconnect the installation.'); } $accessToken = $oauth2->getAccessToken(''); - $refreshToken = $oauth2->getRefreshToken(''); - $verificationId = $oauth2->getUserID($accessToken); - - if (empty($verificationId)) { - $current = $this->getCurrentInstallation($dbForPlatform, $installation); - if (!$current->isEmpty() && !empty($current->getAttribute('personalAccessToken')) && !$this->isExpired($current->getAttribute('personalAccessTokenExpiry'))) { - return $current; - } - - throw new Exception(Exception::GENERAL_PROVIDER_FAILURE, 'Failed to refresh OAuth2 access token. Please reconnect the installation.'); - } $installation = $installation ->setAttribute('personalAccessToken', $accessToken) - ->setAttribute('personalRefreshToken', $refreshToken) + ->setAttribute('personalRefreshToken', $oauth2->getRefreshToken('')) ->setAttribute('personalAccessTokenExpiry', DateTime::addSeconds(new \DateTime(), (int)$oauth2->getAccessTokenExpiry(''))); + // The provider has already rotated the family, so persist before anything else can fail. $dbForPlatform->updateDocument('installations', $installation->getId(), new Document([ 'personalAccessToken' => $installation->getAttribute('personalAccessToken'), 'personalRefreshToken' => $installation->getAttribute('personalRefreshToken'), 'personalAccessTokenExpiry' => $installation->getAttribute('personalAccessTokenExpiry'), ])); + if (empty($oauth2->getUserID($accessToken))) { + throw new Exception(Exception::GENERAL_PROVIDER_FAILURE, 'Failed to refresh OAuth2 access token. Please reconnect the installation.'); + } + return $installation; } @@ -96,6 +136,13 @@ class InstallationTokens } } + protected function isUsable(Document $installation): bool + { + return !$installation->isEmpty() + && !empty($installation->getAttribute('personalAccessToken')) + && !$this->isExpired($installation->getAttribute('personalAccessTokenExpiry')); + } + protected function getCurrentInstallation(Database $dbForPlatform, Document $installation): Document { try { diff --git a/tests/unit/Vcs/InstallationTokensTest.php b/tests/unit/Vcs/InstallationTokensTest.php index 96f1381eee..c32aedc93d 100644 --- a/tests/unit/Vcs/InstallationTokensTest.php +++ b/tests/unit/Vcs/InstallationTokensTest.php @@ -11,12 +11,17 @@ use PHPUnit\Framework\TestCase; use Utopia\Database\Database; use Utopia\Database\DateTime; use Utopia\Database\Document; +use Utopia\Database\Validator\Authorization; final class InstallationTokensTest extends TestCase { protected function db(): Database { - return $this->createStub(Database::class); + $db = $this->createStub(Database::class); + $db->method('getAuthorization')->willReturn(new Authorization()); + $db->method('getDocument')->willReturn(new Document()); + + return $db; } public function testUnexpiredTokenIsNotRefreshed(): void @@ -83,16 +88,9 @@ final class InstallationTokensTest extends TestCase })) ->willReturnArgument(2); - $installation = new Document([ - '$id' => 'installation1', - 'personalAccessToken' => 'stale-token', - 'personalRefreshToken' => 'stale-refresh', - 'personalAccessTokenExpiry' => DateTime::addSeconds(new \DateTime(), -3600), - ]); - $oauth2 = $this->fakeOAuth2(); - $result = (new InstallationTokens())->refresh($installation, $db, $oauth2); + $result = (new InstallationTokens())->refresh($this->expired(), $db, $oauth2); $this->assertSame('fresh-token', $result->getAttribute('personalAccessToken')); $this->assertSame(1, $oauth2->refreshCalls); @@ -139,78 +137,116 @@ final class InstallationTokensTest extends TestCase public function testFailedRefreshThrows(): void { - $installation = new Document([ - '$id' => 'installation1', - 'personalAccessToken' => 'stale-token', - 'personalRefreshToken' => 'stale-refresh', - 'personalAccessTokenExpiry' => DateTime::addSeconds(new \DateTime(), -3600), - ]); - $oauth2 = $this->fakeOAuth2(emptyUserId: true); $this->expectException(Exception::class); $this->expectExceptionMessage('Failed to refresh OAuth2 access token'); - (new InstallationTokens())->refresh($installation, $this->db(), $oauth2); + (new InstallationTokens())->refresh($this->expired(), $this->db(), $oauth2); } - public function testFailedRefreshReturnsCurrentInstallationWhenAnotherRequestRefreshed(): void + public function testRotatedTokenIsPersistedWhenVerificationFails(): void { $db = $this->createMock(Database::class); - $current = new Document([ - '$id' => 'installation1', - 'personalAccessToken' => 'already-refreshed-token', - 'personalRefreshToken' => 'already-refreshed-refresh', - 'personalAccessTokenExpiry' => DateTime::addSeconds(new \DateTime(), 3600), - ]); + $db->method('getAuthorization')->willReturn(new Authorization()); + $db->method('getDocument')->willReturn(new Document()); + // The provider rotated the family, so the new pair has to land even though the call after it failed. $db->expects($this->once()) - ->method('getDocument') - ->with('installations', 'installation1') - ->willReturn($current); - $db->expects($this->never())->method('updateDocument'); - - $installation = new Document([ - '$id' => 'installation1', - 'personalAccessToken' => 'stale-token', - 'personalRefreshToken' => 'stale-refresh', - 'personalAccessTokenExpiry' => DateTime::addSeconds(new \DateTime(), -3600), - ]); + ->method('updateDocument') + ->with('installations', 'installation1', $this->callback(function (Document $update) { + $this->assertSame('fresh-refresh', $update->getAttribute('personalRefreshToken')); + return true; + })) + ->willReturnArgument(2); $oauth2 = $this->fakeOAuth2(emptyUserId: true); - $result = (new InstallationTokens())->refresh($installation, $db, $oauth2); - - $this->assertSame('already-refreshed-token', $result->getAttribute('personalAccessToken')); + try { + (new InstallationTokens())->refresh($this->expired(), $db, $oauth2); + $this->fail('Expected an Exception'); + } catch (Exception $e) { + $this->assertSame(Exception::GENERAL_PROVIDER_FAILURE, $e->getType()); + } } - public function testRefreshExceptionReturnsCurrentInstallationWhenAnotherRequestRefreshed(): void + public function testTokenRefreshedByLockHolderIsReused(): void { $db = $this->createMock(Database::class); - $current = new Document([ - '$id' => 'installation1', - 'personalAccessToken' => 'already-refreshed-token', - 'personalRefreshToken' => 'already-refreshed-refresh', - 'personalAccessTokenExpiry' => DateTime::addSeconds(new \DateTime(), 3600), - ]); + $db->method('getAuthorization')->willReturn(new Authorization()); $db->expects($this->once()) ->method('getDocument') ->with('installations', 'installation1') - ->willReturn($current); + ->willReturn(new Document([ + '$id' => 'installation1', + 'personalAccessToken' => 'already-refreshed-token', + 'personalRefreshToken' => 'already-refreshed-refresh', + 'personalAccessTokenExpiry' => DateTime::addSeconds(new \DateTime(), 3600), + ])); $db->expects($this->never())->method('updateDocument'); - $installation = new Document([ + $oauth2 = $this->fakeOAuth2(); + + $result = (new InstallationTokens())->refresh($this->expired(), $db, $oauth2); + + $this->assertSame('already-refreshed-token', $result->getAttribute('personalAccessToken')); + $this->assertSame(0, $oauth2->refreshCalls); + } + + public function testRefreshIsSerializedByLock(): void + { + $db = $this->createMock(Database::class); + $db->method('getAuthorization')->willReturn(new Authorization()); + $db->method('getDocument')->willReturn(new Document()); + $db->method('updateDocument')->willReturnArgument(2); + + $db->expects($this->once()) + ->method('createDocument') + ->with('vcsCommentLocks', $this->callback(function (Document $lock) { + $this->assertSame('installation-installation1', $lock->getId()); + return true; + })) + ->willReturnArgument(1); + + $db->expects($this->once()) + ->method('deleteDocument') + ->with('vcsCommentLocks', 'installation-installation1') + ->willReturn(true); + + $oauth2 = $this->fakeOAuth2(); + + (new InstallationTokens())->refresh($this->expired(), $db, $oauth2); + + $this->assertSame(1, $oauth2->refreshCalls); + } + + public function testLockIsReleasedWhenRefreshFails(): void + { + $db = $this->createMock(Database::class); + $db->method('getAuthorization')->willReturn(new Authorization()); + $db->method('getDocument')->willReturn(new Document()); + $db->method('createDocument')->willReturnArgument(1); + + $db->expects($this->once()) + ->method('deleteDocument') + ->with('vcsCommentLocks', 'installation-installation1') + ->willReturn(true); + + $oauth2 = $this->fakeOAuth2(throwOnRefresh: true); + + $this->expectException(Exception::class); + $this->expectExceptionMessage('Failed to refresh OAuth2 access token'); + (new InstallationTokens())->refresh($this->expired(), $db, $oauth2); + } + + protected function expired(): Document + { + return new Document([ '$id' => 'installation1', 'personalAccessToken' => 'stale-token', 'personalRefreshToken' => 'stale-refresh', 'personalAccessTokenExpiry' => DateTime::addSeconds(new \DateTime(), -3600), ]); - - $oauth2 = $this->fakeOAuth2(throwOnRefresh: true); - - $result = (new InstallationTokens())->refresh($installation, $db, $oauth2); - - $this->assertSame('already-refreshed-token', $result->getAttribute('personalAccessToken')); } protected function fakeOAuth2(bool $emptyUserId = false, bool $throwOnRefresh = false) From a87b2eea03636f7783d6ccdede8404adadbdd577 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 29 Jul 2026 13:59:29 +0530 Subject: [PATCH 02/12] refactor(vcs): return the persisted installation from the exchange Take the document updateDocument() returns instead of mutating a local copy and reading the attributes back. The returned document is the merged row, so callers also see the new $updatedAt rather than a hand-assembled approximation of it. --- src/Appwrite/Vcs/InstallationTokens.php | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/Appwrite/Vcs/InstallationTokens.php b/src/Appwrite/Vcs/InstallationTokens.php index 5d75dcc166..1918d50fa9 100644 --- a/src/Appwrite/Vcs/InstallationTokens.php +++ b/src/Appwrite/Vcs/InstallationTokens.php @@ -104,16 +104,11 @@ class InstallationTokens $accessToken = $oauth2->getAccessToken(''); - $installation = $installation - ->setAttribute('personalAccessToken', $accessToken) - ->setAttribute('personalRefreshToken', $oauth2->getRefreshToken('')) - ->setAttribute('personalAccessTokenExpiry', DateTime::addSeconds(new \DateTime(), (int)$oauth2->getAccessTokenExpiry(''))); - // The provider has already rotated the family, so persist before anything else can fail. - $dbForPlatform->updateDocument('installations', $installation->getId(), new Document([ - 'personalAccessToken' => $installation->getAttribute('personalAccessToken'), - 'personalRefreshToken' => $installation->getAttribute('personalRefreshToken'), - 'personalAccessTokenExpiry' => $installation->getAttribute('personalAccessTokenExpiry'), + $installation = $dbForPlatform->updateDocument('installations', $installation->getId(), new Document([ + 'personalAccessToken' => $accessToken, + 'personalRefreshToken' => $oauth2->getRefreshToken(''), + 'personalAccessTokenExpiry' => DateTime::addSeconds(new \DateTime(), (int)$oauth2->getAccessTokenExpiry('')), ])); if (empty($oauth2->getUserID($accessToken))) { From 042f23f12b841c9fc148301714e85f4398b8caf5 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 29 Jul 2026 14:07:15 +0530 Subject: [PATCH 03/12] docs(vcs): note why the comment lock collection is reused State that reusing it is a simplicity choice and that a generic lock collection is the better home, so the next reader does not have to infer either from the collection name. --- src/Appwrite/Vcs/InstallationTokens.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Appwrite/Vcs/InstallationTokens.php b/src/Appwrite/Vcs/InstallationTokens.php index 1918d50fa9..9e290dd2b4 100644 --- a/src/Appwrite/Vcs/InstallationTokens.php +++ b/src/Appwrite/Vcs/InstallationTokens.php @@ -47,8 +47,9 @@ class InstallationTokens } // Providers rotate refresh tokens: two requests exchanging the same one revokes the family. - // The comment lock collection is reused here, it holds nothing but ids, and the prefix - // keeps these apart from the provider comment ids stored alongside them. + // The comment lock collection is reused for simplicity: it holds nothing but ids, and the + // prefix keeps these apart from the provider comment ids stored alongside them. Ideally + // this moves to a generic lock collection. $lock = 'installation-' . $installation->getId(); $authorization = $dbForPlatform->getAuthorization(); $acquired = false; From 4b73de8f1004e29aaecdffdad6e1f668657acadd Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 29 Jul 2026 14:10:16 +0530 Subject: [PATCH 04/12] fix(vcs): clear the stored pair when the provider rejects it A refresh token the provider no longer accepts was left on the row, so every later call replayed it. Clear the access token, refresh token and expiry instead, which stops the replay and leaves the installation reading as one that needs reconnecting. Providers answer a rejected refresh token with a 200 and an error body, so the signal is an empty access token rather than a thrown request. A throwing call may be a timeout or an outage, and clearing on those would force a reconnect for a passing failure, so the pair survives them. --- src/Appwrite/Vcs/InstallationTokens.php | 15 +++++++ tests/unit/Vcs/InstallationTokensTest.php | 54 +++++++++++++++++++++-- 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/src/Appwrite/Vcs/InstallationTokens.php b/src/Appwrite/Vcs/InstallationTokens.php index 9e290dd2b4..e03a4f13ff 100644 --- a/src/Appwrite/Vcs/InstallationTokens.php +++ b/src/Appwrite/Vcs/InstallationTokens.php @@ -100,11 +100,26 @@ class InstallationTokens try { $oauth2->refreshTokens($installation->getAttribute('personalRefreshToken')); } catch (\Throwable) { + // The call itself failed, so this may be a timeout or a provider outage rather than a + // dead token. Leave the stored pair alone, it may still work once the provider is back. throw new Exception(Exception::GENERAL_PROVIDER_FAILURE, 'Failed to refresh OAuth2 access token. Please reconnect the installation.'); } $accessToken = $oauth2->getAccessToken(''); + if (empty($accessToken)) { + // Providers answer a rejected refresh token with a 200 and an error body, so an empty + // token here means the pair is dead rather than the request having failed. Clear it: + // keeping it replays a token the provider refuses, and empty reads as needs reconnecting. + $dbForPlatform->updateDocument('installations', $installation->getId(), new Document([ + 'personalAccessToken' => '', + 'personalRefreshToken' => '', + 'personalAccessTokenExpiry' => null, + ])); + + throw new Exception(Exception::GENERAL_PROVIDER_FAILURE, 'Failed to refresh OAuth2 access token. Please reconnect the installation.'); + } + // The provider has already rotated the family, so persist before anything else can fail. $installation = $dbForPlatform->updateDocument('installations', $installation->getId(), new Document([ 'personalAccessToken' => $accessToken, diff --git a/tests/unit/Vcs/InstallationTokensTest.php b/tests/unit/Vcs/InstallationTokensTest.php index c32aedc93d..afc0ea09f3 100644 --- a/tests/unit/Vcs/InstallationTokensTest.php +++ b/tests/unit/Vcs/InstallationTokensTest.php @@ -169,6 +169,47 @@ final class InstallationTokensTest extends TestCase } } + public function testRejectedRefreshTokenIsCleared(): void + { + $db = $this->createMock(Database::class); + $db->method('getAuthorization')->willReturn(new Authorization()); + $db->method('getDocument')->willReturn(new Document()); + + $db->expects($this->once()) + ->method('updateDocument') + ->with('installations', 'installation1', $this->callback(function (Document $update) { + $this->assertSame('', $update->getAttribute('personalAccessToken')); + $this->assertSame('', $update->getAttribute('personalRefreshToken')); + $this->assertNull($update->getAttribute('personalAccessTokenExpiry')); + return true; + })) + ->willReturnArgument(2); + + $oauth2 = $this->fakeOAuth2(rejectRefresh: true); + + try { + (new InstallationTokens())->refresh($this->expired(), $db, $oauth2); + $this->fail('Expected an Exception'); + } catch (Exception $e) { + $this->assertSame(Exception::GENERAL_PROVIDER_FAILURE, $e->getType()); + } + } + + public function testProviderOutageLeavesStoredTokenAlone(): void + { + $db = $this->createMock(Database::class); + $db->method('getAuthorization')->willReturn(new Authorization()); + $db->method('getDocument')->willReturn(new Document()); + + // A throwing call may be a timeout, so the pair must survive it. + $db->expects($this->never())->method('updateDocument'); + + $oauth2 = $this->fakeOAuth2(throwOnRefresh: true); + + $this->expectException(Exception::class); + (new InstallationTokens())->refresh($this->expired(), $db, $oauth2); + } + public function testTokenRefreshedByLockHolderIsReused(): void { $db = $this->createMock(Database::class); @@ -249,13 +290,13 @@ final class InstallationTokensTest extends TestCase ]); } - protected function fakeOAuth2(bool $emptyUserId = false, bool $throwOnRefresh = false) + protected function fakeOAuth2(bool $emptyUserId = false, bool $throwOnRefresh = false, bool $rejectRefresh = false) { - return new class ($emptyUserId, $throwOnRefresh) extends OAuth2 { + return new class ($emptyUserId, $throwOnRefresh, $rejectRefresh) extends OAuth2 { public int $refreshCalls = 0; protected array $tokens = []; - public function __construct(protected bool $emptyUserId, protected bool $throwOnRefresh) + public function __construct(protected bool $emptyUserId, protected bool $throwOnRefresh, protected bool $rejectRefresh) { parent::__construct('id', 'secret', ''); } @@ -282,6 +323,13 @@ final class InstallationTokensTest extends TestCase throw new \RuntimeException('refresh token already used'); } + // Providers answer a rejected refresh token with a 200 and an error body. + if ($this->rejectRefresh) { + $this->tokens = []; + + return $this->tokens; + } + $this->tokens = [ 'access_token' => 'fresh-token', 'refresh_token' => 'fresh-refresh', From ff5248756ee97d22e35e00cc8ac8e48e484fdfc4 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 29 Jul 2026 14:16:43 +0530 Subject: [PATCH 05/12] feat(vcs): expose whether an installation still holds a token Add a fresh boolean to the installation response, false once the access token has been cleared because the provider rejected the pair. Without it the console cannot tell a healthy installation from one that needs reconnecting, since the tokens themselves are not part of the response. --- .../Platform/Modules/VCS/Http/Installations/Get.php | 2 ++ .../Platform/Modules/VCS/Http/Installations/XList.php | 4 ++++ src/Appwrite/Utopia/Response/Model/Installation.php | 6 ++++++ tests/e2e/Services/VCS/VCSConsoleClientTest.php | 1 + 4 files changed, 13 insertions(+) diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Installations/Get.php b/src/Appwrite/Platform/Modules/VCS/Http/Installations/Get.php index 4e7b80f5b2..ffded18353 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Installations/Get.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Installations/Get.php @@ -67,6 +67,8 @@ class Get extends Action throw new Exception(Exception::INSTALLATION_NOT_FOUND); } + $installation->setAttribute('fresh', !empty($installation->getAttribute('personalAccessToken'))); + $response->dynamic($installation, Response::MODEL_INSTALLATION); } } diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Installations/XList.php b/src/Appwrite/Platform/Modules/VCS/Http/Installations/XList.php index 628459fb27..b57457a612 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Installations/XList.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Installations/XList.php @@ -112,6 +112,10 @@ class XList extends Action throw new Exception(Exception::DATABASE_QUERY_ORDER_NULL, "The order attribute '{$e->getAttribute()}' had a null value. Cursor pagination requires all documents order attribute values are non-null."); } + foreach ($results as $installation) { + $installation->setAttribute('fresh', !empty($installation->getAttribute('personalAccessToken'))); + } + $response->dynamic(new Document([ 'installations' => $results, 'total' => $total, diff --git a/src/Appwrite/Utopia/Response/Model/Installation.php b/src/Appwrite/Utopia/Response/Model/Installation.php index 29d29e8d5a..e865fa6f1b 100644 --- a/src/Appwrite/Utopia/Response/Model/Installation.php +++ b/src/Appwrite/Utopia/Response/Model/Installation.php @@ -47,6 +47,12 @@ class Installation extends Model 'description' => 'VCS (Version Control System) installation ID.', 'default' => '', 'example' => '5322', + ]) + ->addRule('fresh', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether the installation still holds an access token. When false, it must be reconnected before its repositories can be reached.', + 'default' => true, + 'example' => true, ]); } diff --git a/tests/e2e/Services/VCS/VCSConsoleClientTest.php b/tests/e2e/Services/VCS/VCSConsoleClientTest.php index 134336769f..a1bbf28141 100644 --- a/tests/e2e/Services/VCS/VCSConsoleClientTest.php +++ b/tests/e2e/Services/VCS/VCSConsoleClientTest.php @@ -126,6 +126,7 @@ final class VCSConsoleClientTest extends Scope $this->assertEquals(200, $installation['headers']['status-code']); $this->assertEquals('github', $installation['body']['provider']); $this->assertEquals('appwrite-test', $installation['body']['organization']); + $this->assertTrue($installation['body']['fresh']); } public function testDetectRuntime(): void From c8ff08c21c78463c10ad2523233cae1a0e8244cc Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 29 Jul 2026 14:30:13 +0530 Subject: [PATCH 06/12] fix(vcs): never write a token the provider did not give us Clearing the stored pair when a refresh came back without a token was wrong. The request layer throws only on a 4xx or 5xx, so a timeout or a DNS failure returns an empty body without throwing and reached the same branch as a rejected token. A passing provider failure would therefore have cleared credentials across installations and forced reconnects. The two cases also differ by provider: GitHub answers a dead refresh token with a 200 and an error body, while GitLab and Gitea answer 400, so neither an empty token nor a thrown request identifies a rejection on its own. Bail out instead and leave the row untouched, which also stops the earlier reordering from persisting an empty access token. --- src/Appwrite/Vcs/InstallationTokens.php | 14 +++---------- tests/unit/Vcs/InstallationTokensTest.php | 25 +++++++---------------- 2 files changed, 10 insertions(+), 29 deletions(-) diff --git a/src/Appwrite/Vcs/InstallationTokens.php b/src/Appwrite/Vcs/InstallationTokens.php index e03a4f13ff..474e1e0f75 100644 --- a/src/Appwrite/Vcs/InstallationTokens.php +++ b/src/Appwrite/Vcs/InstallationTokens.php @@ -100,23 +100,15 @@ class InstallationTokens try { $oauth2->refreshTokens($installation->getAttribute('personalRefreshToken')); } catch (\Throwable) { - // The call itself failed, so this may be a timeout or a provider outage rather than a - // dead token. Leave the stored pair alone, it may still work once the provider is back. throw new Exception(Exception::GENERAL_PROVIDER_FAILURE, 'Failed to refresh OAuth2 access token. Please reconnect the installation.'); } $accessToken = $oauth2->getAccessToken(''); + // A provider can answer without a token, by rejecting the refresh token with a 200 and an + // error body or by not answering at all. Both leave nothing worth writing, and persisting + // an empty token would replace a pair that may still be good. if (empty($accessToken)) { - // Providers answer a rejected refresh token with a 200 and an error body, so an empty - // token here means the pair is dead rather than the request having failed. Clear it: - // keeping it replays a token the provider refuses, and empty reads as needs reconnecting. - $dbForPlatform->updateDocument('installations', $installation->getId(), new Document([ - 'personalAccessToken' => '', - 'personalRefreshToken' => '', - 'personalAccessTokenExpiry' => null, - ])); - throw new Exception(Exception::GENERAL_PROVIDER_FAILURE, 'Failed to refresh OAuth2 access token. Please reconnect the installation.'); } diff --git a/tests/unit/Vcs/InstallationTokensTest.php b/tests/unit/Vcs/InstallationTokensTest.php index afc0ea09f3..934220a823 100644 --- a/tests/unit/Vcs/InstallationTokensTest.php +++ b/tests/unit/Vcs/InstallationTokensTest.php @@ -169,39 +169,28 @@ final class InstallationTokensTest extends TestCase } } - public function testRejectedRefreshTokenIsCleared(): void + public function testEmptyTokenResponseIsNotPersisted(): void { $db = $this->createMock(Database::class); $db->method('getAuthorization')->willReturn(new Authorization()); $db->method('getDocument')->willReturn(new Document()); - $db->expects($this->once()) - ->method('updateDocument') - ->with('installations', 'installation1', $this->callback(function (Document $update) { - $this->assertSame('', $update->getAttribute('personalAccessToken')); - $this->assertSame('', $update->getAttribute('personalRefreshToken')); - $this->assertNull($update->getAttribute('personalAccessTokenExpiry')); - return true; - })) - ->willReturnArgument(2); + // A provider that answers without a token leaves nothing worth writing, and the stored + // pair may still be good, so it has to survive. + $db->expects($this->never())->method('updateDocument'); $oauth2 = $this->fakeOAuth2(rejectRefresh: true); - try { - (new InstallationTokens())->refresh($this->expired(), $db, $oauth2); - $this->fail('Expected an Exception'); - } catch (Exception $e) { - $this->assertSame(Exception::GENERAL_PROVIDER_FAILURE, $e->getType()); - } + $this->expectException(Exception::class); + (new InstallationTokens())->refresh($this->expired(), $db, $oauth2); } - public function testProviderOutageLeavesStoredTokenAlone(): void + public function testFailedRefreshCallIsNotPersisted(): void { $db = $this->createMock(Database::class); $db->method('getAuthorization')->willReturn(new Authorization()); $db->method('getDocument')->willReturn(new Document()); - // A throwing call may be a timeout, so the pair must survive it. $db->expects($this->never())->method('updateDocument'); $oauth2 = $this->fakeOAuth2(throwOnRefresh: true); From c690bc919a3f77901603d78f8fd3f27f1696189d Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 29 Jul 2026 14:32:51 +0530 Subject: [PATCH 07/12] Revert "feat(vcs): expose whether an installation still holds a token" This reverts commit ff5248756e. The flag was derived from an empty access token, which nothing sets any more now that clearing a rejected pair has been removed, so it would have reported every installation as healthy including the ones that cannot refresh. Expiry is no better a source: the access token lapses every few hours by design, and the refresh window that actually matters is specific to GitHub. Whether an installation needs reconnecting is only knowable when a refresh is attempted, so it belongs with a stored record of that outcome rather than a value inferred from the row. --- .../Platform/Modules/VCS/Http/Installations/Get.php | 2 -- .../Platform/Modules/VCS/Http/Installations/XList.php | 4 ---- src/Appwrite/Utopia/Response/Model/Installation.php | 6 ------ tests/e2e/Services/VCS/VCSConsoleClientTest.php | 1 - 4 files changed, 13 deletions(-) diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Installations/Get.php b/src/Appwrite/Platform/Modules/VCS/Http/Installations/Get.php index ffded18353..4e7b80f5b2 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Installations/Get.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Installations/Get.php @@ -67,8 +67,6 @@ class Get extends Action throw new Exception(Exception::INSTALLATION_NOT_FOUND); } - $installation->setAttribute('fresh', !empty($installation->getAttribute('personalAccessToken'))); - $response->dynamic($installation, Response::MODEL_INSTALLATION); } } diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Installations/XList.php b/src/Appwrite/Platform/Modules/VCS/Http/Installations/XList.php index b57457a612..628459fb27 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Installations/XList.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Installations/XList.php @@ -112,10 +112,6 @@ class XList extends Action throw new Exception(Exception::DATABASE_QUERY_ORDER_NULL, "The order attribute '{$e->getAttribute()}' had a null value. Cursor pagination requires all documents order attribute values are non-null."); } - foreach ($results as $installation) { - $installation->setAttribute('fresh', !empty($installation->getAttribute('personalAccessToken'))); - } - $response->dynamic(new Document([ 'installations' => $results, 'total' => $total, diff --git a/src/Appwrite/Utopia/Response/Model/Installation.php b/src/Appwrite/Utopia/Response/Model/Installation.php index e865fa6f1b..29d29e8d5a 100644 --- a/src/Appwrite/Utopia/Response/Model/Installation.php +++ b/src/Appwrite/Utopia/Response/Model/Installation.php @@ -47,12 +47,6 @@ class Installation extends Model 'description' => 'VCS (Version Control System) installation ID.', 'default' => '', 'example' => '5322', - ]) - ->addRule('fresh', [ - 'type' => self::TYPE_BOOLEAN, - 'description' => 'Whether the installation still holds an access token. When false, it must be reconnected before its repositories can be reached.', - 'default' => true, - 'example' => true, ]); } diff --git a/tests/e2e/Services/VCS/VCSConsoleClientTest.php b/tests/e2e/Services/VCS/VCSConsoleClientTest.php index a1bbf28141..134336769f 100644 --- a/tests/e2e/Services/VCS/VCSConsoleClientTest.php +++ b/tests/e2e/Services/VCS/VCSConsoleClientTest.php @@ -126,7 +126,6 @@ final class VCSConsoleClientTest extends Scope $this->assertEquals(200, $installation['headers']['status-code']); $this->assertEquals('github', $installation['body']['provider']); $this->assertEquals('appwrite-test', $installation['body']['organization']); - $this->assertTrue($installation['body']['fresh']); } public function testDetectRuntime(): void From 2037bc548d0bc1606060794573e8a3d82c45e532 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 29 Jul 2026 14:36:37 +0530 Subject: [PATCH 08/12] test(vcs): name the fake's empty response for what it is The mode was called rejectRefresh and its comment claimed a rejected refresh token, which is the attribution the production code no longer makes: a provider answering without a token looks identical to a request that timed out. Call it emptyTokens and say so. --- tests/unit/Vcs/InstallationTokensTest.php | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/tests/unit/Vcs/InstallationTokensTest.php b/tests/unit/Vcs/InstallationTokensTest.php index 934220a823..0a554caac6 100644 --- a/tests/unit/Vcs/InstallationTokensTest.php +++ b/tests/unit/Vcs/InstallationTokensTest.php @@ -179,7 +179,7 @@ final class InstallationTokensTest extends TestCase // pair may still be good, so it has to survive. $db->expects($this->never())->method('updateDocument'); - $oauth2 = $this->fakeOAuth2(rejectRefresh: true); + $oauth2 = $this->fakeOAuth2(emptyTokens: true); $this->expectException(Exception::class); (new InstallationTokens())->refresh($this->expired(), $db, $oauth2); @@ -279,13 +279,13 @@ final class InstallationTokensTest extends TestCase ]); } - protected function fakeOAuth2(bool $emptyUserId = false, bool $throwOnRefresh = false, bool $rejectRefresh = false) + protected function fakeOAuth2(bool $emptyUserId = false, bool $throwOnRefresh = false, bool $emptyTokens = false) { - return new class ($emptyUserId, $throwOnRefresh, $rejectRefresh) extends OAuth2 { + return new class ($emptyUserId, $throwOnRefresh, $emptyTokens) extends OAuth2 { public int $refreshCalls = 0; protected array $tokens = []; - public function __construct(protected bool $emptyUserId, protected bool $throwOnRefresh, protected bool $rejectRefresh) + public function __construct(protected bool $emptyUserId, protected bool $throwOnRefresh, protected bool $emptyTokens) { parent::__construct('id', 'secret', ''); } @@ -312,8 +312,9 @@ final class InstallationTokensTest extends TestCase throw new \RuntimeException('refresh token already used'); } - // Providers answer a rejected refresh token with a 200 and an error body. - if ($this->rejectRefresh) { + // A provider can answer without any token, and the reason is not visible here: + // GitHub reports a dead refresh token this way, and so does a timed out request. + if ($this->emptyTokens) { $this->tokens = []; return $this->tokens; From 81b9f929d93752891353a59132b1f0a346e38534 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 29 Jul 2026 14:41:14 +0530 Subject: [PATCH 09/12] fix(vcs): clear the pair when the provider states it refused the token Restores clearing the access token, refresh token and expiry, keyed on the provider saying it refused the token rather than on any failure. The OAuth2 exception already parses the body, so invalid_grant and bad_refresh_token are readable directly, and GitHub's habit of reporting a refusal in a 200 body is handled by reading the returned tokens. A timeout, a 5xx or any other throwable states no reason and leaves the pair intact, so a passing provider failure cannot force a reconnect. The fake's refresh behaviour became a mode rather than a fourth boolean. --- src/Appwrite/Vcs/InstallationTokens.php | 33 ++++++++-- tests/unit/Vcs/InstallationTokensTest.php | 80 +++++++++++++++++++---- 2 files changed, 95 insertions(+), 18 deletions(-) diff --git a/src/Appwrite/Vcs/InstallationTokens.php b/src/Appwrite/Vcs/InstallationTokens.php index 474e1e0f75..01f707a2ac 100644 --- a/src/Appwrite/Vcs/InstallationTokens.php +++ b/src/Appwrite/Vcs/InstallationTokens.php @@ -3,6 +3,7 @@ namespace Appwrite\Vcs; use Appwrite\Auth\OAuth2; +use Appwrite\Auth\OAuth2\Exception as OAuth2Exception; use Appwrite\Extend\Exception; use Utopia\Console; use Utopia\Database\Database; @@ -98,16 +99,22 @@ class InstallationTokens protected function exchange(Document $installation, Database $dbForPlatform, OAuth2 $oauth2): Document { try { - $oauth2->refreshTokens($installation->getAttribute('personalRefreshToken')); + $tokens = $oauth2->refreshTokens($installation->getAttribute('personalRefreshToken')); + } catch (OAuth2Exception $err) { + $this->discard($installation, $dbForPlatform, $err->getError()); + + throw new Exception(Exception::GENERAL_PROVIDER_FAILURE, 'Failed to refresh OAuth2 access token. Please reconnect the installation.'); } catch (\Throwable) { throw new Exception(Exception::GENERAL_PROVIDER_FAILURE, 'Failed to refresh OAuth2 access token. Please reconnect the installation.'); } + // GitHub answers a refused token with a 200 and an error body rather than a 4xx. + $this->discard($installation, $dbForPlatform, $tokens['error'] ?? ''); + $accessToken = $oauth2->getAccessToken(''); - // A provider can answer without a token, by rejecting the refresh token with a 200 and an - // error body or by not answering at all. Both leave nothing worth writing, and persisting - // an empty token would replace a pair that may still be good. + // No token and no stated reason, so the provider may simply not have answered. Persisting + // an empty token here would replace a pair that is possibly still good. if (empty($accessToken)) { throw new Exception(Exception::GENERAL_PROVIDER_FAILURE, 'Failed to refresh OAuth2 access token. Please reconnect the installation.'); } @@ -126,6 +133,24 @@ class InstallationTokens return $installation; } + /** + * Drops the stored pair when the provider states it refused the token, so later calls stop + * replaying it. Only an explicit refusal counts: a timeout or a 5xx may pass, and clearing on + * those would force a reconnect that was never needed. + */ + protected function discard(Document $installation, Database $dbForPlatform, mixed $error): void + { + if (!\is_string($error) || !\in_array($error, ['invalid_grant', 'bad_refresh_token'], true)) { + return; + } + + $dbForPlatform->updateDocument('installations', $installation->getId(), new Document([ + 'personalAccessToken' => '', + 'personalRefreshToken' => '', + 'personalAccessTokenExpiry' => null, + ])); + } + protected function isExpired(?string $expiry): bool { if (empty($expiry)) { diff --git a/tests/unit/Vcs/InstallationTokensTest.php b/tests/unit/Vcs/InstallationTokensTest.php index 0a554caac6..d67ad842e2 100644 --- a/tests/unit/Vcs/InstallationTokensTest.php +++ b/tests/unit/Vcs/InstallationTokensTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Tests\Unit\Vcs; use Appwrite\Auth\OAuth2; +use Appwrite\Auth\OAuth2\Exception as OAuth2Exception; use Appwrite\Extend\Exception; use Appwrite\Vcs\InstallationTokens; use PHPUnit\Framework\TestCase; @@ -169,6 +170,48 @@ final class InstallationTokensTest extends TestCase } } + public function testRefusedRefreshTokenIsCleared(): void + { + $db = $this->createMock(Database::class); + $db->method('getAuthorization')->willReturn(new Authorization()); + $db->method('getDocument')->willReturn(new Document()); + + $db->expects($this->once()) + ->method('updateDocument') + ->with('installations', 'installation1', $this->callback(function (Document $update) { + $this->assertSame('', $update->getAttribute('personalAccessToken')); + $this->assertSame('', $update->getAttribute('personalRefreshToken')); + $this->assertNull($update->getAttribute('personalAccessTokenExpiry')); + return true; + })) + ->willReturnArgument(2); + + $oauth2 = $this->fakeOAuth2(refresh: 'refused'); + + $this->expectException(Exception::class); + (new InstallationTokens())->refresh($this->expired(), $db, $oauth2); + } + + public function testInvalidGrantIsCleared(): void + { + $db = $this->createMock(Database::class); + $db->method('getAuthorization')->willReturn(new Authorization()); + $db->method('getDocument')->willReturn(new Document()); + + $db->expects($this->once()) + ->method('updateDocument') + ->with('installations', 'installation1', $this->callback(function (Document $update) { + $this->assertSame('', $update->getAttribute('personalRefreshToken')); + return true; + })) + ->willReturnArgument(2); + + $oauth2 = $this->fakeOAuth2(refresh: 'invalidGrant'); + + $this->expectException(Exception::class); + (new InstallationTokens())->refresh($this->expired(), $db, $oauth2); + } + public function testEmptyTokenResponseIsNotPersisted(): void { $db = $this->createMock(Database::class); @@ -179,7 +222,7 @@ final class InstallationTokensTest extends TestCase // pair may still be good, so it has to survive. $db->expects($this->never())->method('updateDocument'); - $oauth2 = $this->fakeOAuth2(emptyTokens: true); + $oauth2 = $this->fakeOAuth2(refresh: 'empty'); $this->expectException(Exception::class); (new InstallationTokens())->refresh($this->expired(), $db, $oauth2); @@ -193,7 +236,7 @@ final class InstallationTokensTest extends TestCase $db->expects($this->never())->method('updateDocument'); - $oauth2 = $this->fakeOAuth2(throwOnRefresh: true); + $oauth2 = $this->fakeOAuth2(refresh: 'throw'); $this->expectException(Exception::class); (new InstallationTokens())->refresh($this->expired(), $db, $oauth2); @@ -262,7 +305,7 @@ final class InstallationTokensTest extends TestCase ->with('vcsCommentLocks', 'installation-installation1') ->willReturn(true); - $oauth2 = $this->fakeOAuth2(throwOnRefresh: true); + $oauth2 = $this->fakeOAuth2(refresh: 'throw'); $this->expectException(Exception::class); $this->expectExceptionMessage('Failed to refresh OAuth2 access token'); @@ -279,13 +322,16 @@ final class InstallationTokensTest extends TestCase ]); } - protected function fakeOAuth2(bool $emptyUserId = false, bool $throwOnRefresh = false, bool $emptyTokens = false) + /** + * @param string $refresh One of: ok, refused, invalidGrant, empty, throw. + */ + protected function fakeOAuth2(bool $emptyUserId = false, string $refresh = 'ok') { - return new class ($emptyUserId, $throwOnRefresh, $emptyTokens) extends OAuth2 { + return new class ($emptyUserId, $refresh) extends OAuth2 { public int $refreshCalls = 0; protected array $tokens = []; - public function __construct(protected bool $emptyUserId, protected bool $throwOnRefresh, protected bool $emptyTokens) + public function __construct(protected bool $emptyUserId, protected string $refresh) { parent::__construct('id', 'secret', ''); } @@ -308,16 +354,22 @@ final class InstallationTokensTest extends TestCase public function refreshTokens(string $refreshToken): array { $this->refreshCalls++; - if ($this->throwOnRefresh) { - throw new \RuntimeException('refresh token already used'); - } - // A provider can answer without any token, and the reason is not visible here: - // GitHub reports a dead refresh token this way, and so does a timed out request. - if ($this->emptyTokens) { - $this->tokens = []; + // GitHub states a refused token in a 200 body; GitLab and Gitea answer 400. + // A request that never completed states nothing at all. + switch ($this->refresh) { + case 'refused': + $this->tokens = ['error' => 'bad_refresh_token']; - return $this->tokens; + return $this->tokens; + case 'invalidGrant': + throw new OAuth2Exception('{"error":"invalid_grant"}', 400); + case 'empty': + $this->tokens = []; + + return $this->tokens; + case 'throw': + throw new \RuntimeException('connection timed out'); } $this->tokens = [ From a3b3697938ced39e9a178b7baa55304554059efd Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 29 Jul 2026 14:44:08 +0530 Subject: [PATCH 10/12] refactor(vcs): name the token reset clear, as elsewhere in the codebase --- src/Appwrite/Vcs/InstallationTokens.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Appwrite/Vcs/InstallationTokens.php b/src/Appwrite/Vcs/InstallationTokens.php index 01f707a2ac..c192f6c07b 100644 --- a/src/Appwrite/Vcs/InstallationTokens.php +++ b/src/Appwrite/Vcs/InstallationTokens.php @@ -101,7 +101,7 @@ class InstallationTokens try { $tokens = $oauth2->refreshTokens($installation->getAttribute('personalRefreshToken')); } catch (OAuth2Exception $err) { - $this->discard($installation, $dbForPlatform, $err->getError()); + $this->clear($installation, $dbForPlatform, $err->getError()); throw new Exception(Exception::GENERAL_PROVIDER_FAILURE, 'Failed to refresh OAuth2 access token. Please reconnect the installation.'); } catch (\Throwable) { @@ -109,7 +109,7 @@ class InstallationTokens } // GitHub answers a refused token with a 200 and an error body rather than a 4xx. - $this->discard($installation, $dbForPlatform, $tokens['error'] ?? ''); + $this->clear($installation, $dbForPlatform, $tokens['error'] ?? ''); $accessToken = $oauth2->getAccessToken(''); @@ -138,7 +138,7 @@ class InstallationTokens * replaying it. Only an explicit refusal counts: a timeout or a 5xx may pass, and clearing on * those would force a reconnect that was never needed. */ - protected function discard(Document $installation, Database $dbForPlatform, mixed $error): void + protected function clear(Document $installation, Database $dbForPlatform, mixed $error): void { if (!\is_string($error) || !\in_array($error, ['invalid_grant', 'bad_refresh_token'], true)) { return; From 045078941ca295312f8ffc9135442032baea1400 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 29 Jul 2026 14:47:13 +0530 Subject: [PATCH 11/12] test(vcs): cover the state a cleared installation is left in Once the pair is cleared the expiry is null, which the refresh treats as nothing to do, so the installation comes back untouched and the provider is not called. GitHub then works from its app credentials. That behaviour now carries the recovery for installations whose refresh token is gone, so it should be pinned down rather than inferred. --- tests/unit/Vcs/InstallationTokensTest.php | 24 +++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/unit/Vcs/InstallationTokensTest.php b/tests/unit/Vcs/InstallationTokensTest.php index d67ad842e2..45e7fda6b6 100644 --- a/tests/unit/Vcs/InstallationTokensTest.php +++ b/tests/unit/Vcs/InstallationTokensTest.php @@ -76,6 +76,30 @@ final class InstallationTokensTest extends TestCase $this->assertSame(0, $oauth2->refreshCalls); } + public function testClearedInstallationIsReturnedWithoutCallingTheProvider(): void + { + // The state clear() leaves behind. GitHub works from here on its app credentials, and the + // providers that need the token fail at the adapter with a definite reason. + $installation = new Document([ + '$id' => 'installation1', + 'personalAccessToken' => '', + 'personalRefreshToken' => '', + 'personalAccessTokenExpiry' => null, + ]); + + $db = $this->createMock(Database::class); + $db->method('getAuthorization')->willReturn(new Authorization()); + $db->expects($this->never())->method('updateDocument'); + $db->expects($this->never())->method('createDocument'); + + $oauth2 = $this->fakeOAuth2(); + + $result = (new InstallationTokens())->refresh($installation, $db, $oauth2); + + $this->assertSame('', $result->getAttribute('personalAccessToken')); + $this->assertSame(0, $oauth2->refreshCalls); + } + public function testExpiredTokenIsRefreshedAndPersisted(): void { $db = $this->createMock(Database::class); From 7ad4eea88b8c0ace92d9dbb215b532d264ec9d85 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 29 Jul 2026 14:51:55 +0530 Subject: [PATCH 12/12] test(vcs): express the fake's refresh behaviour as a match The unit suite has no other switch statement, and match drops the two repeated returns along with the fallthrough to the default tokens. --- tests/unit/Vcs/InstallationTokensTest.php | 31 ++++++++--------------- 1 file changed, 11 insertions(+), 20 deletions(-) diff --git a/tests/unit/Vcs/InstallationTokensTest.php b/tests/unit/Vcs/InstallationTokensTest.php index 45e7fda6b6..22d3896810 100644 --- a/tests/unit/Vcs/InstallationTokensTest.php +++ b/tests/unit/Vcs/InstallationTokensTest.php @@ -381,26 +381,17 @@ final class InstallationTokensTest extends TestCase // GitHub states a refused token in a 200 body; GitLab and Gitea answer 400. // A request that never completed states nothing at all. - switch ($this->refresh) { - case 'refused': - $this->tokens = ['error' => 'bad_refresh_token']; - - return $this->tokens; - case 'invalidGrant': - throw new OAuth2Exception('{"error":"invalid_grant"}', 400); - case 'empty': - $this->tokens = []; - - return $this->tokens; - case 'throw': - throw new \RuntimeException('connection timed out'); - } - - $this->tokens = [ - 'access_token' => 'fresh-token', - 'refresh_token' => 'fresh-refresh', - 'expires_in' => 3600, - ]; + $this->tokens = match ($this->refresh) { + 'refused' => ['error' => 'bad_refresh_token'], + 'invalidGrant' => throw new OAuth2Exception('{"error":"invalid_grant"}', 400), + 'empty' => [], + 'throw' => throw new \RuntimeException('connection timed out'), + default => [ + 'access_token' => 'fresh-token', + 'refresh_token' => 'fresh-refresh', + 'expires_in' => 3600, + ], + }; return $this->tokens; }