From c65361ba44d0724f22c98646452346a172b50364 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 18:22:43 -0800 Subject: [PATCH 1/2] proto: exercise IMAP budgets with small test limits --- crates/proto/src/imap/gmail_labels_tests.rs | 83 +++++++++++++++--- crates/proto/src/imap/limits_tests.rs | 96 ++++++++++++++++++--- crates/proto/src/imap/mod.rs | 57 +++++++++--- crates/proto/src/imap/status.rs | 2 +- 4 files changed, 202 insertions(+), 36 deletions(-) diff --git a/crates/proto/src/imap/gmail_labels_tests.rs b/crates/proto/src/imap/gmail_labels_tests.rs index 441e3220bf..c1437bf78e 100644 --- a/crates/proto/src/imap/gmail_labels_tests.rs +++ b/crates/proto/src/imap/gmail_labels_tests.rs @@ -18,6 +18,16 @@ fn owned(labels: &[&str]) -> Option> { Some(labels.iter().map(|l| l.to_string()).collect()) } +fn small_limits() -> Limits { + Limits { + responses: 1_000, + command_text: MAX_COMMAND_TEXT / 256, + fetch_text: MAX_FETCH_TEXT / 256, + flag_bytes: MAX_FLAG_BYTES / 256, + label_bytes: MAX_GMAIL_LABEL_BYTES / 256, + } +} + #[test] fn labels_come_with_the_flags() { let mut server = String::new(); @@ -165,22 +175,25 @@ fn tiny_labels_count_against_the_budget_too() { #[test] fn a_big_folders_listing_is_not_cut_short_for_its_size() { - // 300,000 messages with labels: more text than one command may otherwise bring (32 MiB). - let count: u32 = 300_000; + // The listing still exceeds an ordinary command's text cap, with every UID retained. + let limits = small_limits(); + let count: u32 = 1_200; let mut server = String::with_capacity(count as usize * 200); for uid in 1..=count { server += &format!( "* {uid} FETCH (FLAGS (\\Seen) UID {uid} X-GM-LABELS (\\Inbox \\Important \"Work/Clients and partners\" \"Receipts 2026\" \"Travel/Japan\"))\r\n" ); } - assert!(server.len() > MAX_COMMAND_TEXT); + assert!(server.len() > limits.command_text); server += "A0001 OK done\r\n"; let mut s = Script::new(server); - let mut imap = Imap::resume(&mut s); + let mut imap = Imap::resume_with_limits(&mut s, limits); imap.selected = Selected { exists: count, uid_validity: 1, uid_next: count + 1 }; - assert_eq!(imap.uid_fetch_flags_labels("1:*").map(|got| got.len()), Ok(count as usize)); + let got = imap.uid_fetch_flags_labels("1:*"); + assert_eq!(got.as_ref().map(|got| got.len()), Ok(count as usize)); + assert_eq!(got.unwrap().into_iter().map(|f| f.uid).collect::>(), (1..=count).collect::>()); // The room is the listing's alone: the next command has the usual cap again. - assert_eq!(imap.text_cap, MAX_COMMAND_TEXT); + assert_eq!(imap.text_cap, limits.command_text); } #[test] @@ -188,24 +201,30 @@ fn a_mailbox_claimed_huge_cant_fill_memory_with_flags() { // Any server (no Gmail here): ten million messages claimed, then message after message with // every flag it may have. The text it may send is capped, and so are the flags kept: the // listing fails, and never hands back messages that seem to have lost their flags. + assert_eq!(MAX_RESPONSES, 250_000); + assert_eq!(MAX_COMMAND_TEXT, 32 << 20); + assert_eq!(MAX_FETCH_TEXT, 256 << 20); + assert_eq!(MAX_FLAG_BYTES, 256 << 20); + assert_eq!(MAX_GMAIL_LABEL_BYTES, 32 << 20); + let limits = small_limits(); let flags: Vec = (0..MAX_FLAGS).map(|n| format!("f{n}")).collect(); let flags = flags.join(" "); let mut server = String::new(); let mut uid = 0u32; - while server.len() < MAX_FETCH_TEXT / 4 { + while server.len() < limits.fetch_text / 4 { uid += 1; server += &format!("* {uid} FETCH (UID {uid} FLAGS ({flags}))\r\n"); } server += "A0001 OK done\r\n"; let mut s = Script::new(server); - let mut imap = Imap::resume(&mut s); + let mut imap = Imap::resume_with_limits(&mut s, limits); imap.selected = Selected { exists: 10_000_000, uid_validity: 1, uid_next: 0 }; let got = imap.uid_fetch_flags("1:*"); assert!(matches!(&got, Err(ProtoError::Protocol(m)) if format!("{m:?}").contains("more flags")), "{:?}", got.as_ref().map(Vec::len)); - assert_eq!(imap.text_cap, MAX_COMMAND_TEXT); + assert_eq!(imap.text_cap, limits.command_text); // And what it may send at all stays within the ceiling, however many messages are claimed. - let mut s = Script::new(format!("* OK {}\r\n", "x".repeat(60_000)).repeat(MAX_FETCH_TEXT / 60_000 + 8)); - let mut imap = Imap::resume(&mut s); + let mut s = Script::new(format!("* OK {}\r\n", "x".repeat(60_000)).repeat(limits.fetch_text / 60_000 + 8)); + let mut imap = Imap::resume_with_limits(&mut s, limits); imap.selected = Selected { exists: u32::MAX, uid_validity: 1, uid_next: 0 }; assert!(matches!(imap.uid_fetch_flags("1:*"), Err(ProtoError::Protocol(_)))); } @@ -228,3 +247,45 @@ fn a_small_folders_listing_still_has_its_cap() { assert!(matches!(imap.uid_fetch_flags_labels("1:*"), Err(ProtoError::Protocol(_)))); assert_eq!(imap.text_cap, MAX_COMMAND_TEXT); } + +#[test] +fn flag_and_label_budgets_count_stored_bytes() { + // Flags are all-or-nothing; the entry and each String count, not only its characters. + for extra in [0, 1] { + let mut limits = small_limits(); + limits.flag_bytes = ENTRY_OVERHEAD + FLAG_OVERHEAD + 1; + let flag = "f".repeat(1 + extra); + let mut s = Script::new(format!("* 1 FETCH (UID 1 FLAGS ({flag}))\r\nA0001 OK done\r\n")); + { + let mut imap = Imap::resume_with_limits(&mut s, limits); + imap.selected = Selected { exists: 1, uid_validity: 1, uid_next: 2 }; + let got = imap.uid_fetch_flags("1:*"); + if extra == 0 { + assert_eq!(got.unwrap().into_iter().map(|f| (f.uid, f.flags)).collect::>(), [(1, vec!["f".to_string()])]); + } else { + assert!(matches!(got, Err(ProtoError::Protocol(m)) if m.to_string().contains("more flags"))); + } + assert_eq!(imap.response_cap, limits.responses); + assert_eq!(imap.text_cap, limits.command_text); + } + assert_eq!(s.sent(), "A0001 UID FETCH 1:* (UID FLAGS)\r\n"); + assert!(s.finished()); + } + // Labels have a soft budget: keep the exact fit, but leave an over-budget label unset. + for extra in [0, 1] { + let mut limits = small_limits(); + limits.label_bytes = LABEL_OVERHEAD + 1; + let label = "a".repeat(1 + extra); + let mut s = Script::new(format!("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS ({label}))\r\nA0001 OK done\r\n")); + { + let mut imap = Imap::resume_with_limits(&mut s, limits); + imap.selected = Selected { exists: 1, uid_validity: 1, uid_next: 2 }; + let got = imap.uid_fetch_flags_labels("1:*").unwrap(); + assert_eq!(got.into_iter().map(|f| (f.uid, f.gmail_labels)).collect::>(), [(1, if extra == 0 { owned(&["a"]) } else { None })]); + assert_eq!(imap.response_cap, limits.responses); + assert_eq!(imap.text_cap, limits.command_text); + } + assert_eq!(s.sent(), "A0001 UID FETCH 1:* (UID FLAGS X-GM-LABELS)\r\n"); + assert!(s.finished()); + } +} diff --git a/crates/proto/src/imap/limits_tests.rs b/crates/proto/src/imap/limits_tests.rs index 9b802055c0..8aec9f8017 100644 --- a/crates/proto/src/imap/limits_tests.rs +++ b/crates/proto/src/imap/limits_tests.rs @@ -14,6 +14,22 @@ fn opened(s: &mut Script, exists: u32, uid_next: u32) -> Imap<&mut Script> { imap } +fn small_limits() -> Limits { + Limits { + responses: 1_000, + command_text: MAX_COMMAND_TEXT / 256, + fetch_text: MAX_FETCH_TEXT / 256, + flag_bytes: MAX_FLAG_BYTES / 256, + label_bytes: MAX_GMAIL_LABEL_BYTES / 256, + } +} + +fn opened_with_limits(s: &mut Script, exists: u32, uid_next: u32, limits: Limits) -> Imap<&mut Script> { + let mut imap = Imap::resume_with_limits(s, limits); + imap.selected = Selected { exists, uid_validity: 1, uid_next }; + imap +} + /// `lines` lines made by `line(n)`. fn flood(lines: usize, line: impl Fn(usize) -> String) -> String { (0..lines).map(line).collect() @@ -25,16 +41,17 @@ fn padding() -> String { #[test] fn a_flood_of_long_lines_ends_the_command() { + let limits = small_limits(); let pad = padding(); - // 600 lines of 60 KB are more than the 32 MB one command may bring. - let server = flood(600, |n| format!("* {n} FETCH (UID {} FLAGS ({pad}))\r\n", n + 1)) + "A0001 OK done\r\n"; + // Three lines of 60 KiB exceed the small command floor, below the per-line cap. + let server = flood(3, |n| format!("* {n} FETCH (UID {} FLAGS ({pad}))\r\n", n + 1)) + "A0001 OK done\r\n"; let mut s = Script::new(server); - let err = opened(&mut s, 1000, 2000).uid_fetch_flags("1:*").unwrap_err(); + let err = opened_with_limits(&mut s, 10, 20, limits).uid_fetch_flags("1:*").unwrap_err(); assert!(matches!(err, ProtoError::Protocol(ref m) if m.to_string().contains("too much")), "{err:?}"); // The same in a list. - let server = flood(600, |n| format!("* LIST () \"/\" \"{n}{pad}\"\r\n")) + "A0001 OK done\r\n"; + let server = flood(3, |n| format!("* LIST () \"/\" \"{n}{pad}\"\r\n")) + "A0001 OK done\r\n"; let mut s = Script::new(server); - assert!(matches!(opened(&mut s, 0, 0).list(), Err(ProtoError::Protocol(_)))); + assert!(matches!(opened_with_limits(&mut s, 0, 0, limits).list(), Err(ProtoError::Protocol(_)))); } #[test] @@ -177,19 +194,38 @@ proptest! { #[test] fn a_folder_with_more_messages_than_other_commands_may_answer_still_reads() { - let exists = 300_000u32; + let limits = small_limits(); + let exists = 1_200u32; let lines = |n: u32| flood(n as usize, |i| format!("* {i} FETCH (UID {} FLAGS ())\r\n", i + 1)) + "A0001 OK done\r\n"; let mut s = Script::new(lines(exists)); - assert_eq!(opened(&mut s, exists, exists + 1).uid_fetch_flags("1:*").unwrap().len(), exists as usize); + let mut imap = opened_with_limits(&mut s, exists, exists + 1, limits); + assert_eq!(imap.uid_fetch_flags("1:*").unwrap().len(), exists as usize); + assert_eq!(imap.response_cap, limits.responses); let sizes = flood(exists as usize, |i| format!("* {i} FETCH (UID {} RFC822.SIZE 1)\r\n", i + 1)) + "A0001 OK done\r\n"; let mut s = Script::new(sizes); - assert_eq!(opened(&mut s, exists, exists + 1).uid_fetch_sizes("1:*").unwrap().len(), exists as usize); + let mut imap = opened_with_limits(&mut s, exists, exists + 1, limits); + assert_eq!(imap.uid_fetch_sizes("1:*").unwrap().len(), exists as usize); + assert_eq!(imap.response_cap, limits.responses); // Responses that are not messages still end at the cap for that folder, and the next command is back to the usual one. let noise = "* OK still here\r\n".repeat(2 * exists as usize + FETCH_SLACK + 1) + "A0001 OK done\r\n"; let mut s = Script::new(noise); - let mut imap = opened(&mut s, exists, exists + 1); + let mut imap = opened_with_limits(&mut s, exists, exists + 1, limits); assert!(matches!(imap.uid_fetch_flags("1:*"), Err(ProtoError::Protocol(_)))); - assert_eq!(imap.response_cap, MAX_RESPONSES); + assert_eq!(imap.response_cap, limits.responses); + // The tagged answer itself consumes one response: N-1 noise lines plus that answer fit. + let cap = 2 * exists as usize + FETCH_SLACK; + for extra in [0, 1] { + let noise = "* OK still here\r\n".repeat(cap - 1 + extra) + "A0001 OK done\r\n"; + let mut s = Script::new(noise); + let mut imap = opened_with_limits(&mut s, exists, exists + 1, limits); + let got = imap.uid_fetch_sizes("1:*"); + if extra == 0 { + assert_eq!(got, Ok(Vec::new())); + } else { + assert!(matches!(got, Err(ProtoError::Protocol(m)) if m.to_string().contains("too many responses"))); + } + assert_eq!(imap.response_cap, limits.responses); + } } #[test] @@ -213,3 +249,43 @@ fn brackets_in_flag_keywords_do_not_consume_body_sections() { assert_eq!(opened(&mut s, 1, 4).uid_fetch_message(3).unwrap().unwrap().body, Some(b"ok".to_vec())); } } + +#[test] +fn command_text_budget_counts_exact_bytes() { + // Every byte outside literals counts, including each CRLF and the final tagged answer. + let transcript = |bytes: usize| { + let done = "A0001 OK done\r\n"; + let mut left = bytes - done.len(); + let mut server = String::new(); + while left > MAX_LINE { + let line = format!("* OK {}\r\n", "x".repeat(60 * 1024)); + left -= line.len(); + server += &line; + } + assert!(left >= 7); + server += &format!("* OK {}\r\n", "x".repeat(left - 7)); + server += done; + assert_eq!(server.len(), bytes); + server + }; + let limits = small_limits(); + // LIST and a small FETCH use the command floor; a huge claimed mailbox uses the ceiling. + for (list, exists, cap) in [(true, 0, limits.command_text), (false, 10, limits.command_text), (false, u32::MAX, limits.fetch_text)] { + for extra in [0, 1] { + let mut s = Script::new(transcript(cap + extra)); + { + let mut imap = opened_with_limits(&mut s, exists, 0, limits); + let got = if list { imap.list().map(|got| got.len()) } else { imap.uid_fetch_flags("1:*").map(|got| got.len()) }; + if extra == 0 { + assert_eq!(got, Ok(0)); + } else { + assert!(matches!(got, Err(ProtoError::Protocol(m)) if m.to_string().contains("too much"))); + } + assert_eq!(imap.response_cap, limits.responses); + assert_eq!(imap.text_cap, limits.command_text); + } + assert_eq!(s.sent(), if list { "A0001 LIST \"\" \"*\"\r\n" } else { "A0001 UID FETCH 1:* (UID FLAGS)\r\n" }); + assert!(s.finished()); + } + } +} diff --git a/crates/proto/src/imap/mod.rs b/crates/proto/src/imap/mod.rs index d469bffcc0..2649cb0ebe 100644 --- a/crates/proto/src/imap/mod.rs +++ b/crates/proto/src/imap/mod.rs @@ -102,9 +102,32 @@ const MAX_FOUND: usize = 1_000; /// in: as many as fit the longest line read, at the longest a UID is written. pub const MAX_GMAIL_FOUND: usize = 5_000; +/// Budgets shared by the commands of one session. Public constructors use the production caps. +#[derive(Clone, Copy)] +struct Limits { + responses: usize, + command_text: usize, + fetch_text: usize, + flag_bytes: usize, + label_bytes: usize, +} + +impl Default for Limits { + fn default() -> Self { + Self { + responses: MAX_RESPONSES, + command_text: MAX_COMMAND_TEXT, + fetch_text: MAX_FETCH_TEXT, + flag_bytes: MAX_FLAG_BYTES, + label_bytes: MAX_GMAIL_LABEL_BYTES, + } + } +} + /// An IMAP session on a stream. pub struct Imap { wire: Wire, + limits: Limits, /// The number in the next command's tag. next_tag: u32, secrets: Secrets, @@ -470,8 +493,8 @@ impl Wanted { /// Most responses a fetch of this mailbox may bring: one for each message it may report, but /// never fewer than any other command. - fn responses(&self) -> usize { - self.cap.max(MAX_RESPONSES) + fn responses(&self, minimum: usize) -> usize { + self.cap.max(minimum) } fn wants(&self, uid: u32) -> bool { @@ -678,8 +701,13 @@ impl Imap { /// Continue on a stream that already greeted (after the caller wrapped it in TLS). pub fn resume(stream: S) -> Self { + Self::resume_with_limits(stream, Limits::default()) + } + + fn resume_with_limits(stream: S, limits: Limits) -> Self { Imap { wire: Wire::new(stream), + limits, next_tag: 1, secrets: Secrets::default(), capabilities: None, @@ -689,8 +717,8 @@ impl Imap { appended: Vec::new(), leaving: false, text_seen: 0, - response_cap: MAX_RESPONSES, - text_cap: MAX_COMMAND_TEXT, + response_cap: limits.responses, + text_cap: limits.command_text, skip_long: false, skipped: false, idle_tag: None, @@ -884,6 +912,7 @@ impl Imap { fn fetch_flags(&mut self, set: &str, ids: bool, labels_wanted: bool) -> Result, ProtoError> { type FetchedFlags = (Vec, Option, Option>); + let limits = self.limits; let mut found: BTreeMap = BTreeMap::new(); // The bytes of labels and of flags kept so far, all messages together. let mut label_bytes = 0usize; @@ -896,12 +925,12 @@ impl Imap { }; let command = Self::fetch(set, items)?; let mut wanted = Wanted::new(set, &self.selected).ok_or_else(|| ProtoError::Protocol(said!("not a set of messages")))?; - self.response_cap = wanted.responses(); + self.response_cap = wanted.responses(self.limits.responses); let claimed = usize::try_from(self.selected.exists).unwrap_or(usize::MAX); - self.text_cap = claimed.saturating_mul(FETCH_TEXT_PER_MESSAGE).clamp(MAX_COMMAND_TEXT, MAX_FETCH_TEXT); + self.text_cap = claimed.saturating_mul(FETCH_TEXT_PER_MESSAGE).clamp(limits.command_text, limits.fetch_text); let answered = self.run(command, &mut |values| { // A response with a UID shows the message is there, even one that forgot the flags. - if flag_bytes <= MAX_FLAG_BYTES + if flag_bytes <= limits.flag_bytes && let Some(item) = Item::from(values) && wanted.wants(item.uid) && (found.contains_key(&item.uid) || wanted.room(found.len())) @@ -911,7 +940,7 @@ impl Imap { let size = item.flags.iter().flatten().map(|flag| flag.len().saturating_add(FLAG_OVERHEAD)).sum::(); let entry = if found.contains_key(&item.uid) { 0 } else { ENTRY_OVERHEAD }; flag_bytes = flag_bytes.saturating_add(size).saturating_add(entry); - if flag_bytes > MAX_FLAG_BYTES { + if flag_bytes > limits.flag_bytes { return; } let (flags, id, labels) = found.entry(item.uid).or_default(); @@ -924,17 +953,17 @@ impl Imap { } if labels_wanted && let Some(later) = item.gmail_labels { let size = later.iter().map(|label| label.len().saturating_add(LABEL_OVERHEAD)).sum::(); - if label_bytes.saturating_add(size) <= MAX_GMAIL_LABEL_BYTES { + if label_bytes.saturating_add(size) <= limits.label_bytes { label_bytes = label_bytes.saturating_add(size); *labels = Some(later); } } } }); - self.response_cap = MAX_RESPONSES; - self.text_cap = MAX_COMMAND_TEXT; + self.response_cap = limits.responses; + self.text_cap = limits.command_text; answered?; - if flag_bytes > MAX_FLAG_BYTES { + if flag_bytes > limits.flag_bytes { return Err(ProtoError::Protocol(said!("more flags than one listing keeps"))); } wanted.check()?; @@ -949,7 +978,7 @@ impl Imap { let mut out: Vec<(u32, u64)> = Vec::new(); let command = Self::fetch(set, "(UID RFC822.SIZE)")?; let mut wanted = Wanted::new(set, &self.selected).ok_or_else(|| ProtoError::Protocol(said!("not a set of messages")))?; - self.response_cap = wanted.responses(); + self.response_cap = wanted.responses(self.limits.responses); let answered = self.run(command, &mut |values| { if let Some(Item { uid, size: Some(size), .. }) = Item::from(values) && wanted.wants(uid) @@ -958,7 +987,7 @@ impl Imap { out.push((uid, size)); } }); - self.response_cap = MAX_RESPONSES; + self.response_cap = self.limits.responses; answered?; wanted.check()?; out.sort_by_key(|(uid, _)| *uid); diff --git a/crates/proto/src/imap/status.rs b/crates/proto/src/imap/status.rs index 3c378308a3..7d998f8a84 100644 --- a/crates/proto/src/imap/status.rs +++ b/crates/proto/src/imap/status.rs @@ -144,7 +144,7 @@ impl Imap { self.note_status(&line); } Response::Data(values) => { - if self.text_seen > MAX_COMMAND_TEXT { + if self.text_seen > self.limits.command_text { return Err(ProtoError::Protocol(said!("the server sent too much in answer to one command"))); } self.note_data(&values); From c63da66850d6a9830328de4fd735c7301bd23b70 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 18:25:49 -0800 Subject: [PATCH 2/2] proto: remove obsolete command-limit import --- crates/proto/src/imap/status.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/proto/src/imap/status.rs b/crates/proto/src/imap/status.rs index 7d998f8a84..74251040c9 100644 --- a/crates/proto/src/imap/status.rs +++ b/crates/proto/src/imap/status.rs @@ -8,7 +8,7 @@ use std::io::{Read, Write}; use super::parse::{Status, Value}; -use super::{Command, Imap, MAX_COMMAND_TEXT, MAX_QUOTED, Part, Response}; +use super::{Command, Imap, MAX_QUOTED, Part, Response}; use crate::i18n::said; use crate::{ProtoError, for_trace};