Merge remote-tracking branch 'origin/feat/vcs-installation-tokens' into feat/vcs-factory

This commit is contained in:
harsh mahajan committed 2026-07-14 14:47:45 +05:30
commit 77f25efdd5
24 files changed
+1155 -6

No files matched your search

+6
View File
@@ -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
+2 -2
View File
@@ -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,
+54
View File
@@ -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' => ''
],
],
],
[
+14
View File
@@ -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'],
],
];
+56
View File
@@ -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')
+3
View File
@@ -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
+2
View File
@@ -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 () => []);
+12
View File
@@ -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
+154
View File
@@ -0,0 +1,154 @@
<?php
namespace Appwrite\Auth\OAuth2;
use Appwrite\Auth\OAuth2;
class Gitea extends OAuth2
{
protected string $endpoint = '';
protected array $user = [];
protected array $tokens = [];
protected array $scopes = [
'read:user',
'read:repository',
'write:repository',
'read:organization',
'read:issue',
'write:issue',
];
public function setEndpoint(string $endpoint): void
{
$this->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) ?? [];
}
}
+13
View File
@@ -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 {
@@ -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'],
@@ -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());
}
@@ -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;
@@ -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());
@@ -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;
@@ -0,0 +1,113 @@
<?php
namespace Appwrite\Platform\Modules\VCS\Http\Authorize;
use Appwrite\Auth\OAuth2;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Action;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\ContentType;
use Appwrite\SDK\Method;
use Appwrite\SDK\MethodType;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Document;
use Utopia\Platform\Scope\HTTP;
use Utopia\System\System;
/**
* Installation entry point for OAuth2-based VCS providers. Redirects to the
* provider's authorization page; the matching Callback action completes the
* flow. App-based providers (GitHub) have their own installation flow.
*/
abstract class Base extends Action
{
use HTTP;
/**
* Provider key in the `vcs` config registry.
*/
abstract public static function getProvider(): string;
/**
* Provider display name, used in SDK method names and error messages.
*/
abstract public static function getProviderName(): string;
/**
* Builds this provider's OAuth2 client, pointed at the browser-facing
* endpoint (which may differ from the server-side API endpoint in
* containerized setups) since the login URL is opened by the browser.
*/
abstract protected function createOAuth2(string $callback, array $state): OAuth2;
public function __construct()
{
$key = static::getProvider();
$name = static::getProviderName();
$this
->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());
}
}
@@ -0,0 +1,191 @@
<?php
namespace Appwrite\Platform\Modules\VCS\Http\Callback;
use Appwrite\Auth\OAuth2;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Action;
use Appwrite\Platform\Permission as AppwritePermission;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Database\Document;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Query;
use Utopia\Platform\Scope\HTTP;
use Utopia\System\System;
use Utopia\Validator\Text;
/**
* OAuth2 callback for OAuth2-based VCS providers. Exchanges the authorization
* code for tokens and upserts a personal installation for the project carried
* in the state parameter.
*/
abstract class Base extends Action
{
use HTTP;
use AppwritePermission;
/**
* Provider key in the `vcs` config registry.
*/
abstract public static function getProvider(): string;
/**
* Provider display name, used in error messages.
*/
abstract public static function getProviderName(): string;
/**
* Builds this provider's OAuth2 client, pointed at the server-side API
* endpoint (token exchange is a server-to-server call, unlike Authorize's
* browser-facing endpoint).
*/
abstract protected function createOAuth2(string $callback): OAuth2;
public function __construct()
{
$key = static::getProvider();
$this
->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]));
}
}
@@ -0,0 +1,43 @@
<?php
namespace Appwrite\Platform\Modules\VCS\Http\Gitea\Authorize;
use Appwrite\Auth\OAuth2;
use Appwrite\Auth\OAuth2\Gitea as OAuth2Gitea;
use Appwrite\Platform\Modules\VCS\Http\Authorize\Base;
use Utopia\System\System;
class Get extends Base
{
public static function getName()
{
return 'getVCSGiteaAuthorize';
}
public static function getProvider(): string
{
return 'gitea';
}
public static function getProviderName(): string
{
return 'Gitea';
}
protected function createOAuth2(string $callback, array $state): OAuth2
{
$oauth2 = new OAuth2Gitea(
System::getEnv('_APP_VCS_GITEA_CLIENT_ID', ''),
System::getEnv('_APP_VCS_GITEA_CLIENT_SECRET', ''),
$callback,
$state
);
// The login page is opened by the browser, which may reach Gitea on a
// different host than the server-side API endpoint (e.g. Docker).
$browserEndpoint = System::getEnv('_APP_VCS_GITEA_BROWSER_ENDPOINT', System::getEnv('_APP_VCS_GITEA_ENDPOINT', ''));
$oauth2->setEndpoint($browserEndpoint);
return $oauth2;
}
}
@@ -0,0 +1,39 @@
<?php
namespace Appwrite\Platform\Modules\VCS\Http\Gitea\Callback;
use Appwrite\Auth\OAuth2;
use Appwrite\Auth\OAuth2\Gitea as OAuth2Gitea;
use Appwrite\Platform\Modules\VCS\Http\Callback\Base;
use Utopia\System\System;
class Get extends Base
{
public static function getName()
{
return 'getVCSGiteaCallback';
}
public static function getProvider(): string
{
return 'gitea';
}
public static function getProviderName(): string
{
return 'Gitea';
}
protected function createOAuth2(string $callback): OAuth2
{
$oauth2 = new OAuth2Gitea(
System::getEnv('_APP_VCS_GITEA_CLIENT_ID', ''),
System::getEnv('_APP_VCS_GITEA_CLIENT_SECRET', ''),
$callback
);
$oauth2->setEndpoint(System::getEnv('_APP_VCS_GITEA_ENDPOINT', ''));
return $oauth2;
}
}
@@ -0,0 +1,261 @@
<?php
namespace Appwrite\Platform\Modules\VCS\Http\Gitea\Events;
use Appwrite\Event\Publisher\Build as BuildPublisher;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Action;
use Appwrite\Platform\Modules\VCS\Http\GitHub\Deployment;
use Appwrite\Utopia\Request;
use Appwrite\Utopia\Response;
use Appwrite\Vcs\Factory as VcsFactory;
use Utopia\Console;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
use Utopia\Platform\Scope\HTTP;
use Utopia\Span\Span;
use Utopia\VCS\Adapter\Git;
class Create extends Action
{
use HTTP;
use Deployment;
public static function getName()
{
return 'createVCSGiteaEvent';
}
public function __construct()
{
$this
->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])));
}
}
}
}
}
@@ -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);
}
}
@@ -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());
}
}
@@ -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.',
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Vcs;
use Appwrite\Event\Publisher\Build as BuildPublisher;
use Appwrite\Platform\Modules\VCS\Http\Gitea\Events\Create;
use Appwrite\Vcs\Factory as VcsFactory;
use PHPUnit\Framework\TestCase;
use ReflectionMethod;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
final class GiteaClosedPullRequestEventTest extends TestCase
{
private Create $handler;
public function setUp(): void
{
$this->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);
}
}