From 75c65375322243380858a234f975cc0c887bf75e Mon Sep 17 00:00:00 2001 From: Jean Date: Fri, 17 Jul 2026 02:53:48 +0000 Subject: [PATCH] standard replies: emit IRCv3 FAIL/WARN/NOTE for service errors, config-gated --- api/src/lib.rs | 47 ++++++++++++++++++++++++++++ modules/nickserv/src/identify.rs | 8 ++--- modules/protocol/inspircd/src/lib.rs | 38 ++++++++++++++++++++++ src/config.rs | 5 +++ src/engine/mod.rs | 27 ++++++++++++++++ src/engine/register.rs | 2 +- src/engine/tests.rs | 30 ++++++++++++++++++ src/main.rs | 1 + 8 files changed, 153 insertions(+), 5 deletions(-) diff --git a/api/src/lib.rs b/api/src/lib.rs index 3c66773..d4560c2 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -64,6 +64,20 @@ pub enum NetEvent { Unknown { line: String }, } +// The three IRCv3 standard-reply verbs (https://ircv3.net/specs/extensions/standard-replies). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ReplyKind { Fail, Warn, Note } + +impl ReplyKind { + pub fn verb(self) -> &'static str { + match self { + ReplyKind::Fail => "FAIL", + ReplyKind::Warn => "WARN", + ReplyKind::Note => "NOTE", + } + } +} + // Normalized outbound intents the engine wants performed on the network. #[derive(Debug, Clone)] pub enum NetAction { @@ -79,6 +93,11 @@ pub enum NetAction { IntroduceUser { uid: String, nick: String, ident: String, host: String, gecos: String }, Privmsg { from: String, to: String, text: String }, Notice { from: String, to: String, text: String }, + // An IRCv3 standard reply (FAIL/WARN/NOTE) from a service to a client. Not + // routable over s2s directly, so it's encapsulated for the target's server + // (m_services_stdrpl) to re-emit locally, cap-gated. `command`/`from` may be + // "*" for none/server-sourced. Degrades to a Notice when the feature is off. + StandardReply { kind: ReplyKind, from: String, to: String, command: String, code: String, text: String }, AccountResponse { reqid: String, origin: String, kind: String, account: String, status: String, code: String, message: String }, // A SASL exchange step back to the ircd, sourced from our SASL agent. mode = C/D. Sasl { agent: String, client: String, mode: String, data: Vec }, @@ -300,6 +319,34 @@ impl ServiceCtx { }); } + // IRCv3 standard replies from a service (`from` uid) to a client (`to` uid). + // FAIL = the command failed; WARN = it worked but mind the caveat; NOTE = + // informational. `command` is the command the reply relates to (or "*"), + // `code` a machine-readable token (e.g. "ACCESS_DENIED"). Spec-aware clients + // render the code + text; the rest get a plain notice (engine/module decide). + pub fn fail(&mut self, from: &str, to: &str, command: &str, code: &str, text: impl Into) { + self.standard_reply(ReplyKind::Fail, from, to, command, code, text); + } + + pub fn warn(&mut self, from: &str, to: &str, command: &str, code: &str, text: impl Into) { + self.standard_reply(ReplyKind::Warn, from, to, command, code, text); + } + + pub fn note(&mut self, from: &str, to: &str, command: &str, code: &str, text: impl Into) { + self.standard_reply(ReplyKind::Note, from, to, command, code, text); + } + + fn standard_reply(&mut self, kind: ReplyKind, from: &str, to: &str, command: &str, code: &str, text: impl Into) { + self.actions.push(NetAction::StandardReply { + kind, + from: from.to_string(), + to: to.to_string(), + command: command.to_string(), + code: code.to_string(), + text: text.into(), + }); + } + // Record a stat counter bump (namespaced, e.g. "chanserv.register"). Folded // into the engine's shared registry, which the gRPC Stats API exposes. pub fn count(&mut self, key: impl Into) { diff --git a/modules/nickserv/src/identify.rs b/modules/nickserv/src/identify.rs index 236dbed..311aa5e 100644 --- a/modules/nickserv/src/identify.rs +++ b/modules/nickserv/src/identify.rs @@ -14,7 +14,7 @@ pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: }; // Distinguish an unregistered account from a wrong password. if !db.exists(account_name) { - ctx.notice(me, from.uid, format!("\x02{account_name}\x02 isn't registered.")); + ctx.fail(me, from.uid, "IDENTIFY", "ACCOUNT_NOT_REGISTERED", format!("\x02{account_name}\x02 isn't registered.")); return; } // A suspended account can't be logged into (checked before the password so it @@ -33,14 +33,14 @@ pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: msg.push_str(&format!(" The suspension is due to lift on {}.", human_time(exp))); } msg.push_str(" If you think this is a mistake, please contact the network staff."); - ctx.notice(me, from.uid, msg); + ctx.fail(me, from.uid, "IDENTIFY", "ACCOUNT_SUSPENDED", msg); } return; } } // Refuse while throttled, so a password can't be brute-forced. if let Some(secs) = db.auth_lockout(account_name) { - ctx.notice(me, from.uid, format!("Too many failed attempts. Please wait {secs}s and try again.")); + ctx.fail(me, from.uid, "IDENTIFY", "RATE_LIMITED", format!("Too many failed attempts. Please wait {secs}s and try again.")); return; } // Fetch the verifier cheaply and hand the (~1s) PBKDF2 verify to the engine to @@ -51,7 +51,7 @@ pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: // Exists but has no verifier (e.g. cert-only) — a password can't match. db.note_auth(account_name, false); ctx.count("nickserv.identify_fail"); - ctx.notice(me, from.uid, "Invalid password. Please try again."); + ctx.fail(me, from.uid, "IDENTIFY", "INVALID_CREDENTIALS", "Invalid password. Please try again."); } Some((account, verifier)) => { // Already identified to this account: skip the (wasted) verify. diff --git a/modules/protocol/inspircd/src/lib.rs b/modules/protocol/inspircd/src/lib.rs index e79f232..ae7f003 100644 --- a/modules/protocol/inspircd/src/lib.rs +++ b/modules/protocol/inspircd/src/lib.rs @@ -315,6 +315,17 @@ impl Protocol for InspIrcd { NetAction::Notice { from, to, text } => { vec![format!(":{} NOTICE {} :{}", from, to, text)] } + // Standard reply: encapsulate for the target's server to re-emit locally + // (FAIL/WARN/NOTE aren't s2s-routable). ENCAP * so only the server the + // target is local to acts. "*" = no source service / no command. + NetAction::StandardReply { kind, from, to, command, code, text } => { + let src = if from.is_empty() { "*" } else { from.as_str() }; + let cmd = if command.is_empty() { "*" } else { command.as_str() }; + vec![self.sourced(format!( + "ENCAP * SWSTDRPL {to} {src} {verb} {cmd} {code} :{text}", + verb = kind.verb() + ))] + } // Answer the origin server: ENCAP SWACCTRES // : NetAction::AccountResponse { reqid, origin, kind, account, status, code, message } => { @@ -623,6 +634,33 @@ mod tests { assert!(!lines[0].contains('\n') && !lines[0].contains('\r')); } + // A standard reply encapsulates as ENCAP * SWSTDRPL + // :, sourced from the services server so the target's + // server (m_services_stdrpl) can re-emit it locally. + #[test] + fn standard_reply_serializes_to_encap() { + let lines = proto().serialize(&NetAction::StandardReply { + kind: echo_api::ReplyKind::Fail, + from: "42SAAAAAB".into(), + to: "0IRAAAAAB".into(), + command: "IDENTIFY".into(), + code: "INVALID_CREDENTIALS".into(), + text: "Invalid password. Please try again.".into(), + }); + assert_eq!(lines, vec![":42S ENCAP * SWSTDRPL 0IRAAAAAB 42SAAAAAB FAIL IDENTIFY INVALID_CREDENTIALS :Invalid password. Please try again.".to_string()]); + + // Empty source/command collapse to "*". + let lines = proto().serialize(&NetAction::StandardReply { + kind: echo_api::ReplyKind::Note, + from: String::new(), + to: "0IRAAAAAB".into(), + command: String::new(), + code: "INFO".into(), + text: "heads up".into(), + }); + assert_eq!(lines, vec![":42S ENCAP * SWSTDRPL 0IRAAAAAB * NOTE * INFO :heads up".to_string()]); + } + // Account-registration relay wire format, matching the ircd's account module: // a leaf forwards ENCAP SWACCTREG // :, and we answer the origin server with ENCAP SWACCTRES. The diff --git a/src/config.rs b/src/config.rs index f2c0355..5b9e773 100644 --- a/src/config.rs +++ b/src/config.rs @@ -293,6 +293,11 @@ pub struct Server { // startup. Default "#services"; empty leaves them out of any channel. #[serde(default = "default_services_channel")] pub services_channel: String, + // Emit IRCv3 standard replies (FAIL/WARN/NOTE) for service errors instead of + // plain notices. Needs m_services_stdrpl loaded on the ircd; off until then, + // otherwise the replies are dropped. Off = today's notice behaviour. + #[serde(default)] + pub standard_replies: bool, } fn default_services_channel() -> String { diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 3a54418..c86d6fb 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -106,6 +106,7 @@ pub struct Engine { service_host: String, // hostname the service pseudo-clients wear service_oper_type: String, // oper type our services are flagged with (WHOIS "is a "); empty = don't oper services_channel: String, // channel all service pseudo-clients join at startup; empty = none + standard_replies: bool, // emit IRCv3 FAIL/WARN/NOTE for service errors; off = degrade to notices enforce_seq: u32, // counter appended to guest_nick pending_enforce: Vec, // registered nicks awaiting identify-or-rename bot_uids: HashMap, // casefolded bot nick -> live uid (per connection) @@ -242,6 +243,7 @@ impl Engine { service_host: "services.local".to_string(), service_oper_type: String::new(), services_channel: String::new(), + standard_replies: false, enforce_seq: 0, pending_enforce: Vec::new(), bot_uids: HashMap::new(), @@ -785,6 +787,10 @@ impl Engine { self.services_channel = channel.into(); } + pub fn set_standard_replies(&mut self, on: bool) { + self.standard_replies = on; + } + // A user arrived on (or changed to) a registered nick: if they aren't logged // into that account, prompt them to IDENTIFY and schedule a rename. Gated on // `synced` so a netburst can't enforce every already-online user; a user who @@ -1287,9 +1293,30 @@ impl Engine { // Give every user-removal a traceable incident id, stamped into its reason // and recorded in the searchable log (OperServ LOGSEARCH). self.stamp_incidents(&mut out); + // When standard replies are off (or the ircd module isn't loaded), a + // FAIL/WARN/NOTE would be dropped — degrade each to a plain notice so the + // user always hears the outcome. + if !self.standard_replies { + self.degrade_standard_replies(&mut out); + } out } + // Rewrite any StandardReply into an equivalent Notice `*** command: text` + // (or `*** text` when there's no command), sourced from the same service. + fn degrade_standard_replies(&self, actions: &mut [NetAction]) { + for a in actions.iter_mut() { + if let NetAction::StandardReply { from, to, command, text, .. } = a { + let body = if command.is_empty() || command == "*" { + format!("*** {text}") + } else { + format!("*** {command}: {text}") + }; + *a = NetAction::Notice { from: std::mem::take(from), to: std::mem::take(to), text: body }; + } + } + } + // Mint an incident id for each kick/kill in `actions`, append `[#id]` to its // reason, and record a searchable summary. One choke-point so every removal — // from a bot kicker, a fantasy command, a vote, or an operator — is logged. diff --git a/src/engine/register.rs b/src/engine/register.rs index 0e4783a..923bc57 100644 --- a/src/engine/register.rs +++ b/src/engine/register.rs @@ -281,7 +281,7 @@ impl Engine { let mut ctx = ServiceCtx::default(); if !ok { ctx.count("nickserv.identify_fail"); - ctx.notice(&agent, &uid, "Invalid password. Please try again."); + ctx.fail(&agent, &uid, "IDENTIFY", "INVALID_CREDENTIALS", "Invalid password. Please try again."); } else { ctx.login(&uid, &account); ctx.count("nickserv.identify"); diff --git a/src/engine/tests.rs b/src/engine/tests.rs index e7d55b6..6225546 100644 --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -325,6 +325,36 @@ assert!(matches!(e.db.certfp_add("bar", fp), Err(db::CertError::InUse)), "a fingerprint maps to one account"); } + // Standard replies gate: off (default) degrades a service FAIL to a notice so + // nothing is lost; on, the structured FAIL survives with command + code. + #[test] + fn standard_replies_gate_service_failures() { + let connect = |e: &mut Engine| { + e.handle(NetEvent::UserConnect { uid: "000AAAAAB".into(), nick: "foo".into(), host: "h".into(), ip: "0.0.0.0".into() }); + }; + let identify_unregistered = |e: &mut Engine| e.handle(NetEvent::Privmsg { + from: "000AAAAAB".into(), to: "42SAAAAAA".into(), text: "IDENTIFY ghost pw".into(), + }); + + // Off: no StandardReply reaches the wire; the user still gets a notice. + let mut off = engine_with("stdrploff", "foo", "sesame"); + connect(&mut off); + let a = identify_unregistered(&mut off); + assert!(a.iter().any(|x| matches!(x, NetAction::Notice { text, .. } if text.contains("isn't registered"))), "{a:?}"); + assert!(!a.iter().any(|x| matches!(x, NetAction::StandardReply { .. })), "off must degrade: {a:?}"); + + // On: the FAIL survives, carrying the command and machine code. + let mut on = engine_with("stdrplon", "foo", "sesame"); + on.set_standard_replies(true); + connect(&mut on); + let b = identify_unregistered(&mut on); + let hit = b.iter().find_map(|x| match x { + NetAction::StandardReply { kind, command, code, .. } => Some((kind.verb(), command.clone(), code.clone())), + _ => None, + }); + assert_eq!(hit, Some(("FAIL", "IDENTIFY".to_string(), "ACCOUNT_NOT_REGISTERED".to_string())), "{b:?}"); + } + // IDENTIFY logs in, LOGOUT clears the accountname (ircd emits RPL_LOGGEDOUT). #[test] fn nickserv_logout_clears_account() { diff --git a/src/main.rs b/src/main.rs index 2aa2a77..50efab9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -191,6 +191,7 @@ async fn main() -> Result<()> { engine.lock().await.set_service_host(service_host); engine.lock().await.set_service_oper_type(cfg.server.service_oper_type.clone()); engine.lock().await.set_services_channel(cfg.server.services_channel.clone()); + engine.lock().await.set_standard_replies(cfg.server.standard_replies); engine.lock().await.set_log_channel(cfg.log.as_ref().map(|l| l.channel.clone())); if enabled("debugserv") { // DebugServ speaks the live feed into the log channel; give the engine its uid.