Skip to content

fix: delete a project's storage objects on S3 - #14626

Merged
ChiragAgg5k merged 5 commits into
mainfrom
fix/project-delete-storage
Oct 18, 2026
Merged

ChiragAgg5k merged 5 commits into
mainfrom
fix/project-delete-storage

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Deleting a project leaves its storage behind. Two bugs stack up:

DELETE /project ─▶ deletes worker
  injected project reloads the deleted row → {}       (A) devices rooted at .../app-  (no id)
  S3::delete($root, true) → DeleteObject "root"        (B) one key removed, nothing under root/

A) Devices built from the deleted project

deleteProject() builds its devices from the deleted $document (wrapped in TelemetryDevice) and throws on an empty project id. Deployment source, build and screenshot files are deleted as single objects (non-recursive).

Signature changes (protected/public, for subclasses):

protected function deleteProject(Database $dbForPlatform, callable $getProjectDB, callable $getDatabasesDB, Telemetry $telemetry, Provider $certificates, Document $document, Bus $bus, ?Store $executionStore = null): void

public function action(Message $message, Document $project, Database $dbForPlatform, callable $getProjectDB, callable $getDatabasesDB, Device $deviceForFiles, Device $deviceForFunctions, Device $deviceForSites, Device $deviceForBuilds, Telemetry $telemetry, Provider $certificates, Executor $executor, string $executionRetention, int $executionsRetentionCount, DeletePublisher $publisherForDeletes, UsagePublisher $publisherForUsage, Bus $bus, Store $executionStore): void

// actionWithUsage: same as action + UsageConnection $usageConnection

deviceForCache is no longer injected; deleteProjectsByTeam() also takes Telemetry.

B) Recursive S3 delete removes the whole directory

delete('a/b', true) → ListObjectsV2 prefix=a/b/ → DeleteObjects (batched, follows continuation tokens)
deletePath('img')   → prefix root/img/            (img2 is not matched)
delete/deletePath of the whole bucket, the whole root, or outside it (root/../x)
                    → \InvalidArgumentException before any request
  • keys in the DeleteObjects body are XML-escaped
  • RemoteException on per-key <Error>s, on a whole-batch error, and on a listing that is not a ListObjectsV2 result

Test Plan

Each test was seen red before its fix:

Test Breaks when Red message
E2E S3Base::testRecursiveDeleteStaysInsideTheRoot containment check disabled; check without trailing slash /outside-…/sentinel.txt is outside the root and must survive delete('../outside-…', true); /root-…/sentinel.txt … must survive delete('../root-…', true)
E2E testDeleteRecursive delete() skips the prefix rec-…/a/1.txt survived delete('rec-…/a', true)
E2E testRecursiveDeleteRefusesAnEmptyPrefix root check on the raw path deletePath('.') must refuse…, deletePath('x/..') must refuse…
E2E testDeletePathKeepsSiblings, testRecursiveDeleteEscapesKeys img matches img2; keys not escaped
Unit testRecursiveDeleteFollowsTheContinuationToken continuation token ignored actual size 3 matches expected size 5
Unit testAnEmptyTruncatedPageDoesNotEndTheDelete empty page ends the loop actual size 1 matches expected size 3
Unit testAListingThatIsNotAListObjectsResultIsAnError non-listing body treated as empty
Unit testKeysTheServiceFailedToDeleteAreAnError (one key / two keys / whole batch) <Error> ignored Keys the service could not delete must not be reported as deleted
Unit DeletesTest::testProjectDeleteWithoutAnIdTouchesNothing no empty-id guard Store::deleteProject(''): void was not expected to be called
App E2E ProjectConsoleClientTest::testDeleteProjectStorage devices from the injected project uploads / functions / builds roots not emptied

The unit tests cover what MinIO can't produce (pagination edge cases, service errors). testDeleteProjectStorage runs in the default (local device) Project lanes and, via #[Group('s3')] and .github/ci/e2e.json, in the S3 Storage lane.

Merge order

