From 7e567de8fea907caa22b9f270c8f76cc0eee9dc2 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 16:31:27 +0530 Subject: [PATCH 01/12] fix(deployments): canonicalize the root directory an artifact indexes into MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `providerRootDirectory` reached the jobs-service through `trim($subdir, '/')`, which strips slashes but not dots. `docs`, `docs/` and `/docs` all canonicalized to `docs`, while `./docs` survived verbatim as an artifact subdir naming a path segment that does not exist in the extracted tree. `.` and `./` were worse: they collapsed to a non-empty `.`, so the repository-root case emitted a subdir instead of omitting one. Canonicalize on the consume side, in `Deployments::rootDirectory()`. Every remote-source build funnels through `submit()`, so one choke point covers new writes, rows already holding `./docs`, webhooks, duplicates and templates without a migration. Drop whole `.` segments rather than trimming the character. The builds worker's `ltrim($path, '.')` turned `.github` into `github` — a silent wrong-directory build — and left `../etc` traversal intact. Both worker call sites now share the canonicalizer, and the jobs-service hand-off passes the canonicalized value instead of re-reading the raw attribute, which also closes a mismatch where the template push committed at a space-stripped path but sent the space-bearing one. `..` segments are dropped rather than resolved, so a subdir cannot escape the tree it indexes into. --- src/Appwrite/Deployment/Deployments.php | 29 +++++++- .../Modules/Functions/Workers/Builds.php | 12 +-- tests/unit/Deployment/DeploymentsTest.php | 74 ++++++++++++++++++- 3 files changed, 101 insertions(+), 14 deletions(-) diff --git a/src/Appwrite/Deployment/Deployments.php b/src/Appwrite/Deployment/Deployments.php index 1112a4bab2..79db97a904 100644 --- a/src/Appwrite/Deployment/Deployments.php +++ b/src/Appwrite/Deployment/Deployments.php @@ -293,6 +293,31 @@ readonly class Deployments return $this->dbForProject->getDocument('deployments', $deploymentId)->getAttribute('status', ''); } + /** + * Canonicalize a root directory into the subdirectory path an artifact can + * match against a tree: no leading `./`, no surrounding slashes, `''` for + * the repository root. + * + * The console's directory picker and every shipped site template write the + * path with a `./` prefix (`./astro/starter`), while a hand-typed one is + * usually bare (`docs`) and sometimes trailing-slashed (`docs/`). All three + * name the same directory, so all three must produce the same subdir. + * + * Dropping whole `.` segments rather than trimming the character keeps a + * hidden directory intact — `ltrim('.github', '.')` would deploy `github`. + * `..` segments are dropped for the same reason a subdir cannot escape the + * tree it indexes into. + */ + public static function rootDirectory(string $rootDirectory): string + { + $segments = \array_filter( + \explode('/', $rootDirectory), + fn (string $segment) => $segment !== '' && $segment !== '.' && $segment !== '..', + ); + + return \implode('/', $segments); + } + /** * The build command for a deployment: its buildCommands, wrapped for * sites with the framework's env and bundle commands. @@ -385,12 +410,12 @@ readonly class Deployments // - otherwise: the deployment's uploaded tarball, fetched from Appwrite // over a presigned GET (manual upload / duplicate). if (isset($source['clone'])) { - $subdir = \trim($source['subdir'] ?? '', '/'); + $subdir = self::rootDirectory($source['subdir'] ?? ''); $sourceArtifacts = [ new CloneArtifact(id: 'source', in: $source['clone'], out: 'source', ref: $source['ref'] ?? '', subdir: $subdir, headers: $source['headers'] ?? []), ]; } elseif ($source !== null) { - $subdir = \trim($source['subdir'] ?? '', '/'); + $subdir = self::rootDirectory($source['subdir'] ?? ''); $sourceArtifacts = [ new DownloadArtifact(id: 'source', in: $source['url'], out: 'source.tar.gz', headers: $source['headers'] ?? []), new UnarchiveArtifact(id: 'extract', in: 'source.tar.gz', out: 'source', subdir: $subdir !== '' ? $subdir : null, strip: true, depends: 'source'), diff --git a/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php b/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php index eee89f1a5d..7a7ae264bb 100644 --- a/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php +++ b/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php @@ -275,10 +275,7 @@ class Builds extends Action try { // VCS and VCS+Temaplte $tmpDirectory = '/tmp/builds/' . $deploymentId . '/code'; - $rootDirectory = $resource->getAttribute('providerRootDirectory', ''); - $rootDirectory = \rtrim($rootDirectory, '/'); - $rootDirectory = \ltrim($rootDirectory, '.'); - $rootDirectory = \ltrim($rootDirectory, '/'); + $rootDirectory = Deployments::rootDirectory($resource->getAttribute('providerRootDirectory', '')); $owner = $providerAdapter->getOwnerName($providerInstallationId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); @@ -333,10 +330,7 @@ class Builds extends Action $templateReferenceType = $template->getAttribute('referenceType', ''); $templateReferenceValue = $template->getAttribute('referenceValue', ''); - $templateRootDirectory = $template->getAttribute('rootDirectory', ''); - $templateRootDirectory = \rtrim($templateRootDirectory, '/'); - $templateRootDirectory = \ltrim($templateRootDirectory, '.'); - $templateRootDirectory = \ltrim($templateRootDirectory, '/'); + $templateRootDirectory = Deployments::rootDirectory($template->getAttribute('rootDirectory', '')); if (! empty($templateRepositoryName) && ! empty($templateOwnerName) && ! empty($templateReferenceType) && ! empty($templateReferenceValue)) { // Clone template repo @@ -403,7 +397,7 @@ class Builds extends Action $cloneOwner, $cloneRepository, $ref, - $resource->getAttribute('providerRootDirectory', ''), + $rootDirectory, ); Console::execute('rm -rf ' . \escapeshellarg('/tmp/builds/' . $deploymentId), '', $stdout, $stderr); diff --git a/tests/unit/Deployment/DeploymentsTest.php b/tests/unit/Deployment/DeploymentsTest.php index de41f435d3..9f04c67a04 100644 --- a/tests/unit/Deployment/DeploymentsTest.php +++ b/tests/unit/Deployment/DeploymentsTest.php @@ -6,6 +6,7 @@ namespace Tests\Unit\Deployment; use Appwrite\Deployment\Deployments; use Appwrite\Extend\Exception; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Utopia\Config\Config; use Utopia\Database\Document; @@ -35,6 +36,32 @@ final class DeploymentsTest extends TestCase ); } + public static function rootDirectories(): \Iterator + { + yield 'repository root' => ['', '']; + yield 'dot' => ['.', '']; + yield 'dot slash' => ['./', '']; + yield 'bare' => ['docs', 'docs']; + yield 'trailing slash' => ['docs/', 'docs']; + yield 'dot slash prefix' => ['./docs', 'docs']; + yield 'dot slash prefix and trailing slash' => ['./docs/', 'docs']; + yield 'leading slash' => ['/docs', 'docs']; + yield 'nested' => ['docs/nested', 'docs/nested']; + yield 'nested with prefix and trailing slash' => ['./docs/nested/', 'docs/nested']; + yield 'shipped site template' => ['./astro/starter', 'astro/starter']; + yield 'hidden directory' => ['.github', '.github']; + yield 'dot-prefixed name' => ['..foo', '..foo']; + yield 'nested hidden directory' => ['./.github/actions', '.github/actions']; + yield 'traversal' => ['../etc', 'etc']; + yield 'embedded traversal' => ['./docs/../../etc', 'docs/etc']; + } + + #[DataProvider('rootDirectories')] + public function testRootDirectoryCanonicalizes(string $rootDirectory, string $expected): void + { + $this->assertSame($expected, Deployments::rootDirectory($rootDirectory)); + } + public function testFunctionCommandIsDeploymentBuildCommands(): void { $resource = new Document(['$collection' => 'functions']); @@ -128,7 +155,7 @@ final class DeploymentsTest extends TestCase $this->assertSame(['users.read'], Deployments::scopes($site)); } - private function buildPayload(array $vars): array + private function buildPayload(array $vars, ?array $source = null): array { // Presigned-URL and ephemeral-key signing both run before the // variables are assembled, and refuse an empty key. @@ -150,9 +177,50 @@ final class DeploymentsTest extends TestCase ]), new Document(['$id' => 'deployment1', 'buildCommands' => 'npm install']), ['apiHostname' => 'localhost'], + $source, ); } + private function artifact(array $payload, string $id): object + { + foreach ($payload['artifacts'] as $artifact) { + if ($artifact->id === $id) { + return $artifact; + } + } + + $this->fail("No '{$id}' artifact in the payload"); + } + + public function testPayloadUnarchivesFromCanonicalSubdirectory(): void + { + $payload = $this->buildPayload([], ['url' => 'https://example.com/x.tar.gz', 'subdir' => './docs/nested/']); + + $this->assertSame('docs/nested', $this->artifact($payload, 'extract')->subdir); + } + + #[DataProvider('repositoryRoots')] + public function testPayloadOmitsSubdirectoryForRepositoryRoot(string $rootDirectory): void + { + $payload = $this->buildPayload([], ['url' => 'https://example.com/x.tar.gz', 'subdir' => $rootDirectory]); + + $this->assertNull($this->artifact($payload, 'extract')->subdir); + } + + public static function repositoryRoots(): \Iterator + { + yield 'empty' => ['']; + yield 'dot' => ['.']; + yield 'dot slash' => ['./']; + } + + public function testPayloadClonesFromCanonicalSubdirectory(): void + { + $payload = $this->buildPayload([], ['clone' => 'https://example.com/r.git', 'ref' => 'main', 'subdir' => './docs']); + + $this->assertSame('docs', $this->artifact($payload, 'source')->subdir); + } + public function testPayloadRefusesVariableKeyTheClusterWouldRefuse(): void { try { @@ -178,8 +246,8 @@ final class DeploymentsTest extends TestCase final readonly class ExposedDeployments extends Deployments { - public static function submitPayload(Document $project, Document $resource, Document $deployment, array $platform): array + public static function submitPayload(Document $project, Document $resource, Document $deployment, array $platform, ?array $source = null): array { - return static::payload($project, $resource, $deployment, $platform); + return static::payload($project, $resource, $deployment, $platform, $source); } } From cdefa07dc538f76b7f6e60daa668c7695c2228d2 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 16:31:33 +0530 Subject: [PATCH 02/12] fix(vcs): record the root directory on webhook deployments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shared deployment document carried every other `provider*` field but not `providerRootDirectory`, so a push-triggered deployment persisted an empty root directory. The build itself was correct — the root directory is passed separately — but duplicating such a deployment reads the value back off the source document, so a redeploy silently built from the repository root. The trait is shared by GitHub, GitLab, Gitea, Bitbucket and Origin. --- src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php index d9e123764f..5f863dd65c 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php @@ -391,6 +391,7 @@ trait Deployment 'providerCommitUrl' => $providerCommitUrl, 'providerCommentId' => \strval($latestCommentId), 'providerBranch' => $providerBranch, + 'providerRootDirectory' => $resource->getAttribute('providerRootDirectory', ''), 'activate' => $activate, ]); From 922f601f3e71037e70627686ec4144427fdf09e6 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 16:39:17 +0530 Subject: [PATCH 03/12] fix(deployments): refuse a root directory that leaves the repository MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dropping `..` segments made `docs/../x` build `docs/x`, which is neither the directory the caller named nor the one POSIX would resolve — and if both exist, the wrong application deploys with no warning. Resolving the segment instead would let the subdir climb out of the tree it indexes into. Refuse the path instead. The failure is the owner's to fix, so it joins the refused-variable-key case in carrying its reason into the build log rather than a generic internal error. --- app/config/errors.php | 5 +++++ src/Appwrite/Deployment/Deployments.php | 26 +++++++++++++++++------ src/Appwrite/Extend/Exception.php | 1 + tests/unit/Deployment/DeploymentsTest.php | 24 +++++++++++++++++++-- 4 files changed, 47 insertions(+), 9 deletions(-) diff --git a/app/config/errors.php b/app/config/errors.php index dc0cccc6d1..f01d4bf0b7 100644 --- a/app/config/errors.php +++ b/app/config/errors.php @@ -734,6 +734,11 @@ return [ 'description' => 'Deployment with the requested ID could not be found.', 'code' => 404, ], + Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY => [ + 'name' => Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY, + 'description' => 'Root directory must stay inside the repository. Remove the ".." segments, then retry the deployment.', + 'code' => 400, + ], Exception::DEPLOYMENT_INVALID_FILE_SIZE => [ 'name' => Exception::DEPLOYMENT_INVALID_FILE_SIZE, 'description' => 'The deployment file size is either not valid or exceeds the maximum allowed size. Please check the file or the value of the _APP_COMPUTE_SIZE_LIMIT environment variable.', diff --git a/src/Appwrite/Deployment/Deployments.php b/src/Appwrite/Deployment/Deployments.php index 79db97a904..e1996c8be3 100644 --- a/src/Appwrite/Deployment/Deployments.php +++ b/src/Appwrite/Deployment/Deployments.php @@ -223,10 +223,11 @@ readonly class Deployments try { $this->jobs->create(...static::payload($this->project, $resource, $deployment, $this->platform, $source)); } catch (\Throwable $error) { - // A refused variable key is the owner's to fix, so the build log - // carries the actual reason; anything else stays a generic - // internal error. - $buildLogs = $error instanceof Exception && $error->getType() === Exception::VARIABLE_INVALID_KEY + // A refused variable key or root directory is the owner's to fix, + // so the build log carries the actual reason; anything else stays a + // generic internal error. + $owned = [Exception::VARIABLE_INVALID_KEY, Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY]; + $buildLogs = $error instanceof Exception && \in_array($error->getType(), $owned, true) ? "\n" . $error->getMessage() . "\n" : "\nAn internal error occurred while building. Please try again, and contact support if the problem persists.\n"; @@ -305,16 +306,27 @@ readonly class Deployments * * Dropping whole `.` segments rather than trimming the character keeps a * hidden directory intact — `ltrim('.github', '.')` would deploy `github`. - * `..` segments are dropped for the same reason a subdir cannot escape the - * tree it indexes into. + * + * A `..` segment is refused rather than dropped or resolved. Dropping it + * would silently build `docs/x` for a `docs/../x` that names `x`, and + * resolving it would let the subdir climb out of the tree it indexes into. + * + * @throws Exception when a segment would leave the repository */ public static function rootDirectory(string $rootDirectory): string { $segments = \array_filter( \explode('/', $rootDirectory), - fn (string $segment) => $segment !== '' && $segment !== '.' && $segment !== '..', + fn (string $segment) => $segment !== '' && $segment !== '.', ); + if (\in_array('..', $segments, true)) { + throw new Exception( + Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY, + 'Root directory ' . \json_encode($rootDirectory) . ' must stay inside the repository. Remove the ".." segments, then retry the deployment.' + ); + } + return \implode('/', $segments); } diff --git a/src/Appwrite/Extend/Exception.php b/src/Appwrite/Extend/Exception.php index 7c4fe95295..a25ee9397d 100644 --- a/src/Appwrite/Extend/Exception.php +++ b/src/Appwrite/Extend/Exception.php @@ -191,6 +191,7 @@ class Exception extends \Exception /** Deployments */ public const string DEPLOYMENT_NOT_FOUND = 'deployment_not_found'; public const string DEPLOYMENT_INVALID_FILE_SIZE = 'deployment_invalid_file_size'; + public const string DEPLOYMENT_INVALID_ROOT_DIRECTORY = 'deployment_invalid_root_directory'; /** Builds */ public const string BUILD_NOT_FOUND = 'build_not_found'; diff --git a/tests/unit/Deployment/DeploymentsTest.php b/tests/unit/Deployment/DeploymentsTest.php index 9f04c67a04..aee91f6b6d 100644 --- a/tests/unit/Deployment/DeploymentsTest.php +++ b/tests/unit/Deployment/DeploymentsTest.php @@ -52,8 +52,6 @@ final class DeploymentsTest extends TestCase yield 'hidden directory' => ['.github', '.github']; yield 'dot-prefixed name' => ['..foo', '..foo']; yield 'nested hidden directory' => ['./.github/actions', '.github/actions']; - yield 'traversal' => ['../etc', 'etc']; - yield 'embedded traversal' => ['./docs/../../etc', 'docs/etc']; } #[DataProvider('rootDirectories')] @@ -62,6 +60,28 @@ final class DeploymentsTest extends TestCase $this->assertSame($expected, Deployments::rootDirectory($rootDirectory)); } + #[DataProvider('escapingRootDirectories')] + public function testRootDirectoryRefusesSegmentLeavingTheRepository(string $rootDirectory): void + { + try { + Deployments::rootDirectory($rootDirectory); + $this->fail('Expected the root directory to be refused before job submission'); + } catch (Exception $error) { + $this->assertSame(Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY, $error->getType()); + } + } + + public static function escapingRootDirectories(): \Iterator + { + yield 'parent' => ['..']; + yield 'parent path' => ['../etc']; + yield 'parent path with prefix' => ['./../etc']; + // Dropping the segment would silently build 'docs/x'; resolving it, + // 'x'. Neither is the directory the caller named. + yield 'interior parent' => ['docs/../x']; + yield 'escaping interior parent' => ['./docs/../../etc']; + } + public function testFunctionCommandIsDeploymentBuildCommands(): void { $resource = new Document(['$collection' => 'functions']); From 88ed9ab46bd93bf8094639dfa3f54d1959e0b0bd Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 16:39:24 +0530 Subject: [PATCH 04/12] test(vcs): cover a nested root directory through push and duplicate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Builds a function from './docs/nested/' — the form the console's directory picker writes — over the Gitea suite, the only live-VCS suite CI boots. Covers both halves observably: the push-created deployment must execute the nested entrypoint, and duplicating it must reach 'ready'. A duplicate reads the root directory back off the source deployment, so a regression that stops persisting it builds from the repository root, where the auto-init README is the only file and no entrypoint exists. --- .../VCSGitea/VCSGiteaConsoleClientTest.php | 83 ++++++++++++++++++- 1 file changed, 81 insertions(+), 2 deletions(-) diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index abd16dc7fa..5b7d99902c 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -110,6 +110,80 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-v2'), 30000, 1000); } + public function testCreateDeploymentFromNestedRootDirectory(): void + { + $projectId = $this->getProject()['$id']; + $installationId = $this->createInstallationHelper()['$id']; + + $repository = $this->giteaApiHelper(Client::METHOD_POST, '/api/v1/user/repos', [ + 'name' => 'function-' . \uniqid(), + 'auto_init' => true, + 'default_branch' => 'main', + 'private' => false, + ]); + $this->assertEquals(201, $repository['headers']['status-code'], \json_encode($repository['body'])); + $repositoryName = $repository['body']['name']; + + $workdir = \sys_get_temp_dir() . '/vcs-gitea-' . \uniqid(); + $endpoint = System::getEnv('_APP_VCS_GITEA_ENDPOINT', 'http://gitea:3000'); + $remote = \str_replace('://', '://' . self::GITEA_USERNAME . ':' . self::GITEA_PASSWORD . '@', $endpoint) + . '/' . self::GITEA_USERNAME . '/' . $repositoryName . '.git'; + + $this->gitHelper("git clone {$remote} {$workdir}", \sys_get_temp_dir()); + $this->writeFunctionHelper($workdir, 'gitea-nested-v1', 'docs/nested'); + $this->gitHelper('git add docs && git commit -m "Add nested function"', $workdir); + $this->gitHelper('git push origin main', $workdir); + + // The console's directory picker writes the path in this form; it names + // the same directory as 'docs/nested'. + $function = $this->client->call(Client::METHOD_POST, '/functions', \array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + ], $this->getHeaders()), [ + 'functionId' => ID::unique(), + 'name' => 'Gitea nested VCS', + 'execute' => [Role::any()->toString()], + 'runtime' => 'node-22', + 'entrypoint' => 'index.js', + 'timeout' => 15, + 'installationId' => $installationId, + 'providerRepositoryId' => (string) $repository['body']['id'], + 'providerBranch' => 'main', + 'providerRootDirectory' => './docs/nested/', + ]); + $this->assertEquals(201, $function['headers']['status-code'], \json_encode($function['body'])); + $functionId = $function['body']['$id']; + + $knownIds = $this->listDeploymentIdsHelper($functionId); + + $this->writeFunctionHelper($workdir, 'gitea-nested-v2', 'docs/nested'); + $this->gitHelper('git add docs && git commit -m "Update nested function"', $workdir); + $this->gitHelper('git push origin main', $workdir); + + $webhookDeploymentId = $this->waitForNewDeploymentReadyHelper($functionId, $knownIds); + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2'), 30000, 1000); + + // A push-created deployment must persist the root directory it built + // from, since duplicating one reads the value back off this document. + $webhookDeployment = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/deployments/' . $webhookDeploymentId, \array_merge([ + 'x-appwrite-project' => $projectId, + ], $this->getHeaders())); + $this->assertEquals(200, $webhookDeployment['headers']['status-code']); + $this->assertEquals('./docs/nested/', $webhookDeployment['body']['providerRootDirectory']); + + $duplicate = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', \array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + ], $this->getHeaders()), [ + 'deploymentId' => $webhookDeploymentId, + ]); + $this->assertEquals(202, $duplicate['headers']['status-code'], \json_encode($duplicate['body'])); + + // Building from the repository root instead would fail outright: the + // root holds only the auto-init README, no entrypoint. + $this->waitForDeploymentReadyHelper($functionId, $duplicate['body']['$id']); + } + public function testClosePullRequestRemovesAuthorization(): void { /** @@ -374,9 +448,14 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertSame(0, $exitCode, "Git command failed: {$command}\n" . \implode("\n", $output)); } - private function writeFunctionHelper(string $workdir, string $output): void + private function writeFunctionHelper(string $workdir, string $output, string $path = ''): void { - \file_put_contents($workdir . '/index.js', "module.exports = async (context) => context.res.send('{$output}');\n"); + $directory = $workdir . ($path === '' ? '' : '/' . $path); + if (! \is_dir($directory)) { + \mkdir($directory, 0o777, true); + } + + \file_put_contents($directory . '/index.js', "module.exports = async (context) => context.res.send('{$output}');\n"); } private function waitForDeploymentReadyHelper(string $functionId, string $deploymentId): void From 7e7702494244934ab15f6d4d0056e1a1166a5168 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 16:50:11 +0530 Subject: [PATCH 05/12] test(vcs): prove the persisted root directory through the duplicate build The deployment response model does not expose providerRootDirectory, so reading it off the body asserted on a key that is never returned. Duplicating the push-created deployment proves the same thing through behavior: the duplicate reads the root directory back off the deployment it copies, so it only reaches 'ready' if the push persisted one. Also deploy explicitly before pushing, so the nested entrypoint is observed executing on a deployment the test activated rather than one it assumed was active. --- .../VCSGitea/VCSGiteaConsoleClientTest.php | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index 5b7d99902c..ff84f95872 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -154,6 +154,19 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertEquals(201, $function['headers']['status-code'], \json_encode($function['body'])); $functionId = $function['body']['$id']; + $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/vcs', \array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + ], $this->getHeaders()), [ + 'type' => 'branch', + 'reference' => 'main', + 'activate' => true, + ]); + $this->assertEquals(202, $deployment['headers']['status-code'], \json_encode($deployment['body'])); + + $this->waitForDeploymentReadyHelper($functionId, $deployment['body']['$id']); + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v1'), 30000, 1000); + $knownIds = $this->listDeploymentIdsHelper($functionId); $this->writeFunctionHelper($workdir, 'gitea-nested-v2', 'docs/nested'); @@ -161,16 +174,11 @@ final class VCSGiteaConsoleClientTest extends Scope $this->gitHelper('git push origin main', $workdir); $webhookDeploymentId = $this->waitForNewDeploymentReadyHelper($functionId, $knownIds); - $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2'), 30000, 1000); - - // A push-created deployment must persist the root directory it built - // from, since duplicating one reads the value back off this document. - $webhookDeployment = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/deployments/' . $webhookDeploymentId, \array_merge([ - 'x-appwrite-project' => $projectId, - ], $this->getHeaders())); - $this->assertEquals(200, $webhookDeployment['headers']['status-code']); - $this->assertEquals('./docs/nested/', $webhookDeployment['body']['providerRootDirectory']); + // A duplicate reads the root directory back off the deployment it + // copies, so this only builds if the push-created deployment persisted + // one. Building from the repository root instead fails outright: the + // root holds only the auto-init README, no entrypoint. $duplicate = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', \array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, @@ -179,8 +187,6 @@ final class VCSGiteaConsoleClientTest extends Scope ]); $this->assertEquals(202, $duplicate['headers']['status-code'], \json_encode($duplicate['body'])); - // Building from the repository root instead would fail outright: the - // root holds only the auto-init README, no entrypoint. $this->waitForDeploymentReadyHelper($functionId, $duplicate['body']['$id']); } From c56c4ed8ead3fa2c2c05fb68e03437a993110ebc Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 17:17:54 +0530 Subject: [PATCH 06/12] fix(deployments): leave a parent segment for the extractor to resolve MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refusing `..` added a failure mode where there was none: `trim($subdir, '/')` has always passed a parent segment through untouched, so `docs/../x` reaches the extractor today and resolves to the directory it names. Rejecting it before job submission turns a working deployment into a 400. Canonicalize the forms that actually diverge — empty and `.` segments — and leave the rest of the path as given. Dropping `..` instead would silently build `docs/x`, which is the reason it was singled out in the first place. --- app/config/errors.php | 5 ----- src/Appwrite/Deployment/Deployments.php | 24 +++++++--------------- src/Appwrite/Extend/Exception.php | 1 - tests/unit/Deployment/DeploymentsTest.php | 25 +++-------------------- 4 files changed, 10 insertions(+), 45 deletions(-) diff --git a/app/config/errors.php b/app/config/errors.php index f01d4bf0b7..dc0cccc6d1 100644 --- a/app/config/errors.php +++ b/app/config/errors.php @@ -734,11 +734,6 @@ return [ 'description' => 'Deployment with the requested ID could not be found.', 'code' => 404, ], - Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY => [ - 'name' => Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY, - 'description' => 'Root directory must stay inside the repository. Remove the ".." segments, then retry the deployment.', - 'code' => 400, - ], Exception::DEPLOYMENT_INVALID_FILE_SIZE => [ 'name' => Exception::DEPLOYMENT_INVALID_FILE_SIZE, 'description' => 'The deployment file size is either not valid or exceeds the maximum allowed size. Please check the file or the value of the _APP_COMPUTE_SIZE_LIMIT environment variable.', diff --git a/src/Appwrite/Deployment/Deployments.php b/src/Appwrite/Deployment/Deployments.php index e1996c8be3..5e634f5238 100644 --- a/src/Appwrite/Deployment/Deployments.php +++ b/src/Appwrite/Deployment/Deployments.php @@ -223,11 +223,10 @@ readonly class Deployments try { $this->jobs->create(...static::payload($this->project, $resource, $deployment, $this->platform, $source)); } catch (\Throwable $error) { - // A refused variable key or root directory is the owner's to fix, - // so the build log carries the actual reason; anything else stays a - // generic internal error. - $owned = [Exception::VARIABLE_INVALID_KEY, Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY]; - $buildLogs = $error instanceof Exception && \in_array($error->getType(), $owned, true) + // A refused variable key is the owner's to fix, so the build log + // carries the actual reason; anything else stays a generic + // internal error. + $buildLogs = $error instanceof Exception && $error->getType() === Exception::VARIABLE_INVALID_KEY ? "\n" . $error->getMessage() . "\n" : "\nAn internal error occurred while building. Please try again, and contact support if the problem persists.\n"; @@ -307,11 +306,9 @@ readonly class Deployments * Dropping whole `.` segments rather than trimming the character keeps a * hidden directory intact — `ltrim('.github', '.')` would deploy `github`. * - * A `..` segment is refused rather than dropped or resolved. Dropping it - * would silently build `docs/x` for a `docs/../x` that names `x`, and - * resolving it would let the subdir climb out of the tree it indexes into. - * - * @throws Exception when a segment would leave the repository + * `..` is left alone. Dropping it would silently build `docs/x` for a + * `docs/../x` that names `x`, and resolving it here would duplicate what + * the extractor already does with the path it is handed. */ public static function rootDirectory(string $rootDirectory): string { @@ -320,13 +317,6 @@ readonly class Deployments fn (string $segment) => $segment !== '' && $segment !== '.', ); - if (\in_array('..', $segments, true)) { - throw new Exception( - Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY, - 'Root directory ' . \json_encode($rootDirectory) . ' must stay inside the repository. Remove the ".." segments, then retry the deployment.' - ); - } - return \implode('/', $segments); } diff --git a/src/Appwrite/Extend/Exception.php b/src/Appwrite/Extend/Exception.php index a25ee9397d..7c4fe95295 100644 --- a/src/Appwrite/Extend/Exception.php +++ b/src/Appwrite/Extend/Exception.php @@ -191,7 +191,6 @@ class Exception extends \Exception /** Deployments */ public const string DEPLOYMENT_NOT_FOUND = 'deployment_not_found'; public const string DEPLOYMENT_INVALID_FILE_SIZE = 'deployment_invalid_file_size'; - public const string DEPLOYMENT_INVALID_ROOT_DIRECTORY = 'deployment_invalid_root_directory'; /** Builds */ public const string BUILD_NOT_FOUND = 'build_not_found'; diff --git a/tests/unit/Deployment/DeploymentsTest.php b/tests/unit/Deployment/DeploymentsTest.php index aee91f6b6d..ad66431dab 100644 --- a/tests/unit/Deployment/DeploymentsTest.php +++ b/tests/unit/Deployment/DeploymentsTest.php @@ -51,6 +51,9 @@ final class DeploymentsTest extends TestCase yield 'shipped site template' => ['./astro/starter', 'astro/starter']; yield 'hidden directory' => ['.github', '.github']; yield 'dot-prefixed name' => ['..foo', '..foo']; + // Left for the extractor to resolve; dropping it would build 'docs/x'. + yield 'parent' => ['docs/../x', 'docs/../x']; + yield 'parent with prefix' => ['./docs/../x', 'docs/../x']; yield 'nested hidden directory' => ['./.github/actions', '.github/actions']; } @@ -60,28 +63,6 @@ final class DeploymentsTest extends TestCase $this->assertSame($expected, Deployments::rootDirectory($rootDirectory)); } - #[DataProvider('escapingRootDirectories')] - public function testRootDirectoryRefusesSegmentLeavingTheRepository(string $rootDirectory): void - { - try { - Deployments::rootDirectory($rootDirectory); - $this->fail('Expected the root directory to be refused before job submission'); - } catch (Exception $error) { - $this->assertSame(Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY, $error->getType()); - } - } - - public static function escapingRootDirectories(): \Iterator - { - yield 'parent' => ['..']; - yield 'parent path' => ['../etc']; - yield 'parent path with prefix' => ['./../etc']; - // Dropping the segment would silently build 'docs/x'; resolving it, - // 'x'. Neither is the directory the caller named. - yield 'interior parent' => ['docs/../x']; - yield 'escaping interior parent' => ['./docs/../../etc']; - } - public function testFunctionCommandIsDeploymentBuildCommands(): void { $resource = new Document(['$collection' => 'functions']); From ff7d4f7ffa38f1e760f996eecdf1252d7ffad767 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 17:31:30 +0530 Subject: [PATCH 07/12] chore: trim the root directory comments to the surrounding density --- src/Appwrite/Deployment/Deployments.php | 19 ++++--------------- .../VCSGitea/VCSGiteaConsoleClientTest.php | 8 ++------ tests/unit/Deployment/DeploymentsTest.php | 1 - 3 files changed, 6 insertions(+), 22 deletions(-) diff --git a/src/Appwrite/Deployment/Deployments.php b/src/Appwrite/Deployment/Deployments.php index 5e634f5238..a3c983fbd9 100644 --- a/src/Appwrite/Deployment/Deployments.php +++ b/src/Appwrite/Deployment/Deployments.php @@ -294,21 +294,10 @@ readonly class Deployments } /** - * Canonicalize a root directory into the subdirectory path an artifact can - * match against a tree: no leading `./`, no surrounding slashes, `''` for - * the repository root. - * - * The console's directory picker and every shipped site template write the - * path with a `./` prefix (`./astro/starter`), while a hand-typed one is - * usually bare (`docs`) and sometimes trailing-slashed (`docs/`). All three - * name the same directory, so all three must produce the same subdir. - * - * Dropping whole `.` segments rather than trimming the character keeps a - * hidden directory intact — `ltrim('.github', '.')` would deploy `github`. - * - * `..` is left alone. Dropping it would silently build `docs/x` for a - * `docs/../x` that names `x`, and resolving it here would duplicate what - * the extractor already does with the path it is handed. + * Resolve the path forms a caller may store - '', '.', './docs', 'docs/' - + * to the plain subdirectory an artifact matches against a tree. Whole '.' + * segments go, not the character: ltrim('.github', '.') would deploy + * 'github'. '..' is left for the extractor to resolve. */ public static function rootDirectory(string $rootDirectory): string { diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index ff84f95872..29a5c9f317 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -134,8 +134,6 @@ final class VCSGiteaConsoleClientTest extends Scope $this->gitHelper('git add docs && git commit -m "Add nested function"', $workdir); $this->gitHelper('git push origin main', $workdir); - // The console's directory picker writes the path in this form; it names - // the same directory as 'docs/nested'. $function = $this->client->call(Client::METHOD_POST, '/functions', \array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, @@ -175,10 +173,8 @@ final class VCSGiteaConsoleClientTest extends Scope $webhookDeploymentId = $this->waitForNewDeploymentReadyHelper($functionId, $knownIds); - // A duplicate reads the root directory back off the deployment it - // copies, so this only builds if the push-created deployment persisted - // one. Building from the repository root instead fails outright: the - // root holds only the auto-init README, no entrypoint. + // A duplicate reads the root directory off the deployment it copies, so + // this only builds if the push persisted one. $duplicate = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', \array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, diff --git a/tests/unit/Deployment/DeploymentsTest.php b/tests/unit/Deployment/DeploymentsTest.php index ad66431dab..197ffcb85a 100644 --- a/tests/unit/Deployment/DeploymentsTest.php +++ b/tests/unit/Deployment/DeploymentsTest.php @@ -51,7 +51,6 @@ final class DeploymentsTest extends TestCase yield 'shipped site template' => ['./astro/starter', 'astro/starter']; yield 'hidden directory' => ['.github', '.github']; yield 'dot-prefixed name' => ['..foo', '..foo']; - // Left for the extractor to resolve; dropping it would build 'docs/x'. yield 'parent' => ['docs/../x', 'docs/../x']; yield 'parent with prefix' => ['./docs/../x', 'docs/../x']; yield 'nested hidden directory' => ['./.github/actions', '.github/actions']; From 8dd9227c1ce3d03d4c2e5e676c77d6c77f6325d8 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 17:37:50 +0530 Subject: [PATCH 08/12] test(vcs): group the nested root directory assertions --- tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index 29a5c9f317..b48ebc0ab7 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -112,6 +112,9 @@ final class VCSGiteaConsoleClientTest extends Scope public function testCreateDeploymentFromNestedRootDirectory(): void { + /** + * Test for SUCCESS + */ $projectId = $this->getProject()['$id']; $installationId = $this->createInstallationHelper()['$id']; From 9d4363d869457a717a9db80b7c78f094e889b452 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Mon, 14 Sep 2026 11:32:27 +0530 Subject: [PATCH 09/12] fix(deployments): preserve source roots on legacy redeployments --- src/Appwrite/Deployment/Deployments.php | 2 + .../Http/Deployments/Duplicate/Create.php | 3 +- .../Http/Deployments/Duplicate/Create.php | 3 +- .../VCSGitea/VCSGiteaConsoleClientTest.php | 93 ++++++++++++-- tests/unit/Deployment/DeploymentsTest.php | 115 ++++++++++++++++++ 5 files changed, 203 insertions(+), 13 deletions(-) diff --git a/src/Appwrite/Deployment/Deployments.php b/src/Appwrite/Deployment/Deployments.php index 3cc4cef5b1..4459522724 100644 --- a/src/Appwrite/Deployment/Deployments.php +++ b/src/Appwrite/Deployment/Deployments.php @@ -162,6 +162,8 @@ readonly class Deployments string $ref, string $rootDirectory = '', ): Document { + $deployment->setAttribute('providerRootDirectory', $rootDirectory); + if ($vcs->supportsRepositoryArchives()) { return $this->createFromUrl( $resource, diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php index 5f98bbf24a..412fd7c45c 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php @@ -164,7 +164,8 @@ class Create extends Action $owner, $repository, $ref, - $deployment->getAttribute('providerRootDirectory', ''), + // Older connected deployments did not snapshot their source root. + $deployment->getAttribute('providerRootDirectory') ?? $function->getAttribute('providerRootDirectory', ''), ); } else { // Public template repo: providerBranch holds the resolved ref, diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php index f9a81f494e..ab648640ac 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php @@ -189,7 +189,8 @@ class Create extends Action $owner, $repository, $ref, - $deployment->getAttribute('providerRootDirectory', ''), + // Older connected deployments did not snapshot their source root. + $deployment->getAttribute('providerRootDirectory') ?? $site->getAttribute('providerRootDirectory', ''), ); } else { // Public template repo: providerBranch holds the resolved ref, diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index f55e863118..ad69a917d4 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -4,13 +4,20 @@ declare(strict_types=1); namespace Tests\E2E\Services\VCSGitea; +use Appwrite\Database\Factory; use Appwrite\Tests\Async\Exceptions\Critical; use Tests\E2E\Client; use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideConsole; +use Utopia\Cache\Adapter\Pool as CachePool; +use Utopia\Cache\Adapter\Sharding; +use Utopia\Cache\Cache; +use Utopia\Config\Config; +use Utopia\Database\Document; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Role; +use Utopia\Database\Validator\Authorization; use Utopia\System\System; final class VCSGiteaConsoleClientTest extends Scope @@ -116,6 +123,10 @@ final class VCSGiteaConsoleClientTest extends Scope * Test for SUCCESS */ $projectId = $this->getProject()['$id']; + $headers = \array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + ], $this->getHeaders()); $installationId = $this->createInstallationHelper()['$id']; $repository = $this->giteaApiHelper(Client::METHOD_POST, '/api/v1/user/repos', [ @@ -133,8 +144,10 @@ final class VCSGiteaConsoleClientTest extends Scope . '/' . self::GITEA_USERNAME . '/' . $repositoryName . '.git'; $this->gitHelper("git clone {$remote} {$workdir}", \sys_get_temp_dir()); - $this->writeFunctionHelper($workdir, 'gitea-nested-v1', 'docs/nested'); - $this->gitHelper('git add docs && git commit -m "Add nested function"', $workdir); + \mkdir($workdir . '/docs/nested', 0o777, true); + \file_put_contents($workdir . '/index.js', "module.exports = async (context) => context.res.send('gitea-root:' + process.env.APPWRITE_VCS_ROOT_DIRECTORY);\n"); + \file_put_contents($workdir . '/docs/nested/index.js', "module.exports = async (context) => context.res.send('gitea-nested-v1:' + process.env.APPWRITE_VCS_ROOT_DIRECTORY);\n"); + $this->gitHelper('git add index.js docs && git commit -m "Add nested function"', $workdir); $this->gitHelper('git push origin main', $workdir); $function = $this->client->call(Client::METHOD_POST, '/functions', \array_merge([ @@ -166,27 +179,82 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertEquals(202, $deployment['headers']['status-code'], \json_encode($deployment['body'])); $this->waitForDeploymentReadyHelper($functionId, $deployment['body']['$id']); - $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v1'), 30000, 1000); + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v1:./docs/nested/'), 30000, 1000); $knownIds = $this->listDeploymentIdsHelper($functionId); - $this->writeFunctionHelper($workdir, 'gitea-nested-v2', 'docs/nested'); + \file_put_contents($workdir . '/docs/nested/index.js', "module.exports = async (context) => context.res.send('gitea-nested-v2:' + process.env.APPWRITE_VCS_ROOT_DIRECTORY);\n"); $this->gitHelper('git add docs && git commit -m "Update nested function"', $workdir); $this->gitHelper('git push origin main', $workdir); $webhookDeploymentId = $this->waitForNewDeploymentReadyHelper($functionId, $knownIds); + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2:./docs/nested/', $webhookDeploymentId), 30000, 1000); - // A duplicate reads the root directory off the deployment it copies, so - // this only builds if the push persisted one. - $duplicate = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', \array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - ], $this->getHeaders()), [ + // Upgrade fixture: deployments created before source roots were saved + // have NULL here. This metadata has no public update endpoint. + $seed = function (?string $root) use ($projectId, $webhookDeploymentId) { + global $register; + $pools = $register->get('pools'); + $cache = new Cache(new Sharding(\array_map( + fn (string $name) => new CachePool($pools->get($name)), + Config::getParam('pools-cache', []), + ))); + $authorization = new Authorization(); + $factory = new Factory($pools, $cache, $authorization); + + $authorization->skip(function () use ($factory, $projectId, $webhookDeploymentId, $root) { + $project = $factory->platform()->getDocument('projects', $projectId); + $database = $factory->project($project); + $database->updateDocument('deployments', $webhookDeploymentId, new Document([ + 'providerRootDirectory' => $root, + ])); + $database->purgeCachedDocument('deployments', $webhookDeploymentId); + $this->assertSame($root, $database->getDocument('deployments', $webhookDeploymentId)->getAttribute('providerRootDirectory')); + }); + }; + if (\Swoole\Coroutine::getCid() >= 0) { + $seed(null); + } else { + \Swoole\Coroutine\run(fn () => $seed(null)); + } + + $duplicate = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', $headers, [ 'deploymentId' => $webhookDeploymentId, ]); $this->assertEquals(202, $duplicate['headers']['status-code'], \json_encode($duplicate['body'])); $this->waitForDeploymentReadyHelper($functionId, $duplicate['body']['$id']); + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2:./docs/nested/', $duplicate['body']['$id']), 30000, 1000); + + // The healed deployment must retain its source root after settings change. + $updated = $this->client->call(Client::METHOD_PUT, '/functions/' . $functionId, $headers, [ + 'name' => 'Gitea nested VCS', + 'execute' => [Role::any()->toString()], + 'providerRootDirectory' => 'missing', + ]); + $this->assertEquals(200, $updated['headers']['status-code'], \json_encode($updated['body'])); + $this->assertSame('missing', $updated['body']['providerRootDirectory']); + + $preserved = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', $headers, [ + 'deploymentId' => $duplicate['body']['$id'], + ]); + $this->assertEquals(202, $preserved['headers']['status-code'], \json_encode($preserved['body'])); + $this->waitForDeploymentReadyHelper($functionId, $preserved['body']['$id']); + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2:./docs/nested/', $preserved['body']['$id']), 30000, 1000); + + // An explicit empty snapshot names the repository root, even when the + // function now points elsewhere. It must not take the legacy fallback. + if (\Swoole\Coroutine::getCid() >= 0) { + $seed(''); + } else { + \Swoole\Coroutine\run(fn () => $seed('')); + } + $root = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', $headers, [ + 'deploymentId' => $webhookDeploymentId, + ]); + $this->assertEquals(202, $root['headers']['status-code'], \json_encode($root['body'])); + $this->waitForDeploymentReadyHelper($functionId, $root['body']['$id']); + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-root:', $root['body']['$id']), 30000, 1000); } public function testClosePullRequestRemovesAuthorization(): void @@ -522,7 +590,7 @@ final class VCSGiteaConsoleClientTest extends Scope return $response['body']['deployments'] ?? []; } - private function assertExecutionOutputHelper(string $functionId, string $output): void + private function assertExecutionOutputHelper(string $functionId, string $output, ?string $deploymentId = null): void { $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', \array_merge([ 'content-type' => 'application/json', @@ -534,6 +602,9 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertEquals(201, $execution['headers']['status-code'], \json_encode($execution['body'])); $this->assertEquals('completed', $execution['body']['status'] ?? '', \json_encode($execution['body'])); $this->assertEquals($output, $execution['body']['responseBody'] ?? ''); + if ($deploymentId !== null) { + $this->assertSame($deploymentId, $execution['body']['deploymentId']); + } } private function buildGiteaState(string $projectId, string $success, string $failure): string diff --git a/tests/unit/Deployment/DeploymentsTest.php b/tests/unit/Deployment/DeploymentsTest.php index 197ffcb85a..a662753694 100644 --- a/tests/unit/Deployment/DeploymentsTest.php +++ b/tests/unit/Deployment/DeploymentsTest.php @@ -6,13 +6,65 @@ namespace Tests\Unit\Deployment; use Appwrite\Deployment\Deployments; use Appwrite\Extend\Exception; +use OpenRuntimes\Orchestrator\Jobs; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; use Utopia\Config\Config; +use Utopia\Database\Database; use Utopia\Database\Document; +use Utopia\Psr7\Response; +use Utopia\Psr7\Stream; +use Utopia\VCS\Adapter\Git\GitHub; final class DeploymentsTest extends TestCase { + public static function sources(): \Iterator + { + yield 'archive subdirectory' => [true, 'functions/api']; + yield 'archive root' => [true, '']; + yield 'clone subdirectory' => [false, 'functions/api']; + yield 'clone root' => [false, '']; + } + + #[DataProvider('sources')] + public function testCreateVcsDeploymentPersistsSourceRoot(bool $archives, string $root): void + { + $previousKey = \getenv('_APP_OPENSSL_KEY_V1'); + \putenv('_APP_OPENSSL_KEY_V1=unit-test-key'); + + try { + $database = new VcsDeploymentDatabase(); + $client = new VcsBuildClient(); + $deployments = new Deployments(new Jobs($client), $database, new Document(['$id' => 'project', 'region' => 'default']), ['apiHostname' => 'localhost']); + + $deployment = $deployments->createFromVcs( + new Document([ + '$id' => 'function', + '$collection' => 'functions', + 'runtime' => \array_key_first(Config::getParam('runtimes-v2')), + 'providerRootDirectory' => 'changed/function/setting', + ]), + new Document(['$id' => 'deployment', 'buildCommands' => 'npm ci']), + new VcsRepository($archives), + 'owner', + 'repository', + 'commit', + $root, + ); + + $this->assertSame('waiting', $deployment->getAttribute('status')); + $this->assertSame($root, $database->getDocument('deployments', 'deployment')->getAttribute('providerRootDirectory')); + $this->assertSame($root, $client->payload['environment']['APPWRITE_VCS_ROOT_DIRECTORY']); + $artifacts = \array_column($client->payload['artifacts'], null, 'id'); + $this->assertSame($root, $artifacts[$archives ? 'extract' : 'source']['subdir'] ?? ''); + } finally { + \putenv($previousKey === false ? '_APP_OPENSSL_KEY_V1' : '_APP_OPENSSL_KEY_V1=' . $previousKey); + } + } + public function testSiteCommandIncludesFrameworkAndDeploymentCommands(): void { Config::setParam('frameworks', [ @@ -251,3 +303,66 @@ final readonly class ExposedDeployments extends Deployments return static::payload($project, $resource, $deployment, $platform, $source); } } + +final class VcsDeploymentDatabase extends Database +{ + private Document $deployment; + + public function __construct() + { + } + + public function createDocument(string $collection, Document $document): Document + { + $this->deployment = clone $document; + $this->deployment->setAttribute('$sequence', '1'); + + return clone $this->deployment; + } + + public function updateDocuments(string $collection, Document $updates, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE, ?callable $onNext = null, ?callable $onError = null): int + { + $this->deployment->setAttributes($updates->getArrayCopy()); + + return 1; + } + + public function getDocument(string $collection, string $id, array $queries = [], bool $forUpdate = false): Document + { + return clone $this->deployment; + } +} + +final class VcsBuildClient implements ClientInterface +{ + public array $payload = []; + + public function sendRequest(RequestInterface $request): ResponseInterface + { + $this->payload = \json_decode((string) $request->getBody(), true, flags: JSON_THROW_ON_ERROR); + + return new Response(202, body: new Stream('{"id":"build","status":"accepted"}')); + } +} + +final class VcsRepository extends GitHub +{ + public function __construct(private bool $archives) + { + } + + public function supportsRepositoryArchives(): bool + { + return $this->archives; + } + + public function getRepositoryPresignedUrl(string $owner, string $repositoryName, string $ref = '', string $format = 'tarball'): string + { + return 'https://vcs.example/source.tar.gz'; + } + + public function getRepositoryCloneUrl(string $owner, string $repositoryName): string + { + return 'https://vcs.example/source.git'; + } +} From e06f75bd8eef77c528dd37a954a7db75b9a168cc Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Thu, 17 Sep 2026 14:13:42 +0530 Subject: [PATCH 10/12] chore(deps): bump utopia-php/vcs to 5.5.0 --- composer.json | 2 +- composer.lock | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/composer.json b/composer.json index 8d5d830090..04ab21bc17 100644 --- a/composer.json +++ b/composer.json @@ -104,7 +104,7 @@ "utopia-php/telemetry": "^0.4", "utopia-php/user-agent": "0.1.*", "mustangostang/spyc": "0.6.*", - "utopia-php/vcs": "5.4.*", + "utopia-php/vcs": "5.5.*", "utopia-php/websocket": "2.0.2", "dragonmantank/cron-expression": "3.4.*", "chillerlan/php-qrcode": "4.3.*", diff --git a/composer.lock b/composer.lock index 4c270aa001..5ef852281f 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "a6c7073c169d41bd738310bdb883d0e3", + "content-hash": "f7ded3605b7574ac15000ccecaa56361", "packages": [ { "name": "adhocore/jwt", @@ -5079,16 +5079,16 @@ }, { "name": "utopia-php/vcs", - "version": "5.4.0", + "version": "5.5.0", "source": { "type": "git", "url": "https://github.com/utopia-php/vcs.git", - "reference": "1224f6eade2ad7be43c9bcb4459321d9ffec97dc" + "reference": "de3d3dafe019f8cffd97480a9f2bf15d7514678c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/vcs/zipball/1224f6eade2ad7be43c9bcb4459321d9ffec97dc", - "reference": "1224f6eade2ad7be43c9bcb4459321d9ffec97dc", + "url": "https://api.github.com/repos/utopia-php/vcs/zipball/de3d3dafe019f8cffd97480a9f2bf15d7514678c", + "reference": "de3d3dafe019f8cffd97480a9f2bf15d7514678c", "shasum": "" }, "require": { @@ -5131,10 +5131,10 @@ "vcs" ], "support": { - "source": "https://github.com/utopia-php/vcs/tree/5.4.0", + "source": "https://github.com/utopia-php/vcs/tree/5.5.0", "issues": "https://github.com/utopia-php/vcs/issues" }, - "time": "2026-09-15T08:06:27+00:00" + "time": "2026-09-17T08:01:03+00:00" }, { "name": "utopia-php/websocket", From e749da240ab1ab4347f1e2a7d5965b213204a3a9 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Thu, 17 Sep 2026 15:40:50 +0530 Subject: [PATCH 11/12] fix(deployments): redeploy from the resource's current root directory --- .../Http/Deployments/Duplicate/Create.php | 3 +- .../Http/Deployments/Duplicate/Create.php | 3 +- .../VCSGitea/VCSGiteaConsoleClientTest.php | 152 +----------------- tests/unit/Deployment/DeploymentsTest.php | 117 -------------- 4 files changed, 3 insertions(+), 272 deletions(-) diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php index 7ba0a2fbf8..f5842b298d 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php @@ -167,8 +167,7 @@ class Create extends Action $owner, $repository, $ref, - // Older connected deployments did not snapshot their source root. - $deployment->getAttribute('providerRootDirectory') ?? $function->getAttribute('providerRootDirectory', ''), + $function->getAttribute('providerRootDirectory', ''), ); } else { // Public template repo: providerBranch holds the resolved ref, diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php index 1a399d34c8..c7348f315c 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php @@ -192,8 +192,7 @@ class Create extends Action $owner, $repository, $ref, - // Older connected deployments did not snapshot their source root. - $deployment->getAttribute('providerRootDirectory') ?? $site->getAttribute('providerRootDirectory', ''), + $site->getAttribute('providerRootDirectory', ''), ); } else { // Public template repo: providerBranch holds the resolved ref, diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index a7ed0dbff1..8db0756915 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -4,20 +4,13 @@ declare(strict_types=1); namespace Tests\E2E\Services\VCSGitea; -use Appwrite\Database\Factory; use Appwrite\Tests\Async\Exceptions\Critical; use Tests\E2E\Client; use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideConsole; -use Utopia\Cache\Adapter\Pool as CachePool; -use Utopia\Cache\Adapter\Sharding; -use Utopia\Cache\Cache; -use Utopia\Config\Config; -use Utopia\Database\Document; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Role; -use Utopia\Database\Validator\Authorization; use Utopia\System\System; final class VCSGiteaConsoleClientTest extends Scope @@ -117,146 +110,6 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-v2'), 30000, 1000); } - public function testCreateDeploymentFromNestedRootDirectory(): void - { - /** - * Test for SUCCESS - */ - $projectId = $this->getProject()['$id']; - $headers = \array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - ], $this->getHeaders()); - $installationId = $this->createInstallationHelper()['$id']; - - $repository = $this->giteaApiHelper(Client::METHOD_POST, '/api/v1/user/repos', [ - 'name' => 'function-' . \uniqid(), - 'auto_init' => true, - 'default_branch' => 'main', - 'private' => false, - ]); - $this->assertEquals(201, $repository['headers']['status-code'], \json_encode($repository['body'])); - $repositoryName = $repository['body']['name']; - - $workdir = \sys_get_temp_dir() . '/vcs-gitea-' . \uniqid(); - $endpoint = System::getEnv('_APP_VCS_GITEA_ENDPOINT', 'http://gitea:3000'); - $remote = \str_replace('://', '://' . self::GITEA_USERNAME . ':' . self::GITEA_PASSWORD . '@', $endpoint) - . '/' . self::GITEA_USERNAME . '/' . $repositoryName . '.git'; - - $this->gitHelper("git clone {$remote} {$workdir}", \sys_get_temp_dir()); - \mkdir($workdir . '/docs/nested', 0o777, true); - \file_put_contents($workdir . '/index.js', "module.exports = async (context) => context.res.send('gitea-root:' + process.env.APPWRITE_VCS_ROOT_DIRECTORY);\n"); - \file_put_contents($workdir . '/docs/nested/index.js', "module.exports = async (context) => context.res.send('gitea-nested-v1:' + process.env.APPWRITE_VCS_ROOT_DIRECTORY);\n"); - $this->gitHelper('git add index.js docs && git commit -m "Add nested function"', $workdir); - $this->gitHelper('git push origin main', $workdir); - - $function = $this->client->call(Client::METHOD_POST, '/functions', \array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - ], $this->getHeaders()), [ - 'functionId' => ID::unique(), - 'name' => 'Gitea nested VCS', - 'execute' => [Role::any()->toString()], - 'runtime' => 'node-22', - 'entrypoint' => 'index.js', - 'timeout' => 15, - 'installationId' => $installationId, - 'providerRepositoryId' => (string) $repository['body']['id'], - 'providerBranch' => 'main', - 'providerRootDirectory' => './docs/nested/', - ]); - $this->assertEquals(201, $function['headers']['status-code'], \json_encode($function['body'])); - $functionId = $function['body']['$id']; - - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/vcs', \array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - ], $this->getHeaders()), [ - 'type' => 'branch', - 'reference' => 'main', - 'activate' => true, - ]); - $this->assertEquals(202, $deployment['headers']['status-code'], \json_encode($deployment['body'])); - - $this->waitForDeploymentReadyHelper($functionId, $deployment['body']['$id']); - $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v1:./docs/nested/'), 30000, 1000); - - $knownIds = $this->listDeploymentIdsHelper($functionId); - - \file_put_contents($workdir . '/docs/nested/index.js', "module.exports = async (context) => context.res.send('gitea-nested-v2:' + process.env.APPWRITE_VCS_ROOT_DIRECTORY);\n"); - $this->gitHelper('git add docs && git commit -m "Update nested function"', $workdir); - $this->gitHelper('git push origin main', $workdir); - - $webhookDeploymentId = $this->waitForNewDeploymentReadyHelper($functionId, $knownIds); - $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2:./docs/nested/', $webhookDeploymentId), 30000, 1000); - - // Upgrade fixture: deployments created before source roots were saved - // have NULL here. This metadata has no public update endpoint. - $seed = function (?string $root) use ($projectId, $webhookDeploymentId) { - global $register; - $pools = $register->get('pools'); - $cache = new Cache(new Sharding(\array_map( - fn (string $name) => new CachePool($pools->get($name)), - Config::getParam('pools-cache', []), - ))); - $authorization = new Authorization(); - $factory = new Factory($pools, $cache, $authorization); - - $authorization->skip(function () use ($factory, $projectId, $webhookDeploymentId, $root) { - $project = $factory->platform()->getDocument('projects', $projectId); - $database = $factory->project($project); - $database->updateDocument('deployments', $webhookDeploymentId, new Document([ - 'providerRootDirectory' => $root, - ])); - $database->purgeCachedDocument('deployments', $webhookDeploymentId); - $this->assertSame($root, $database->getDocument('deployments', $webhookDeploymentId)->getAttribute('providerRootDirectory')); - }); - }; - if (\Swoole\Coroutine::getCid() >= 0) { - $seed(null); - } else { - \Swoole\Coroutine\run(fn () => $seed(null)); - } - - $duplicate = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', $headers, [ - 'deploymentId' => $webhookDeploymentId, - ]); - $this->assertEquals(202, $duplicate['headers']['status-code'], \json_encode($duplicate['body'])); - - $this->waitForDeploymentReadyHelper($functionId, $duplicate['body']['$id']); - $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2:./docs/nested/', $duplicate['body']['$id']), 30000, 1000); - - // The healed deployment must retain its source root after settings change. - $updated = $this->client->call(Client::METHOD_PUT, '/functions/' . $functionId, $headers, [ - 'name' => 'Gitea nested VCS', - 'execute' => [Role::any()->toString()], - 'providerRootDirectory' => 'missing', - ]); - $this->assertEquals(200, $updated['headers']['status-code'], \json_encode($updated['body'])); - $this->assertSame('missing', $updated['body']['providerRootDirectory']); - - $preserved = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', $headers, [ - 'deploymentId' => $duplicate['body']['$id'], - ]); - $this->assertEquals(202, $preserved['headers']['status-code'], \json_encode($preserved['body'])); - $this->waitForDeploymentReadyHelper($functionId, $preserved['body']['$id']); - $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2:./docs/nested/', $preserved['body']['$id']), 30000, 1000); - - // An explicit empty snapshot names the repository root, even when the - // function now points elsewhere. It must not take the legacy fallback. - if (\Swoole\Coroutine::getCid() >= 0) { - $seed(''); - } else { - \Swoole\Coroutine\run(fn () => $seed('')); - } - $root = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', $headers, [ - 'deploymentId' => $webhookDeploymentId, - ]); - $this->assertEquals(202, $root['headers']['status-code'], \json_encode($root['body'])); - $this->waitForDeploymentReadyHelper($functionId, $root['body']['$id']); - $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-root:', $root['body']['$id']), 30000, 1000); - } - public function testClosePullRequestRemovesAuthorization(): void { /** @@ -585,7 +438,7 @@ final class VCSGiteaConsoleClientTest extends Scope return $response['body']['deployments'] ?? []; } - private function assertExecutionOutputHelper(string $functionId, string $output, ?string $deploymentId = null): void + private function assertExecutionOutputHelper(string $functionId, string $output): void { $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', \array_merge([ 'content-type' => 'application/json', @@ -597,9 +450,6 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertEquals(201, $execution['headers']['status-code'], \json_encode($execution['body'])); $this->assertEquals('completed', $execution['body']['status'] ?? '', \json_encode($execution['body'])); $this->assertEquals($output, $execution['body']['responseBody'] ?? ''); - if ($deploymentId !== null) { - $this->assertSame($deploymentId, $execution['body']['deploymentId']); - } } private function buildGiteaState(string $projectId, string $success, string $failure): string diff --git a/tests/unit/Deployment/DeploymentsTest.php b/tests/unit/Deployment/DeploymentsTest.php index 55da3c35ea..0ef0ea0633 100644 --- a/tests/unit/Deployment/DeploymentsTest.php +++ b/tests/unit/Deployment/DeploymentsTest.php @@ -6,66 +6,12 @@ namespace Tests\Unit\Deployment; use Appwrite\Deployment\Deployments; use Appwrite\Extend\Exception; -use OpenRuntimes\Orchestrator\Jobs; -use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Psr\Http\Client\ClientInterface; -use Psr\Http\Message\RequestInterface; -use Psr\Http\Message\ResponseInterface; use Utopia\Config\Config; -use Utopia\Database\Database; use Utopia\Database\Document; -use Utopia\Psr7\Response; -use Utopia\Psr7\Stream; -use Utopia\VCS\Adapter\Git\GitHub; final class DeploymentsTest extends TestCase { - public static function sources(): \Iterator - { - yield 'archive subdirectory' => [true, 'functions/api']; - yield 'archive root' => [true, '']; - yield 'clone subdirectory' => [false, 'functions/api']; - yield 'clone root' => [false, '']; - } - - #[DataProvider('sources')] - public function testCreateVcsDeploymentPersistsSourceRoot(bool $archives, string $root): void - { - $previousKey = \getenv('_APP_OPENSSL_KEY_V1'); - \putenv('_APP_OPENSSL_KEY_V1=unit-test-key'); - - try { - $database = new VcsDeploymentDatabase(); - $client = new VcsBuildClient(); - $deployments = new Deployments(new Jobs($client), $database, new Document(['$id' => 'project', 'region' => 'default']), ['apiHostname' => 'localhost']); - - $deployment = $deployments->createFromVcs( - new Document([ - '$id' => 'function', - '$collection' => 'functions', - 'runtime' => \array_key_first(Config::getParam('runtimes-v2')), - 'providerRootDirectory' => 'changed/function/setting', - ]), - new Document(['$id' => 'deployment', 'buildCommands' => 'npm ci']), - 900, - new VcsRepository($archives), - 'owner', - 'repository', - 'commit', - $root, - ); - - $this->assertSame('waiting', $deployment->getAttribute('status')); - $this->assertSame($root, $database->getDocument('deployments', 'deployment')->getAttribute('providerRootDirectory')); - $this->assertSame($root, $client->payload['environment']['APPWRITE_VCS_ROOT_DIRECTORY']); - $artifacts = \array_column($client->payload['artifacts'], null, 'id'); - $this->assertSame($root, $artifacts[$archives ? 'extract' : 'source']['subdir'] ?? ''); - } finally { - \putenv($previousKey === false ? '_APP_OPENSSL_KEY_V1' : '_APP_OPENSSL_KEY_V1=' . $previousKey); - } - } - public function testSiteCommandIncludesFrameworkAndDeploymentCommands(): void { Config::setParam('frameworks', [ @@ -237,66 +183,3 @@ final readonly class ExposedDeployments extends Deployments return static::payload($project, $resource, $deployment, $platform, 137); } } - -final class VcsDeploymentDatabase extends Database -{ - private Document $deployment; - - public function __construct() - { - } - - public function createDocument(string $collection, Document $document): Document - { - $this->deployment = clone $document; - $this->deployment->setAttribute('$sequence', '1'); - - return clone $this->deployment; - } - - public function updateDocuments(string $collection, Document $updates, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE, ?callable $onNext = null, ?callable $onError = null): int - { - $this->deployment->setAttributes($updates->getArrayCopy()); - - return 1; - } - - public function getDocument(string $collection, string $id, array $queries = [], bool $forUpdate = false): Document - { - return clone $this->deployment; - } -} - -final class VcsBuildClient implements ClientInterface -{ - public array $payload = []; - - public function sendRequest(RequestInterface $request): ResponseInterface - { - $this->payload = \json_decode((string) $request->getBody(), true, flags: JSON_THROW_ON_ERROR); - - return new Response(202, body: new Stream('{"id":"build","status":"accepted"}')); - } -} - -final class VcsRepository extends GitHub -{ - public function __construct(private bool $archives) - { - } - - public function supportsRepositoryArchives(): bool - { - return $this->archives; - } - - public function getRepositoryPresignedUrl(string $owner, string $repositoryName, string $ref = '', string $format = 'tarball'): string - { - return 'https://vcs.example/source.tar.gz'; - } - - public function getRepositoryCloneUrl(string $owner, string $repositoryName): string - { - return 'https://vcs.example/source.git'; - } -} From c00eb376db6513db5718305c02d5e42f457438ae Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Thu, 17 Sep 2026 15:40:50 +0530 Subject: [PATCH 12/12] test(vcs): cover a redeploy after the root directory changes --- .../VCSGitea/VCSGiteaConsoleClientTest.php | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index 8db0756915..cea9401442 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -110,6 +110,75 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-v2'), 30000, 1000); } + public function testCreateDuplicateDeploymentWithRootDirectory(): void + { + $projectId = $this->getProject()['$id']; + $headers = \array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + ], $this->getHeaders()); + $installationId = $this->createInstallationHelper()['$id']; + + $repository = $this->giteaApiHelper(Client::METHOD_POST, '/api/v1/user/repos', [ + 'name' => 'function-' . \uniqid(), + 'auto_init' => true, + 'default_branch' => 'main', + 'private' => false, + ]); + $this->assertEquals(201, $repository['headers']['status-code'], \json_encode($repository['body'])); + + $workdir = \sys_get_temp_dir() . '/vcs-gitea-' . \uniqid(); + $endpoint = System::getEnv('_APP_VCS_GITEA_ENDPOINT', 'http://gitea:3000'); + $remote = \str_replace('://', '://' . self::GITEA_USERNAME . ':' . self::GITEA_PASSWORD . '@', $endpoint) + . '/' . self::GITEA_USERNAME . '/' . $repository['body']['name'] . '.git'; + + $this->gitHelper("git clone {$remote} {$workdir}", \sys_get_temp_dir()); + foreach (['api', 'web'] as $directory) { + \mkdir($workdir . '/functions/' . $directory, 0o777, true); + \file_put_contents($workdir . '/functions/' . $directory . '/index.js', "module.exports = async (context) => context.res.send('{$directory}:' + process.env.APPWRITE_VCS_ROOT_DIRECTORY);\n"); + } + $this->gitHelper('git add functions && git commit -m "Add functions"', $workdir); + $this->gitHelper('git push origin main', $workdir); + + $function = $this->client->call(Client::METHOD_POST, '/functions', $headers, [ + 'functionId' => ID::unique(), + 'name' => 'Gitea root directory', + 'execute' => [Role::any()->toString()], + 'runtime' => 'node-22', + 'entrypoint' => 'index.js', + 'timeout' => 15, + 'installationId' => $installationId, + 'providerRepositoryId' => (string) $repository['body']['id'], + 'providerBranch' => 'main', + 'providerRootDirectory' => 'functions/api', + ]); + $this->assertEquals(201, $function['headers']['status-code'], \json_encode($function['body'])); + $functionId = $function['body']['$id']; + + $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/vcs', $headers, [ + 'type' => 'branch', + 'reference' => 'main', + 'activate' => true, + ]); + $this->assertEquals(202, $deployment['headers']['status-code'], \json_encode($deployment['body'])); + $this->waitForDeploymentReadyHelper($functionId, $deployment['body']['$id']); + + $function = $this->client->call(Client::METHOD_PUT, '/functions/' . $functionId, $headers, [ + 'name' => 'Gitea root directory', + 'execute' => [Role::any()->toString()], + 'providerRootDirectory' => 'functions/web', + ]); + $this->assertEquals(200, $function['headers']['status-code'], \json_encode($function['body'])); + + $duplicate = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', $headers, [ + 'deploymentId' => $deployment['body']['$id'], + ]); + $this->assertEquals(202, $duplicate['headers']['status-code'], \json_encode($duplicate['body'])); + $this->waitForDeploymentReadyHelper($functionId, $duplicate['body']['$id']); + + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'web:functions/web'), 30000, 1000); + } + public function testClosePullRequestRemovesAuthorization(): void { /**