Skip to content

fix(storage): harden chunked uploads, rename and preview - #14935

Merged
lohanidamodar merged 12 commits into
mainfrom
fix/storage-upload-hardening
Oct 29, 2026
Merged

lohanidamodar merged 12 commits into
mainfrom
fix/storage-upload-hardening

Conversation

@lohanidamodar

Copy link
Copy Markdown
Member

What does this PR do?

Small storage hardening fixes:

  • Chunked upload range: a Content-Range starting at the declared size (e.g. bytes 10485760-10485760/10485760) mapped to chunk chunksTotal + 1. That stray part could leave an upload unable to finalize. These requests now fail with storage_invalid_content_range, the same as other invalid ranges. A zero total is rejected for the same reason.
  • Rename: PUT /v1/storage/buckets/:bucketId/files/:fileId now checks a changed name against the bucket's allowedFileExtensions, as create already does. It returns storage_file_type_unsupported on a mismatch. A name that doesn't change is not re-checked, so files uploaded before an allowlist change can still have their permissions updated.
  • Preview rate limit: getFilePreview gets an abuse limit of 60 requests per minute. The key is IP + user + file, so a gallery of many different files is unaffected. API keys and console users are exempt, as with every other abuse limit.
  • Idle chunked uploads: the daily per-project maintenance job now cleans up chunked uploads that have not received a chunk for 7 days (APP_STORAGE_UPLOAD_RETENTION). It aborts the staged parts on the device (Local tmp_ directory or S3 multipart upload) and deletes the pending file document. Until now these were only removed if someone explicitly deleted the file.

Why the cleanup sits in the maintenance delete job

Expiry of per-project data already runs from DELETE_TYPE_MAINTENANCE in the deletes worker (sessions, tokens, challenges, transactions, presences, push ledger). The storage device for the project is already injected there, so adding cleanup to that list needs no new queue, schedule or injection, and the worker's action() signature stays the same.

  • Finding pending uploads: a pending document has an empty signature until its last chunk completes it, so the query uses the existing _key_signature index. A row is touched only after chunksUploaded < chunksTotal is confirmed in code.
  • Idle, not old: every chunk updates the document, so $updatedAt measures time since the last chunk. A slow but active upload is never removed.
  • Device first: the document is deleted only after the device abort succeeds, or reports the staging as already gone. If the abort fails, the row stays and the next run retries.
  • Errors: a failure in one bucket is logged and does not stop the other buckets or the rest of the maintenance job.

The per-chunk component of the create-file abuse key is left unchanged. Removing it would limit every client upload to 60 chunks (about 300 MB) per minute.

Test Plan

New E2E tests:

  • StorageCustomServerTest::testChunkedUploadRejectsRangePastLastChunk: a range one past the last chunk returns 400 storage_invalid_content_range, and no pending file is created.
  • StorageCustomServerTest::testUpdateFileRejectsDisallowedExtension: in a png-only bucket, renaming to renamed.png succeeds, renaming to renamed.exe returns 400 storage_file_type_unsupported, and the stored name is unchanged.
  • StorageCustomServerTest::testIdleChunkedUploadDeletedByMaintenance:
    • Starts two 2-chunk uploads and backdates one past the retention window.
    • Runs maintenance --type=trigger.
    • Asserts the idle upload is gone (404), the recent one is untouched, and the idle ID can start over from chunk 1.
  • AbuseTest::testAbuseGetFilePreview (abuseEnabled group):
    • 60 guest previews of one file at distinct widths succeed and the 61st returns 429.
    • A different file is still served.

Local runs:

  • composer lint (Pint) on the changed files passes.
  • PHPStan on the changed files passes.
  • Rector dry-run on the changed tests passes.
  • tests/unit/Platform/Workers/DeletesTest.php passes.
  • The E2E tests above have not been run locally and need CI.

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? Only the preview route's rate-limit labels change. Specs are generated, and none are checked in.

- Reject a Content-Range that addresses a chunk past the last one.
- Apply the bucket's allowed extensions when a file is renamed.
- Rate limit file previews per caller and file.
- Abort chunked uploads idle for 7 days during maintenance and remove
  their pending file documents.
@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.

@github-actions

github-actions Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/storage-upload-hardening (after).

Metric Before After Change
🚀 Requests/sec 203.41 195.89 ⚪ -3.7%
⏱️ Latency P50 84.02 ms 88.29 ms 🔴 +5.1%
⏱️ Latency P95 203.5 ms 207.38 ms ⚪ +1.9%
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 88.29 207.38 12,540 195.89 +3.88
Account 163.9 303.02 660 11.22 +19.38
TablesDB 83.61 155.37 6,820 110.39 -9.53
Storage 86.07 198.38 3,300 54.31 +6.8
Functions 126.92 246.4 1,760 29.61 +26.92

Top API waits (after)

API request Max wait (ms)
account.name.update 454.5
storage.buckets.create 398.2
functions.create 366.34
functions.variables.update 364.02
account.prefs.update 357.17

Request input holds only query and body values, so a key such as
{param-fileId} never resolved for a path param and every file shared
one preview counter.
@lohanidamodar
lohanidamodar marked this pull request as ready for review October 26, 2026 01:50
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟠 1 high · 🟡 1 medium

💬 Inline comments (1)

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

🟠 High — Query params override path params in abuse keys, enabling limit bypass · api.php:622–626 · unchanged line

