diff --git a/.env b/.env index e3809d4476..ed524c5c25 100644 --- a/.env +++ b/.env @@ -155,4 +155,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 0eb43f783b..ac39a49444 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -1257,6 +1257,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..4264d6c0d9 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,17 @@ 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', + ], + // 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/controllers/mock.php b/app/controllers/mock.php index 1c71406926..ca80f08e38 100644 --- a/app/controllers/mock.php +++ b/app/controllers/mock.php @@ -295,6 +295,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/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 86edbb2ce0..8957b4f8ff 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('vcsWebhookSecret', fn (VcsFactory $vcsFactory) => fn (string $provider) => $vcsFactory->getWebhookSecret($provider), ['vcsFactory']); $container->set('plan', fn () => []); diff --git a/docker-compose.yml b/docker-compose.yml index fd9dee1235..ae7b889dcf 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -197,6 +197,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 @@ -479,6 +485,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..1cc891c167 --- /dev/null +++ b/src/Appwrite/Auth/OAuth2/Gitea.php @@ -0,0 +1,154 @@ +endpoint = \rtrim($endpoint, '/'); + } + + public function getName(): string + { + return 'gitea'; + } + + 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) + ]); + } + + 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; + } + + 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; + } + + public function getUserID(string $accessToken): string + { + $user = $this->getUser($accessToken); + + return \strval($user['id'] ?? ''); + } + + public function getUserEmail(string $accessToken): string + { + $user = $this->getUser($accessToken); + + return $user['email'] ?? ''; + } + + public function isEmailVerified(string $accessToken): bool + { + $user = $this->getUser($accessToken); + + return $user['verified'] ?? false; + } + + public function getUserName(string $accessToken): string + { + $user = $this->getUser($accessToken); + + return $user['full_name'] ?? ''; + } + + public function getUserSlug(string $accessToken): string + { + $user = $this->getUser($accessToken); + + return $user['login'] ?? ''; + } + + 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 3a997c865d..4aa05673c1 100644 --- a/src/Appwrite/Migration/Version/V25.php +++ b/src/Appwrite/Migration/Version/V25.php @@ -66,6 +66,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; + case 'databases': if ($collectionType === 'projects') { try { diff --git a/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php b/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php index 0ab83d27d2..9adf5ebf9a 100644 --- a/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php +++ b/src/Appwrite/Platform/Modules/Console/Http/Variables/Get.php @@ -87,6 +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' => $vcsProviders(), '_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 943a5e3af5..453dd000d1 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 as VcsFactory; +use Appwrite\Vcs\RepositoryWebhooks; use OpenRuntimes\Orchestrator\Jobs; use Utopia\Abuse\Abuse; use Utopia\Config\Config; @@ -43,6 +44,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 { @@ -131,6 +133,7 @@ class Create extends Base ->inject('dbForPlatform') ->inject('request') ->inject('vcsFactory') + ->inject('repositoryWebhooks') ->inject('authorization') ->inject('platform') ->callback($this->action(...)); @@ -176,6 +179,7 @@ class Create extends Base Database $dbForPlatform, Request $request, VcsFactory $vcsFactory, + RepositoryWebhooks $repositoryWebhooks, Authorization $authorization, array $platform ) { @@ -306,6 +310,18 @@ class Create extends Base 'providerPullRequestIds' => [] ])); + try { + $providerAdapter = $vcsFactory->fromInstallation($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; + } + $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 11d1cc8fd7..62eb1c46b4 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 as VcsFactory; +use Appwrite\Vcs\RepositoryWebhooks; use Executor\Executor; use OpenRuntimes\Orchestrator\Jobs; use Utopia\Config\Config; @@ -36,6 +37,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 { @@ -115,6 +117,7 @@ class Update extends Base ->inject('jobs') ->inject('dbForPlatform') ->inject('vcsFactory') + ->inject('repositoryWebhooks') ->inject('executor') ->inject('authorization') ->inject('platform') @@ -153,6 +156,7 @@ class Update extends Base Jobs $jobs, Database $dbForPlatform, VcsFactory $vcsFactory, + RepositoryWebhooks $repositoryWebhooks, Executor $executor, Authorization $authorization, array $platform @@ -246,6 +250,18 @@ class Update extends Base $repositoryId = $repository->getId(); $repositoryInternalId = $repository->getSequence(); + + try { + $providerAdapter = $vcsFactory->fromInstallation($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; + } } $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 9472a82174..289142bdd4 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 as VcsFactory; +use Appwrite\Vcs\RepositoryWebhooks; use Utopia\Config\Config; use Utopia\Database\Database; use Utopia\Database\Document; @@ -25,6 +27,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 { @@ -102,6 +105,8 @@ class Create extends Base ->inject('project') ->inject('queueForEvents') ->inject('dbForPlatform') + ->inject('vcsFactory') + ->inject('repositoryWebhooks') ->callback($this->action(...)); } @@ -133,7 +138,9 @@ class Create extends Base Database $dbForProject, Document $project, Event $queueForEvents, - Database $dbForPlatform + Database $dbForPlatform, + VcsFactory $vcsFactory, + RepositoryWebhooks $repositoryWebhooks ) { if (!empty($adapter)) { $configFramework = Config::getParam('frameworks')[$framework] ?? []; @@ -221,6 +228,22 @@ class Create extends Base 'providerPullRequestIds' => [] ]); $repository = $dbForPlatform->createDocument('repositories', $repository); + + try { + $providerAdapter = $vcsFactory->fromInstallation($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; + } + $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 7c5bea3a16..6ae47e5a6e 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 as VcsFactory; +use Appwrite\Vcs\RepositoryWebhooks; use Executor\Executor; use Utopia\Config\Config; use Utopia\Database\Database; @@ -30,6 +31,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 { @@ -109,6 +111,7 @@ class Update extends Base ->inject('publisherForBuilds') ->inject('dbForPlatform') ->inject('vcsFactory') + ->inject('repositoryWebhooks') ->inject('executor') ->inject('platform') ->callback($this->action(...)); @@ -146,6 +149,7 @@ class Update extends Base BuildPublisher $publisherForBuilds, Database $dbForPlatform, VcsFactory $vcsFactory, + RepositoryWebhooks $repositoryWebhooks, Executor $executor, array $platform ) { @@ -247,6 +251,18 @@ class Update extends Base $repository = $dbForPlatform->createDocument('repositories', $repository); $repositoryId = $repository->getId(); $repositoryInternalId = $repository->getSequence(); + + try { + $providerAdapter = $vcsFactory->fromInstallation($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; + } } $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..06b0fcea1a --- /dev/null +++ b/src/Appwrite/Platform/Modules/VCS/Http/Authorize/Base.php @@ -0,0 +1,113 @@ +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('vcsConfigured') + ->inject('response') + ->inject('project') + ->inject('platform') + ->callback($this->action(...)); + } + + public function action( + string $success, + string $failure, + callable $vcsConfigured, + Response $response, + Document $project, + array $platform + ) { + $key = static::getProvider(); + + 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.'); + } + + $protocol = System::getEnv('_APP_OPTIONS_FORCE_HTTPS') === 'disabled' ? 'http' : 'https'; + $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 + ->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..9e76682b13 --- /dev/null +++ b/src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php @@ -0,0 +1,191 @@ +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'] ?? ''; + + // 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()) { + $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..62e86483aa --- /dev/null +++ b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php @@ -0,0 +1,261 @@ +setHttpMethod(Action::HTTP_REQUEST_METHOD_POST) + ->setHttpPath('/v1/vcs/gitea/events') + ->desc('Create event') + ->groups(['api', 'vcs']) + ->label('scope', 'public') + ->inject('vcsFactory') + ->inject('vcsWebhookSecret') + ->inject('request') + ->inject('response') + ->inject('dbForPlatform') + ->inject('authorization') + ->inject('getProjectDB') + ->inject('publisherForBuilds') + ->inject('platform') + ->callback($this->action(...)); + } + + public function action( + VcsFactory $vcsFactory, + callable $vcsWebhookSecret, + 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 = $vcsWebhookSecret('gitea'); + + $valid = !empty($secretKey) && $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); + } + + private function resolveGiteaInstallation(Document $repository, Database $dbForPlatform, Authorization $authorization): ?Document + { + $installation = $authorization->skip(fn () => $dbForPlatform->getDocument('installations', $repository->getAttribute('installationId', ''))); + + if ($installation->isEmpty() || $installation->getAttribute('provider', 'github') !== 'gitea') { + return null; + } + + return $installation; + } + + private function resolveAdapterForRepository(Document $repository, VcsFactory $vcsFactory, Database $dbForPlatform, Authorization $authorization): ?Git + { + $installation = $this->resolveGiteaInstallation($repository, $dbForPlatform, $authorization); + + if ($installation === null) { + 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, + VcsFactory $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_COMMIT_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, + VcsFactory $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) { + if ($this->resolveGiteaInstallation($repository, $dbForPlatform, $authorization) === null) { + continue; + } + + $providerPullRequestIds = $repository->getAttribute('providerPullRequestIds', []); + + if (\in_array($providerPullRequestId, $providerPullRequestIds)) { + $providerPullRequestIds = \array_diff($providerPullRequestIds, [$providerPullRequestId]); + $authorization->skip(fn () => $dbForPlatform->updateDocument('repositories', $repository->getId(), new Document(['providerPullRequestIds' => $providerPullRequestIds]))); + } + } + } + } +} 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 9fd9804042..56454b6457 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; @@ -77,11 +78,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()]), @@ -96,7 +99,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 { @@ -132,4 +135,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/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/tests/unit/Vcs/GiteaClosedPullRequestEventTest.php b/tests/unit/Vcs/GiteaClosedPullRequestEventTest.php new file mode 100644 index 0000000000..d0544e5a8b --- /dev/null +++ b/tests/unit/Vcs/GiteaClosedPullRequestEventTest.php @@ -0,0 +1,82 @@ +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->createStub(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->createStub(BuildPublisher::class); + $vcsFactory = $this->createStub(VcsFactory::class); + + $this->callHandler('handlePullRequestEvent', [ + 'action' => 'closed', + 'repositoryId' => '5', + 'pullRequestNumber' => 5, + 'external' => true, + ], $vcsFactory, $dbForPlatform, $authorization, $publisherForBuilds, fn () => null, []); + } + + private function callHandler(string $method, mixed ...$arguments): mixed + { + return (new ReflectionMethod($this->handler, $method))->invoke($this->handler, ...$arguments); + } +}