π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Limit wall message payload size
Anand Baburajandb32abab677c
diff --git a/rust/wall/src/client.rs b/rust/wall/src/client.rsindex ebb560178b..a274fe0ac6 100644--- a/rust/wall/src/client.rs+++ b/rust/wall/src/client.rs@@ -39,6 +39,11 @@ pub const MAX_WALL_POST_PLAINTEXT_BYTES: usize =MAX_WALL_POST_UPLOAD_BYTES - PACKED_SECRETBOX_OVERHEAD_BYTES;pub const MAX_WALL_AVATAR_PLAINTEXT_BYTES: usize =MAX_WALL_AVATAR_UPLOAD_BYTES - PACKED_SECRETBOX_OVERHEAD_BYTES;+pub const MAX_WALL_MESSAGE_TEXT_CHARS: usize = 1000;+pub const MAX_WALL_MESSAGE_TEXT_BYTES: usize = 4 * 1024;+pub const MAX_WALL_MESSAGE_CIPHER_DECODED_BYTES: usize = 6 * 1024;+pub const MAX_WALL_MESSAGE_PAYLOAD_BYTES: usize =+ MAX_WALL_MESSAGE_CIPHER_DECODED_BYTES - PACKED_SECRETBOX_OVERHEAD_BYTES;#[derive(Debug, Clone)]struct ResolvedWallAccess {@@ -1022,6 +1027,7 @@ impl AccountWallCtx {let message_key = generate_key();let plaintext = serde_json::to_vec(payload).map_err(|err| WallError::InvalidInput(format!("invalid message payload: {err}")))?;+ validate_message_payload(payload, plaintext.len())?;let sender_key = sealed::seal(&message_key, &self.public_key)?;let recipient_key = sealed::seal(&message_key, &recipient_public_key)?;Ok(CreateMessageRequest {@@ -1307,6 +1313,25 @@ fn ensure_wall_upload_size(purpose: &str, encrypted_size: usize, max_bytes: usizOk(())}+fn validate_message_payload(payload: &MessagePayload, plaintext_len: usize) -> Result<()> {+ if payload.text.chars().count() > MAX_WALL_MESSAGE_TEXT_CHARS {+ return Err(WallError::InvalidInput(format!(+ "message text must be {MAX_WALL_MESSAGE_TEXT_CHARS} characters or fewer"+ )));+ }+ if payload.text.len() > MAX_WALL_MESSAGE_TEXT_BYTES {+ return Err(WallError::InvalidInput(format!(+ "message text must be {MAX_WALL_MESSAGE_TEXT_BYTES} bytes or fewer"+ )));+ }+ if plaintext_len > MAX_WALL_MESSAGE_PAYLOAD_BYTES {+ return Err(WallError::InvalidInput(format!(+ "message payload must be {MAX_WALL_MESSAGE_PAYLOAD_BYTES} bytes or fewer"+ )));+ }+ Ok(())+}+fn post_response_from_feed_item(item: &FeedItem) -> PostResponse {PostResponse {post_id: item.post_id,@@ -2764,6 +2789,46 @@ mod tests {delete.assert_async().await;}+ #[test]+ fn message_payload_limits_reject_oversized_text_and_payload() {+ let valid = MessagePayload {+ version: 1,+ kind: MESSAGE_KIND_REGULAR.to_owned(),+ text: "hello".to_owned(),+ quote: None,+ };+ let valid_plaintext = serde_json::to_vec(&valid).expect("valid payload json");+ validate_message_payload(&valid, valid_plaintext.len())+ .expect("short message should be accepted");++ let too_many_chars = MessagePayload {+ text: "a".repeat(MAX_WALL_MESSAGE_TEXT_CHARS + 1),+ ..valid.clone()+ };+ let plaintext = serde_json::to_vec(&too_many_chars).expect("long text json");+ let err = validate_message_payload(&too_many_chars, plaintext.len())+ .expect_err("long message text should be rejected");+ assert!(err.to_string().contains("characters or fewer"));++ let oversized_payload = MessagePayload {+ text: "ok".to_owned(),+ quote: Some(MessageQuote {+ post_id: 1,+ wall_id: "wall_owner_main".to_owned(),+ caption: Some("a".repeat(MAX_WALL_MESSAGE_PAYLOAD_BYTES)),+ object_key: None,+ width: None,+ height: None,+ media_type: None,+ }),+ ..valid+ };+ let plaintext = serde_json::to_vec(&oversized_payload).expect("large payload json");+ let err = validate_message_payload(&oversized_payload, plaintext.len())+ .expect_err("large serialized payload should be rejected");+ assert!(err.to_string().contains("payload must be"));+ }+#[tokio::test]async fn list_post_likers_uses_post_likes_endpoint() {let mut server = Server::new_async().await;diff --git a/rust/wall/src/lib.rs b/rust/wall/src/lib.rsindex aa0977c023..6a98d0f761 100644--- a/rust/wall/src/lib.rs+++ b/rust/wall/src/lib.rs@@ -6,7 +6,9 @@ pub mod transport;pub use client::{AccountWallCtx, MAX_WALL_AVATAR_PLAINTEXT_BYTES, MAX_WALL_AVATAR_UPLOAD_BYTES,- MAX_WALL_POST_PLAINTEXT_BYTES, MAX_WALL_POST_UPLOAD_BYTES, WallLinkCtx,+ MAX_WALL_MESSAGE_CIPHER_DECODED_BYTES, MAX_WALL_MESSAGE_PAYLOAD_BYTES,+ MAX_WALL_MESSAGE_TEXT_BYTES, MAX_WALL_MESSAGE_TEXT_CHARS, MAX_WALL_POST_PLAINTEXT_BYTES,+ MAX_WALL_POST_UPLOAD_BYTES, WallLinkCtx,};pub use error::{Result, WallError};pub use models::{diff --git a/server/wall/controller/messages.go b/server/wall/controller/messages.goindex 44d3607929..5862f90cff 100644--- a/server/wall/controller/messages.go+++ b/server/wall/controller/messages.go@@ -2,6 +2,7 @@ package controllerimport ("database/sql"+ "encoding/base64""errors""strconv""strings"@@ -16,6 +17,11 @@ import (const (wallMessageKindRegular = "regular"wallMessageKindPostReply = "post_reply"++ maxWallMessageCipherEncodedBytes = 8 * 1024+ maxWallMessageCipherDecodedBytes = 6 * 1024+ maxWallMessageKeyEncodedBytes = 1024+ maxWallMessageKeyDecodedBytes = 768)type MessagesController struct {@@ -265,6 +271,30 @@ func validateCreateMessageRequest(req models.CreateMessageRequest) error {strings.TrimSpace(req.RecipientEncryptedMessageKey) == "" {return ente.NewBadRequestWithMessage("messageCipher and encrypted message keys are required")}+ if err := validateEncodedWallMessageField("messageCipher", req.MessageCipher, maxWallMessageCipherEncodedBytes, maxWallMessageCipherDecodedBytes); err != nil {+ return err+ }+ if err := validateEncodedWallMessageField("senderEncryptedMessageKey", req.SenderEncryptedMessageKey, maxWallMessageKeyEncodedBytes, maxWallMessageKeyDecodedBytes); err != nil {+ return err+ }+ if err := validateEncodedWallMessageField("recipientEncryptedMessageKey", req.RecipientEncryptedMessageKey, maxWallMessageKeyEncodedBytes, maxWallMessageKeyDecodedBytes); err != nil {+ return err+ }+ return nil+}++func validateEncodedWallMessageField(field string, value string, maxEncodedBytes int, maxDecodedBytes int) error {+ trimmed := strings.TrimSpace(value)+ if len(trimmed) > maxEncodedBytes {+ return ente.NewBadRequestWithMessage(field + " is too large")+ }+ decoded, err := base64.StdEncoding.DecodeString(trimmed)+ if err != nil || len(decoded) == 0 {+ return ente.NewBadRequestWithMessage(field + " must be valid base64")+ }+ if len(decoded) > maxDecodedBytes {+ return ente.NewBadRequestWithMessage(field + " is too large")+ }return nil}diff --git a/server/wall/controller/messages_test.go b/server/wall/controller/messages_test.goindex 24b727f6ad..42b03d210d 100644--- a/server/wall/controller/messages_test.go+++ b/server/wall/controller/messages_test.go@@ -2,6 +2,7 @@ package controllerimport ("context"+ "encoding/base64""errors""testing"@@ -38,17 +39,17 @@ func TestMessageReplyValidation(t *testing.T) {charlieMessage := createRepoMessage(t, repos, charlieID, charlieWall.WallID, aliceID, aliceWall.WallID, "")_, err := controller.Create(newWallControllerContext(aliceID), bobWall.WallID, models.CreateMessageRequest{- MessageCipher: "reply-cipher",- SenderEncryptedMessageKey: "reply-sender-key",- RecipientEncryptedMessageKey: "reply-recipient-key",+ MessageCipher: wallTestB64("reply-cipher"),+ SenderEncryptedMessageKey: wallTestB64("reply-sender-key"),+ RecipientEncryptedMessageKey: wallTestB64("reply-recipient-key"),ReplyMessageID: charlieMessage.MessageID,})require.Error(t, err)reply, err := controller.Create(newWallControllerContext(aliceID), bobWall.WallID, models.CreateMessageRequest{- MessageCipher: "reply-cipher",- SenderEncryptedMessageKey: "reply-sender-key",- RecipientEncryptedMessageKey: "reply-recipient-key",+ MessageCipher: wallTestB64("reply-cipher"),+ SenderEncryptedMessageKey: wallTestB64("reply-sender-key"),+ RecipientEncryptedMessageKey: wallTestB64("reply-recipient-key"),ReplyMessageID: bobMessage.MessageID,})require.NoError(t, err)@@ -57,9 +58,9 @@ func TestMessageReplyValidation(t *testing.T) {require.NoError(t, repos.Messages.DeleteMessage(ctx, bobMessage.MessageID, bobID))_, err = controller.Create(newWallControllerContext(aliceID), bobWall.WallID, models.CreateMessageRequest{- MessageCipher: "reply-after-delete-cipher",- SenderEncryptedMessageKey: "reply-after-delete-sender-key",- RecipientEncryptedMessageKey: "reply-after-delete-recipient-key",+ MessageCipher: wallTestB64("reply-after-delete-cipher"),+ SenderEncryptedMessageKey: wallTestB64("reply-after-delete-sender-key"),+ RecipientEncryptedMessageKey: wallTestB64("reply-after-delete-recipient-key"),ReplyMessageID: bobMessage.MessageID,})require.Error(t, err)@@ -95,6 +96,31 @@ func TestMessageLikeAndDeleteAccess(t *testing.T) {require.Contains(t, err.Error(), "cannot like a deleted message")}+func TestValidateCreateMessageRequestLimits(t *testing.T) {+ valid := models.CreateMessageRequest{+ MessageCipher: wallTestB64("cipher"),+ SenderEncryptedMessageKey: wallTestB64("sender-key"),+ RecipientEncryptedMessageKey: wallTestB64("recipient-key"),+ }+ require.NoError(t, validateCreateMessageRequest(valid))++ invalidBase64 := valid+ invalidBase64.MessageCipher = "not-base64"+ require.Error(t, validateCreateMessageRequest(invalidBase64))++ tooLargeCipher := valid+ tooLargeCipher.MessageCipher = base64.StdEncoding.EncodeToString(make([]byte, maxWallMessageCipherDecodedBytes+1))+ err := validateCreateMessageRequest(tooLargeCipher)+ require.Error(t, err)+ require.Contains(t, err.Error(), "messageCipher is too large")++ tooLargeKey := valid+ tooLargeKey.SenderEncryptedMessageKey = base64.StdEncoding.EncodeToString(make([]byte, maxWallMessageKeyDecodedBytes+1))+ err = validateCreateMessageRequest(tooLargeKey)+ require.Error(t, err)+ require.Contains(t, err.Error(), "senderEncryptedMessageKey is too large")+}+func createMessageControllerUserAndWall(t *testing.T, repos *wallrepo.Module, slug string, publicKey string) (int64, *wallrepo.WallRecord) {t.Helper()userID := insertWallControllerUser(t, repos, slug+"@example.com", publicKey)@@ -123,3 +149,7 @@ func createRepoMessage(t *testing.T, repos *wallrepo.Module, senderID int64, senrequire.NoError(t, err)return message}++func wallTestB64(value string) string {+ return base64.StdEncoding.EncodeToString([]byte(value))+}diff --git a/web/apps/social/src/components/SocialFileViewer.tsx b/web/apps/social/src/components/SocialFileViewer.tsxindex 39dfc96e3c..444dcf3c56 100644--- a/web/apps/social/src/components/SocialFileViewer.tsx+++ b/web/apps/social/src/components/SocialFileViewer.tsx@@ -23,6 +23,7 @@ import {formatSocialDate,initialsFor,} from "utils/socialDisplay";+import { clampSocialWallMessageText } from "utils/socialMessageLimits";const green = "#08C225";const paleGreen = "#E7F6E9";@@ -1311,7 +1312,11 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({disabled={isReplyActionRunning}onBlur={() => setIsReplyFocused(false)}onChange={(event) => {- setReplyText(event.target.value);+ const nextText = clampSocialWallMessageText(+ event.target.value,+ );+ event.currentTarget.value = nextText;+ setReplyText(nextText);resizeCaptionInput(event.currentTarget,replyInputMinHeight,diff --git a/web/apps/social/src/screens/MessagesScreen.tsx b/web/apps/social/src/screens/MessagesScreen.tsxindex d7773add58..15a6c00b06 100644--- a/web/apps/social/src/screens/MessagesScreen.tsx+++ b/web/apps/social/src/screens/MessagesScreen.tsx@@ -17,6 +17,7 @@ import type {SocialWallMessageConversation,} from "services/socialWall";import { firstNameFrom, initialsFor } from "utils/socialDisplay";+import { clampSocialWallMessageText } from "utils/socialMessageLimits";export const messagesBackground = "#FFFFFF";@@ -1457,7 +1458,12 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({component="textarea"aria-label={`Message ${selectedName}`}onChange={(event) => {- setMessageText(event.target.value);+ const nextText =+ clampSocialWallMessageText(+ event.target.value,+ );+ event.currentTarget.value = nextText;+ setMessageText(nextText);resizeComposer(event.currentTarget);}}onKeyDown={handleComposerKeyDown}diff --git a/web/apps/social/src/services/socialWall.ts b/web/apps/social/src/services/socialWall.tsindex 4f0cda666f..cdd40c7269 100644--- a/web/apps/social/src/services/socialWall.ts+++ b/web/apps/social/src/services/socialWall.ts@@ -6,6 +6,7 @@ import { loadEnteWasm } from "ente-wasm/load";import type { PendingSocialInvite } from "services/socialInvite";import { socialInviteURL } from "services/socialInvite";import { ensureCurrentWallContext } from "services/socialProfile";+import { normalizeSocialWallMessageText } from "utils/socialMessageLimits";interface WallAvatar {objectKey: string;@@ -748,20 +749,22 @@ export const loadCurrentPostLikers = async (postId: number) => {};export const replyToCurrentPost = async (postId: number, text: string) => {+ const messageText = normalizeSocialWallMessageText(text);const ctx = await ensureCurrentWallContext();try {- await ctx.reply_to_post(BigInt(postId), text.trim());+ await ctx.reply_to_post(BigInt(postId), messageText);} finally {ctx.free();}};export const sendCurrentMessage = async (wallId: string, text: string) => {+ const messageText = normalizeSocialWallMessageText(text);const ctx = await ensureCurrentWallContext();try {return await messageFromWallMessage(ctx,- (await ctx.send_message(wallId, text.trim())) as WallMessage,+ (await ctx.send_message(wallId, messageText)) as WallMessage,true,);} finally {@@ -774,6 +777,7 @@ export const replyToCurrentMessage = async (messageId: string,text: string,) => {+ const messageText = normalizeSocialWallMessageText(text);const ctx = await ensureCurrentWallContext();try {return await messageFromWallMessage(@@ -781,7 +785,7 @@ export const replyToCurrentMessage = async ((await ctx.reply_to_message(wallId,messageId,- text.trim(),+ messageText,)) as WallMessage,true,);diff --git a/web/apps/social/src/utils/socialMessageLimits.ts b/web/apps/social/src/utils/socialMessageLimits.tsnew file mode 100644index 0000000000..c2d54a4fe2--- /dev/null+++ b/web/apps/social/src/utils/socialMessageLimits.ts@@ -0,0 +1,14 @@+export const socialWallMessageTextMaxLength = 1000;++export const clampSocialWallMessageText = (text: string) =>+ Array.from(text).slice(0, socialWallMessageTextMaxLength).join("");++export const normalizeSocialWallMessageText = (text: string) => {+ const trimmed = text.trim();+ if (Array.from(trimmed).length > socialWallMessageTextMaxLength) {+ throw new Error(+ `Message must be ${socialWallMessageTextMaxLength} characters or less.`,+ );+ }+ return trimmed;+};