Skip to content

fix(avatars): cap remote fetch size and rate limit image and favicon - #14788

Merged
ChiragAgg5k merged 3 commits into
mainfrom
fix/avatars-remote-fetch-cap
Oct 22, 2026
Merged

ChiragAgg5k merged 3 commits into
mainfrom
fix/avatars-remote-fetch-cap

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Bounds how much the avatars endpoints read from a remote URL.

  • clientForAvatars (used by /v1/avatars/image, /v1/avatars/favicon and the Gravatar, Libravatar and OAuth2 photo providers) now sets CURLOPT_MAXFILESIZE_LARGE to APP_STORAGE_READ_BUFFER (20MB), the ceiling storage already uses for anything it holds in memory (previews, compression, encryption). The image and favicon handlers already map any transfer error to AVATAR_REMOTE_URL_FAILED; photo providers treat it as a miss and fall through to the next provider.
  • On the bundled cURL (8.22), the limit is checked against decoded body bytes while the transfer is in progress. It also applies to chunked responses with no Content-Length, so a compressed response stops at the cap after decoding. I checked this against a local server: a 192MB plain stream and a 200KB gzip body that decodes to 200MB were both cut off at the cap within milliseconds, and peak memory stayed at 6MB.
  • Connect (5s) and total (15s) timeouts move onto the shared client, replacing the per-call withTimeout(15) in the image and favicon handlers. Photo providers keep their own shorter budget.
  • /v1/avatars/image and /v1/avatars/favicon get abuse-key url:{url},ip:{ip} with 60 requests per minute.

I didn't stream through Client::stream() with a byte-counting sink. When a sink throws inside the cURL write callback, PHP's ext/curl does not abort the transfer: the callback still reports the full chunk length, so cURL keeps downloading until the server finishes or the timeout fires. Memory stays bounded, but the connection does not. The adapter option stops the transfer itself.

Test Plan

  • New e2e AvatarsCustomServerTest::testGetRemoteFileTooLarge. It uploads tests/resources/disk-a/large-file.mp4 (23.6MB) and logo.png to a public bucket, then points the avatars endpoints at this instance's own /view URL. That URL goes through an API rule on a *.127.0.0.1.nip.io name, because CI's router protection refuses bare IP hosts. The name resolves to loopback, which the test .env allows through _APP_ALLOWED_INTERNAL_ADDRESSES. The view endpoint streams files above 20MB in chunks with no Content-Length, so the test exercises the mid-transfer cutoff.
    • Success: /avatars/image on the small file returns a PNG.
    • Failure: /avatars/image and /avatars/favicon on the large file return 404 avatar_remote_url_failed. Without the cap, image returns avatar_image_not_found and favicon goes on to fetch /favicon.ico.
  • Not run locally against a full stack; relying on the Avatars e2e lane in CI.
  • composer lint, PHPStan (host, phpstan.neon) and composer refactor:check pass on the touched files.

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#6674

Remote images, favicons and photo-provider downloads were buffered in full,
after automatic content decoding, with no size limit. The avatars client
now sets CURLOPT_MAXFILESIZE_LARGE to APP_STORAGE_READ_BUFFER, the same
20MB ceiling storage uses for in-memory processing. cURL counts decoded
bytes against it and aborts the transfer as soon as it is passed, so a
compressed response cannot expand past the cap either. Connect and total
timeouts move onto the shared client, and the image and favicon routes get
a per-IP abuse limit.
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟠 1 high

💬 Inline comments (1)

  • 🟠 CURLOPT_MAXFILESIZE_LARGE cap does not apply to HTTP transfers — resources.php:112
🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Close $handle with try/finally around chunk loop (AvatarsCustomServerTest.php:223) — In testGetRemoteFileTooLarge, fclose($handle) sits after the upload loop (tests/e2e/Services/Avatars/AvatarsCustomServerTest.php:223-245), so a failed per-chunk assertEquals(201, ...) aborts the test mid-loop and leaks the file handle opened by fopen.

The change hardens the /avatars/image and /avatars/favicon remote-fetch endpoints: a CURLOPT_MAXFILESIZE_LARGE cap and connect/total timeouts are baked into the shared clientForAvatars container resource, per-call withTimeout(15) cloning is removed from both actions, and abuse-key/limit labels are added. A new e2e test exercises oversized remote files through chunked storage uploads. The main concern is that CURLOPT_MAXFILESIZE_LARGE is not enforced by libcurl on HTTP transfers, so the cap may be a no-op for these clients and the e2e assertions could be masking it.

Files Change
app/init/resources.php Adds CURLOPT_MAXFILESIZE_LARGE (bounded by APP_STORAGE_READ_BUFFER) and baked-in connect/total timeouts to the shared avatars client factory.
src/Appwrite/Platform/Modules/Avatars/Http/Favicon/Get.php, Http/Image/Get.php Drop per-request timeout cloning in favor of the shared client config; add abuse rate-limit labels.
tests/e2e/Services/Avatars/AvatarsCustomServerTest.php Adds testGetRemoteFileTooLarge covering oversized remote fetches for both endpoints via chunked uploads.

