Skip to content

fix(messaging): decrypt email attachments before sending - #13525

Merged
HarshMN2345 merged 3 commits into
mainfrom
fix/messaging-encrypted-attachments
Sep 10, 2026
Merged

HarshMN2345 merged 3 commits into
mainfrom
fix/messaging-encrypted-attachments

Conversation

@HarshMN2345

@HarshMN2345 HarshMN2345 commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Fixes #9068 — an email attachment taken from a bucket with encryption enabled arrives as AES-128-GCM ciphertext, and the recipient cannot open it. The same applies to a bucket with compression set: the attachment arrives gzip/zstd-compressed.

Root cause: uploads are compressed and then encrypted (Storage/.../Files/Create.php:381-408), and every storage read endpoint undoes both before serving (Files/View/Get.php:171-197 and its siblings). Workers/Messaging.php was the only consumer of stored bytes in the messaging pipeline that skipped that step — it passed $file->getAttribute('path') straight to new Attachment(...), so the adapter read the stored bytes off disk verbatim. Push images are unaffected: they go through a pre-signed URL that hits the /push endpoint, which does decrypt.

Changes:

  • prepareAttachments() decrypts and then decompresses each attachment, writing the result to a job-unique directory under the project's local uploads root (_attachments/<uid>/<bucketId>/<fileId>). A bucket ID may not start with an underscore (Validator/Key.php:52-55), so the directory cannot collide with a stored bucket.
  • It runs once per message, in sendExternalMessage() before the batch() fan-out, instead of once per batch per retry attempt inside buildEmailMessage() (100–500 times for a 5000-recipient SES send). The prepared array<Attachment> is threaded down sendBatch → retrySend → buildMessage → buildEmailMessage, which lets Device $deviceForFiles and Document $project drop out of that chain.
  • Nothing is written back to the file's own path. The old copy($path, $path, $localDevice) needed a DeviceType::Local guard precisely because on a local install getLocalDevice($project) is deviceForFiles; writing plaintext there would have destroyed the ciphertext irrecoverably, since openSSLIV/openSSLTag would still claim the file is encrypted. Both guards are gone now that the target is derived from the scratch directory. This also removes the same-path copy race, where up to MESSAGE_SEND_CONCURRENCY coroutines truncated and refilled one destination while siblings read it.
  • Cleanup moved to a finally in action(), so decrypted plaintext no longer survives the five early returns and every throw that skipped the old post-delivery block. Deleting one directory also drops the two getDocument() calls per attachment that the old cleanup performed, and with them its ability to throw over a bucket deleted between send and cleanup.
  • A decompressor reports failure as an empty string (GZIP::decompress is : string in a file without strict_types, so gzdecode()'s false is coerced to ''). Files stored above the 20MB read buffer before 1.5.0 recorded an algorithm they were never compressed with; they now fall back to their stored bytes rather than being mailed as an empty file, matching how Files/Download/Get.php:190-216 keeps them downloadable. An undecryptable file (rotated or missing _APP_OPENSSL_KEY_V*) fails the send instead of mailing ciphertext.
  • Attachments carry a path and no content: Sendgrid.php:88,97 and Mailgun.php:111,121-126 read only Attachment::getPath(), so a content-only attachment would throw on both. Keeping a real file also keeps their filesize()-based size guards honest.
  • OpenSSL::decrypt's docblock said @return string; openssl_decrypt returns string|false. Corrected, so the new guard type-checks at PHPStan level 4.

Test Plan

Reproduced on main and fixed on this branch, same fixture. Loaded main's Workers/Messaging.php under a separate namespace alongside this branch's, stored one file the way Files/Create.php does for an encrypted + gzip bucket, and read the bytes each version's Attachment puts on the wire:

first bytes the adapter sends
stored on disk (ciphertext) 746a776b4d514f4e675a324651463568502f454e43755132…
before (main) 746a776b4d514f4e675a324651463568502f454e43755132… — identical to the ciphertext
after (this branch) 696e766f6963655f69642c616d6f756e740a494e562d312c… = invoice_id,amount\nINV-1,…

prepareAttachments() executed against real stored files, seven cases, all delivering the expected bytes: encrypted+gzip, encrypted only, gzip only, zstd only, plain, a legacy row whose algorithm says gzip over uncompressed bytes, and a genuinely zero-byte upload. In every case the stored original stayed byte-intact and the scratch directory was fully reclaimed. Separately confirmed that the remote-device branch copies into the scratch directory rather than the stored path, and that a file whose key no longer decrypts it throws instead of being sent.

New e2e: testSendEmailEncryptedAttachment uploads a CSV to an encrypted + gzip bucket, mails it through an SMTP provider to maildev, and asserts the delivered attachment bytes equal the source file. It guards the premise with assertTrue($file['body']['encryption']) so it cannot pass vacuously, and binds its own target to its own provider so it does not depend on which email provider the project enabled first. The maildev REST shape it asserts on (attachments[].generatedFileName, GET /email/:id/attachment/:name) was verified live.

Static analysis and formatting: pint --test and composer refactor:check are clean, and a full composer analyze on this branch produces an error set byte-identical to main's own baseline measured in the same tree (2 pre-existing errors, both in Files/Preview/Get.php, neither in a file this PR touches).

The new e2e test could not be executed locally: every worker container crash-loops because composer.lock pins utopia-php/queue 1.1.4 while app/worker.php:80 passes maxCoroutines:, so POST /v1/messaging/messages/email 500s on Utopia\Queue\Publisher not found before the worker is ever reached. That is pre-existing on main and unrelated to this change; the test's first 18 assertions pass and it stops exactly there.

Related PRs and Issues

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 surface change; the worker is internal.

@greptile-apps

greptile-apps Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR prepares email attachments from Appwrite storage before provider delivery.

  • Decrypts and decompresses stored attachment bytes into job-unique local scratch paths.
  • Reuses prepared attachments across batches and retries.
  • Cleans plaintext scratch files in a finally block and reports unsuccessful cleanup.
  • Corrects the documented return type of OpenSSL::decrypt.
  • Adds an end-to-end test for encrypted, gzip-compressed email attachments.

Confidence Score: 5/5

The PR appears safe to merge, with no outstanding correctness or security issue identified.

The earlier scratch-write finding was withdrawn after confirming that the concrete local storage implementation throws on failure, and the plaintext-cleanup finding is resolved by deletion in finally followed by an existence check and span reporting. No new blocking failure remains.

Important Files Changed

Filename Overview
src/Appwrite/OpenSSL/OpenSSL.php Corrects the decrypt helper’s return annotation to include OpenSSL failure.
src/Appwrite/Platform/Workers/Messaging.php Materializes decrypted and decompressed attachments once per message, safely reuses them during delivery, and cleans the scratch directory afterward.
tests/e2e/Services/Messaging/MessagingBase.php Adds coverage confirming an encrypted and compressed storage file is delivered with its original bytes.

Reviews (4): Last reviewed commit: "fix(messaging): fail the send when an at..." | Re-trigger Greptile

@HarshMN2345
HarshMN2345 force-pushed the fix/messaging-encrypted-attachments branch from 9a9245b to 0b44f44 Compare September 8, 2026 10:25
@github-actions

github-actions Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/messaging-encrypted-attachments (after).

Metric Before After Change
🚀 Requests/sec 211.58 201.63 ⚪ -4.7%
⏱️ Latency P50 82.03 ms 85.82 ms ⚪ +4.6%
⏱️ Latency P95 190.82 ms 207.27 ms 🔴 +8.6%
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.82 207.27 12,540 201.63 +16.46
Account 176.27 315.97 660 11.4 +38.03
TablesDB 81.87 147.6 6,820 112.82 +1.5
Storage 80.83 179.29 3,300 56.06 +14.29
Functions 128.62 254.3 1,760 30.54 +36.44

Top API waits (after)

API request Max wait (ms)
functions.variables.update 479.86
functions.create 457.8
account.name.update 432.18
account.prefs.update 405.35
tablesdb.rows.create 386.26

The messaging worker handed mail adapters the stored file path, which
for a bucket with encryption or compression enabled is ciphertext or
compressed bytes rather than what the recipient should receive. Every
storage read endpoint undoes both transforms before serving; the email
attachment path was the only consumer of stored bytes in the messaging
pipeline that did not.

Attachments are now materialised once per job, ahead of the recipient
fan-out, into a job-unique directory under the project's local uploads
root: decrypt, then decompress, the reverse of what upload applies.
Building them there rather than in buildEmailMessage also stops the work
repeating once per batch per retry attempt, and keeps concurrent
coroutines off a shared destination path. Nothing is written back to the
file's own path, which on a local install is the stored original, so the
DeviceType::Local guards that existed to prevent a self-copy are gone.
Cleanup moves to a finally in action(), covering the failure paths the
old post-delivery block skipped.

A decompressor reports failure as an empty string, so files stored above
the read buffer before 1.5.0 -- which recorded an algorithm they were
never compressed with -- fall back to their stored bytes instead of
being mailed as an empty file. An undecryptable file fails the send.

Attachments carry a path and no content: Sendgrid and Mailgun read only
Attachment::getPath().
Recursive delete reports failure by returning false, but so does an
absent directory, which is the normal outcome for a message that
materialised no attachments. Checking the return value alone would flag
almost every send. Test the directory instead: one that is still there
after the delete is decrypted plaintext left on local storage, which
until now went unnoticed because this is the only cleanup and nothing
sweeps the directory afterwards.

Reported through a span rather than thrown, so it cannot bury the
exception the send itself raised.
Local storage reports a write failure by throwing, but the device
contract allows a falsy return, and an attachment built for a target
that was never written sends the provider after a file that is not
there. Trim three comments that restated the code they sat on.
@HarshMN2345
HarshMN2345 force-pushed the fix/messaging-encrypted-attachments branch from 63859b3 to 08fa061 Compare September 8, 2026 11:12
@HarshMN2345
HarshMN2345 merged commit 4ac28ac into main Sep 10, 2026
87 of 88 checks passed
@ChiragAgg5k ChiragAgg5k mentioned this pull request Sep 10, 2026
2 of 4 tasks
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.

🐛 Bug Report: Sending email attachment from encrypted bucket will send encrypted file

2 participants