Repository navigation
fix(messaging): decrypt email attachments before sending - #13525
Merged
Merged
Conversation
Contributor
Greptile SummaryThis PR prepares email attachments from Appwrite storage before provider delivery.
Confidence Score: 5/5The 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 Important Files Changed
Reviews (4): Last reviewed commit: "fix(messaging): fail the send when an at..." | Re-trigger Greptile |
HarshMN2345
force-pushed
the
fix/messaging-encrypted-attachments
branch
from
September 8, 2026 10:25
9a9245b to
0b44f44
Compare
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
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
force-pushed
the
fix/messaging-encrypted-attachments
branch
from
September 8, 2026 11:12
63859b3 to
08fa061
Compare
ChiragAgg5k
approved these changes
Sep 10, 2026
2 tasks done
2 of 4 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
compressionset: 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-197and its siblings).Workers/Messaging.phpwas the only consumer of stored bytes in the messaging pipeline that skipped that step — it passed$file->getAttribute('path')straight tonew 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/pushendpoint, 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.sendExternalMessage()before thebatch()fan-out, instead of once per batch per retry attempt insidebuildEmailMessage()(100–500 times for a 5000-recipient SES send). The preparedarray<Attachment>is threaded downsendBatch → retrySend → buildMessage → buildEmailMessage, which letsDevice $deviceForFilesandDocument $projectdrop out of that chain.copy($path, $path, $localDevice)needed aDeviceType::Localguard precisely because on a local installgetLocalDevice($project)isdeviceForFiles; writing plaintext there would have destroyed the ciphertext irrecoverably, sinceopenSSLIV/openSSLTagwould 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 toMESSAGE_SEND_CONCURRENCYcoroutines truncated and refilled one destination while siblings read it.finallyinaction(), 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 twogetDocument()calls per attachment that the old cleanup performed, and with them its ability to throw over a bucket deleted between send and cleanup.GZIP::decompressis: stringin a file withoutstrict_types, sogzdecode()'sfalseis coerced to''). Files stored above the 20MB read buffer before 1.5.0 recorded analgorithmthey were never compressed with; they now fall back to their stored bytes rather than being mailed as an empty file, matching howFiles/Download/Get.php:190-216keeps them downloadable. An undecryptable file (rotated or missing_APP_OPENSSL_KEY_V*) fails the send instead of mailing ciphertext.content:Sendgrid.php:88,97andMailgun.php:111,121-126read onlyAttachment::getPath(), so a content-only attachment would throw on both. Keeping a real file also keeps theirfilesize()-based size guards honest.OpenSSL::decrypt's docblock said@return string;openssl_decryptreturnsstring|false. Corrected, so the new guard type-checks at PHPStan level 4.Test Plan
Reproduced on
mainand fixed on this branch, same fixture. Loadedmain'sWorkers/Messaging.phpunder a separate namespace alongside this branch's, stored one file the wayFiles/Create.phpdoes for an encrypted + gzip bucket, and read the bytes each version'sAttachmentputs on the wire:746a776b4d514f4e675a324651463568502f454e43755132…main)746a776b4d514f4e675a324651463568502f454e43755132…— identical to the ciphertext696e766f6963655f69642c616d6f756e740a494e562d312c…=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 whosealgorithmsays 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:
testSendEmailEncryptedAttachmentuploads 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 withassertTrue($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 --testandcomposer refactor:checkare clean, and a fullcomposer analyzeon this branch produces an error set byte-identical tomain's own baseline measured in the same tree (2 pre-existing errors, both inFiles/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.lockpinsutopia-php/queue1.1.4 whileapp/worker.php:80passesmaxCoroutines:, soPOST /v1/messaging/messages/email500s onUtopia\Queue\Publisher not foundbefore the worker is ever reached. That is pre-existing onmainand unrelated to this change; the test's first 18 assertions pass and it stops exactly there.Related PRs and Issues
Checklist