mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-29 17:55:45 +01:00
Merge pull request #2750 from yoriswind/codex/2213-imap-test-caps
proto: exercise IMAP budgets with small private limits
This commit is contained in:
4 files changed
+262
-16
No files matched your search
@@ -236,3 +236,112 @@ 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);
|
||||
}
|
||||
|
||||
// Small private budgets exercise the real parser alongside the default-cap controls above.
|
||||
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 small_limits_a_big_folders_listing_is_not_cut_short_for_its_size() {
|
||||
// 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() > limits.command_text);
|
||||
server += "A0001 OK done\r\n";
|
||||
let mut s = Script::new(server);
|
||||
let mut imap = Imap::resume_with_limits(&mut s, limits);
|
||||
imap.selected = Selected { exists: count, uid_validity: 1, uid_next: count + 1 };
|
||||
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::<Vec<_>>(), (1..=count).collect::<Vec<_>>());
|
||||
// The room is the listing's alone: the next command has the usual cap again.
|
||||
assert_eq!(imap.text_cap, limits.command_text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_limits_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<String> = (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() < 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_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, 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(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(_))));
|
||||
}
|
||||
|
||||
#[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::<Vec<_>>(), [(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::<Vec<_>>(), [(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());
|
||||
}
|
||||
}
|
||||
@@ -222,3 +222,111 @@ 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()));
|
||||
}
|
||||
}
|
||||
|
||||
// Small private budgets exercise the real parser alongside the default-cap controls above.
|
||||
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
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_limits_a_flood_of_long_lines_ends_the_command() {
|
||||
let limits = small_limits();
|
||||
let pad = padding();
|
||||
// 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_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(3, |n| format!("* LIST () \"/\" \"{n}{pad}\"\r\n")) + "A0001 OK done\r\n";
|
||||
let mut s = Script::new(server);
|
||||
assert!(matches!(opened_with_limits(&mut s, 0, 0, limits).list(), Err(ProtoError::Protocol(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_limits_a_folder_with_more_messages_than_other_commands_may_answer_still_reads() {
|
||||
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));
|
||||
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);
|
||||
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_with_limits(&mut s, exists, exists + 1, limits);
|
||||
assert!(matches!(imap.uid_fetch_flags("1:*"), Err(ProtoError::Protocol(_))));
|
||||
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]
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<S> {
|
||||
wire: Wire<S>,
|
||||
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<S: Read + Write> Imap<S> {
|
||||
|
||||
/// 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<S: Read + Write> Imap<S> {
|
||||
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<S: Read + Write> Imap<S> {
|
||||
|
||||
fn fetch_flags(&mut self, set: &str, ids: bool, labels_wanted: bool) -> Result<Vec<Fetched>, ProtoError> {
|
||||
type FetchedFlags = (Vec<String>, Option<u64>, Option<Vec<String>>);
|
||||
let limits = self.limits;
|
||||
let mut found: BTreeMap<u32, FetchedFlags> = 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<S: Read + Write> Imap<S> {
|
||||
};
|
||||
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<S: Read + Write> Imap<S> {
|
||||
let size = item.flags.iter().flatten().map(|flag| flag.len().saturating_add(FLAG_OVERHEAD)).sum::<usize>();
|
||||
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<S: Read + Write> Imap<S> {
|
||||
}
|
||||
if labels_wanted && let Some(later) = item.gmail_labels {
|
||||
let size = later.iter().map(|label| label.len().saturating_add(LABEL_OVERHEAD)).sum::<usize>();
|
||||
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<S: Read + Write> Imap<S> {
|
||||
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<S: Read + Write> Imap<S> {
|
||||
out.push((uid, size));
|
||||
}
|
||||
});
|
||||
self.response_cap = MAX_RESPONSES;
|
||||
self.response_cap = self.limits.responses;
|
||||
answered?;
|
||||
wanted.check()?;
|
||||
out.sort_by_key(|(uid, _)| *uid);
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -144,7 +144,7 @@ impl<S: Read + Write> Imap<S> {
|
||||
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);
|
||||
|
||||
Reference in new issue
Block a user