diff --git a/app/config/vcs.php b/app/config/vcs.php index 3f8a266ea4..f32d95acc8 100644 --- a/app/config/vcs.php +++ b/app/config/vcs.php @@ -14,7 +14,10 @@ use Utopia\VCS\Adapter\Git\GitLab; return [ 'github' => [ 'adapter' => GitHub::class, - 'oauth2' => OAuth2Github::class, + // Each provider owns its own construction quirks (Gitea calls + // setEndpoint(), GitLab JSON-encodes its secret); Factory just + // supplies the resolved env values, so no per-provider branching lives there. + 'oauth2' => fn (string $clientId, string $clientSecret, string $endpoint) => new OAuth2Github($clientId, $clientSecret, ''), 'variables' => [ 'appName' => ['required' => true, 'envVariable' => '_APP_VCS_GITHUB_APP_NAME'], 'privateKey' => ['required' => true, 'envVariable' => '_APP_VCS_GITHUB_PRIVATE_KEY'], @@ -26,7 +29,11 @@ return [ ], 'gitea' => [ 'adapter' => Gitea::class, - 'oauth2' => OAuth2Gitea::class, + 'oauth2' => function (string $clientId, string $clientSecret, string $endpoint) { + $oauth2 = new OAuth2Gitea($clientId, $clientSecret, ''); + $oauth2->setEndpoint($endpoint); + return $oauth2; + }, 'variables' => [ 'endpoint' => ['required' => true, 'envVariable' => '_APP_VCS_GITEA_ENDPOINT'], 'clientId' => ['required' => true, 'envVariable' => '_APP_VCS_GITEA_CLIENT_ID'], @@ -38,7 +45,13 @@ return [ ], 'gitlab' => [ 'adapter' => GitLab::class, - 'oauth2' => OAuth2Gitlab::class, + // Auth\OAuth2\Gitlab is shared with the "Sign in with GitLab" account-login + // provider, which JSON-encodes its secret as {"clientSecret","endpoint"} + // to support a per-project self-hosted endpoint -- match that shape here too. + 'oauth2' => fn (string $clientId, string $clientSecret, string $endpoint) => new OAuth2Gitlab($clientId, \json_encode([ + 'clientSecret' => $clientSecret, + 'endpoint' => $endpoint, + ]), ''), // Only official gitlab.com is supported -- fixed, not configurable. 'endpoint' => 'https://gitlab.com', 'variables' => [ diff --git a/src/Appwrite/Auth/OAuth2/Gitea.php b/src/Appwrite/Auth/OAuth2/Gitea.php index 1b73817bbd..57467130aa 100644 --- a/src/Appwrite/Auth/OAuth2/Gitea.php +++ b/src/Appwrite/Auth/OAuth2/Gitea.php @@ -3,10 +3,9 @@ namespace Appwrite\Auth\OAuth2; use Appwrite\Auth\OAuth2; -use Appwrite\Vcs\EnvOAuth2; -use Utopia\System\System; +use Appwrite\Vcs\RepositoryOAuth2; -class Gitea extends OAuth2 implements EnvOAuth2 +class Gitea extends OAuth2 implements RepositoryOAuth2 { protected string $endpoint = ''; @@ -18,14 +17,6 @@ class Gitea extends OAuth2 implements EnvOAuth2 'read:user', ]; - public static function fromEnv(): OAuth2&EnvOAuth2 - { - $oauth2 = new self(System::getEnv('_APP_VCS_GITEA_CLIENT_ID', ''), System::getEnv('_APP_VCS_GITEA_CLIENT_SECRET', ''), ''); - $oauth2->setEndpoint(System::getEnv('_APP_VCS_GITEA_ENDPOINT', '')); - - return $oauth2; - } - public function setEndpoint(string $endpoint): void { $this->endpoint = \rtrim($endpoint, '/'); diff --git a/src/Appwrite/Auth/OAuth2/Github.php b/src/Appwrite/Auth/OAuth2/Github.php index b3be5243a7..71a52d2604 100644 --- a/src/Appwrite/Auth/OAuth2/Github.php +++ b/src/Appwrite/Auth/OAuth2/Github.php @@ -3,17 +3,11 @@ namespace Appwrite\Auth\OAuth2; use Appwrite\Auth\OAuth2; -use Appwrite\Vcs\EnvOAuth2; +use Appwrite\Vcs\RepositoryOAuth2; use Utopia\Fetch\Client as FetchClient; -use Utopia\System\System; -class Github extends OAuth2 implements EnvOAuth2 +class Github extends OAuth2 implements RepositoryOAuth2 { - public static function fromEnv(): OAuth2&EnvOAuth2 - { - return new self(System::getEnv('_APP_VCS_GITHUB_CLIENT_ID', ''), System::getEnv('_APP_VCS_GITHUB_CLIENT_SECRET', ''), ''); - } - /** * @var array */ diff --git a/src/Appwrite/Auth/OAuth2/Gitlab.php b/src/Appwrite/Auth/OAuth2/Gitlab.php index 9e8c89e51e..bc34e69a28 100644 --- a/src/Appwrite/Auth/OAuth2/Gitlab.php +++ b/src/Appwrite/Auth/OAuth2/Gitlab.php @@ -3,30 +3,20 @@ namespace Appwrite\Auth\OAuth2; use Appwrite\Auth\OAuth2; -use Appwrite\Vcs\EnvOAuth2; -use Utopia\System\System; +use Appwrite\Vcs\RepositoryOAuth2; // Reference Material // https://docs.gitlab.com/ee/api/oauth2.html -class Gitlab extends OAuth2 implements EnvOAuth2 +/** + * Shared with the "Sign in with GitLab" account-login OAuth2 provider, which + * stores its secret as JSON ({"clientSecret": "...", "endpoint": "..."}) to + * support self-hosted GitLab per-project. The VCS flow (see app/config/vcs.php) + * only supports official gitlab.com, but still encodes to that same JSON + * shape so getAppSecret()/getEndpoint() stay correct for both consumers. + */ +class Gitlab extends OAuth2 implements RepositoryOAuth2 { - /** - * This class is shared with the "Sign in with GitLab" account-login - * OAuth2 provider, which stores its secret as JSON - * ({"clientSecret": "...", "endpoint": "..."}) to support self-hosted - * GitLab per-project. The VCS flow only supports official gitlab.com, - * but still encodes to that same JSON shape so getAppSecret()/getEndpoint() - * stay correct for both consumers. - */ - public static function fromEnv(): OAuth2&EnvOAuth2 - { - return new self(System::getEnv('_APP_VCS_GITLAB_CLIENT_ID', ''), \json_encode([ - 'clientSecret' => System::getEnv('_APP_VCS_GITLAB_CLIENT_SECRET', ''), - 'endpoint' => 'https://gitlab.com', - ]), ''); - } - /** * @var array */ diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Gitlab/Events/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/Gitlab/Events/Create.php index 24f4c7b844..e770a930a9 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Gitlab/Events/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Gitlab/Events/Create.php @@ -9,6 +9,7 @@ use Appwrite\Utopia\Request; use Appwrite\Utopia\Response; use Appwrite\Vcs\Factory as VcsFactory; use Appwrite\Vcs\InstallationTokens; +use Appwrite\Vcs\RepositoryPullRequestCleanup; use Utopia\Console; use Utopia\Database\Database; use Utopia\Database\Document; @@ -261,24 +262,7 @@ class Create extends Action return; } - $repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', [ - Query::equal('providerRepositoryId', [$providerRepositoryId]), - Query::orderDesc('$createdAt'), - Query::limit(100), - ])); - - foreach ($repositories as $repository) { - if ($this->resolveGitlabInstallation($repository, $dbForPlatform, $authorization) === null) { - continue; - } - - $providerPullRequestIds = $repository->getAttribute('providerPullRequestIds', []); - - if (\in_array($providerPullRequestId, $providerPullRequestIds)) { - $providerPullRequestIds = \array_diff($providerPullRequestIds, [$providerPullRequestId]); - $authorization->skip(fn () => $dbForPlatform->updateDocument('repositories', $repository->getId(), new Document(['providerPullRequestIds' => $providerPullRequestIds]))); - } - } + (new RepositoryPullRequestCleanup())->remove($dbForPlatform, $authorization, 'gitlab', $providerRepositoryId, $providerPullRequestId); } } } diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Installations/Repositories/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/Installations/Repositories/Create.php index 10d46bc80a..28db0f1b4a 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Installations/Repositories/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Installations/Repositories/Create.php @@ -10,6 +10,7 @@ use Appwrite\SDK\Response as SDKResponse; use Appwrite\Utopia\Response; use Appwrite\Vcs\Factory as VcsFactory; use Appwrite\Vcs\InstallationTokens; +use Appwrite\Vcs\RepositoryOAuth2; use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Query; @@ -80,6 +81,10 @@ class Create extends Action if ($installation->getAttribute('personal', false) === true) { $oauth2 = $vcsFactory->oauth2FromProvider($provider); + if (!$oauth2 instanceof RepositoryOAuth2) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'VCS provider does not support repository creation: ' . $provider); + } + $identity = null; if ($provider === 'github' && (empty($installation->getAttribute('personalAccessToken')) || empty($installation->getAttribute('personalRefreshToken')) || empty($installation->getAttribute('personalAccessTokenExpiry')))) { $identity = $dbForPlatform->findOne('identities', [ diff --git a/src/Appwrite/Vcs/EnvOAuth2.php b/src/Appwrite/Vcs/EnvOAuth2.php deleted file mode 100644 index 6f11df33bc..0000000000 --- a/src/Appwrite/Vcs/EnvOAuth2.php +++ /dev/null @@ -1,18 +0,0 @@ -getEnv($key, 'webhookSecret'); } - public function oauth2FromProvider(string $key): OAuth2&EnvOAuth2 + public function oauth2FromProvider(string $key): OAuth2 { - $class = $this->registry[$key]['oauth2'] ?? null; + $builder = $this->registry[$key]['oauth2'] ?? null; - if ($class === null || !\is_a($class, EnvOAuth2::class, true)) { + if (!\is_callable($builder)) { throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Unsupported VCS provider: ' . $key); } - return $class::fromEnv(); + $clientId = $this->getEnv($key, 'clientId'); + $clientSecret = $this->getEnv($key, 'clientSecret'); + $endpoint = $this->registry[$key]['endpoint'] ?? $this->getEnv($key, 'endpoint'); + + $oauth2 = $builder($clientId, $clientSecret, $endpoint); + + if (!$oauth2 instanceof OAuth2) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'VCS provider "' . $key . '" oauth2 builder returned an invalid client'); + } + + return $oauth2; } protected function getEnv(string $key, string $name): string diff --git a/src/Appwrite/Vcs/RepositoryOAuth2.php b/src/Appwrite/Vcs/RepositoryOAuth2.php new file mode 100644 index 0000000000..6923275bb0 --- /dev/null +++ b/src/Appwrite/Vcs/RepositoryOAuth2.php @@ -0,0 +1,14 @@ +skip(fn () => $dbForPlatform->find('repositories', [ + Query::equal('providerRepositoryId', [$providerRepositoryId]), + Query::orderDesc('$createdAt'), + Query::limit(100), + ])); + + foreach ($repositories as $repository) { + $installation = $authorization->skip(fn () => $dbForPlatform->getDocument('installations', $repository->getAttribute('installationId', ''))); + + if ($installation->isEmpty() || $installation->getAttribute('provider', 'github') !== $provider) { + continue; + } + + $providerPullRequestIds = $repository->getAttribute('providerPullRequestIds', []); + + if (\in_array($providerPullRequestId, $providerPullRequestIds)) { + $providerPullRequestIds = \array_diff($providerPullRequestIds, [$providerPullRequestId]); + $authorization->skip(fn () => $dbForPlatform->updateDocument('repositories', $repository->getId(), new Document(['providerPullRequestIds' => $providerPullRequestIds]))); + } + } + } +} diff --git a/tests/unit/Vcs/FactoryTest.php b/tests/unit/Vcs/FactoryTest.php index f66bb26aef..9c758593bd 100644 --- a/tests/unit/Vcs/FactoryTest.php +++ b/tests/unit/Vcs/FactoryTest.php @@ -6,10 +6,8 @@ namespace Tests\Unit\Vcs; use Appwrite\Auth\OAuth2\Github as OAuth2Github; use Appwrite\Extend\Exception; -use Appwrite\Vcs\EnvOAuth2; use Appwrite\Vcs\Factory; use PHPUnit\Framework\TestCase; -use ReflectionProperty; use Utopia\Cache\Adapter\None; use Utopia\Cache\Cache; use Utopia\Config\Config; @@ -33,7 +31,7 @@ final class FactoryTest extends TestCase foreach ($registry as $key => $entry) { $this->assertTrue(\is_subclass_of($entry['adapter'], Git::class), "Adapter for '{$key}' must extend Git"); - $this->assertContains(EnvOAuth2::class, \class_implements($entry['oauth2']) ?: [], "OAuth2 client for '{$key}' must implement EnvOAuth2"); + $this->assertIsCallable($entry['oauth2'], "OAuth2 builder for '{$key}' must be callable"); $this->assertNotEmpty($entry['variables'], "Variables missing for '{$key}'"); foreach ($entry['variables'] as $name => $variable) { $this->assertStringStartsWith('_APP_VCS_', $variable['envVariable'] ?? '', "Env variable for '{$name}' missing or invalid for '{$key}'"); @@ -127,8 +125,7 @@ final class FactoryTest extends TestCase $factory = new Factory($this->cache(), ['gitlab' => $entry]); $adapter = $factory->fromProvider('gitlab'); - $property = new ReflectionProperty($adapter, 'endpoint'); - $this->assertSame('https://gitlab.com/api/v4', $property->getValue($adapter)); + $this->assertSame('https://gitlab.com/owner/repo', $adapter->getRepositoryUrl('owner', 'repo')); } public function testFromProviderFixedEndpointIgnoresEnv(): void @@ -142,8 +139,7 @@ final class FactoryTest extends TestCase \putenv('_APP_VCS_TEST_ENDPOINT=https://gitlab.example.com'); $adapter = $factory->fromProvider('gitlab'); - $property = new ReflectionProperty($adapter, 'endpoint'); - $this->assertSame('https://gitlab.com/api/v4', $property->getValue($adapter)); + $this->assertSame('https://gitlab.com/owner/repo', $adapter->getRepositoryUrl('owner', 'repo')); } public function testGetWebhookSecret(): void @@ -169,7 +165,7 @@ final class FactoryTest extends TestCase { return [ 'adapter' => GitHub::class, - 'oauth2' => OAuth2Github::class, + 'oauth2' => fn (string $clientId, string $clientSecret, string $endpoint) => new OAuth2Github($clientId, $clientSecret, ''), 'variables' => [ 'appName' => ['required' => true, 'envVariable' => '_APP_VCS_GITHUB_APP_NAME'], 'privateKey' => ['required' => true, 'envVariable' => '_APP_VCS_GITHUB_PRIVATE_KEY'], diff --git a/tests/unit/Vcs/GitlabClosedPullRequestEventTest.php b/tests/unit/Vcs/RepositoryPullRequestCleanupTest.php similarity index 64% rename from tests/unit/Vcs/GitlabClosedPullRequestEventTest.php rename to tests/unit/Vcs/RepositoryPullRequestCleanupTest.php index fefbde0c5e..b289ec9263 100644 --- a/tests/unit/Vcs/GitlabClosedPullRequestEventTest.php +++ b/tests/unit/Vcs/RepositoryPullRequestCleanupTest.php @@ -4,25 +4,15 @@ declare(strict_types=1); namespace Tests\Unit\Vcs; -use Appwrite\Platform\Modules\VCS\Http\Gitlab\Events\Create; -use Appwrite\Vcs\Factory as VcsFactory; -use Appwrite\Vcs\InstallationTokens; +use Appwrite\Vcs\RepositoryPullRequestCleanup; use PHPUnit\Framework\TestCase; -use ReflectionMethod; use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Validator\Authorization; -final class GitlabClosedPullRequestEventTest extends TestCase +final class RepositoryPullRequestCleanupTest extends TestCase { - private Create $handler; - - public function setUp(): void - { - $this->handler = new Create(); - } - - public function testClosedEventOnlyUpdatesGitlabRepositories(): void + public function testRemoveOnlyUpdatesGitlabRepositories(): void { // A GitHub repo and a GitLab repo can share the same numeric // providerRepositoryId since each is scoped to its own server. @@ -64,20 +54,6 @@ final class GitlabClosedPullRequestEventTest extends TestCase return true; })); - $vcsFactory = $this->createStub(VcsFactory::class); - $installationTokens = $this->createStub(InstallationTokens::class); - $deploymentsFactory = fn () => null; - - $this->callHandler('handlePullRequestEvent', [ - 'action' => 'closed', - 'repositoryId' => '5', - 'pullRequestNumber' => 5, - 'external' => true, - ], $vcsFactory, $installationTokens, $dbForPlatform, $authorization, fn () => null, [], $deploymentsFactory); - } - - private function callHandler(string $method, mixed ...$arguments): mixed - { - return (new ReflectionMethod($this->handler, $method))->invoke($this->handler, ...$arguments); + (new RepositoryPullRequestCleanup())->remove($dbForPlatform, $authorization, 'gitlab', '5', 5); } }