A run that was not due dropped its transaction, and sqlx rolls a dropped one back only when the connection is returned, from a background task. Until then the advisory lock stays taken, so a run right after it (the test's next call on a busy CI runner; on the server a tick that comes at the wrong moment) found the lock taken and skipped. Every way out of run_daily now rolls back explicitly (sending happens on the pool; the transaction only holds the lock). The test checks from a connection of its own that no lock is left after a run that sent nothing.
421 lines
14 KiB
Rust
421 lines
14 KiB
Rust
//! 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 <reminders@lannadesk.com>"),
|
|
"{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"));
|
|
}
|
|
|
|
/// A mail's text as the reader sees it: quoted-printable decoded (lettre
|
|
/// encodes long lines so).
|
|
fn readable(data: &str) -> String {
|
|
let joined = data.replace("=\n", "");
|
|
let b = joined.as_bytes();
|
|
let mut out = Vec::new();
|
|
let mut i = 0;
|
|
while i < b.len() {
|
|
if b[i] == b'='
|
|
&& i + 2 < b.len()
|
|
&& let Ok(v) = u8::from_str_radix(&joined[i + 1..i + 3], 16)
|
|
{
|
|
out.push(v);
|
|
i += 3;
|
|
continue;
|
|
}
|
|
out.push(b[i]);
|
|
i += 1;
|
|
}
|
|
String::from_utf8_lossy(&out).into_owned()
|
|
}
|
|
|
|
/// Chiang Mai time on Nov 22, 2026 plus `days`.
|
|
fn cm(days: i64, h: u32, m: u32) -> chrono::DateTime<chrono::Utc> {
|
|
use chrono::TimeZone;
|
|
visa::dates::bangkok()
|
|
.with_ymd_and_hms(2026, 11, 22, h, m, 0)
|
|
.unwrap()
|
|
.with_timezone(&chrono::Utc)
|
|
+ chrono::Duration::days(days)
|
|
}
|
|
|
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
|
async fn the_journal_anchor_goes_out_daily_and_checks_later(pool: PgPool) {
|
|
let (port, got) = fake_smtp().await;
|
|
let cfg = with_mail(port);
|
|
let app = with_config(pool.clone(), cfg.clone());
|
|
let r = app
|
|
.post(
|
|
"/lawyers",
|
|
&[("name", "Malee Rakdee"), ("status", "active")],
|
|
)
|
|
.await;
|
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
|
|
|
// nobody to send to yet: the day's run does nothing
|
|
let out = visa::anchor::run_daily(&cfg, &pool, cm(0, 7, 5))
|
|
.await
|
|
.unwrap();
|
|
assert!(
|
|
matches!(out, Some(visa::anchor::Outcome::Nothing(_))),
|
|
"{out:?}"
|
|
);
|
|
sqlx::query("DELETE FROM journal_anchors")
|
|
.execute(&pool)
|
|
.await
|
|
.unwrap();
|
|
|
|
// the recipients: checked, saved, and the change is in the journal
|
|
let r = app
|
|
.post(
|
|
"/notifications/anchor-to",
|
|
&[("anchor_to", "lead@example.com, nope")],
|
|
)
|
|
.await;
|
|
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
|
assert!(
|
|
r.text().contains("Not an email address: nope."),
|
|
"{}",
|
|
r.text()
|
|
);
|
|
let r = app
|
|
.post(
|
|
"/notifications/anchor-to",
|
|
&[("anchor_to", "lead@example.com, archive@example.org")],
|
|
)
|
|
.await;
|
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
|
let said: String =
|
|
sqlx::query_scalar("SELECT detail FROM journal WHERE event = 'anchor recipients changed'")
|
|
.fetch_one(&pool)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(
|
|
said,
|
|
"The journal's daily anchor goes to lead@example.com, archive@example.org (before: nobody)."
|
|
);
|
|
let page = app.get("/notifications").await.text();
|
|
assert!(
|
|
page.contains("value=\"lead@example.com, archive@example.org\""),
|
|
"{page}"
|
|
);
|
|
|
|
// before seven nothing goes; at seven one mail to each, with the head
|
|
assert!(
|
|
visa::anchor::run_daily(&cfg, &pool, cm(0, 6, 50))
|
|
.await
|
|
.unwrap()
|
|
.is_none()
|
|
);
|
|
// a run that sends nothing lets go of its lock before it returns, as a
|
|
// connection of its own (another run's) sees it
|
|
let mut other = <sqlx::PgConnection as sqlx::Connection>::connect_with(&pool.connect_options())
|
|
.await
|
|
.unwrap();
|
|
let held: i64 = sqlx::query_scalar(
|
|
"SELECT count(*) FROM pg_locks WHERE locktype = 'advisory' \
|
|
AND database = (SELECT oid FROM pg_database WHERE datname = current_database())",
|
|
)
|
|
.fetch_one(&mut other)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(held, 0, "the anchor's lock is still held");
|
|
let out = visa::anchor::run_daily(&cfg, &pool, cm(0, 7, 5))
|
|
.await
|
|
.unwrap();
|
|
assert!(
|
|
matches!(
|
|
out,
|
|
Some(visa::anchor::Outcome::Sent {
|
|
failed: 0,
|
|
to: 2,
|
|
..
|
|
})
|
|
),
|
|
"{out:?}"
|
|
);
|
|
let check = visa::journal::verify(&pool).await.unwrap();
|
|
let mails = got.lock().unwrap().clone();
|
|
assert_eq!(mails.len(), 2);
|
|
assert_eq!(mails[1].to, ["<archive@example.org>"]);
|
|
let m = &readable(&mails[0].data);
|
|
assert!(m.contains(&format!("Its hash: {}", check.head)), "{m}");
|
|
assert!(m.contains("Last entry: number 2,"), "{m}");
|
|
assert!(m.contains("The chain checked whole"), "{m}");
|
|
assert!(
|
|
m.contains(&format!("/journal/anchor?seq=2&hash={}", check.head)),
|
|
"{m}"
|
|
);
|
|
// once a day; the next day with nothing new: no mail, noted
|
|
assert!(
|
|
visa::anchor::run_daily(&cfg, &pool, cm(0, 9, 0))
|
|
.await
|
|
.unwrap()
|
|
.is_none()
|
|
);
|
|
let out = visa::anchor::run_daily(&cfg, &pool, cm(1, 7, 1))
|
|
.await
|
|
.unwrap();
|
|
assert!(
|
|
matches!(out, Some(visa::anchor::Outcome::Unchanged)),
|
|
"{out:?}"
|
|
);
|
|
assert_eq!(got.lock().unwrap().len(), 2);
|
|
// by hand it goes at once
|
|
let r = app.post("/notifications/anchor-now", &[]).await;
|
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
|
assert_eq!(r.location(), "/notifications?anchor=sent#anchor");
|
|
assert_eq!(got.lock().unwrap().len(), 4);
|
|
let logged: i64 =
|
|
sqlx::query_scalar("SELECT count(*) FROM notifications WHERE purpose = 'anchor'")
|
|
.fetch_one(&pool)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(logged, 4);
|
|
let page = app.get("/notifications").await.text();
|
|
assert!(page.contains("id=\"anchor-log\""), "{page}");
|
|
assert!(page.contains(">unchanged<"), "{page}");
|
|
|
|
// the check: the kept hash still matches ...
|
|
let t = app
|
|
.get(&format!("/journal/anchor?seq=2&hash={}", check.head))
|
|
.await
|
|
.text();
|
|
assert!(t.contains("Entry 2 still has this hash."), "{t}");
|
|
// ... another one does not, and an entry taken out shows
|
|
let t = app
|
|
.get(&format!("/journal/anchor?seq=2&hash={}", "ab".repeat(32)))
|
|
.await
|
|
.text();
|
|
assert!(t.contains("Entry 2 has a different hash now."), "{t}");
|
|
let t = app
|
|
.get(&format!("/journal/anchor?seq=99&hash={}", check.head))
|
|
.await
|
|
.text();
|
|
assert!(t.contains("There is no entry 99."), "{t}");
|
|
let r = app.get("/journal/anchor?seq=x&hash=short").await;
|
|
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
|
}
|
|
|
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
|
async fn a_broken_chain_is_said_in_the_anchor_mail(pool: PgPool) {
|
|
let (port, got) = fake_smtp().await;
|
|
let cfg = with_mail(port);
|
|
let app = with_config(pool.clone(), cfg.clone());
|
|
app.post(
|
|
"/lawyers",
|
|
&[("name", "Malee Rakdee"), ("status", "active")],
|
|
)
|
|
.await;
|
|
app.post(
|
|
"/notifications/anchor-to",
|
|
&[("anchor_to", "lead@example.com")],
|
|
)
|
|
.await;
|
|
// a change made around the app
|
|
sqlx::query("ALTER TABLE journal DISABLE TRIGGER journal_no_change")
|
|
.execute(&pool)
|
|
.await
|
|
.unwrap();
|
|
sqlx::query("UPDATE journal SET detail = 'something else' WHERE seq = 1")
|
|
.execute(&pool)
|
|
.await
|
|
.unwrap();
|
|
let out = visa::anchor::run_daily(&cfg, &pool, cm(0, 7, 5))
|
|
.await
|
|
.unwrap();
|
|
assert!(
|
|
matches!(out, Some(visa::anchor::Outcome::Sent { .. })),
|
|
"{out:?}"
|
|
);
|
|
let m = readable(&got.lock().unwrap()[0].data);
|
|
assert!(m.contains("WARNING: THE CHAIN DID NOT CHECK WHOLE"), "{m}");
|
|
let whole: bool = sqlx::query_scalar("SELECT whole FROM journal_anchors")
|
|
.fetch_one(&pool)
|
|
.await
|
|
.unwrap();
|
|
assert!(!whole);
|
|
}
|