C12.5: mail accounts, add and remove

ElyMail's window lists accounts and adds Gmail, Microsoft, iCloud
(app-specific password), IMAP and POP3 ones; a check logs in to both
servers and reports each. Accounts live in the store as JSON with a
case-insensitive unique address; secrets go to the keychain. Removal
names the cache it deletes, takes the secret first and puts it back
when local removal fails. Originals are set aside until commit and
restored after a crash. Requests are numbered so late results stay
with their own dialog. The account list is keyboard-navigable.
This commit is contained in:
雷电芽衣 committed 2026-10-19 20:17:19 -04:00
1 parent 5068bc07ca
commit 1c225f6812
39 files changed
+3152 -105

No files matched your search

+123
View File
@@ -0,0 +1,123 @@
//! An account's servers and how it signs in (MAIL-01, 02).
use serde::{Deserialize, Serialize};
use crate::{Error, Imap, Login, Pop, Result, Secret, Server, Smtp, TlsConnector, oauth};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Protocol {
Imap,
Pop,
}
/// A password, or OAuth with one provider.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Auth {
Password,
Google,
Microsoft,
}
impl Auth {
/// The OAuth server; None for a password.
pub fn provider(self) -> Option<Result<oauth::Provider>> {
match self {
Auth::Password => None,
Auth::Google => Some(oauth::google()),
Auth::Microsoft => Some(oauth::microsoft()),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Account {
pub address: String,
pub user: String,
pub auth: Auth,
pub protocol: Protocol,
pub incoming: Server,
pub outgoing: Server,
}
/// What each server answered.
pub struct Checked {
pub incoming: Result<()>,
pub outgoing: Result<()>,
}
impl Checked {
pub fn passed(&self) -> bool {
self.incoming.is_ok() && self.outgoing.is_ok()
}
}
impl Account {
/// The vault name of its password or refresh token.
pub fn secret_name(&self) -> String {
format!("account:{}", self.address)
}
/// Refuses what no server could carry.
pub fn valid(&self) -> Result<()> {
crate::smtp::mailbox(&self.address)?;
if self.user.is_empty() || self.user.contains(['\r', '\n']) {
return Err(Error::Invalid("a user name on one line is needed".into()));
}
for server in [&self.incoming, &self.outgoing] {
if server.host.is_empty() || server.host.contains(char::is_whitespace) {
return Err(Error::Invalid(format!("a server host: {:?}", server.host)));
}
if server.port == 0 {
return Err(Error::Invalid("port 0".into()));
}
}
Ok(())
}
pub fn login(&self, secret: Secret) -> Login {
Login {
user: self.user.clone(),
secret,
}
}
/// Logs in to both servers at once, then leaves.
pub async fn check(&self, secret: Secret, tls: &TlsConnector) -> Checked {
let login = self.login(secret);
let (incoming, outgoing) = tokio::join!(
self.check_incoming(&login, tls),
check_outgoing(&self.outgoing, &login, tls)
);
log::info!(
"mail: check: incoming {}, outgoing {}",
outcome(&incoming),
outcome(&outgoing)
);
Checked { incoming, outgoing }
}
async fn check_incoming(&self, login: &Login, tls: &TlsConnector) -> Result<()> {
match self.protocol {
Protocol::Imap => {
Imap::connect(&self.incoming, login, tls)
.await?
.logout()
.await
}
Protocol::Pop => Pop::connect(&self.incoming, login, tls).await?.quit().await,
}
}
}
async fn check_outgoing(server: &Server, login: &Login, tls: &TlsConnector) -> Result<()> {
Smtp::connect(server, login, tls).await?.quit().await
}
fn outcome(result: &Result<()>) -> &'static str {
match result {
Ok(()) => "passed",
Err(_) => "failed",
}
}
+3
View File
@@ -23,6 +23,8 @@ pub enum Error {
Mime(String),
/// The local store failed: database, disk or damage.
Store(String),
/// An account with this address is already kept.
Taken(String),
/// The store refuses writes; the reason says why.
ReadOnly(String),
/// The system credential store failed.
@@ -47,6 +49,7 @@ impl fmt::Display for Error {
Self::Invalid(text) => write!(f, "cannot be sent: {text}"),
Self::Mime(text) => write!(f, "unreadable message: {text}"),
Self::Store(text) => write!(f, "local store failed: {text}"),
Self::Taken(address) => write!(f, "{address} is already added"),
Self::ReadOnly(text) => write!(f, "local store is read-only: {text}"),
Self::Vault(text) => write!(f, "credential store failed: {text}"),
Self::Unavailable(name) => write!(f, "{name} sign-in is not in this build"),
+3 -1
View File
@@ -1,5 +1,6 @@
//! Mail protocols, sync and local storage for ElyMail.
mod account;
mod error;
mod imap;
mod mime;
@@ -11,12 +12,13 @@ mod store;
mod vault;
mod wire;
pub use account::{Account, Auth, Checked, Protocol};
pub use error::{Error, Result};
pub use imap::Imap;
pub use mime::{Built, Draft, Mail, Mailbox, Part, build, read};
pub use net::{Login, Secret, Security, Server, system_tls};
pub use pop::Pop;
pub use smtp::Smtp;
pub use store::{AccountId, Fetched, Key, MailboxId, MessageId, Sizes, Store, Stored};
pub use store::{AccountId, Cached, Fetched, Key, MailboxId, MessageId, Sizes, Store, Stored};
pub use tokio_rustls::TlsConnector;
pub use vault::{Backend, Kept, Keyring, Vault};
+4 -2
View File
@@ -2,6 +2,7 @@ use std::{future::Future, sync::Arc, time::Duration};
use rustls::{ClientConfig, crypto::ring, pki_types::ServerName};
use rustls_platform_verifier::BuilderVerifierExt;
use serde::{Deserialize, Serialize};
use tokio::net::TcpStream;
use tokio_rustls::{TlsConnector, client::TlsStream};
@@ -11,7 +12,7 @@ pub(crate) type Stream = TlsStream<TcpStream>;
const WAIT: Duration = Duration::from_secs(60);
#[derive(Clone, Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Server {
pub host: String,
pub port: u16,
@@ -19,7 +20,8 @@ pub struct Server {
}
/// No plaintext: every mode ends in TLS.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Security {
Tls,
StartTls,
+4 -15
View File
@@ -10,6 +10,8 @@ use rusqlite::{Connection, OpenFlags, OptionalExtension, params};
use crate::{Error, Result};
mod accounts;
mod aside;
mod html;
mod messages;
mod schema;
@@ -17,6 +19,7 @@ mod search;
#[cfg(test)]
mod tests;
pub use accounts::Cached;
pub use messages::{Fetched, Key, Stored};
const DB: &str = "mail.db";
@@ -63,21 +66,6 @@ impl Store {
}
}
pub fn add_account(&self, address: &str) -> Result<AccountId> {
self.writable()?;
self.conn
.execute("INSERT INTO accounts (address) VALUES (?1)", [address])?;
Ok(AccountId(self.conn.last_insert_rowid()))
}
pub fn accounts(&self) -> Result<Vec<(AccountId, String)>> {
let mut query = self
.conn
.prepare("SELECT id, address FROM accounts ORDER BY id")?;
let rows = query.query_map([], |row| Ok((AccountId(row.get(0)?), row.get(1)?)))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// The mailbox by name, made on first use.
pub fn mailbox(&self, account: AccountId, name: &str) -> Result<MailboxId> {
let find = "SELECT id FROM mailboxes WHERE account = ?1 AND name = ?2";
@@ -155,6 +143,7 @@ fn open(dir: &Path, steps: &[&str]) -> Result<Store> {
}
conn.pragma_update(None, "foreign_keys", true)?;
conn.pragma_update(None, "journal_mode", "WAL")?;
aside::recover(&conn, dir)?;
log::info!("mail: store opened at schema v{target}");
Ok(Store {
conn,
@@ -0,0 +1,110 @@
//! Accounts: added, listed, and removed with their cache.
use std::{fs, io::ErrorKind};
use rusqlite::params;
use super::{AccountId, CONTENT, Store, aside::Aside, disk};
use crate::{Account, Error, Result};
/// What removing an account deletes here.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Cached {
pub messages: u64,
/// Originals no other account shares.
pub bytes: u64,
}
impl Store {
/// Addresses differ in more than ASCII case.
pub fn add_account(&self, account: &Account) -> Result<AccountId> {
self.writable()?;
let settings = serde_json::to_string(account)?;
let added = self.conn.execute(
"INSERT INTO accounts (address, settings) VALUES (?1, ?2)",
params![account.address, settings],
);
match added {
Ok(_) => Ok(AccountId(self.conn.last_insert_rowid())),
Err(rusqlite::Error::SqliteFailure(err, _))
if err.extended_code == rusqlite::ffi::SQLITE_CONSTRAINT_UNIQUE =>
{
Err(Error::Taken(account.address.clone()))
}
Err(err) => Err(err.into()),
}
}
pub fn accounts(&self) -> Result<Vec<(AccountId, Account)>> {
let mut query = self
.conn
.prepare("SELECT id, settings FROM accounts ORDER BY id")?;
let rows = query.query_map([], |row| {
Ok((AccountId(row.get(0)?), row.get::<_, String>(1)?))
})?;
rows.map(|row| {
let (id, settings) = row?;
Ok((id, serde_json::from_str(&settings)?))
})
.collect()
}
pub fn cached(&self, account: AccountId) -> Result<Cached> {
let messages: i64 = self.conn.query_row(
"SELECT count(*) FROM messages JOIN mailboxes ON messages.mailbox = mailboxes.id
WHERE mailboxes.account = ?1",
[account.0],
|row| row.get(0),
)?;
let mut bytes = 0;
for hash in self.only_in(account)? {
let path = self.dir.join(CONTENT).join(&hash[..2]).join(&hash);
bytes += match fs::metadata(path) {
Ok(meta) => meta.len(),
Err(err) if err.kind() == ErrorKind::NotFound => 0,
Err(err) => return Err(disk("measuring an original", err)),
};
}
let messages = u64::try_from(messages)
.map_err(|_| Error::Store(format!("a negative count: {messages}")))?;
Ok(Cached { messages, bytes })
}
/// The account, its mailboxes, messages and unshared originals.
pub fn remove_account(&mut self, account: AccountId) -> Result<()> {
self.writable()?;
let hashes = self.only_in(account)?;
let tx = self.conn.transaction()?;
let mut aside = Aside::new(&self.dir);
let done = (|| -> Result<()> {
let gone = tx.execute("DELETE FROM accounts WHERE id = ?1", [account.0])?;
if gone != 1 {
return Err(Error::Store(format!("no account {}", account.0)));
}
for hash in &hashes {
aside.drop_unused(&tx, hash)?;
}
Ok(tx.commit()?)
})();
aside.settle(done)?;
log::info!(
"mail: account {} removed with {} originals",
account.0,
hashes.len()
);
Ok(())
}
fn only_in(&self, account: AccountId) -> Result<Vec<String>> {
let mut query = self.conn.prepare(
"SELECT DISTINCT content FROM messages JOIN mailboxes ON messages.mailbox = mailboxes.id
WHERE mailboxes.account = ?1 AND content IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM messages AS other
JOIN mailboxes AS theirs ON other.mailbox = theirs.id
WHERE other.content = messages.content AND theirs.account <> ?1)
ORDER BY content",
)?;
let rows = query.query_map([account.0], |row| row.get(0))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
}
+139
View File
@@ -0,0 +1,139 @@
//! Originals set aside until their transaction commits.
use std::{
fs,
io::ErrorKind,
path::{Path, PathBuf},
};
use rusqlite::Connection;
use super::{CONTENT, disk};
use crate::{Error, Result};
const MARK: &str = ".gone";
fn original(dir: &Path, hash: &str) -> PathBuf {
dir.join(CONTENT).join(&hash[..2]).join(hash)
}
fn parked(dir: &Path, hash: &str) -> PathBuf {
dir.join(CONTENT)
.join(&hash[..2])
.join(format!(".{hash}{MARK}"))
}
/// Renamed, not deleted, so a rollback can put them back.
pub(super) struct Aside {
dir: PathBuf,
moved: Vec<String>,
}
impl Aside {
pub fn new(dir: &Path) -> Self {
Self {
dir: dir.to_owned(),
moved: Vec::new(),
}
}
/// Once no row names the hash; runs before commit.
pub fn drop_unused(&mut self, conn: &Connection, hash: &str) -> Result<()> {
let used: bool = conn.query_row(
"SELECT EXISTS (SELECT 1 FROM messages WHERE content = ?1)",
[hash],
|row| row.get(0),
)?;
if used {
return Ok(());
}
match fs::rename(original(&self.dir, hash), parked(&self.dir, hash)) {
Ok(()) => {
self.moved.push(hash.to_owned());
Ok(())
}
Err(err) if err.kind() == ErrorKind::NotFound => {
log::warn!("mail: original {hash} was already gone");
Ok(())
}
Err(err) => Err(disk("deleting an original", err)),
}
}
/// Deletes on success; puts every file back on failure.
pub fn settle<T>(self, done: Result<T>) -> Result<T> {
match done {
Ok(value) => {
for hash in &self.moved {
if let Err(err) = fs::remove_file(parked(&self.dir, hash)) {
log::error!("mail: original {hash} stays set aside: {err}");
}
}
Ok(value)
}
Err(err) => {
let mut stuck = Vec::new();
for hash in self.moved.iter().rev() {
if let Err(back) =
fs::rename(parked(&self.dir, hash), original(&self.dir, hash))
{
stuck.push(format!("{hash}: {back}"));
}
}
if stuck.is_empty() {
Err(err)
} else {
Err(Error::Store(format!(
"{err}; originals not put back (restored at next start): {}",
stuck.join("; ")
)))
}
}
}
}
}
/// After a crash: back if named, deleted if not.
pub(super) fn recover(conn: &Connection, dir: &Path) -> Result<()> {
let mut back = 0;
let mut gone = 0;
let shards =
fs::read_dir(dir.join(CONTENT)).map_err(|err| disk("reading the originals", err))?;
for shard in shards {
let shard = shard.map_err(|err| disk("reading the originals", err))?;
let files = fs::read_dir(shard.path()).map_err(|err| disk("reading the originals", err))?;
for file in files {
let name = file
.map_err(|err| disk("reading the originals", err))?
.file_name();
let Some(hash) = name
.to_str()
.and_then(|name| name.strip_prefix('.'))
.and_then(|name| name.strip_suffix(MARK))
.filter(|hash| hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit()))
else {
continue;
};
let named: bool = conn.query_row(
"SELECT EXISTS (SELECT 1 FROM messages WHERE content = ?1)",
[hash],
|row| row.get(0),
)?;
if named {
fs::rename(parked(dir, hash), original(dir, hash))
.map_err(|err| disk("restoring an original", err))?;
back += 1;
} else {
fs::remove_file(parked(dir, hash))
.map_err(|err| disk("deleting an original", err))?;
gone += 1;
}
}
}
if back + gone > 0 {
log::warn!(
"mail: {back} originals restored and {gone} deleted after an interrupted change"
);
}
Ok(())
}
+56 -69
View File
@@ -1,9 +1,9 @@
use std::{fs, io::ErrorKind, path::Path};
use rusqlite::{Connection, OptionalExtension, Row, ToSql, Transaction, params};
use rusqlite::{OptionalExtension, Row, ToSql, Transaction, params};
use sha2::{Digest, Sha256};
use super::{CONTENT, MailboxId, MessageId, Store, disk, search};
use super::{CONTENT, MailboxId, MessageId, Store, aside::Aside, disk, search};
use crate::{Error, Mail, Mailbox, Result, read};
/// RFC 3501 §2.3.1.1: identity is mailbox, UIDVALIDITY and UID.
@@ -89,11 +89,12 @@ impl Store {
let mail = read(bytes)?;
let (content, made) = self.keep(bytes)?;
let written = self.write(mailbox, key, flags, &mail, Some(&content), existing);
if written.is_err()
&& made
&& let Err(gone) = drop_unused(&self.conn, &self.dir, &content)
{
log::error!("mail: an unused original stays after a failed write: {gone}");
if written.is_err() && made {
let mut aside = Aside::new(&self.dir);
let gone = aside.drop_unused(&self.conn, &content);
if let Err(gone) = aside.settle(gone) {
log::error!("mail: an unused original stays after a failed write: {gone}");
}
}
written
}
@@ -132,42 +133,46 @@ impl Store {
&content,
];
let tx = self.conn.transaction()?;
let mut old: Option<String> = None;
let id = match existing {
Some(id) => {
old = tx.query_row(
"SELECT content FROM messages WHERE id = ?1",
[id.0],
|row| row.get(0),
)?;
values.push(&id.0);
tx.execute(
"UPDATE messages SET message_id = ?1, in_reply_to = ?2, refs = ?3,
subject = ?4, sender = ?5, recipients = ?6, copies = ?7, date = ?8,
attachments = ?9, content = ?10 WHERE id = ?11",
values.as_slice(),
)?;
id
let mut aside = Aside::new(&self.dir);
let done = (|| -> Result<MessageId> {
let mut old: Option<String> = None;
let id = match &existing {
Some(id) => {
old = tx.query_row(
"SELECT content FROM messages WHERE id = ?1",
[id.0],
|row| row.get(0),
)?;
values.push(&id.0);
tx.execute(
"UPDATE messages SET message_id = ?1, in_reply_to = ?2, refs = ?3,
subject = ?4, sender = ?5, recipients = ?6, copies = ?7, date = ?8,
attachments = ?9, content = ?10 WHERE id = ?11",
values.as_slice(),
)?;
*id
}
None => {
values.extend::<[&dyn ToSql; 4]>([&mailbox.0, &uidvalidity, &uid, &uidl]);
tx.execute(
"INSERT INTO messages (message_id, in_reply_to, refs, subject, sender,
recipients, copies, date, attachments, content, mailbox, uidvalidity,
uid, uidl) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12,
?13, ?14)",
values.as_slice(),
)?;
MessageId(tx.last_insert_rowid())
}
};
replace_flags(&tx, id, flags)?;
search::index(&tx, id, mail, content.is_some())?;
if let Some(old) = old.filter(|old| Some(old.as_str()) != content) {
aside.drop_unused(&tx, &old)?;
}
None => {
values.extend::<[&dyn ToSql; 4]>([&mailbox.0, &uidvalidity, &uid, &uidl]);
tx.execute(
"INSERT INTO messages (message_id, in_reply_to, refs, subject, sender,
recipients, copies, date, attachments, content, mailbox, uidvalidity,
uid, uidl) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12,
?13, ?14)",
values.as_slice(),
)?;
MessageId(tx.last_insert_rowid())
}
};
replace_flags(&tx, id, flags)?;
search::index(&tx, id, mail, content.is_some())?;
if let Some(old) = old.filter(|old| Some(old.as_str()) != content) {
drop_unused(&tx, &self.dir, &old)?;
}
tx.commit()?;
Ok(id)
tx.commit()?;
Ok(id)
})();
aside.settle(done)
}
pub fn set_flags(&mut self, id: MessageId, flags: &[&str]) -> Result<()> {
@@ -205,12 +210,15 @@ impl Store {
self.writable()?;
let content = self.content(id)?;
let tx = self.conn.transaction()?;
tx.execute("DELETE FROM messages WHERE id = ?1", [id.0])?;
if let Some(hash) = content {
drop_unused(&tx, &self.dir, &hash)?;
}
tx.commit()?;
Ok(())
let mut aside = Aside::new(&self.dir);
let done = (|| -> Result<()> {
tx.execute("DELETE FROM messages WHERE id = ?1", [id.0])?;
if let Some(hash) = content {
aside.drop_unused(&tx, &hash)?;
}
Ok(tx.commit()?)
})();
aside.settle(done)
}
fn content(&self, id: MessageId) -> Result<Option<String>> {
@@ -253,27 +261,6 @@ impl Store {
}
}
/// Deletes the file once no row names it; runs before commit.
fn drop_unused(conn: &Connection, dir: &Path, hash: &str) -> Result<()> {
let used: bool = conn.query_row(
"SELECT EXISTS (SELECT 1 FROM messages WHERE content = ?1)",
[hash],
|row| row.get(0),
)?;
if used {
return Ok(());
}
let path = dir.join(CONTENT).join(&hash[..2]).join(hash);
match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(err) if err.kind() == ErrorKind::NotFound => {
log::warn!("mail: original {hash} was already gone");
Ok(())
}
Err(err) => Err(disk("deleting an original", err)),
}
}
fn replace_flags(tx: &Transaction, id: MessageId, flags: &[&str]) -> Result<()> {
tx.execute("DELETE FROM flags WHERE message = ?1", [id.0])?;
for flag in flags {
+2 -1
View File
@@ -4,7 +4,8 @@ pub(super) const STEPS: &[&str] = &[V1];
const V1: &str = "
CREATE TABLE accounts (
id INTEGER PRIMARY KEY,
address TEXT NOT NULL UNIQUE
address TEXT NOT NULL UNIQUE COLLATE NOCASE,
settings TEXT NOT NULL
);
CREATE TABLE mailboxes (
id INTEGER PRIMARY KEY,
+21 -5
View File
@@ -3,7 +3,23 @@ use std::fs;
use rusqlite::Connection;
use super::{BACKUPS, DB, open, schema::STEPS};
use crate::Error;
use crate::{Account, Auth, Error, Protocol, Security, Server};
fn account(address: &str) -> Account {
let server = Server {
host: "127.0.0.1".into(),
port: 993,
security: Security::Tls,
};
Account {
address: address.into(),
user: address.into(),
auth: Auth::Password,
protocol: Protocol::Imap,
incoming: server.clone(),
outgoing: server,
}
}
const ADD: &str = "ALTER TABLE accounts ADD COLUMN nick TEXT";
const BROKEN: &str = "ALTER TABLE nowhere ADD COLUMN nick TEXT";
@@ -36,7 +52,7 @@ fn an_upgrade_backs_up_first() {
let dir = tempfile::tempdir().unwrap();
open(dir.path(), &[STEPS[0]])
.unwrap()
.add_account("ann@example.com")
.add_account(&account("ann@example.com"))
.unwrap();
let store = open(dir.path(), &[STEPS[0], ADD]).unwrap();
assert_eq!(store.read_only(), None);
@@ -55,13 +71,13 @@ fn a_failed_upgrade_keeps_the_data_and_refuses_writes() {
let dir = tempfile::tempdir().unwrap();
open(dir.path(), &[STEPS[0]])
.unwrap()
.add_account("ann@example.com")
.add_account(&account("ann@example.com"))
.unwrap();
let store = open(dir.path(), &[STEPS[0], ADD, BROKEN]).unwrap();
let reason = store.read_only().unwrap();
assert!(reason.contains("v1 to v3"), "{reason}");
assert_eq!(store.accounts().unwrap()[0].1, "ann@example.com");
let err = store.add_account("bo@example.com").unwrap_err();
assert_eq!(store.accounts().unwrap()[0].1.address, "ann@example.com");
let err = store.add_account(&account("bo@example.com")).unwrap_err();
assert!(matches!(err, Error::ReadOnly(_)), "{err}");
drop(store);
assert_eq!(version(&dir.path().join(DB)), 1);
+4 -2
View File
@@ -93,11 +93,13 @@ impl Vault {
.map_err(|reason| Error::Vault(format!("reading {name}: {reason}")))
}
/// A refused delete keeps the session copy too.
pub fn remove(&self, name: &str) -> Result<()> {
self.session().remove(name);
self.backend
.delete(name)
.map_err(|reason| Error::Vault(format!("deleting {name}: {reason}")))
.map_err(|reason| Error::Vault(format!("deleting {name}: {reason}")))?;
self.session().remove(name);
Ok(())
}
fn session(&self) -> std::sync::MutexGuard<'_, HashMap<String, String>> {
+200
View File
@@ -0,0 +1,200 @@
mod fake;
use base64::{Engine, engine::general_purpose::STANDARD};
use ely_mail_engine::{
Account, Auth, Cached, Error, Fetched, Key, Protocol, Secret, Security, Server, Store,
};
use fake::{Certs, account, certs, expect, send, serve};
fn pop_oauth(address: &str) -> Account {
Account {
address: address.into(),
user: "bo".into(),
auth: Auth::Microsoft,
protocol: Protocol::Pop,
incoming: Server {
host: "pop.example.com".into(),
port: 995,
security: Security::Tls,
},
outgoing: Server {
host: "smtp.example.com".into(),
port: 587,
security: Security::StartTls,
},
}
}
#[test]
fn accounts_come_back_as_added() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open(dir.path()).unwrap();
let ann = account("ann@example.com");
let bo = pop_oauth("bo@example.com");
let first = store.add_account(&ann).unwrap();
let second = store.add_account(&bo).unwrap();
drop(store);
let store = Store::open(dir.path()).unwrap();
assert_eq!(store.accounts().unwrap(), [(first, ann), (second, bo)]);
}
#[test]
fn an_address_is_added_once() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open(dir.path()).unwrap();
store.add_account(&account("ann@example.com")).unwrap();
let err = store
.add_account(&pop_oauth("ANN@Example.com"))
.unwrap_err();
assert!(
matches!(&err, Error::Taken(address) if address == "ANN@Example.com"),
"{err}"
);
assert_eq!(store.accounts().unwrap().len(), 1);
}
#[test]
fn removing_an_account_keeps_what_another_shares() {
let dir = tempfile::tempdir().unwrap();
let mut store = Store::open(dir.path()).unwrap();
let ann = store.add_account(&account("ann@example.com")).unwrap();
let bo = store.add_account(&account("bo@example.com")).unwrap();
let (ann_inbox, bo_inbox) = (
store.mailbox(ann, "INBOX").unwrap(),
store.mailbox(bo, "INBOX").unwrap(),
);
let shared = b"Subject: Both\r\n\r\nshared\r\n";
let own = b"Subject: Ann only\r\n\r\nmine and mine alone\r\n";
let key = |uid| Key::Imap {
uidvalidity: 1,
uid,
};
store
.put(ann_inbox, &key(1), &[], Fetched::Whole(shared))
.unwrap();
store
.put(ann_inbox, &key(2), &[], Fetched::Whole(own))
.unwrap();
let kept = store
.put(bo_inbox, &key(1), &[], Fetched::Whole(shared))
.unwrap();
assert_eq!(
store.cached(ann).unwrap(),
Cached {
messages: 2,
bytes: own.len() as u64
}
);
store.remove_account(ann).unwrap();
assert_eq!(store.accounts().unwrap().len(), 1);
assert_eq!(store.original(kept).unwrap().unwrap(), shared);
assert_eq!(store.sizes().unwrap().originals, shared.len() as u64);
let err = store.remove_account(ann).unwrap_err();
assert!(matches!(err, Error::Store(_)), "{err}");
}
/// IMAP and SMTP scripts that log in and leave.
async fn servers(
certs: &Certs,
imap_answer: &str,
) -> (Account, Vec<tokio::task::JoinHandle<Result<(), String>>>) {
let mut imap = vec![
send("* OK ready\n"),
expect("{tag} LOGIN \"ann@example.com\" \"pw\""),
send(imap_answer),
];
if imap_answer.contains(" OK ") {
imap.extend([expect("{tag} LOGOUT"), send("* BYE\n{tag} OK bye\n")]);
}
let (incoming, imap) = serve(certs, Security::Tls, imap).await;
let smtp = 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"),
];
let (outgoing, smtp) = serve(certs, Security::Tls, smtp).await;
let account = Account {
incoming,
outgoing,
..account("ann@example.com")
};
(account, vec![imap, smtp])
}
#[tokio::test]
async fn a_check_logs_in_to_both_servers() {
let certs = certs();
let (account, scripts) = servers(&certs, "{tag} OK in\n").await;
let checked = account
.check(Secret::Password("pw".into()), &certs.trusted)
.await;
assert!(checked.passed());
for script in scripts {
script.await.unwrap().unwrap();
}
}
#[tokio::test]
async fn each_server_answers_for_itself() {
let certs = certs();
let (account, scripts) =
servers(&certs, "{tag} NO [AUTHENTICATIONFAILED] bad password\n").await;
let checked = account
.check(Secret::Password("pw".into()), &certs.trusted)
.await;
assert!(!checked.passed());
match checked.incoming {
Err(Error::Rejected(text)) => assert!(text.contains("bad password"), "{text}"),
other => panic!("incoming: {:?}", other.err()),
}
checked.outgoing.unwrap();
for script in scripts {
script.await.unwrap().unwrap();
}
}
#[test]
fn what_no_server_could_carry_is_refused() {
account("ann@example.com").valid().unwrap();
let broken = [
Account {
address: "ann".into(),
..account("ann@example.com")
},
Account {
user: String::new(),
..account("ann@example.com")
},
Account {
user: "ann\r\nRSET".into(),
..account("ann@example.com")
},
Account {
incoming: Server {
host: "imap example.com".into(),
port: 993,
security: Security::Tls,
},
..account("ann@example.com")
},
Account {
outgoing: Server {
host: "smtp.example.com".into(),
port: 0,
security: Security::Tls,
},
..account("ann@example.com")
},
];
for account in broken {
let err = account.valid().unwrap_err();
assert!(matches!(err, Error::Invalid(_)), "{err}");
}
}
+73
View File
@@ -0,0 +1,73 @@
mod fake;
use std::{fs, path::Path};
use ely_mail_engine::{Fetched, Key, Store};
use fake::account;
use sha2::{Digest, Sha256};
fn hash(bytes: &[u8]) -> String {
Sha256::digest(bytes)
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
fn parked(dir: &Path, hash: &str) -> std::path::PathBuf {
dir.join("content")
.join(&hash[..2])
.join(format!(".{hash}.gone"))
}
fn key(uid: u32) -> Key {
Key::Imap {
uidvalidity: 1,
uid,
}
}
#[test]
fn a_removal_that_fails_midway_keeps_every_original() {
let dir = tempfile::tempdir().unwrap();
let mut store = Store::open(dir.path()).unwrap();
let ann = store.add_account(&account("ann@example.com")).unwrap();
let inbox = store.mailbox(ann, "INBOX").unwrap();
let one: &[u8] = b"Subject: One\r\n\r\nfirst\r\n";
let two: &[u8] = b"Subject: Two\r\n\r\nsecond\r\n";
let a = store.put(inbox, &key(1), &[], Fetched::Whole(one)).unwrap();
let b = store.put(inbox, &key(2), &[], Fetched::Whole(two)).unwrap();
let last = hash(one).max(hash(two));
fs::create_dir(parked(dir.path(), &last)).unwrap();
store.remove_account(ann).unwrap_err();
assert_eq!(store.accounts().unwrap().len(), 1);
assert_eq!(store.original(a).unwrap().unwrap(), one);
assert_eq!(store.original(b).unwrap().unwrap(), two);
fs::remove_dir(parked(dir.path(), &last)).unwrap();
store.remove_account(ann).unwrap();
assert_eq!(store.sizes().unwrap().originals, 0);
}
#[test]
fn a_restart_puts_back_what_a_crash_left_aside() {
let dir = tempfile::tempdir().unwrap();
let mut store = Store::open(dir.path()).unwrap();
let ann = store.add_account(&account("ann@example.com")).unwrap();
let inbox = store.mailbox(ann, "INBOX").unwrap();
let kept: &[u8] = b"Subject: Kept\r\n\r\nstill named\r\n";
let id = store
.put(inbox, &key(1), &[], Fetched::Whole(kept))
.unwrap();
drop(store);
let named = hash(kept);
let original = dir.path().join("content").join(&named[..2]).join(&named);
fs::rename(&original, parked(dir.path(), &named)).unwrap();
let orphan = hash(b"nobody names this");
let shard = dir.path().join("content").join(&orphan[..2]);
fs::create_dir_all(&shard).unwrap();
fs::write(parked(dir.path(), &orphan), b"nobody names this").unwrap();
let store = Store::open(dir.path()).unwrap();
assert_eq!(store.original(id).unwrap().unwrap(), kept);
assert!(!parked(dir.path(), &named).exists());
assert!(!parked(dir.path(), &orphan).exists());
assert_eq!(store.sizes().unwrap().originals, kept.len() as u64);
}
+18 -1
View File
@@ -5,7 +5,7 @@ pub mod smtp;
use std::sync::Arc;
use ely_mail_engine::{Login, Secret, Security, Server, TlsConnector};
use ely_mail_engine::{Account, Auth, Login, Protocol, Secret, Security, Server, TlsConnector};
use rcgen::{CertificateParams, KeyPair};
use tokio::{
io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader},
@@ -78,6 +78,23 @@ pub fn certs() -> Certs {
}
}
/// An IMAP account on the test address.
pub fn account(address: &str) -> Account {
let server = |port| Server {
host: "127.0.0.1".into(),
port,
security: Security::Tls,
};
Account {
address: address.into(),
user: address.into(),
auth: Auth::Password,
protocol: Protocol::Imap,
incoming: server(993),
outgoing: server(465),
}
}
pub fn login(secret: Secret) -> Login {
Login {
user: "ann@example.com".into(),
+5 -1
View File
@@ -1,3 +1,5 @@
mod fake;
use std::path::Path;
use ely_mail_engine::{Error, Fetched, Key, MailboxId, MessageId, Store};
@@ -23,7 +25,9 @@ fn headers(raw: &[u8]) -> &[u8] {
fn inbox(dir: &Path) -> (Store, MailboxId) {
let store = Store::open(dir).unwrap();
let account = store.add_account("ann@example.com").unwrap();
let account = store
.add_account(&fake::account("ann@example.com"))
.unwrap();
let inbox = store.mailbox(account, "INBOX").unwrap();
(store, inbox)
}
@@ -1,5 +1,7 @@
#![cfg(windows)]
mod fake;
use std::{fs::File, os::windows::fs::OpenOptionsExt, path::Path};
use ely_mail_engine::{Fetched, Key, MailboxId, Store};
@@ -10,7 +12,9 @@ const TWO: &[u8] = b"Subject: two\r\n\r\nsecond body\r\n";
fn inbox(dir: &Path) -> (Store, MailboxId) {
let store = Store::open(dir).unwrap();
let account = store.add_account("ann@example.com").unwrap();
let account = store
.add_account(&fake::account("ann@example.com"))
.unwrap();
let inbox = store.mailbox(account, "INBOX").unwrap();
(store, inbox)
}
+5 -1
View File
@@ -1,3 +1,5 @@
mod fake;
use std::path::Path;
use ely_mail_engine::{Error, Fetched, Key, MailboxId, MessageId, Store};
@@ -17,7 +19,9 @@ fn sample() -> Vec<u8> {
fn inbox(dir: &Path) -> (Store, MailboxId) {
let store = Store::open(dir).unwrap();
let account = store.add_account("ann@example.com").unwrap();
let account = store
.add_account(&fake::account("ann@example.com"))
.unwrap();
let inbox = store.mailbox(account, "INBOX").unwrap();
(store, inbox)
}
+4 -3
View File
@@ -67,9 +67,10 @@ fn a_refused_store_keeps_the_secret_for_this_session() {
assert!(matches!(err, Error::Vault(text) if text.contains("locked")));
let err = vault.remove("a").err().unwrap();
assert!(matches!(err, Error::Vault(_)));
assert!(
vault.get("a").is_err(),
"the session copy is gone after remove"
assert_eq!(
vault.get("a").unwrap().as_deref(),
Some("pw"),
"a failed remove keeps the session copy"
);
}
+3
View File
@@ -4,6 +4,7 @@ mod analysis;
mod calc;
mod data;
mod doc;
mod mail;
mod mark;
mod mark_menus;
mod motion;
@@ -165,6 +166,7 @@ fn catalogs() -> (Catalog, Catalog) {
.chain(office::EN)
.chain(doc::EN)
.chain(refs::EN)
.chain(mail::EN)
.chain(tools::EN)
.chain(table::EN)
.chain(calc::EN)
@@ -189,6 +191,7 @@ fn catalogs() -> (Catalog, Catalog) {
.chain(office::ZH_CN)
.chain(doc::ZH_CN)
.chain(refs::ZH_CN)
.chain(mail::ZH_CN)
.chain(tools::ZH_CN)
.chain(table::ZH_CN)
.chain(calc::ZH_CN)
+215
View File
@@ -0,0 +1,215 @@
//! ElyMail's accounts.
pub(super) const EN: &[(&str, &str)] = &[
("mail.menu.account", "Account"),
("mail.add.open", "Add Account…"),
("mail.remove.open", "Remove Account…"),
("mail.cancel", "Cancel"),
("mail.empty", "No mail accounts yet"),
("mail.accounts", "Accounts"),
("mail.add.title", "Add Account"),
("mail.kind.gmail", "Gmail"),
("mail.kind.microsoft", "Microsoft"),
("mail.kind.icloud", "iCloud"),
("mail.kind.imap", "IMAP"),
("mail.kind.pop", "POP3"),
("mail.add.address", "Email address"),
("mail.add.address_hint", "Email address (optional)"),
("mail.add.user", "User name"),
("mail.add.password", "Password"),
("mail.add.incoming", "Incoming server"),
("mail.add.outgoing", "Outgoing server (SMTP)"),
("mail.add.port", "Port"),
("mail.add.security", "Security"),
("mail.security.tls", "TLS"),
("mail.security.starttls", "STARTTLS"),
("mail.auth.title", "Sign-in"),
("mail.auth.password", "Password"),
("mail.auth.google", "Google"),
("mail.auth.microsoft", "Microsoft"),
(
"mail.icloud.steps",
"iCloud needs an app-specific password: sign in to your Apple Account, open Sign-In and Security, choose App-Specific Passwords, make one and paste it below.",
),
("mail.icloud.open", "Open Apple Account"),
("mail.icloud.password", "App-specific password"),
("mail.add.check", "Check"),
("mail.add.sign_in", "Sign In with {method}"),
("mail.add.save", "Add Account"),
("mail.add.signing", "Finish signing in in your browser."),
("mail.add.checking", "Checking both servers…"),
("mail.add.saving", "Saving…"),
("mail.check.incoming", "Incoming server: {result}"),
("mail.check.outgoing", "Outgoing server: {result}"),
("mail.check.passed", "signed in"),
("mail.add.need_address", "Type the email address."),
("mail.add.need_user", "Type the user name."),
("mail.add.need_password", "Type the password."),
("mail.add.need_host", "Type both server names."),
("mail.add.bad_port", "{port} is not a port; use 1 to 65535."),
("mail.add.invalid", "These settings cannot be used: {error}"),
("mail.add.taken", "{address} is already added."),
(
"mail.add.unavailable.google",
"Gmail sign-in is not in this build: it was built without a Google client ID.",
),
(
"mail.add.unavailable.microsoft",
"Microsoft sign-in is not in this build: it was built without a Microsoft client ID.",
),
("mail.add.sign_in_failed", "Sign-in did not finish: {error}"),
("mail.add.check_failed", "The check did not finish: {error}"),
("mail.add.save_failed", "The account was not saved: {error}"),
("mail.add.added", "{address} added."),
(
"mail.add.session_only",
"The system keychain refused the password, so it is kept only until ElyMail quits: {error}",
),
("mail.error.connect", "cannot connect ({detail})"),
(
"mail.error.tls_failed",
"the secure connection failed ({detail})",
),
(
"mail.error.rejected",
"the server refused the sign-in: {detail}",
),
("mail.error.server", "the server refused: {detail}"),
(
"mail.error.protocol",
"the server's reply cannot be read: {detail}",
),
("mail.error.timeout", "no answer while {detail}"),
("mail.error.other", "{detail}"),
(
"mail.error.tls",
"Secure connections are not available: {error}",
),
("mail.error.store", "The mail store is not open: {error}"),
("mail.store.unopened", "The mail store did not open"),
("mail.store.unread", "The accounts could not be read"),
(
"mail.store.read_only",
"The mail store is read-only, so nothing can be added or removed: {error}",
),
("mail.account.line", "{protocol} · {host}"),
("mail.account.server", "{host}:{port}, {security}"),
("mail.account.address", "Address"),
("mail.account.user", "User name"),
("mail.account.incoming", "Incoming"),
("mail.account.outgoing", "Outgoing"),
("mail.account.auth", "Sign-in"),
("mail.remove.title", "Remove {address}?"),
(
"mail.remove.message",
"This removes from this computer the {n} messages kept for it ({size}), its drafts, and its saved password or sign-in. Mail on the server is not touched.",
),
(
"mail.remove.message.one",
"This removes from this computer the 1 message kept for it ({size}), its drafts, and its saved password or sign-in. Mail on the server is not touched.",
),
("mail.remove.go", "Remove Account"),
("mail.remove.done", "{address} removed."),
("mail.remove.failed", "The account was not removed: {error}"),
];
pub(super) const ZH_CN: &[(&str, &str)] = &[
("mail.menu.account", "账号"),
("mail.add.open", "添加账号…"),
("mail.remove.open", "删除账号…"),
("mail.cancel", "取消"),
("mail.empty", "还没有邮件账号"),
("mail.accounts", "账号"),
("mail.add.title", "添加账号"),
("mail.kind.gmail", "Gmail"),
("mail.kind.microsoft", "Microsoft"),
("mail.kind.icloud", "iCloud"),
("mail.kind.imap", "IMAP"),
("mail.kind.pop", "POP3"),
("mail.add.address", "邮箱地址"),
("mail.add.address_hint", "邮箱地址(可不填)"),
("mail.add.user", "用户名"),
("mail.add.password", "密码"),
("mail.add.incoming", "收信服务器"),
("mail.add.outgoing", "发信服务器(SMTP)"),
("mail.add.port", "端口"),
("mail.add.security", "加密"),
("mail.security.tls", "TLS"),
("mail.security.starttls", "STARTTLS"),
("mail.auth.title", "登录方式"),
("mail.auth.password", "密码"),
("mail.auth.google", "Google"),
("mail.auth.microsoft", "Microsoft"),
(
"mail.icloud.steps",
"iCloud 须用应用专用密码:登录 Apple 账户,打开“登录与安全”,选“应用专用密码”,生成一个,粘贴到下面。",
),
("mail.icloud.open", "打开 Apple 账户"),
("mail.icloud.password", "应用专用密码"),
("mail.add.check", "检查"),
("mail.add.sign_in", "以 {method} 登录"),
("mail.add.save", "添加账号"),
("mail.add.signing", "请在浏览器中完成登录。"),
("mail.add.checking", "正在检查收发两个服务器…"),
("mail.add.saving", "正在保存…"),
("mail.check.incoming", "收信服务器:{result}"),
("mail.check.outgoing", "发信服务器:{result}"),
("mail.check.passed", "已登录"),
("mail.add.need_address", "请填写邮箱地址。"),
("mail.add.need_user", "请填写用户名。"),
("mail.add.need_password", "请填写密码。"),
("mail.add.need_host", "请填写两个服务器名。"),
("mail.add.bad_port", "{port} 不是端口,请填 1 至 65535。"),
("mail.add.invalid", "这些设置用不了:{error}"),
("mail.add.taken", "{address} 已经添加过。"),
(
"mail.add.unavailable.google",
"本构建没有 Gmail 登录:构建时未带 Google 客户端 ID。",
),
(
"mail.add.unavailable.microsoft",
"本构建没有 Microsoft 登录:构建时未带 Microsoft 客户端 ID。",
),
("mail.add.sign_in_failed", "登录没有完成:{error}"),
("mail.add.check_failed", "检查没有完成:{error}"),
("mail.add.save_failed", "账号没有保存:{error}"),
("mail.add.added", "已添加 {address}。"),
(
"mail.add.session_only",
"系统钥匙串拒绝了密码,它只保留到 ElyMail 退出:{error}",
),
("mail.error.connect", "连不上({detail})"),
("mail.error.tls_failed", "安全连接失败({detail})"),
("mail.error.rejected", "服务器拒绝登录:{detail}"),
("mail.error.server", "服务器拒绝:{detail}"),
("mail.error.protocol", "读不懂服务器的回复:{detail}"),
("mail.error.timeout", "{detail}时没有回应"),
("mail.error.other", "{detail}"),
("mail.error.tls", "无法建立安全连接:{error}"),
("mail.error.store", "邮件存储没有打开:{error}"),
("mail.store.unopened", "邮件存储打不开"),
("mail.store.unread", "读不出账号"),
(
"mail.store.read_only",
"邮件存储为只读,不能添加或删除:{error}",
),
("mail.account.line", "{protocol} · {host}"),
("mail.account.server", "{host}:{port},{security}"),
("mail.account.address", "地址"),
("mail.account.user", "用户名"),
("mail.account.incoming", "收信"),
("mail.account.outgoing", "发信"),
("mail.account.auth", "登录方式"),
("mail.remove.title", "删除 {address}?"),
(
"mail.remove.message",
"将从本机删去它的 {n} 封缓存邮件({size})、草稿与保存的密码或登录。服务器上的邮件不动。",
),
(
"mail.remove.message.one",
"将从本机删去它的 1 封缓存邮件({size})、草稿与保存的密码或登录。服务器上的邮件不动。",
),
("mail.remove.go", "删除账号"),
("mail.remove.done", "已删除 {address}。"),
("mail.remove.failed", "账号没有删除:{error}"),
];