diff --git a/docs/notifications.md b/docs/notifications.md index e47d2d9..7ef291d 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -57,6 +57,30 @@ scheduler --RunReport--> NotifySink --(send)--> channel --> one consumer task queue messages, the heartbeat and test messages), and every **email subject** is `🐧 [pingwin] `, cut at 150 characters. The email body has no prefix. The prefix counts towards Telegram's 4096-character limit. +- **Bold in Telegram.** The target name and the status words are bold; reasons, + durations, times and notes are regular. In Telegram `db-1: ssh OFFLINE (refused) + since 14:02 UTC` looks like **db-1: ssh OFFLINE** (refused) since 14:02 UTC, sent + as `db-1: ssh OFFLINE (refused) since 14:02 UTC`. The first status shares + its bold run with the name (`web-1: host RECOVERED after 12m ...`), every + further status is bold on its own (`web-1: ping OK, https OFFLINE + (timeout) ...`). The headline of the "Telegram restored after X" / "rate limit + ended after X" line, the title line of the heartbeat and "pingwin test message" + are bold too. + - **How it works.** Telegram messages are sent with `parse_mode: "HTML"`. The + alert text is built once with invisible bold markers (private-use characters, + `message::render`, `notify::markup`) and stored like that in the queue. Only + when it is sent: Telegram gets everything **HTML-escaped** (`&`, `<`, `>`) with + the markers turned into `...`; email gets the markers removed. Names, + error texts and any other dynamic text can therefore never inject a tag, and + unbalanced bold is closed automatically. Telegram answers malformed HTML with a + 400 "can't parse entities", so nothing unescaped may reach it. + - **Email stays plain text**: no ``, no entities, also for delayed queue rows + and the failover test. + - **Queue rows from before this change** have no markers: they are sent escaped + and not bold. + - **Truncation** (4000 visible characters including the prefix, below Telegram's + 4096 limit) happens on the marked text, before the HTML is built, so a cut never + splits a tag or an entity and an open bold part is closed. - "since" is the time of the first failed probe of the outage. Times are shown in the `display_tz` setting (default `UTC`); the date is added only when it differs from the message's own date. diff --git a/src/dump.rs b/src/dump.rs index 9fc2185..6a6e4dd 100644 --- a/src/dump.rs +++ b/src/dump.rs @@ -43,6 +43,7 @@ use jiff::tz::TimeZone; use crate::admin; use crate::export::{self, RunsCsv, csv_text, csv_writer, format_local, format_utc, opt}; use crate::notify::config::load_display_tz; +use crate::notify::markup; use crate::store::{Store, Target}; /// Rows read from the store per page. @@ -353,7 +354,8 @@ async fn write_files( n.email_attempts.to_string(), n.delivered_ms.map(format_utc).unwrap_or_default(), csv_text(n.last_error.as_deref().unwrap_or_default()), - csv_text(&n.message), + // Stored with invisible bold markers (notify::markup): drop them. + csv_text(&markup::plain(&n.message)), ])?; summary.notifications += 1; } diff --git a/src/notify.rs b/src/notify.rs index 24568d4..5774145 100644 --- a/src/notify.rs +++ b/src/notify.rs @@ -23,6 +23,7 @@ pub mod config; pub mod dispatch; pub mod heartbeat; +pub mod markup; pub mod message; pub mod smtp; pub mod telegram; diff --git a/src/notify/dispatch.rs b/src/notify/dispatch.rs index cd0661d..089f6da 100644 --- a/src/notify/dispatch.rs +++ b/src/notify/dispatch.rs @@ -132,6 +132,7 @@ use super::config::{ self, ConfigStoreError, SecretField, SmtpConfig, TelegramConfig, keys, load_display_tz, load_telegram, }; +use super::markup; use super::message::{self, TargetChange, format_time_full, human_duration}; use super::smtp::{self, SMTP_OVERALL_TIMEOUT, SmtpError}; use super::telegram::{ChatInfo, DEFAULT_BASE_URL, TelegramClient, TelegramError}; @@ -1022,8 +1023,11 @@ impl Notifier { let (name, result) = match &channel { TestChannel::Telegram(cfg) => ( "Telegram", - self.send_telegram(cfg, &format!("pingwin test message ({now})")) - .await, + self.send_telegram( + cfg, + &format!("{} ({now})", markup::bold("pingwin test message")), + ) + .await, ), TestChannel::Email(cfg) => { let text = format!("pingwin test message ({now})"); @@ -1149,13 +1153,16 @@ impl Notifier { Ok(()) } + /// Email is plain text: the bold markers of the shared message text are dropped + /// here, the one path every email takes. async fn send_email(&self, cfg: &SmtpConfig, text: &str, body: &str) -> Result<(), String> { + let (text, body) = (markup::plain(text), markup::plain(body)); let first_line = text.lines().next().unwrap_or(""); let subject: String = format!("{PREFIX}[pingwin] {first_line}") .chars() .take(150) .collect(); - smtp::send_email_with_timeout(cfg, &subject, body, self.inner.smtp_timeout) + smtp::send_email_with_timeout(cfg, &subject, &body, self.inner.smtp_timeout) .await .map_err(|e: SmtpError| e.to_string()) } @@ -1327,12 +1334,13 @@ fn new_row(text: &str, created_ms: i64, tg_enabled: bool, email_enabled: bool) - } /// `Telegram restored after 2h 13m (unreachable since 14:02 UTC)`, or after a 429 -/// `Telegram rate limit ended after 2h 13m (rate limited since 14:02 UTC)`, if +/// `Telegram rate limit ended after 2h 13m (rate limited since 14:02 UTC)` (the +/// headline before the parenthesis is bold, see [`markup`]), if /// `health` still records an outage. Must be computed **before** the send that ends /// the outage, and sent inside that send's text (a successful send clears the outage). pub(super) fn restored_header(health: &Health, now_ms: i64, tz: &TimeZone) -> Option { let since = format_time_full(health.unreachable_since_ms?, tz); - let line = restored_text(Channel::Telegram, health, now_ms)?; + let line = markup::bold(&restored_text(Channel::Telegram, health, now_ms)?); Some(match health.outage { Outage::RateLimited { .. } => format!("{line} (rate limited since {since})"), Outage::Unreachable => format!("{line} (unreachable since {since})"), @@ -1359,7 +1367,8 @@ fn email_body(text: &str, note: Option<&str>) -> String { } } -/// `[delayed (originally , https OFFLINE (handshake_reset) since 14:00 UTC" + ] + ); + // Telegram is told to parse HTML. + let requests = fx.tg.received_requests().await.unwrap(); + let body: serde_json::Value = serde_json::from_slice(&requests[0].body).unwrap(); + assert_eq!(body["parse_mode"], "HTML"); +} + +#[tokio::test] +async fn email_stays_plain_text() { + let fx = fixture(false, true).await; + fx.notifier.handle(fx.change("a", "", "<", "&", "\u{E000}", "\u{E001}"] { + assert!(!mail.contains(forbidden), "{forbidden:?} in {mail}"); + } +} + +#[tokio::test] +async fn stored_message_keeps_bold_markers_and_the_queue_view_text_is_plain() { + let fx = fixture(true, false).await; + fx.notifier.handle(fx.change("web-1")).await.unwrap(); + let message = fx.rows().await[0].1.message.clone(); + assert!(message.contains(markup::BOLD_ON), "{message:?}"); + assert_eq!( + markup::plain(&message), + "web-1: ping OK, https OFFLINE (handshake_reset) since 14:00 UTC" + ); +} + +#[tokio::test] +async fn delayed_flush_escapes_old_plain_rows_and_bolds_new_ones() { + let fx = fixture(true, false).await; + // Stored before bold existed: plain text, with characters that need escaping. + fx.store + .insert_notification(pending_row("old<1>: ping OK & https OFFLINE", T0 - 60_000)) + .await + .unwrap(); + // Stored after: bold markers. + let marked = format!( + "{} (timeout) since 14:00 UTC", + markup::bold("db<1>: HOST OFFLINE") + ); + fx.store + .insert_notification(pending_row(&marked, T0 - 30_000)) + .await + .unwrap(); + fx.notifier.tick().await.unwrap(); + + assert_eq!( + fx.tg_raw_texts().await, + vec![ + "🐧 [delayed (originally 2026-11-30 13:59 UTC)] old<1>: ping OK & https OFFLINE", + "🐧 [delayed (originally 2026-11-30 13:59 UTC)] db<1>: HOST OFFLINE (timeout) since 14:00 UTC", + ] + ); +} + +#[tokio::test] +async fn delayed_row_goes_out_by_email_as_plain_text() { + let fx = fixture(false, true).await; + let marked = format!("{} (timeout)", markup::bold("db<1>: HOST OFFLINE")); + fx.store + .insert_notification(NotificationV1 { + email_status: ChannelStatus::Pending.code(), + telegram_status: ChannelStatus::NotUsed.code(), + ..pending_row(&marked, T0 - 30_000) + }) + .await + .unwrap(); + fx.notifier.tick().await.unwrap(); + let mails = fx.smtp.messages(); + assert_eq!(mails.len(), 1); + assert!( + mails[0].contains("db<1>: HOST OFFLINE (timeout)"), + "{}", + mails[0] + ); + assert!(!mails[0].contains("") && !mails[0].contains('\u{E000}')); +} + +#[test] +fn restored_header_has_a_bold_headline_and_regular_details() { + let health = Health { + unreachable_since_ms: Some(T0 - 120_000), + ..Health::default() + }; + let header = restored_header(&health, T0, &TimeZone::UTC).unwrap(); + assert_eq!( + markup::html(&header), + "Telegram restored after 2m (unreachable since 2026-11-30 13:58 UTC)" + ); + let limited = Health { + outage: Outage::RateLimited { retry_after_s: 5 }, + ..health + }; + let header = restored_header(&limited, T0, &TimeZone::UTC).unwrap(); + assert_eq!( + markup::html(&header), + "Telegram rate limit ended after 2m (rate limited since 2026-11-30 13:58 UTC)" + ); +} + +#[tokio::test] +async fn test_message_has_a_bold_title() { + let fx = fixture(false, false).await; + let outcome = fx + .notifier + .send_test(TestChannel::Telegram(tg_config(false))) + .await; + assert!(outcome.ok, "{outcome:?}"); + let raw = fx.tg_raw_texts().await; + assert!( + raw[0].starts_with("🐧 pingwin test message (2026-11-30 14:00 UTC)"), + "{raw:?}" + ); +} + +#[tokio::test] +async fn very_long_messages_are_cut_before_the_html_is_built() { + let fx = fixture(true, false).await; + // A bold part that straddles the cut, full of characters that become entities. + let long = format!("{}{}", markup::bold(&"<&>".repeat(3000)), "tail"); + fx.store + .insert_notification(pending_row(&long, T0 - 1000)) + .await + .unwrap(); + fx.notifier.tick().await.unwrap(); + let raw = fx.tg_raw_texts().await; + assert_eq!(raw.len(), 1); + let html = &raw[0]; + assert_eq!(html.matches("").count(), 1, "bold opened once"); + assert_eq!(html.matches("").count(), 1, "and closed"); + assert!(html.ends_with("")); + // Every `&` starts a whole entity, so nothing was cut in the middle of one. + let body = html.trim_end_matches(""); + assert!(body.ends_with("<") || body.ends_with("&") || body.ends_with(">")); + // The visible text, with entities decoded, is exactly the limit (prefix included). + assert_eq!(unhtml(html).chars().count(), 4000); +} + +#[tokio::test] +async fn heartbeat_title_is_bold() { + use crate::notify::config::keys; + let fx = fixture(true, false).await; + let source = FakeSource { + calls: Mutex::new(0), + }; + fx.store + .set_setting(keys::HEARTBEAT_ENABLED, "true") + .await + .unwrap(); + fx.store + .set_setting(keys::HEARTBEAT_TIME, "14:00") + .await + .unwrap(); + fx.notifier.heartbeat_tick(&source).await.unwrap(); + let raw = fx.tg_raw_texts().await; + assert!( + raw[0].starts_with( + "🐧 pingwin daily summary, 2026-11-30 14:00 UTC\nie-node: ping OK\n" + ), + "{raw:?}" + ); +} diff --git a/src/notify/heartbeat.rs b/src/notify/heartbeat.rs index 2e81e9e..d8aead2 100644 --- a/src/notify/heartbeat.rs +++ b/src/notify/heartbeat.rs @@ -34,6 +34,7 @@ use jiff::tz::TimeZone; use super::config::{keys, load_display_tz, validate_hhmm}; use super::dispatch::{Channel, Notifier, NotifyError, restored_header}; +use super::markup; use super::message::format_time_full; use crate::state::State; use crate::store::codes::{EventKind, SubjectKind}; @@ -86,7 +87,14 @@ pub fn due_date( /// The heartbeat text. pub fn render_summary(summary: &Summary, now_ms: i64, tz: &TimeZone) -> String { - let mut out = format!("pingwin daily summary, {}\n", format_time_full(now_ms, tz)); + // Title line bold; one line per target, name and states bold as in an alert. + let mut out = format!( + "{}\n", + markup::bold(&format!( + "pingwin daily summary, {}", + format_time_full(now_ms, tz) + )) + ); if summary.targets.is_empty() { out.push_str("No targets configured.\n"); } @@ -94,17 +102,27 @@ pub fn render_summary(summary: &Summary, now_ms: i64, tz: &TimeZone) -> String { let parts: Vec = target .subjects .iter() - .map(|(kind, state)| { + .enumerate() + .map(|(i, (kind, state))| { let word = match state { State::Online => "OK", State::Degraded => "degraded", State::Offline => "OFFLINE", State::Unchecked => "unchecked", }; - format!("{} {word}", kind.label()) + let status = format!("{} {word}", kind.label()); + if i == 0 { + markup::bold(&format!("{}: {status}", target.name)) + } else { + markup::bold(&status) + } }) .collect(); - out.push_str(&format!("{}: {}\n", target.name, parts.join(", "))); + if parts.is_empty() { + out.push_str(&format!("{}\n", markup::bold(&target.name))); + } else { + out.push_str(&format!("{}\n", parts.join(", "))); + } } out.push_str(&format!( "State changes in the last 24 h: {}", @@ -293,7 +311,14 @@ mod tests { }; let text = render_summary(&summary, ts("2026-11-30T08:00:00Z"), &TimeZone::UTC); assert_eq!( - text, + markup::html(&text), + "pingwin daily summary, 2026-11-30 08:00 UTC\n\ + ie-node: ping OK, https OFFLINE\n\ + de-node: ping OK\n\ + State changes in the last 24 h: 3" + ); + assert_eq!( + markup::plain(&text), "pingwin daily summary, 2026-11-30 08:00 UTC\n\ ie-node: ping OK, https OFFLINE\n\ de-node: ping OK\n\ diff --git a/src/notify/markup.rs b/src/notify/markup.rs new file mode 100644 index 0000000..03ecbf7 --- /dev/null +++ b/src/notify/markup.rs @@ -0,0 +1,126 @@ +//! Bold text for Telegram, plain text everywhere else. +//! +//! Alert texts are built once and used for three things: the Telegram message, the +//! email, and the queue row (which is stored and may be sent days later, by either +//! channel). To keep one text for all three, bold parts are wrapped in two invisible +//! marker characters from the Unicode private-use area: +//! +//! ```text +//! web-1: host RECOVERED after 12m (down since 14:02 UTC) +//! ``` +//! +//! - [`html`] turns that into Telegram HTML (`parse_mode: "HTML"`): everything is +//! escaped (`&`, `<`, `>`), the markers become `` and ``. Text without +//! markers, such as rows queued before bold existed, is simply escaped. +//! - [`plain`] drops the markers: used for email and for the dashboard's queue list. +//! +//! The markers are never HTML, so nothing that comes from outside (target names, +//! error texts) can inject a tag: it is escaped like all other text. [`html`] also +//! guarantees balanced tags whatever the input looks like. Anything that shows a +//! stored message outside Telegram (email, dashboard, CSV dump) must go through +//! [`plain`]. + +/// Start of a bold part. +pub const BOLD_ON: char = '\u{E000}'; +/// End of a bold part. +pub const BOLD_OFF: char = '\u{E001}'; + +fn is_marker(c: char) -> bool { + c == BOLD_ON || c == BOLD_OFF +} + +/// Wrap `text` in bold markers. Markers inside `text` are removed first, so a +/// hostile name cannot end the bold part early. +pub fn bold(text: &str) -> String { + let inner: String = text.chars().filter(|c| !is_marker(*c)).collect(); + format!("{BOLD_ON}{inner}{BOLD_OFF}") +} + +/// The text without markers (email, dashboard, logs). +pub fn plain(text: &str) -> String { + text.chars().filter(|c| !is_marker(*c)).collect() +} + +/// Cut to at most `max` visible characters (markers do not count). Cutting happens on +/// the marked text, *before* HTML conversion, so no tag or entity can be split; +/// [`html`] closes a bold part that the cut left open. +pub fn truncate(text: &str, max: usize) -> String { + let mut visible = 0; + let mut out = String::new(); + for c in text.chars() { + if !is_marker(c) { + if visible == max { + break; + } + visible += 1; + } + out.push(c); + } + out +} + +/// Telegram HTML: escape `&`, `<`, `>` and turn markers into `` / ``. +/// A nested start or a stray end is ignored and an open bold part is closed at the +/// end, so the result is always balanced. +pub fn html(text: &str) -> String { + let mut out = String::with_capacity(text.len() + 16); + let mut open = false; + for c in text.chars() { + match c { + BOLD_ON if !open => { + open = true; + out.push_str(""); + } + BOLD_OFF if open => { + open = false; + out.push_str(""); + } + BOLD_ON | BOLD_OFF => {} + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + c => out.push(c), + } + } + if open { + out.push_str(""); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn html_escapes_and_bolds() { + let text = format!("{}a x", BOLD_ON, BOLD_OFF); + assert_eq!(html(&text), "a<b&c: ok > x"); + assert_eq!(plain(&text), "a x"); + } + + #[test] + fn unmarked_text_is_only_escaped() { + assert_eq!(html("old & more"), "old <row> & more"); + } + + #[test] + fn html_is_always_balanced() { + let messy = format!("{BOLD_ON}a{BOLD_ON}b{BOLD_OFF}{BOLD_OFF}{BOLD_OFF}c{BOLD_ON}d"); + assert_eq!(html(&messy), "abcd"); + } + + #[test] + fn bold_strips_markers_from_its_content() { + assert_eq!(plain(&bold(&format!("x{BOLD_OFF}y"))), "xy"); + assert_eq!(html(&bold(&format!("x{BOLD_OFF}y"))), "xy"); + } + + #[test] + fn truncate_counts_visible_chars_and_html_closes_bold() { + let text = format!("{}{}{}", BOLD_ON, "a".repeat(10), BOLD_OFF); + let cut = truncate(&text, 4); + assert_eq!(html(&cut), "aaaa"); + assert_eq!(truncate("&&&&", 2), "&&"); + } +} diff --git a/src/notify/message.rs b/src/notify/message.rs index f01187f..94cbade 100644 --- a/src/notify/message.rs +++ b/src/notify/message.rs @@ -33,6 +33,7 @@ use std::time::Duration; use jiff::tz::TimeZone; +use super::markup; use crate::state::{Effect, State, Transition}; use crate::store::codes::{FailureReason, SubjectKind}; use crate::time::zoned; @@ -140,6 +141,10 @@ fn change_of(t: &Transition) -> Change { } /// Build the message text, or `None` if nothing notifiable changed. +/// +/// The text carries bold markers (see [`markup`]): the target name and each status +/// (`web-1: host RECOVERED`, `ssh OFFLINE`) are bold, reasons, durations and times are +/// not. Use [`markup::plain`] for email and [`markup::html`] for Telegram. pub fn render(change: &TargetChange, tz: &TimeZone) -> Option { if !change.is_notifiable() { return None; @@ -156,8 +161,8 @@ pub fn render(change: &TargetChange, tz: &TimeZone) -> Option { } = &s.change { return Some(format!( - "{}: HOST OFFLINE ({}) since {}", - change.target_name, + "{} ({}) since {}", + markup::bold(&format!("{}: HOST OFFLINE", change.target_name)), reason.label(), format_time(*failing_since_ms, at, tz), )); @@ -167,19 +172,31 @@ pub fn render(change: &TargetChange, tz: &TimeZone) -> Option { let parts: Vec = change .subjects .iter() - .map(|s| { + .enumerate() + .map(|(i, s)| { let label = match s.kind { // "host" reads better than "ping" next to RECOVERED. SubjectKind::Ping if matches!(s.change, Change::Recovered { .. }) => "host", kind => kind.label(), }; + // The first status shares its bold run with the target name: + // `web-1: host RECOVERED`. + let bold_status = |status: &str| { + let status = format!("{label} {status}"); + if i == 0 { + markup::bold(&format!("{}: {status}", change.target_name)) + } else { + markup::bold(&status) + } + }; match &s.change { Change::Offline { reason, failing_since_ms, .. } => format!( - "{label} OFFLINE ({}) since {}", + "{} ({}) since {}", + bold_status("OFFLINE"), reason.label(), format_time(*failing_since_ms, at, tz) ), @@ -187,18 +204,19 @@ pub fn render(change: &TargetChange, tz: &TimeZone) -> Option { outage, failing_since_ms, } => format!( - "{label} RECOVERED after {} (down since {})", + "{} after {} (down since {})", + bold_status("RECOVERED"), human_duration(*outage), format_time(*failing_since_ms, at, tz) ), - Change::Current(State::Online) => format!("{label} OK"), - Change::Current(State::Degraded) => format!("{label} degraded"), - Change::Current(State::Offline) => format!("{label} OFFLINE"), - Change::Current(State::Unchecked) => format!("{label} unchecked"), + Change::Current(State::Online) => bold_status("OK"), + Change::Current(State::Degraded) => bold_status("degraded"), + Change::Current(State::Offline) => bold_status("OFFLINE"), + Change::Current(State::Unchecked) => bold_status("unchecked"), } }) .collect(); - Some(format!("{}: {}", change.target_name, parts.join(", "))) + Some(parts.join(", ")) } /// `14:02 UTC`, or `2026-11-29 23:40 UTC` when `ms` is on another local date than @@ -245,6 +263,11 @@ pub fn human_duration(d: Duration) -> String { #[cfg(test)] mod tests { use super::*; + + /// `render` without the bold markers, as the email shows it. + fn render_plain(c: &TargetChange, tz: &TimeZone) -> Option { + render(c, tz).map(|t| markup::plain(&t)) + } use crate::state::Status; use jiff::Timestamp; @@ -283,7 +306,7 @@ mod tests { ), ]); assert_eq!( - render(&c, &TimeZone::UTC).unwrap(), + render_plain(&c, &TimeZone::UTC).unwrap(), "ie-node: ping OK, ssh OK, https OFFLINE (handshake_reset) since 14:02 UTC" ); } @@ -299,11 +322,11 @@ mod tests { ]); let tokyo = TimeZone::get("Asia/Tokyo").unwrap(); assert_eq!( - render(&c, &tokyo).unwrap(), + render_plain(&c, &tokyo).unwrap(), "ie-node: ping OK, ssh OFFLINE (timeout) since 23:02 JST" ); let ny = TimeZone::get("America/New_York").unwrap(); - assert!(render(&c, &ny).unwrap().ends_with("since 09:02 EST")); + assert!(render_plain(&c, &ny).unwrap().ends_with("since 09:02 EST")); } #[test] @@ -319,7 +342,7 @@ mod tests { offline(FailureReason::HandshakeReset, "2026-11-30T14:02:00Z"), ), ]); - let text = render(&c, &TimeZone::UTC).unwrap(); + let text = render_plain(&c, &TimeZone::UTC).unwrap(); assert_eq!(text, "ie-node: HOST OFFLINE (timeout) since 14:02 UTC"); assert!(!text.contains("ssh") && !text.contains("https")); } @@ -337,7 +360,7 @@ mod tests { ), ]); assert_eq!( - render(&c, &TimeZone::UTC).unwrap(), + render_plain(&c, &TimeZone::UTC).unwrap(), "ie-node: ping OK, https RECOVERED after 12m (down since 13:51 UTC)" ); } @@ -352,7 +375,7 @@ mod tests { }, )]); assert_eq!( - render(&c, &TimeZone::UTC).unwrap(), + render_plain(&c, &TimeZone::UTC).unwrap(), "ie-node: host RECOVERED after 15h 23m (down since 2026-11-29 22:40 UTC)" ); } @@ -364,8 +387,8 @@ mod tests { (SubjectKind::Ssh, Change::Current(State::Degraded)), ]); assert!(!c.is_notifiable()); - assert_eq!(render(&c, &TimeZone::UTC), None); - assert_eq!(render(&change(vec![]), &TimeZone::UTC), None); + assert_eq!(render_plain(&c, &TimeZone::UTC), None); + assert_eq!(render_plain(&change(vec![]), &TimeZone::UTC), None); } #[test] @@ -467,4 +490,45 @@ mod tests { let c = TargetChange::from_transitions(9, "n", 3000, &[(SubjectKind::Ssh, t_deg)]); assert!(!c.is_notifiable()); } + + #[test] + fn name_and_status_are_bold_details_are_not() { + let c = change(vec![ + (SubjectKind::Ping, Change::Current(State::Online)), + ( + SubjectKind::Ssh, + offline(FailureReason::Refused, "2026-11-30T14:02:00Z"), + ), + ]); + assert_eq!( + markup::html(&render(&c, &TimeZone::UTC).unwrap()), + "ie-node: ping OK, ssh OFFLINE (refused) since 14:02 UTC" + ); + let host = change(vec![( + SubjectKind::Ping, + offline(FailureReason::Timeout, "2026-11-30T14:02:00Z"), + )]); + assert_eq!( + markup::html(&render(&host, &TimeZone::UTC).unwrap()), + "ie-node: HOST OFFLINE (timeout) since 14:02 UTC" + ); + } + + #[test] + fn hostile_target_name_is_escaped_in_html() { + let mut c = change(vec![( + SubjectKind::Ping, + offline(FailureReason::Timeout, "2026-11-30T14:02:00Z"), + )]); + c.target_name = "a".into(); + let text = render(&c, &TimeZone::UTC).unwrap(); + assert_eq!( + markup::html(&text), + "a<b&c>: HOST OFFLINE (timeout) since 14:02 UTC" + ); + assert_eq!( + markup::plain(&text), + "a: HOST OFFLINE (timeout) since 14:02 UTC" + ); + } } diff --git a/src/notify/telegram.rs b/src/notify/telegram.rs index 85b52d9..428781c 100644 --- a/src/notify/telegram.rs +++ b/src/notify/telegram.rs @@ -48,6 +48,7 @@ use std::time::Duration; use rustls::{ClientConfig, RootCertStore}; use super::config::TelegramConfig; +use super::markup; use crate::config::Secret; pub const DEFAULT_BASE_URL: &str = "https://api.telegram.org"; @@ -178,16 +179,23 @@ impl TelegramClient { self } - /// Send a plain-text message to the configured chat: one try plus one retry for - /// transient failures (timeouts, connection problems, 5xx). A 429 is not retried. + /// Send a message to the configured chat: one try plus one retry for transient + /// failures (timeouts, connection problems, 5xx). A 429 is not retried. + /// + /// `text` is plain text that may carry bold markers (see [`markup`]). It is cut to + /// [`MAX_TEXT_CHARS`] visible characters first and only then converted to Telegram + /// HTML (`parse_mode: "HTML"`), so a cut can never split a tag or an entity, and + /// everything that is not a bold marker is escaped: Telegram answers malformed HTML + /// with a 400 "can't parse entities". pub async fn send_message(&self, text: &str) -> Result<(), TelegramError> { if self.chat_id.is_empty() { return Err(TelegramError::NotConfigured); } - let text: String = text.chars().take(MAX_TEXT_CHARS).collect(); + let text = markup::html(&markup::truncate(text, MAX_TEXT_CHARS)); let body = serde_json::json!({ "chat_id": self.chat_id, "text": text, + "parse_mode": "HTML", "disable_web_page_preview": true, }); self.call_with_retry("sendMessage", &body).await.map(|_| ()) @@ -409,6 +417,28 @@ mod tests { let body: serde_json::Value = serde_json::from_slice(&requests[0].body).unwrap(); assert_eq!(body["chat_id"], "42"); assert_eq!(body["text"], "hello"); + assert_eq!(body["parse_mode"], "HTML"); + } + + #[tokio::test] + async fn text_is_escaped_bolded_and_cut_without_breaking_the_html() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(200).set_body_json(ok_body())) + .mount(&server) + .await; + let text = format!("{} & y", markup::bold("a serde_json::Value { serde_json::from_slice(&requests[i].body).unwrap() }; + assert_eq!(body(0)["text"], "a<b <x> & y"); + let cut = body(1)["text"].as_str().unwrap().to_owned(); + assert_eq!(cut, format!("{}", "&".repeat(MAX_TEXT_CHARS))); } #[tokio::test] diff --git a/src/notify/wiring.rs b/src/notify/wiring.rs index c44fbbb..54266a6 100644 --- a/src/notify/wiring.rs +++ b/src/notify/wiring.rs @@ -362,7 +362,7 @@ mod tests { let texts = texts(&tg).await; assert_eq!(texts.len(), 3, "{texts:?}"); for (text, name) in texts.iter().zip(["host-a", "host-b", "host-c"]) { - assert!(text.starts_with(&format!("🐧 {name}")), "{texts:?}"); + assert!(text.starts_with(&format!("🐧 {name}:")), "{texts:?}"); } assert_eq!(store.notification_count().await.unwrap(), 3); } diff --git a/src/test_seed.rs b/src/test_seed.rs index 9ca5c41..946551e 100644 --- a/src/test_seed.rs +++ b/src/test_seed.rs @@ -113,7 +113,8 @@ pub async fn notification( ) -> u64 { store .insert_notification(NotificationV1 { - message: format!("message at {created_ms}"), + // Bold markers as real alerts have; every reader must strip them. + message: format!("{} at {created_ms}", crate::notify::markup::bold("message")), created_ms, telegram_status: telegram.code(), email_status: email.code(), diff --git a/src/web/notifications.rs b/src/web/notifications.rs index a0ee125..6c074e8 100644 --- a/src/web/notifications.rs +++ b/src/web/notifications.rs @@ -565,7 +565,7 @@ async fn queue_template( email: channel_text(r.email()), attempts: format!("{} / {}", r.telegram_attempts, r.email_attempts), last_error: r.last_error, - message: r.message, + message: crate::notify::markup::plain(&r.message), }) .collect(); Ok(QueueTemplate {