Every day from 07:00 Chiang Mai time the app mails the journal's last entry number and its hash to the addresses set on the Notifications page (src/anchor.rs, migration 0012: settings, journal_anchors), when anything was added since the last anchor that went out. A day without news is noted without a mail; a failed send is tried again after an hour; a transaction-level advisory lock keeps two runs from both sending. "Send the anchor now" sends at once. Each mail says whether the chain checked whole (in capitals when it did not) and links to /journal/anchor, which compares a kept entry number and hash with the journal now: the same hash, another one, or no such entry. Changing the recipients is itself a journal entry. Every anchor mail is in the notifications log. Tests: the daily rule (before seven, once a day, an hour after a failure), recipients checked and journaled, one mail per recipient with the head hash, unchanged days, by hand, the check page's three answers, and a chain broken around the app said in the mail. 126 unit, 67 integration.
185 lines
5.8 KiB
Rust
185 lines
5.8 KiB
Rust
//! Mail from the app: SMTP submission to the fleet's mail server as the
|
|
//! mailbox `reminders@lannadesk.com` (phase 8). Every mail sent or failed
|
|
//! is written to the notifications log, so the office sees what went out.
|
|
|
|
use std::time::Duration;
|
|
|
|
use anyhow::{Context, Result};
|
|
use lettre::message::Mailbox;
|
|
use lettre::message::header::ContentType;
|
|
use lettre::transport::smtp::authentication::Credentials;
|
|
use lettre::transport::smtp::client::{Tls, TlsParameters};
|
|
use lettre::transport::smtp::extension::ClientId;
|
|
use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
|
|
use serde::Serialize;
|
|
use sqlx::PgPool;
|
|
|
|
use crate::config::{MailConfig, MailSecurity};
|
|
|
|
/// The sender and the reply address parse as addresses.
|
|
pub fn check_addresses(cfg: &MailConfig) -> Result<()> {
|
|
cfg.from
|
|
.parse::<Mailbox>()
|
|
.with_context(|| format!("VISA_MAIL_FROM is not an address: {}", cfg.from))?;
|
|
if let Some(r) = &cfg.reply_to {
|
|
r.parse::<Mailbox>()
|
|
.with_context(|| format!("VISA_MAIL_REPLY_TO is not an address: {r}"))?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Whether a recipient's address is one mail can go to.
|
|
pub fn valid_address(addr: &str) -> bool {
|
|
let a = addr.trim();
|
|
a.len() <= 254 && a.parse::<Mailbox>().is_ok() && a.contains('@') && !a.contains('<')
|
|
}
|
|
|
|
/// The name this machine gives the mail server: the app's public host.
|
|
pub fn hello_name(public_url: &str) -> String {
|
|
public_url
|
|
.split("://")
|
|
.nth(1)
|
|
.unwrap_or("localhost")
|
|
.split(['/', ':'])
|
|
.next()
|
|
.filter(|h| !h.is_empty())
|
|
.unwrap_or("localhost")
|
|
.to_string()
|
|
}
|
|
|
|
/// A plain-text mail.
|
|
pub struct Outgoing<'a> {
|
|
pub to: &'a str,
|
|
pub subject: &'a str,
|
|
pub text: &'a str,
|
|
}
|
|
|
|
/// Sends one mail; Ok holds the server's answer ("2.0.0 Ok: queued as …").
|
|
/// `hello` names this machine to the server: the app's public name.
|
|
pub async fn send(cfg: &MailConfig, hello: &str, mail: &Outgoing<'_>) -> Result<String> {
|
|
let mut builder = Message::builder()
|
|
.from(cfg.from.parse()?)
|
|
.to(mail.to.trim().parse().context("not an email address")?)
|
|
.subject(mail.subject)
|
|
.header(ContentType::TEXT_PLAIN);
|
|
if let Some(r) = &cfg.reply_to {
|
|
builder = builder.reply_to(r.parse()?);
|
|
}
|
|
let message = builder.body(mail.text.to_string())?;
|
|
let tls = || TlsParameters::new(cfg.host.clone());
|
|
let mut transport = AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&cfg.host)
|
|
.port(cfg.port)
|
|
.hello_name(ClientId::Domain(hello.to_string()))
|
|
.timeout(Some(Duration::from_secs(20)))
|
|
.tls(match cfg.security {
|
|
MailSecurity::Tls => Tls::Wrapper(tls()?),
|
|
MailSecurity::StartTls => Tls::Required(tls()?),
|
|
MailSecurity::None => Tls::None,
|
|
});
|
|
if let Some(p) = &cfg.password {
|
|
transport = transport.credentials(Credentials::new(cfg.user.clone(), p.clone()));
|
|
}
|
|
let answer = transport
|
|
.build()
|
|
.send(message)
|
|
.await
|
|
.with_context(|| format!("sending through {}:{}", cfg.host, cfg.port))?;
|
|
Ok(answer.message().collect::<Vec<_>>().join(" "))
|
|
}
|
|
|
|
/// One line of the notifications log.
|
|
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
|
|
pub struct Logged {
|
|
pub id: i64,
|
|
pub channel: String,
|
|
pub purpose: String,
|
|
pub recipient: String,
|
|
pub subject: String,
|
|
pub status: String,
|
|
pub detail: String,
|
|
pub actor: String,
|
|
pub created_at: chrono::DateTime<chrono::Utc>,
|
|
}
|
|
|
|
/// What a notification was and how it went, for the log.
|
|
pub struct Entry<'a> {
|
|
pub channel: &'a str,
|
|
pub purpose: &'a str,
|
|
pub recipient: &'a str,
|
|
pub subject: &'a str,
|
|
pub result: &'a Result<String>,
|
|
pub actor: &'a str,
|
|
}
|
|
|
|
pub async fn log(db: &PgPool, e: &Entry<'_>) -> Result<i64> {
|
|
let (status, detail) = match e.result {
|
|
Ok(answer) => ("sent", answer.clone()),
|
|
Err(err) => ("failed", format!("{err:#}")),
|
|
};
|
|
let detail: String = detail.chars().take(1000).collect();
|
|
Ok(sqlx::query_scalar(
|
|
"INSERT INTO notifications (channel, purpose, recipient, subject, status, detail, actor) \
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id",
|
|
)
|
|
.bind(e.channel)
|
|
.bind(e.purpose)
|
|
.bind(e.recipient.trim())
|
|
.bind(e.subject)
|
|
.bind(status)
|
|
.bind(detail)
|
|
.bind(e.actor)
|
|
.fetch_one(db)
|
|
.await?)
|
|
}
|
|
|
|
pub async fn recent(db: &PgPool, limit: i64) -> Result<Vec<Logged>> {
|
|
Ok(
|
|
sqlx::query_as("SELECT * FROM notifications ORDER BY id DESC LIMIT $1")
|
|
.bind(limit)
|
|
.fetch_all(db)
|
|
.await?,
|
|
)
|
|
}
|
|
|
|
pub async fn get(db: &PgPool, id: i64) -> Result<Option<Logged>> {
|
|
Ok(sqlx::query_as("SELECT * FROM notifications WHERE id = $1")
|
|
.bind(id)
|
|
.fetch_optional(db)
|
|
.await?)
|
|
}
|
|
|
|
/// The address someone last sent a test to, to offer it again.
|
|
pub async fn last_test_address(db: &PgPool, actor: &str) -> Result<Option<String>> {
|
|
Ok(sqlx::query_scalar(
|
|
"SELECT recipient FROM notifications WHERE actor = $1 AND channel = 'email' \
|
|
AND purpose = 'test' ORDER BY id DESC LIMIT 1",
|
|
)
|
|
.bind(actor)
|
|
.fetch_optional(db)
|
|
.await?)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn addresses_are_checked() {
|
|
assert!(valid_address("alex@buildfor.life"));
|
|
assert!(valid_address(" contact@lannadesk.com "));
|
|
assert!(!valid_address("alex"));
|
|
assert!(
|
|
!valid_address("Alex <alex@buildfor.life>"),
|
|
"the address only"
|
|
);
|
|
assert!(!valid_address("a@b@c"));
|
|
}
|
|
|
|
#[test]
|
|
fn the_server_hears_the_public_name() {
|
|
assert_eq!(hello_name("https://app.lannadesk.com"), "app.lannadesk.com");
|
|
assert_eq!(hello_name("http://127.0.0.1:8040"), "127.0.0.1");
|
|
assert_eq!(hello_name("nonsense"), "localhost");
|
|
}
|
|
}
|