Cotton code
392 lines · 20.9 KB · RustRaw
//! One sender's mail to Trash (src/mail/trash.rs), against a fake IMAP server on this machine's loopback and an//! object inside the test that keeps the outbox. Every address and message is invented; no real account is reached.mod support;use std::collections::BTreeMap;use std::io::{BufRead, BufReader, Write};use std::net::TcpListener;use std::sync::{Arc, Mutex};use cotton_mac::mail::acts::Helps;use cotton_mac::mail::client::{dial, ImapClient, ImapError, Server};use cotton_mac::mail::trash::{self, Drained, TrashError, BATCH};use cotton_mac::object::ObjectClient;use serde_json::{json, Value};/// No act here lands a page.fn no_erase(_: &[cotton_mac::mail::trash::GoneMail]) -> Result<usize, String> {    Ok(0)}fn no_land(_: &str, _: &[u8]) -> Result<Value, String> {    Err("unused".into())}use support::{Answer, TestServer};const SPAM: &str = "deals@shop.invented";/// A mailbox: its UIDVALIDITY, next UID, and messages as (uid, From line).#[derive(Clone)]struct Box_ {    validity: u32,    next: u32,    messages: Vec<(u32, String)>,}#[derive(Clone)]struct Fake {    gmail: bool,    can_move: bool,    boxes: BTreeMap<String, Box_>,    /// Drop the connection after this many MOVE/COPY commands (a Mac that stopped mid-move).    cut_after_moves: Option<usize>,}type Shared = Arc<Mutex<Fake>>;fn uids_of(set: &str) -> Vec<u32> {    set.split(',').filter_map(|u| u.parse().ok()).collect()}/// The fake: LOGIN, CAPABILITY, LIST (special use), EXAMINE, SELECT, UID SEARCH FROM, UID FETCH of the From header,/// UID MOVE and UID COPY, LOGOUT. Records every command but LOGIN's. Anything else, STORE and EXPUNGE included, is/// recorded and refused.fn imap(fake: Shared) -> (u16, Arc<Mutex<Vec<String>>>) {    let listener = TcpListener::bind("127.0.0.1:0").unwrap();    let port = listener.local_addr().unwrap().port();    let lines = Arc::new(Mutex::new(Vec::new()));    let recorded = Arc::clone(&lines);    std::thread::spawn(move || {        for stream in listener.incoming() {            let Ok(stream) = stream else { continue };            let fake = Arc::clone(&fake);            let recorded = Arc::clone(&recorded);            std::thread::spawn(move || {                let mut writer = stream.try_clone().unwrap();                let mut reader = BufReader::new(stream);                writer.write_all(b"* OK fake ready\r\n").unwrap();                let mut open: Option<(String, bool)> = None;                let mut moves = 0usize;                loop {                    let mut line = String::new();                    if reader.read_line(&mut line).unwrap_or(0) == 0 {                        return;                    }                    let line = line.trim_end().to_string();                    let (tag, rest) = line.split_once(' ').unwrap();                    let words: Vec<&str> = rest.split(' ').collect();                    if words[0] != "LOGIN" {                        recorded.lock().unwrap().push(rest.to_string());                    }                    let mut state = fake.lock().unwrap();                    let all = if state.gmail { "[Gmail]/All Mail" } else { "INBOX" }.to_string();                    let trash = if state.gmail { "[Gmail]/Trash" } else { "Deleted Items" }.to_string();                    let mut out = String::new();                    let named = |rest: &str| rest.split_once(' ').map(|(_, n)| n.trim_matches('"').to_string()).unwrap_or_default();                    match words[0] {                        "LOGIN" => out.push_str(&format!("{tag} OK signed in\r\n")),                        "CAPABILITY" => {                            let gm = if state.gmail { " X-GM-EXT-1" } else { "" };                            let mv = if state.can_move { " MOVE" } else { "" };                            out.push_str(&format!("* CAPABILITY IMAP4rev1 IDLE{gm}{mv}\r\n{tag} OK\r\n"));                        }                        "LIST" => {                            if state.gmail {                                out.push_str("* LIST (\\HasNoChildren \\All) \"/\" \"[Gmail]/All Mail\"\r\n");                            }                            out.push_str(&format!("* LIST (\\HasNoChildren) \"/\" \"INBOX\"\r\n* LIST (\\HasNoChildren \\Trash) \"/\" \"{trash}\"\r\n{tag} OK\r\n"));                        }                        "EXAMINE" | "SELECT" => {                            let name = named(rest);                            let held = state.boxes.entry(name.clone()).or_insert(Box_ { validity: 1, next: 1, messages: vec![] }).clone();                            open = Some((name, words[0] == "SELECT"));                            out.push_str(&format!(                                "* {} EXISTS\r\n* OK [UIDVALIDITY {}] v\r\n* OK [UIDNEXT {}] n\r\n{tag} OK [{}] done\r\n",                                held.messages.len(),                                held.validity,                                held.next,                                if words[0] == "SELECT" { "READ-WRITE" } else { "READ-ONLY" }                            ));                        }                        "UID" if words[1] == "SEARCH" && words[2] == "FROM" => {                            let wanted = words[3..].join(" ").trim_matches('"').to_lowercase();                            let held = &state.boxes[&open.as_ref().unwrap().0];                            // As a server does: any part of the From line.                            let found: Vec<String> = held.messages.iter().filter(|m| m.1.to_lowercase().contains(&wanted)).map(|m| m.0.to_string()).collect();                            out.push_str(&format!("* SEARCH {}\r\n{tag} OK\r\n", found.join(" ")));                        }                        "UID" if words[1] == "FETCH" && rest.contains("BODY.PEEK[HEADER.FIELDS (MESSAGE-ID)]") => {                            let held = &state.boxes[&open.as_ref().unwrap().0];                            for (n, uid) in uids_of(words[2]).into_iter().enumerate() {                                if !held.messages.iter().any(|m| m.0 == uid) {                                    continue;                                }                                let header = format!("Message-ID: <t{uid}@mail.invented>\r\n\r\n");                                let gm = if rest.contains("X-GM-MSGID") { format!("X-GM-MSGID {} ", 0x2000 + uid) } else { String::new() };                                out.push_str(&format!("* {} FETCH (UID {uid} {gm}BODY[HEADER.FIELDS (MESSAGE-ID)] {{{}}}\r\n{header})\r\n", n + 1, header.len()));                            }                            out.push_str(&format!("{tag} OK\r\n"));                        }                        "UID" if words[1] == "FETCH" && rest.contains("BODY.PEEK[HEADER.FIELDS (FROM)]") => {                            let held = &state.boxes[&open.as_ref().unwrap().0];                            for (n, uid) in uids_of(words[2]).into_iter().enumerate() {                                let Some((_, from)) = held.messages.iter().find(|m| m.0 == uid) else { continue };                                let header = format!("From: {from}\r\n\r\n");                                out.push_str(&format!("* {} FETCH (UID {uid} BODY[HEADER.FIELDS (FROM)] {{{}}}\r\n{header})\r\n", n + 1, header.len()));                            }                            out.push_str(&format!("{tag} OK\r\n"));                        }                        "UID" if (words[1] == "MOVE" && state.can_move) || words[1] == "COPY" => {                            let (from, writable) = open.clone().unwrap();                            assert!(writable, "a move only from a SELECTed mailbox");                            let to = words[3..].join(" ").trim_matches('"').to_string();                            assert_eq!(to, trash, "mail moves to the account's Trash, nowhere else");                            if state.cut_after_moves == Some(moves) {                                return;                            }                            moves += 1;                            let wanted = uids_of(words[2]);                            let leaves = words[1] == "MOVE" || state.gmail;                            let source = state.boxes.get_mut(&from).unwrap();                            let taken: Vec<(u32, String)> = source.messages.iter().filter(|m| wanted.contains(&m.0)).cloned().collect();                            // MOVE leaves the source; on Gmail a COPY into Trash does too.                            if leaves {                                source.messages.retain(|m| !wanted.contains(&m.0));                            }                            let bin = state.boxes.entry(to).or_insert(Box_ { validity: 7, next: 1, messages: vec![] });                            for (_, from) in taken {                                let uid = bin.next;                                bin.next += 1;                                bin.messages.push((uid, from));                            }                            out.push_str(&format!("{tag} OK done\r\n"));                        }                        "LOGOUT" => {                            writer.write_all(format!("* BYE bye\r\n{tag} OK\r\n").as_bytes()).unwrap();                            return;                        }                        _ => out.push_str(&format!("{tag} BAD not here\r\n")),                    }                    let _ = all;                    drop(state);                    writer.write_all(out.as_bytes()).unwrap();                }            });        }    });    (port, lines)}/// A mailbox of `spam` messages from SPAM, mixed with mail from others: one whose address only contains SPAM's,/// and a person's.fn fake(gmail: bool, can_move: bool, spam: u32) -> Shared {    let mut messages = Vec::new();    let mut uid = 1;    for n in 0..spam {        messages.push((uid, if n % 2 == 0 { format!("Invented Shop <{SPAM}>") } else { SPAM.to_uppercase() }));        uid += 1;        if n % 50 == 0 {            messages.push((uid, "Not Them <no-deals@shop.invented>".to_string()));            uid += 1;            messages.push((uid, "Asha <asha@friend.invented>".to_string()));            uid += 1;        }    }    let name = if gmail { "[Gmail]/All Mail" } else { "INBOX" }.to_string();    Arc::new(Mutex::new(Fake { gmail, can_move, boxes: BTreeMap::from([(name, Box_ { validity: 42, next: uid, messages })]), cut_after_moves: None }))}fn connect(port: u16) -> Result<ImapClient, ImapError> {    let mut client = ImapClient::start(dial(&Server { host: "127.0.0.1".into(), port, tls: false })?)?;    client.login("owner@mail.invented", "app-pw")?;    Ok(client)}fn left(fake: &Shared, mailbox: &str) -> Vec<String> {    fake.lock().unwrap().boxes.get(mailbox).map(|b| b.messages.iter().map(|m| m.1.clone()).collect()).unwrap_or_default()}fn never_erased(lines: &[String]) {    for line in lines {        let verb = line.split(' ').nth(if line.starts_with("UID") { 1 } else { 0 }).unwrap_or_default();        assert!(!["STORE", "EXPUNGE", "DELETE"].contains(&verb), "never erased: {line}");    }}/// RULE (coordinator, 23 Nov 2026): a count first, of that exact address only, read only; then the move to the/// provider's Trash in batches, never an expunge; mail after the count is left.#[test]fn a_sender_is_counted_then_moved_to_gmail_trash_in_batches() {    let fake = fake(true, true, 450);    let (port, lines) = imap(Arc::clone(&fake));    let mut client = connect(port).unwrap();    let counted = trash::count(&mut client, " Deals@Shop.Invented ").unwrap();    assert_eq!((counted.mailbox.as_str(), counted.uids.len(), counted.uid_validity), ("[Gmail]/All Mail", 450, 42));    assert!(lines.lock().unwrap().iter().all(|l| !l.starts_with("SELECT") && !l.contains("MOVE")), "counting writes nothing");    // Mail from them after the count is not the owner's choice yet: it stays.    {        let mut state = fake.lock().unwrap();        let all = state.boxes.get_mut("[Gmail]/All Mail").unwrap();        let uid = all.next;        all.next += 1;        all.messages.push((uid, format!("Invented Shop <{SPAM}>")));    }    let mut seen = Vec::new();    let moved = trash::trash(&mut client, SPAM, counted.uid_validity, counted.uid_below, None, &mut |n| {        seen.push(n);        true    })    .unwrap();    assert_eq!(moved, 450);    assert_eq!(seen, vec![BATCH, 2 * BATCH, 450], "a progress after each batch");    let kept = left(&fake, "[Gmail]/All Mail");    assert_eq!(kept.iter().filter(|f| f.to_lowercase().contains(SPAM) && !f.contains("no-deals")).count(), 1, "only the mail after the count is left");    assert_eq!(kept.iter().filter(|f| f.contains("asha@") || f.contains("no-deals@")).count(), 18, "nobody else's mail moves");    assert_eq!(left(&fake, "[Gmail]/Trash").len(), 450);    let moves = lines.lock().unwrap().iter().filter(|l| l.starts_with("UID MOVE")).count();    assert_eq!(moves, 3);    never_erased(&lines.lock().unwrap());}#[test]fn gmail_without_move_copies_into_trash_and_another_server_without_move_is_refused() {    let gmail = fake(true, false, 3);    let (port, lines) = imap(Arc::clone(&gmail));    let mut client = connect(port).unwrap();    let counted = trash::count(&mut client, SPAM).unwrap();    assert_eq!(trash::trash(&mut client, SPAM, counted.uid_validity, counted.uid_below, None, &mut |_| true).unwrap(), 3);    assert!(lines.lock().unwrap().iter().any(|l| l.starts_with("UID COPY")));    assert_eq!(left(&gmail, "[Gmail]/Trash").len(), 3);    never_erased(&lines.lock().unwrap());    let other = fake(false, false, 3);    let (port, lines) = imap(Arc::clone(&other));    let mut client = connect(port).unwrap();    assert!(matches!(trash::count(&mut client, SPAM), Err(TrashError::CannotMove)));    assert_eq!(left(&other, "INBOX").len(), 3 + 2);    never_erased(&lines.lock().unwrap());    // MOVE on another server: its own Trash, from INBOX.    let moving = fake(false, true, 3);    let (port, _) = imap(Arc::clone(&moving));    let mut client = connect(port).unwrap();    let counted = trash::count(&mut client, SPAM).unwrap();    assert_eq!(trash::trash(&mut client, SPAM, counted.uid_validity, counted.uid_below, None, &mut |_| true).unwrap(), 3);    assert_eq!(left(&moving, "Deleted Items").len(), 3);}/// The object as the outbox needs it: `GET /v1/outbox?status=` and `/v1/act` updates.fn object(rows: Vec<Value>) -> (TestServer, Arc<Mutex<Vec<Value>>>) {    let held = Arc::new(Mutex::new(rows));    let shared = Arc::clone(&held);    let server = TestServer::start(move |request| {        let mut rows = shared.lock().unwrap();        if let Some(status) = request.path.strip_prefix("/v1/outbox?status=") {            let found: Vec<Value> = rows.iter().filter(|r| r["status"] == status).cloned().collect();            return Answer::json(200, json!({ "rows": found }));        }        let body = request.json();        assert_eq!((body["act"].as_str(), body["args"]["table"].as_str()), (Some("update"), Some("outbox")));        let id = body["args"]["id"].as_str().unwrap();        let row = rows.iter_mut().find(|r| r["id"] == id).unwrap();        for (k, v) in body["args"]["data"].as_object().unwrap() {            row[k] = v.clone();        }        Answer::json(200, json!({ "version": 1, "changed": [] }))    });    (server, held)}/// No mail act here names a mail, and nothing unsubscribes.fn helps() -> Helps<'static> {    fn none(_: &str) -> Option<cotton_mac::mail::acts::Mail> {        None    }    fn no_post(_: &str) -> Result<(), String> {        Err("unused".into())    }    Helps { mail: &none, post: &no_post, listed: None, retry_failed: false, land_page: &no_land, erase: &no_erase }}fn row(rows: &Arc<Mutex<Vec<Value>>>, id: &str) -> Value {    rows.lock().unwrap().iter().find(|r| r["id"] == id).cloned().unwrap()}/// RULE: the phone asks through the outbox, as a WhatsApp send does: a count, then the move with what the count/// fixed; a run cut short leaves the move `sending`, and the next run goes on without moving anything twice.#[test]fn the_outbox_counts_then_moves_and_a_stopped_move_resumes() {    let fake = self::fake(true, true, 450);    let (port, lines) = imap(Arc::clone(&fake));    let (server, rows) = object(vec![        json!({ "id": "count-1", "channel": "mail", "kind": "sender_count", "to": SPAM, "status": "queued" }),        json!({ "id": "wa-1", "channel": "whatsapp", "to": "+15550000001", "body": "invented", "status": "queued" }),        json!({ "id": "other-account", "channel": "mail", "kind": "sender_count", "account": "someone@else.invented", "to": SPAM, "status": "queued" }),    ]);    let object = ObjectClient::new(server.url.clone(), Some("device-token".into())).unwrap();    let drained = trash::drain(&object, "Owner@Mail.Invented", &mut || connect(port), &helps()).unwrap();    assert_eq!(drained, Drained { counted: 1, ..Drained::default() });    let counted = row(&rows, "count-1");    assert_eq!((counted["status"].as_str(), counted["count"].as_u64(), counted["uid_validity"].as_u64()), (Some("sent"), Some(450), Some(42)));    assert_eq!(row(&rows, "wa-1")["status"], "queued", "a WhatsApp row is not mail's");    assert_eq!(row(&rows, "other-account")["status"], "queued", "another account's row waits for it");    assert!(left(&fake, "[Gmail]/Trash").is_empty(), "a count moves nothing");    // The owner saw 450 and said move them. The Mac stops after the first batch.    rows.lock().unwrap().push(json!({ "id": "trash-1", "channel": "mail", "kind": "sender_trash", "to": SPAM, "count": 450, "uid_validity": counted["uid_validity"], "uid_below": counted["uid_below"], "status": "queued" }));    fake.lock().unwrap().cut_after_moves = Some(1);    let drained = trash::drain(&object, "owner@mail.invented", &mut || connect(port), &helps()).unwrap();    assert_eq!(drained.trashed, 0);    let stopped = row(&rows, "trash-1");    assert_eq!((stopped["status"].as_str(), stopped["moved"].as_u64()), (Some("sending"), Some(BATCH as u64)));    assert_eq!(left(&fake, "[Gmail]/Trash").len(), BATCH);    fake.lock().unwrap().cut_after_moves = None;    let drained = trash::drain(&object, "owner@mail.invented", &mut || connect(port), &helps()).unwrap();    assert_eq!(drained, Drained { trashed: 1, ..Drained::default() });    let done = row(&rows, "trash-1");    assert_eq!((done["status"].as_str(), done["moved"].as_u64()), (Some("sent"), Some(450)));    assert_eq!(left(&fake, "[Gmail]/Trash").len(), 450, "nothing moved twice");    never_erased(&lines.lock().unwrap());    // ACTS-CHECK (24 Nov 2026): a move with no count of the Mac's (filed when Comms showed only what it holds) is    // counted first and his mail's count said; his Try again moves exactly that set. A count of no address fails.    {        let mut state = fake.lock().unwrap();        let all = state.boxes.get_mut("[Gmail]/All Mail").unwrap();        for _ in 0..3 {            let uid = all.next;            all.next += 1;            all.messages.push((uid, format!("Invented Shop <{SPAM}>")));        }    }    rows.lock().unwrap().push(json!({ "id": "trash-2", "channel": "mail", "kind": "sender_trash", "to": SPAM, "count": 3, "status": "queued" }));    rows.lock().unwrap().push(json!({ "id": "count-2", "channel": "mail", "kind": "sender_count", "to": "not an address", "status": "queued" }));    let drained = trash::drain(&object, "owner@mail.invented", &mut || connect(port), &helps()).unwrap();    assert_eq!(drained.failed, 2, "counted and said, nothing moved; and the count of no address");    assert_eq!(row(&rows, "trash-2")["error"], "Your mail holds 3 emails from them. Try again to move those 3 to Trash.");    assert_eq!(left(&fake, "[Gmail]/Trash").len(), 450);    {        let mut held = rows.lock().unwrap();        let again = held.iter_mut().find(|r| r["id"] == "trash-2").unwrap();        again["status"] = json!("queued");        again["error"] = Value::Null;    }    let drained = trash::drain(&object, "owner@mail.invented", &mut || connect(port), &helps()).unwrap();    assert_eq!(drained.trashed, 1);    let whole = row(&rows, "trash-2");    assert_eq!((whole["status"].as_str(), whole["moved"].as_u64(), whole["uid_validity"].as_u64()), (Some("sent"), Some(3), Some(42)), "the three that came since");    assert_eq!(whole["count"], 3, "his mail's count, the one he agreed to");    assert_eq!(left(&fake, "[Gmail]/Trash").len(), 453);    assert_eq!(row(&rows, "count-2")["error"], "\"not an address\" is not an email address.");    // Renumbered since the count: nothing moves.    let renumbered = self::fake(true, true, 2);    let (port, _) = imap(Arc::clone(&renumbered));    rows.lock().unwrap().push(json!({ "id": "trash-3", "channel": "mail", "kind": "sender_trash", "to": SPAM, "uid_validity": 41, "uid_below": 99, "status": "queued" }));    trash::drain(&object, "owner@mail.invented", &mut || connect(port), &helps()).unwrap();    assert_eq!(row(&rows, "trash-3")["error"], "The mailbox was renumbered since the count. Count again.");    assert!(left(&renumbered, "[Gmail]/Trash").is_empty());}