Reviewed commit: 58ce3ef

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

ghost commented Oct 22, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The shared avatar HTTP client now caps remote response bodies at the storage read-buffer limit and applies connection and total timeouts. The image and favicon routes use that client and have per-URL/IP abuse limits. E2E coverage checks small and oversized remote files, verifies both route limits, and closes the large-file fixture handle even when upload assertions fail.

Latest changes: The newest commits add E2E checks for image and favicon abuse limits and ensure the large-file fixture handle closes if its upload loop fails.

Verdict New comments Fixed Still open
✅ Approved 0 1 0
📂 Walkthrough · 5
File Change
app/init/resources.php Configures the shared avatar HTTP client with a response-size cap and connection and total timeouts.
src/Appwrite/Platform/Modules/Avatars/Http/Image/Get.php Adds a per-URL/IP abuse limit and uses the shared avatar client.
src/Appwrite/Platform/Modules/Avatars/Http/Favicon/Get.php Adds a per-URL/IP abuse limit and uses the shared avatar client for page and icon fetches.
tests/e2e/General/AbuseTest.php Checks that image and favicon fetch requests are throttled after the configured limit.
tests/e2e/Services/Avatars/AvatarsCustomServerTest.php Exercises small and oversized remote-file behavior through a custom API domain and closes the source handle in a finally block.
✅ Fixed since the last review · 1
  • Add coverage for the new avatar rate limits · src/Appwrite/Platform/Modules/Avatars/Http/Image/Get.php:40

Reviewed the commits since b887987 · 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 · Looks good to merge. 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 adds a 20MB download cap, shared client timeouts, and abuse rate-limit labels to the Avatars remote-fetch endpoints, plus an e2e regression test, but the size cap relies on a libcurl option that does not apply to HTTP transfers.

Key findings

  • 🟠 CURLOPT_MAXFILESIZE_LARGE cap does not apply to HTTP transfers — resources.php:112

Comment thread app/init/resources.php
Comment on lines +112 to +119
$container->set('clientForAvatars', fn () => (new Client(new CurlAdapter(options: [
\CURLOPT_MAXFILESIZE_LARGE => APP_STORAGE_READ_BUFFER,
]), new PublicInternet(
...\array_map(
fn (string $range) => new IPRange($range),
\array_filter(\array_map('trim', \explode(',', System::getEnv('_APP_ALLOWED_INTERNAL_ADDRESSES', '')))),
)
)), []);
)))->withConnectTimeout(5)->withTimeout(15), []);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 security · high

CURLOPT_MAXFILESIZE_LARGE cap does not apply to HTTP transfers

The size cap added to clientForAvatars (app/init/resources.php:112-113) relies on CURLOPT_MAXFILESIZE_LARGE, but libcurl enforces this option only on FTP/FILE/SFTP downloads — it does not affect HTTP transfers, which is all these clients ever do. The CurlAdapter write callback (packages/client/src/Adapter/Curl/Client.php:358) accumulates response body bytes with no size limit, so the intended 20 MB cap is a no-op. An attacker-controlled target of /avatars/image or /avatars/favicon can still stream arbitrarily large (including gzip-decoded) bodies into memory within the 15s timeout, reproducing the resource exhaustion this change sets out to prevent.

📋 Prompt for AI Agents

In app/init/resources.php around lines 112-113, the CURLOPT_MAXFILESIZE_LARGE => APP_STORAGE_READ_BUFFER option on the CurlAdapter does not apply to HTTP transfers per libcurl semantics, so the intended cap on avatar fetches is a no-op. Add a byte-counting guard in packages/client/src/Adapter/Curl/Client.php's CURLOPT_WRITEFUNCTION callback (around line 358) — or a client-level decorator used only by clientForAvatars — that aborts the transfer (throws a PSR-18 client exception) once accumulated body bytes exceed APP_STORAGE_READ_BUFFER, so the exception surfaces in the Avatars actions as AVATAR_REMOTE_URL_FAILED before unbounded memory is consumed.

@ChiragAgg5k ChiragAgg5k Oct 22, 2026 •

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.

