Cotton code
401 lines · 18.9 KB · RustRaw
//! The Mac's mail acts at their edges, tried from outside (agreed with mac-import on 24 Nov 2026://! mac-import owns src/mail/acts.rs and tests/mail_acts.rs, launch-ios this file). RFC 8058's one-click POST goes to//! a TLS server on this machine's loopback whose certificate only this test trusts (`add_root_certificate`, never//! `danger_accept_invalid_certs`); the sweep runs against a small fake IMAP server. Every address is invented; no//! real account or sender is reached.use std::io::{BufRead, BufReader, Read, Write};use std::net::{TcpListener, TcpStream};use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};use cotton_mac::mail::acts::{self, Mail};use cotton_mac::mail::client::{dial, ImapClient, Server};use cotton_mac::mail::tally::Tally;const SPAM: &str = "deals@shop.invented";const FRIEND: &str = "asha@mail.invented";const ACCOUNT: &str = "owner@mail.invented";// ---- List-Unsubscribe: which link is the one-click one ----fn offered(unsubscribe: &str) -> Mail {    Mail { list_unsubscribe: Some(unsubscribe.into()), list_unsubscribe_post: Some("List-Unsubscribe=One-Click".into()), ..Mail::default() }}/// RULE (RFC 8058): the one-click link is the header's https one, wherever it stands among the others.#[test]fn the_https_link_is_found_behind_the_others() {    let found = |header: &str| acts::one_click_link(&offered(header));    assert_eq!(found("<http://shop.invented/u/1>, <https://shop.invented/u/2>").as_deref(), Some("https://shop.invented/u/2"), "behind a plain http one");    assert_eq!(        found("<mailto:u@shop.invented?subject=out>, <http://shop.invented/u/1>, <https://shop.invented/u/3>").as_deref(),        Some("https://shop.invented/u/3"),        "third, behind mailto and http"    );    assert_eq!(found("<https://shop.invented/a>, <https://shop.invented/b>").as_deref(), Some("https://shop.invented/a"), "the first of two");    assert_eq!(found("<mailto:u@shop.invented>,\r\n <https://shop.invented/u/4>").as_deref(), Some("https://shop.invented/u/4"), "a folded header");    assert_eq!(found("<mailto:u@shop.invented>, <http://shop.invented/u/5>"), None, "no https link, no one-click");    assert_eq!(found("https://shop.invented/u/6"), None, "a link outside its angle brackets is not the header's");}// ---- The one-click POST over TLS ----/// What the loopback server answers one request: a status, headers, or no answer at all.#[derive(Clone)]enum Reply {    Status(u16),    Redirect(u16, String),    Silent,    Hang,}#[derive(Clone, Debug)]struct Seen {    method: String,    path: String,    headers: Vec<(String, String)>,    body: String,}struct Loopback {    port: u16,    root: reqwest::Certificate,    seen: Arc<Mutex<Vec<Seen>>>,}fn read_request<S: Read>(stream: &mut S) -> Option<Seen> {    let mut reader = BufReader::new(stream);    let mut first = String::new();    reader.read_line(&mut first).ok()?;    let mut parts = first.split_whitespace();    let (method, path) = (parts.next()?.to_string(), parts.next()?.to_string());    let mut headers = Vec::new();    loop {        let mut line = String::new();        reader.read_line(&mut line).ok()?;        let line = line.trim_end();        if line.is_empty() {            break;        }        let (k, v) = line.split_once(':')?;        headers.push((k.trim().to_ascii_lowercase(), v.trim().to_string()));    }    let length: usize = headers.iter().find(|(k, _)| k == "content-length").and_then(|(_, v)| v.parse().ok()).unwrap_or(0);    let mut body = vec![0; length];    reader.read_exact(&mut body).ok()?;    Some(Seen { method, path, headers, body: String::from_utf8_lossy(&body).into_owned() })}/// A TLS server on 127.0.0.1 with a certificate made for this run; `reply` answers each request by its path.fn loopback(reply: impl Fn(&str) -> Reply + Send + Sync + 'static) -> Loopback {    let made = rcgen::generate_simple_self_signed(vec!["127.0.0.1".to_string(), "localhost".to_string()]).unwrap();    let der = made.cert.der().clone();    let key = rustls::pki_types::PrivateKeyDer::Pkcs8(made.key_pair.serialize_der().into());    let config = rustls::ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))        .with_safe_default_protocol_versions()        .unwrap()        .with_no_client_auth()        .with_single_cert(vec![der.clone()], key)        .unwrap();    let config = Arc::new(config);    let listener = TcpListener::bind("127.0.0.1:0").unwrap();    let port = listener.local_addr().unwrap().port();    let seen = Arc::new(Mutex::new(Vec::new()));    let recorded = Arc::clone(&seen);    let reply = Arc::new(reply);    std::thread::spawn(move || {        for tcp in listener.incoming() {            let Ok(tcp) = tcp else { continue };            let (config, recorded, reply) = (Arc::clone(&config), Arc::clone(&recorded), Arc::clone(&reply));            std::thread::spawn(move || {                let connection = rustls::ServerConnection::new(config).unwrap();                let mut tls = rustls::StreamOwned::new(connection, tcp);                let Some(request) = read_request(&mut tls) else { return };                let path = request.path.clone();                recorded.lock().unwrap().push(request);                let answer = match reply(&path) {                    Reply::Status(code) => format!("HTTP/1.1 {code} X\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"),                    Reply::Redirect(code, to) => format!("HTTP/1.1 {code} X\r\nLocation: {to}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"),                    // The connection closes without a word.                    Reply::Silent => return,                    // Nothing is said for longer than the Mac waits.                    Reply::Hang => {                        std::thread::sleep(Duration::from_secs(40));                        return;                    }                };                let _ = tls.write_all(answer.as_bytes());                let _ = tls.flush();                tls.conn.send_close_notify();                let _ = tls.flush();            });        }    });    Loopback { port, root: reqwest::Certificate::from_der(&der).unwrap(), seen }}impl Loopback {    fn link(&self, path: &str) -> String {        format!("https://127.0.0.1:{}{path}", self.port)    }    /// The Mac's own POST, trusting only this server's certificate besides its usual roots.    fn post(&self, path: &str) -> Result<(), String> {        acts::post_one_click_with(reqwest::blocking::Client::builder().add_root_certificate(self.root.clone()), &self.link(path))    }    fn seen(&self) -> Vec<Seen> {        self.seen.lock().unwrap().clone()    }}/// A plain-http server that only records whether anything reached it.fn plain() -> (u16, Arc<Mutex<usize>>) {    let listener = TcpListener::bind("127.0.0.1:0").unwrap();    let port = listener.local_addr().unwrap().port();    let hits = Arc::new(Mutex::new(0));    let counted = Arc::clone(&hits);    std::thread::spawn(move || {        for tcp in listener.incoming() {            let Ok(mut tcp): Result<TcpStream, _> = tcp else { continue };            *counted.lock().unwrap() += 1;            let _ = read_request(&mut tcp);            let _ = tcp.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");        }    });    (port, hits)}/// RULE (RFC 8058): one POST of `List-Unsubscribe=One-Click`, form-encoded, carrying no cookie and nothing of his.#[test]fn the_one_click_post_is_one_bare_form() {    let server = loopback(|_| Reply::Status(200));    server.post("/u/1?list=winter").unwrap();    let seen = server.seen();    assert_eq!(seen.len(), 1, "one POST: {seen:?}");    let request = &seen[0];    assert_eq!((request.method.as_str(), request.path.as_str(), request.body.as_str()), ("POST", "/u/1?list=winter", "List-Unsubscribe=One-Click"));    let header = |name: &str| request.headers.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str());    assert_eq!(header("content-type"), Some("application/x-www-form-urlencoded"));    assert_eq!(header("cookie"), None, "no cookie");    assert_eq!(header("authorization"), None, "nothing of his");}/// RULE: a sender's server that refuses the POST is a refusal, whichever way it refuses, so `unsubscribe` falls back/// to Trash on arrival (tests/mail_acts.rs shows that fallback with a recorded closure; this is the real POST).#[test]fn a_refused_post_is_an_error_with_its_status() {    let server = loopback(|path| match path {        "/gone" => Reply::Status(410),        "/broken" => Reply::Status(500),        "/busy" => Reply::Status(503),        _ => Reply::Silent,    });    for (path, code) in [("/gone", "410"), ("/broken", "500"), ("/busy", "503")] {        let refused = server.post(path).expect_err(path);        assert!(refused.contains(code), "{path}: {refused}");    }    assert!(server.post("/hung-up").is_err(), "a connection closed without an answer");}/// RULE: the POST follows only a 307 or 308 (which keep it a POST), only to https, and stops after five.#[test]fn a_redirect_is_followed_only_to_https_and_at_most_five() {    let (plain_port, plain_hits) = plain();    let server = loopback(move |path| match path {        "/to-http" => Reply::Redirect(307, format!("http://127.0.0.1:{plain_port}/u")),        "/to-https" => Reply::Redirect(307, "/done".into()),        "/to-page" => Reply::Redirect(302, "/thanks".into()),        "/thanks" => Reply::Status(200),        "/done" => Reply::Status(200),        hop if hop.starts_with("/hop/") => {            let n: u32 = hop["/hop/".len()..].parse().unwrap();            Reply::Redirect(307, format!("/hop/{}", n + 1))        }        _ => Reply::Status(404),    });    assert!(server.post("/to-http").is_err(), "a redirect to plain http is refused");    assert_eq!(*plain_hits.lock().unwrap(), 0, "and nothing reached the plain server");    server.post("/to-https").unwrap();    let last = server.seen().into_iter().last().unwrap();    assert_eq!((last.path.as_str(), last.method.as_str(), last.body.as_str()), ("/done", "POST", "List-Unsubscribe=One-Click"), "a 307 to https is followed");    // A 302 would be followed as a GET with no body (FAKES AUDIT, a95f5a02af): a click not taken, and nothing asked.    let refused = server.post("/to-page").expect_err("a 302 is not a click taken");    assert!(refused.contains("not taken"), "{refused}");    assert!(server.seen().iter().all(|r| r.path != "/thanks"), "its page was never asked for");    let before = server.seen().len();    assert!(server.post("/hop/1").is_err(), "an endless chain of redirects is refused");    let hops = server.seen().len() - before;    assert!(hops <= 6, "at most the first request and five redirects: {hops}");}/// RULE: a sender's server that says nothing does not hold the Mac's run: the POST gives up within its wait.#[test]fn a_silent_server_is_given_up_on() {    let server = loopback(|_| Reply::Hang);    let started = Instant::now();    assert!(server.post("/u/1").is_err());    assert!(started.elapsed() < Duration::from_secs(35), "gave up after {:?}", started.elapsed());}// ---- Trash on arrival after the mailbox is renumbered ----#[derive(Clone)]struct Msg {    uid: u32,    from: String,}struct Mailbox {    validity: u32,    next: u32,    inbox: Vec<Msg>,    trash: Vec<Msg>,}type Shared = Arc<Mutex<Mailbox>>;/// A small IMAP server (not Gmail): INBOX and Deleted Items, enough for the sweep. It records every command.fn imap(mailbox: 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 (mailbox, recorded) = (Arc::clone(&mailbox), 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();                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();                    recorded.lock().unwrap().push(rest.to_string());                    let mut state = mailbox.lock().unwrap();                    let out = match words[0] {                        "LOGIN" => format!("{tag} OK signed in\r\n"),                        "CAPABILITY" => format!("* CAPABILITY IMAP4rev1 MOVE\r\n{tag} OK\r\n"),                        "LIST" => format!("* LIST (\\HasNoChildren) \"/\" \"INBOX\"\r\n* LIST (\\HasNoChildren \\Trash) \"/\" \"Deleted Items\"\r\n{tag} OK\r\n"),                        "EXAMINE" | "SELECT" => format!(                            "* {} EXISTS\r\n* OK [UIDVALIDITY {}] v\r\n* OK [UIDNEXT {}] n\r\n{tag} OK done\r\n",                            state.inbox.len(),                            state.validity,                            state.next                        ),                        "UID" if words[1] == "SEARCH" => {                            // `UID n:* FROM "x"` or `FROM "x"`.                            let (from, at) = if words[2] == "UID" { (words[3].split(':').next().unwrap().parse::<u32>().unwrap(), 4) } else { (1, 2) };                            assert_eq!(words[at], "FROM");                            let wanted = words[at + 1..].join(" ").trim_matches('"').to_lowercase();                            let found: Vec<String> =                                state.inbox.iter().filter(|m| m.uid >= from && m.from.contains(&wanted)).map(|m| m.uid.to_string()).collect();                            format!("* SEARCH {}\r\n{tag} OK\r\n", found.join(" "))                        }                        "UID" if words[1] == "FETCH" => {                            let mut out = String::new();                            for (n, uid) in words[2].split(',').filter_map(|u| u.parse::<u32>().ok()).enumerate() {                                let Some(m) = state.inbox.iter().find(|m| m.uid == uid) else { continue };                                let header = format!("From: {}\r\n\r\n", m.from);                                out.push_str(&format!("* {} FETCH (UID {uid} BODY[HEADER.FIELDS (FROM)] {{{}}}\r\n{header})\r\n", n + 1, header.len()));                            }                            out + &format!("{tag} OK\r\n")                        }                        "UID" if words[1] == "MOVE" => {                            assert_eq!(words[3..].join(" ").trim_matches('"'), "Deleted Items", "to Trash, nowhere else");                            let wanted: Vec<u32> = words[2].split(',').filter_map(|u| u.parse().ok()).collect();                            let taken: Vec<Msg> = state.inbox.iter().filter(|m| wanted.contains(&m.uid)).cloned().collect();                            state.inbox.retain(|m| !wanted.contains(&m.uid));                            state.trash.extend(taken);                            format!("{tag} OK done\r\n")                        }                        "LOGOUT" => {                            let _ = writer.write_all(format!("* BYE bye\r\n{tag} OK\r\n").as_bytes());                            return;                        }                        _ => format!("{tag} BAD not here\r\n"),                    };                    drop(state);                    writer.write_all(out.as_bytes()).unwrap();                }            });        }    });    (port, lines)}fn connect(port: u16) -> ImapClient {    let mut client = ImapClient::start(dial(&Server { host: "127.0.0.1".into(), port, tls: false }).unwrap()).unwrap();    client.login(ACCOUNT, "app-pw").unwrap();    client}fn from(uid: u32, who: &str) -> Msg {    Msg { uid, from: who.to_string() }}/// RULE: once the mailbox is renumbered (a new UIDVALIDITY), the sweep cannot tell what came before, so it moves/// nothing and starts the list again from the new next UID; mail that arrives after that goes to Trash as before.#[test]fn a_renumbered_mailbox_restarts_the_list_and_moves_nothing() {    let dir = tempfile::tempdir().unwrap();    let listed = Tally::open(&dir.path().join("mail.db")).unwrap();    // He unsubscribed while the mailbox was numbered 42, from UID 5 on.    listed.listen(ACCOUNT, SPAM, 42, 5).unwrap();    // The server has since renumbered: UIDVALIDITY 43, and their old mail now stands at low UIDs.    let mailbox = Arc::new(Mutex::new(Mailbox {        validity: 43,        next: 9,        inbox: vec![from(2, SPAM), from(5, SPAM), from(6, FRIEND), from(8, SPAM)],        trash: vec![],    }));    let (port, lines) = imap(Arc::clone(&mailbox));    let mut client = connect(port);    assert_eq!(acts::sweep(&mut client, &listed, ACCOUNT).unwrap(), 0, "nothing moves after a renumbering");    assert_eq!(mailbox.lock().unwrap().inbox.len(), 4);    assert_eq!(listed.listened(ACCOUNT).unwrap(), vec![(SPAM.to_string(), 43, 9)], "the list starts again at the new next UID");    // New mail from them, and from a friend, arrives after the renumbering.    {        let mut state = mailbox.lock().unwrap();        state.inbox.extend([from(9, SPAM), from(10, FRIEND)]);        state.next = 11;    }    assert_eq!(acts::sweep(&mut client, &listed, ACCOUNT).unwrap(), 1, "what arrives after is swept");    let state = mailbox.lock().unwrap();    assert_eq!(state.trash.iter().map(|m| m.uid).collect::<Vec<_>>(), [9]);    assert!(state.inbox.iter().any(|m| m.uid == 10), "a friend's mail stays");    assert!(state.inbox.iter().any(|m| m.uid == 8), "their mail from before the renumbering stays");    drop(state);    assert_eq!(listed.listened(ACCOUNT).unwrap(), vec![(SPAM.to_string(), 43, 11)]);    for line in lines.lock().unwrap().iter() {        assert!(!line.contains("\\Deleted") && !line.contains("EXPUNGE"), "never erased: {line}");    }}/// RULE: a sweep with nobody listed opens no mailbox at all.#[test]fn a_sweep_with_nobody_listed_touches_nothing() {    let dir = tempfile::tempdir().unwrap();    let listed = Tally::open(&dir.path().join("mail.db")).unwrap();    let mailbox = Arc::new(Mutex::new(Mailbox { validity: 1, next: 3, inbox: vec![from(1, SPAM), from(2, SPAM)], trash: vec![] }));    let (port, lines) = imap(Arc::clone(&mailbox));    let mut client = connect(port);    let before = lines.lock().unwrap().len();    assert_eq!(acts::sweep(&mut client, &listed, ACCOUNT).unwrap(), 0);    let after: Vec<String> = lines.lock().unwrap()[before..].to_vec();    assert!(after.iter().all(|l| !l.starts_with("SELECT") && !l.starts_with("UID")), "no mailbox opened: {after:?}");    assert_eq!(mailbox.lock().unwrap().inbox.len(), 2);}