From a67409e0d3e5932d2dba2b283ae311f4d8a397a8 Mon Sep 17 00:00:00 2001 From: Jean Date: Tue, 14 Jul 2026 01:33:30 +0000 Subject: [PATCH] =?UTF-8?q?OperServ:=20OPER=20=E2=80=94=20runtime=20operat?= =?UTF-8?q?or=20management?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OPER ADD / DEL / LIST grants or revokes services-operator privileges (auspex, suspend, admin) at runtime, without editing config and restarting. Runtime grants are event-sourced (Global, so they federate and survive restart) and UNIONED with the declarative [[oper]] config at the engine, so either source makes an account an operator; a config oper can't be revoked here. Admin-only. Factored the privilege-name parsing into Privs::from_names (+ names/union) so config loading and runtime grants share one definition. --- api/src/lib.rs | 33 ++++++++++++++++++++++ operserv/src/lib.rs | 5 +++- operserv/src/oper.rs | 65 ++++++++++++++++++++++++++++++++++++++++++++ src/config.rs | 12 +------- src/engine/db.rs | 57 ++++++++++++++++++++++++++++++++++++-- src/engine/mod.rs | 58 +++++++++++++++++++++++++++++++++++++-- src/grpc.rs | 4 ++- 7 files changed, 217 insertions(+), 17 deletions(-) create mode 100644 operserv/src/oper.rs diff --git a/api/src/lib.rs b/api/src/lib.rs index 2571176..e1c228c 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -181,6 +181,35 @@ impl Privs { pub fn any(self) -> bool { self.0 != 0 } + + // The union of two privilege sets (holds a privilege in either). + pub fn union(self, other: Privs) -> Self { + Privs(self.0 | other.0) + } + + // Build a set from privilege names ("auspex"/"suspend"/"admin"), ignoring any + // that aren't recognised. Shared by the config loader and runtime OPER grants. + pub fn from_names>(names: &[S]) -> Self { + let mut privs = Privs::default(); + for n in names { + match n.as_ref().to_ascii_lowercase().as_str() { + "auspex" => privs = privs.with(Priv::Auspex), + "suspend" => privs = privs.with(Priv::Suspend), + "admin" => privs = privs.with(Priv::Admin), + _ => {} + } + } + privs + } + + // The privilege names held, for display. + pub fn names(self) -> Vec<&'static str> { + [(Priv::Auspex, "auspex"), (Priv::Suspend, "suspend"), (Priv::Admin, "admin")] + .into_iter() + .filter(|(p, _)| self.has(*p)) + .map(|(_, n)| n) + .collect() + } } // Who sent the command, resolved by the engine (UID + current nick + the @@ -731,6 +760,10 @@ pub trait Store { fn news_add(&mut self, kind: &str, text: &str, setter: &str) -> u64; fn news_del(&mut self, id: u64) -> bool; fn news(&self, kind: &str) -> Vec; + // Runtime operator grants (OperServ OPER), merged with config opers. + fn oper_grant(&mut self, account: &str, privs: Vec); + fn oper_revoke(&mut self, account: &str) -> bool; + fn opers_list(&self) -> Vec<(String, Vec)>; fn register_channel(&mut self, name: &str, founder: &str) -> Result<(), ChanError>; fn drop_channel(&mut self, name: &str) -> Result<(), ChanError>; fn set_mlock(&mut self, name: &str, on: &str, off: &str) -> Result<(), ChanError>; diff --git a/operserv/src/lib.rs b/operserv/src/lib.rs index 690ef02..284c74c 100644 --- a/operserv/src/lib.rs +++ b/operserv/src/lib.rs @@ -25,6 +25,8 @@ mod svs; mod info; #[path = "news.rs"] mod news; +#[path = "oper.rs"] +mod oper; pub struct OperServ { pub uid: String, @@ -61,6 +63,7 @@ impl Service for OperServ { Some(cmd) if cmd.eq_ignore_ascii_case("SVSJOIN") => svs::join(me, from, args, ctx, net), Some(cmd) if cmd.eq_ignore_ascii_case("INFO") => info::handle(me, from, args, ctx, db), Some(cmd) if cmd.eq_ignore_ascii_case("NEWS") => news::handle(me, from, args, ctx, db), + Some(cmd) if cmd.eq_ignore_ascii_case("OPER") => oper::handle(me, from, args, ctx, db), Some(cmd) if cmd.eq_ignore_ascii_case("HELP") => help(me, from, ctx), None => help(me, from, ctx), Some(other) => ctx.notice(me, from.uid, format!("I don't know \x02{other}\x02. Try \x02HELP\x02.")), @@ -69,5 +72,5 @@ impl Service for OperServ { } fn help(me: &str, from: &Sender, ctx: &mut ServiceCtx) { - ctx.notice(me, from.uid, "OperServ holds network operator tools (Priv::Admin): \x02AKILL\x02 ADD|DEL|LIST (user@host bans), \x02SQLINE\x02 ADD|DEL|LIST (nick bans), \x02GLOBAL\x02 (announce to everyone), \x02KILL\x02 [reason] (disconnect a user), \x02KICK\x02 <#chan> [reason], \x02MODE\x02 <#chan> [params], \x02IGNORE\x02 ADD|DEL|LIST (silence a user from services), \x02STATS\x02 (enforcement overview), \x02SVSNICK\x02 , \x02SVSJOIN\x02 <#chan> [key], \x02INFO\x02 ADD|DEL (staff notes), \x02NEWS\x02 ADD|DEL|LIST (announcements)."); + ctx.notice(me, from.uid, "OperServ holds network operator tools (Priv::Admin): \x02AKILL\x02 ADD|DEL|LIST (user@host bans), \x02SQLINE\x02 ADD|DEL|LIST (nick bans), \x02GLOBAL\x02 (announce to everyone), \x02KILL\x02 [reason] (disconnect a user), \x02KICK\x02 <#chan> [reason], \x02MODE\x02 <#chan> [params], \x02IGNORE\x02 ADD|DEL|LIST (silence a user from services), \x02STATS\x02 (enforcement overview), \x02SVSNICK\x02 , \x02SVSJOIN\x02 <#chan> [key], \x02INFO\x02 ADD|DEL (staff notes), \x02NEWS\x02 ADD|DEL|LIST (announcements), \x02OPER\x02 ADD|DEL|LIST (runtime operators)."); } diff --git a/operserv/src/oper.rs b/operserv/src/oper.rs new file mode 100644 index 0000000..63265a9 --- /dev/null +++ b/operserv/src/oper.rs @@ -0,0 +1,65 @@ +use fedserv_api::{Priv, Sender, ServiceCtx, Store}; + +// OPER ADD | OPER DEL | OPER LIST: manage +// runtime services operators (merged with the declarative config opers). The +// privileges are auspex, suspend, admin. Admin-only — only an admin grants oper. +pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) { + if !from.privs.has(Priv::Admin) { + ctx.notice(me, from.uid, "Access denied — OPER needs the \x02admin\x02 privilege."); + return; + } + match args.get(1).map(|s| s.to_ascii_uppercase()).as_deref() { + Some("ADD") | Some("SET") => add(me, from, args.get(2).copied(), args.get(3).copied(), ctx, db), + Some("DEL") | Some("REMOVE") => del(me, from, args.get(2).copied(), ctx, db), + Some("LIST") | Some("VIEW") => list(me, from, ctx, db), + _ => ctx.notice(me, from.uid, "Syntax: OPER ADD | OPER DEL | OPER LIST — privs: auspex, suspend, admin"), + } +} + +fn add(me: &str, from: &Sender, account: Option<&str>, privs: Option<&str>, ctx: &mut ServiceCtx, db: &mut dyn Store) { + let (Some(account), Some(privs)) = (account, privs) else { + ctx.notice(me, from.uid, "Syntax: OPER ADD "); + return; + }; + let Some(account) = db.resolve_account(account).map(str::to_string) else { + ctx.notice(me, from.uid, format!("\x02{account}\x02 isn't registered.")); + return; + }; + // Keep only recognised privilege names. + let names: Vec = privs + .split(',') + .map(|p| p.trim().to_ascii_lowercase()) + .filter(|p| matches!(p.as_str(), "auspex" | "suspend" | "admin")) + .collect(); + if names.is_empty() { + ctx.notice(me, from.uid, "No valid privileges given (auspex, suspend, admin)."); + return; + } + db.oper_grant(&account, names.clone()); + ctx.notice(me, from.uid, format!("\x02{account}\x02 is now an operator ({}).", names.join(", "))); +} + +fn del(me: &str, from: &Sender, account: Option<&str>, ctx: &mut ServiceCtx, db: &mut dyn Store) { + let Some(account) = account else { + ctx.notice(me, from.uid, "Syntax: OPER DEL "); + return; + }; + let canonical = db.resolve_account(account).map(str::to_string).unwrap_or_else(|| account.to_string()); + if db.oper_revoke(&canonical) { + ctx.notice(me, from.uid, format!("\x02{canonical}\x02 is no longer a runtime operator.")); + } else { + ctx.notice(me, from.uid, format!("\x02{account}\x02 isn't a runtime operator (config opers are set in the daemon config).")); + } +} + +fn list(me: &str, from: &Sender, ctx: &mut ServiceCtx, db: &mut dyn Store) { + let opers = db.opers_list(); + if opers.is_empty() { + ctx.notice(me, from.uid, "No runtime operators (config opers are set in the daemon config)."); + return; + } + for (account, privs) in &opers { + ctx.notice(me, from.uid, format!(" \x02{account}\x02 — {}", privs.join(", "))); + } + ctx.notice(me, from.uid, format!("End of runtime operator list ({} shown).", opers.len())); +} diff --git a/src/config.rs b/src/config.rs index df13616..863720c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -80,19 +80,9 @@ pub struct Oper { impl Config { // The account -> privileges table (casefolded keys) built from [[oper]]. pub fn opers(&self) -> std::collections::HashMap { - use fedserv_api::{Priv, Privs}; let mut map = std::collections::HashMap::new(); for o in &self.oper { - let mut privs = Privs::default(); - for p in &o.privs { - match p.to_ascii_lowercase().as_str() { - "auspex" => privs = privs.with(Priv::Auspex), - "suspend" => privs = privs.with(Priv::Suspend), - "admin" => privs = privs.with(Priv::Admin), - other => tracing::warn!(privilege = other, account = %o.account, "unknown oper privilege, ignoring"), - } - } - map.insert(o.account.to_ascii_lowercase(), privs); + map.insert(o.account.to_ascii_lowercase(), fedserv_api::Privs::from_names(&o.privs)); } map } diff --git a/src/engine/db.rs b/src/engine/db.rs index bafe7cd..a4f5614 100644 --- a/src/engine/db.rs +++ b/src/engine/db.rs @@ -30,7 +30,7 @@ use super::scram::{self, Hash}; // fedserv-api SDK crate; re-exported so the engine keeps naming them locally and // modules importing `crate::engine::db::{ChanError, ...}` are unaffected. pub use fedserv_api::{ - AccountView, AjoinView, AkillView, BotView, IgnoreView, MemoView, NewsView, SuspensionView, ChanAccessView, ChanAkickView, ChanError, ChanSetting, ChannelView, CertError, CodeKind, Kicker, RegError, Store, TriggerView, VhostView, + AccountView, AjoinView, AkillView, BotView, IgnoreView, MemoView, NewsView, Privs, SuspensionView, ChanAccessView, ChanAkickView, ChanError, ChanSetting, ChannelView, CertError, CodeKind, Kicker, RegError, Store, TriggerView, VhostView, }; #[derive(Debug, Clone, Serialize, Deserialize)] @@ -188,6 +188,9 @@ pub enum Event { // News items (OperServ NEWS). The stable `id` makes deletion order-independent. NewsAdded { id: u64, kind: String, text: String, setter: String, ts: u64 }, NewsDeleted { id: u64 }, + // Runtime operator grants (OperServ OPER). + OperGranted { account: String, privs: Vec }, + OperRevoked { account: String }, // Network bans (OperServ AKILL / SQLINE). Global: a ban covers the whole // network, so every node holds the list and re-applies it at burst. `kind` // is the ircd X-line type and defaults to "G" for records predating it. @@ -248,7 +251,9 @@ impl Event { | Event::AkillAdded { .. } | Event::AkillRemoved { .. } | Event::NewsAdded { .. } - | Event::NewsDeleted { .. } => Scope::Global, + | Event::NewsDeleted { .. } + | Event::OperGranted { .. } + | Event::OperRevoked { .. } => Scope::Global, Event::ChannelRegistered { .. } | Event::ChannelDropped { .. } | Event::ChannelMlock { .. } @@ -359,6 +364,9 @@ pub struct NetData { pub akills: Vec, pub news: Vec, pub news_seq: u64, + // Runtime services operators (OperServ OPER), casefolded account -> privilege + // names. Merged with the declarative [[oper]] config at the engine. + pub opers: HashMap>, } // A memo left for an account (MemoServ). @@ -1084,6 +1092,9 @@ impl Db { for n in &self.net.news { snapshot.push(Event::NewsAdded { id: n.id, kind: n.kind.clone(), text: n.text.clone(), setter: n.setter.clone(), ts: n.ts }); } + for (account, privs) in &self.net.opers { + snapshot.push(Event::OperGranted { account: account.clone(), privs: privs.clone() }); + } self.log.compact(snapshot)?; tracing::info!(before, after = self.log.len(), "compacted event log"); Ok(()) @@ -1884,6 +1895,33 @@ impl Db { .collect() } + /// Grant runtime operator privileges to an account (replaces any existing). + pub fn oper_grant(&mut self, account: &str, privs: Vec) { + let _ = self.log.append(Event::OperGranted { account: account.to_string(), privs: privs.clone() }); + self.net.opers.insert(key(account), privs); + } + + /// Revoke a runtime operator grant. Returns whether one existed. + pub fn oper_revoke(&mut self, account: &str) -> bool { + if !self.net.opers.contains_key(&key(account)) { + return false; + } + let _ = self.log.append(Event::OperRevoked { account: account.to_string() }); + self.net.opers.remove(&key(account)); + true + } + + /// The runtime operator grants, as (account, privilege-names). + pub fn opers_list(&self) -> Vec<(String, Vec)> { + self.net.opers.iter().map(|(a, p)| (a.clone(), p.clone())).collect() + } + + /// The runtime privileges granted to an account, if any (config opers are + /// merged in separately by the engine). + pub fn oper_privs_of(&self, account: &str) -> Option { + self.net.opers.get(&key(account)).map(|names| Privs::from_names(names)) + } + /// Add a news item of `kind` ("logon"/"oper"). Returns its stable id. pub fn news_add(&mut self, kind: &str, text: &str, setter: &str) -> u64 { let id = self.net.news_seq; @@ -2892,6 +2930,12 @@ fn apply(accounts: &mut HashMap, channels: &mut HashMap { net.news.retain(|n| n.id != id); } + Event::OperGranted { account, privs } => { + net.opers.insert(key(&account), privs); + } + Event::OperRevoked { account } => { + net.opers.remove(&key(&account)); + } } } @@ -3163,6 +3207,15 @@ impl Store for Db { fn news(&self, kind: &str) -> Vec { Db::news(self, kind) } + fn oper_grant(&mut self, account: &str, privs: Vec) { + Db::oper_grant(self, account, privs) + } + fn oper_revoke(&mut self, account: &str) -> bool { + Db::oper_revoke(self, account) + } + fn opers_list(&self) -> Vec<(String, Vec)> { + Db::opers_list(self) + } fn register_channel(&mut self, name: &str, founder: &str) -> Result<(), ChanError> { Db::register_channel(self, name, founder) } diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 80dd025..d75d6f6 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -247,9 +247,15 @@ impl Engine { self.opers = opers; } - // The privileges an account holds, empty if it is not an oper. + // The privileges an account holds, empty if it is not an oper. The declarative + // config opers and the runtime OPER grants are unioned, so either source can + // make an account an operator. fn oper_privs(&self, account: &str) -> Privs { - self.opers.get(&account.to_ascii_lowercase()).copied().unwrap_or_default() + let config = self.opers.get(&account.to_ascii_lowercase()).copied().unwrap_or_default(); + match self.db.oper_privs_of(account) { + Some(runtime) => config.union(runtime), + None => config, + } } // Our services SID, needed to mint valid bot uids. @@ -1604,6 +1610,8 @@ fn audit_summary(event: &db::Event) -> Option { }, NewsAdded { kind, .. } => format!("added a \x02{kind}\x02 news item"), NewsDeleted { .. } => "removed a news item".to_string(), + OperGranted { account, privs } => format!("granted \x02{account}\x02 operator ({})", privs.join(", ")), + OperRevoked { account } => format!("revoked \x02{account}\x02's operator access"), AccountNoExpire { account, on } => { let verb = if *on { "pinned" } else { "unpinned" }; format!("{verb} account \x02{account}\x02 against expiry") @@ -4046,6 +4054,52 @@ mod tests { } } + // OperServ OPER: a runtime grant actually confers privileges (merged with the + // config opers), and revoking removes them. Admin-only. + #[test] + fn operserv_oper_grants_runtime_privileges() { + use fedserv_operserv::OperServ; + let path = std::env::temp_dir().join("fedserv-osoper.jsonl"); + let _ = std::fs::remove_file(&path); + let mut db = Db::open(&path, "42S"); + db.scram_iterations = 4096; + db.register("staff", "password1", None).unwrap(); + db.register("alice", "password1", 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("staff".to_string(), Privs::default().with(fedserv_api::Priv::Admin)); + e.set_opers(opers); + let os = |e: &mut Engine, uid: &str, t: &str| e.handle(NetEvent::Privmsg { from: uid.into(), to: "42SAAAAAH".into(), text: t.into() }); + let denied = |out: &[NetAction]| out.iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("Access denied"))); + + e.handle(NetEvent::UserConnect { uid: "000AAAAAS".into(), nick: "staff".into(), host: "h".into() }); + e.handle(NetEvent::Privmsg { from: "000AAAAAS".into(), to: "42SAAAAAA".into(), text: "IDENTIFY password1".into() }); + e.handle(NetEvent::UserConnect { uid: "000AAAAAL".into(), nick: "alice".into(), host: "h".into() }); + e.handle(NetEvent::Privmsg { from: "000AAAAAL".into(), to: "42SAAAAAA".into(), text: "IDENTIFY password1".into() }); + + // Before the grant, alice is a plain user — OperServ shuts her out. + assert!(denied(&os(&mut e, "000AAAAAL", "STATS")), "alice not an oper yet"); + + // Grant alice admin at runtime; now the same command works. + os(&mut e, "000AAAAAS", "OPER ADD alice admin"); + assert!(!denied(&os(&mut e, "000AAAAAL", "STATS")), "alice is an oper after the grant"); + assert!(os(&mut e, "000AAAAAS", "OPER LIST").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("alice"))), "listed"); + + // Revoke; alice loses access again. + os(&mut e, "000AAAAAS", "OPER DEL alice"); + assert!(denied(&os(&mut e, "000AAAAAL", "STATS")), "alice lost access after revoke"); + + // A config oper is not a runtime oper, so it can't be DEL'd here. + assert!(os(&mut e, "000AAAAAS", "OPER DEL staff").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("isn't a runtime operator"))), "config oper untouched"); + } + // OperServ NEWS: logon news greets everyone on connect, oper news greets an // operator on login; ADD/DEL/LIST are admin-only. #[test] diff --git a/src/grpc.rs b/src/grpc.rs index e499918..6e99ff2 100644 --- a/src/grpc.rs +++ b/src/grpc.rs @@ -172,7 +172,9 @@ fn to_wire(entry: &LogEntry) -> Option { | Event::AccountOperNoteSet { .. } | Event::ChannelOperNoteSet { .. } | Event::NewsAdded { .. } - | Event::NewsDeleted { .. } => return None, + | Event::NewsDeleted { .. } + | Event::OperGranted { .. } + | Event::OperRevoked { .. } => return None, }; Some(ReplicationEvent { origin: entry.origin().to_string(), seq: entry.seq(), lamport: entry.lamport(), kind: Some(kind) }) }