This option does apply to HTTP. libcurl documents CURLOPT_MAXFILESIZE_LARGE for FTP, HTTP and MQTT, and since 8.4.0 it also stops a transfer whose size is unknown up front once it passes the limit. The Appwrite image ships curl 8.22.0 (curl_version() in appwrite/appwrite:2.6.1). I checked it against a local server, using the adapter configured the same way as clientForAvatars. A chunked 192MB plain body was aborted at exactly 20,000,000 bytes with Exceeded the maximum allowed file size in 0.06s. A 200KB gzip body that decodes to 200MB was aborted at 19,986,934 decoded bytes with Would have exceeded max file size. Peak memory was 6MB in both cases, so the limit is checked against decoded bytes as they are written. The e2e test also covers the chunked case: the storage /view endpoint streams files over 20MB without a Content-Length, and the test asserts avatar_remote_url_failed. Without the cap, image returns avatar_image_not_found instead. I did not use a byte-counting write callback: when a PHP callback throws inside the cURL write function, ext/curl still reports the full chunk as handled, so the transfer keeps running until the timeout. The handle nitpick is fixed in 943795b: the upload loop now closes it in finally.

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/avatars-remote-fetch-cap (after).

Metric Before After Change
🚀 Requests/sec 204.67 209.13 ⚪ +2.2%
⏱️ Latency P50 83.17 ms 83.31 ms ⚪ +0.2%
⏱️ Latency P95 198.05 ms 190.2 ms ⚪ -4%
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 83.31 190.2 13,110 209.13 -7.85
Account 151.09 271.75 690 11.44 -8.59
TablesDB 80.66 146.23 7,130 116.4 -0.79
Storage 76.52 189.92 3,450 57.86 -13.64
Functions 113.11 223.69 1,840 31.6 -1.57

Top API waits (after)

API request Max wait (ms)
functions.variables.update 419.1
functions.create 408.34
storage.files.create 389.38
storage.buckets.create 360.76
functions.delete 342.82

CI enables router protection, which refuses requests addressed to a bare
IP, so the fixture is served through an API rule on a nip.io name that
resolves to loopback.
Guests past 60 fetches a minute from one address get 429 on both routes.
The large-file upload in the avatars test now closes its handle when a
chunk assertion fails.

@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

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

@ChiragAgg5k
ChiragAgg5k merged commit d2c83c3 into main Oct 22, 2026
74 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the fix/avatars-remote-fetch-cap branch October 22, 2026 16:49
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ckport #14788)

The image and favicon avatars read a remote body of any size into memory. They now keep at most APP_STORAGE_READ_BUFFER bytes and fail with avatar_remote_url_failed past it, and both routes are limited to 60 requests per minute per IP. 1.9 fetches through utopia-php/fetch, whose cURL adapter takes no raw options, so the cap is enforced in a chunk callback rather than with CURLOPT_MAXFILESIZE_LARGE. The remote-file-too-large E2E test is not ported: it relies on the internal address allowlist 1.9 does not have.

(cherry picked from commit d2c83c3)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ckport #14788)

The image and favicon avatars read a remote body of any size into memory. They now keep at most APP_STORAGE_READ_BUFFER bytes and fail with avatar_remote_url_failed past it, and both routes are limited to 60 requests per minute per IP. 1.9 fetches through utopia-php/fetch, whose cURL adapter takes no raw options, so the cap is enforced in a chunk callback rather than with CURLOPT_MAXFILESIZE_LARGE. The remote-file-too-large E2E test is not ported: it relies on the internal address allowlist 1.9 does not have.

(cherry picked from commit d2c83c3)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ckport #14788)

The image and favicon avatars read a remote body of any size into memory. They now keep at most APP_STORAGE_READ_BUFFER bytes and fail with avatar_remote_url_failed past it, and both routes are limited to 60 requests per minute per IP. 1.9 fetches through utopia-php/fetch, whose cURL adapter takes no raw options, so the cap is enforced in a chunk callback rather than with CURLOPT_MAXFILESIZE_LARGE. The remote-file-too-large E2E test is not ported: it relies on the internal address allowlist 1.9 does not have.

(cherry picked from commit d2c83c3)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ckport #14788)

The image and favicon avatars read a remote body of any size into memory. They now keep at most APP_STORAGE_READ_BUFFER bytes and fail with avatar_remote_url_failed past it, and both routes are limited to 60 requests per minute per IP. 1.9 fetches through utopia-php/fetch, whose cURL adapter takes no raw options, so the cap is enforced in a chunk callback rather than with CURLOPT_MAXFILESIZE_LARGE. The remote-file-too-large E2E test is not ported: it relies on the internal address allowlist 1.9 does not have.

(cherry picked from commit d2c83c3)
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…ckport #14788)

The image and favicon avatars read a remote body of any size into memory. They now fetch through a cURL adapter that aborts the transfer once the body passes APP_STORAGE_READ_BUFFER (CURLOPT_MAXFILESIZE_LARGE plus a write callback that stops on the cap), failing with avatar_remote_url_failed, and both routes are limited to 60 requests per minute per IP. 1.9 fetches through utopia-php/fetch, whose cURL adapter takes no raw options, hence the small Appwrite\Utopia\Fetch\Adapter\Curl. The remote-file-too-large E2E test is not ported: it relies on the internal address allowlist 1.9 does not have.

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

fix(avatars): cap remote fetch size and rate limit image and favicon

(cherry picked from commit d2c83c3)
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