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:
1 parent
d7de5619a7
commit
9f47b94714
21 files changed
+2848
-20
No files matched your search
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "ely-mail-engine"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
imap-proto.workspace = true
|
||||
base64.workspace = true
|
||||
log.workspace = true
|
||||
mail-send.workspace = true
|
||||
nom.workspace = true
|
||||
rustls.workspace = true
|
||||
rustls-platform-verifier.workspace = true
|
||||
smtp-proto = "0.2"
|
||||
tokio.workspace = true
|
||||
tokio-rustls.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
ely-platform.workspace = true
|
||||
rcgen.workspace = true
|
||||
tempfile.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,38 @@
|
||||
use std::{fmt, io};
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Why a mail server conversation failed; server words kept.
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
/// No TCP connection: name lookup, refusal, reset.
|
||||
Connect(io::Error),
|
||||
/// TLS handshake or certificate check failed.
|
||||
Tls(String),
|
||||
/// The server refused the credentials.
|
||||
Rejected(String),
|
||||
/// The server refused a command after login.
|
||||
Server(String),
|
||||
/// The server said something the client cannot read.
|
||||
Protocol(String),
|
||||
/// The server did not answer in time.
|
||||
Timeout(&'static str),
|
||||
/// An address or login the protocol cannot carry.
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Connect(err) => write!(f, "cannot connect: {err}"),
|
||||
Self::Tls(text) => write!(f, "TLS failed: {text}"),
|
||||
Self::Rejected(text) => write!(f, "login refused: {text}"),
|
||||
Self::Server(text) => write!(f, "server refused: {text}"),
|
||||
Self::Protocol(text) => write!(f, "unreadable reply: {text}"),
|
||||
Self::Timeout(step) => write!(f, "no answer while {step}"),
|
||||
Self::Invalid(text) => write!(f, "cannot be sent: {text}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
@@ -0,0 +1,325 @@
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use imap_proto::{AttributeValue, MailboxDatum, Response, Status};
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio_rustls::TlsConnector;
|
||||
|
||||
use crate::{
|
||||
Error, Result,
|
||||
net::{self, Login, Secret, Security, Server, Stream, within},
|
||||
wire::{Wire, words},
|
||||
};
|
||||
|
||||
/// A logged-in IMAP session over TLS.
|
||||
pub struct Imap {
|
||||
conn: Conn<Stream>,
|
||||
}
|
||||
|
||||
/// One command argument.
|
||||
enum Arg<'a> {
|
||||
/// Written as is.
|
||||
Atom(&'a str),
|
||||
/// Quoted, or a literal when quotes cannot carry it.
|
||||
Text(&'a str),
|
||||
}
|
||||
|
||||
/// OK, or the words of NO or BAD.
|
||||
type Outcome = std::result::Result<(), String>;
|
||||
|
||||
impl Imap {
|
||||
pub async fn connect(server: &Server, login: &Login, tls: &TlsConnector) -> Result<Self> {
|
||||
let tcp = net::tcp(server).await?;
|
||||
let stream = match server.security {
|
||||
Security::Tls => net::tls(tcp, server, tls).await?,
|
||||
Security::StartTls => {
|
||||
let mut plain = Conn::new(tcp);
|
||||
within("waiting for the greeting", plain.greeting()).await??;
|
||||
within("starting TLS", plain.run("STARTTLS", &[], |_, _| {}))
|
||||
.await??
|
||||
.map_err(Error::Server)?;
|
||||
net::tls(plain.wire.into_inner()?, server, tls).await?
|
||||
}
|
||||
};
|
||||
let mut conn = Conn::new(stream);
|
||||
if server.security == Security::Tls {
|
||||
within("waiting for the greeting", conn.greeting()).await??;
|
||||
}
|
||||
let outcome = match &login.secret {
|
||||
Secret::Password(password) => {
|
||||
let args = [Arg::Text(&login.user), Arg::Text(password)];
|
||||
within("logging in", conn.run("LOGIN", &args, |_, _| {})).await??
|
||||
}
|
||||
Secret::Token(token) => {
|
||||
within("logging in", conn.xoauth2(&login.xoauth2(token))).await??
|
||||
}
|
||||
};
|
||||
outcome.map_err(Error::Rejected)?;
|
||||
log::info!("mail: IMAP login on {}", server.host);
|
||||
Ok(Self { conn })
|
||||
}
|
||||
|
||||
/// Every mailbox name the server lists.
|
||||
pub async fn mailboxes(&mut self) -> Result<Vec<String>> {
|
||||
let mut names = Vec::new();
|
||||
let args = [Arg::Text(""), Arg::Atom("*")];
|
||||
within(
|
||||
"listing mailboxes",
|
||||
self.conn.run("LIST", &args, |response, raw| {
|
||||
if let Response::MailboxData(MailboxDatum::List(list)) = response {
|
||||
names.push(mailbox_name(&list.name, raw));
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await??
|
||||
.map_err(Error::Server)?;
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// The raw message; `None` once the UID is gone.
|
||||
pub async fn fetch(&mut self, mailbox: &str, uid: u32) -> Result<Option<Vec<u8>>> {
|
||||
let examine = [Arg::Text(mailbox)];
|
||||
within(
|
||||
"opening the mailbox",
|
||||
self.conn.run("EXAMINE", &examine, |_, _| {}),
|
||||
)
|
||||
.await??
|
||||
.map_err(Error::Server)?;
|
||||
let number = uid.to_string();
|
||||
let args = [Arg::Atom(&number), Arg::Atom("BODY.PEEK[]")];
|
||||
let mut found = None;
|
||||
within(
|
||||
"fetching the message",
|
||||
self.conn.run("UID FETCH", &args, |response, _| {
|
||||
if let Response::Fetch(_, values) = response
|
||||
&& values.contains(&AttributeValue::Uid(uid))
|
||||
{
|
||||
found = Some(body(values));
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await??
|
||||
.map_err(Error::Server)?;
|
||||
match found {
|
||||
None => Ok(None),
|
||||
Some(None) => Err(Error::Protocol(format!("UID {uid} came without a body"))),
|
||||
Some(Some(body)) => Ok(Some(body)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn logout(mut self) -> Result<()> {
|
||||
within("logging out", self.conn.run("LOGOUT", &[], |_, _| {}))
|
||||
.await??
|
||||
.map_err(Error::Server)
|
||||
}
|
||||
}
|
||||
|
||||
/// imap-proto keeps quoted escapes; a literal is as sent.
|
||||
fn mailbox_name(name: &str, raw: &[u8]) -> String {
|
||||
let line = raw.strip_suffix(b"\r\n").unwrap_or(raw);
|
||||
let name_end = |end: &[u8], mark: &[u8]| {
|
||||
end.strip_suffix(name.as_bytes())
|
||||
.is_some_and(|rest| rest.ends_with(mark))
|
||||
};
|
||||
let literal = name_end(line, b"}\r\n");
|
||||
let quoted = line
|
||||
.strip_suffix(b"\"")
|
||||
.is_some_and(|end| name_end(end, b"\""));
|
||||
if literal || !quoted {
|
||||
return name.to_owned();
|
||||
}
|
||||
let mut plain = String::with_capacity(name.len());
|
||||
let mut chars = name.chars();
|
||||
while let Some(char) = chars.next() {
|
||||
match char {
|
||||
'\\' => plain.extend(chars.next()),
|
||||
_ => plain.push(char),
|
||||
}
|
||||
}
|
||||
plain
|
||||
}
|
||||
|
||||
fn body(values: &[AttributeValue]) -> Option<Vec<u8>> {
|
||||
values.iter().find_map(|value| match value {
|
||||
AttributeValue::BodySection {
|
||||
section: None,
|
||||
data: Some(data),
|
||||
..
|
||||
} => Some(data.to_vec()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
struct Conn<S> {
|
||||
wire: Wire<S>,
|
||||
tags: u32,
|
||||
}
|
||||
|
||||
impl<S: AsyncRead + AsyncWrite + Unpin> Conn<S> {
|
||||
fn new(io: S) -> Self {
|
||||
Self {
|
||||
wire: Wire::new(io),
|
||||
tags: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// `* BYE` ends with the server's words.
|
||||
async fn greeting(&mut self) -> Result<()> {
|
||||
self.wire
|
||||
.next(|response, raw| match response {
|
||||
Response::Data {
|
||||
status: Status::Ok, ..
|
||||
} => Ok(()),
|
||||
Response::Data {
|
||||
status: Status::Bye,
|
||||
..
|
||||
} => Err(Error::Server(words(raw))),
|
||||
Response::Data { status, .. } => Err(Error::Protocol(format!(
|
||||
"the greeting was {status:?}, not OK"
|
||||
))),
|
||||
_ => Err(Error::Protocol("the first line was not a greeting".into())),
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
fn tag(&mut self) -> String {
|
||||
self.tags += 1;
|
||||
format!("A{}", self.tags)
|
||||
}
|
||||
|
||||
/// Sends a command; untagged responses go to `each`.
|
||||
async fn run(
|
||||
&mut self,
|
||||
verb: &str,
|
||||
args: &[Arg<'_>],
|
||||
mut each: impl FnMut(&Response, &[u8]),
|
||||
) -> Result<Outcome> {
|
||||
let tag = self.tag();
|
||||
log::debug!("mail: IMAP {tag} {verb}");
|
||||
let mut line = format!("{tag} {verb}").into_bytes();
|
||||
for arg in args {
|
||||
line.push(b' ');
|
||||
match arg {
|
||||
Arg::Atom(atom) => line.extend_from_slice(atom.as_bytes()),
|
||||
Arg::Text(text) => match quoted(text)? {
|
||||
Some(quoted) => line.extend_from_slice(quoted.as_bytes()),
|
||||
None => {
|
||||
line.extend_from_slice(format!("{{{}}}\r\n", text.len()).as_bytes());
|
||||
self.wire.write(&line).await?;
|
||||
line.clear();
|
||||
if let Err(words) = self.proceed(&tag, &mut each).await? {
|
||||
return Ok(Err(words));
|
||||
}
|
||||
line.extend_from_slice(text.as_bytes());
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
line.extend_from_slice(b"\r\n");
|
||||
self.wire.write(&line).await?;
|
||||
loop {
|
||||
match self.step(&tag, &mut each).await? {
|
||||
Step::Done(outcome) => return Ok(outcome),
|
||||
Step::Untagged => {}
|
||||
Step::Continue => {
|
||||
return Err(Error::Protocol(
|
||||
"the server asked for more than was sent".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for `+` before a literal.
|
||||
async fn proceed(
|
||||
&mut self,
|
||||
tag: &str,
|
||||
each: &mut impl FnMut(&Response, &[u8]),
|
||||
) -> Result<Outcome> {
|
||||
loop {
|
||||
match self.step(tag, each).await? {
|
||||
Step::Continue => return Ok(Ok(())),
|
||||
Step::Done(Ok(())) => {
|
||||
return Err(Error::Protocol(
|
||||
"the command ended before its literal".into(),
|
||||
));
|
||||
}
|
||||
Step::Done(refused) => return Ok(refused),
|
||||
Step::Untagged => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers the first challenge; empty after, so a refusal ends.
|
||||
async fn xoauth2(&mut self, initial: &str) -> Result<Outcome> {
|
||||
let tag = self.tag();
|
||||
self.wire
|
||||
.write(format!("{tag} AUTHENTICATE XOAUTH2\r\n").as_bytes())
|
||||
.await?;
|
||||
let mut answer = Some(STANDARD.encode(initial));
|
||||
loop {
|
||||
match self.step(&tag, &mut |_, _| {}).await? {
|
||||
Step::Continue => {
|
||||
let line = answer.take().unwrap_or_default() + "\r\n";
|
||||
self.wire.write(line.as_bytes()).await?;
|
||||
}
|
||||
Step::Done(outcome) => return Ok(outcome),
|
||||
Step::Untagged => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn step(&mut self, tag: &str, each: &mut impl FnMut(&Response, &[u8])) -> Result<Step> {
|
||||
self.wire
|
||||
.next(|response, raw| match response {
|
||||
Response::Continue(_) => Ok(Step::Continue),
|
||||
Response::Done {
|
||||
tag: done, status, ..
|
||||
} => {
|
||||
if done.0 != tag {
|
||||
return Err(Error::Protocol(format!(
|
||||
"a reply for {} came while waiting for {tag}",
|
||||
done.0
|
||||
)));
|
||||
}
|
||||
match status {
|
||||
Status::Ok => Ok(Step::Done(Ok(()))),
|
||||
Status::No | Status::Bad => Ok(Step::Done(Err(words(raw)))),
|
||||
other => Err(Error::Protocol(format!("{tag} ended with {other:?}"))),
|
||||
}
|
||||
}
|
||||
untagged => {
|
||||
each(untagged, raw);
|
||||
Ok(Step::Untagged)
|
||||
}
|
||||
})
|
||||
.await?
|
||||
}
|
||||
}
|
||||
|
||||
enum Step {
|
||||
Continue,
|
||||
Untagged,
|
||||
Done(Outcome),
|
||||
}
|
||||
|
||||
/// `None` when only a literal can carry the text.
|
||||
fn quoted(text: &str) -> Result<Option<String>> {
|
||||
if text.contains('\0') {
|
||||
return Err(Error::Invalid("IMAP cannot carry a NUL byte".into()));
|
||||
}
|
||||
if !text
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii() && byte != b'\r' && byte != b'\n')
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let mut quoted = String::with_capacity(text.len() + 2);
|
||||
quoted.push('"');
|
||||
for char in text.chars() {
|
||||
if char == '"' || char == '\\' {
|
||||
quoted.push('\\');
|
||||
}
|
||||
quoted.push(char);
|
||||
}
|
||||
quoted.push('"');
|
||||
Ok(Some(quoted))
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! Mail protocols, sync and local storage for ElyMail.
|
||||
|
||||
mod error;
|
||||
mod imap;
|
||||
mod net;
|
||||
mod pop;
|
||||
mod smtp;
|
||||
mod wire;
|
||||
|
||||
pub use error::{Error, Result};
|
||||
pub use imap::Imap;
|
||||
pub use net::{Login, Secret, Security, Server, system_tls};
|
||||
pub use pop::Pop;
|
||||
pub use smtp::Smtp;
|
||||
pub use tokio_rustls::TlsConnector;
|
||||
@@ -0,0 +1,83 @@
|
||||
use std::{future::Future, sync::Arc, time::Duration};
|
||||
|
||||
use rustls::{ClientConfig, crypto::ring, pki_types::ServerName};
|
||||
use rustls_platform_verifier::BuilderVerifierExt;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio_rustls::{TlsConnector, client::TlsStream};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
pub(crate) type Stream = TlsStream<TcpStream>;
|
||||
|
||||
const WAIT: Duration = Duration::from_secs(60);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Server {
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
pub security: Security,
|
||||
}
|
||||
|
||||
/// No plaintext: every mode ends in TLS.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Security {
|
||||
Tls,
|
||||
StartTls,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Login {
|
||||
pub user: String,
|
||||
pub secret: Secret,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum Secret {
|
||||
Password(String),
|
||||
/// An OAuth access token, sent as XOAUTH2.
|
||||
Token(String),
|
||||
}
|
||||
|
||||
impl Login {
|
||||
/// The SASL XOAUTH2 initial response, before base64.
|
||||
pub(crate) fn xoauth2(&self, token: &str) -> String {
|
||||
format!("user={}\x01auth=Bearer {token}\x01\x01", self.user)
|
||||
}
|
||||
}
|
||||
|
||||
/// Verifies servers with the system's trust store.
|
||||
pub fn system_tls() -> Result<TlsConnector> {
|
||||
let config = ClientConfig::builder_with_provider(Arc::new(ring::default_provider()))
|
||||
.with_safe_default_protocol_versions()
|
||||
.and_then(|builder| builder.with_platform_verifier())
|
||||
.map_err(|err| Error::Tls(err.to_string()))?
|
||||
.with_no_client_auth();
|
||||
Ok(TlsConnector::from(Arc::new(config)))
|
||||
}
|
||||
|
||||
pub(crate) async fn within<T>(step: &'static str, work: impl Future<Output = T>) -> Result<T> {
|
||||
tokio::time::timeout(WAIT, work)
|
||||
.await
|
||||
.map_err(|_| Error::Timeout(step))
|
||||
}
|
||||
|
||||
pub(crate) async fn tcp(server: &Server) -> Result<TcpStream> {
|
||||
let stream = within(
|
||||
"connecting",
|
||||
TcpStream::connect((server.host.as_str(), server.port)),
|
||||
)
|
||||
.await?
|
||||
.map_err(Error::Connect)?;
|
||||
log::info!("mail: connected to {}:{}", server.host, server.port);
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
pub(crate) async fn tls(tcp: TcpStream, server: &Server, tls: &TlsConnector) -> Result<Stream> {
|
||||
let name = ServerName::try_from(server.host.clone())
|
||||
.map_err(|err| Error::Tls(format!("{}: {err}", server.host)))?;
|
||||
let stream = within("starting TLS", tls.connect(name, tcp))
|
||||
.await?
|
||||
.map_err(|err| Error::Tls(err.to_string()))?;
|
||||
log::info!("mail: TLS with {}:{}", server.host, server.port);
|
||||
Ok(stream)
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
use std::io;
|
||||
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
|
||||
use tokio_rustls::TlsConnector;
|
||||
|
||||
use crate::{
|
||||
Error, Result,
|
||||
net::{self, Login, Secret, Security, Server, Stream, within},
|
||||
};
|
||||
|
||||
/// A logged-in POP3 session (RFC 1939) over TLS.
|
||||
pub struct Pop {
|
||||
io: BufReader<Stream>,
|
||||
}
|
||||
|
||||
impl Pop {
|
||||
pub async fn connect(server: &Server, login: &Login, tls: &TlsConnector) -> Result<Self> {
|
||||
let tcp = net::tcp(server).await?;
|
||||
let stream = match server.security {
|
||||
Security::Tls => net::tls(tcp, server, tls).await?,
|
||||
Security::StartTls => {
|
||||
let mut plain = BufReader::new(tcp);
|
||||
within("waiting for the greeting", status(&mut plain)).await??;
|
||||
within("starting TLS", ask(&mut plain, "STLS")).await??;
|
||||
// Plain bytes here would pass as TLS data.
|
||||
if !plain.buffer().is_empty() {
|
||||
return Err(Error::Protocol("the server sent data after STLS".into()));
|
||||
}
|
||||
net::tls(plain.into_inner(), server, tls).await?
|
||||
}
|
||||
};
|
||||
let mut io = BufReader::new(stream);
|
||||
if server.security == Security::Tls {
|
||||
within("waiting for the greeting", status(&mut io)).await??;
|
||||
}
|
||||
within("logging in", authenticate(&mut io, login)).await??;
|
||||
log::info!("mail: POP3 login on {}", server.host);
|
||||
Ok(Self { io })
|
||||
}
|
||||
|
||||
/// Message numbers with their unique ids.
|
||||
pub async fn uids(&mut self) -> Result<Vec<(usize, String)>> {
|
||||
let list = within("listing messages", async {
|
||||
ask(&mut self.io, "UIDL").await?;
|
||||
lines(&mut self.io).await
|
||||
})
|
||||
.await??;
|
||||
list.split(|&byte| byte == b'\n')
|
||||
.filter(|line| !line.is_empty())
|
||||
.map(|line| {
|
||||
let line = std::str::from_utf8(line.strip_suffix(b"\r").unwrap_or(line))
|
||||
.map_err(|_| Error::Protocol("UIDL sent a line that is not text".into()))?;
|
||||
let unreadable = || Error::Protocol(format!("UIDL sent {line:?}"));
|
||||
let (number, id) = line.split_once(' ').ok_or_else(unreadable)?;
|
||||
let number = number.parse().map_err(|_| unreadable())?;
|
||||
Ok((number, id.trim_end().to_owned()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn fetch(&mut self, number: usize) -> Result<Vec<u8>> {
|
||||
within("fetching the message", async {
|
||||
ask(&mut self.io, &format!("RETR {number}")).await?;
|
||||
lines(&mut self.io).await
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
pub async fn quit(mut self) -> Result<()> {
|
||||
within("logging out", ask(&mut self.io, "QUIT")).await??;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn authenticate<S>(io: &mut BufReader<S>, login: &Login) -> Result<()>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
match &login.secret {
|
||||
Secret::Password(password) => {
|
||||
one_line(&login.user)?;
|
||||
one_line(password)?;
|
||||
ask(io, &format!("USER {}", login.user))
|
||||
.await
|
||||
.map_err(refused)?;
|
||||
ask(io, &format!("PASS {password}"))
|
||||
.await
|
||||
.map_err(refused)?;
|
||||
}
|
||||
Secret::Token(token) => {
|
||||
send(io, "AUTH XOAUTH2").await?;
|
||||
if status(io).await.map_err(refused)?.is_none() {
|
||||
return Err(Error::Protocol(
|
||||
"XOAUTH2 was accepted before the token".into(),
|
||||
));
|
||||
}
|
||||
send(io, &STANDARD.encode(login.xoauth2(token))).await?;
|
||||
if status(io).await.map_err(refused)?.is_some() {
|
||||
// An error challenge; the empty answer draws -ERR.
|
||||
send(io, "").await?;
|
||||
status(io).await.map_err(refused)?;
|
||||
return Err(Error::Protocol(
|
||||
"the token was challenged, then accepted".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Text after `+OK`, or `Some` after a `+` challenge.
|
||||
async fn status<S>(io: &mut BufReader<S>) -> Result<Option<String>>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
let line = line(io).await?;
|
||||
let words = |rest: &[u8]| String::from_utf8_lossy(rest).trim().to_owned();
|
||||
if line.starts_with(b"+OK") {
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix(b"-ERR") {
|
||||
return Err(Error::Server(words(rest)));
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix(b"+") {
|
||||
return Ok(Some(words(rest)));
|
||||
}
|
||||
Err(Error::Protocol(
|
||||
"the server's line was neither +OK nor -ERR".into(),
|
||||
))
|
||||
}
|
||||
|
||||
/// One command that must end in `+OK`.
|
||||
async fn ask<S>(io: &mut BufReader<S>, command: &str) -> Result<()>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
send(io, command).await?;
|
||||
match status(io).await? {
|
||||
None => Ok(()),
|
||||
Some(_) => Err(Error::Protocol(
|
||||
"the server sent a challenge to a command".into(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn send<S>(io: &mut BufReader<S>, command: &str) -> Result<()>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
let stream = io.get_mut();
|
||||
stream
|
||||
.write_all(command.as_bytes())
|
||||
.await
|
||||
.map_err(Error::Connect)?;
|
||||
stream.write_all(b"\r\n").await.map_err(Error::Connect)?;
|
||||
stream.flush().await.map_err(Error::Connect)
|
||||
}
|
||||
|
||||
async fn line<S>(io: &mut BufReader<S>) -> Result<Vec<u8>>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
let mut line = Vec::new();
|
||||
io.read_until(b'\n', &mut line)
|
||||
.await
|
||||
.map_err(Error::Connect)?;
|
||||
if line.last() != Some(&b'\n') {
|
||||
return Err(Error::Connect(io::ErrorKind::UnexpectedEof.into()));
|
||||
}
|
||||
Ok(line)
|
||||
}
|
||||
|
||||
/// A multi-line answer, dot-unstuffed, line ends kept.
|
||||
async fn lines<S>(io: &mut BufReader<S>) -> Result<Vec<u8>>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin,
|
||||
{
|
||||
let mut body = Vec::new();
|
||||
loop {
|
||||
let line = line(io).await?;
|
||||
if line == b".\r\n" || line == b".\n" {
|
||||
return Ok(body);
|
||||
}
|
||||
body.extend_from_slice(line.strip_prefix(b".").unwrap_or(&line));
|
||||
}
|
||||
}
|
||||
|
||||
/// A line break would start a second command.
|
||||
fn one_line(text: &str) -> Result<()> {
|
||||
if text.contains(['\r', '\n']) {
|
||||
return Err(Error::Invalid(
|
||||
"a user name or password holds a line break".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn refused(err: Error) -> Error {
|
||||
match err {
|
||||
Error::Server(text) => Error::Rejected(text),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use mail_send::{
|
||||
Credentials, Error as SendError, SmtpClient,
|
||||
smtp::{AssertReply, message::Parameters},
|
||||
};
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio_rustls::TlsConnector;
|
||||
|
||||
use crate::{
|
||||
Error, Result,
|
||||
net::{self, Login, Secret, Security, Server, Stream, within},
|
||||
};
|
||||
|
||||
/// EHLO name: an address literal, so no host name leaks.
|
||||
const HELLO: &str = "[127.0.0.1]";
|
||||
const WAIT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// A logged-in SMTP session over TLS.
|
||||
pub struct Smtp {
|
||||
client: SmtpClient<Stream>,
|
||||
/// The server takes UTF-8 addresses (SMTPUTF8).
|
||||
utf8: bool,
|
||||
}
|
||||
|
||||
impl Smtp {
|
||||
pub async fn connect(server: &Server, login: &Login, tls: &TlsConnector) -> Result<Self> {
|
||||
let tcp = net::tcp(server).await?;
|
||||
let mut client = match server.security {
|
||||
Security::Tls => {
|
||||
let mut client = smtp(net::tls(tcp, server, tls).await?);
|
||||
greeting(&mut client).await?;
|
||||
client
|
||||
}
|
||||
Security::StartTls => {
|
||||
let mut plain = smtp(tcp);
|
||||
greeting(&mut plain).await?;
|
||||
let hello = within("greeting", plain.ehlo(HELLO))
|
||||
.await?
|
||||
.map_err(failed)?;
|
||||
if !hello.has_capability(smtp_proto::EXT_START_TLS) {
|
||||
return Err(Error::Server("the server does not offer STARTTLS".into()));
|
||||
}
|
||||
within("starting TLS", plain.start_tls(tls, &server.host))
|
||||
.await?
|
||||
.map_err(failed)?
|
||||
}
|
||||
};
|
||||
let hello = within("greeting", client.capabilities(HELLO, false))
|
||||
.await?
|
||||
.map_err(failed)?;
|
||||
match &login.secret {
|
||||
Secret::Password(password) => {
|
||||
let credentials = Credentials::Plain {
|
||||
username: login.user.clone(),
|
||||
secret: password.clone(),
|
||||
};
|
||||
within("logging in", client.authenticate(&credentials, &hello))
|
||||
.await?
|
||||
.map_err(refused)?;
|
||||
}
|
||||
Secret::Token(token) => {
|
||||
if hello.auth_mechanisms & smtp_proto::AUTH_XOAUTH2 == 0 {
|
||||
return Err(Error::Rejected("the server does not offer XOAUTH2".into()));
|
||||
}
|
||||
within("logging in", xoauth2(&mut client, &login.xoauth2(token))).await??;
|
||||
}
|
||||
}
|
||||
log::info!("mail: SMTP login on {}", server.host);
|
||||
let utf8 = hello.has_capability(smtp_proto::EXT_SMTP_UTF8);
|
||||
Ok(Self { client, utf8 })
|
||||
}
|
||||
|
||||
/// Hands one message to the server for these recipients.
|
||||
pub async fn send(&mut self, from: &str, to: &[String], message: &[u8]) -> Result<()> {
|
||||
if to.is_empty() {
|
||||
return Err(Error::Invalid("a message needs a recipient".into()));
|
||||
}
|
||||
for email in to.iter().map(String::as_str).chain([from]) {
|
||||
mailbox(email)?;
|
||||
}
|
||||
let data = data(message)?;
|
||||
let mut params = Parameters::new();
|
||||
let header = message
|
||||
.windows(4)
|
||||
.position(|end| end == b"\r\n\r\n")
|
||||
.map_or(message, |at| &message[..at]);
|
||||
if !from.is_ascii() || to.iter().any(|to| !to.is_ascii()) || !header.is_ascii() {
|
||||
if !self.utf8 {
|
||||
return Err(Error::Invalid(
|
||||
"the server does not take non-ASCII addresses or headers".into(),
|
||||
));
|
||||
}
|
||||
params.add("SMTPUTF8");
|
||||
}
|
||||
let sent = within("sending", async {
|
||||
self.client.mail_from(from, ¶ms).await?;
|
||||
for to in to {
|
||||
self.client.rcpt_to(to, &Parameters::new()).await?;
|
||||
}
|
||||
self.client.cmd(b"DATA\r\n").await?.assert_code(354)?;
|
||||
self.client.stream.write_all(&data).await?;
|
||||
self.client.stream.flush().await?;
|
||||
self.client.read().await?.assert_positive_completion()
|
||||
})
|
||||
.await?;
|
||||
if let Err(SendError::UnexpectedReply(reply)) = sent {
|
||||
// A refusal leaves the transaction open.
|
||||
let words = format!("{} {}", reply.code(), reply.message());
|
||||
return Err(match within("resetting", self.client.rset()).await? {
|
||||
Ok(()) => Error::Server(words),
|
||||
Err(err) => Error::Server(format!("{words}; RSET failed: {}", failed(err))),
|
||||
});
|
||||
}
|
||||
sent.map_err(failed)?;
|
||||
log::info!("mail: SMTP accepted a message for {} recipients", to.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn quit(self) -> Result<()> {
|
||||
within("logging out", self.client.quit())
|
||||
.await?
|
||||
.map_err(failed)
|
||||
}
|
||||
}
|
||||
|
||||
fn smtp<T: tokio::io::AsyncRead + tokio::io::AsyncWrite>(stream: T) -> SmtpClient<T> {
|
||||
SmtpClient {
|
||||
stream,
|
||||
timeout: WAIT,
|
||||
}
|
||||
}
|
||||
|
||||
async fn greeting<T>(client: &mut SmtpClient<T>) -> Result<()>
|
||||
where
|
||||
T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
|
||||
{
|
||||
let reply = within("waiting for the greeting", client.read())
|
||||
.await?
|
||||
.map_err(failed)?;
|
||||
reply.assert_positive_completion().map_err(failed)
|
||||
}
|
||||
|
||||
/// Gmail's exchange: an error challenge draws an empty line.
|
||||
async fn xoauth2<T>(client: &mut SmtpClient<T>, initial: &str) -> Result<()>
|
||||
where
|
||||
T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
|
||||
{
|
||||
let command = format!("AUTH XOAUTH2 {}\r\n", STANDARD.encode(initial));
|
||||
let mut reply = client.cmd(command).await.map_err(failed)?;
|
||||
if reply.code() == 334 {
|
||||
reply = client.cmd("\r\n").await.map_err(failed)?;
|
||||
}
|
||||
match reply.code() {
|
||||
235 => Ok(()),
|
||||
code => Err(Error::Rejected(format!("{code} {}", reply.message()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// RFC 5321 §4.5.2: a leading dot doubles.
|
||||
fn data(message: &[u8]) -> Result<Vec<u8>> {
|
||||
let mut out = Vec::with_capacity(message.len() + 8);
|
||||
let mut start = true;
|
||||
for (at, &byte) in message.iter().enumerate() {
|
||||
let bare = match byte {
|
||||
b'\r' => message.get(at + 1) != Some(&b'\n'),
|
||||
b'\n' => at == 0 || message[at - 1] != b'\r',
|
||||
_ => false,
|
||||
};
|
||||
if bare {
|
||||
return Err(Error::Invalid("the message has a bare CR or LF".into()));
|
||||
}
|
||||
if start && byte == b'.' {
|
||||
out.push(b'.');
|
||||
}
|
||||
out.push(byte);
|
||||
start = byte == b'\n';
|
||||
}
|
||||
if !out.is_empty() && !out.ends_with(b"\r\n") {
|
||||
out.extend_from_slice(b"\r\n");
|
||||
}
|
||||
out.extend_from_slice(b".\r\n");
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// RFC 5321 §4.1.2 Mailbox, with RFC 6531 UTF-8.
|
||||
fn mailbox(email: &str) -> Result<()> {
|
||||
let readable = email.rsplit_once('@').is_some_and(|(local, domain)| {
|
||||
let local = match local
|
||||
.strip_prefix('"')
|
||||
.and_then(|rest| rest.strip_suffix('"'))
|
||||
{
|
||||
Some(inner) => quoted(inner),
|
||||
None => dotted(local),
|
||||
};
|
||||
local && domain_ok(domain)
|
||||
});
|
||||
if !readable {
|
||||
return Err(Error::Invalid(format!("not a mail address: {email:?}")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn quoted(inner: &str) -> bool {
|
||||
let mut chars = inner.chars();
|
||||
while let Some(char) = chars.next() {
|
||||
let fine = match char {
|
||||
'\\' => chars.next().is_some_and(|next| matches!(next, ' '..='~')),
|
||||
'"' => false,
|
||||
' '..='~' => true,
|
||||
_ => !char.is_ascii(),
|
||||
};
|
||||
if !fine {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn dotted(local: &str) -> bool {
|
||||
let atext = |char: char| {
|
||||
char.is_ascii_alphanumeric() || "!#$%&'*+-/=?^_`{|}~".contains(char) || !char.is_ascii()
|
||||
};
|
||||
local
|
||||
.split('.')
|
||||
.all(|atom| !atom.is_empty() && atom.chars().all(atext))
|
||||
}
|
||||
|
||||
fn domain_ok(domain: &str) -> bool {
|
||||
if let Some(literal) = domain
|
||||
.strip_prefix('[')
|
||||
.and_then(|rest| rest.strip_suffix(']'))
|
||||
{
|
||||
return !literal.is_empty()
|
||||
&& literal
|
||||
.bytes()
|
||||
.all(|byte| matches!(byte, 33..=90 | 94..=126));
|
||||
}
|
||||
domain.split('.').all(|label| {
|
||||
!label.is_empty()
|
||||
&& !label.starts_with('-')
|
||||
&& !label.ends_with('-')
|
||||
&& label
|
||||
.chars()
|
||||
.all(|char| char.is_ascii_alphanumeric() || char == '-' || !char.is_ascii())
|
||||
})
|
||||
}
|
||||
|
||||
fn refused(err: SendError) -> Error {
|
||||
match err {
|
||||
SendError::AuthenticationFailed(reply) => {
|
||||
Error::Rejected(format!("{} {}", reply.code(), reply.message()))
|
||||
}
|
||||
SendError::UnsupportedAuthMechanism => {
|
||||
Error::Rejected("the server offers no login method for these credentials".into())
|
||||
}
|
||||
other => failed(other),
|
||||
}
|
||||
}
|
||||
|
||||
fn failed(err: SendError) -> Error {
|
||||
match err {
|
||||
SendError::Io(err) => Error::Connect(err),
|
||||
SendError::Tls(err) => Error::Tls(err.to_string()),
|
||||
SendError::Timeout => Error::Timeout("talking to the server"),
|
||||
SendError::UnexpectedReply(reply) => {
|
||||
Error::Server(format!("{} {}", reply.code(), reply.message()))
|
||||
}
|
||||
other => Error::Protocol(other.to_string()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
use std::io;
|
||||
|
||||
use imap_proto::{Response, Status};
|
||||
use nom::{Err as NomErr, Needed};
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
const CHUNK: usize = 16 * 1024;
|
||||
|
||||
/// IMAP responses off a byte stream; keeps the last BYE.
|
||||
pub(crate) struct Wire<S> {
|
||||
io: S,
|
||||
buf: Vec<u8>,
|
||||
/// Bytes the next parse needs before it can finish.
|
||||
needs: usize,
|
||||
bye: Option<String>,
|
||||
}
|
||||
|
||||
impl<S: AsyncRead + AsyncWrite + Unpin> Wire<S> {
|
||||
pub fn new(io: S) -> Self {
|
||||
Self {
|
||||
io,
|
||||
buf: Vec::new(),
|
||||
needs: 0,
|
||||
bye: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands the next response and its raw bytes to `read`.
|
||||
pub async fn next<R>(&mut self, mut read: impl FnMut(&Response, &[u8]) -> R) -> Result<R> {
|
||||
loop {
|
||||
if self.buf.len() >= self.needs && !self.buf.is_empty() {
|
||||
let parsed = match Response::parse(&self.buf) {
|
||||
Ok((rest, response)) => {
|
||||
let used = self.buf.len() - rest.len();
|
||||
let raw = &self.buf[..used];
|
||||
if let Response::Data {
|
||||
status: Status::Bye,
|
||||
..
|
||||
} = response
|
||||
{
|
||||
self.bye = Some(words(raw));
|
||||
}
|
||||
Some((used, read(&response, raw)))
|
||||
}
|
||||
Err(NomErr::Incomplete(Needed::Size(more))) => {
|
||||
self.needs = self.buf.len() + more.get();
|
||||
None
|
||||
}
|
||||
Err(NomErr::Incomplete(Needed::Unknown)) => {
|
||||
self.needs = self.buf.len() + 1;
|
||||
None
|
||||
}
|
||||
Err(_) => {
|
||||
return Err(Error::Protocol(
|
||||
"a reply from the server could not be read".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
if let Some((used, value)) = parsed {
|
||||
self.buf.drain(..used);
|
||||
self.needs = 0;
|
||||
return Ok(value);
|
||||
}
|
||||
}
|
||||
self.buf.reserve(CHUNK);
|
||||
match self.io.read_buf(&mut self.buf).await {
|
||||
Ok(0) => return Err(self.closed(io::ErrorKind::UnexpectedEof.into())),
|
||||
Ok(_) => {}
|
||||
Err(err) => return Err(self.closed(err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn write(&mut self, bytes: &[u8]) -> Result<()> {
|
||||
let sent = async {
|
||||
self.io.write_all(bytes).await?;
|
||||
self.io.flush().await
|
||||
};
|
||||
sent.await.map_err(|err| self.closed(err))
|
||||
}
|
||||
|
||||
/// The stream for TLS; bytes already read would be plaintext.
|
||||
pub fn into_inner(self) -> Result<S> {
|
||||
if !self.buf.is_empty() {
|
||||
return Err(Error::Protocol(
|
||||
"the server sent data before TLS began".into(),
|
||||
));
|
||||
}
|
||||
Ok(self.io)
|
||||
}
|
||||
|
||||
/// After BYE, a dropped line is the server's words.
|
||||
fn closed(&self, err: io::Error) -> Error {
|
||||
match &self.bye {
|
||||
Some(words) => Error::Server(words.clone()),
|
||||
None => Error::Connect(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The line after its tag, as the server wrote it.
|
||||
pub(crate) fn words(raw: &[u8]) -> String {
|
||||
let line = raw.strip_suffix(b"\r\n").unwrap_or(raw);
|
||||
let text = line.splitn(2, |&byte| byte == b' ').nth(1).unwrap_or(line);
|
||||
String::from_utf8_lossy(text).into_owned()
|
||||
}
|
||||
@@ -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")),
|
||||
}
|
||||
}
|
||||
@@ -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}"
|
||||
);
|
||||
}
|
||||
@@ -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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
Reference in new issue
Block a user