From f464e35486538b34a033fd06068dba558ca25875 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 3 Sep 2026 06:51:45 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20sender=20check,=20ported=20from=20izlek?= =?UTF-8?q?=20=E2=80=94=20probe=20without=20sending,=20standing=20on=20the?= =?UTF-8?q?=20panel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 'Check connection' dials the server and stops before sending: connect, TLS, hello, AUTH, NOOP, hang up — lettre's test_connection under a 15s outer timeout, which izlek measured as necessary because lettre's own timeout does not catch a socket that accepts and then goes quiet. - The probe's verdict is recorded (at, ms, error) and the Mail section shows it as a standing line: NotConfigured / Unchecked / Connected with the handshake's milliseconds / Refused with what the server said. - Saving settings wipes the record, so 'Connected' can never outlive the settings it proved; a save also re-probes in the background. Verified: suite 37 green; driven in the browser — save triggers the background probe, the standing line shows the refusal with the server's own words, the button re-probes and both paths log to the event ledger. --- crates/im-core/src/settings.rs | 153 +++++++++++++++++++++++++++++++++ crates/im-web/assets/main.css | 10 +++ crates/im-web/src/admin.rs | 75 +++++++++++++++- crates/im-web/src/mailer.rs | 34 ++++++++ style/main.scss | 10 +++ 5 files changed, 278 insertions(+), 4 deletions(-) diff --git a/crates/im-core/src/settings.rs b/crates/im-core/src/settings.rs index ca4a794..257668c 100644 --- a/crates/im-core/src/settings.rs +++ b/crates/im-core/src/settings.rs @@ -75,6 +75,102 @@ pub async fn smtp(store: &Store) -> Result { }) } +/// One probe of the sender, as izlek records it: when it ran, how long the +/// handshake took, and what the server said if it refused. `error: None` is +/// a pass. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SenderCheck { + pub at: time::OffsetDateTime, + pub took_ms: u64, + pub error: Option, +} + +/// What the panel can claim about the sender right now. Saved settings wipe +/// the recorded check, so "Connected" can never outlive the settings it +/// proved. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Standing { + NotConfigured, + Unchecked, + Connected { + at: time::OffsetDateTime, + took_ms: u64, + }, + Refused { + at: time::OffsetDateTime, + said: String, + }, +} + +/// The sender's standing: settings plus the last probe, folded. +pub async fn standing(store: &Store) -> Result { + if !smtp(store).await?.configured() { + return Ok(Standing::NotConfigured); + } + let Some(check) = last_check(store).await? else { + return Ok(Standing::Unchecked); + }; + Ok(match check.error { + None => Standing::Connected { + at: check.at, + took_ms: check.took_ms, + }, + Some(said) => Standing::Refused { at: check.at, said }, + }) +} + +/// Writes down what a probe saw. The error text is built from what the +/// server said, never from the credentials we sent — safe to store and show. +pub async fn record_check(store: &Store, check: &SenderCheck) -> Result<()> { + set( + store, + "smtp_check_at", + &check + .at + .format(&time::format_description::well_known::Rfc3339) + .map_err(backend)?, + ) + .await?; + set(store, "smtp_check_ms", &check.took_ms.to_string()).await?; + set( + store, + "smtp_check_error", + check.error.as_deref().unwrap_or(""), + ) + .await?; + Ok(()) +} + +/// The last recorded probe, if any. +pub async fn last_check(store: &Store) -> Result> { + let Some(at) = get(store, "smtp_check_at").await? else { + return Ok(None); + }; + let at = time::OffsetDateTime::parse(&at, &time::format_description::well_known::Rfc3339) + .map_err(backend)?; + let took_ms = get(store, "smtp_check_ms") + .await? + .and_then(|raw| raw.parse().ok()) + .unwrap_or(0); + let error = get(store, "smtp_check_error") + .await? + .filter(|said| !said.is_empty()); + Ok(Some(SenderCheck { at, took_ms, error })) +} + +/// A saved sender cannot borrow the last probe's verdict: the check is +/// cleared on every settings write, like izlek's. +async fn clear_check(store: &Store) -> Result<()> { + for key in ["smtp_check_at", "smtp_check_ms", "smtp_check_error"] { + store + .conn + .execute("DELETE FROM settings WHERE key = ?1", turso::params![key]) + .await + .map_err(backend)?; + } + Ok(()) +} + /// Writes the SMTP settings. `password: None` keeps the stored one — the /// panel's password field is write-only, like izlek's. pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Result<()> { @@ -85,6 +181,9 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res "smtp_username", "smtp_from", "smtp_password", + "smtp_check_at", + "smtp_check_ms", + "smtp_check_error", ] { store .conn @@ -94,6 +193,8 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res } return Ok(()); } + // A saved sender cannot borrow the last probe's verdict. + clear_check(store).await?; set(store, "smtp_host", &smtp.host).await?; set(store, "smtp_port", &smtp.port.to_string()).await?; set(store, "smtp_username", &smtp.username).await?; @@ -143,6 +244,7 @@ mod tests { // An empty host clears the sender. set_smtp(&store, &Smtp::default(), None).await.unwrap(); + assert!(!smtp(&store).await.unwrap().configured()); } @@ -170,4 +272,55 @@ mod tests { let wrong_key = [9u8; 32]; assert!(secret::open(&wrong_key, &sealed).is_none()); } + + #[tokio::test] + async fn check_records_and_a_save_wipes_it() { + let store = Store::open(Path::new(":memory:")).await.unwrap(); + assert_eq!(standing(&store).await.unwrap(), Standing::NotConfigured); + + let value = Smtp { + host: "smtp.example.com".into(), + port: 587, + username: "auth@example.com".into(), + from: "im ".into(), + password: None, + }; + set_smtp(&store, &value, Some("s3cret")).await.unwrap(); + assert_eq!(standing(&store).await.unwrap(), Standing::Unchecked); + + record_check( + &store, + &SenderCheck { + at: time::OffsetDateTime::now_utc(), + took_ms: 142, + error: None, + }, + ) + .await + .unwrap(); + assert!(matches!( + standing(&store).await.unwrap(), + Standing::Connected { took_ms: 142, .. } + )); + + record_check( + &store, + &SenderCheck { + at: time::OffsetDateTime::now_utc(), + took_ms: 0, + error: Some("the mail server did not answer in time".into()), + }, + ) + .await + .unwrap(); + assert!(matches!( + standing(&store).await.unwrap(), + Standing::Refused { .. } + )); + + // A new save cannot borrow the old probe's verdict. + set_smtp(&store, &value, None).await.unwrap(); + assert_eq!(standing(&store).await.unwrap(), Standing::Unchecked); + assert!(last_check(&store).await.unwrap().is_none()); + } } diff --git a/crates/im-web/assets/main.css b/crates/im-web/assets/main.css index 30a463b..70045ba 100644 --- a/crates/im-web/assets/main.css +++ b/crates/im-web/assets/main.css @@ -494,6 +494,16 @@ body:has(.admin-shell) { gap: 12px; } +.admin-standing { + font-size: 12px; + color: var(--muted); +} + +.admin-pair { + display: flex; + gap: 8px; +} + input[type=checkbox] { accent-color: var(--accent); } diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index 31154c0..db9f21a 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -238,12 +238,35 @@ async fn users_section( } async fn mail_section(cx: &Cx) -> Result { - let smtp = settings::smtp(&app(cx).store).await?; + let store = &app(cx).store; + let smtp = settings::smtp(store).await?; let password_note = if smtp.password.is_some() { "password is set — fill to replace, leave empty to keep" } else { "no password set" }; + // The standing line, izlek's chip as a sentence: what the last probe + // proved, and when. Saving settings wipes the record, so this can never + // claim "connected" for settings that changed since. + let stamp = |at: time::OffsetDateTime| { + at.format(&time::macros::format_description!( + "[year]-[month]-[day] [hour]:[minute] UTC" + )) + .unwrap_or_default() + }; + let standing = match settings::standing(store).await? { + settings::Standing::NotConfigured => "No sender configured.".to_string(), + settings::Standing::Unchecked => { + "Saved, but never checked — the check dials the server and stops before sending." + .to_string() + } + settings::Standing::Connected { at, took_ms } => { + format!("Connected · {took_ms} ms · {}", stamp(at)) + } + settings::Standing::Refused { at, said } => { + format!("Refused · {} — {}", stamp(at), escape(&said)) + } + }; Ok(format!( r#"
Mail
@@ -261,9 +284,11 @@ async fn mail_section(cx: &Cx) -> Result { -
- -
+
{standing}
+
+
+
+
"#, escape(&smtp.host), smtp.port, @@ -489,6 +514,9 @@ async fn smtp_save(cx: &Cx, Form(input): Form) -> Result { }; settings::set_smtp(store, &value, input.password.as_deref()).await?; events::log(store, "smtp_updated", Some(&me.email), None).await; + // The saved sender gets re-probed in the background — the standing line + // on the Mail section catches up on the next view, like izlek's panel. + tokio::spawn(probe(store_of(cx))); back(cx, "mail", "&ok=smtp") } @@ -522,3 +550,42 @@ async fn smtp_test(cx: &Cx) -> Result { } } } +/// Dials the mail server without sending, on an admin's say-so, and writes +/// down what it said. The result shows on the Mail section as the standing +/// line; the panel redirects straight back. +#[route(POST "/admin/smtp_check")] +async fn smtp_check(cx: &Cx) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + probe(store_of(cx)).await; + events::log(&app(cx).store, "smtp_checked", Some(&me.email), None).await; + back(cx, "mail", "") +} + +fn store_of(cx: &Cx) -> std::sync::Arc { + app(cx).store.clone() +} + +/// Runs the probe and records whatever it saw. Shared by the check button +/// and the after-save probe: a saved sender is re-probed in the background, +/// so the standing line catches up on the next view without making the save +/// itself wait on a mail server. +async fn probe(store: std::sync::Arc) { + let check = match mailer::check(&store).await { + Ok(took_ms) => settings::SenderCheck { + at: time::OffsetDateTime::now_utc(), + took_ms, + error: None, + }, + Err(problem) => settings::SenderCheck { + at: time::OffsetDateTime::now_utc(), + took_ms: 0, + error: Some(problem.to_string()), + }, + }; + if let Err(problem) = settings::record_check(&store, &check).await { + eprintln!("im: failed to record the sender check: {problem}"); + } +} diff --git a/crates/im-web/src/mailer.rs b/crates/im-web/src/mailer.rs index 78bae40..7c94fcb 100644 --- a/crates/im-web/src/mailer.rs +++ b/crates/im-web/src/mailer.rs @@ -15,6 +15,13 @@ pub enum MailError { Settings(#[from] im_core::store::StoreError), } +/// How long to wait on a mail server before writing the attempt off. Long +/// enough for a slow but healthy server on a bad link, short enough that an +/// admin who mistyped the port is told while still looking at the screen. +/// izlek measured that lettre's own timeout does not catch a socket that +/// accepts and then says nothing — this outer bound is the backstop. +const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15); + pub type Result = std::result::Result; fn transport(smtp: &Smtp) -> Result> { @@ -80,6 +87,33 @@ pub async fn send_invite(store: &Store, issuer: &str, email: &str, token: &str) Ok(link) } +/// Dials the mail server without sending anything: connect, TLS, hello, +/// authenticate, NOOP, hang up. A pass proves the host, the port, the +/// encryption and the password; it says nothing about whether the +/// from-address may send — a server that accepts the login can still refuse +/// the envelope, which is what the test mail is for. +/// +/// Returns the handshake's milliseconds on a pass. The error text is built +/// from what the server said, never from what we sent it, so it is safe to +/// store and show. +pub async fn check(store: &Store) -> Result { + let smtp = settings::smtp(store).await?; + let transport = transport(&smtp)?; + let started = std::time::Instant::now(); + match tokio::time::timeout(PROBE_TIMEOUT, transport.test_connection()).await { + Ok(Ok(true)) => Ok(started.elapsed().as_millis() as u64), + // Connected, then would not answer a NOOP — nothing about the + // settings is proven wrong, but nothing is proven right either. + Ok(Ok(false)) => Err(MailError::Backend( + "the mail server accepted the connection and then went quiet".into(), + )), + Ok(Err(e)) => Err(MailError::Backend(e.to_string())), + Err(_) => Err(MailError::Backend( + "the mail server did not answer in time".into(), + )), + } +} + /// The panel's test button: proves the sender end to end, to the admin's own /// address. pub async fn send_test(store: &Store, to: &str) -> Result<()> { diff --git a/style/main.scss b/style/main.scss index eabb115..b9e82a1 100644 --- a/style/main.scss +++ b/style/main.scss @@ -530,6 +530,16 @@ body:has(.admin-shell) { gap: 12px; } +.admin-standing { + font-size: 12px; + color: var(--muted); +} + +.admin-pair { + display: flex; + gap: 8px; +} + input[type="checkbox"] { accent-color: var(--accent); } @media (max-width: 720px) {