Skip to content

fix: confine repository root directories and build artifact reads - #14808

Merged
ChiragAgg5k merged 4 commits into
mainfrom
fix/build-path-confinement
Oct 22, 2026
Merged

ChiragAgg5k merged 4 commits into
mainfrom
fix/build-path-confinement

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Confines repository root directories and build artifact reads to the directories they belong to.

Root directories

  • New Appwrite\Vcs\Validator\Directory: a repository-relative directory with no .. segment and no control characters. A leading / or ./ keeps meaning the repository root, as the builds worker already reads it, so existing clients that send /apps/web or ./ keep working.
  • Used for providerRootDirectory on function and site create/update, rootDirectory on function and site template deployments, the deprecated templateRootDirectory on function create, and providerRootDirectory on the VCS contents and detections endpoints. The OpenAPI spec maps it like Text, so the generated specs do not change.
  • Builds worker: stored values are checked with the same validator before cloning. Each root directory is then resolved segment by segment inside its checkout without following symbolic links, and the result must realpath to itself. The template merge uses rsync --safe-links and fails the build on a non-zero exit. The "root directory with spaces" rename and the directory handed to createFromDirectory go through the same resolution.

Build artifacts

  • Local build jobs now mount only their own output directory (app-{projectId}/{deploymentId}) and the project's cache directory (app-{projectId}/cache) rather than the whole project directory. Both are created before submission because a Docker volume subpath must exist. The orchestrator accepts nested subpaths and multiple mounts of one volume.
  • Deployments::isArtifact(): on the local device, a deployment file is readable only when it is a regular file inside the device root and its realpath equals its path. The Jobs worker's readiness check and both deployment download endpoints (output and source) use it. A file that fails the check is treated as missing.

packages/vcs Git::normalizeRepositoryPath() still accepts .. segments. This PR handles that on the app side and does not change the package.

Test Plan

  • Unit: tests/unit/Vcs/Validator/DirectoryTest.php covers the accepted and refused paths. tests/unit/Deployment/DeploymentsTest.php covers the narrowed mounts, isolation from sibling deployments and projects, and isArtifact() against a regular file, a link, a linked parent directory, a parent segment, a directory, a missing file and paths outside the root.
  • E2E: testRootDirectoryMustStayInsideRepository in FunctionsCustomServerTest and SitesCustomServerTest. A repository-anchored root is accepted. Template deployment, create and update return 400 for .., ../other, x/../../y and /../x, and the stored value does not change.
  • Ran locally: Pint, PHPStan (host config) on the touched files, Rector check, and the unit suites above plus tests/unit/SDK and tests/unit/GraphQL. I did not run the e2e lanes locally because the docker stack is shared on this machine. CI runs them, and the Functions and Sites build lanes also exercise the narrowed mounts end to end.

Related PRs and Issues

None.

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs?

Related: appwrite-labs/cloud#6673

Root directories are joined onto checkout paths and fed to mkdir, mv and
rsync in the builds worker, so a value or a checked-out link could resolve
outside the checkout. Validate them as repository-relative paths at the
API, and in the worker resolve each segment inside its checkout without
following links before merging, with rsync keeping only links inside the
template and its exit code checked.

Build jobs could write the whole project directory on the local builds
volume, and artifact reads followed links. Mount only the deployment's
output directory and the project cache, and read a deployment file only
when it is a regular file inside its device.
Function and site create, update and template deployment refuse a root
directory with a parent segment, and the deprecated template root
directory on function create is validated the same way.
@luxor-code-review

luxor-code-review Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 3 medium

💬 Inline comments (2)

📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to

🟡 Medium — Legacy providerRootDirectory bypasses the worker validation · Builds.php:322–328 · unchanged line

// src/Appwrite/Platform/Modules/Functions/Workers/Builds.php
322	            $rootDirectory = $resource->getAttribute('providerRootDirectory', '');
323	            $rootDirectory = \rtrim($rootDirectory, '/');
324	            $rootDirectory = \ltrim($rootDirectory, '.');
325	            $rootDirectory = \ltrim($rootDirectory, '/');
326	            if (!(new Directory(\PHP_INT_MAX))->isValid($rootDirectory)) {
327	                throw new BuildException('Root directory must stay inside the repository.');
328	            }

The build worker validates the ltrim/rtrim-normalized $rootDirectory with the new Directory validator (src/Appwrite/Platform/Modules/Functions/Workers/Builds.php:326), but the lossy ltrim($rootDirectory, '.') rewrites a legacy stored ../src into src, which then passes validation and builds different content than the user configured. Separately, the createFromVcs hand-off passes the raw, never-validated attribute (src/Appwrite/Platform/Modules/Functions/Workers/Builds.php:482), which flows into the jobs-service as subdir and into the APPWRITE_VCS_ROOT_DIRECTORY build env (src/Appwrite/Deployment/Deployments.php:974) outside the worker's confine() protection.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Inconsistent providerRootDirectory max length across endpoints (Directory.php:13) — The new Appwrite\Vcs\Validator\Directory caps paths at 128 chars by default, but the VCS endpoints validate the same providerRootDirectory field with new Directory(256) (src/Appwrite/Platform/Modules/VCS/Http/Installations/Repositories/Detections/Create.php:97).

