From 8439c90bc16332010eaab20a96b534293f6335f0 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Thu, 9 Jul 2026 15:17:53 +0530 Subject: [PATCH 01/12] feat: add Gitea VCS provider Adds Gitea as the first additional VCS provider on the Factory/ InstallationTokens/RepositoryWebhooks foundation from the previous two PRs, using OAuth2 (personal installations) rather than a GitHub-App- style flow. - app/config/vcs.php: gitea registry entry (adapter, env vars). - Appwrite\Auth\OAuth2\Gitea: OAuth2 protocol implementation. - VCS\Http\Authorize\Base / Callback\Base: generic OAuth2 install flow for any OAuth2-based provider, no registry lookup for OAuth2 itself -- each provider's own subclass constructs its own OAuth2 client and picks the browser vs API endpoint, matching the polymorphism-over- branching direction from review (no shared 'createOAuth2' factory). - VCS\Http\Gitea\{Authorize,Callback,Events}: thin per-provider subclasses. - RepositoryWebhooks now takes Factory in its constructor and gates on the adapter's own requiresRepositoryWebhook() capability, so callers invoke it unconditionally on every repository connection without knowing which providers need one; also derives the webhook URL and secret internally instead of taking them as caller-supplied params. - Wired RepositoryWebhooks::ensure() into the four endpoints that actually create a repository connection (Sites/Functions Create and Update) -- the two endpoints that only trigger a deployment against an already-connected repo need no change. - V25 migration + collection resize: personalAccessToken/ personalRefreshToken 256 -> 2048 chars (Gitea's OAuth2 tokens run longer than GitHub's). - Env vars, docker-compose passthrough, mock endpoint for E2E test setup, and _APP_VCS_PROVIDERS exposed via Console Variables so the console knows which providers are actually configured. Gitea's Events webhook handler resolves a fresh adapter per repository connection (via Factory::fromInstallation) rather than one adapter for the whole batch like GitHub App does, since each OAuth2 installation carries its own personal token -- repositories matching the same providerRepositoryId can belong to different Appwrite installations. Known limitation: owner resolution for org-owned Gitea repositories during webhook processing falls back to the token owner's own login (correct for personal repos, the common case); a real fix needs the installation's stored organization threaded through the shared Deployment trait, which the existing GitHub-only createGitDeployments signature doesn't carry today. --- .env | 6 + app/config/collections/platform.php | 4 +- app/config/variables.php | 54 ++++ app/config/vcs.php | 12 + app/controllers/mock.php | 56 ++++ app/init/resources.php | 2 +- docker-compose.yml | 12 + src/Appwrite/Auth/OAuth2/Gitea.php | 213 +++++++++++++++ src/Appwrite/Migration/Version/V25.php | 13 + .../Modules/Console/Http/Variables/Get.php | 1 + .../Functions/Http/Functions/Create.php | 8 + .../Functions/Http/Functions/Update.php | 8 + .../Modules/Sites/Http/Sites/Create.php | 14 +- .../Modules/Sites/Http/Sites/Update.php | 8 + .../Modules/VCS/Http/Authorize/Base.php | 111 ++++++++ .../Modules/VCS/Http/Callback/Base.php | 182 +++++++++++++ .../Modules/VCS/Http/Gitea/Authorize/Get.php | 43 +++ .../Modules/VCS/Http/Gitea/Callback/Get.php | 39 +++ .../Modules/VCS/Http/Gitea/Events/Create.php | 252 ++++++++++++++++++ .../Platform/Modules/VCS/Services/Http.php | 8 + .../Response/Model/ConsoleVariables.php | 7 + src/Appwrite/Vcs/Factory.php | 8 + src/Appwrite/Vcs/RepositoryWebhooks.php | 47 +++- tests/unit/Vcs/RepositoryWebhooksTest.php | 65 +++-- 24 files changed, 1146 insertions(+), 27 deletions(-) create mode 100644 src/Appwrite/Auth/OAuth2/Gitea.php create mode 100644 src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php create mode 100644 src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php create mode 100644 src/Appwrite/Platform/Modules/VCS/Http/Gitea/Authorize/Get.php create mode 100644 src/Appwrite/Platform/Modules/VCS/Http/Gitea/Callback/Get.php create mode 100644 src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php diff --git a/.env b/.env index 63c856cd8d..2d813f024c 100644 --- a/.env +++ b/.env @@ -150,4 +150,10 @@ _APP_VCS_GITHUB_CLIENT_ID= _APP_VCS_GITHUB_CLIENT_SECRET= _APP_VCS_GITHUB_PRIVATE_KEY=disabled _APP_VCS_GITHUB_WEBHOOK_SECRET= +_APP_VCS_GITEA_ENDPOINT= +_APP_VCS_GITEA_BROWSER_ENDPOINT= +_APP_VCS_GITEA_CLIENT_ID= +_APP_VCS_GITEA_CLIENT_SECRET= +_APP_VCS_GITEA_WEBHOOK_SECRET= +_APP_VCS_WEBHOOK_URL= _APP_WEBHOOK_MAX_FAILED_ATTEMPTS=10 diff --git a/app/config/collections/platform.php b/app/config/collections/platform.php index 2aff20aee5..9fd0667d17 100644 --- a/app/config/collections/platform.php +++ b/app/config/collections/platform.php @@ -1842,7 +1842,7 @@ $platformCollections = [ '$id' => ID::custom('personalAccessToken'), 'type' => Database::VAR_STRING, 'format' => '', - 'size' => 256, + 'size' => 2048, 'signed' => true, 'required' => false, 'default' => null, @@ -1864,7 +1864,7 @@ $platformCollections = [ '$id' => ID::custom('personalRefreshToken'), 'type' => Database::VAR_STRING, 'format' => '', - 'size' => 256, + 'size' => 2048, 'signed' => true, 'required' => false, 'default' => null, diff --git a/app/config/variables.php b/app/config/variables.php index 2082868183..a98b6422e3 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -1210,6 +1210,60 @@ return [ 'question' => '', 'filter' => '' ], + [ + 'name' => '_APP_VCS_GITEA_ENDPOINT', + 'description' => 'URL of your self-hosted Gitea instance, reachable from the Appwrite server (e.g. for API calls and webhook token exchange).', + 'introduction' => '2.0.0', + 'default' => '', + 'required' => false, + 'question' => '', + 'filter' => '' + ], + [ + 'name' => '_APP_VCS_GITEA_BROWSER_ENDPOINT', + 'description' => 'URL of your Gitea instance reachable from the browser, if different from _APP_VCS_GITEA_ENDPOINT (e.g. when Appwrite and Gitea are on the same Docker network but Gitea is exposed to the browser on a different host). Falls back to _APP_VCS_GITEA_ENDPOINT when unset.', + 'introduction' => '2.0.0', + 'default' => '', + 'required' => false, + 'question' => '', + 'filter' => '' + ], + [ + 'name' => '_APP_VCS_GITEA_CLIENT_ID', + 'description' => 'Gitea OAuth2 application client ID. You can generate one in your Gitea instance under Settings > Applications.', + 'introduction' => '2.0.0', + 'default' => '', + 'required' => false, + 'question' => '', + 'filter' => '' + ], + [ + 'name' => '_APP_VCS_GITEA_CLIENT_SECRET', + 'description' => 'Gitea OAuth2 application client secret. You can generate one in your Gitea instance under Settings > Applications.', + 'introduction' => '2.0.0', + 'default' => '', + 'required' => false, + 'question' => '', + 'filter' => '' + ], + [ + 'name' => '_APP_VCS_GITEA_WEBHOOK_SECRET', + 'description' => 'Secret used to validate incoming Gitea webhook payloads.', + 'introduction' => '2.0.0', + 'default' => '', + 'required' => false, + 'question' => '', + 'filter' => '' + ], + [ + 'name' => '_APP_VCS_WEBHOOK_URL', + 'description' => 'Base URL Appwrite advertises to self-hosted VCS providers when registering repository webhooks, if different from the public domain (e.g. a Docker-internal address). Falls back to the public domain when unset.', + 'introduction' => '2.0.0', + 'default' => '', + 'required' => false, + 'question' => '', + 'filter' => '' + ], ], ], [ diff --git a/app/config/vcs.php b/app/config/vcs.php index 1f76c4d86e..1f22e474d9 100644 --- a/app/config/vcs.php +++ b/app/config/vcs.php @@ -4,6 +4,7 @@ * VCS provider registry, read by Appwrite\Vcs\Factory. */ +use Utopia\VCS\Adapter\Git\Gitea; use Utopia\VCS\Adapter\Git\GitHub; return [ @@ -20,4 +21,15 @@ return [ ], 'requiredEnvVariables' => ['APP_NAME', 'PRIVATE_KEY', 'APP_ID', 'CLIENT_ID', 'CLIENT_SECRET'], ], + 'gitea' => [ + 'enabled' => true, + 'adapter' => Gitea::class, + 'envVariables' => [ + 'ENDPOINT' => '_APP_VCS_GITEA_ENDPOINT', + 'CLIENT_ID' => '_APP_VCS_GITEA_CLIENT_ID', + 'CLIENT_SECRET' => '_APP_VCS_GITEA_CLIENT_SECRET', + 'WEBHOOK_SECRET' => '_APP_VCS_GITEA_WEBHOOK_SECRET', + ], + 'requiredEnvVariables' => ['ENDPOINT', 'CLIENT_ID', 'CLIENT_SECRET'], + ], ]; diff --git a/app/controllers/mock.php b/app/controllers/mock.php index a2170ab24f..f265a365d6 100644 --- a/app/controllers/mock.php +++ b/app/controllers/mock.php @@ -281,6 +281,62 @@ Http::get('/v1/mock/github/callback') ]); }); +Http::get('/v1/mock/gitea/callback') + ->desc('Create installation document using Gitea OAuth2 tokens') + ->groups(['mock', 'api', 'vcs']) + ->label('scope', 'public') + ->label('docs', false) + ->param('projectId', '', new UID(), 'Project ID of the project where Gitea is to be installed') + ->param('giteaUserId', '', new Text(256), 'Gitea user ID') + ->param('organization', '', new Text(256), 'Gitea username or organization') + ->param('accessToken', '', new Text(2048), 'Gitea access token') + ->inject('response') + ->inject('dbForPlatform') + ->action(function (string $projectId, string $giteaUserId, string $organization, string $accessToken, Response $response, Database $dbForPlatform) { + $isDevelopment = System::getEnv('_APP_ENV', 'development') === 'development'; + + if (!$isDevelopment) { + throw new Exception(Exception::GENERAL_NOT_IMPLEMENTED); + } + + $project = $dbForPlatform->getDocument('projects', $projectId); + + if ($project->isEmpty()) { + throw new Exception(Exception::PROJECT_NOT_FOUND, 'Project with the ID from state could not be found.'); + } + + if (empty($giteaUserId) || empty($organization) || empty($accessToken)) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Missing Gitea installation details'); + } + + $projectInternalId = $project->getSequence(); + $teamId = $project->getAttribute('teamId', ''); + + $installation = $dbForPlatform->createDocument('installations', new Document([ + '$id' => ID::unique(), + '$permissions' => [ + Permission::read(Role::team(ID::custom($teamId))), + Permission::update(Role::team(ID::custom($teamId), 'owner')), + Permission::update(Role::team(ID::custom($teamId), 'developer')), + Permission::delete(Role::team(ID::custom($teamId), 'owner')), + Permission::delete(Role::team(ID::custom($teamId), 'developer')), + ], + 'providerInstallationId' => $giteaUserId, + 'projectId' => $projectId, + 'projectInternalId' => $projectInternalId, + 'provider' => 'gitea', + 'organization' => $organization, + 'personal' => true, + 'personalAccessToken' => $accessToken, + 'personalRefreshToken' => '', + 'personalAccessTokenExpiry' => null, + ])); + + $response->json([ + 'installationId' => $installation->getId(), + ]); + }); + Http::shutdown() ->groups(['mock']) ->inject('response') diff --git a/app/init/resources.php b/app/init/resources.php index 180afd21bd..d02ed42c5a 100644 --- a/app/init/resources.php +++ b/app/init/resources.php @@ -350,7 +350,7 @@ $container->set('promiseAdapter', fn ($register) => $register->get('promiseAdapt $container->set('vcsFactory', fn (Cache $cache) => new VcsFactory($cache), ['cache']); $container->set('installationTokens', fn () => new InstallationTokens(), []); -$container->set('repositoryWebhooks', fn () => new RepositoryWebhooks(), []); +$container->set('repositoryWebhooks', fn (VcsFactory $vcsFactory) => new RepositoryWebhooks($vcsFactory), ['vcsFactory']); $container->set('plan', fn () => []); diff --git a/docker-compose.yml b/docker-compose.yml index 1b5163e1e5..cdbdbce214 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -192,6 +192,12 @@ services: - _APP_VCS_GITHUB_WEBHOOK_SECRET - _APP_VCS_GITHUB_CLIENT_SECRET - _APP_VCS_GITHUB_CLIENT_ID + - _APP_VCS_GITEA_ENDPOINT + - _APP_VCS_GITEA_BROWSER_ENDPOINT + - _APP_VCS_GITEA_CLIENT_ID + - _APP_VCS_GITEA_CLIENT_SECRET + - _APP_VCS_GITEA_WEBHOOK_SECRET + - _APP_VCS_WEBHOOK_URL - _APP_MIGRATIONS_FIREBASE_CLIENT_ID - _APP_MIGRATIONS_FIREBASE_CLIENT_SECRET - _APP_ASSISTANT_OPENAI_API_KEY @@ -472,6 +478,12 @@ services: - _APP_VCS_GITHUB_APP_NAME - _APP_VCS_GITHUB_PRIVATE_KEY - _APP_VCS_GITHUB_APP_ID + - _APP_VCS_GITEA_ENDPOINT + - _APP_VCS_GITEA_BROWSER_ENDPOINT + - _APP_VCS_GITEA_CLIENT_ID + - _APP_VCS_GITEA_CLIENT_SECRET + - _APP_VCS_GITEA_WEBHOOK_SECRET + - _APP_VCS_WEBHOOK_URL - _APP_FUNCTIONS_TIMEOUT - _APP_SITES_TIMEOUT - _APP_COMPUTE_BUILD_TIMEOUT diff --git a/src/Appwrite/Auth/OAuth2/Gitea.php b/src/Appwrite/Auth/OAuth2/Gitea.php new file mode 100644 index 0000000000..af82dd440f --- /dev/null +++ b/src/Appwrite/Auth/OAuth2/Gitea.php @@ -0,0 +1,213 @@ +endpoint = \rtrim($endpoint, '/'); + } + + /** + * @return string + */ + public function getName(): string + { + return 'gitea'; + } + + /** + * @return string + */ + public function getLoginURL(): string + { + return $this->endpoint . '/login/oauth/authorize?' . \http_build_query([ + 'client_id' => $this->appID, + 'redirect_uri' => $this->callback, + 'response_type' => 'code', + 'scope' => \implode(' ', $this->getScopes()), + 'state' => \json_encode($this->state) + ]); + } + + /** + * @param string $code + * + * @return array + */ + protected function getTokens(string $code): array + { + if (empty($this->tokens)) { + $response = $this->request( + 'POST', + $this->endpoint . '/login/oauth/access_token', + ['Content-Type: application/json'], + \json_encode([ + 'client_id' => $this->appID, + 'client_secret' => $this->appSecret, + 'grant_type' => 'authorization_code', + 'redirect_uri' => $this->callback, + 'code' => $code + ]) + ); + + $this->tokens = \json_decode($response, true) ?? []; + } + + return $this->tokens; + } + + /** + * @param string $refreshToken + * + * @return array + */ + public function refreshTokens(string $refreshToken): array + { + $response = $this->request( + 'POST', + $this->endpoint . '/login/oauth/access_token', + ['Content-Type: application/json'], + \json_encode([ + 'client_id' => $this->appID, + 'client_secret' => $this->appSecret, + 'grant_type' => 'refresh_token', + 'refresh_token' => $refreshToken + ]) + ); + + $this->tokens = \json_decode($response, true) ?? []; + + if (empty($this->tokens['refresh_token'])) { + $this->tokens['refresh_token'] = $refreshToken; + } + + return $this->tokens; + } + + /** + * @param string $accessToken + * + * @return string + */ + public function getUserID(string $accessToken): string + { + $user = $this->getUser($accessToken); + + return \strval($user['id'] ?? ''); + } + + /** + * @param string $accessToken + * + * @return string + */ + public function getUserEmail(string $accessToken): string + { + $user = $this->getUser($accessToken); + + return $user['email'] ?? ''; + } + + /** + * @param string $accessToken + * + * @return bool + */ + public function isEmailVerified(string $accessToken): bool + { + $user = $this->getUser($accessToken); + + return $user['verified'] ?? false; + } + + /** + * @param string $accessToken + * + * @return string + */ + public function getUserName(string $accessToken): string + { + $user = $this->getUser($accessToken); + + return $user['full_name'] ?? ''; + } + + /** + * @param string $accessToken + * + * @return string + */ + public function getUserSlug(string $accessToken): string + { + $user = $this->getUser($accessToken); + + return $user['login'] ?? ''; + } + + /** + * @param string $accessToken + * + * @return array + */ + protected function getUser(string $accessToken) + { + if (empty($this->user)) { + $this->user = \json_decode($this->request('GET', $this->endpoint . '/api/v1/user', ['Authorization: token ' . $accessToken]), true) ?? []; + + // Gitea reports the primary email's verification separately + $emails = \json_decode($this->request('GET', $this->endpoint . '/api/v1/user/emails', ['Authorization: token ' . $accessToken]), true); + + foreach (\is_array($emails) ? $emails : [] as $email) { + if (($email['primary'] ?? false) === true) { + $this->user['email'] = $email['email'] ?? ($this->user['email'] ?? ''); + $this->user['verified'] = $email['verified'] ?? false; + break; + } + } + } + + return $this->user; + } + + public function createRepository(string $accessToken, string $repositoryName, bool $private): array + { + $repository = $this->request('POST', $this->endpoint . '/api/v1/user/repos', ['Authorization: token ' . $accessToken, 'Content-Type: application/json'], \json_encode([ + 'name' => $repositoryName, + 'private' => $private + ])); + + return \json_decode($repository, true) ?? []; + } +} diff --git a/src/Appwrite/Migration/Version/V25.php b/src/Appwrite/Migration/Version/V25.php index 800b9b451f..6ee9cc8ab9 100644 --- a/src/Appwrite/Migration/Version/V25.php +++ b/src/Appwrite/Migration/Version/V25.php @@ -63,6 +63,19 @@ class V25 extends Migration } $this->dbForProject->purgeCachedCollection($id); break; + + case 'installations': + if ($collectionType === 'console') { + foreach (['personalAccessToken', 'personalRefreshToken'] as $attribute) { + try { + $this->dbForProject->updateAttribute($id, $attribute, size: 2048); + } catch (Throwable $th) { + Console::warning("Failed to resize attribute \"{$attribute}\" in collection {$id}: {$th->getMessage()}"); + } + } + } + $this->dbForProject->purgeCachedCollection($id); + break; } } } diff --git a/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php b/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php index f1beaeb276..0c58da109c 100644 --- a/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php +++ b/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php @@ -88,6 +88,7 @@ class Get extends Action '_APP_COMPUTE_SIZE_LIMIT' => +System::getEnv('_APP_COMPUTE_SIZE_LIMIT'), '_APP_USAGE_STATS' => System::getEnv('_APP_USAGE_STATS'), '_APP_VCS_ENABLED' => $isVcsEnabled, + '_APP_VCS_PROVIDERS' => $vcsFactory->getProviders(), '_APP_DOMAIN_ENABLED' => $isDomainEnabled, '_APP_ASSISTANT_ENABLED' => $isAssistantEnabled, '_APP_DOMAIN_SITES' => $platform['sitesDomain'], diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php index bbb6ecf265..d12d652749 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php @@ -21,6 +21,7 @@ use Appwrite\Utopia\Database\Validator\CustomId; use Appwrite\Utopia\Response; use Appwrite\Utopia\Response\Model\Rule; use Appwrite\Vcs\Factory; +use Appwrite\Vcs\RepositoryWebhooks; use Utopia\Abuse\Abuse; use Utopia\Config\Config; use Utopia\Database\Database; @@ -129,6 +130,7 @@ class Create extends Base ->inject('dbForPlatform') ->inject('request') ->inject('vcsFactory') + ->inject('repositoryWebhooks') ->inject('authorization') ->inject('platform') ->callback($this->action(...)); @@ -173,6 +175,7 @@ class Create extends Base Database $dbForPlatform, Request $request, Factory $vcsFactory, + RepositoryWebhooks $repositoryWebhooks, Authorization $authorization, array $platform ) { @@ -303,6 +306,11 @@ class Create extends Base 'providerPullRequestIds' => [] ])); + $providerAdapter = $vcsFactory->fromInstallation($installation); + $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); + $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); + $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); + $function->setAttribute('repositoryId', $repository->getId()); $function->setAttribute('repositoryInternalId', $repository->getSequence()); } diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php index f275a15aee..0ebfd9e665 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php @@ -14,6 +14,7 @@ use Appwrite\SDK\Response as SDKResponse; use Appwrite\Task\Validator\Cron; use Appwrite\Utopia\Response; use Appwrite\Vcs\Factory; +use Appwrite\Vcs\RepositoryWebhooks; use Executor\Executor; use Utopia\Config\Config; use Utopia\Database\Database; @@ -113,6 +114,7 @@ class Update extends Base ->inject('publisherForBuilds') ->inject('dbForPlatform') ->inject('vcsFactory') + ->inject('repositoryWebhooks') ->inject('executor') ->inject('authorization') ->inject('platform') @@ -150,6 +152,7 @@ class Update extends Base BuildPublisher $publisherForBuilds, Database $dbForPlatform, Factory $vcsFactory, + RepositoryWebhooks $repositoryWebhooks, Executor $executor, Authorization $authorization, array $platform @@ -243,6 +246,11 @@ class Update extends Base $repositoryId = $repository->getId(); $repositoryInternalId = $repository->getSequence(); + + $providerAdapter = $vcsFactory->fromInstallation($installation); + $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); + $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); + $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); } $live = true; diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php index 3c51c57420..617acb95e4 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php @@ -11,6 +11,8 @@ use Appwrite\SDK\Method; use Appwrite\SDK\Response as SDKResponse; use Appwrite\Utopia\Database\Validator\CustomId; use Appwrite\Utopia\Response; +use Appwrite\Vcs\Factory; +use Appwrite\Vcs\RepositoryWebhooks; use Utopia\Config\Config; use Utopia\Database\Database; use Utopia\Database\Document; @@ -102,6 +104,8 @@ class Create extends Base ->inject('project') ->inject('queueForEvents') ->inject('dbForPlatform') + ->inject('vcsFactory') + ->inject('repositoryWebhooks') ->callback($this->action(...)); } @@ -133,7 +137,9 @@ class Create extends Base Database $dbForProject, Document $project, Event $queueForEvents, - Database $dbForPlatform + Database $dbForPlatform, + Factory $vcsFactory, + RepositoryWebhooks $repositoryWebhooks ) { if (!empty($adapter)) { $configFramework = Config::getParam('frameworks')[$framework] ?? []; @@ -215,6 +221,12 @@ class Create extends Base 'providerPullRequestIds' => [] ]); $repository = $dbForPlatform->createDocument('repositories', $repository); + + $providerAdapter = $vcsFactory->fromInstallation($installation); + $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); + $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); + $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); + $site->setAttribute('repositoryId', $repository->getId()); $site->setAttribute('repositoryInternalId', $repository->getSequence()); diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php index 6604354436..eada5634d8 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php @@ -12,6 +12,7 @@ use Appwrite\SDK\Method; use Appwrite\SDK\Response as SDKResponse; use Appwrite\Utopia\Response; use Appwrite\Vcs\Factory; +use Appwrite\Vcs\RepositoryWebhooks; use Executor\Executor; use Utopia\Config\Config; use Utopia\Database\Database; @@ -109,6 +110,7 @@ class Update extends Base ->inject('publisherForBuilds') ->inject('dbForPlatform') ->inject('vcsFactory') + ->inject('repositoryWebhooks') ->inject('executor') ->inject('platform') ->callback($this->action(...)); @@ -146,6 +148,7 @@ class Update extends Base BuildPublisher $publisherForBuilds, Database $dbForPlatform, Factory $vcsFactory, + RepositoryWebhooks $repositoryWebhooks, Executor $executor, array $platform ) { @@ -241,6 +244,11 @@ class Update extends Base $repository = $dbForPlatform->createDocument('repositories', $repository); $repositoryId = $repository->getId(); $repositoryInternalId = $repository->getSequence(); + + $providerAdapter = $vcsFactory->fromInstallation($installation); + $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); + $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); + $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); } $live = true; diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php b/src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php new file mode 100644 index 0000000000..eeea2c19cd --- /dev/null +++ b/src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php @@ -0,0 +1,111 @@ +setHttpMethod(Action::HTTP_REQUEST_METHOD_GET) + ->setHttpPath('/v1/vcs/' . $key . '/authorize') + ->desc('Create ' . $name . ' installation') + ->groups(['api', 'vcs']) + ->label('scope', 'vcs.read') + ->label('error', APP_VIEWS_DIR . '/general/error.phtml') + ->label('sdk', new Method( + namespace: 'vcs', + group: 'installations', + name: 'create' . $name . 'Installation', + description: '/docs/references/vcs/create-' . $key . '-installation.md', + auth: [AuthType::ADMIN], + responses: [ + new SDKResponse( + code: Response::STATUS_CODE_MOVED_PERMANENTLY, + model: Response::MODEL_NONE, + ) + ], + contentType: ContentType::HTML, + type: MethodType::WEBAUTH, + hide: true, + )) + ->param('success', '', fn ($redirectValidator) => $redirectValidator, 'URL to redirect back to console after a successful installation attempt.', true, ['redirectValidator']) + ->param('failure', '', fn ($redirectValidator) => $redirectValidator, 'URL to redirect back to console after a failed installation attempt.', true, ['redirectValidator']) + ->inject('vcsFactory') + ->inject('response') + ->inject('project') + ->inject('platform') + ->callback($this->action(...)); + } + + public function action( + string $success, + string $failure, + Factory $vcsFactory, + Response $response, + Document $project, + array $platform + ) { + $key = static::getProvider(); + + if (!$vcsFactory->isConfigured($key)) { + throw new Exception(Exception::GENERAL_SERVER_ERROR, static::getProviderName() . ' provider is not configured. Please configure VCS (Version Control System) variables in .env file.'); + } + + $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; + $hostname = $platform['consoleHostname'] ?? ''; + $callback = $protocol . '://' . $hostname . '/v1/vcs/' . $key . '/callback'; + + $oauth2 = $this->createOAuth2($callback, [ + 'projectId' => $project->getId(), + 'success' => $success, + 'failure' => $failure, + ]); + + $response + ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') + ->addHeader('Pragma', 'no-cache') + ->redirect($oauth2->getLoginURL()); + } +} diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php b/src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php new file mode 100644 index 0000000000..1c8ab3e3ad --- /dev/null +++ b/src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php @@ -0,0 +1,182 @@ +setHttpMethod(Action::HTTP_REQUEST_METHOD_GET) + ->setHttpPath('/v1/vcs/' . $key . '/callback') + ->desc('Get installation and authorization from ' . $key) + ->groups(['api', 'vcs']) + ->label('scope', 'public') + ->label('error', APP_VIEWS_DIR . '/general/error.phtml') + ->param('code', '', new Text(2048, 0), 'OAuth2 code. This is a temporary code that the will be later exchanged for an access token.', true) + ->param('state', '', new Text(2048), 'OAuth2 state. Contains info sent when starting authorization flow.', true) + ->inject('response') + ->inject('dbForPlatform') + ->inject('platform') + ->callback($this->action(...)); + } + + public function action( + string $code, + string $state, + Response $response, + Database $dbForPlatform, + array $platform + ) { + $key = static::getProvider(); + + if (empty($state)) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Missing state parameter. Please restart the installation from the Appwrite Console.'); + } + + $state = \json_decode($state, true) ?? []; + $redirectFailure = $state['failure'] ?? ''; + $projectId = $state['projectId'] ?? ''; + + $project = $dbForPlatform->getDocument('projects', $projectId); + + if ($project->isEmpty()) { + $this->failure($response, $redirectFailure, 'Project with the ID from state could not be found.', Exception::PROJECT_NOT_FOUND); + return; + } + + $region = $project->getAttribute('region', 'default'); + $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; + $hostname = $platform['consoleHostname'] ?? ''; + + $defaultState = [ + 'success' => $protocol . '://' . $hostname . "/console/project-$region-$projectId/settings/git-installations", + 'failure' => $protocol . '://' . $hostname . "/console/project-$region-$projectId/settings/git-installations", + ]; + + $state = \array_merge($defaultState, $state); + $redirectSuccess = $state['success'] ?? ''; + $redirectFailure = $state['failure'] ?? ''; + + if (empty($code)) { + $this->failure($response, $redirectFailure, 'OAuth2 authorization code is missing.'); + return; + } + + $callback = $protocol . '://' . $hostname . '/v1/vcs/' . $key . '/callback'; + $oauth2 = $this->createOAuth2($callback); + + $accessToken = $oauth2->getAccessToken($code); + $refreshToken = $oauth2->getRefreshToken($code); + $accessTokenExpiry = DateTime::addSeconds(new \DateTime(), \intval($oauth2->getAccessTokenExpiry($code))); + + if (empty($accessToken)) { + $this->failure($response, $redirectFailure, 'Failed to exchange authorization code for an access token.'); + return; + } + + $providerInstallationId = $oauth2->getUserID($accessToken); + $owner = \method_exists($oauth2, 'getUserSlug') ? $oauth2->getUserSlug($accessToken) : ''; + + if (empty($providerInstallationId) || empty($owner)) { + $this->failure($response, $redirectFailure, 'Failed to get user information from ' . static::getProviderName() . '.'); + return; + } + + $projectInternalId = $project->getSequence(); + + $installation = $dbForPlatform->findOne('installations', [ + Query::equal('providerInstallationId', [$providerInstallationId]), + Query::equal('projectInternalId', [$projectInternalId]), + Query::equal('provider', [$key]), + ]); + + if ($installation->isEmpty()) { + $teamId = $project->getAttribute('teamId', ''); + + $installation = $dbForPlatform->createDocument('installations', new Document([ + '$id' => ID::unique(), + '$permissions' => $this->getPermissions($teamId, $projectId), + 'providerInstallationId' => $providerInstallationId, + 'projectId' => $projectId, + 'projectInternalId' => $projectInternalId, + 'provider' => $key, + 'organization' => $owner, + 'personal' => true, + 'personalRefreshToken' => $refreshToken, + 'personalAccessToken' => $accessToken, + 'personalAccessTokenExpiry' => $accessTokenExpiry, + ])); + } else { + $installation = $dbForPlatform->updateDocument('installations', $installation->getId(), new Document([ + 'organization' => $owner, + 'personal' => true, + 'personalRefreshToken' => $refreshToken, + 'personalAccessToken' => $accessToken, + 'personalAccessTokenExpiry' => $accessTokenExpiry, + ])); + } + + $response + ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') + ->addHeader('Pragma', 'no-cache') + ->redirect($redirectSuccess); + } + + /** + * Redirect back to the console with an error, or throw when no redirect is available. + */ + protected function failure(Response $response, string $redirect, string $error, string $type = Exception::GENERAL_ARGUMENT_INVALID): void + { + if (empty($redirect)) { + throw new Exception($type, $error); + } + + $separator = \str_contains($redirect, '?') ? '&' : '?'; + $response + ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') + ->addHeader('Pragma', 'no-cache') + ->redirect($redirect . $separator . \http_build_query(['error' => $error])); + } +} diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Authorize/Get.php b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Authorize/Get.php new file mode 100644 index 0000000000..e77d2267ec --- /dev/null +++ b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Authorize/Get.php @@ -0,0 +1,43 @@ +setEndpoint($browserEndpoint); + + return $oauth2; + } +} diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Callback/Get.php b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Callback/Get.php new file mode 100644 index 0000000000..09590ab1bb --- /dev/null +++ b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Callback/Get.php @@ -0,0 +1,39 @@ +setEndpoint(System::getEnv('_APP_VCS_GITEA_ENDPOINT', '')); + + return $oauth2; + } +} diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php new file mode 100644 index 0000000000..17f02c577a --- /dev/null +++ b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php @@ -0,0 +1,252 @@ +setHttpMethod(Action::HTTP_REQUEST_METHOD_POST) + ->setHttpPath('/v1/vcs/gitea/events') + ->desc('Create event') + ->groups(['api', 'vcs']) + ->label('scope', 'public') + ->inject('vcsFactory') + ->inject('request') + ->inject('response') + ->inject('dbForPlatform') + ->inject('authorization') + ->inject('getProjectDB') + ->inject('publisherForBuilds') + ->inject('platform') + ->callback($this->action(...)); + } + + public function action( + Factory $vcsFactory, + Request $request, + Response $response, + Database $dbForPlatform, + Authorization $authorization, + callable $getProjectDB, + BuildPublisher $publisherForBuilds, + array $platform + ) { + $vcs = $vcsFactory->fromProvider('gitea'); + + $event = $request->getHeaderLine($vcs->getEventHeaderName(), ''); + Span::add('vcs.gitea.event.name', $event); + + $payload = $request->getRawPayload(); + $signature = $request->getHeaderLine($vcs->getSignatureHeaderName(), ''); + $secretKey = System::getEnv('_APP_VCS_GITEA_WEBHOOK_SECRET', ''); + + $valid = empty($secretKey) ? true : $vcs->validateWebhookEvent($payload, $signature, $secretKey); + Span::add('vcs.gitea.event.signature.valid', $valid); + + if (!$valid) { + throw new Exception(Exception::GENERAL_ACCESS_FORBIDDEN, 'Invalid webhook payload signature. Please make sure the webhook secret has same value in your Gitea repository settings and in the _APP_VCS_GITEA_WEBHOOK_SECRET environment variable'); + } + + $parsedPayload = $vcs->getEvent($event, $payload); + + match ($event) { + 'push' => $this->handlePushEvent($parsedPayload, $vcsFactory, $dbForPlatform, $authorization, $publisherForBuilds, $getProjectDB, $platform), + 'pull_request' => $this->handlePullRequestEvent($parsedPayload, $vcsFactory, $dbForPlatform, $authorization, $publisherForBuilds, $getProjectDB, $platform), + default => null, + }; + + $response->json($parsedPayload); + } + + /** + * Resolves an authenticated adapter for a repository connection's own + * installation. Unlike GitHub App, where one adapter serves every + * repository under an installation, Gitea's OAuth2 installations each + * carry their own personal token — repositories matching the same + * providerRepositoryId can belong to different Appwrite installations. + */ + private function resolveAdapterForRepository(Document $repository, Factory $vcsFactory, Database $dbForPlatform, Authorization $authorization): ?Git + { + $installation = $authorization->skip(fn () => $dbForPlatform->getDocument('installations', $repository->getAttribute('installationId', ''))); + + if ($installation->isEmpty()) { + return null; + } + + try { + return $vcsFactory->fromInstallation($installation); + } catch (\Throwable $error) { + Console::warning("Failed to resolve Gitea adapter for installation '{$installation->getId()}': " . $error->getMessage()); + return null; + } + } + + private function handlePushEvent( + array $parsedPayload, + Factory $vcsFactory, + Database $dbForPlatform, + Authorization $authorization, + BuildPublisher $publisherForBuilds, + callable $getProjectDB, + array $platform, + ) { + $providerBranchDeleted = $parsedPayload['branchDeleted'] ?? false; + $providerBranch = $parsedPayload['branch'] ?? ''; + $providerBranchUrl = $parsedPayload['branchUrl'] ?? ''; + $providerRepositoryId = $parsedPayload['repositoryId'] ?? ''; + $providerRepositoryName = $parsedPayload['repositoryName'] ?? ''; + $providerRepositoryUrl = $parsedPayload['repositoryUrl'] ?? ''; + $providerCommitHash = $parsedPayload['commitHash'] ?? ''; + $providerRepositoryOwner = $parsedPayload['owner'] ?? ''; + $providerCommitAuthorName = $parsedPayload['headCommitAuthorName'] ?? ''; + $providerCommitAuthorEmail = $parsedPayload['headCommitAuthorEmail'] ?? ''; + $providerCommitAuthorUrl = $parsedPayload['authorUrl'] ?? ''; + $providerCommitMessage = $parsedPayload['headCommitMessage'] ?? ''; + $providerCommitUrl = $parsedPayload['headCommitUrl'] ?? ''; + + Span::add('vcs.gitea.event.repo.id', $providerRepositoryId); + Span::add('vcs.gitea.event.repo.name', $providerRepositoryName); + Span::add('vcs.gitea.event.branch', $providerBranch); + + if ($providerCommitAuthorEmail === APP_VCS_GITHUB_EMAIL || $providerBranchDeleted) { + return; + } + + $repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', [ + Query::equal('providerRepositoryId', [$providerRepositoryId]), + Query::limit(100), + ])); + + $providerAffectedFiles = $parsedPayload['affectedFiles'] ?? []; + + foreach ($repositories as $repository) { + $adapter = $this->resolveAdapterForRepository($repository, $vcsFactory, $dbForPlatform, $authorization); + + if ($adapter === null) { + continue; + } + + $providerInstallationId = $repository->getAttribute('installationId', ''); + + $this->createGitDeployments($adapter, $providerInstallationId, [$repository], $providerBranch, $providerBranchUrl, $providerRepositoryName, $providerRepositoryUrl, $providerRepositoryOwner, $providerCommitHash, $providerCommitAuthorName, $providerCommitAuthorUrl, $providerCommitMessage, $providerCommitUrl, '', $providerAffectedFiles, false, $dbForPlatform, $authorization, $publisherForBuilds, $getProjectDB, $platform); + } + } + + private function handlePullRequestEvent( + array $parsedPayload, + Factory $vcsFactory, + Database $dbForPlatform, + Authorization $authorization, + BuildPublisher $publisherForBuilds, + callable $getProjectDB, + array $platform, + ) { + $action = $parsedPayload['action'] ?? ''; + + if ($action === 'opened' || $action === 'reopened' || $action === 'synchronize') { + $providerBranch = $parsedPayload['branch'] ?? ''; + $providerBranchUrl = $parsedPayload['branchUrl'] ?? ''; + $providerRepositoryId = $parsedPayload['repositoryId'] ?? ''; + $providerRepositoryName = $parsedPayload['repositoryName'] ?? ''; + $providerRepositoryUrl = $parsedPayload['repositoryUrl'] ?? ''; + $providerPullRequestId = $parsedPayload['pullRequestNumber'] ?? ''; + $providerCommitHash = $parsedPayload['commitHash'] ?? ''; + $providerRepositoryOwner = $parsedPayload['owner'] ?? ''; + $external = $parsedPayload['external'] ?? true; + $providerCommitUrl = $parsedPayload['headCommitUrl'] ?? ''; + $providerCommitAuthorUrl = $parsedPayload['authorUrl'] ?? ''; + + Span::add('vcs.gitea.event.repo.id', $providerRepositoryId); + Span::add('vcs.gitea.event.repo.name', $providerRepositoryName); + Span::add('vcs.gitea.event.branch', $providerBranch); + + // Ignore sync for non-external. We handle it in the push webhook. + if (!$external && $action === 'synchronize') { + return; + } + + $repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', [ + Query::equal('providerRepositoryId', [$providerRepositoryId]), + Query::orderDesc('$createdAt'), + Query::limit(100), + ])); + + foreach ($repositories as $repository) { + $adapter = $this->resolveAdapterForRepository($repository, $vcsFactory, $dbForPlatform, $authorization); + + if ($adapter === null) { + continue; + } + + $providerInstallationId = $repository->getAttribute('installationId', ''); + + try { + $commitDetails = $adapter->getCommit($providerRepositoryOwner, $providerRepositoryName, $providerCommitHash); + } catch (\Throwable $e) { + Console::warning("Failed to fetch commit '{$providerCommitHash}': " . $e->getMessage()); + $commitDetails = []; + } + $providerCommitAuthor = $commitDetails['commitAuthor'] ?? ''; + $providerCommitMessage = $commitDetails['commitMessage'] ?? ''; + + $prFiles = $adapter->getPullRequestFiles($providerRepositoryOwner, $providerRepositoryName, $providerPullRequestId); + $providerAffectedFiles = [ + ...array_column($prFiles, 'filename'), + ...array_filter(array_column($prFiles, 'previous_filename')), + ]; + + $this->createGitDeployments($adapter, $providerInstallationId, [$repository], $providerBranch, $providerBranchUrl, $providerRepositoryName, $providerRepositoryUrl, $providerRepositoryOwner, $providerCommitHash, $providerCommitAuthor, $providerCommitAuthorUrl, $providerCommitMessage, $providerCommitUrl, $providerPullRequestId, $providerAffectedFiles, $external, $dbForPlatform, $authorization, $publisherForBuilds, $getProjectDB, $platform); + } + } elseif ($action === 'closed') { + $providerRepositoryId = $parsedPayload['repositoryId'] ?? ''; + $providerPullRequestId = $parsedPayload['pullRequestNumber'] ?? ''; + $external = $parsedPayload['external'] ?? true; + + if (!$external) { + return; + } + + $repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', [ + Query::equal('providerRepositoryId', [$providerRepositoryId]), + Query::orderDesc('$createdAt'), + Query::limit(100), + ])); + + foreach ($repositories as $repository) { + $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/src/Appwrite/Platform/Modules/VCS/Services/Http.php b/src/Appwrite/Platform/Modules/VCS/Services/Http.php index ae766ad00e..dfdd6c8a5f 100644 --- a/src/Appwrite/Platform/Modules/VCS/Services/Http.php +++ b/src/Appwrite/Platform/Modules/VCS/Services/Http.php @@ -2,6 +2,9 @@ namespace Appwrite\Platform\Modules\VCS\Services; +use Appwrite\Platform\Modules\VCS\Http\Gitea\Authorize\Get as GetGiteaAuthorize; +use Appwrite\Platform\Modules\VCS\Http\Gitea\Callback\Get as GetGiteaCallback; +use Appwrite\Platform\Modules\VCS\Http\Gitea\Events\Create as CreateGiteaEvent; use Appwrite\Platform\Modules\VCS\Http\GitHub\Authorize\External\Update as UpdateExternalDeployment; use Appwrite\Platform\Modules\VCS\Http\GitHub\Authorize\Get as GetGitHubAuthorize; use Appwrite\Platform\Modules\VCS\Http\GitHub\Callback\Get as GetGitHubCallback; @@ -28,6 +31,10 @@ class Http extends Service $this->addAction(GetGitHubCallback::getName(), new GetGitHubCallback()); $this->addAction(UpdateExternalDeployment::getName(), new UpdateExternalDeployment()); + // Gitea Authorization & Callback + $this->addAction(GetGiteaAuthorize::getName(), new GetGiteaAuthorize()); + $this->addAction(GetGiteaCallback::getName(), new GetGiteaCallback()); + // Installations $this->addAction(GetInstallation::getName(), new GetInstallation()); $this->addAction(ListInstallations::getName(), new ListInstallations()); @@ -43,5 +50,6 @@ class Http extends Service // Events $this->addAction(CreateGitHubEvent::getName(), new CreateGitHubEvent()); + $this->addAction(CreateGiteaEvent::getName(), new CreateGiteaEvent()); } } diff --git a/src/Appwrite/Utopia/Response/Model/ConsoleVariables.php b/src/Appwrite/Utopia/Response/Model/ConsoleVariables.php index 5ca01ca010..ab179d04ee 100644 --- a/src/Appwrite/Utopia/Response/Model/ConsoleVariables.php +++ b/src/Appwrite/Utopia/Response/Model/ConsoleVariables.php @@ -64,6 +64,13 @@ class ConsoleVariables extends Model 'default' => false, 'example' => true, ]) + ->addRule('_APP_VCS_PROVIDERS', [ + 'type' => self::TYPE_STRING, + 'description' => 'List of configured VCS providers.', + 'default' => [], + 'example' => ['github'], + 'array' => true, + ]) ->addRule('_APP_DOMAIN_ENABLED', [ 'type' => self::TYPE_BOOLEAN, 'description' => 'Defines if main domain is configured. If so, custom domains can be created.', diff --git a/src/Appwrite/Vcs/Factory.php b/src/Appwrite/Vcs/Factory.php index edd7f5e939..3a6bb687a8 100644 --- a/src/Appwrite/Vcs/Factory.php +++ b/src/Appwrite/Vcs/Factory.php @@ -117,6 +117,14 @@ class Factory return $adapter; } + /** + * Webhook secret configured for a provider, empty if none is set. + */ + public function getWebhookSecret(string $key): string + { + return $this->getEnv($key, 'WEBHOOK_SECRET'); + } + protected function getEnv(string $key, string $name): string { $variable = $this->registry[$key]['envVariables'][$name] ?? ''; diff --git a/src/Appwrite/Vcs/RepositoryWebhooks.php b/src/Appwrite/Vcs/RepositoryWebhooks.php index a39a679bc8..905634a493 100644 --- a/src/Appwrite/Vcs/RepositoryWebhooks.php +++ b/src/Appwrite/Vcs/RepositoryWebhooks.php @@ -6,21 +6,29 @@ use Appwrite\Extend\Exception; use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Query; +use Utopia\System\System; use Utopia\VCS\Adapter\Git; /** * Creates per-repository webhooks for self-hosted providers. * - * GitHub App deliveries need no per-repository webhook, so no endpoint calls - * this yet; it exists so a self-hosted OAuth2 provider (e.g. Gitea) can wire - * into it without inventing its own idempotency check. + * Callers invoke this unconditionally on every repository connection; it + * no-ops for providers whose adapter reports no per-repository webhook is + * needed (e.g. GitHub App, which delivers events platform-wide), so no + * endpoint needs to know which providers require one. */ class RepositoryWebhooks { + public function __construct( + protected Factory $vcsFactory, + ) { + } + /** - * Creates a webhook for $owner/$repositoryName unless a `repositories` - * document already exists for this installation + provider repository - * (an earlier connection already went through this path). + * Creates a webhook for $owner/$repositoryName unless the adapter's + * provider doesn't need one, or a `repositories` document already + * exists for this installation + provider repository (an earlier + * connection already went through this path). */ public function ensure( Git $adapter, @@ -29,9 +37,11 @@ class RepositoryWebhooks string $providerRepositoryId, string $owner, string $repositoryName, - string $url, - string $secret, ): void { + if (!$adapter->requiresRepositoryWebhook()) { + return; + } + $connections = $dbForPlatform->count('repositories', [ Query::equal('installationInternalId', [$installation->getSequence()]), Query::equal('providerRepositoryId', [$providerRepositoryId]), @@ -41,10 +51,31 @@ class RepositoryWebhooks return; } + $provider = $installation->getAttribute('provider', 'github'); + $url = $this->buildWebhookUrl($provider); + $secret = $this->vcsFactory->getWebhookSecret($provider); + try { $adapter->createWebhook($owner, $repositoryName, $url, $secret); } catch (\Throwable $error) { throw new Exception(Exception::GENERAL_PROVIDER_FAILURE, 'Failed to create repository webhook: ' . $error->getMessage()); } } + + protected function buildWebhookUrl(string $provider): string + { + $endpoint = System::getEnv('_APP_VCS_WEBHOOK_URL', ''); + if (empty($endpoint)) { + $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; + $endpoint = $protocol . '://' . System::getEnv('_APP_DOMAIN', 'localhost'); + } + + // Accept the base with or without a trailing /v1 (both are used in practice). + $endpoint = \rtrim($endpoint, '/'); + if (\str_ends_with($endpoint, '/v1')) { + $endpoint = \substr($endpoint, 0, -3); + } + + return $endpoint . '/v1/vcs/' . $provider . '/events'; + } } diff --git a/tests/unit/Vcs/RepositoryWebhooksTest.php b/tests/unit/Vcs/RepositoryWebhooksTest.php index 6f5a546ee1..40f3e5db3d 100644 --- a/tests/unit/Vcs/RepositoryWebhooksTest.php +++ b/tests/unit/Vcs/RepositoryWebhooksTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Tests\Unit\Vcs; use Appwrite\Extend\Exception; +use Appwrite\Vcs\Factory; use Appwrite\Vcs\RepositoryWebhooks; use PHPUnit\Framework\TestCase; use Utopia\Database\Database; @@ -13,46 +14,80 @@ use Utopia\VCS\Adapter\Git; final class RepositoryWebhooksTest extends TestCase { + public function testSkipsWhenAdapterDoesNotRequireWebhook(): void + { + $adapter = $this->createMock(Git::class); + $adapter->method('requiresRepositoryWebhook')->willReturn(false); + $adapter->expects($this->never())->method('createWebhook'); + + $db = $this->createMock(Database::class); + $db->expects($this->never())->method('count'); + + $installation = new Document(['$sequence' => 1, 'provider' => 'github']); + + $this->ensure($adapter, $installation, $db, $this->factory('secret')); + } + public function testCreatesWebhookWhenNoExistingConnection(): void { - $db = $this->createMock(Database::class); - $db->expects($this->once())->method('count')->willReturn(1); - $adapter = $this->createMock(Git::class); + $adapter->method('requiresRepositoryWebhook')->willReturn(true); $adapter->expects($this->once()) ->method('createWebhook') ->with('owner', 'repo', 'https://example.com/v1/vcs/gitea/events', 'secret') ->willReturn(1); - $installation = new Document(['$sequence' => 1]); + $db = $this->createMock(Database::class); + $db->expects($this->once())->method('count')->willReturn(1); - (new RepositoryWebhooks())->ensure($adapter, $installation, $db, 'repo-1', 'owner', 'repo', 'https://example.com/v1/vcs/gitea/events', 'secret'); + $installation = new Document(['$sequence' => 1, 'provider' => 'gitea']); + + $this->ensure($adapter, $installation, $db, $this->factory('secret')); } public function testSkipsWhenRepositoryAlreadyConnected(): void { + $adapter = $this->createMock(Git::class); + $adapter->method('requiresRepositoryWebhook')->willReturn(true); + $adapter->expects($this->never())->method('createWebhook'); + $db = $this->createMock(Database::class); $db->expects($this->once())->method('count')->willReturn(2); - $adapter = $this->createMock(Git::class); - $adapter->expects($this->never())->method('createWebhook'); + $installation = new Document(['$sequence' => 1, 'provider' => 'gitea']); - $installation = new Document(['$sequence' => 1]); - - (new RepositoryWebhooks())->ensure($adapter, $installation, $db, 'repo-1', 'owner', 'repo', 'https://example.com/v1/vcs/gitea/events', 'secret'); + $this->ensure($adapter, $installation, $db, $this->factory('secret')); } public function testAdapterFailureIsWrapped(): void { + $adapter = $this->createMock(Git::class); + $adapter->method('requiresRepositoryWebhook')->willReturn(true); + $adapter->method('createWebhook')->willThrowException(new \RuntimeException('provider unreachable')); + $db = $this->createMock(Database::class); $db->method('count')->willReturn(1); - $adapter = $this->createMock(Git::class); - $adapter->method('createWebhook')->willThrowException(new \RuntimeException('provider unreachable')); - - $installation = new Document(['$sequence' => 1]); + $installation = new Document(['$sequence' => 1, 'provider' => 'gitea']); $this->expectException(Exception::class); - (new RepositoryWebhooks())->ensure($adapter, $installation, $db, 'repo-1', 'owner', 'repo', 'https://example.com/v1/vcs/gitea/events', 'secret'); + $this->ensure($adapter, $installation, $db, $this->factory('secret')); + } + + protected function ensure(Git $adapter, Document $installation, Database $db, Factory $vcsFactory): void + { + \putenv('_APP_VCS_WEBHOOK_URL=https://example.com'); + + (new RepositoryWebhooks($vcsFactory))->ensure($adapter, $installation, $db, 'repo-1', 'owner', 'repo'); + + \putenv('_APP_VCS_WEBHOOK_URL'); + } + + protected function factory(string $secret): Factory + { + $factory = $this->createMock(Factory::class); + $factory->method('getWebhookSecret')->willReturn($secret); + + return $factory; } } From 587073d9368ff5c1b8fb64ea4cc1853dfbcf1231 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Thu, 9 Jul 2026 18:29:01 +0530 Subject: [PATCH 02/12] fix: address Greptile findings on Gitea webhook wiring and OAuth2 scope - Widened Gitea OAuth2 scopes from read:user alone to also include read:repository, write:repository, read:organization. The resulting token is reused for every VCS operation on the installation (list repos, read contents, create webhooks), not just login, so read:user alone would fail with 403s on nearly every call. - Made WEBHOOK_SECRET required for Gitea (added to requiredEnvVariables in app/config/vcs.php) and changed the validation guard in Gitea/Events/Create.php to fail closed instead of open when it's unset. GitHub App deliveries stay validated independently via a signed JWT even without a webhook secret configured; Gitea has no equivalent fallback, so an empty secret there meant no verification at all. - Fixed cross-provider repository ID collision: Gitea and GitHub repository IDs are independent numeric sequences and can collide. repositories has no provider attribute to filter the query on, so resolveAdapterForRepository() now checks the matched installation's own provider and skips anything that isn't 'gitea', instead of silently building a mismatched adapter for a same-ID GitHub repo. - Fixed the orphaned-repository-document bug across all four connect paths (Functions/Sites Create/Update): getOwnerName/getRepositoryName/ ensure() now only run when the adapter's requiresRepositoryWebhook() is true (GitHub's is false, so this also removes two previously unconditional GitHub API round-trips on every GitHub connect), and any failure during that block now deletes the just-created repositories document before rethrowing -- otherwise a failed first attempt left a row behind that made every retry's connection count look like a repeat, silently skipping webhook creation forever. --- app/config/vcs.php | 5 ++++- src/Appwrite/Auth/OAuth2/Gitea.php | 6 ++++++ .../Modules/Functions/Http/Functions/Create.php | 13 ++++++++++--- .../Modules/Functions/Http/Functions/Update.php | 13 ++++++++++--- .../Platform/Modules/Sites/Http/Sites/Create.php | 16 +++++++++++++--- .../Platform/Modules/Sites/Http/Sites/Update.php | 13 ++++++++++--- .../Modules/VCS/Http/Gitea/Events/Create.php | 14 +++++++++++++- 7 files changed, 66 insertions(+), 14 deletions(-) diff --git a/app/config/vcs.php b/app/config/vcs.php index 1f22e474d9..787fb07ecc 100644 --- a/app/config/vcs.php +++ b/app/config/vcs.php @@ -30,6 +30,9 @@ return [ 'CLIENT_SECRET' => '_APP_VCS_GITEA_CLIENT_SECRET', 'WEBHOOK_SECRET' => '_APP_VCS_GITEA_WEBHOOK_SECRET', ], - 'requiredEnvVariables' => ['ENDPOINT', 'CLIENT_ID', 'CLIENT_SECRET'], + // WEBHOOK_SECRET is required (unlike GitHub's) because a Gitea webhook + // has no other verification layer -- GitHub App deliveries also carry + // a signed JWT Appwrite always validates independently of the secret. + 'requiredEnvVariables' => ['ENDPOINT', 'CLIENT_ID', 'CLIENT_SECRET', 'WEBHOOK_SECRET'], ], ]; diff --git a/src/Appwrite/Auth/OAuth2/Gitea.php b/src/Appwrite/Auth/OAuth2/Gitea.php index af82dd440f..dd649047d1 100644 --- a/src/Appwrite/Auth/OAuth2/Gitea.php +++ b/src/Appwrite/Auth/OAuth2/Gitea.php @@ -27,8 +27,14 @@ class Gitea extends OAuth2 /** * @var array */ + // The resulting personal token is reused for every VCS operation on the + // installation (list/create repos, read contents, create webhooks, + // comment on PRs) via Factory::fromInstallation(), not just login. protected array $scopes = [ 'read:user', + 'read:repository', + 'write:repository', + 'read:organization', ]; /** diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php index d12d652749..613efe402c 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php @@ -307,9 +307,16 @@ class Create extends Base ])); $providerAdapter = $vcsFactory->fromInstallation($installation); - $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); - $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); - $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); + if ($providerAdapter->requiresRepositoryWebhook()) { + try { + $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); + $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); + $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); + } catch (\Throwable $error) { + $dbForPlatform->deleteDocument('repositories', $repository->getId()); + throw $error; + } + } $function->setAttribute('repositoryId', $repository->getId()); $function->setAttribute('repositoryInternalId', $repository->getSequence()); diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php index 0ebfd9e665..7418dc809a 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php @@ -248,9 +248,16 @@ class Update extends Base $repositoryInternalId = $repository->getSequence(); $providerAdapter = $vcsFactory->fromInstallation($installation); - $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); - $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); - $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); + if ($providerAdapter->requiresRepositoryWebhook()) { + try { + $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); + $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); + $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); + } catch (\Throwable $error) { + $dbForPlatform->deleteDocument('repositories', $repository->getId()); + throw $error; + } + } } $live = true; diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php index 617acb95e4..d6e00b39e5 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php @@ -223,9 +223,19 @@ class Create extends Base $repository = $dbForPlatform->createDocument('repositories', $repository); $providerAdapter = $vcsFactory->fromInstallation($installation); - $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); - $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); - $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); + if ($providerAdapter->requiresRepositoryWebhook()) { + try { + $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); + $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); + $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); + } catch (\Throwable $error) { + // Don't leave an orphaned repositories document behind -- it + // would make the next retry's connection count look like a + // repeat, silently skipping webhook creation. + $dbForPlatform->deleteDocument('repositories', $repository->getId()); + throw $error; + } + } $site->setAttribute('repositoryId', $repository->getId()); $site->setAttribute('repositoryInternalId', $repository->getSequence()); diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php index eada5634d8..83de5f3c2f 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php @@ -246,9 +246,16 @@ class Update extends Base $repositoryInternalId = $repository->getSequence(); $providerAdapter = $vcsFactory->fromInstallation($installation); - $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); - $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); - $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); + if ($providerAdapter->requiresRepositoryWebhook()) { + try { + $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); + $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); + $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); + } catch (\Throwable $error) { + $dbForPlatform->deleteDocument('repositories', $repository->getId()); + throw $error; + } + } } $live = true; diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php index 17f02c577a..33fe0b3e10 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php @@ -67,7 +67,11 @@ class Create extends Action $signature = $request->getHeaderLine($vcs->getSignatureHeaderName(), ''); $secretKey = System::getEnv('_APP_VCS_GITEA_WEBHOOK_SECRET', ''); - $valid = empty($secretKey) ? true : $vcs->validateWebhookEvent($payload, $signature, $secretKey); + // Fail closed, unlike GitHub App deliveries: those also carry a + // signed JWT Appwrite always validates, so an empty webhook secret + // there still leaves a real check in place. Gitea has no such + // fallback -- an empty secret here would mean no verification at all. + $valid = !empty($secretKey) && $vcs->validateWebhookEvent($payload, $signature, $secretKey); Span::add('vcs.gitea.event.signature.valid', $valid); if (!$valid) { @@ -100,6 +104,14 @@ class Create extends Action return null; } + // `repositories` has no provider attribute -- providerRepositoryId is + // provider-scoped numeric IDs from independent servers, so a GitHub + // and a Gitea repository can collide on the same ID. Filter by the + // matched installation's own provider instead of the query. + if ($installation->getAttribute('provider', 'github') !== 'gitea') { + return null; + } + try { return $vcsFactory->fromInstallation($installation); } catch (\Throwable $error) { From 797111dee4c279d27c8cc4054501cb7474d3b094 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Thu, 9 Jul 2026 19:05:21 +0530 Subject: [PATCH 03/12] refactor: migrate Gitea webhook wiring to closure-resolved vcs adapters Sites/Create and the Gitea events handler were the two remaining call sites still injecting Factory directly; they now use vcsForInstallation/vcsForProvider like everything else in the stack. --- .../Modules/Sites/Http/Sites/Create.php | 7 +++--- .../Modules/VCS/Http/Gitea/Events/Create.php | 25 ++++++++++--------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php index d6e00b39e5..3f8d35f78a 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php @@ -11,7 +11,6 @@ use Appwrite\SDK\Method; use Appwrite\SDK\Response as SDKResponse; use Appwrite\Utopia\Database\Validator\CustomId; use Appwrite\Utopia\Response; -use Appwrite\Vcs\Factory; use Appwrite\Vcs\RepositoryWebhooks; use Utopia\Config\Config; use Utopia\Database\Database; @@ -104,7 +103,7 @@ class Create extends Base ->inject('project') ->inject('queueForEvents') ->inject('dbForPlatform') - ->inject('vcsFactory') + ->inject('vcsForInstallation') ->inject('repositoryWebhooks') ->callback($this->action(...)); } @@ -138,7 +137,7 @@ class Create extends Base Document $project, Event $queueForEvents, Database $dbForPlatform, - Factory $vcsFactory, + callable $vcsForInstallation, RepositoryWebhooks $repositoryWebhooks ) { if (!empty($adapter)) { @@ -222,7 +221,7 @@ class Create extends Base ]); $repository = $dbForPlatform->createDocument('repositories', $repository); - $providerAdapter = $vcsFactory->fromInstallation($installation); + $providerAdapter = $vcsForInstallation($installation); if ($providerAdapter->requiresRepositoryWebhook()) { try { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php index 33fe0b3e10..1d1dd99dbf 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php @@ -8,7 +8,6 @@ use Appwrite\Platform\Action; use Appwrite\Platform\Modules\VCS\Http\GitHub\Deployment; use Appwrite\Utopia\Request; use Appwrite\Utopia\Response; -use Appwrite\Vcs\Factory; use Utopia\Console; use Utopia\Database\Database; use Utopia\Database\Document; @@ -37,7 +36,8 @@ class Create extends Action ->desc('Create event') ->groups(['api', 'vcs']) ->label('scope', 'public') - ->inject('vcsFactory') + ->inject('vcsForProvider') + ->inject('vcsForInstallation') ->inject('request') ->inject('response') ->inject('dbForPlatform') @@ -49,7 +49,8 @@ class Create extends Action } public function action( - Factory $vcsFactory, + callable $vcsForProvider, + callable $vcsForInstallation, Request $request, Response $response, Database $dbForPlatform, @@ -58,7 +59,7 @@ class Create extends Action BuildPublisher $publisherForBuilds, array $platform ) { - $vcs = $vcsFactory->fromProvider('gitea'); + $vcs = $vcsForProvider('gitea'); $event = $request->getHeaderLine($vcs->getEventHeaderName(), ''); Span::add('vcs.gitea.event.name', $event); @@ -81,8 +82,8 @@ class Create extends Action $parsedPayload = $vcs->getEvent($event, $payload); match ($event) { - 'push' => $this->handlePushEvent($parsedPayload, $vcsFactory, $dbForPlatform, $authorization, $publisherForBuilds, $getProjectDB, $platform), - 'pull_request' => $this->handlePullRequestEvent($parsedPayload, $vcsFactory, $dbForPlatform, $authorization, $publisherForBuilds, $getProjectDB, $platform), + 'push' => $this->handlePushEvent($parsedPayload, $vcsForInstallation, $dbForPlatform, $authorization, $publisherForBuilds, $getProjectDB, $platform), + 'pull_request' => $this->handlePullRequestEvent($parsedPayload, $vcsForInstallation, $dbForPlatform, $authorization, $publisherForBuilds, $getProjectDB, $platform), default => null, }; @@ -96,7 +97,7 @@ class Create extends Action * carry their own personal token — repositories matching the same * providerRepositoryId can belong to different Appwrite installations. */ - private function resolveAdapterForRepository(Document $repository, Factory $vcsFactory, Database $dbForPlatform, Authorization $authorization): ?Git + private function resolveAdapterForRepository(Document $repository, callable $vcsForInstallation, Database $dbForPlatform, Authorization $authorization): ?Git { $installation = $authorization->skip(fn () => $dbForPlatform->getDocument('installations', $repository->getAttribute('installationId', ''))); @@ -113,7 +114,7 @@ class Create extends Action } try { - return $vcsFactory->fromInstallation($installation); + return $vcsForInstallation($installation); } catch (\Throwable $error) { Console::warning("Failed to resolve Gitea adapter for installation '{$installation->getId()}': " . $error->getMessage()); return null; @@ -122,7 +123,7 @@ class Create extends Action private function handlePushEvent( array $parsedPayload, - Factory $vcsFactory, + callable $vcsForInstallation, Database $dbForPlatform, Authorization $authorization, BuildPublisher $publisherForBuilds, @@ -159,7 +160,7 @@ class Create extends Action $providerAffectedFiles = $parsedPayload['affectedFiles'] ?? []; foreach ($repositories as $repository) { - $adapter = $this->resolveAdapterForRepository($repository, $vcsFactory, $dbForPlatform, $authorization); + $adapter = $this->resolveAdapterForRepository($repository, $vcsForInstallation, $dbForPlatform, $authorization); if ($adapter === null) { continue; @@ -173,7 +174,7 @@ class Create extends Action private function handlePullRequestEvent( array $parsedPayload, - Factory $vcsFactory, + callable $vcsForInstallation, Database $dbForPlatform, Authorization $authorization, BuildPublisher $publisherForBuilds, @@ -211,7 +212,7 @@ class Create extends Action ])); foreach ($repositories as $repository) { - $adapter = $this->resolveAdapterForRepository($repository, $vcsFactory, $dbForPlatform, $authorization); + $adapter = $this->resolveAdapterForRepository($repository, $vcsForInstallation, $dbForPlatform, $authorization); if ($adapter === null) { continue; From ccd0ba5d3b6964fe92bd526ecaecba339f447337 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Fri, 10 Jul 2026 14:04:03 +0530 Subject: [PATCH 04/12] refactor: use verifySignature() in Gitea event handler Preserves the existing fail-closed behavior (empty secret = invalid) now that the library throws instead of returning a bool. --- .../Platform/Modules/VCS/Http/Gitea/Events/Create.php | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php index 1d1dd99dbf..2c07f63ba9 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php @@ -17,6 +17,7 @@ use Utopia\Platform\Scope\HTTP; use Utopia\Span\Span; use Utopia\System\System; use Utopia\VCS\Adapter\Git; +use Utopia\VCS\Exception\SignatureVerificationException; class Create extends Action { @@ -72,7 +73,14 @@ class Create extends Action // signed JWT Appwrite always validates, so an empty webhook secret // there still leaves a real check in place. Gitea has no such // fallback -- an empty secret here would mean no verification at all. - $valid = !empty($secretKey) && $vcs->validateWebhookEvent($payload, $signature, $secretKey); + $valid = false; + if (!empty($secretKey)) { + try { + $vcs->verifySignature($payload, $signature, $secretKey); + $valid = true; + } catch (SignatureVerificationException) { + } + } Span::add('vcs.gitea.event.signature.valid', $valid); if (!$valid) { From 18505c812b6f2ed0c8d87c3ce40e55bdb2e8777e Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Fri, 10 Jul 2026 15:10:30 +0530 Subject: [PATCH 05/12] revert: use validateWebhookEvent() and hasPerRepositoryWebhooks() Matches the library revert -- Gitea event handling goes back to the bool-returning validateWebhookEvent(), and the four repo-connect webhook-wiring call sites pick up the hasPerRepositoryWebhooks rename. --- .../Modules/Functions/Http/Functions/Create.php | 2 +- .../Modules/Functions/Http/Functions/Update.php | 2 +- .../Platform/Modules/Sites/Http/Sites/Create.php | 2 +- .../Platform/Modules/Sites/Http/Sites/Update.php | 2 +- .../Platform/Modules/VCS/Http/Gitea/Events/Create.php | 10 +--------- 5 files changed, 5 insertions(+), 13 deletions(-) diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php index 45198c149e..6ec997f7ca 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php @@ -306,7 +306,7 @@ class Create extends Base ])); $providerAdapter = $vcsForInstallation($installation); - if ($providerAdapter->requiresRepositoryWebhook()) { + if ($providerAdapter->hasPerRepositoryWebhooks()) { try { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php index 1ff5e0cbab..ce4715c854 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php @@ -247,7 +247,7 @@ class Update extends Base $repositoryInternalId = $repository->getSequence(); $providerAdapter = $vcsForInstallation($installation); - if ($providerAdapter->requiresRepositoryWebhook()) { + if ($providerAdapter->hasPerRepositoryWebhooks()) { try { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php index 3f8d35f78a..c29cca3c5d 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php @@ -222,7 +222,7 @@ class Create extends Base $repository = $dbForPlatform->createDocument('repositories', $repository); $providerAdapter = $vcsForInstallation($installation); - if ($providerAdapter->requiresRepositoryWebhook()) { + if ($providerAdapter->hasPerRepositoryWebhooks()) { try { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php index b6f514812d..e2a1103c2a 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php @@ -245,7 +245,7 @@ class Update extends Base $repositoryInternalId = $repository->getSequence(); $providerAdapter = $vcsForInstallation($installation); - if ($providerAdapter->requiresRepositoryWebhook()) { + if ($providerAdapter->hasPerRepositoryWebhooks()) { try { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php index 2c07f63ba9..1d1dd99dbf 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php @@ -17,7 +17,6 @@ use Utopia\Platform\Scope\HTTP; use Utopia\Span\Span; use Utopia\System\System; use Utopia\VCS\Adapter\Git; -use Utopia\VCS\Exception\SignatureVerificationException; class Create extends Action { @@ -73,14 +72,7 @@ class Create extends Action // signed JWT Appwrite always validates, so an empty webhook secret // there still leaves a real check in place. Gitea has no such // fallback -- an empty secret here would mean no verification at all. - $valid = false; - if (!empty($secretKey)) { - try { - $vcs->verifySignature($payload, $signature, $secretKey); - $valid = true; - } catch (SignatureVerificationException) { - } - } + $valid = !empty($secretKey) && $vcs->validateWebhookEvent($payload, $signature, $secretKey); Span::add('vcs.gitea.event.signature.valid', $valid); if (!$valid) { From 3cc049282fc636b934344a4c8c6a24e821e964f2 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Fri, 10 Jul 2026 15:25:44 +0530 Subject: [PATCH 06/12] refactor: rename to supportsRepositoryWebhooks per review --- .../Platform/Modules/Functions/Http/Functions/Create.php | 2 +- .../Platform/Modules/Functions/Http/Functions/Update.php | 2 +- src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php | 2 +- src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php index 6ec997f7ca..a8216e5328 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php @@ -306,7 +306,7 @@ class Create extends Base ])); $providerAdapter = $vcsForInstallation($installation); - if ($providerAdapter->hasPerRepositoryWebhooks()) { + if ($providerAdapter->supportsRepositoryWebhooks()) { try { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php index ce4715c854..e8eadbc9dc 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php @@ -247,7 +247,7 @@ class Update extends Base $repositoryInternalId = $repository->getSequence(); $providerAdapter = $vcsForInstallation($installation); - if ($providerAdapter->hasPerRepositoryWebhooks()) { + if ($providerAdapter->supportsRepositoryWebhooks()) { try { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php index c29cca3c5d..dff6225fa3 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php @@ -222,7 +222,7 @@ class Create extends Base $repository = $dbForPlatform->createDocument('repositories', $repository); $providerAdapter = $vcsForInstallation($installation); - if ($providerAdapter->hasPerRepositoryWebhooks()) { + if ($providerAdapter->supportsRepositoryWebhooks()) { try { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php index e2a1103c2a..587e2d756d 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php @@ -245,7 +245,7 @@ class Update extends Base $repositoryInternalId = $repository->getSequence(); $providerAdapter = $vcsForInstallation($installation); - if ($providerAdapter->hasPerRepositoryWebhooks()) { + if ($providerAdapter->supportsRepositoryWebhooks()) { try { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); From 160515290fd5ed6add3ca30a35097bf3817335f2 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Fri, 10 Jul 2026 17:43:50 +0530 Subject: [PATCH 07/12] refactor: check webhook scopes array at repo-connect call sites Matches the array-based API -- skip resolving owner/repo and calling RepositoryWebhooks::ensure() when the adapter reports installation-scope delivery, same as before for GitHub/Gitea, but now forward-compatible if GitHub's array grows to include repository scope too. --- .../Platform/Modules/Functions/Http/Functions/Create.php | 3 ++- .../Platform/Modules/Functions/Http/Functions/Update.php | 3 ++- src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php | 3 ++- src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php | 3 ++- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php index a8216e5328..c765759c94 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php @@ -42,6 +42,7 @@ use Utopia\Validator\Boolean; use Utopia\Validator\Range; use Utopia\Validator\Text; use Utopia\Validator\WhiteList; +use Utopia\VCS\Adapter\Git; class Create extends Base { @@ -306,7 +307,7 @@ class Create extends Base ])); $providerAdapter = $vcsForInstallation($installation); - if ($providerAdapter->supportsRepositoryWebhooks()) { + if (!\in_array(Git::WEBHOOK_SCOPE_INSTALLATION, $providerAdapter->getSupportedWebhookScopes(), true)) { try { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php index e8eadbc9dc..4b9c922a7f 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php @@ -35,6 +35,7 @@ use Utopia\Validator\Nullable; use Utopia\Validator\Range; use Utopia\Validator\Text; use Utopia\Validator\WhiteList; +use Utopia\VCS\Adapter\Git; class Update extends Base { @@ -247,7 +248,7 @@ class Update extends Base $repositoryInternalId = $repository->getSequence(); $providerAdapter = $vcsForInstallation($installation); - if ($providerAdapter->supportsRepositoryWebhooks()) { + if (!\in_array(Git::WEBHOOK_SCOPE_INSTALLATION, $providerAdapter->getSupportedWebhookScopes(), true)) { try { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php index dff6225fa3..76dd2ba083 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php @@ -26,6 +26,7 @@ use Utopia\Validator\Boolean; use Utopia\Validator\Range; use Utopia\Validator\Text; use Utopia\Validator\WhiteList; +use Utopia\VCS\Adapter\Git; class Create extends Base { @@ -222,7 +223,7 @@ class Create extends Base $repository = $dbForPlatform->createDocument('repositories', $repository); $providerAdapter = $vcsForInstallation($installation); - if ($providerAdapter->supportsRepositoryWebhooks()) { + if (!\in_array(Git::WEBHOOK_SCOPE_INSTALLATION, $providerAdapter->getSupportedWebhookScopes(), true)) { try { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php index 587e2d756d..a6a0605524 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php @@ -30,6 +30,7 @@ use Utopia\Validator\Nullable; use Utopia\Validator\Range; use Utopia\Validator\Text; use Utopia\Validator\WhiteList; +use Utopia\VCS\Adapter\Git; class Update extends Base { @@ -245,7 +246,7 @@ class Update extends Base $repositoryInternalId = $repository->getSequence(); $providerAdapter = $vcsForInstallation($installation); - if ($providerAdapter->supportsRepositoryWebhooks()) { + if (!\in_array(Git::WEBHOOK_SCOPE_INSTALLATION, $providerAdapter->getSupportedWebhookScopes(), true)) { try { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); From b10c746cb7180b30078e14b08b495776b03de4f6 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Fri, 10 Jul 2026 18:15:35 +0530 Subject: [PATCH 08/12] fix: guard the closed-PR handler against cross-provider collisions The opened/reopened/synchronize paths already skip repositories whose installation isn't gitea (via resolveAdapterForRepository), but the closed-PR path updated providerPullRequestIds on any matching providerRepositoryId regardless of provider. Since GitHub and Gitea both assign short sequential repo/PR numbers, a Gitea PR close could silently strip a GitHub repository's tracked PR ID. Extracts the provider check into isGiteaRepository() and applies it in both paths. --- .../Modules/VCS/Http/Gitea/Events/Create.php | 29 +++++-- .../Vcs/GiteaClosedPullRequestEventTest.php | 80 +++++++++++++++++++ 2 files changed, 101 insertions(+), 8 deletions(-) create mode 100644 tests/unit/Vcs/GiteaClosedPullRequestEventTest.php diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php index 1d1dd99dbf..cb1c8199e1 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php @@ -97,21 +97,30 @@ class Create extends Action * carry their own personal token — repositories matching the same * providerRepositoryId can belong to different Appwrite installations. */ - private function resolveAdapterForRepository(Document $repository, callable $vcsForInstallation, Database $dbForPlatform, Authorization $authorization): ?Git + /** + * `repositories` has no provider attribute -- providerRepositoryId is + * provider-scoped numeric IDs from independent servers, so a GitHub + * and a Gitea repository can collide on the same ID. Filter by the + * matched installation's own provider instead of the query. + */ + private function isGiteaRepository(Document $repository, Database $dbForPlatform, Authorization $authorization): bool { $installation = $authorization->skip(fn () => $dbForPlatform->getDocument('installations', $repository->getAttribute('installationId', ''))); if ($installation->isEmpty()) { + return false; + } + + return $installation->getAttribute('provider', 'github') === 'gitea'; + } + + private function resolveAdapterForRepository(Document $repository, callable $vcsForInstallation, Database $dbForPlatform, Authorization $authorization): ?Git + { + if (!$this->isGiteaRepository($repository, $dbForPlatform, $authorization)) { return null; } - // `repositories` has no provider attribute -- providerRepositoryId is - // provider-scoped numeric IDs from independent servers, so a GitHub - // and a Gitea repository can collide on the same ID. Filter by the - // matched installation's own provider instead of the query. - if ($installation->getAttribute('provider', 'github') !== 'gitea') { - return null; - } + $installation = $authorization->skip(fn () => $dbForPlatform->getDocument('installations', $repository->getAttribute('installationId', ''))); try { return $vcsForInstallation($installation); @@ -253,6 +262,10 @@ class Create extends Action ])); foreach ($repositories as $repository) { + if (!$this->isGiteaRepository($repository, $dbForPlatform, $authorization)) { + continue; + } + $providerPullRequestIds = $repository->getAttribute('providerPullRequestIds', []); if (\in_array($providerPullRequestId, $providerPullRequestIds)) { diff --git a/tests/unit/Vcs/GiteaClosedPullRequestEventTest.php b/tests/unit/Vcs/GiteaClosedPullRequestEventTest.php new file mode 100644 index 0000000000..2cb0417c76 --- /dev/null +++ b/tests/unit/Vcs/GiteaClosedPullRequestEventTest.php @@ -0,0 +1,80 @@ +handler = new Create(); + } + + public function testClosedEventOnlyUpdatesGiteaRepositories(): void + { + // A GitHub repo and a Gitea repo can share the same numeric + // providerRepositoryId since each is scoped to its own server. + $giteaRepository = new Document([ + '$id' => 'repo-gitea', + 'installationId' => 'install-gitea', + 'providerRepositoryId' => '5', + 'providerPullRequestIds' => [5], + ]); + + $githubRepository = new Document([ + '$id' => 'repo-github', + 'installationId' => 'install-github', + 'providerRepositoryId' => '5', + 'providerPullRequestIds' => [5], + ]); + + $giteaInstallation = new Document(['$id' => 'install-gitea', 'provider' => 'gitea']); + $githubInstallation = new Document(['$id' => 'install-github', 'provider' => 'github']); + + $dbForPlatform = $this->createMock(Database::class); + $authorization = $this->createMock(Authorization::class); + + $dbForPlatform->method('find')->willReturn([$giteaRepository, $githubRepository]); + + $dbForPlatform->method('getDocument') + ->willReturnCallback(fn (string $collection, string $id): Document => match ($id) { + 'install-gitea' => $giteaInstallation, + 'install-github' => $githubInstallation, + default => new Document(), + }); + + $authorization->method('skip')->willReturnCallback(fn (callable $fn): mixed => $fn()); + + $dbForPlatform->expects($this->once()) + ->method('updateDocument') + ->with('repositories', 'repo-gitea', $this->callback(function (Document $doc) { + $this->assertSame([], array_values($doc->getAttribute('providerPullRequestIds'))); + return true; + })); + + $publisherForBuilds = $this->createMock(BuildPublisher::class); + + $this->callHandler('handlePullRequestEvent', [ + 'action' => 'closed', + 'repositoryId' => '5', + 'pullRequestNumber' => 5, + 'external' => true, + ], fn () => null, $dbForPlatform, $authorization, $publisherForBuilds, fn () => null, []); + } + + private function callHandler(string $method, mixed ...$arguments): mixed + { + return (new ReflectionMethod($this->handler, $method))->invoke($this->handler, ...$arguments); + } +} From de6d55d8ac24219978d6d736827777bc4597b9fc Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Fri, 10 Jul 2026 18:45:29 +0530 Subject: [PATCH 09/12] style: use createStub for unasserted BuildPublisher mock Rector's CreateStubOverCreateMockArgRector flagged this -- the fake is never asserted on, so it should be a stub not a mock. --- tests/unit/Vcs/GiteaClosedPullRequestEventTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/Vcs/GiteaClosedPullRequestEventTest.php b/tests/unit/Vcs/GiteaClosedPullRequestEventTest.php index 2cb0417c76..85877b4005 100644 --- a/tests/unit/Vcs/GiteaClosedPullRequestEventTest.php +++ b/tests/unit/Vcs/GiteaClosedPullRequestEventTest.php @@ -63,7 +63,7 @@ final class GiteaClosedPullRequestEventTest extends TestCase return true; })); - $publisherForBuilds = $this->createMock(BuildPublisher::class); + $publisherForBuilds = $this->createStub(BuildPublisher::class); $this->callHandler('handlePullRequestEvent', [ 'action' => 'closed', From df24bcaa3a174eab9e902f151c33e879261828e9 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Fri, 10 Jul 2026 19:41:43 +0530 Subject: [PATCH 10/12] fix: cover vcsForInstallation() itself with the orphan-cleanup try/catch vcsForInstallation($installation) was called before the try block in all four repo-connect handlers. If adapter construction throws (e.g. token refresh failing at construction time), the repositories document created just before it was left orphaned uncaught -- the next retry's idempotency check in RepositoryWebhooks::ensure() would then see it as an existing connection and silently skip webhook creation, permanently breaking that connection. Moved adapter resolution inside the try. Also removes a redundant duplicate installation fetch in the Gitea events handler: resolveAdapterForRepository() re-queried the same installation document that isGiteaRepository() (now resolveGiteaInstallation(), returning the Document instead of a bool) had already loaded. --- .../Functions/Http/Functions/Create.php | 12 ++++++------ .../Functions/Http/Functions/Update.php | 12 ++++++------ .../Modules/Sites/Http/Sites/Create.php | 18 +++++++++--------- .../Modules/Sites/Http/Sites/Update.php | 12 ++++++------ .../Modules/VCS/Http/Gitea/Events/Create.php | 16 ++++++++-------- 5 files changed, 35 insertions(+), 35 deletions(-) diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php index c765759c94..c965d5a17e 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php @@ -306,16 +306,16 @@ class Create extends Base 'providerPullRequestIds' => [] ])); - $providerAdapter = $vcsForInstallation($installation); - if (!\in_array(Git::WEBHOOK_SCOPE_INSTALLATION, $providerAdapter->getSupportedWebhookScopes(), true)) { - try { + try { + $providerAdapter = $vcsForInstallation($installation); + if (!\in_array(Git::WEBHOOK_SCOPE_INSTALLATION, $providerAdapter->getSupportedWebhookScopes(), true)) { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); - } catch (\Throwable $error) { - $dbForPlatform->deleteDocument('repositories', $repository->getId()); - throw $error; } + } catch (\Throwable $error) { + $dbForPlatform->deleteDocument('repositories', $repository->getId()); + throw $error; } $function->setAttribute('repositoryId', $repository->getId()); diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php index 4b9c922a7f..a2fecf5ce3 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Functions/Update.php @@ -247,16 +247,16 @@ class Update extends Base $repositoryId = $repository->getId(); $repositoryInternalId = $repository->getSequence(); - $providerAdapter = $vcsForInstallation($installation); - if (!\in_array(Git::WEBHOOK_SCOPE_INSTALLATION, $providerAdapter->getSupportedWebhookScopes(), true)) { - try { + try { + $providerAdapter = $vcsForInstallation($installation); + if (!\in_array(Git::WEBHOOK_SCOPE_INSTALLATION, $providerAdapter->getSupportedWebhookScopes(), true)) { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); - } catch (\Throwable $error) { - $dbForPlatform->deleteDocument('repositories', $repository->getId()); - throw $error; } + } catch (\Throwable $error) { + $dbForPlatform->deleteDocument('repositories', $repository->getId()); + throw $error; } } diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php index 76dd2ba083..e8513fe5f7 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Create.php @@ -222,19 +222,19 @@ class Create extends Base ]); $repository = $dbForPlatform->createDocument('repositories', $repository); - $providerAdapter = $vcsForInstallation($installation); - if (!\in_array(Git::WEBHOOK_SCOPE_INSTALLATION, $providerAdapter->getSupportedWebhookScopes(), true)) { - try { + try { + $providerAdapter = $vcsForInstallation($installation); + if (!\in_array(Git::WEBHOOK_SCOPE_INSTALLATION, $providerAdapter->getSupportedWebhookScopes(), true)) { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); - } catch (\Throwable $error) { - // Don't leave an orphaned repositories document behind -- it - // would make the next retry's connection count look like a - // repeat, silently skipping webhook creation. - $dbForPlatform->deleteDocument('repositories', $repository->getId()); - throw $error; } + } catch (\Throwable $error) { + // Don't leave an orphaned repositories document behind -- it + // would make the next retry's connection count look like a + // repeat, silently skipping webhook creation. + $dbForPlatform->deleteDocument('repositories', $repository->getId()); + throw $error; } $site->setAttribute('repositoryId', $repository->getId()); diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php index a6a0605524..303d21779f 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Sites/Update.php @@ -245,16 +245,16 @@ class Update extends Base $repositoryId = $repository->getId(); $repositoryInternalId = $repository->getSequence(); - $providerAdapter = $vcsForInstallation($installation); - if (!\in_array(Git::WEBHOOK_SCOPE_INSTALLATION, $providerAdapter->getSupportedWebhookScopes(), true)) { - try { + try { + $providerAdapter = $vcsForInstallation($installation); + if (!\in_array(Git::WEBHOOK_SCOPE_INSTALLATION, $providerAdapter->getSupportedWebhookScopes(), true)) { $owner = $providerAdapter->getOwnerName($installation->getAttribute('providerInstallationId', ''), (int)$providerRepositoryId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); $repositoryWebhooks->ensure($providerAdapter, $installation, $dbForPlatform, $providerRepositoryId, $owner, $repositoryName); - } catch (\Throwable $error) { - $dbForPlatform->deleteDocument('repositories', $repository->getId()); - throw $error; } + } catch (\Throwable $error) { + $dbForPlatform->deleteDocument('repositories', $repository->getId()); + throw $error; } } diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php index cb1c8199e1..e115ac03e3 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php @@ -103,25 +103,25 @@ class Create extends Action * and a Gitea repository can collide on the same ID. Filter by the * matched installation's own provider instead of the query. */ - private function isGiteaRepository(Document $repository, Database $dbForPlatform, Authorization $authorization): bool + private function resolveGiteaInstallation(Document $repository, Database $dbForPlatform, Authorization $authorization): ?Document { $installation = $authorization->skip(fn () => $dbForPlatform->getDocument('installations', $repository->getAttribute('installationId', ''))); - if ($installation->isEmpty()) { - return false; + if ($installation->isEmpty() || $installation->getAttribute('provider', 'github') !== 'gitea') { + return null; } - return $installation->getAttribute('provider', 'github') === 'gitea'; + return $installation; } private function resolveAdapterForRepository(Document $repository, callable $vcsForInstallation, Database $dbForPlatform, Authorization $authorization): ?Git { - if (!$this->isGiteaRepository($repository, $dbForPlatform, $authorization)) { + $installation = $this->resolveGiteaInstallation($repository, $dbForPlatform, $authorization); + + if ($installation === null) { return null; } - $installation = $authorization->skip(fn () => $dbForPlatform->getDocument('installations', $repository->getAttribute('installationId', ''))); - try { return $vcsForInstallation($installation); } catch (\Throwable $error) { @@ -262,7 +262,7 @@ class Create extends Action ])); foreach ($repositories as $repository) { - if (!$this->isGiteaRepository($repository, $dbForPlatform, $authorization)) { + if ($this->resolveGiteaInstallation($repository, $dbForPlatform, $authorization) === null) { continue; } From 426b32eb28e5269a834044f5db118a79f5c40ac2 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Fri, 10 Jul 2026 19:54:11 +0530 Subject: [PATCH 11/12] fix: sign OAuth2 state and add issue scopes for Gitea The callback endpoint is public and previously trusted the raw JSON state -- anyone with their own valid authorization code could submit an arbitrary projectId and attach their VCS account as an installation on another project (and control the unvalidated redirect URLs). Authorize now signs projectId/success/failure with HMAC-SHA256 over _APP_OPENSSL_KEY_V1 and the callback fails closed on mismatch. Also adds read:issue/write:issue to the requested Gitea scopes -- the adapter's PR comment methods go through /repos/.../issues/... which Gitea's scoped tokens reject without them, breaking non-silent mode. --- src/Appwrite/Auth/OAuth2/Gitea.php | 2 ++ .../Platform/Modules/VCS/Http/Authorize/Base.php | 3 +++ src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php | 9 +++++++++ 3 files changed, 14 insertions(+) diff --git a/src/Appwrite/Auth/OAuth2/Gitea.php b/src/Appwrite/Auth/OAuth2/Gitea.php index dd649047d1..01914ce8e7 100644 --- a/src/Appwrite/Auth/OAuth2/Gitea.php +++ b/src/Appwrite/Auth/OAuth2/Gitea.php @@ -35,6 +35,8 @@ class Gitea extends OAuth2 'read:repository', 'write:repository', 'read:organization', + 'read:issue', + 'write:issue', ]; /** diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php b/src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php index eeea2c19cd..6784fe385d 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php @@ -97,10 +97,13 @@ abstract class Base extends Action $hostname = $platform['consoleHostname'] ?? ''; $callback = $protocol . '://' . $hostname . '/v1/vcs/' . $key . '/callback'; + // The callback endpoint is public, so it verifies this signature + // before trusting the projectId and redirect URLs in state. $oauth2 = $this->createOAuth2($callback, [ 'projectId' => $project->getId(), 'success' => $success, 'failure' => $failure, + 'signature' => \hash_hmac('sha256', \json_encode([$project->getId(), $success, $failure]), System::getEnv('_APP_OPENSSL_KEY_V1', '')), ]); $response diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php b/src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php index 1c8ab3e3ad..9e76682b13 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php @@ -79,6 +79,15 @@ abstract class Base extends Action $redirectFailure = $state['failure'] ?? ''; $projectId = $state['projectId'] ?? ''; + // This endpoint is public -- without verifying the signature the + // Authorize action put in state, anyone with their own valid + // authorization code could pass an arbitrary projectId here and + // attach their VCS account as an installation on another project. + $signature = \hash_hmac('sha256', \json_encode([$projectId, $state['success'] ?? '', $redirectFailure]), System::getEnv('_APP_OPENSSL_KEY_V1', '')); + if (!\hash_equals($signature, $state['signature'] ?? '')) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid state parameter. Please restart the installation from the Appwrite Console.'); + } + $project = $dbForPlatform->getDocument('projects', $projectId); if ($project->isEmpty()) { From 11969eb89c262430cf916cd6d2a6c771199399dd Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Mon, 13 Jul 2026 17:32:23 +0530 Subject: [PATCH 12/12] Clean up Gitea VCS provider wiring --- app/config/vcs.php | 5 +- app/init/constants.php | 3 + app/init/resources.php | 2 + src/Appwrite/Auth/OAuth2/Gitea.php | 67 ------------------- .../Modules/Console/Http/Variables/Get.php | 2 +- .../Modules/VCS/Http/Authorize/Base.php | 7 +- .../Modules/VCS/Http/Gitea/Events/Create.php | 24 ++----- .../Installations/Repositories/Create.php | 25 ++++++- .../Vcs/GiteaClosedPullRequestEventTest.php | 2 +- 9 files changed, 38 insertions(+), 99 deletions(-) diff --git a/app/config/vcs.php b/app/config/vcs.php index 787fb07ecc..4264d6c0d9 100644 --- a/app/config/vcs.php +++ b/app/config/vcs.php @@ -30,9 +30,8 @@ return [ 'CLIENT_SECRET' => '_APP_VCS_GITEA_CLIENT_SECRET', 'WEBHOOK_SECRET' => '_APP_VCS_GITEA_WEBHOOK_SECRET', ], - // WEBHOOK_SECRET is required (unlike GitHub's) because a Gitea webhook - // has no other verification layer -- GitHub App deliveries also carry - // a signed JWT Appwrite always validates independently of the secret. + // Unlike GitHub's legacy optional secret, Gitea webhooks must always + // have a shared secret because Appwrite creates them directly. 'requiredEnvVariables' => ['ENDPOINT', 'CLIENT_ID', 'CLIENT_SECRET', 'WEBHOOK_SECRET'], ], ]; diff --git a/app/init/constants.php b/app/init/constants.php index df85fc0925..c90db28043 100644 --- a/app/init/constants.php +++ b/app/init/constants.php @@ -108,6 +108,9 @@ const APP_SDK_PLATFORM_STATIC = 'static'; const APP_VCS_GITHUB_USERNAME = 'Appwrite'; const APP_VCS_GITHUB_EMAIL = 'team@appwrite.io'; const APP_VCS_GITHUB_URL = 'https://github.com/TeamAppwrite'; +const APP_VCS_COMMIT_USERNAME = APP_VCS_GITHUB_USERNAME; +const APP_VCS_COMMIT_EMAIL = APP_VCS_GITHUB_EMAIL; +const APP_VCS_COMMIT_URL = APP_VCS_GITHUB_URL; const APP_BRANDED_EMAIL_BASE_TEMPLATE = 'email-base-styled'; // Embeddings diff --git a/app/init/resources.php b/app/init/resources.php index 0633c78a95..d0b22475fb 100644 --- a/app/init/resources.php +++ b/app/init/resources.php @@ -384,6 +384,8 @@ $container->set('repositoryWebhooks', fn (VcsFactory $vcsFactory) => new Reposit $container->set('vcsProviders', fn (VcsFactory $vcsFactory) => fn () => $vcsFactory->getProviders(), ['vcsFactory']); +$container->set('vcsConfigured', fn (VcsFactory $vcsFactory) => fn (string $provider) => $vcsFactory->isConfigured($provider), ['vcsFactory']); + $container->set('vcsForInstallation', fn (VcsFactory $vcsFactory) => fn (Document $installation) => $vcsFactory->fromInstallation($installation), ['vcsFactory']); $container->set('vcsForProvider', fn (VcsFactory $vcsFactory) => fn (string $provider) => $vcsFactory->fromProvider($provider), ['vcsFactory']); diff --git a/src/Appwrite/Auth/OAuth2/Gitea.php b/src/Appwrite/Auth/OAuth2/Gitea.php index 01914ce8e7..1cc891c167 100644 --- a/src/Appwrite/Auth/OAuth2/Gitea.php +++ b/src/Appwrite/Auth/OAuth2/Gitea.php @@ -4,32 +4,14 @@ namespace Appwrite\Auth\OAuth2; use Appwrite\Auth\OAuth2; -// Reference Material -// https://docs.gitea.com/development/oauth2-provider - class Gitea extends OAuth2 { - /** - * @var string - */ protected string $endpoint = ''; - /** - * @var array - */ protected array $user = []; - /** - * @var array - */ protected array $tokens = []; - /** - * @var array - */ - // The resulting personal token is reused for every VCS operation on the - // installation (list/create repos, read contents, create webhooks, - // comment on PRs) via Factory::fromInstallation(), not just login. protected array $scopes = [ 'read:user', 'read:repository', @@ -39,25 +21,16 @@ class Gitea extends OAuth2 'write:issue', ]; - /** - * Set the URL of the Gitea instance (self-hosted). - */ public function setEndpoint(string $endpoint): void { $this->endpoint = \rtrim($endpoint, '/'); } - /** - * @return string - */ public function getName(): string { return 'gitea'; } - /** - * @return string - */ public function getLoginURL(): string { return $this->endpoint . '/login/oauth/authorize?' . \http_build_query([ @@ -69,11 +42,6 @@ class Gitea extends OAuth2 ]); } - /** - * @param string $code - * - * @return array - */ protected function getTokens(string $code): array { if (empty($this->tokens)) { @@ -96,11 +64,6 @@ class Gitea extends OAuth2 return $this->tokens; } - /** - * @param string $refreshToken - * - * @return array - */ public function refreshTokens(string $refreshToken): array { $response = $this->request( @@ -124,11 +87,6 @@ class Gitea extends OAuth2 return $this->tokens; } - /** - * @param string $accessToken - * - * @return string - */ public function getUserID(string $accessToken): string { $user = $this->getUser($accessToken); @@ -136,11 +94,6 @@ class Gitea extends OAuth2 return \strval($user['id'] ?? ''); } - /** - * @param string $accessToken - * - * @return string - */ public function getUserEmail(string $accessToken): string { $user = $this->getUser($accessToken); @@ -148,11 +101,6 @@ class Gitea extends OAuth2 return $user['email'] ?? ''; } - /** - * @param string $accessToken - * - * @return bool - */ public function isEmailVerified(string $accessToken): bool { $user = $this->getUser($accessToken); @@ -160,11 +108,6 @@ class Gitea extends OAuth2 return $user['verified'] ?? false; } - /** - * @param string $accessToken - * - * @return string - */ public function getUserName(string $accessToken): string { $user = $this->getUser($accessToken); @@ -172,11 +115,6 @@ class Gitea extends OAuth2 return $user['full_name'] ?? ''; } - /** - * @param string $accessToken - * - * @return string - */ public function getUserSlug(string $accessToken): string { $user = $this->getUser($accessToken); @@ -184,11 +122,6 @@ class Gitea extends OAuth2 return $user['login'] ?? ''; } - /** - * @param string $accessToken - * - * @return array - */ protected function getUser(string $accessToken) { if (empty($this->user)) { diff --git a/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php b/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php index 609e3083aa..9adf5ebf9a 100644 --- a/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php +++ b/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php @@ -87,7 +87,7 @@ class Get extends Action '_APP_COMPUTE_SIZE_LIMIT' => +System::getEnv('_APP_COMPUTE_SIZE_LIMIT'), '_APP_USAGE_STATS' => System::getEnv('_APP_USAGE_STATS'), '_APP_VCS_ENABLED' => $isVcsEnabled, - '_APP_VCS_PROVIDERS' => $vcsFactory->getProviders(), + '_APP_VCS_PROVIDERS' => $vcsProviders(), '_APP_DOMAIN_ENABLED' => $isDomainEnabled, '_APP_ASSISTANT_ENABLED' => $isAssistantEnabled, '_APP_DOMAIN_SITES' => $platform['sitesDomain'], diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php b/src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php index 6784fe385d..06b0fcea1a 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php @@ -11,7 +11,6 @@ use Appwrite\SDK\Method; use Appwrite\SDK\MethodType; use Appwrite\SDK\Response as SDKResponse; use Appwrite\Utopia\Response; -use Appwrite\Vcs\Factory; use Utopia\Database\Document; use Utopia\Platform\Scope\HTTP; use Utopia\System\System; @@ -72,7 +71,7 @@ abstract class Base extends Action )) ->param('success', '', fn ($redirectValidator) => $redirectValidator, 'URL to redirect back to console after a successful installation attempt.', true, ['redirectValidator']) ->param('failure', '', fn ($redirectValidator) => $redirectValidator, 'URL to redirect back to console after a failed installation attempt.', true, ['redirectValidator']) - ->inject('vcsFactory') + ->inject('vcsConfigured') ->inject('response') ->inject('project') ->inject('platform') @@ -82,14 +81,14 @@ abstract class Base extends Action public function action( string $success, string $failure, - Factory $vcsFactory, + callable $vcsConfigured, Response $response, Document $project, array $platform ) { $key = static::getProvider(); - if (!$vcsFactory->isConfigured($key)) { + if (!$vcsConfigured($key)) { throw new Exception(Exception::GENERAL_SERVER_ERROR, static::getProviderName() . ' provider is not configured. Please configure VCS (Version Control System) variables in .env file.'); } diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php index e115ac03e3..a04ef72eda 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php @@ -15,7 +15,6 @@ use Utopia\Database\Query; use Utopia\Database\Validator\Authorization; use Utopia\Platform\Scope\HTTP; use Utopia\Span\Span; -use Utopia\System\System; use Utopia\VCS\Adapter\Git; class Create extends Action @@ -38,6 +37,7 @@ class Create extends Action ->label('scope', 'public') ->inject('vcsForProvider') ->inject('vcsForInstallation') + ->inject('vcsWebhookSecret') ->inject('request') ->inject('response') ->inject('dbForPlatform') @@ -51,6 +51,7 @@ class Create extends Action public function action( callable $vcsForProvider, callable $vcsForInstallation, + callable $vcsWebhookSecret, Request $request, Response $response, Database $dbForPlatform, @@ -66,12 +67,8 @@ class Create extends Action $payload = $request->getRawPayload(); $signature = $request->getHeaderLine($vcs->getSignatureHeaderName(), ''); - $secretKey = System::getEnv('_APP_VCS_GITEA_WEBHOOK_SECRET', ''); + $secretKey = $vcsWebhookSecret('gitea'); - // Fail closed, unlike GitHub App deliveries: those also carry a - // signed JWT Appwrite always validates, so an empty webhook secret - // there still leaves a real check in place. Gitea has no such - // fallback -- an empty secret here would mean no verification at all. $valid = !empty($secretKey) && $vcs->validateWebhookEvent($payload, $signature, $secretKey); Span::add('vcs.gitea.event.signature.valid', $valid); @@ -90,19 +87,6 @@ class Create extends Action $response->json($parsedPayload); } - /** - * Resolves an authenticated adapter for a repository connection's own - * installation. Unlike GitHub App, where one adapter serves every - * repository under an installation, Gitea's OAuth2 installations each - * carry their own personal token — repositories matching the same - * providerRepositoryId can belong to different Appwrite installations. - */ - /** - * `repositories` has no provider attribute -- providerRepositoryId is - * provider-scoped numeric IDs from independent servers, so a GitHub - * and a Gitea repository can collide on the same ID. Filter by the - * matched installation's own provider instead of the query. - */ private function resolveGiteaInstallation(Document $repository, Database $dbForPlatform, Authorization $authorization): ?Document { $installation = $authorization->skip(fn () => $dbForPlatform->getDocument('installations', $repository->getAttribute('installationId', ''))); @@ -157,7 +141,7 @@ class Create extends Action Span::add('vcs.gitea.event.repo.name', $providerRepositoryName); Span::add('vcs.gitea.event.branch', $providerBranch); - if ($providerCommitAuthorEmail === APP_VCS_GITHUB_EMAIL || $providerBranchDeleted) { + if ($providerCommitAuthorEmail === APP_VCS_COMMIT_EMAIL || $providerBranchDeleted) { return; } 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 18f38cdb38..4962f5f739 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Installations/Repositories/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Installations/Repositories/Create.php @@ -2,6 +2,7 @@ namespace Appwrite\Platform\Modules\VCS\Http\Installations\Repositories; +use Appwrite\Auth\OAuth2\Gitea as OAuth2Gitea; use Appwrite\Auth\OAuth2\Github as OAuth2Github; use Appwrite\Extend\Exception; use Appwrite\Platform\Action; @@ -76,11 +77,13 @@ class Create extends Action throw new Exception(Exception::INSTALLATION_NOT_FOUND); } + $provider = $installation->getAttribute('provider', 'github'); + if ($installation->getAttribute('personal', false) === true) { - $oauth2 = new OAuth2Github(System::getEnv('_APP_VCS_GITHUB_CLIENT_ID', ''), System::getEnv('_APP_VCS_GITHUB_CLIENT_SECRET', ''), ""); + $oauth2 = $this->createOAuth2($provider); $identity = null; - if (empty($installation->getAttribute('personalAccessToken')) || empty($installation->getAttribute('personalRefreshToken')) || empty($installation->getAttribute('personalAccessTokenExpiry'))) { + if ($provider === 'github' && (empty($installation->getAttribute('personalAccessToken')) || empty($installation->getAttribute('personalRefreshToken')) || empty($installation->getAttribute('personalAccessTokenExpiry')))) { $identity = $dbForPlatform->findOne('identities', [ Query::equal('provider', ['github']), Query::equal('userInternalId', [$user->getSequence()]), @@ -95,7 +98,7 @@ class Create extends Action try { $repository = $oauth2->createRepository($accessToken, $name, $private); - } catch (Exception $exception) { + } catch (\Throwable $exception) { throw new Exception(Exception::GENERAL_PROVIDER_FAILURE, "VCS provider failed to process the request: " . $exception->getMessage()); } } else { @@ -131,4 +134,20 @@ class Create extends Action $response->dynamic(new Document($repository), Response::MODEL_PROVIDER_REPOSITORY); } + + protected function createOAuth2(string $provider): OAuth2Github|OAuth2Gitea + { + if ($provider === 'github') { + return new OAuth2Github(System::getEnv('_APP_VCS_GITHUB_CLIENT_ID', ''), System::getEnv('_APP_VCS_GITHUB_CLIENT_SECRET', ''), ""); + } + + if ($provider === 'gitea') { + $oauth2 = new OAuth2Gitea(System::getEnv('_APP_VCS_GITEA_CLIENT_ID', ''), System::getEnv('_APP_VCS_GITEA_CLIENT_SECRET', ''), ""); + $oauth2->setEndpoint(System::getEnv('_APP_VCS_GITEA_ENDPOINT', '')); + + return $oauth2; + } + + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Unsupported VCS provider: ' . $provider); + } } diff --git a/tests/unit/Vcs/GiteaClosedPullRequestEventTest.php b/tests/unit/Vcs/GiteaClosedPullRequestEventTest.php index 85877b4005..3a844625e5 100644 --- a/tests/unit/Vcs/GiteaClosedPullRequestEventTest.php +++ b/tests/unit/Vcs/GiteaClosedPullRequestEventTest.php @@ -43,7 +43,7 @@ final class GiteaClosedPullRequestEventTest extends TestCase $githubInstallation = new Document(['$id' => 'install-github', 'provider' => 'github']); $dbForPlatform = $this->createMock(Database::class); - $authorization = $this->createMock(Authorization::class); + $authorization = $this->createStub(Authorization::class); $dbForPlatform->method('find')->willReturn([$giteaRepository, $githubRepository]);