diff --git a/.env b/.env index 6873f98a80..e1032c8a8d 100644 --- a/.env +++ b/.env @@ -167,5 +167,8 @@ _APP_VCS_GITEA_WEBHOOK_SECRET=gitea-webhook-secret _APP_VCS_GITLAB_CLIENT_ID= _APP_VCS_GITLAB_CLIENT_SECRET= _APP_VCS_GITLAB_WEBHOOK_SECRET= +_APP_VCS_BITBUCKET_CLIENT_ID= +_APP_VCS_BITBUCKET_CLIENT_SECRET= +_APP_VCS_BITBUCKET_WEBHOOK_SECRET= _APP_VCS_WEBHOOK_URL=http://appwrite/v1 _APP_WEBHOOK_MAX_FAILED_ATTEMPTS=10 diff --git a/app/config/variables.php b/app/config/variables.php index 6cc2bf12e3..bd91706cf5 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -1365,6 +1365,33 @@ return [ 'question' => '', 'filter' => '' ], + [ + 'name' => '_APP_VCS_BITBUCKET_CLIENT_ID', + 'description' => 'Bitbucket OAuth2 consumer key. You can generate one in your Bitbucket workspace under Settings > OAuth consumers.', + 'introduction' => '2.0.0', + 'default' => '', + 'required' => false, + 'question' => '', + 'filter' => '' + ], + [ + 'name' => '_APP_VCS_BITBUCKET_CLIENT_SECRET', + 'description' => 'Bitbucket OAuth2 consumer secret. You can generate one in your Bitbucket workspace under Settings > OAuth consumers.', + 'introduction' => '2.0.0', + 'default' => '', + 'required' => false, + 'question' => '', + 'filter' => '' + ], + [ + 'name' => '_APP_VCS_BITBUCKET_WEBHOOK_SECRET', + 'description' => 'Secret used to validate incoming Bitbucket 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.', diff --git a/app/config/vcs.php b/app/config/vcs.php index f32d95acc8..d3a5dc8279 100644 --- a/app/config/vcs.php +++ b/app/config/vcs.php @@ -4,9 +4,11 @@ * VCS provider registry, read by Appwrite\Vcs\Factory. */ +use Appwrite\Auth\OAuth2\Bitbucket as OAuth2Bitbucket; use Appwrite\Auth\OAuth2\Gitea as OAuth2Gitea; use Appwrite\Auth\OAuth2\Github as OAuth2Github; use Appwrite\Auth\OAuth2\Gitlab as OAuth2Gitlab; +use Utopia\VCS\Adapter\Git\Bitbucket; use Utopia\VCS\Adapter\Git\Gitea; use Utopia\VCS\Adapter\Git\GitHub; use Utopia\VCS\Adapter\Git\GitLab; @@ -60,4 +62,18 @@ return [ 'webhookSecret' => ['required' => true, 'envVariable' => '_APP_VCS_GITLAB_WEBHOOK_SECRET'], ], ], + 'bitbucket' => [ + 'adapter' => Bitbucket::class, + 'oauth2' => fn (string $clientId, string $clientSecret, string $endpoint) => new OAuth2Bitbucket($clientId, $clientSecret, ''), + // Only official bitbucket.org/api.bitbucket.org is supported -- fixed, + // not configurable. Deliberately no 'endpoint' key here: unlike + // GitLab's, Bitbucket's setEndpoint() sets the API base + // (api.bitbucket.org), not the browser host, so this must stay unset + // rather than pointed at the wrong host. + 'variables' => [ + 'clientId' => ['required' => true, 'envVariable' => '_APP_VCS_BITBUCKET_CLIENT_ID'], + 'clientSecret' => ['required' => true, 'envVariable' => '_APP_VCS_BITBUCKET_CLIENT_SECRET'], + 'webhookSecret' => ['required' => true, 'envVariable' => '_APP_VCS_BITBUCKET_WEBHOOK_SECRET'], + ], + ], ]; diff --git a/app/init/constants.php b/app/init/constants.php index 1604594096..61d861936b 100644 --- a/app/init/constants.php +++ b/app/init/constants.php @@ -113,6 +113,7 @@ const APP_VCS_GITHUB_EMAIL = 'team@appwrite.io'; const APP_VCS_GITHUB_URL = 'https://github.com/TeamAppwrite'; const APP_VCS_GITEA_EMAIL = 'team@appwrite.io'; // Used to detect Appwrite's own commits const APP_VCS_GITLAB_EMAIL = 'team@appwrite.io'; // Used to detect Appwrite's own commits +const APP_VCS_BITBUCKET_EMAIL = 'team@appwrite.io'; // Used to detect Appwrite's own commits const APP_BRANDED_EMAIL_BASE_TEMPLATE = 'email-base-styled'; // Embeddings diff --git a/composer.lock b/composer.lock index f42fafee22..4e0ec81935 100644 --- a/composer.lock +++ b/composer.lock @@ -5161,16 +5161,16 @@ }, { "name": "utopia-php/vcs", - "version": "5.0.0", + "version": "5.1.0", "source": { "type": "git", "url": "https://github.com/utopia-php/vcs.git", - "reference": "de39bfdfaa8880b8c4370812cf837e98cf7b0fcf" + "reference": "040a0d5d92ffa33964dc1607d1b95a526c6ffc49" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/vcs/zipball/de39bfdfaa8880b8c4370812cf837e98cf7b0fcf", - "reference": "de39bfdfaa8880b8c4370812cf837e98cf7b0fcf", + "url": "https://api.github.com/repos/utopia-php/vcs/zipball/040a0d5d92ffa33964dc1607d1b95a526c6ffc49", + "reference": "040a0d5d92ffa33964dc1607d1b95a526c6ffc49", "shasum": "" }, "require": { @@ -5221,10 +5221,10 @@ "vcs" ], "support": { - "source": "https://github.com/utopia-php/vcs/tree/5.0.0", + "source": "https://github.com/utopia-php/vcs/tree/5.1.0", "issues": "https://github.com/utopia-php/vcs/issues" }, - "time": "2026-07-31T15:03:38+00:00" + "time": "2026-08-07T08:58:14+00:00" }, { "name": "utopia-php/websocket", diff --git a/docker-compose.yml b/docker-compose.yml index b00594cc7b..b376ca65f5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -207,6 +207,9 @@ services: - _APP_VCS_GITLAB_CLIENT_ID - _APP_VCS_GITLAB_CLIENT_SECRET - _APP_VCS_GITLAB_WEBHOOK_SECRET + - _APP_VCS_BITBUCKET_CLIENT_ID + - _APP_VCS_BITBUCKET_CLIENT_SECRET + - _APP_VCS_BITBUCKET_WEBHOOK_SECRET - _APP_VCS_WEBHOOK_URL - _APP_MIGRATIONS_FIREBASE_CLIENT_ID - _APP_MIGRATIONS_FIREBASE_CLIENT_SECRET @@ -506,6 +509,9 @@ services: - _APP_VCS_GITLAB_CLIENT_ID - _APP_VCS_GITLAB_CLIENT_SECRET - _APP_VCS_GITLAB_WEBHOOK_SECRET + - _APP_VCS_BITBUCKET_CLIENT_ID + - _APP_VCS_BITBUCKET_CLIENT_SECRET + - _APP_VCS_BITBUCKET_WEBHOOK_SECRET - _APP_VCS_WEBHOOK_URL - _APP_FUNCTIONS_TIMEOUT - _APP_SITES_TIMEOUT diff --git a/src/Appwrite/Auth/OAuth2/Bitbucket.php b/src/Appwrite/Auth/OAuth2/Bitbucket.php index 361bc22b65..de8b21145c 100644 --- a/src/Appwrite/Auth/OAuth2/Bitbucket.php +++ b/src/Appwrite/Auth/OAuth2/Bitbucket.php @@ -53,16 +53,19 @@ class Bitbucket extends OAuth2 protected function getTokens(string $code): array { if (empty($this->tokens)) { - // Required as per Bitbucket Spec. - $headers = ['Content-Type: application/x-www-form-urlencoded']; + // Bitbucket wants HTTP Basic Auth here, not client_id/secret in + // the body -- the body form fails silently with a misleading + // "invalid_grant" error instead of an auth error. + $headers = [ + 'Content-Type: application/x-www-form-urlencoded', + 'Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret), + ]; $this->tokens = \json_decode($this->request( 'POST', 'https://bitbucket.org/site/oauth2/access_token', $headers, \http_build_query([ 'code' => $code, - 'client_id' => $this->appID, - 'client_secret' => $this->appSecret, 'grant_type' => 'authorization_code' ]) ), true); @@ -78,14 +81,15 @@ class Bitbucket extends OAuth2 */ public function refreshTokens(string $refreshToken): array { - $headers = ['Content-Type: application/x-www-form-urlencoded']; + $headers = [ + 'Content-Type: application/x-www-form-urlencoded', + 'Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret), + ]; $this->tokens = \json_decode($this->request( 'POST', 'https://bitbucket.org/site/oauth2/access_token', $headers, \http_build_query([ - 'client_id' => $this->appID, - 'client_secret' => $this->appSecret, 'grant_type' => 'refresh_token', 'refresh_token' => $refreshToken ]) @@ -152,6 +156,88 @@ class Bitbucket extends OAuth2 return $user['display_name'] ?? ''; } + /** + * Resolves the account's personal workspace slug, which repository API + * calls need to address. `/user`'s username/nickname aren't valid + * workspace identifiers for migrated accounts (silently returns zero + * repositories rather than an error), and the account's UUID doesn't + * double as its workspace's either, so this goes through + * GET /user/workspaces instead. + * + * @param string $accessToken + * @return string + */ + public function getUserSlug(string $accessToken): string + { + $user = $this->getUser($accessToken); + + $headers = ['Authorization: Bearer ' . $accessToken]; + $workspaces = \json_decode($this->request('GET', 'https://api.bitbucket.org/2.0/user/workspaces', $headers), true); + $values = $workspaces['values'] ?? []; + // Some Bitbucket user-scoped list endpoints wrap the resource under + // its own key (e.g. the older /permissions/workspaces did); accept + // either shape rather than assume this one is flat. + $first = $values[0] ?? []; + $slug = $first['slug'] ?? ($first['workspace']['slug'] ?? ''); + + if (!empty($slug)) { + return $slug; + } + + return $user['username'] ?? ($user['nickname'] ?? ''); + } + + /** + * @link https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-repositories-workspace-repo-slug-post + * + * Bitbucket has no implicit "current user's default namespace" the way + * GitHub/GitLab do -- the workspace is always part of the URL. Defaults + * to the token owner's own workspace (their user slug) when no + * $namespaceId (a workspace slug) is given. + * + * @param string $accessToken + * @param string $repositoryName + * @param bool $private + * @param string $namespaceId + * + * @return array + */ + public function createRepository(string $accessToken, string $repositoryName, bool $private, string $namespaceId = ''): array + { + $workspace = !empty($namespaceId) ? $namespaceId : $this->getUserSlug($accessToken); + + $repository = $this->request( + 'POST', + 'https://api.bitbucket.org/2.0/repositories/' . \rawurlencode($workspace) . '/' . \rawurlencode($repositoryName), + ['Authorization: Bearer ' . $accessToken, 'Content-Type: application/json'], + \json_encode([ + 'scm' => 'git', + 'is_private' => $private, + ]) + ); + + $repository = \json_decode($repository, true) ?? []; + + // Normalize to the GitHub/Gitea/GitLab field shape ProviderRepository expects. + if (isset($repository['uuid'])) { + $repository['id'] = $repository['uuid']; + } + + if (isset($repository['is_private'])) { + $repository['private'] = $repository['is_private']; + } + + if (isset($repository['updated_on'])) { + $repository['pushed_at'] = $repository['updated_on']; + } + + if (isset($repository['error']['message']) && !isset($repository['message'])) { + $repository['message'] = $repository['error']['message']; + } + + return $repository; + } + /** * @param string $accessToken * @@ -160,10 +246,15 @@ class Bitbucket extends OAuth2 protected function getUser(string $accessToken): array { if (empty($this->user)) { - $user = $this->request('GET', 'https://api.bitbucket.org/2.0/user?access_token=' . \urlencode($accessToken)); + // Bitbucket's CHANGE-3052 (enforced since 2026-05-04) removed the + // ?access_token= query param; the token must be sent as a Bearer + // Authorization header instead. + $headers = ['Authorization: Bearer ' . $accessToken]; + + $user = $this->request('GET', 'https://api.bitbucket.org/2.0/user', $headers); $this->user = \json_decode($user, true); - $emails = $this->request('GET', 'https://api.bitbucket.org/2.0/user/emails?access_token=' . \urlencode($accessToken)); + $emails = $this->request('GET', 'https://api.bitbucket.org/2.0/user/emails', $headers); $emails = \json_decode($emails, true); if (isset($emails['values'])) { foreach ($emails['values'] as $email) { diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Bitbucket/Authorize/Get.php b/src/Appwrite/Platform/Modules/VCS/Http/Bitbucket/Authorize/Get.php new file mode 100644 index 0000000000..586bd0fec3 --- /dev/null +++ b/src/Appwrite/Platform/Modules/VCS/Http/Bitbucket/Authorize/Get.php @@ -0,0 +1,42 @@ +setHttpMethod(Action::HTTP_REQUEST_METHOD_POST) + ->setHttpPath('/v1/vcs/bitbucket/events') + ->desc('Create event') + ->groups(['api', 'vcs']) + ->label('scope', 'public') + ->inject('vcsFactory') + ->inject('vcsWebhookSecret') + ->inject('installationTokens') + ->inject('request') + ->inject('response') + ->inject('dbForPlatform') + ->inject('authorization') + ->inject('getProjectDB') + ->inject('deploymentsFactory') + ->inject('platform') + ->callback($this->action(...)); + } + + public function action( + VcsFactory $vcsFactory, + callable $vcsWebhookSecret, + InstallationTokens $installationTokens, + Request $request, + Response $response, + Database $dbForPlatform, + Authorization $authorization, + callable $getProjectDB, + callable $deploymentsFactory, + array $platform + ) { + $vcs = $vcsFactory->fromProvider('bitbucket'); + + $event = $request->getHeaderLine($vcs->getEventHeaderName(), ''); + Span::add('vcs.bitbucket.event.name', $event); + + $payload = $request->getRawPayload(); + $signature = $request->getHeaderLine($vcs->getSignatureHeaderName(), ''); + $secretKey = $vcsWebhookSecret('bitbucket'); + + $valid = !empty($secretKey) && $vcs->validateWebhookEvent($payload, $signature, $secretKey); + Span::add('vcs.bitbucket.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 Bitbucket repository settings and in the _APP_VCS_BITBUCKET_WEBHOOK_SECRET environment variable'); + } + + // A single Bitbucket push delivery batches every branch it touched + $parsedPayloads = $vcs->getEvents($event, $payload); + + foreach ($parsedPayloads as $parsedPayload) { + match ($event) { + 'repo:push' => $this->handlePushEvent($parsedPayload, $vcsFactory, $installationTokens, $dbForPlatform, $authorization, $getProjectDB, $platform, $deploymentsFactory), + 'pullrequest:created', 'pullrequest:updated', 'pullrequest:fulfilled', 'pullrequest:rejected' => $this->handlePullRequestEvent($parsedPayload, $vcsFactory, $installationTokens, $dbForPlatform, $authorization, $getProjectDB, $platform, $deploymentsFactory), + default => null, + }; + } + + $response->json(['events' => $parsedPayloads]); + } + + private function resolveBitbucketInstallation(Document $repository, Database $dbForPlatform, Authorization $authorization): ?Document + { + $installation = $authorization->skip(fn () => $dbForPlatform->getDocument('installations', $repository->getAttribute('installationId', ''))); + + if ($installation->isEmpty() || $installation->getAttribute('provider', 'github') !== 'bitbucket') { + return null; + } + + return $installation; + } + + /** + * A refresh/adapter failure is pushed onto $errors instead of swallowed, so the + * caller can surface a non-2xx response and Bitbucket logs it as a failed delivery. + */ + private function resolveAdapterForRepository(Document $repository, VcsFactory $vcsFactory, InstallationTokens $installationTokens, Database $dbForPlatform, Authorization $authorization, array &$errors): ?Git + { + $installation = $this->resolveBitbucketInstallation($repository, $dbForPlatform, $authorization); + + if ($installation === null) { + return null; + } + + try { + $installation = $installationTokens->refreshForInstallation($installation, $dbForPlatform, $vcsFactory); + + return $vcsFactory->fromInstallation($installation); + } catch (\Throwable $error) { + $message = "Failed to resolve Bitbucket adapter for installation '{$installation->getId()}': " . $error->getMessage(); + Console::warning($message); + Span::add("vcs.bitbucket.event.installation.{$installation->getId()}.error", $message); + $errors[] = $message; + return null; + } + } + + private function handlePushEvent( + array $parsedPayload, + VcsFactory $vcsFactory, + InstallationTokens $installationTokens, + Database $dbForPlatform, + Authorization $authorization, + callable $getProjectDB, + array $platform, + callable $deploymentsFactory, + ) { + $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.bitbucket.event.repo.id', $providerRepositoryId); + Span::add('vcs.bitbucket.event.repo.name', $providerRepositoryName); + Span::add('vcs.bitbucket.event.branch', $providerBranch); + + if ($providerCommitAuthorEmail === APP_VCS_BITBUCKET_EMAIL || $providerBranchDeleted) { + return; + } + + $repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', [ + Query::equal('providerRepositoryId', [$providerRepositoryId]), + Query::limit(100), + ])); + + $providerAffectedFiles = $parsedPayload['affectedFiles'] ?? []; + + $errors = []; + foreach ($repositories as $repository) { + $adapter = $this->resolveAdapterForRepository($repository, $vcsFactory, $installationTokens, $dbForPlatform, $authorization, $errors); + + 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, $getProjectDB, $platform, $deploymentsFactory); + } + + if (!empty($errors)) { + throw new Exception(Exception::GENERAL_UNKNOWN, \implode("\n", $errors)); + } + } + + private function handlePullRequestEvent( + array $parsedPayload, + VcsFactory $vcsFactory, + InstallationTokens $installationTokens, + Database $dbForPlatform, + Authorization $authorization, + callable $getProjectDB, + array $platform, + callable $deploymentsFactory, + ) { + $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.bitbucket.event.repo.id', $providerRepositoryId); + Span::add('vcs.bitbucket.event.repo.name', $providerRepositoryName); + Span::add('vcs.bitbucket.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), + ])); + + $errors = []; + foreach ($repositories as $repository) { + $adapter = $this->resolveAdapterForRepository($repository, $vcsFactory, $installationTokens, $dbForPlatform, $authorization, $errors); + + 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, $getProjectDB, $platform, $deploymentsFactory); + } + + if (!empty($errors)) { + throw new Exception(Exception::GENERAL_UNKNOWN, \implode("\n", $errors)); + } + } elseif ($action === 'closed') { + $providerRepositoryId = $parsedPayload['repositoryId'] ?? ''; + $providerPullRequestId = $parsedPayload['pullRequestNumber'] ?? ''; + $external = $parsedPayload['external'] ?? true; + + if (!$external) { + return; + } + + (new RepositoryPullRequestCleanup())->remove($dbForPlatform, $authorization, 'bitbucket', $providerRepositoryId, $providerPullRequestId); + } + } +} diff --git a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Events/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Events/Create.php index 6a87450cd9..8db5f1d670 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Events/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Events/Create.php @@ -79,16 +79,18 @@ class Create extends Action throw new Exception(Exception::GENERAL_ACCESS_FORBIDDEN, "Invalid webhook payload signature. Please make sure the webhook secret has same value in your GitHub app and in the _APP_VCS_GITHUB_WEBHOOK_SECRET environment variable"); } - $parsedPayload = $vcs->getEvent($event, $payload); + $parsedPayloads = $vcs->getEvents($event, $payload); - match ($event) { - GitHub::EVENT_INSTALLATION => $this->handleInstallationEvent($parsedPayload, $dbForPlatform, $authorization, $getProjectDB), - GitHub::EVENT_PUSH => $this->handlePushEvent($parsedPayload, $vcsFactory, $dbForPlatform, $authorization, $getProjectDB, $platform, $deploymentsFactory), - GitHub::EVENT_PULL_REQUEST => $this->handlePullRequestEvent($parsedPayload, $vcsFactory, $dbForPlatform, $authorization, $getProjectDB, $platform, $deploymentsFactory), - default => null, - }; + foreach ($parsedPayloads as $parsedPayload) { + match ($event) { + GitHub::EVENT_INSTALLATION => $this->handleInstallationEvent($parsedPayload, $dbForPlatform, $authorization, $getProjectDB), + GitHub::EVENT_PUSH => $this->handlePushEvent($parsedPayload, $vcsFactory, $dbForPlatform, $authorization, $getProjectDB, $platform, $deploymentsFactory), + GitHub::EVENT_PULL_REQUEST => $this->handlePullRequestEvent($parsedPayload, $vcsFactory, $dbForPlatform, $authorization, $getProjectDB, $platform, $deploymentsFactory), + default => null, + }; + } - $response->json($parsedPayload); + $response->json(['events' => $parsedPayloads]); } protected function preprocessEvent(Request $request) diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php index 113906151d..02bf1baf71 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Gitea/Events/Create.php @@ -77,15 +77,17 @@ class Create extends Action 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); + $parsedPayloads = $vcs->getEvents($event, $payload); - match ($event) { - 'push' => $this->handlePushEvent($parsedPayload, $vcsFactory, $installationTokens, $dbForPlatform, $authorization, $getProjectDB, $platform, $deploymentsFactory), - 'pull_request' => $this->handlePullRequestEvent($parsedPayload, $vcsFactory, $installationTokens, $dbForPlatform, $authorization, $getProjectDB, $platform, $deploymentsFactory), - default => null, - }; + foreach ($parsedPayloads as $parsedPayload) { + match ($event) { + 'push' => $this->handlePushEvent($parsedPayload, $vcsFactory, $installationTokens, $dbForPlatform, $authorization, $getProjectDB, $platform, $deploymentsFactory), + 'pull_request' => $this->handlePullRequestEvent($parsedPayload, $vcsFactory, $installationTokens, $dbForPlatform, $authorization, $getProjectDB, $platform, $deploymentsFactory), + default => null, + }; + } - $response->json($parsedPayload); + $response->json(['events' => $parsedPayloads]); } private function resolveGiteaInstallation(Document $repository, Database $dbForPlatform, Authorization $authorization): ?Document diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Gitlab/Events/Create.php b/src/Appwrite/Platform/Modules/VCS/Http/Gitlab/Events/Create.php index e770a930a9..f93add52a5 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Gitlab/Events/Create.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Gitlab/Events/Create.php @@ -78,15 +78,17 @@ class Create extends Action throw new Exception(Exception::GENERAL_ACCESS_FORBIDDEN, 'Invalid webhook payload signature. Please make sure the webhook secret has same value in your GitLab repository settings and in the _APP_VCS_GITLAB_WEBHOOK_SECRET environment variable'); } - $parsedPayload = $vcs->getEvent($event, $payload); + $parsedPayloads = $vcs->getEvents($event, $payload); - match ($event) { - 'Push Hook' => $this->handlePushEvent($parsedPayload, $vcsFactory, $installationTokens, $dbForPlatform, $authorization, $getProjectDB, $platform, $deploymentsFactory), - 'Merge Request Hook' => $this->handlePullRequestEvent($parsedPayload, $vcsFactory, $installationTokens, $dbForPlatform, $authorization, $getProjectDB, $platform, $deploymentsFactory), - default => null, - }; + foreach ($parsedPayloads as $parsedPayload) { + match ($event) { + 'Push Hook' => $this->handlePushEvent($parsedPayload, $vcsFactory, $installationTokens, $dbForPlatform, $authorization, $getProjectDB, $platform, $deploymentsFactory), + 'Merge Request Hook' => $this->handlePullRequestEvent($parsedPayload, $vcsFactory, $installationTokens, $dbForPlatform, $authorization, $getProjectDB, $platform, $deploymentsFactory), + default => null, + }; + } - $response->json($parsedPayload); + $response->json(['events' => $parsedPayloads]); } private function resolveGitlabInstallation(Document $repository, Database $dbForPlatform, Authorization $authorization): ?Document diff --git a/src/Appwrite/Platform/Modules/VCS/Http/Installations/Namespaces/XList.php b/src/Appwrite/Platform/Modules/VCS/Http/Installations/Namespaces/XList.php index 21ece11ad9..fc520846c2 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/Installations/Namespaces/XList.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/Installations/Namespaces/XList.php @@ -97,7 +97,24 @@ class XList extends Action $page = ($offset / $limit) + 1; - ['items' => $namespaces, 'total' => $total] = $vcs->listNamespaces($page, $limit, $search); + // listNamespaces() has a throwing default on the abstract Git class + // rather than being absent, so a provider that doesn't report + // namespaces is found by catching, not by checking for the method. + try { + ['items' => $namespaces, 'total' => $total] = $vcs->listNamespaces($page, $limit, $search); + } catch (\Throwable) { + $providerInstallationId = $installation->getAttribute('providerInstallationId', ''); + $owner = $vcs->getOwnerName($providerInstallationId); + $matches = empty($search) || \stripos($owner, $search) !== false; + $namespaces = $matches ? [[ + 'id' => $providerInstallationId, + 'name' => $owner, + 'path' => $owner, + 'kind' => $installation->getAttribute('personal', false) ? 'user' : 'group', + 'avatarUrl' => '', + ]] : []; + $total = \count($namespaces); + } $namespaces = \array_map(fn ($namespace) => new Document([ '$id' => $namespace['id'] ?? '', diff --git a/src/Appwrite/Platform/Modules/VCS/Services/Http.php b/src/Appwrite/Platform/Modules/VCS/Services/Http.php index 063be6bd9d..e078c8fca0 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\Bitbucket\Authorize\Get as GetBitbucketAuthorize; +use Appwrite\Platform\Modules\VCS\Http\Bitbucket\Callback\Get as GetBitbucketCallback; +use Appwrite\Platform\Modules\VCS\Http\Bitbucket\Events\Create as CreateBitbucketEvent; 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; @@ -43,6 +46,10 @@ class Http extends Service $this->addAction(GetGitlabAuthorize::getName(), new GetGitlabAuthorize()); $this->addAction(GetGitlabCallback::getName(), new GetGitlabCallback()); + // Bitbucket Authorization & Callback + $this->addAction(GetBitbucketAuthorize::getName(), new GetBitbucketAuthorize()); + $this->addAction(GetBitbucketCallback::getName(), new GetBitbucketCallback()); + // Installations $this->addAction(GetInstallation::getName(), new GetInstallation()); $this->addAction(ListInstallations::getName(), new ListInstallations()); @@ -61,5 +68,6 @@ class Http extends Service $this->addAction(CreateGitHubEvent::getName(), new CreateGitHubEvent()); $this->addAction(CreateGiteaEvent::getName(), new CreateGiteaEvent()); $this->addAction(CreateGitlabEvent::getName(), new CreateGitlabEvent()); + $this->addAction(CreateBitbucketEvent::getName(), new CreateBitbucketEvent()); } }