The S3 Storage lane uses path-style MinIO (_APP_STORAGE_S3_ENDPOINT: http://minio:9000, bucket appwrite, no MINIO_DOMAIN), where bucket-level listing is broken on main. That was fixed by the path-style addressing PR, #14628.

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? (no API metadata change)

@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟠 1 high · 🟡 1 medium

💬 Inline comments (2)

  • 🟠 Virtual-hosted S3 copy builds a doubled bucket copy-source — S3.php:577
  • 🟡 .. in S3 paths resolves past the device root in list/delete prefixes — S3.php:906

This PR introduces explicit path-style vs virtual-hosted addressing for the S3 storage device, adds recursive delete, deletePath, and deletePrefix (batched via DeleteObjects with continuation tokens), and reworks the project-deletion worker to construct devices lazily and clean project storage roots. Tests cover the new device semantics and add an e2e regression for project storage deletion, with CI lane wiring updated.

Files Change
packages/storage/src/Device/S3.php, packages/storage/src/Device.php Add pathStyle mode, recursive delete(), deletePath()/deletePrefix() with batched DeleteObjects, and widened device contract.
src/Appwrite/Platform/Workers/Deletes.php, app/init/resources.php Build storage devices per project inside deleteProject() and guard empty project IDs; configure S3 devices with path-style detection.
tests/unit/Storage/DeviceTest.php, packages/storage/tests/* Unit and e2e coverage for path-style addressing, prefix deletes, and sibling-prefixed paths.
tests/e2e/Services/Project/ProjectConsoleClientTest.php, tests/unit/Platform/Workers/DeletesTest.php Regression tests for project storage cleanup.
.github/ci/e2e.json Extends the s3 CI lane to cover the Project service.

Reviewed commit: e5e0fd2

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

ghost commented Oct 17, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

This change adds paginated recursive deletion for S3 objects, with path containment checks and error reporting, and updates project cleanup to construct storage devices from the deleted project document. It also adds unit and end-to-end coverage for recursive deletion and project storage cleanup.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 10
File Change
.github/ci/e2e.json Adds Project E2E coverage to the S3 storage lane.
packages/storage/README.md Documents recursive S3 deletion semantics, addressing, and errors.
packages/storage/src/Device.php Clarifies the delete and deletePath contracts.
packages/storage/src/Device/S3.php Adds guarded, paginated recursive deletion and batch-error handling.
packages/storage/tests/Device/S3Test.php Covers continuation tokens, malformed listings, and batch failures.
packages/storage/tests/E2E/S3Base.php Adds adapter-level recursive deletion and path-safety coverage.
packages/storage/tests/E2E/S3Test.php Adds path-style recursive deletion and bucket-protection coverage.
src/Appwrite/Platform/Workers/Deletes.php Builds project storage devices from the deleted project document and recursively removes storage.
tests/e2e/Services/Project/ProjectConsoleClientTest.php Verifies project deletion removes uploaded files, deployments, and builds.
tests/unit/Platform/Workers/DeletesTest.php Covers project deletion messages missing a project ID.
🔇 Filtered out · 1

Findings Hansi considered but did not post.

Finding Why
Validate the listing response type, not only IsTruncated Verifier: The decoder does discard the XML root, but the finding requires an unrelated API response that no production path here produces. listBucket() explicitly sends a GET with list-type=2, prefix and max-keys (lines 615–627); multipart listings are requested separately with uploads= in listUploads() (lines 970–986). call() builds and signs the query from per-call parameters and decodes that request's response, while the default client's response body is local to each sendRequest(). There is no traced route for a ListMultipartUploadsResult to reach deletePrefix(). This is hypothetical hardening against a misbehaving endpoint rather than a demonstrated deletion bug.

Reviewed a01dca3 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • 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.

@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.

Adds path-style S3 addressing, recursive/bulk delete support to the storage device, and per-project storage cleanup in the deletes worker.

Key findings

  • 🟠 Virtual-hosted S3 copy builds a doubled bucket copy-source — S3.php:577
  • 🟡 .. in S3 paths resolves past the device root in list/delete prefixes — S3.php:906

Comment thread packages/storage/src/Device/S3.php Resolved
Comment thread packages/storage/src/Device/S3.php Resolved
@github-actions

github-actions Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/project-delete-storage (after).

Metric Before After Change
🚀 Requests/sec 175.09 176.54 ⚪ +0.8%
⏱️ Latency P50 97.47 ms 99.38 ms ⚪ +2%
⏱️ Latency P95 235.53 ms 226.93 ms ⚪ -3.7%
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 99.38 226.93 11,400 176.54 -8.6
Account 183.76 362.81 600 10.09 +6.91
TablesDB 96.02 177.03 6,200 98.48 +2.63
Storage 91.89 203.64 3,000 49.34 -26.93
Functions 140.09 268.33 1,600 27.18 +4.17

Top API waits (after)

API request Max wait (ms)
account.prefs.update 732.83
account.name.update 517.19
storage.files.create 498.02
functions.variables.create 440.75
functions.create 411.28

@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

Comment thread packages/storage/src/Device/S3.php Resolved
@ChiragAgg5k
ChiragAgg5k force-pushed the fix/project-delete-storage branch from 8a5d69f to a6ae564 Compare October 18, 2026 09:01
ghost
ghost previously requested changes Oct 18, 2026

@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 B · 1 blocking finding to address. Summary

Comment thread packages/storage/src/Device/S3.php Resolved
@ghost
ghost dismissed their stale review October 18, 2026 09:07

The findings that requested changes are resolved. See the summary comment for what is still open.

@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@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

@ChiragAgg5k
ChiragAgg5k force-pushed the fix/project-delete-storage branch from a6ae564 to 2ab28cf Compare October 18, 2026 10:05
@pkg-pr-new

pkg-pr-new Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/appwrite/appwrite/@appwrite.io/console@14626

commit: bde3bc0

@ChiragAgg5k
ChiragAgg5k force-pushed the fix/project-delete-storage branch from 2ab28cf to bde3bc0 Compare October 18, 2026 10:31
… objects

A deployment archive, a build output and a deployment screenshot are each one object, but the worker deleted them with recursive set. Once a recursive S3 delete lists and batch-deletes everything under path/, that flag would add a listing request per file for nothing, and would remove any object that happens to sit under the file's name followed by a slash.
…r outside the root

An empty key turns `DELETE /` into DeleteBucket, and a recursive delete or deletePath() that resolves to the whole bucket names every object in it. Both are refused with an InvalidArgumentException before any request is sent, ahead of the recursive delete that lists and removes the keys under a directory.

A path-style device also refuses a bare bucket name, its own or another, since `DELETE /{bucket}` is DeleteBucket there as well.

Only deletePath() refuses the device root itself; its check compares resolved paths, so '.', 'x/..' and '/' are caught along with ''. delete($root, true) is still allowed, because the deletes worker removes a deleted project's storage that way.

getAbsolutePath() pops '..' without stopping at the root, so root/../other names a sibling of the root. A recursive delete or deletePath() whose resolved directory is not inside the root is refused as well, and the comparison is made on whole path segments so root-x/ is not mistaken for part of root/.

Device::delete() and Device::deletePath() document that a device may refuse such paths with an InvalidArgumentException.
…S3 delete

S3 has no directories, so a recursive delete that only sends DELETE for the path removes at most one object and leaves everything under path/ behind. A recursive delete now lists the keys under path/ page by page, following the continuation token, and removes each page with one DeleteObjects request. deletePath() goes through the same code, so recursive delete() reuses deletePath()'s escaping and bucket addressing.

A page with no keys does not end the delete while a continuation token remains. A listing that cannot be followed raises a RemoteException instead of passing for an empty or finished directory: one without IsTruncated, which every ListObjectsV2 result carries, one that is truncated without a continuation token (a ListObjects V1 answer carries only NextMarker), and one that hands back the token it was asked with, which would otherwise loop forever.

Following the continuation token, the empty page and the listings that cannot be followed are covered by unit tests: the first needs more than 1000 objects end to end, and MinIO cannot be made to answer the others. An E2E test deletes nested objects through a path-style endpoint and keeps a sibling that shares the name as a prefix.
DeleteObjects can answer 200 with a body that is a top-level Error, which fails every key of the batch. That body was read as an empty error list, so the delete reported success while the objects survived. It now raises a RemoteException carrying the batch size, the directory and the error code.

An Error entry that has a Code but no Key now counts as a failure instead of being skipped, and is reported with `?` for its key. An Error that decodes to no entries, such as `<Error/>` or bare text, fails the whole batch. Every failure message names the directory being deleted.

These stay unit tests: MinIO offers no way to make it fail keys of a batch.
…evices

The project row is deleted before the deletes worker runs, and the worker resolves its injected project by reading that row back. For a project delete the injected project is therefore empty, so the injected storage devices were rooted at 'app-' with no ID: the recursive deletes ran against a root that holds none of the project's objects, and every file, deployment, build and cache entry of the deleted project stayed behind.

deleteProject() now builds the uploads, sites, functions, builds and cache devices from the deleted project's ID, wrapped in the telemetry device like the injected ones, each inside its own try so one failing root does not leave the others. The device parameters, and the cache device injection that only this path used, are gone; deleteProjectsByTeam() no longer builds devices for it.

deleteProject() refuses a document without an ID before it touches anything. The danger of an empty ID is the database half: getProjectDB() and the projectInternalId queries would run for an empty project. A unit test sends such a message and checks that no database, device or execution store is called.

testDeleteProjectStorage uploads a file and deploys a function, waits for the build to be ready and for its output to be stored, deletes the project and waits for its uploads, functions and builds roots to be empty. It runs in the S3 storage group, so the Project service is added to that group.
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