operserv: REHASH reloads config live without a restart
All checks were successful
CI / check (push) Successful in 3m54s

This commit is contained in:
Jean Chevronnet 2026-07-17 10:46:12 +00:00
parent e112b8737c
commit 64b675e61f
No known key found for this signature in database
8 changed files with 126 additions and 1 deletions

View file

@ -169,6 +169,11 @@ pub enum NetAction {
// link layer exits cleanly; `restart` exits non-zero so a supervisor (systemd
// Restart=) brings it back. Never serialized.
Shutdown { restart: bool, reason: String },
// Internal only: re-read config.toml and apply the reloadable settings to the
// running engine (OperServ REHASH). The link layer resolves it against the
// engine and sends the outcome back to `requester` from `agent`. Never
// serialized as-is.
Rehash { requester: String, agent: String },
}
// How to answer a registration once its credentials have been derived.
@ -386,6 +391,13 @@ impl ServiceCtx {
self.actions.push(NetAction::Shutdown { restart, reason: reason.into() });
}
// Re-read config.toml and apply the reloadable settings live (OperServ REHASH).
// The engine resolves this off the command path and notices `requester` from
// `agent` with the outcome.
pub fn rehash(&mut self, agent: &str, requester: &str) {
self.actions.push(NetAction::Rehash { requester: requester.to_string(), agent: agent.to_string() });
}
// Hand a password change to the engine to finish: its derivation runs off the
// reactor, then the engine commits it and notices `uid`, sourced from `agent`.
pub fn defer_password(&mut self, account: impl Into<String>, password: impl Into<String>, agent: impl Into<String>, uid: impl Into<String>) {

View file

@ -39,6 +39,8 @@ mod logsearch;
mod defcon;
#[path = "shutdown.rs"]
mod shutdown;
#[path = "rehash.rs"]
mod rehash;
#[path = "set.rs"]
mod set;
@ -95,6 +97,7 @@ impl Service for OperServ {
Some(cmd) if cmd.eq_ignore_ascii_case("SET") => set::handle(me, from, args, ctx, db),
Some(cmd) if cmd.eq_ignore_ascii_case("SHUTDOWN") => shutdown::handle(me, from, false, args, ctx),
Some(cmd) if cmd.eq_ignore_ascii_case("RESTART") => shutdown::handle(me, from, true, args, ctx),
Some(cmd) if cmd.eq_ignore_ascii_case("REHASH") => rehash::handle(me, from, ctx),
Some(cmd) if cmd.eq_ignore_ascii_case("HELP") => echo_api::help(me, from, ctx, BLURB, TOPICS, args.get(1).copied()),
None => echo_api::help(me, from, ctx, BLURB, TOPICS, None),
Some(other) => ctx.notice(me, from.uid, format!("I don't know \x02{other}\x02. Try \x02HELP\x02.")),
@ -131,4 +134,5 @@ const TOPICS: &[HelpEntry] = &[
HelpEntry { cmd: "SET", summary: "services-wide settings", detail: "Syntax: \x02SET READONLY {ON|OFF}\x02\nToggles read-only lockdown: while on, no registrations or changes are accepted." },
HelpEntry { cmd: "SHUTDOWN", summary: "stop services", detail: "Syntax: \x02SHUTDOWN [reason]\x02\nStops the services process. It stays down until restarted." },
HelpEntry { cmd: "RESTART", summary: "restart services", detail: "Syntax: \x02RESTART [reason]\x02\nRestarts the services process (a supervisor respawns it)." },
HelpEntry { cmd: "REHASH", summary: "reload the configuration", detail: "Syntax: \x02REHASH\x02\nRe-reads config.toml and applies the settings that are safe to change while linked (opers, standard-replies, services channel, service oper-type, expiry, session limits) without a restart — no relink, no user disruption. Server identity, service umodes and the keycard endpoint still need a RESTART." },
];

View file

@ -0,0 +1,15 @@
use echo_api::{Priv, Sender, ServiceCtx};
// REHASH: re-read config.toml and apply the settings that are safe to change
// while linked (opers, standard-replies, services channel, service oper-type,
// expiry, session limits) without restarting — so no relink and no user
// disruption. Admin-only. Server identity, service umodes and the keycard
// endpoint still need a RESTART. The engine does the re-read off the command
// path and notices the outcome (or a parse error, keeping the old config).
pub fn handle(me: &str, from: &Sender, ctx: &mut ServiceCtx) {
if !from.privs.has(Priv::Admin) {
ctx.notice(me, from.uid, "Access denied — REHASH needs the \x02admin\x02 privilege.");
return;
}
ctx.rehash(me, from.uid);
}

View file

@ -431,7 +431,7 @@ impl Protocol for InspIrcd {
NetAction::Squit { target, reason } => vec![self.sourced(format!("SQUIT {} :{}", target, reason))],
NetAction::Raw(s) => vec![s.clone()],
// Internal: the link layer handles these before serialization.
NetAction::DeferRegister { .. } | NetAction::DeferPassword { .. } | NetAction::DeferAuthenticate { .. } | NetAction::DeferKeycard { .. } | NetAction::SendEmail { .. } | NetAction::Shutdown { .. } => vec![],
NetAction::DeferRegister { .. } | NetAction::DeferPassword { .. } | NetAction::DeferAuthenticate { .. } | NetAction::DeferKeycard { .. } | NetAction::SendEmail { .. } | NetAction::Shutdown { .. } | NetAction::Rehash { .. } => vec![],
};
// A trailing parameter can carry free-form text (message bodies, kick
// reasons, topics, metadata). Strip CR/LF/NUL at this single choke-point

View file

@ -107,6 +107,7 @@ pub struct Engine {
service_oper_type: String, // oper type our services are flagged with (WHOIS "is a <this>"); 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
config_path: String, // path to config.toml, so OperServ REHASH can re-read it live
enforce_seq: u32, // counter appended to guest_nick
pending_enforce: Vec<PendingEnforce>, // registered nicks awaiting identify-or-rename
bot_uids: HashMap<String, String>, // casefolded bot nick -> live uid (per connection)
@ -244,6 +245,7 @@ impl Engine {
service_oper_type: String::new(),
services_channel: String::new(),
standard_replies: false,
config_path: String::new(),
enforce_seq: 0,
pending_enforce: Vec::new(),
bot_uids: HashMap::new(),
@ -791,6 +793,54 @@ impl Engine {
self.standard_replies = on;
}
pub fn set_config_path(&mut self, path: impl Into<String>) {
self.config_path = path.into();
}
// Re-read config.toml and apply the settings that are safe to change while
// linked, reporting the outcome to the oper who ran REHASH. A parse error
// keeps the running configuration untouched (validate-or-keep, like an ircd
// rehash). Server identity (name/sid/protocol/uplink), service umodes and the
// keycard endpoint are NOT reloadable — they need a restart.
pub fn rehash(&mut self, requester: &str, agent: &str) -> Vec<NetAction> {
let path = self.config_path.clone();
let cfg = match crate::config::Config::load(&path) {
Ok(cfg) => cfg,
Err(e) => {
return vec![NetAction::Notice {
from: agent.to_string(),
to: requester.to_string(),
text: format!("REHASH failed: {e}. The running configuration is unchanged."),
}];
}
};
let opers = cfg.opers();
let oper_count = opers.len();
self.set_opers(opers);
self.set_service_oper_type(cfg.server.service_oper_type.clone());
self.set_services_channel(cfg.server.services_channel.clone());
self.set_standard_replies(cfg.server.standard_replies);
self.set_log_channel(cfg.log.as_ref().map(|l| l.channel.clone()));
self.set_guest_nick(&cfg.server.guest_nick);
if let Some(expire) = &cfg.expire {
self.set_expiry(expire.account_ttl(), expire.channel_ttl(), expire.warn_ttl());
}
if let Some(session) = &cfg.session {
self.set_session_limit(session.limit());
}
let notice = |text: String| NetAction::Notice { from: agent.to_string(), to: requester.to_string(), text };
vec![
notice(format!("Configuration reloaded from \x02{path}\x02.")),
notice(format!(
"Applied: \x02{oper_count}\x02 oper(s), standard-replies \x02{}\x02, services channel \x02{}\x02, service oper-type \x02{}\x02.",
if self.standard_replies { "on" } else { "off" },
if self.services_channel.is_empty() { "(none)" } else { &self.services_channel },
if self.service_oper_type.is_empty() { "(none)" } else { &self.service_oper_type },
)),
notice("Not reloadable (need a RESTART): server name/SID/protocol, uplink, service umodes, keycard.".to_string()),
]
}
// 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

View file

@ -673,6 +673,44 @@
assert_eq!(e.network.account_of("000AAAAAB"), None, "empty account is a logout");
}
// OperServ REHASH is admin-only and hands the reload to the engine (resolved
// in the link layer) addressed back to the oper who ran it.
#[test]
fn operserv_rehash_is_admin_only() {
use echo_operserv::OperServ;
let path = std::env::temp_dir().join("echo-opsrehash.jsonl");
let _ = std::fs::remove_file(&path);
let mut db = Db::open(&path, "test");
db.scram_iterations = 4096;
db.register("alice", "sesame", None).unwrap();
db.register("bob", "sesame", None).unwrap();
let mut e = Engine::new(
vec![
Box::new(NickServ { uid: "42SAAAAAA".into(), guest_nick: "Guest".into(), guest_seq: 0 }),
Box::new(OperServ { uid: "42SAAAAAH".into() }),
],
db,
);
e.set_sid("42S".into());
let mut opers = std::collections::HashMap::new();
opers.insert("alice".to_string(), Privs::default().with(echo_api::Priv::Admin));
opers.insert("bob".to_string(), Privs::default().with(echo_api::Priv::Auspex));
e.set_opers(opers);
e.handle(NetEvent::UserConnect { uid: "000AAAAAB".into(), nick: "alice".into(), host: "h".into(), ip: "0.0.0.0".into() });
e.handle(NetEvent::Privmsg { from: "000AAAAAB".into(), to: "42SAAAAAA".into(), text: "IDENTIFY sesame".into() });
e.handle(NetEvent::UserConnect { uid: "000AAAAAC".into(), nick: "bob".into(), host: "h".into(), ip: "0.0.0.0".into() });
e.handle(NetEvent::Privmsg { from: "000AAAAAC".into(), to: "42SAAAAAA".into(), text: "IDENTIFY sesame".into() });
// Admin: hands off the reload, addressed back to the requesting oper.
let a = e.handle(NetEvent::Privmsg { from: "000AAAAAB".into(), to: "42SAAAAAH".into(), text: "REHASH".into() });
assert!(a.iter().any(|x| matches!(x, NetAction::Rehash { requester, agent } if requester == "000AAAAAB" && agent == "42SAAAAAH")), "{a:?}");
// Oper without admin: denied, no reload handed off.
let b = e.handle(NetEvent::Privmsg { from: "000AAAAAC".into(), to: "42SAAAAAH".into(), text: "REHASH".into() });
assert!(!b.iter().any(|x| matches!(x, NetAction::Rehash { .. })), "non-admin must not rehash: {b:?}");
assert!(b.iter().any(|x| matches!(x, NetAction::Notice { text, .. } if text.contains("admin"))), "{b:?}");
}
// A login that finishes off the handle() path (the link layer's deferred
// password/keycard verify) must still make echo's OWN account map authoritative.
// Otherwise re-identifying an already-logged-in user after a services relink —

View file

@ -143,6 +143,11 @@ pub async fn run(mut proto: Box<dyn Protocol>, engine: Arc<Mutex<Engine>>, addr:
.await?;
engine.lock().await.complete_authenticate(ok, then)
}
// OperServ REHASH: re-read config.toml and apply the
// reloadable settings live, reporting back to the oper.
NetAction::Rehash { requester, agent } => {
engine.lock().await.rehash(&requester, &agent)
}
action => vec![action],
};
for act in outs {

View file

@ -184,6 +184,7 @@ async fn main() -> Result<()> {
let (irc_tx, irc_rx) = tokio::sync::mpsc::unbounded_channel();
engine.lock().await.set_irc_out(irc_tx);
engine.lock().await.set_opers(cfg.opers());
engine.lock().await.set_config_path(path.clone());
engine.lock().await.set_sid(cfg.server.sid.clone());
engine.lock().await.set_guest_nick(&cfg.server.guest_nick);
// Service pseudo-clients wear the configured host, or the server name.