mirror of
https://github.com/appwrite/appwrite.git
synced 2026-11-18 20:36:03 +00:00
Fix VCS OAuth polymorphism: registry owns construction, no reflection in tests
Factory::oauth2FromProvider() delegated construction to a static fromEnv() on each OAuth2 class, which re-hardcoded the same env var names the registry's 'variables' map already owns -- two sources of truth for the same mapping. The registry's 'oauth2' key is now a construction closure (clientId, clientSecret, endpoint) -> OAuth2, so Factory just resolves the env values via its own getEnv() and calls it; no per-provider branching in Factory, and no env var name duplicated outside app/config/vcs.php. EnvOAuth2 also conflated two responsibilities (build-from-env, and create-a-repository). Replaced with a narrow RepositoryOAuth2 interface covering only createRepository(), which is the one capability call sites actually need to check for beyond the base OAuth2 contract. Also removes the two reflection-based tests this repo's conventions disallow: FactoryTest asserted on the vendored GitLab adapter's protected $endpoint via ReflectionProperty -- replaced with an assertion on the public getRepositoryUrl() output, which is derived from the same value. GitlabClosedPullRequestEventTest invoked a private handlePullRequestEvent() via ReflectionMethod -- extracted the closed-PR cleanup into RepositoryPullRequestCleanup, a small public collaborator, and tested that directly instead.
This commit is contained in:
1 parent
7c136f3825
commit
e47a2b54dd
12 files changed
+118
-117
No files matched your search
+16
-3
@@ -14,7 +14,10 @@ use Utopia\VCS\Adapter\Git\GitLab;
|
||||
return [
|
||||
'github' => [
|
||||
'adapter' => GitHub::class,
|
||||
'oauth2' => OAuth2Github::class,
|
||||
// Each provider owns its own construction quirks (Gitea calls
|
||||
// setEndpoint(), GitLab JSON-encodes its secret); Factory just
|
||||
// supplies the resolved env values, so no per-provider branching lives there.
|
||||
'oauth2' => fn (string $clientId, string $clientSecret, string $endpoint) => new OAuth2Github($clientId, $clientSecret, ''),
|
||||
'variables' => [
|
||||
'appName' => ['required' => true, 'envVariable' => '_APP_VCS_GITHUB_APP_NAME'],
|
||||
'privateKey' => ['required' => true, 'envVariable' => '_APP_VCS_GITHUB_PRIVATE_KEY'],
|
||||
@@ -26,7 +29,11 @@ return [
|
||||
],
|
||||
'gitea' => [
|
||||
'adapter' => Gitea::class,
|
||||
'oauth2' => OAuth2Gitea::class,
|
||||
'oauth2' => function (string $clientId, string $clientSecret, string $endpoint) {
|
||||
$oauth2 = new OAuth2Gitea($clientId, $clientSecret, '');
|
||||
$oauth2->setEndpoint($endpoint);
|
||||
return $oauth2;
|
||||
},
|
||||
'variables' => [
|
||||
'endpoint' => ['required' => true, 'envVariable' => '_APP_VCS_GITEA_ENDPOINT'],
|
||||
'clientId' => ['required' => true, 'envVariable' => '_APP_VCS_GITEA_CLIENT_ID'],
|
||||
@@ -38,7 +45,13 @@ return [
|
||||
],
|
||||
'gitlab' => [
|
||||
'adapter' => GitLab::class,
|
||||
'oauth2' => OAuth2Gitlab::class,
|
||||
// Auth\OAuth2\Gitlab is shared with the "Sign in with GitLab" account-login
|
||||
// provider, which JSON-encodes its secret as {"clientSecret","endpoint"}
|
||||
// to support a per-project self-hosted endpoint -- match that shape here too.
|
||||
'oauth2' => fn (string $clientId, string $clientSecret, string $endpoint) => new OAuth2Gitlab($clientId, \json_encode([
|
||||
'clientSecret' => $clientSecret,
|
||||
'endpoint' => $endpoint,
|
||||
]), ''),
|
||||
// Only official gitlab.com is supported -- fixed, not configurable.
|
||||
'endpoint' => 'https://gitlab.com',
|
||||
'variables' => [
|
||||
|
||||
@@ -3,10 +3,9 @@
|
||||
namespace Appwrite\Auth\OAuth2;
|
||||
|
||||
use Appwrite\Auth\OAuth2;
|
||||
use Appwrite\Vcs\EnvOAuth2;
|
||||
use Utopia\System\System;
|
||||
use Appwrite\Vcs\RepositoryOAuth2;
|
||||
|
||||
class Gitea extends OAuth2 implements EnvOAuth2
|
||||
class Gitea extends OAuth2 implements RepositoryOAuth2
|
||||
{
|
||||
protected string $endpoint = '';
|
||||
|
||||
@@ -18,14 +17,6 @@ class Gitea extends OAuth2 implements EnvOAuth2
|
||||
'read:user',
|
||||
];
|
||||
|
||||
public static function fromEnv(): OAuth2&EnvOAuth2
|
||||
{
|
||||
$oauth2 = new self(System::getEnv('_APP_VCS_GITEA_CLIENT_ID', ''), System::getEnv('_APP_VCS_GITEA_CLIENT_SECRET', ''), '');
|
||||
$oauth2->setEndpoint(System::getEnv('_APP_VCS_GITEA_ENDPOINT', ''));
|
||||
|
||||
return $oauth2;
|
||||
}
|
||||
|
||||
public function setEndpoint(string $endpoint): void
|
||||
{
|
||||
$this->endpoint = \rtrim($endpoint, '/');
|
||||
|
||||
@@ -3,17 +3,11 @@
|
||||
namespace Appwrite\Auth\OAuth2;
|
||||
|
||||
use Appwrite\Auth\OAuth2;
|
||||
use Appwrite\Vcs\EnvOAuth2;
|
||||
use Appwrite\Vcs\RepositoryOAuth2;
|
||||
use Utopia\Fetch\Client as FetchClient;
|
||||
use Utopia\System\System;
|
||||
|
||||
class Github extends OAuth2 implements EnvOAuth2
|
||||
class Github extends OAuth2 implements RepositoryOAuth2
|
||||
{
|
||||
public static function fromEnv(): OAuth2&EnvOAuth2
|
||||
{
|
||||
return new self(System::getEnv('_APP_VCS_GITHUB_CLIENT_ID', ''), System::getEnv('_APP_VCS_GITHUB_CLIENT_SECRET', ''), '');
|
||||
}
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
|
||||
@@ -3,30 +3,20 @@
|
||||
namespace Appwrite\Auth\OAuth2;
|
||||
|
||||
use Appwrite\Auth\OAuth2;
|
||||
use Appwrite\Vcs\EnvOAuth2;
|
||||
use Utopia\System\System;
|
||||
use Appwrite\Vcs\RepositoryOAuth2;
|
||||
|
||||
// Reference Material
|
||||
// https://docs.gitlab.com/ee/api/oauth2.html
|
||||
|
||||
class Gitlab extends OAuth2 implements EnvOAuth2
|
||||
/**
|
||||
* Shared with the "Sign in with GitLab" account-login OAuth2 provider, which
|
||||
* stores its secret as JSON ({"clientSecret": "...", "endpoint": "..."}) to
|
||||
* support self-hosted GitLab per-project. The VCS flow (see app/config/vcs.php)
|
||||
* only supports official gitlab.com, but still encodes to that same JSON
|
||||
* shape so getAppSecret()/getEndpoint() stay correct for both consumers.
|
||||
*/
|
||||
class Gitlab extends OAuth2 implements RepositoryOAuth2
|
||||
{
|
||||
/**
|
||||
* This class is shared with the "Sign in with GitLab" account-login
|
||||
* OAuth2 provider, which stores its secret as JSON
|
||||
* ({"clientSecret": "...", "endpoint": "..."}) to support self-hosted
|
||||
* GitLab per-project. The VCS flow only supports official gitlab.com,
|
||||
* but still encodes to that same JSON shape so getAppSecret()/getEndpoint()
|
||||
* stay correct for both consumers.
|
||||
*/
|
||||
public static function fromEnv(): OAuth2&EnvOAuth2
|
||||
{
|
||||
return new self(System::getEnv('_APP_VCS_GITLAB_CLIENT_ID', ''), \json_encode([
|
||||
'clientSecret' => System::getEnv('_APP_VCS_GITLAB_CLIENT_SECRET', ''),
|
||||
'endpoint' => 'https://gitlab.com',
|
||||
]), '');
|
||||
}
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
|
||||
@@ -9,6 +9,7 @@ use Appwrite\Utopia\Request;
|
||||
use Appwrite\Utopia\Response;
|
||||
use Appwrite\Vcs\Factory as VcsFactory;
|
||||
use Appwrite\Vcs\InstallationTokens;
|
||||
use Appwrite\Vcs\RepositoryPullRequestCleanup;
|
||||
use Utopia\Console;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
@@ -261,24 +262,7 @@ class Create extends Action
|
||||
return;
|
||||
}
|
||||
|
||||
$repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', [
|
||||
Query::equal('providerRepositoryId', [$providerRepositoryId]),
|
||||
Query::orderDesc('$createdAt'),
|
||||
Query::limit(100),
|
||||
]));
|
||||
|
||||
foreach ($repositories as $repository) {
|
||||
if ($this->resolveGitlabInstallation($repository, $dbForPlatform, $authorization) === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$providerPullRequestIds = $repository->getAttribute('providerPullRequestIds', []);
|
||||
|
||||
if (\in_array($providerPullRequestId, $providerPullRequestIds)) {
|
||||
$providerPullRequestIds = \array_diff($providerPullRequestIds, [$providerPullRequestId]);
|
||||
$authorization->skip(fn () => $dbForPlatform->updateDocument('repositories', $repository->getId(), new Document(['providerPullRequestIds' => $providerPullRequestIds])));
|
||||
}
|
||||
}
|
||||
(new RepositoryPullRequestCleanup())->remove($dbForPlatform, $authorization, 'gitlab', $providerRepositoryId, $providerPullRequestId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response;
|
||||
use Appwrite\Vcs\Factory as VcsFactory;
|
||||
use Appwrite\Vcs\InstallationTokens;
|
||||
use Appwrite\Vcs\RepositoryOAuth2;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Query;
|
||||
@@ -80,6 +81,10 @@ class Create extends Action
|
||||
if ($installation->getAttribute('personal', false) === true) {
|
||||
$oauth2 = $vcsFactory->oauth2FromProvider($provider);
|
||||
|
||||
if (!$oauth2 instanceof RepositoryOAuth2) {
|
||||
throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'VCS provider does not support repository creation: ' . $provider);
|
||||
}
|
||||
|
||||
$identity = null;
|
||||
if ($provider === 'github' && (empty($installation->getAttribute('personalAccessToken')) || empty($installation->getAttribute('personalRefreshToken')) || empty($installation->getAttribute('personalAccessTokenExpiry')))) {
|
||||
$identity = $dbForPlatform->findOne('identities', [
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Vcs;
|
||||
|
||||
use Appwrite\Auth\OAuth2;
|
||||
|
||||
/**
|
||||
* Implemented by OAuth2 providers usable as a VCS installation's token-refresh
|
||||
* client. Unlike login-only OAuth2 providers (constructed per-project from
|
||||
* console-configured credentials), these are server-configured and can build
|
||||
* themselves from environment variables.
|
||||
*/
|
||||
interface EnvOAuth2
|
||||
{
|
||||
public static function fromEnv(): OAuth2&EnvOAuth2;
|
||||
|
||||
public function createRepository(string $accessToken, string $repositoryName, bool $private): array;
|
||||
}
|
||||
@@ -95,15 +95,25 @@ class Factory
|
||||
return $this->getEnv($key, 'webhookSecret');
|
||||
}
|
||||
|
||||
public function oauth2FromProvider(string $key): OAuth2&EnvOAuth2
|
||||
public function oauth2FromProvider(string $key): OAuth2
|
||||
{
|
||||
$class = $this->registry[$key]['oauth2'] ?? null;
|
||||
$builder = $this->registry[$key]['oauth2'] ?? null;
|
||||
|
||||
if ($class === null || !\is_a($class, EnvOAuth2::class, true)) {
|
||||
if (!\is_callable($builder)) {
|
||||
throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Unsupported VCS provider: ' . $key);
|
||||
}
|
||||
|
||||
return $class::fromEnv();
|
||||
$clientId = $this->getEnv($key, 'clientId');
|
||||
$clientSecret = $this->getEnv($key, 'clientSecret');
|
||||
$endpoint = $this->registry[$key]['endpoint'] ?? $this->getEnv($key, 'endpoint');
|
||||
|
||||
$oauth2 = $builder($clientId, $clientSecret, $endpoint);
|
||||
|
||||
if (!$oauth2 instanceof OAuth2) {
|
||||
throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'VCS provider "' . $key . '" oauth2 builder returned an invalid client');
|
||||
}
|
||||
|
||||
return $oauth2;
|
||||
}
|
||||
|
||||
protected function getEnv(string $key, string $name): string
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Vcs;
|
||||
|
||||
/**
|
||||
* Implemented by OAuth2 providers that can create a repository on behalf of
|
||||
* a personal VCS installation. Narrow on purpose -- it's the only capability
|
||||
* call sites need to check for beyond the base OAuth2 contract; construction
|
||||
* from environment variables is the Factory's job, not the provider's.
|
||||
*/
|
||||
interface RepositoryOAuth2
|
||||
{
|
||||
public function createRepository(string $accessToken, string $repositoryName, bool $private): array;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Vcs;
|
||||
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Query;
|
||||
use Utopia\Database\Validator\Authorization;
|
||||
|
||||
/**
|
||||
* Untracks a closed/merged pull request from every repository connected to
|
||||
* it, scoped to a single provider (a GitHub and a GitLab repository can
|
||||
* share the same numeric providerRepositoryId, since each is scoped to its
|
||||
* own server).
|
||||
*/
|
||||
class RepositoryPullRequestCleanup
|
||||
{
|
||||
public function remove(
|
||||
Database $dbForPlatform,
|
||||
Authorization $authorization,
|
||||
string $provider,
|
||||
string $providerRepositoryId,
|
||||
int|string $providerPullRequestId,
|
||||
): void {
|
||||
$repositories = $authorization->skip(fn () => $dbForPlatform->find('repositories', [
|
||||
Query::equal('providerRepositoryId', [$providerRepositoryId]),
|
||||
Query::orderDesc('$createdAt'),
|
||||
Query::limit(100),
|
||||
]));
|
||||
|
||||
foreach ($repositories as $repository) {
|
||||
$installation = $authorization->skip(fn () => $dbForPlatform->getDocument('installations', $repository->getAttribute('installationId', '')));
|
||||
|
||||
if ($installation->isEmpty() || $installation->getAttribute('provider', 'github') !== $provider) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$providerPullRequestIds = $repository->getAttribute('providerPullRequestIds', []);
|
||||
|
||||
if (\in_array($providerPullRequestId, $providerPullRequestIds)) {
|
||||
$providerPullRequestIds = \array_diff($providerPullRequestIds, [$providerPullRequestId]);
|
||||
$authorization->skip(fn () => $dbForPlatform->updateDocument('repositories', $repository->getId(), new Document(['providerPullRequestIds' => $providerPullRequestIds])));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,8 @@ namespace Tests\Unit\Vcs;
|
||||
|
||||
use Appwrite\Auth\OAuth2\Github as OAuth2Github;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\Vcs\EnvOAuth2;
|
||||
use Appwrite\Vcs\Factory;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use ReflectionProperty;
|
||||
use Utopia\Cache\Adapter\None;
|
||||
use Utopia\Cache\Cache;
|
||||
use Utopia\Config\Config;
|
||||
@@ -33,7 +31,7 @@ final class FactoryTest extends TestCase
|
||||
|
||||
foreach ($registry as $key => $entry) {
|
||||
$this->assertTrue(\is_subclass_of($entry['adapter'], Git::class), "Adapter for '{$key}' must extend Git");
|
||||
$this->assertContains(EnvOAuth2::class, \class_implements($entry['oauth2']) ?: [], "OAuth2 client for '{$key}' must implement EnvOAuth2");
|
||||
$this->assertIsCallable($entry['oauth2'], "OAuth2 builder for '{$key}' must be callable");
|
||||
$this->assertNotEmpty($entry['variables'], "Variables missing for '{$key}'");
|
||||
foreach ($entry['variables'] as $name => $variable) {
|
||||
$this->assertStringStartsWith('_APP_VCS_', $variable['envVariable'] ?? '', "Env variable for '{$name}' missing or invalid for '{$key}'");
|
||||
@@ -127,8 +125,7 @@ final class FactoryTest extends TestCase
|
||||
$factory = new Factory($this->cache(), ['gitlab' => $entry]);
|
||||
|
||||
$adapter = $factory->fromProvider('gitlab');
|
||||
$property = new ReflectionProperty($adapter, 'endpoint');
|
||||
$this->assertSame('https://gitlab.com/api/v4', $property->getValue($adapter));
|
||||
$this->assertSame('https://gitlab.com/owner/repo', $adapter->getRepositoryUrl('owner', 'repo'));
|
||||
}
|
||||
|
||||
public function testFromProviderFixedEndpointIgnoresEnv(): void
|
||||
@@ -142,8 +139,7 @@ final class FactoryTest extends TestCase
|
||||
|
||||
\putenv('_APP_VCS_TEST_ENDPOINT=https://gitlab.example.com');
|
||||
$adapter = $factory->fromProvider('gitlab');
|
||||
$property = new ReflectionProperty($adapter, 'endpoint');
|
||||
$this->assertSame('https://gitlab.com/api/v4', $property->getValue($adapter));
|
||||
$this->assertSame('https://gitlab.com/owner/repo', $adapter->getRepositoryUrl('owner', 'repo'));
|
||||
}
|
||||
|
||||
public function testGetWebhookSecret(): void
|
||||
@@ -169,7 +165,7 @@ final class FactoryTest extends TestCase
|
||||
{
|
||||
return [
|
||||
'adapter' => GitHub::class,
|
||||
'oauth2' => OAuth2Github::class,
|
||||
'oauth2' => fn (string $clientId, string $clientSecret, string $endpoint) => new OAuth2Github($clientId, $clientSecret, ''),
|
||||
'variables' => [
|
||||
'appName' => ['required' => true, 'envVariable' => '_APP_VCS_GITHUB_APP_NAME'],
|
||||
'privateKey' => ['required' => true, 'envVariable' => '_APP_VCS_GITHUB_PRIVATE_KEY'],
|
||||
|
||||
+4
-28
@@ -4,25 +4,15 @@ declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Vcs;
|
||||
|
||||
use Appwrite\Platform\Modules\VCS\Http\Gitlab\Events\Create;
|
||||
use Appwrite\Vcs\Factory as VcsFactory;
|
||||
use Appwrite\Vcs\InstallationTokens;
|
||||
use Appwrite\Vcs\RepositoryPullRequestCleanup;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use ReflectionMethod;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Validator\Authorization;
|
||||
|
||||
final class GitlabClosedPullRequestEventTest extends TestCase
|
||||
final class RepositoryPullRequestCleanupTest extends TestCase
|
||||
{
|
||||
private Create $handler;
|
||||
|
||||
public function setUp(): void
|
||||
{
|
||||
$this->handler = new Create();
|
||||
}
|
||||
|
||||
public function testClosedEventOnlyUpdatesGitlabRepositories(): void
|
||||
public function testRemoveOnlyUpdatesGitlabRepositories(): void
|
||||
{
|
||||
// A GitHub repo and a GitLab repo can share the same numeric
|
||||
// providerRepositoryId since each is scoped to its own server.
|
||||
@@ -64,20 +54,6 @@ final class GitlabClosedPullRequestEventTest extends TestCase
|
||||
return true;
|
||||
}));
|
||||
|
||||
$vcsFactory = $this->createStub(VcsFactory::class);
|
||||
$installationTokens = $this->createStub(InstallationTokens::class);
|
||||
$deploymentsFactory = fn () => null;
|
||||
|
||||
$this->callHandler('handlePullRequestEvent', [
|
||||
'action' => 'closed',
|
||||
'repositoryId' => '5',
|
||||
'pullRequestNumber' => 5,
|
||||
'external' => true,
|
||||
], $vcsFactory, $installationTokens, $dbForPlatform, $authorization, fn () => null, [], $deploymentsFactory);
|
||||
}
|
||||
|
||||
private function callHandler(string $method, mixed ...$arguments): mixed
|
||||
{
|
||||
return (new ReflectionMethod($this->handler, $method))->invoke($this->handler, ...$arguments);
|
||||
(new RepositoryPullRequestCleanup())->remove($dbForPlatform, $authorization, 'gitlab', '5', 5);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user