Phase 8 begins: mail, the Notifications page and a test mail
CI / secret scan (push) Successful in 8s
CI / fmt, clippy, tests (push) Successful in 1m50s
CI / release (push) Skipped

The app sends mail by SMTP submission (src/mail.rs, lettre over rustls
with the system's CA bundle, ring as reqwest): VISA_SMTP_HOST, _PORT
(465), _SECURITY (tls, starttls, or none for a server on this machine),
_USER and the password from VISA_SMTP_PASSWORD_FILE or the credential
smtp-password; VISA_MAIL_FROM defaults to "Lanna Desk <user>",
VISA_MAIL_REPLY_TO is optional. Without VISA_SMTP_HOST mail is off. The
settings are checked at start; the password stays out of Debug.

The Notifications page (Office) shows the sender, server and connection,
sends a test mail to the address given (offered again next time) and
shows the mail server's answer; every message sent or failed is logged
(notifications, migration 0011). Text messages say "not yet".

Tests: a fake SMTP server checks the envelope, Subject and Reply-To, a
refused recipient logged as failed, a bad address and mail switched off.
121 unit, 65 integration.
This commit is contained in:
grabowski committed 2026-11-22 22:18:02 +07:00
1 parent 9ae4d7bd07
commit 2e465a463c
15 files changed
+902 -1

No files matched your search

+190
View File
@@ -0,0 +1,190 @@
//! The Notifications page: the test mail goes through a mail server (here a
//! small fake one on this machine), and every try is in the log.
use std::sync::{Arc, Mutex};
use axum::http::StatusCode;
use sqlx::PgPool;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
use visa::config::{Auth, Config, MailConfig, MailSecurity};
use crate::common::{config, local, with_config};
/// What the fake server received: the envelope and the message.
#[derive(Debug, Default, Clone)]
struct Got {
from: String,
to: Vec<String>,
data: String,
}
/// A mail server that speaks just enough SMTP, takes any mail and refuses
/// recipients at refused.example; returns its port and what it got.
async fn fake_smtp() -> (u16, Arc<Mutex<Vec<Got>>>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let got = Arc::new(Mutex::new(Vec::new()));
let store = got.clone();
tokio::spawn(async move {
loop {
let Ok((sock, _)) = listener.accept().await else {
return;
};
let store = store.clone();
tokio::spawn(async move {
let (r, mut w) = sock.into_split();
let mut lines = BufReader::new(r).lines();
let mut cur = Got::default();
w.write_all(b"220 fake ESMTP\r\n").await.unwrap();
while let Ok(Some(l)) = lines.next_line().await {
let up = l.to_uppercase();
let answer = if up.starts_with("EHLO") {
"250-fake\r\n250 8BITMIME".to_string()
} else if up.starts_with("MAIL FROM:") {
cur.from = l[10..].to_string();
"250 2.1.0 Ok".into()
} else if up.starts_with("RCPT TO:") {
if l.contains("refused.example") {
"550 5.1.1 <nobody@refused.example>: Recipient address rejected".into()
} else {
cur.to.push(l[8..].to_string());
"250 2.1.5 Ok".into()
}
} else if up == "DATA" {
w.write_all(b"354 End data with <CR><LF>.<CR><LF>\r\n")
.await
.unwrap();
while let Ok(Some(d)) = lines.next_line().await {
if d == "." {
break;
}
cur.data.push_str(&d);
cur.data.push('\n');
}
store.lock().unwrap().push(std::mem::take(&mut cur));
"250 2.0.0 Ok: queued as FAKE1".into()
} else if up == "QUIT" {
w.write_all(b"221 2.0.0 Bye\r\n").await.unwrap();
return;
} else {
"250 Ok".into()
};
w.write_all(format!("{answer}\r\n").as_bytes())
.await
.unwrap();
}
});
}
});
(port, got)
}
fn with_mail(port: u16) -> Config {
Config {
mail: Some(MailConfig {
host: "127.0.0.1".into(),
port,
security: MailSecurity::None,
user: String::new(),
password: None,
from: "Lanna Desk <reminders@lannadesk.com>".into(),
reply_to: Some("contact@lannadesk.com".into()),
}),
..config(Auth::Disabled)
}
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn a_test_mail_goes_out_and_into_the_log(pool: PgPool) {
let (port, got) = fake_smtp().await;
let app = with_config(pool.clone(), with_mail(port));
let page = app.get("/notifications").await;
assert_eq!(page.status, StatusCode::OK);
let t = page.text();
assert!(
t.contains("Lanna Desk &lt;reminders@lannadesk.com&gt;"),
"{t}"
);
assert!(t.contains(&format!("127.0.0.1:{port}")), "{t}");
assert!(t.contains("Nothing sent yet"), "{t}");
let r = app
.post("/notifications/test-email", &[("to", "alex@buildfor.life")])
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text());
assert!(
r.location().starts_with("/notifications?sent="),
"{}",
r.location()
);
let mails = got.lock().unwrap().clone();
assert_eq!(mails.len(), 1);
let m = &mails[0];
assert_eq!(m.from, "<reminders@lannadesk.com>");
assert_eq!(m.to, ["<alex@buildfor.life>"]);
assert!(
m.data.contains("Subject: Test from Lanna Desk"),
"{}",
m.data
);
assert!(
m.data.contains("Reply-To: contact@lannadesk.com"),
"{}",
m.data
);
assert!(m.data.contains("local sent it on"), "{}", m.data);
let shown = app.get(r.location()).await.text();
assert!(shown.contains("The test mail went out"), "{shown}");
assert!(shown.contains("queued as FAKE1"), "{shown}");
assert!(
shown.contains("value=\"alex@buildfor.life\""),
"the address is offered again"
);
// a refused recipient is a failure, logged with the server's words
let r = app
.post(
"/notifications/test-email",
&[("to", "nobody@refused.example")],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
let shown = app.get(r.location()).await.text();
assert!(shown.contains("The test mail did not go out"), "{shown}");
assert!(shown.contains("Recipient address rejected"), "{shown}");
let logged: Vec<(String, String)> =
sqlx::query_as("SELECT status, recipient FROM notifications ORDER BY id")
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(
logged,
[
("sent".into(), "alex@buildfor.life".into()),
("failed".into(), "nobody@refused.example".into())
]
);
// not an address: asked again, nothing sent
let r = app
.post("/notifications/test-email", &[("to", "alex at buildfor")])
.await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
assert!(r.text().contains("Enter one email address"));
assert_eq!(got.lock().unwrap().len(), 1);
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn without_a_mail_server_the_page_says_so(pool: PgPool) {
let app = local(pool.clone());
let t = app.get("/notifications").await.text();
assert!(t.contains("not set up"), "{t}");
assert!(!t.contains("id=\"send-test\""), "{t}");
let r = app
.post("/notifications/test-email", &[("to", "alex@buildfor.life")])
.await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
assert!(r.text().contains("Mail is not set up on this server"));
}