// app/controllers/shared/api.php
622	                foreach (\array_merge($pathParams, $request->getParams()) as $key => $value) {
623	                    if (! empty($value)) {
624	                        $params['{param-' . $key . '}'] = (\is_array($value) || \is_object($value)) ? (string) \json_encode($value) : (string) $value;
625	                    }
626	                }

The abuse-key param map is built with array_merge($pathParams, $request->getParams()), so a client-supplied query/body param shadows the path param of the same name (app/controllers/shared/api.php:622). On GET /v1/storage/buckets/:bucketId/files/:fileId/preview the validated action argument takes fileId from the path, but the abuse key fileId:{param-fileId} (src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php:62) is substituted with the attacker-controlled query value. A guest hammering one file can rotate a fake ?fileId= on every request and receive a fresh rate-limit bucket each time while the real path file is served — the 60/60s per-file limit is fully bypassed. The same merge order appears in the shutdown abuse-reset hook at app/controllers/shared/api.php:1014, so a reset would also target the attacker-chosen key.


This PR closes gaps around chunked upload lifecycle and abuse limiting: stale incomplete uploads are now reaped by a maintenance worker, invalid content ranges past the last chunk are rejected at chunk time, file renames are validated against bucket extension policies, and file previews get a per-file 60/minute abuse limit keyed on fileId.

Files Change
app/controllers/shared/api.php Merges route path params into the abuse-key param map so keys can reference fileId and other path params.
src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Create.php Rejects content-range chunks beyond the total chunk count with storage_invalid_content_range.
src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Update.php Validates a changed file name against the bucket's allowedFileExtensions.
src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php Adds a per-fileId abuse key and 60/minute limit for preview requests.
app/init/constants.php, src/Appwrite/Platform/Workers/Deletes.php Introduces APP_STORAGE_UPLOAD_RETENTION (7 days) and a deleteExpiredUploads maintenance pass that aborts and deletes incomplete uploads untouched past the window.
tests/e2e/General/AbuseTest.php, tests/e2e/Services/Storage/StorageCustomServerTest.php E2E coverage for preview abuse limiting, content-range rejection, rename extension rejection, and retention-based cleanup.

Reviewed commit: b9a904e

@ghost

ghost commented Oct 26, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The new renewal checks address the outstanding cleanup-lease issue, and no additional actionable problems were found in this incremental change.

Storage API changes reject invalid chunk ranges, enforce bucket extension allowlists on renamed files, and rate-limit previews per file. The maintenance worker also reaps idle chunked uploads by aborting their staged data before deleting pending file records, with retry handling for failed aborts. E2E and unit coverage was added for these behaviors.

Latest changes: The newest commits renew the cleanup lock before each device operation and stop cleanup when renewal fails, with a unit case covering lease loss before fallback deletion.

Verdict New comments Fixed Still open
✅ Approved 0 1 0
📂 Walkthrough · 9
File Change
app/controllers/shared/api.php Uses route path parameters as authoritative values when building and clearing abuse-limit keys.
app/init/constants.php Defines the retention period for idle chunked uploads.
src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Create.php Rejects chunk upload ranges that start at or beyond the declared file size.
src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Preview/Get.php Adds per-file preview request throttling.
src/Appwrite/Platform/Modules/Storage/Http/Buckets/Files/Update.php Checks changed filenames against the bucket's allowed extensions.
src/Appwrite/Platform/Workers/Deletes.php Cleans up idle pending uploads and renews the upload lock before each device operation.
tests/e2e/General/AbuseTest.php Covers per-file preview limits and route parameters overriding query values in abuse keys.
tests/e2e/Services/Storage/StorageCustomServerTest.php Covers invalid chunk ranges, extension validation on rename, and maintenance cleanup of idle uploads.
tests/unit/Platform/Workers/DeletesTest.php Covers upload-abort retries and verifies cleanup stops after losing its lease.
✅ Fixed since the last review · 1
  • The cleanup lease expires before an upload lease · src/Appwrite/Platform/Workers/Deletes.php:2176

Reviewed the commits since 1519a1e · 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

Comment thread app/controllers/shared/api.php Resolved

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

The PR adds upload-retention cleanup for stale chunked uploads, content-range boundary validation, allowedFileExtensions enforcement on file rename, and per-file abuse keys for file previews — but the abuse-key param merge lets client query params shadow path params, enabling a per-file rate-limit bypass.

Key findings

  • 🟠 Query params override path params in abuse keys, enabling limit bypass — api.php:622
  • 🟡 Failed S3 abort strands pending upload row forever — Deletes.php:2134

@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

The stored date carries a T separator and offset, so a string comparison
against the cutoff misorders values on the same day.
A failed abort keeps the row and its upload ID for up to three runs
before falling back to deleting the path. The cleanup lease matches the
upload lease and is checked before any row is changed.

@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 · See the inline comments. Summary

Also exercises the upload retry through the maintenance job instead of
the private method.
…rdening

# Conflicts:
#	src/Appwrite/Platform/Workers/Deletes.php
Refreshing the lease before the abort, the retry write, the fallback
delete and the row removal stops cleanup once another holder owns the
key, and gives each step a full TTL.

@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

@lohanidamodar
lohanidamodar merged commit 2c9be6e into main Oct 29, 2026
72 checks passed
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.

2 participants