forge
Explore
Log in

Don't you dare go Hollow

Sender check, ported from izlek — probe without sending, standing on the panel

Browse files at this commit

f464e35486538b34a033fd06068dba558ca25875Ahmet Kaan GümüşParent: 0134def
  • feat
    • sender check, ported from izlek — probe without sending, standing on the panel
Show full message
feat: sender check, ported from izlek — probe without sending, standing on the panel

- '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.rsmodified+153 -0
@@ -75,6 +75,102 @@ pub async fn smtp(store: &Store) -> Result<Smtp> {
75 })75 })
76 }76 }
77 77
78+/// One probe of the sender, as izlek records it: when it ran, how long the
79+/// handshake took, and what the server said if it refused. `error: None` is
80+/// a pass.
81+#[derive(Debug, Clone, PartialEq, Eq)]
82+pub struct SenderCheck {
83+ pub at: time::OffsetDateTime,
84+ pub took_ms: u64,
85+ pub error: Option<String>,
86+}
87+
88+/// What the panel can claim about the sender right now. Saved settings wipe
89+/// the recorded check, so "Connected" can never outlive the settings it
90+/// proved.
91+#[derive(Debug, Clone, PartialEq, Eq)]
92+pub enum Standing {
93+ NotConfigured,
94+ Unchecked,
95+ Connected {
96+ at: time::OffsetDateTime,
97+ took_ms: u64,
98+ },
99+ Refused {
100+ at: time::OffsetDateTime,
101+ said: String,
102+ },
103+}
104+
105+/// The sender's standing: settings plus the last probe, folded.
106+pub async fn standing(store: &Store) -> Result<Standing> {
107+ if !smtp(store).await?.configured() {
108+ return Ok(Standing::NotConfigured);
109+ }
110+ let Some(check) = last_check(store).await? else {
111+ return Ok(Standing::Unchecked);
112+ };
113+ Ok(match check.error {
114+ None => Standing::Connected {
115+ at: check.at,
116+ took_ms: check.took_ms,
117+ },
118+ Some(said) => Standing::Refused { at: check.at, said },
119+ })
120+}
121+
122+/// Writes down what a probe saw. The error text is built from what the
123+/// server said, never from the credentials we sent — safe to store and show.
124+pub async fn record_check(store: &Store, check: &SenderCheck) -> Result<()> {
125+ set(
126+ store,
127+ "smtp_check_at",
128+ &check
129+ .at
130+ .format(&time::format_description::well_known::Rfc3339)
131+ .map_err(backend)?,
132+ )
133+ .await?;
134+ set(store, "smtp_check_ms", &check.took_ms.to_string()).await?;
135+ set(
136+ store,
137+ "smtp_check_error",
138+ check.error.as_deref().unwrap_or(""),
139+ )
140+ .await?;
141+ Ok(())
142+}
143+
144+/// The last recorded probe, if any.
145+pub async fn last_check(store: &Store) -> Result<Option<SenderCheck>> {
146+ let Some(at) = get(store, "smtp_check_at").await? else {
147+ return Ok(None);
148+ };
149+ let at = time::OffsetDateTime::parse(&at, &time::format_description::well_known::Rfc3339)
150+ .map_err(backend)?;
151+ let took_ms = get(store, "smtp_check_ms")
152+ .await?
153+ .and_then(|raw| raw.parse().ok())
154+ .unwrap_or(0);
155+ let error = get(store, "smtp_check_error")
156+ .await?
157+ .filter(|said| !said.is_empty());
158+ Ok(Some(SenderCheck { at, took_ms, error }))
159+}
160+
161+/// A saved sender cannot borrow the last probe's verdict: the check is
162+/// cleared on every settings write, like izlek's.
163+async fn clear_check(store: &Store) -> Result<()> {
164+ for key in ["smtp_check_at", "smtp_check_ms", "smtp_check_error"] {
165+ store
166+ .conn
167+ .execute("DELETE FROM settings WHERE key = ?1", turso::params![key])
168+ .await
169+ .map_err(backend)?;
170+ }
171+ Ok(())
172+}
173+
78 /// Writes the SMTP settings. `password: None` keeps the stored one — the174 /// Writes the SMTP settings. `password: None` keeps the stored one — the
79 /// panel's password field is write-only, like izlek's.175 /// panel's password field is write-only, like izlek's.
80 pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Result<()> {176 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
85 "smtp_username",181 "smtp_username",
86 "smtp_from",182 "smtp_from",
87 "smtp_password",183 "smtp_password",
184+ "smtp_check_at",
185+ "smtp_check_ms",
186+ "smtp_check_error",
88 ] {187 ] {
89 store188 store
90 .conn189 .conn
@@ -94,6 +193,8 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res
94 }193 }
95 return Ok(());194 return Ok(());
96 }195 }
196+ // A saved sender cannot borrow the last probe's verdict.
197+ clear_check(store).await?;
97 set(store, "smtp_host", &smtp.host).await?;198 set(store, "smtp_host", &smtp.host).await?;
98 set(store, "smtp_port", &smtp.port.to_string()).await?;199 set(store, "smtp_port", &smtp.port.to_string()).await?;
99 set(store, "smtp_username", &smtp.username).await?;200 set(store, "smtp_username", &smtp.username).await?;
@@ -143,6 +244,7 @@ mod tests {
143 244
144 // An empty host clears the sender.245 // An empty host clears the sender.
145 set_smtp(&store, &Smtp::default(), None).await.unwrap();246 set_smtp(&store, &Smtp::default(), None).await.unwrap();
247+
146 assert!(!smtp(&store).await.unwrap().configured());248 assert!(!smtp(&store).await.unwrap().configured());
147 }249 }
148 250
@@ -170,4 +272,55 @@ mod tests {
170 let wrong_key = [9u8; 32];272 let wrong_key = [9u8; 32];
171 assert!(secret::open(&wrong_key, &sealed).is_none());273 assert!(secret::open(&wrong_key, &sealed).is_none());
172 }274 }
275+
276+ #[tokio::test]
277+ async fn check_records_and_a_save_wipes_it() {
278+ let store = Store::open(Path::new(":memory:")).await.unwrap();
279+ assert_eq!(standing(&store).await.unwrap(), Standing::NotConfigured);
280+
281+ let value = Smtp {
282+ host: "smtp.example.com".into(),
283+ port: 587,
284+ username: "auth@example.com".into(),
285+ from: "im <auth@example.com>".into(),
286+ password: None,
287+ };
288+ set_smtp(&store, &value, Some("s3cret")).await.unwrap();
289+ assert_eq!(standing(&store).await.unwrap(), Standing::Unchecked);
290+
291+ record_check(
292+ &store,
293+ &SenderCheck {
294+ at: time::OffsetDateTime::now_utc(),
295+ took_ms: 142,
296+ error: None,
297+ },
298+ )
299+ .await
300+ .unwrap();
301+ assert!(matches!(
302+ standing(&store).await.unwrap(),
303+ Standing::Connected { took_ms: 142, .. }
304+ ));
305+
306+ record_check(
307+ &store,
308+ &SenderCheck {
309+ at: time::OffsetDateTime::now_utc(),
310+ took_ms: 0,
311+ error: Some("the mail server did not answer in time".into()),
312+ },
313+ )
314+ .await
315+ .unwrap();
316+ assert!(matches!(
317+ standing(&store).await.unwrap(),
318+ Standing::Refused { .. }
319+ ));
320+
321+ // A new save cannot borrow the old probe's verdict.
322+ set_smtp(&store, &value, None).await.unwrap();
323+ assert_eq!(standing(&store).await.unwrap(), Standing::Unchecked);
324+ assert!(last_check(&store).await.unwrap().is_none());
325+ }
173 }326 }
crates/im-web/assets/main.cssmodified+10 -0
@@ -494,6 +494,16 @@ body:has(.admin-shell) {
494 gap: 12px;494 gap: 12px;
495 }495 }
496 496
497+.admin-standing {
498+ font-size: 12px;
499+ color: var(--muted);
500+}
501+
502+.admin-pair {
503+ display: flex;
504+ gap: 8px;
505+}
506+
497 input[type=checkbox] {507 input[type=checkbox] {
498 accent-color: var(--accent);508 accent-color: var(--accent);
499 }509 }
crates/im-web/src/admin.rsmodified+71 -4
@@ -238,12 +238,35 @@ async fn users_section(
238 }238 }
239 239
240 async fn mail_section(cx: &Cx) -> Result<String, topcoat::Error> {240 async fn mail_section(cx: &Cx) -> Result<String, topcoat::Error> {
241- let smtp = settings::smtp(&app(cx).store).await?;241+ let store = &app(cx).store;
242+ let smtp = settings::smtp(store).await?;
242 let password_note = if smtp.password.is_some() {243 let password_note = if smtp.password.is_some() {
243 "password is set — fill to replace, leave empty to keep"244 "password is set — fill to replace, leave empty to keep"
244 } else {245 } else {
245 "no password set"246 "no password set"
246 };247 };
248+ // The standing line, izlek's chip as a sentence: what the last probe
249+ // proved, and when. Saving settings wipes the record, so this can never
250+ // claim "connected" for settings that changed since.
251+ let stamp = |at: time::OffsetDateTime| {
252+ at.format(&time::macros::format_description!(
253+ "[year]-[month]-[day] [hour]:[minute] UTC"
254+ ))
255+ .unwrap_or_default()
256+ };
257+ let standing = match settings::standing(store).await? {
258+ settings::Standing::NotConfigured => "No sender configured.".to_string(),
259+ settings::Standing::Unchecked => {
260+ "Saved, but never checked — the check dials the server and stops before sending."
261+ .to_string()
262+ }
263+ settings::Standing::Connected { at, took_ms } => {
264+ format!("Connected · {took_ms} ms · {}", stamp(at))
265+ }
266+ settings::Standing::Refused { at, said } => {
267+ format!("Refused · {} — {}", stamp(at), escape(&said))
268+ }
269+ };
247 Ok(format!(270 Ok(format!(
248 r#"<div class="admin-card">271 r#"<div class="admin-card">
249 <div class="auth-title">Mail</div>272 <div class="auth-title">Mail</div>
@@ -261,9 +284,11 @@ async fn mail_section(cx: &Cx) -> Result<String, topcoat::Error> {
261 <input class="auth-input auth-input-mono" type="text" name="from" value="{}" placeholder="im &lt;auth@example.com&gt;"></label>284 <input class="auth-input auth-input-mono" type="text" name="from" value="{}" placeholder="im &lt;auth@example.com&gt;"></label>
262 <button class="auth-submit admin-action-wide" type="submit"><span class="auth-submit-text">Save</span></button>285 <button class="auth-submit admin-action-wide" type="submit"><span class="auth-submit-text">Save</span></button>
263 </form>286 </form>
264- <form method="post" action="/admin/smtp_test" class="admin-form">287+ <div class="admin-standing">{standing}</div>
265- <button class="admin-action" type="submit">Send a test mail to myself</button>288+ <div class="admin-pair">
266- </form>289+ <form method="post" action="/admin/smtp_check"><button class="admin-action" type="submit">Check connection</button></form>
290+ <form method="post" action="/admin/smtp_test"><button class="admin-action" type="submit">Send a test mail to myself</button></form>
291+ </div>
267 </div>"#,292 </div>"#,
268 escape(&smtp.host),293 escape(&smtp.host),
269 smtp.port,294 smtp.port,
@@ -489,6 +514,9 @@ async fn smtp_save(cx: &Cx, Form(input): Form<SmtpForm>) -> Result<Response> {
489 };514 };
490 settings::set_smtp(store, &value, input.password.as_deref()).await?;515 settings::set_smtp(store, &value, input.password.as_deref()).await?;
491 events::log(store, "smtp_updated", Some(&me.email), None).await;516 events::log(store, "smtp_updated", Some(&me.email), None).await;
517+ // The saved sender gets re-probed in the background — the standing line
518+ // on the Mail section catches up on the next view, like izlek's panel.
519+ tokio::spawn(probe(store_of(cx)));
492 back(cx, "mail", "&ok=smtp")520 back(cx, "mail", "&ok=smtp")
493 }521 }
494 522
@@ -522,3 +550,42 @@ async fn smtp_test(cx: &Cx) -> Result<Response> {
522 }550 }
523 }551 }
524 }552 }
553+/// Dials the mail server without sending, on an admin's say-so, and writes
554+/// down what it said. The result shows on the Mail section as the standing
555+/// line; the panel redirects straight back.
556+#[route(POST "/admin/smtp_check")]
557+async fn smtp_check(cx: &Cx) -> Result<Response> {
558+ let me = match require_admin(cx).await {
559+ Ok(me) => me,
560+ Err(redirect) => return Ok(redirect),
561+ };
562+ probe(store_of(cx)).await;
563+ events::log(&app(cx).store, "smtp_checked", Some(&me.email), None).await;
564+ back(cx, "mail", "")
565+}
566+
567+fn store_of(cx: &Cx) -> std::sync::Arc<im_core::store::Store> {
568+ app(cx).store.clone()
569+}
570+
571+/// Runs the probe and records whatever it saw. Shared by the check button
572+/// and the after-save probe: a saved sender is re-probed in the background,
573+/// so the standing line catches up on the next view without making the save
574+/// itself wait on a mail server.
575+async fn probe(store: std::sync::Arc<im_core::store::Store>) {
576+ let check = match mailer::check(&store).await {
577+ Ok(took_ms) => settings::SenderCheck {
578+ at: time::OffsetDateTime::now_utc(),
579+ took_ms,
580+ error: None,
581+ },
582+ Err(problem) => settings::SenderCheck {
583+ at: time::OffsetDateTime::now_utc(),
584+ took_ms: 0,
585+ error: Some(problem.to_string()),
586+ },
587+ };
588+ if let Err(problem) = settings::record_check(&store, &check).await {
589+ eprintln!("im: failed to record the sender check: {problem}");
590+ }
591+}
crates/im-web/src/mailer.rsmodified+34 -0
@@ -15,6 +15,13 @@ pub enum MailError {
15 Settings(#[from] im_core::store::StoreError),15 Settings(#[from] im_core::store::StoreError),
16 }16 }
17 17
18+/// How long to wait on a mail server before writing the attempt off. Long
19+/// enough for a slow but healthy server on a bad link, short enough that an
20+/// admin who mistyped the port is told while still looking at the screen.
21+/// izlek measured that lettre's own timeout does not catch a socket that
22+/// accepts and then says nothing — this outer bound is the backstop.
23+const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
24+
18 pub type Result<T, E = MailError> = std::result::Result<T, E>;25 pub type Result<T, E = MailError> = std::result::Result<T, E>;
19 26
20 fn transport(smtp: &Smtp) -> Result<lettre::AsyncSmtpTransport<lettre::Tokio1Executor>> {27 fn transport(smtp: &Smtp) -> Result<lettre::AsyncSmtpTransport<lettre::Tokio1Executor>> {
@@ -80,6 +87,33 @@ pub async fn send_invite(store: &Store, issuer: &str, email: &str, token: &str)
80 Ok(link)87 Ok(link)
81 }88 }
82 89
90+/// Dials the mail server without sending anything: connect, TLS, hello,
91+/// authenticate, NOOP, hang up. A pass proves the host, the port, the
92+/// encryption and the password; it says nothing about whether the
93+/// from-address may send — a server that accepts the login can still refuse
94+/// the envelope, which is what the test mail is for.
95+///
96+/// Returns the handshake's milliseconds on a pass. The error text is built
97+/// from what the server said, never from what we sent it, so it is safe to
98+/// store and show.
99+pub async fn check(store: &Store) -> Result<u64> {
100+ let smtp = settings::smtp(store).await?;
101+ let transport = transport(&smtp)?;
102+ let started = std::time::Instant::now();
103+ match tokio::time::timeout(PROBE_TIMEOUT, transport.test_connection()).await {
104+ Ok(Ok(true)) => Ok(started.elapsed().as_millis() as u64),
105+ // Connected, then would not answer a NOOP — nothing about the
106+ // settings is proven wrong, but nothing is proven right either.
107+ Ok(Ok(false)) => Err(MailError::Backend(
108+ "the mail server accepted the connection and then went quiet".into(),
109+ )),
110+ Ok(Err(e)) => Err(MailError::Backend(e.to_string())),
111+ Err(_) => Err(MailError::Backend(
112+ "the mail server did not answer in time".into(),
113+ )),
114+ }
115+}
116+
83 /// The panel's test button: proves the sender end to end, to the admin's own117 /// The panel's test button: proves the sender end to end, to the admin's own
84 /// address.118 /// address.
85 pub async fn send_test(store: &Store, to: &str) -> Result<()> {119 pub async fn send_test(store: &Store, to: &str) -> Result<()> {
style/main.scssmodified+10 -0
@@ -530,6 +530,16 @@ body:has(.admin-shell) {
530 gap: 12px;530 gap: 12px;
531 }531 }
532 532
533+.admin-standing {
534+ font-size: 12px;
535+ color: var(--muted);
536+}
537+
538+.admin-pair {
539+ display: flex;
540+ gap: 8px;
541+}
542+
533 input[type="checkbox"] { accent-color: var(--accent); }543 input[type="checkbox"] { accent-color: var(--accent); }
534 544
535 @media (max-width: 720px) {545 @media (max-width: 720px) {