OperServ: OPER — runtime operator management

OPER ADD <account> <priv[,priv]> / DEL <account> / 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.
This commit is contained in:
Jean Chevronnet 2026-07-14 01:33:30 +00:00
parent e45eab2cd6
commit a67409e0d3
No known key found for this signature in database
7 changed files with 217 additions and 17 deletions

View file

@ -181,6 +181,35 @@ impl Privs {
pub fn any(self) -> bool { pub fn any(self) -> bool {
self.0 != 0 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<S: AsRef<str>>(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 // 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_add(&mut self, kind: &str, text: &str, setter: &str) -> u64;
fn news_del(&mut self, id: u64) -> bool; fn news_del(&mut self, id: u64) -> bool;
fn news(&self, kind: &str) -> Vec<NewsView>; fn news(&self, kind: &str) -> Vec<NewsView>;
// Runtime operator grants (OperServ OPER), merged with config opers.
fn oper_grant(&mut self, account: &str, privs: Vec<String>);
fn oper_revoke(&mut self, account: &str) -> bool;
fn opers_list(&self) -> Vec<(String, Vec<String>)>;
fn register_channel(&mut self, name: &str, founder: &str) -> Result<(), ChanError>; fn register_channel(&mut self, name: &str, founder: &str) -> Result<(), ChanError>;
fn drop_channel(&mut self, name: &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>; fn set_mlock(&mut self, name: &str, on: &str, off: &str) -> Result<(), ChanError>;

View file

@ -25,6 +25,8 @@ mod svs;
mod info; mod info;
#[path = "news.rs"] #[path = "news.rs"]
mod news; mod news;
#[path = "oper.rs"]
mod oper;
pub struct OperServ { pub struct OperServ {
pub uid: String, 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("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("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("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), Some(cmd) if cmd.eq_ignore_ascii_case("HELP") => help(me, from, ctx),
None => 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.")), 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) { 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 <message> (announce to everyone), \x02KILL\x02 <nick> [reason] (disconnect a user), \x02KICK\x02 <#chan> <nick> [reason], \x02MODE\x02 <#chan> <modes> [params], \x02IGNORE\x02 ADD|DEL|LIST (silence a user from services), \x02STATS\x02 (enforcement overview), \x02SVSNICK\x02 <nick> <newnick>, \x02SVSJOIN\x02 <nick> <#chan> [key], \x02INFO\x02 ADD|DEL <target> (staff notes), \x02NEWS\x02 ADD|DEL|LIST <LOGON|OPER> (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 <message> (announce to everyone), \x02KILL\x02 <nick> [reason] (disconnect a user), \x02KICK\x02 <#chan> <nick> [reason], \x02MODE\x02 <#chan> <modes> [params], \x02IGNORE\x02 ADD|DEL|LIST (silence a user from services), \x02STATS\x02 (enforcement overview), \x02SVSNICK\x02 <nick> <newnick>, \x02SVSJOIN\x02 <nick> <#chan> [key], \x02INFO\x02 ADD|DEL <target> (staff notes), \x02NEWS\x02 ADD|DEL|LIST <LOGON|OPER> (announcements), \x02OPER\x02 ADD|DEL|LIST (runtime operators).");
} }

65
operserv/src/oper.rs Normal file
View file

@ -0,0 +1,65 @@
use fedserv_api::{Priv, Sender, ServiceCtx, Store};
// OPER ADD <account> <priv[,priv…]> | OPER DEL <account> | 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 <account> <priv[,priv]> | OPER DEL <account> | 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 <account> <priv[,priv]>");
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<String> = 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 <account>");
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()));
}

View file

@ -80,19 +80,9 @@ pub struct Oper {
impl Config { impl Config {
// The account -> privileges table (casefolded keys) built from [[oper]]. // The account -> privileges table (casefolded keys) built from [[oper]].
pub fn opers(&self) -> std::collections::HashMap<String, fedserv_api::Privs> { pub fn opers(&self) -> std::collections::HashMap<String, fedserv_api::Privs> {
use fedserv_api::{Priv, Privs};
let mut map = std::collections::HashMap::new(); let mut map = std::collections::HashMap::new();
for o in &self.oper { for o in &self.oper {
let mut privs = Privs::default(); map.insert(o.account.to_ascii_lowercase(), fedserv_api::Privs::from_names(&o.privs));
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 map
} }

View file

@ -30,7 +30,7 @@ use super::scram::{self, Hash};
// fedserv-api SDK crate; re-exported so the engine keeps naming them locally and // fedserv-api SDK crate; re-exported so the engine keeps naming them locally and
// modules importing `crate::engine::db::{ChanError, ...}` are unaffected. // modules importing `crate::engine::db::{ChanError, ...}` are unaffected.
pub use fedserv_api::{ 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)] #[derive(Debug, Clone, Serialize, Deserialize)]
@ -188,6 +188,9 @@ pub enum Event {
// News items (OperServ NEWS). The stable `id` makes deletion order-independent. // News items (OperServ NEWS). The stable `id` makes deletion order-independent.
NewsAdded { id: u64, kind: String, text: String, setter: String, ts: u64 }, NewsAdded { id: u64, kind: String, text: String, setter: String, ts: u64 },
NewsDeleted { id: u64 }, NewsDeleted { id: u64 },
// Runtime operator grants (OperServ OPER).
OperGranted { account: String, privs: Vec<String> },
OperRevoked { account: String },
// Network bans (OperServ AKILL / SQLINE). Global: a ban covers the whole // 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` // 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. // is the ircd X-line type and defaults to "G" for records predating it.
@ -248,7 +251,9 @@ impl Event {
| Event::AkillAdded { .. } | Event::AkillAdded { .. }
| Event::AkillRemoved { .. } | Event::AkillRemoved { .. }
| Event::NewsAdded { .. } | Event::NewsAdded { .. }
| Event::NewsDeleted { .. } => Scope::Global, | Event::NewsDeleted { .. }
| Event::OperGranted { .. }
| Event::OperRevoked { .. } => Scope::Global,
Event::ChannelRegistered { .. } Event::ChannelRegistered { .. }
| Event::ChannelDropped { .. } | Event::ChannelDropped { .. }
| Event::ChannelMlock { .. } | Event::ChannelMlock { .. }
@ -359,6 +364,9 @@ pub struct NetData {
pub akills: Vec<Akill>, pub akills: Vec<Akill>,
pub news: Vec<News>, pub news: Vec<News>,
pub news_seq: u64, 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<String, Vec<String>>,
} }
// A memo left for an account (MemoServ). // A memo left for an account (MemoServ).
@ -1084,6 +1092,9 @@ impl Db {
for n in &self.net.news { 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 }); 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)?; self.log.compact(snapshot)?;
tracing::info!(before, after = self.log.len(), "compacted event log"); tracing::info!(before, after = self.log.len(), "compacted event log");
Ok(()) Ok(())
@ -1884,6 +1895,33 @@ impl Db {
.collect() .collect()
} }
/// Grant runtime operator privileges to an account (replaces any existing).
pub fn oper_grant(&mut self, account: &str, privs: Vec<String>) {
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<String>)> {
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<Privs> {
self.net.opers.get(&key(account)).map(|names| Privs::from_names(names))
}
/// Add a news item of `kind` ("logon"/"oper"). Returns its stable id. /// 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 { pub fn news_add(&mut self, kind: &str, text: &str, setter: &str) -> u64 {
let id = self.net.news_seq; let id = self.net.news_seq;
@ -2892,6 +2930,12 @@ fn apply(accounts: &mut HashMap<String, Account>, channels: &mut HashMap<String,
Event::NewsDeleted { id } => { Event::NewsDeleted { id } => {
net.news.retain(|n| n.id != id); 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<NewsView> { fn news(&self, kind: &str) -> Vec<NewsView> {
Db::news(self, kind) Db::news(self, kind)
} }
fn oper_grant(&mut self, account: &str, privs: Vec<String>) {
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<String>)> {
Db::opers_list(self)
}
fn register_channel(&mut self, name: &str, founder: &str) -> Result<(), ChanError> { fn register_channel(&mut self, name: &str, founder: &str) -> Result<(), ChanError> {
Db::register_channel(self, name, founder) Db::register_channel(self, name, founder)
} }

View file

@ -247,9 +247,15 @@ impl Engine {
self.opers = opers; 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 { 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. // Our services SID, needed to mint valid bot uids.
@ -1604,6 +1610,8 @@ fn audit_summary(event: &db::Event) -> Option<String> {
}, },
NewsAdded { kind, .. } => format!("added a \x02{kind}\x02 news item"), NewsAdded { kind, .. } => format!("added a \x02{kind}\x02 news item"),
NewsDeleted { .. } => "removed a news item".to_string(), 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 } => { AccountNoExpire { account, on } => {
let verb = if *on { "pinned" } else { "unpinned" }; let verb = if *on { "pinned" } else { "unpinned" };
format!("{verb} account \x02{account}\x02 against expiry") 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 // OperServ NEWS: logon news greets everyone on connect, oper news greets an
// operator on login; ADD/DEL/LIST are admin-only. // operator on login; ADD/DEL/LIST are admin-only.
#[test] #[test]

View file

@ -172,7 +172,9 @@ fn to_wire(entry: &LogEntry) -> Option<ReplicationEvent> {
| Event::AccountOperNoteSet { .. } | Event::AccountOperNoteSet { .. }
| Event::ChannelOperNoteSet { .. } | Event::ChannelOperNoteSet { .. }
| Event::NewsAdded { .. } | 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) }) Some(ReplicationEvent { origin: entry.origin().to_string(), seq: entry.seq(), lamport: entry.lamport(), kind: Some(kind) })
} }