C12.1: ely-mail-engine connects over IMAP, POP3 and SMTP

TLS or STARTTLS with the system trust store; password and XOAUTH2
logins keep the server's words on refusal. IMAP and POP3 are written
in the engine (imap-proto parses IMAP replies): async-imap dropped
NO/BAD on LIST and FETCH and lost BYE text, async-pop kept dot
stuffing and logged passwords. SMTP runs its own transaction with
RFC 5321 mailbox checks, full dot transparency, SMTPUTF8 and RSET.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
ZacharyZhang-NYandClaude Opus 5.5 committed 2026-10-19 16:53:53 -04:00
1 parent d7de5619a7
commit 9f47b94714
21 files changed
+2848 -20

No files matched your search

+168
View File
@@ -0,0 +1,168 @@
//! A scripted mail server over real TLS, for protocol tests.
#![allow(dead_code)]
use std::sync::Arc;
use ely_mail_engine::{Login, Secret, Security, Server, TlsConnector};
use rcgen::{CertificateParams, KeyPair};
use tokio::{
io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader},
net::TcpListener,
task::JoinHandle,
};
use tokio_rustls::{
TlsAcceptor,
rustls::{
ClientConfig, RootCertStore, ServerConfig,
crypto::ring,
pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
},
};
pub enum Step {
/// CRLF for `\n`; `{tag}` is the client's last tag.
Send(String),
/// One line; a leading `{tag} ` takes the client's tag.
Expect(String),
/// SMTP DATA lines before the lone dot.
Data(String),
StartTls,
}
pub fn send(text: &str) -> Step {
Step::Send(text.to_owned())
}
pub fn expect(text: &str) -> Step {
Step::Expect(text.to_owned())
}
trait Io: AsyncRead + AsyncWrite + Unpin + Send {}
impl<T: AsyncRead + AsyncWrite + Unpin + Send> Io for T {}
pub struct Certs {
acceptor: TlsAcceptor,
/// Trusts only this test certificate.
pub trusted: TlsConnector,
}
pub fn certs() -> Certs {
let key = KeyPair::generate().unwrap();
let cert = CertificateParams::new(vec!["127.0.0.1".into()])
.unwrap()
.self_signed(&key)
.unwrap();
let der = CertificateDer::from(cert.der().to_vec());
let provider = Arc::new(ring::default_provider());
let server = ServerConfig::builder_with_provider(provider.clone())
.with_safe_default_protocol_versions()
.unwrap()
.with_no_client_auth()
.with_single_cert(
vec![der.clone()],
PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.serialize_der())),
)
.unwrap();
let mut roots = RootCertStore::empty();
roots.add(der).unwrap();
let client = ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.unwrap()
.with_root_certificates(roots)
.with_no_client_auth();
Certs {
acceptor: TlsAcceptor::from(Arc::new(server)),
trusted: TlsConnector::from(Arc::new(client)),
}
}
pub fn login(secret: Secret) -> Login {
Login {
user: "ann@example.com".into(),
secret,
}
}
/// Serves one connection; the task fails on the first mismatch.
pub async fn serve(
certs: &Certs,
security: Security,
steps: Vec<Step>,
) -> (Server, JoinHandle<Result<(), String>>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let acceptor = certs.acceptor.clone();
let task = tokio::spawn(async move {
let (tcp, _) = listener.accept().await.map_err(|err| err.to_string())?;
let io: Box<dyn Io> = match security {
Security::Tls => Box::new(acceptor.accept(tcp).await.map_err(|e| e.to_string())?),
Security::StartTls => Box::new(tcp),
};
run(io, &acceptor, steps).await
});
let server = Server {
host: "127.0.0.1".into(),
port,
security,
};
(server, task)
}
async fn run(io: Box<dyn Io>, acceptor: &TlsAcceptor, steps: Vec<Step>) -> Result<(), String> {
let mut io = BufReader::new(io);
let mut tag = String::new();
for step in steps {
match step {
Step::Send(text) => {
let text = text.replace("{tag}", &tag).replace('\n', "\r\n");
io.write_all(text.as_bytes())
.await
.map_err(|e| e.to_string())?;
io.flush().await.map_err(|e| e.to_string())?;
}
Step::Expect(want) => {
let got = line(&mut io).await?;
let got = match want.strip_prefix("{tag} ") {
Some(_) => {
let (first, rest) = got.split_once(' ').unwrap_or((&got, ""));
tag = first.to_owned();
format!("{{tag}} {rest}")
}
None => got,
};
if got != want {
return Err(format!("expected {want:?}, got {got:?}"));
}
}
Step::Data(want) => {
let mut lines = Vec::new();
loop {
let got = line(&mut io).await?;
if got == "." {
break;
}
lines.push(got);
}
let got = lines.join("\n");
if got != want {
return Err(format!("expected data {want:?}, got {got:?}"));
}
}
Step::StartTls => {
let tcp = io.into_inner();
let tls = acceptor.accept(tcp).await.map_err(|e| e.to_string())?;
io = BufReader::new(Box::new(tls));
}
}
}
Ok(())
}
async fn line(io: &mut BufReader<Box<dyn Io>>) -> Result<String, String> {
let mut line = String::new();
io.read_line(&mut line).await.map_err(|e| e.to_string())?;
match line.strip_suffix("\r\n") {
Some(line) => Ok(line.to_owned()),
None => Err(format!("client sent {line:?} without CRLF")),
}
}
+404
View File
@@ -0,0 +1,404 @@
mod fake;
use base64::{Engine, engine::general_purpose::STANDARD};
use ely_mail_engine::{Error, Imap, Secret, Security, system_tls};
use fake::{certs, expect, login, send, serve};
use tokio::task::JoinHandle;
const TOKEN_LINE: &str = "user=ann@example.com\x01auth=Bearer tok-1\x01\x01";
#[tokio::test]
async fn a_password_login_lists_and_fetches() {
let certs = certs();
let lines = "Subject: Hi\n\nHello\n";
let body = lines.replace('\n', "\r\n");
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("* OK ready\n"),
expect("{tag} LOGIN \"ann@example.com\" \"pw 1\""),
send("{tag} OK done\n"),
expect("{tag} LIST \"\" *"),
send("* LIST (\\HasNoChildren) \"/\" INBOX\n"),
send("* LIST (\\HasNoChildren \\Sent) \"/\" \"Sent Mail\"\n"),
send("{tag} OK listed\n"),
expect("{tag} EXAMINE \"INBOX\""),
send("* 1 EXISTS\n* OK [UIDVALIDITY 7] v\n{tag} OK [READ-ONLY] in\n"),
expect("{tag} UID FETCH 42 BODY.PEEK[]"),
send(&format!(
"* 1 FETCH (UID 42 BODY[] {{{}}}\n{lines})\n{{tag}} OK fetched\n",
body.len()
)),
expect("{tag} LOGOUT"),
send("* BYE\n{tag} OK bye\n"),
],
)
.await;
let mut imap = Imap::connect(
&server,
&login(Secret::Password("pw 1".into())),
&certs.trusted,
)
.await
.unwrap();
assert_eq!(imap.mailboxes().await.unwrap(), ["INBOX", "Sent Mail"]);
let fetched = imap.fetch("INBOX", 42).await.unwrap().unwrap();
assert_eq!(String::from_utf8(fetched).unwrap(), body);
imap.logout().await.unwrap();
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn starttls_then_xoauth2() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::StartTls,
vec![
send("* OK ready\n"),
expect("{tag} STARTTLS"),
send("{tag} OK go\n"),
fake::Step::StartTls,
expect("{tag} AUTHENTICATE XOAUTH2"),
send("+ \n"),
expect(&STANDARD.encode(TOKEN_LINE)),
send("{tag} OK welcome\n"),
expect("{tag} LOGOUT"),
send("* BYE\n{tag} OK bye\n"),
],
)
.await;
let imap = Imap::connect(
&server,
&login(Secret::Token("tok-1".into())),
&certs.trusted,
)
.await
.unwrap();
imap.logout().await.unwrap();
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_refused_password_keeps_the_server_words() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("* OK ready\n"),
expect("{tag} LOGIN \"ann@example.com\" \"bad\""),
send("{tag} NO [AUTHENTICATIONFAILED] Invalid credentials\n"),
],
)
.await;
let err = Imap::connect(
&server,
&login(Secret::Password("bad".into())),
&certs.trusted,
)
.await
.err()
.unwrap();
assert!(
matches!(&err, Error::Rejected(text) if text.contains("Invalid credentials")),
"{err}"
);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_refused_token_answers_the_error_challenge_empty() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("* OK ready\n"),
expect("{tag} AUTHENTICATE XOAUTH2"),
send("+ \n"),
expect(&STANDARD.encode(TOKEN_LINE)),
send(&format!("+ {}\n", STANDARD.encode(r#"{"status":"401"}"#))),
expect(""),
send("{tag} NO [AUTHENTICATIONFAILED] Invalid token\n"),
],
)
.await;
let err = Imap::connect(
&server,
&login(Secret::Token("tok-1".into())),
&certs.trusted,
)
.await
.err()
.unwrap();
assert!(
matches!(&err, Error::Rejected(text) if text.contains("Invalid token")),
"{err}"
);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_missing_uid_is_none() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("* OK ready\n"),
expect("{tag} LOGIN \"ann@example.com\" \"pw\""),
send("{tag} OK done\n"),
expect("{tag} EXAMINE \"INBOX\""),
send("{tag} OK in\n"),
expect("{tag} UID FETCH 9 BODY.PEEK[]"),
send("{tag} OK nothing\n"),
],
)
.await;
let mut imap = Imap::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.unwrap();
assert_eq!(imap.fetch("INBOX", 9).await.unwrap(), None);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn an_unreadable_reply_is_a_protocol_error() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("* OK ready\n"),
expect("{tag} LOGIN \"ann@example.com\" \"pw\""),
send("{tag} OK done\n"),
expect("{tag} LIST \"\" *"),
send("* LIST (((\n"),
],
)
.await;
let mut imap = Imap::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.unwrap();
let err = imap.mailboxes().await.unwrap_err();
assert!(matches!(err, Error::Protocol(_)), "{err}");
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn the_system_store_refuses_an_unknown_certificate() {
let certs = certs();
let (server, _script) = serve(&certs, Security::Tls, vec![send("* OK ready\n")]).await;
let err = Imap::connect(
&server,
&login(Secret::Password("pw".into())),
&system_tls().unwrap(),
)
.await
.err()
.unwrap();
assert!(matches!(err, Error::Tls(_)), "{err}");
}
#[tokio::test]
async fn a_greeting_bye_keeps_the_server_words() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::Tls,
vec![send("* BYE [UNAVAILABLE] Maintenance in progress\n")],
)
.await;
let err = Imap::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.err()
.unwrap();
assert!(
matches!(&err, Error::Server(text) if text.contains("Maintenance in progress")),
"{err}"
);
script.await.unwrap().unwrap();
}
/// Greeting and LOGIN "pw", then `steps`.
async fn logged_in(steps: Vec<fake::Step>) -> (Imap, JoinHandle<Result<(), String>>) {
let certs = certs();
let mut script = vec![
send("* OK ready\n"),
expect("{tag} LOGIN \"ann@example.com\" \"pw\""),
send("{tag} OK done\n"),
];
script.extend(steps);
let (server, script) = serve(&certs, Security::Tls, script).await;
let imap = Imap::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.unwrap();
(imap, script)
}
#[tokio::test]
async fn listed_names_lose_quote_escapes_and_open_as_listed() {
let (mut imap, script) = logged_in(vec![
expect("{tag} LIST \"\" *"),
send("* LIST () \"/\" \"a\\\"b\"\n"),
send("* LIST () \"/\" \"c\\\\d\"\n"),
send("* LIST () \"/\" {3}\ne\\\"\n"),
send("{tag} OK listed\n"),
expect("{tag} EXAMINE \"a\\\"b\""),
send("{tag} OK in\n"),
expect("{tag} UID FETCH 9 BODY.PEEK[]"),
send("{tag} OK nothing\n"),
])
.await;
let names = imap.mailboxes().await.unwrap();
assert_eq!(names, ["a\"b", "c\\d", "e\\\""]);
assert_eq!(imap.fetch(&names[0], 9).await.unwrap(), None);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_refused_list_keeps_the_server_words() {
let (mut imap, script) = logged_in(vec![
expect("{tag} LIST \"\" *"),
send("* LIST () \"/\" INBOX\n"),
send("{tag} NO [UNAVAILABLE] Mailbox listing temporarily unavailable\n"),
])
.await;
let err = imap.mailboxes().await.unwrap_err();
assert!(
matches!(&err, Error::Server(text) if text.contains("listing temporarily unavailable")),
"{err}"
);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_refused_fetch_is_not_a_missing_uid() {
let (mut imap, script) = logged_in(vec![
expect("{tag} EXAMINE \"INBOX\""),
send("{tag} OK in\n"),
expect("{tag} UID FETCH 9 BODY.PEEK[]"),
send("{tag} NO [UNAVAILABLE] Message store temporarily unavailable\n"),
])
.await;
let err = imap.fetch("INBOX", 9).await.unwrap_err();
assert!(
matches!(&err, Error::Server(text) if text.contains("store temporarily unavailable")),
"{err}"
);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_bye_after_login_keeps_the_server_words() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("* OK ready\n"),
expect("{tag} LOGIN \"ann@example.com\" \"pw\""),
send("* BYE [UNAVAILABLE] Too many simultaneous connections\n"),
],
)
.await;
let err = Imap::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.err()
.unwrap();
assert!(
matches!(&err, Error::Server(text) if text.contains("Too many simultaneous connections")),
"{err}"
);
script.await.unwrap().unwrap();
let (mut imap, script) = logged_in(vec![
expect("{tag} LIST \"\" *"),
send("* BYE Shutting down\n"),
])
.await;
let err = imap.mailboxes().await.unwrap_err();
assert!(
matches!(&err, Error::Server(text) if text.contains("Shutting down")),
"{err}"
);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_password_beyond_ascii_goes_as_a_literal() {
let certs = certs();
let password = "pässwört";
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("* OK ready\n"),
expect(&format!(
"{{tag}} LOGIN \"ann@example.com\" {{{}}}",
password.len()
)),
send("+ go on\n"),
expect(password),
send("{tag} OK done\n"),
],
)
.await;
Imap::connect(
&server,
&login(Secret::Password(password.into())),
&certs.trusted,
)
.await
.unwrap();
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn bytes_before_tls_are_refused() {
let certs = certs();
let (server, _script) = serve(
&certs,
Security::StartTls,
vec![
send("* OK ready\n"),
expect("{tag} STARTTLS"),
send("{tag} OK go\n* OK injected\n"),
],
)
.await;
let err = Imap::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.err()
.unwrap();
assert!(
matches!(&err, Error::Protocol(text) if text.contains("before TLS")),
"{err}"
);
}
+226
View File
@@ -0,0 +1,226 @@
mod fake;
use base64::{Engine, engine::general_purpose::STANDARD};
use ely_mail_engine::{Error, Pop, Secret, Security};
use fake::{Step, certs, expect, login, send, serve};
const TOKEN_LINE: &str = "user=ann@example.com\x01auth=Bearer tok-1\x01\x01";
#[tokio::test]
async fn a_password_login_lists_uids_and_fetches() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("+OK ready\n"),
expect("USER ann@example.com"),
send("+OK\n"),
expect("PASS pw 1"),
send("+OK in\n"),
expect("UIDL"),
send("+OK\n1 aa1\n2 bb2\n.\n"),
expect("RETR 2"),
send("+OK 27 octets\nSubject: Hi\n\nHello\n..dot\n...\n.\n"),
expect("QUIT"),
send("+OK bye\n"),
],
)
.await;
let mut pop = Pop::connect(
&server,
&login(Secret::Password("pw 1".into())),
&certs.trusted,
)
.await
.unwrap();
assert_eq!(
pop.uids().await.unwrap(),
[(1, "aa1".to_owned()), (2, "bb2".to_owned())]
);
let message = String::from_utf8(pop.fetch(2).await.unwrap()).unwrap();
assert_eq!(message, "Subject: Hi\r\n\r\nHello\r\n.dot\r\n..\r\n");
pop.quit().await.unwrap();
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn stls_then_xoauth2_sends_the_token_after_the_plus() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::StartTls,
vec![
send("+OK ready\n"),
expect("STLS"),
send("+OK begin TLS\n"),
Step::StartTls,
expect("AUTH XOAUTH2"),
send("+ \n"),
expect(&STANDARD.encode(TOKEN_LINE)),
send("+OK in\n"),
expect("QUIT"),
send("+OK bye\n"),
],
)
.await;
let pop = Pop::connect(
&server,
&login(Secret::Token("tok-1".into())),
&certs.trusted,
)
.await
.unwrap();
pop.quit().await.unwrap();
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_refused_token_answers_the_error_challenge_empty() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("+OK ready\n"),
expect("AUTH XOAUTH2"),
send("+ \n"),
expect(&STANDARD.encode(TOKEN_LINE)),
send(&format!("+ {}\n", STANDARD.encode(r#"{"status":"401"}"#))),
expect(""),
send("-ERR Authentication failure: unknown user name or bad password.\n"),
],
)
.await;
let err = Pop::connect(
&server,
&login(Secret::Token("tok-1".into())),
&certs.trusted,
)
.await
.err()
.unwrap();
assert!(
matches!(&err, Error::Rejected(text) if text.contains("bad password")),
"{err}"
);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_refused_password_keeps_the_server_words() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("+OK ready\n"),
expect("USER ann@example.com"),
send("+OK\n"),
expect("PASS bad"),
send("-ERR [AUTH] Username and password not accepted.\n"),
],
)
.await;
let err = Pop::connect(
&server,
&login(Secret::Password("bad".into())),
&certs.trusted,
)
.await
.err()
.unwrap();
assert!(
matches!(&err, Error::Rejected(text) if text.contains("not accepted")),
"{err}"
);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_greeting_err_keeps_the_server_words() {
let certs = certs();
let (server, script) = serve(&certs, Security::Tls, vec![send("-ERR maildrop busy\n")]).await;
let err = Pop::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.err()
.unwrap();
assert!(
matches!(&err, Error::Server(text) if text == "maildrop busy"),
"{err}"
);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_connection_lost_before_the_pass_reply_is_an_error() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("+OK ready\n"),
expect("USER ann@example.com"),
send("+OK\n"),
expect("PASS pw"),
],
)
.await;
let err = Pop::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.err()
.unwrap();
assert!(matches!(&err, Error::Connect(_)), "{err}");
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn plain_bytes_after_stls_are_refused() {
let certs = certs();
let (server, _script) = serve(
&certs,
Security::StartTls,
vec![
send("+OK ready\n"),
expect("STLS"),
send("+OK begin TLS\nUIDL\n"),
],
)
.await;
let err = Pop::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.err()
.unwrap();
assert!(
matches!(&err, Error::Protocol(text) if text.contains("after STLS")),
"{err}"
);
}
#[tokio::test]
async fn a_line_break_in_the_login_never_leaves() {
let certs = certs();
let (server, script) = serve(&certs, Security::Tls, vec![send("+OK ready\n")]).await;
let err = Pop::connect(
&server,
&login(Secret::Password("pw\r\nDELE 1".into())),
&certs.trusted,
)
.await
.err()
.unwrap();
assert!(matches!(&err, Error::Invalid(_)), "{err}");
script.await.unwrap().unwrap();
}
@@ -0,0 +1,119 @@
//! The real logger at trace, around real protocol traffic.
mod fake;
use base64::{Engine, engine::general_purpose::STANDARD};
use ely_mail_engine::{Imap, Pop, Secret, Security, Smtp};
use ely_platform::AppId;
use fake::{Step, certs, expect, login, send, serve};
const PASSWORD: &str = "PRIVATE_PASSWORD";
const TOKEN: &str = "PRIVATE_TOKEN";
const BODY: &str = "PRIVATE_BODY";
#[tokio::test]
async fn trace_logs_keep_no_password_token_or_mail() {
let dir = tempfile::tempdir().unwrap();
// The only test here; no thread reads env.
unsafe { std::env::set_var("ELY_LOG", "trace") };
ely_platform::logging::init_in(AppId::Mail, dir.path()).unwrap();
let certs = certs();
let message = format!("Subject: x\n\n{BODY}\n");
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("* OK ready\n"),
expect(&format!("{{tag}} LOGIN \"ann@example.com\" \"{PASSWORD}\"")),
send("{tag} OK in\n"),
expect("{tag} EXAMINE \"INBOX\""),
send("{tag} OK done\n"),
expect("{tag} UID FETCH 7 BODY.PEEK[]"),
send(&format!(
"* 1 FETCH (UID 7 BODY[] {{{}}}\n{message})\n{{tag}} OK fetched\n",
message.replace('\n', "\r\n").len()
)),
],
)
.await;
let mut imap = Imap::connect(
&server,
&login(Secret::Password(PASSWORD.into())),
&certs.trusted,
)
.await
.unwrap();
assert!(imap.fetch("INBOX", 7).await.unwrap().is_some());
script.await.unwrap().unwrap();
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("+OK ready\n"),
expect("USER ann@example.com"),
send("+OK\n"),
expect(&format!("PASS {PASSWORD}")),
send("+OK in\n"),
expect("RETR 1"),
send(&format!("+OK\n{message}.\n")),
],
)
.await;
let mut pop = Pop::connect(
&server,
&login(Secret::Password(PASSWORD.into())),
&certs.trusted,
)
.await
.unwrap();
pop.fetch(1).await.unwrap();
script.await.unwrap().unwrap();
let initial = STANDARD.encode(format!(
"user=ann@example.com\x01auth=Bearer {TOKEN}\x01\x01"
));
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("220 mx ready\n"),
expect("EHLO [127.0.0.1]"),
send("250-mx\n250 AUTH XOAUTH2\n"),
expect(&format!("AUTH XOAUTH2 {initial}")),
send("235 ok\n"),
expect("MAIL FROM:<ann@example.com>"),
send("250 ok\n"),
expect("RCPT TO:<bo@example.com>"),
send("250 ok\n"),
expect("DATA"),
send("354 go\n"),
Step::Data(format!("Subject: x\n\n{BODY}")),
send("250 queued\n"),
],
)
.await;
let mut smtp = Smtp::connect(&server, &login(Secret::Token(TOKEN.into())), &certs.trusted)
.await
.unwrap();
smtp.send(
"ann@example.com",
&["bo@example.com".to_owned()],
message.replace('\n', "\r\n").as_bytes(),
)
.await
.unwrap();
script.await.unwrap().unwrap();
log::logger().flush();
let logged = std::fs::read_to_string(dir.path().join("ely.log")).unwrap();
for line in ["IMAP login", "POP3 login", "SMTP login"] {
assert!(logged.contains(line), "missing {line:?} in\n{logged}");
}
for secret in [PASSWORD, TOKEN, BODY, &initial] {
assert!(
!logged.contains(secret),
"{secret} reached the log:\n{logged}"
);
}
}
+458
View File
@@ -0,0 +1,458 @@
mod fake;
use base64::{Engine, engine::general_purpose::STANDARD};
use ely_mail_engine::{Error, Secret, Security, Smtp};
use fake::{Step, certs, expect, login, send, serve};
#[tokio::test]
async fn starttls_password_login_sends_one_message() {
let certs = certs();
let plain = STANDARD.encode("\0ann@example.com\0pw 1");
let (server, script) = serve(
&certs,
Security::StartTls,
vec![
send("220 mx ready\n"),
expect("EHLO [127.0.0.1]"),
send("250-mx\n250 STARTTLS\n"),
expect("STARTTLS"),
send("220 go\n"),
Step::StartTls,
expect("EHLO [127.0.0.1]"),
send("250-mx\n250 AUTH PLAIN\n"),
expect(&format!("AUTH PLAIN {plain}")),
send("235 ok\n"),
expect("MAIL FROM:<ann@example.com>"),
send("250 ok\n"),
expect("RCPT TO:<bo@example.com>"),
send("250 ok\n"),
expect("RCPT TO:<cy@example.com>"),
send("250 ok\n"),
expect("DATA"),
send("354 go\n"),
Step::Data("Subject: Hi\n\nHello\n..dot".into()),
send("250 queued as 7\n"),
expect("QUIT"),
send("221 bye\n"),
],
)
.await;
let mut smtp = Smtp::connect(
&server,
&login(Secret::Password("pw 1".into())),
&certs.trusted,
)
.await
.unwrap();
let to = ["bo@example.com".to_owned(), "cy@example.com".to_owned()];
smtp.send(
"ann@example.com",
&to,
b"Subject: Hi\r\n\r\nHello\r\n.dot\r\n",
)
.await
.unwrap();
smtp.quit().await.unwrap();
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn implicit_tls_xoauth2() {
let certs = certs();
let token = STANDARD.encode("user=ann@example.com\x01auth=Bearer tok-1\x01\x01");
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("220 mx ready\n"),
expect("EHLO [127.0.0.1]"),
send("250-mx\n250 AUTH XOAUTH2\n"),
expect(&format!("AUTH XOAUTH2 {token}")),
send("235 ok\n"),
],
)
.await;
Smtp::connect(
&server,
&login(Secret::Token("tok-1".into())),
&certs.trusted,
)
.await
.unwrap();
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_refused_password_keeps_the_server_words() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("220 mx ready\n"),
expect("EHLO [127.0.0.1]"),
send("250-mx\n250 AUTH PLAIN\n"),
expect(&format!(
"AUTH PLAIN {}",
STANDARD.encode("\0ann@example.com\0bad")
)),
send("535 5.7.8 Username and Password not accepted\n"),
],
)
.await;
let err = Smtp::connect(
&server,
&login(Secret::Password("bad".into())),
&certs.trusted,
)
.await
.err()
.unwrap();
assert!(
matches!(&err, Error::Rejected(text) if text.contains("535") && text.contains("not accepted")),
"{err}"
);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_server_without_starttls_is_refused() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::StartTls,
vec![
send("220 mx ready\n"),
expect("EHLO [127.0.0.1]"),
send("250-mx\n250 AUTH PLAIN\n"),
],
)
.await;
let err = Smtp::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.err()
.unwrap();
assert!(
matches!(&err, Error::Server(text) if text.contains("STARTTLS")),
"{err}"
);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_refused_recipient_keeps_the_server_words() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("220 mx ready\n"),
expect("EHLO [127.0.0.1]"),
send("250-mx\n250 AUTH PLAIN\n"),
expect(&format!(
"AUTH PLAIN {}",
STANDARD.encode("\0ann@example.com\0pw")
)),
send("235 ok\n"),
expect("MAIL FROM:<ann@example.com>"),
send("250 ok\n"),
expect("RCPT TO:<nobody@example.com>"),
send("550 5.1.1 No such user\n"),
expect("RSET"),
send("250 ok\n"),
expect("MAIL FROM:<ann@example.com>"),
send("250 ok\n"),
expect("RCPT TO:<bo@example.com>"),
send("250 ok\n"),
expect("DATA"),
send("354 go\n"),
Step::Data("x".into()),
send("250 queued\n"),
],
)
.await;
let mut smtp = Smtp::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.unwrap();
let err = smtp
.send(
"ann@example.com",
&["nobody@example.com".to_owned()],
b"x\r\n",
)
.await
.unwrap_err();
assert!(
matches!(&err, Error::Server(text) if text.contains("550") && text.contains("No such user")),
"{err}"
);
smtp.send("ann@example.com", &["bo@example.com".to_owned()], b"x\r\n")
.await
.unwrap();
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_refused_token_answers_the_error_challenge_empty() {
let certs = certs();
let token = STANDARD.encode("user=ann@example.com\x01auth=Bearer tok-1\x01\x01");
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("220 mx ready\n"),
expect("EHLO [127.0.0.1]"),
send("250-mx\n250 AUTH XOAUTH2\n"),
expect(&format!("AUTH XOAUTH2 {token}")),
send(&format!("334 {}\n", STANDARD.encode(r#"{"status":"400"}"#))),
expect(""),
send("535-5.7.8 Username and Password not accepted\n535 5.7.8 Learn more\n"),
],
)
.await;
let err = Smtp::connect(
&server,
&login(Secret::Token("tok-1".into())),
&certs.trusted,
)
.await
.err()
.unwrap();
assert!(
matches!(&err, Error::Rejected(text) if text.contains("535") && text.contains("not accepted")),
"{err}"
);
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn an_envelope_with_a_line_break_or_bracket_never_leaves() {
let certs = certs();
let (server, script) = serve(
&certs,
Security::Tls,
vec![
send("220 mx ready\n"),
expect("EHLO [127.0.0.1]"),
send("250-mx\n250 AUTH PLAIN\n"),
expect(&format!(
"AUTH PLAIN {}",
STANDARD.encode("\0ann@example.com\0pw")
)),
send("235 ok\n"),
expect("QUIT"),
send("221 bye\n"),
],
)
.await;
let mut smtp = Smtp::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.unwrap();
let bad = [
(
"ann@example.com",
"bo@example.com>\r\nRCPT TO:<hidden@example.com",
),
(
"ann@example.com>\r\nRCPT TO:<hidden@example.com",
"bo@example.com",
),
("ann@example.com", "bo @example.com"),
("ann@example.com", ""),
(
"ann@example.com",
"\"bo\r\nRCPT TO:<hidden@example.com>\"@example.com",
),
("ann@example.com", "\"bo@example.com"),
("ann@example.com", "bo@exa mple.com"),
];
for (from, to) in bad {
let err = smtp
.send(from, &[to.to_owned()], b"x\r\n")
.await
.unwrap_err();
assert!(matches!(&err, Error::Invalid(_)), "{err}");
}
let err = smtp
.send(
"ann@example.com",
&["bo@example.com".to_owned()],
b"a\n.b\r\n",
)
.await
.unwrap_err();
assert!(
matches!(&err, Error::Invalid(text) if text.contains("bare")),
"{err}"
);
smtp.quit().await.unwrap();
script.await.unwrap().unwrap();
}
async fn logged_in(
ehlo: &str,
steps: Vec<Step>,
) -> (Smtp, tokio::task::JoinHandle<Result<(), String>>) {
let certs = certs();
let mut script = vec![
send("220 mx ready\n"),
expect("EHLO [127.0.0.1]"),
send(ehlo),
expect(&format!(
"AUTH PLAIN {}",
STANDARD.encode("\0ann@example.com\0pw")
)),
send("235 ok\n"),
];
script.extend(steps);
let (server, script) = serve(&certs, Security::Tls, script).await;
let smtp = Smtp::connect(
&server,
&login(Secret::Password("pw".into())),
&certs.trusted,
)
.await
.unwrap();
(smtp, script)
}
/// MAIL, RCPT and DATA with the server agreeing.
fn transaction(mail: &str, rcpt: &str, data: &str) -> Vec<Step> {
vec![
expect(mail),
send("250 ok\n"),
expect(rcpt),
send("250 ok\n"),
expect("DATA"),
send("354 go\n"),
Step::Data(data.to_owned()),
send("250 queued\n"),
]
}
#[tokio::test]
async fn a_quoted_local_part_is_a_mailbox() {
let from = r#""ann \"a\" lee"@example.com"#;
let to = r#""bo smith"@[192.0.2.1]"#;
let (mut smtp, script) = logged_in(
"250-mx\n250 AUTH PLAIN\n",
transaction(
&format!("MAIL FROM:<{from}>"),
&format!("RCPT TO:<{to}>"),
"x",
),
)
.await;
smtp.send(from, &[to.to_owned()], b"x\r\n").await.unwrap();
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_dot_opening_the_first_line_is_stuffed() {
let (mut smtp, script) = logged_in(
"250-mx\n250 AUTH PLAIN\n",
transaction(
"MAIL FROM:<ann@example.com>",
"RCPT TO:<bo@example.com>",
"..X-Trace: yes\nSubject: x\n\n..\nend",
),
)
.await;
smtp.send(
"ann@example.com",
&["bo@example.com".to_owned()],
b".X-Trace: yes\r\nSubject: x\r\n\r\n.\r\nend",
)
.await
.unwrap();
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_utf8_header_needs_smtputf8() {
let message = "Subject: 您好\r\n\r\nhi\r\n";
let (mut smtp, script) = logged_in(
"250-mx\n250-SMTPUTF8\n250 AUTH PLAIN\n",
transaction(
"MAIL FROM:<ann@example.com> SMTPUTF8",
"RCPT TO:<bo@example.com>",
"Subject: 您好\n\nhi",
),
)
.await;
let to = ["bo@example.com".to_owned()];
smtp.send("ann@example.com", &to, message.as_bytes())
.await
.unwrap();
script.await.unwrap().unwrap();
let (mut smtp, script) = logged_in("250-mx\n250 AUTH PLAIN\n", vec![]).await;
let err = smtp
.send("ann@example.com", &to, message.as_bytes())
.await
.unwrap_err();
assert!(
matches!(&err, Error::Invalid(text) if text.contains("headers")),
"{err}"
);
script.await.unwrap().unwrap();
let (mut smtp, script) = logged_in(
"250-mx\n250 AUTH PLAIN\n",
transaction(
"MAIL FROM:<ann@example.com>",
"RCPT TO:<bo@example.com>",
"Subject: hi\n\n您好",
),
)
.await;
smtp.send(
"ann@example.com",
&to,
"Subject: hi\r\n\r\n您好\r\n".as_bytes(),
)
.await
.unwrap();
script.await.unwrap().unwrap();
}
#[tokio::test]
async fn a_utf8_address_needs_smtputf8() {
let to = "用户@例子.广告";
let (mut smtp, script) = logged_in(
"250-mx\n250-SMTPUTF8\n250 AUTH PLAIN\n",
transaction(
"MAIL FROM:<ann@example.com> SMTPUTF8",
&format!("RCPT TO:<{to}>"),
"x",
),
)
.await;
smtp.send("ann@example.com", &[to.to_owned()], b"x\r\n")
.await
.unwrap();
script.await.unwrap().unwrap();
let (mut smtp, script) = logged_in("250-mx\n250 AUTH PLAIN\n", vec![]).await;
let err = smtp
.send("ann@example.com", &[to.to_owned()], b"x\r\n")
.await
.unwrap_err();
assert!(
matches!(&err, Error::Invalid(text) if text.contains("non-ASCII")),
"{err}"
);
script.await.unwrap().unwrap();
}