The change introduces filesystem path confinement for Functions/Sites deployments: a new VCS Directory validator, an isArtifact() guard on downloads, and a confine() helper in the build worker, plus narrower per-deployment volume mounts.

Files Change
src/Appwrite/Deployment/Deployments.php Adds isArtifact() artifact check, per-deployment volume subPaths, and output/cache directory pre-creation
src/Appwrite/Vcs/Validator/Directory.php New validator rejecting absolute paths, .. segments, and symlinks in providerRootDirectory
src/Appwrite/Platform/Modules/Functions/Workers/{Builds,Jobs}.php Adds confine() path confinement, --safe-links rsync, exit-code checks, and isArtifact() readiness check
src/Appwrite/Platform/Modules/{Functions,Sites}/Http/** Applies the Directory validator to create/update/template/download endpoints
src/Appwrite/Platform/Modules/VCS/Http/** Validates providerRootDirectory on VCS contents/detections endpoints
src/Appwrite/SDK/Specification/Format/OpenAPI3.php Emits the new Directory validator type/example in specs
tests/** New unit tests for the validator and isArtifact(), plus e2e tests for root-directory bounds and template deployments

Reviewed commit: 4b012cc

@ChiragAgg5k ChiragAgg5k self-assigned this Oct 22, 2026
@ghost

ghost commented Oct 22, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

Adds a repository-relative directory validator to function, site, and VCS inputs, and confines repository-root resolution and template merges to checked-out trees. Local build jobs mount only deployment output and project cache, while readiness and download reads reject artifact paths that escape the device root. The newest change also validates legacy roots at the shared VCS deployment boundary and adds regression coverage for traversal values.

Latest changes: The newest commit rejects escaping roots in Deployments::createFromVcs before archive, clone, or worker submission, and adds a unit regression test for legacy traversal values.

Verdict New comments Fixed Still open
✅ Approved 0 1 0
📂 Walkthrough · 10
File Change
src/Appwrite/Vcs/Validator/Directory.php; src/Appwrite/SDK/Specification/Format/OpenAPI3.php Define the repository-relative directory validator and map it to the existing OpenAPI string schema.
src/Appwrite/Deployment/Deployments.php Limit local build mounts and artifact reads, and reject stored escaping roots before dispatching a VCS deployment.
src/Appwrite/Platform/Modules/Functions/Http/Functions/{Create,Update}.php; src/Appwrite/Platform/Modules/Functions/Http/Deployments/{Template/Create,Download/Get}.php Validate function roots at API boundaries and guard function deployment artifact downloads.
src/Appwrite/Platform/Modules/Functions/Workers/{Builds,Jobs}.php Confine build paths and apply artifact validation during build readiness checks.
src/Appwrite/Platform/Modules/Sites/Http/Sites/{Create,Update}.php; src/Appwrite/Platform/Modules/Sites/Http/Deployments/{Template/Create,Download/Get}.php Validate site roots at API boundaries and guard site deployment artifact downloads.
src/Appwrite/Platform/Modules/VCS/Http/Installations/Repositories/Contents/Get.php; src/Appwrite/Platform/Modules/VCS/Http/Installations/Repositories/Detections/Create.php Apply repository-directory validation to VCS contents and detections inputs.
tests/unit/Deployment/DeploymentsTest.php; tests/unit/Deployment/RootDirectoryTest.php Cover narrowed mounts, artifact path checks, and rejection of legacy escaping roots.
tests/unit/Vcs/Validator/DirectoryTest.php Test accepted and rejected repository directory values.
tests/e2e/Services/Functions/FunctionsCustomServerTest.php; tests/e2e/Services/Sites/SitesCustomServerTest.php Verify repository-anchored roots are accepted and traversal inputs are rejected through the API.
src/Appwrite/SDK/Specification/Format/OpenAPI3.php Map the directory validator to the existing OpenAPI string schema.
✅ Fixed since the last review · 1
  • Validate stored roots before normalizing them · src/Appwrite/Platform/Modules/Functions/Workers/Builds.php:326

Merged main (0772262); no changes to this PR's code since 1430fbd · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR hardens the deployment pipeline against path traversal by adding a Directory validator and symlink-aware confine()/isArtifact() guards, narrowing build volume mounts to per-deployment subPaths, and adding e2e/unit coverage.

Key findings

Comment on lines 809 to 812
if ($device instanceof Local) {
$device->createDirectory($device->getRoot());
$device->createDirectory($outputDirectory);
$device->createDirectory($cacheDirectory);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 bug · medium

Unchecked pre-creation of volume subPath directories

storage() pre-creates the deployment output and cache directories because Docker's named-volume subPath must exist before the container starts, but the createDirectory return values are ignored (src/Appwrite/Deployment/Deployments.php:810-811). Local::createDirectory uses error-suppressed mkdir and can silently fail on EACCES, ENOSPC, or a missing builds volume root. The job is then submitted successfully and fails later at container creation with an opaque orchestrator error instead of failing fast at submission.

📋 Prompt for AI Agents

In src/Appwrite/Deployment/Deployments.php lines 809-812, storage() calls $device->createDirectory($outputDirectory) and $device->createDirectory($cacheDirectory) on the Local device but ignores their boolean results. Capture both return values and throw an Exception (server-side code, not user-facing) like 'Unable to prepare builds volume directory ...' when either returns false, because Docker volume-subPath mounts require the directories to exist before the build container starts; an unchecked failure surfaces only as a cryptic orchestrator container-creation error later.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this as is, deliberately. Local::createDirectory() returns true when the directory already exists, and the previous single project-root pre-creation also ignored the result. If the directory is missing, the orchestrator refuses the container, and that failure comes back through the job exit callback and fails the deployment. Throwing here would make building the job payload depend on the host filesystem, and it breaks the payload unit tests outside the container. The legacy providerRootDirectory finding outside the diff is fixed in 1430fbd (see the reply on Builds.php).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The explanation doesn't fully address the concern. The argument that 'the orchestrator refuses the container and that failure comes back through the job exit callback' is valid for a missing file, but Docker named-volume subPath mounts require the subdirectory to exist on the host volume before the container starts — if it does not, the orchestrator error is typically opaque and not cleanly routed through the job exit callback in the same way a runtime failure is. Additionally, the comparison to the old single-root pre-creation ignoring its result is not a strong justification: that was also a latent bug, and the new code now mounts two subPaths instead of one, increasing the surface area.

The unit test argument is worth acknowledging — throwing directly inside 'storage()' could complicate payload unit tests. A reasonable middle ground would be to log a warning (e.g. via 'Console::warning') when 'createDirectory' returns false, which preserves the current behavior while making silent failures observable without breaking tests. That said, the core issue — that a false return is completely invisible — remains unaddressed in this diff.

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/build-path-confinement (after).

Metric Before After Change
🚀 Requests/sec 196.68 204.25 ⚪ +3.8%
⏱️ Latency P50 85.66 ms 85.48 ms ⚪ -0.2%
⏱️ Latency P95 211.71 ms 197.27 ms 🟢 -6.8%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 85.48 197.27 12,597 204.25 -14.44
Account 151.88 282.16 663 11.12 -83.37
TablesDB 82.46 142.47 6,851 112.53 -26.1
Storage 79.39 190.39 3,315 56.6 +5.19
Functions 121.56 241.54 1,768 31.12 -13.17

Top API waits (after)

API request Max wait (ms)
account.name.update 529.69
functions.variables.update 467.18
functions.create 403.23
account.prefs.update 400.41
storage.buckets.create 361.14

Trimming leading dots turned a parent segment into a plain name before the
check ran, and redeploys reach createFromVcs without the builds worker, so
validate the stored value as is in both places and fail the deployment
when it leaves the repository. Keep the retry on the site template test.
@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

…ement

# Conflicts:
#	src/Appwrite/Deployment/Deployments.php
@ChiragAgg5k
ChiragAgg5k merged commit e2c3e34 into main Oct 22, 2026
67 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the fix/build-path-confinement branch October 22, 2026 18:14
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
Ported the root directory validation and the builds worker confinement. The build artifact checks target the orchestrator build path, which 1.9.x does not have.

(cherry picked from commit e2c3e34)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
Ported the root directory validation and the builds worker confinement. The build artifact checks target the orchestrator build path, which 1.9.x does not have.

(cherry picked from commit e2c3e34)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
Ported the root directory validation and the builds worker confinement. The build artifact checks target the orchestrator build path, which 1.9.x does not have.

(cherry picked from commit e2c3e34)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
Ported the root directory validation and the builds worker confinement. The build artifact checks target the orchestrator build path, which 1.9.x does not have.

(cherry picked from commit e2c3e34)
Tapraj-Pathak pushed a commit to Tapraj-Pathak/appwrite that referenced this pull request Oct 24, 2026
…ement

fix: confine repository root directories and build artifact reads
(cherry picked from commit e2c3e34)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant