Add OperServ with AKILL network bans

The first operator module. AKILL manages network bans as a typed,
event-sourced list with lazy expiry, mirroring the patterns the other
modules use:

- AKILL ADD [+expiry] <user@host> <reason> stores the ban and drives an
  ircd G-line (applied to matching users already online and to future
  connections); AKILL DEL <mask|number> lifts it; AKILL LIST [pattern]
  shows the live list, numbered. Admin-only.
- Bans are Global events, so every node holds the list and re-asserts each
  one at burst with its remaining duration. Expired bans are hidden lazily
  and dropped at compaction.
- Masks are normalised to user@host (a nick! prefix is stripped, both
  sides lowercased) and an all-wildcard mask is refused.

Email (send_email) is already reachable from the api via ServiceCtx, and
adds AddLine/DelLine to the action vocabulary for any future X-line kinds.
This commit is contained in:
Jean Chevronnet 2026-07-14 00:12:29 +00:00
parent 253d4c2a2d
commit d2c1d076fb
No known key found for this signature in database
12 changed files with 430 additions and 12 deletions

View file

@ -107,7 +107,7 @@ impl Default for Modules {
}
fn default_services() -> Vec<String> {
vec!["nickserv".to_string(), "chanserv".to_string(), "botserv".to_string(), "memoserv".to_string(), "statserv".to_string(), "hostserv".to_string()]
vec!["nickserv".to_string(), "chanserv".to_string(), "botserv".to_string(), "memoserv".to_string(), "statserv".to_string(), "hostserv".to_string(), "operserv".to_string()]
}
#[derive(Debug, Deserialize, Clone)]

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
// modules importing `crate::engine::db::{ChanError, ...}` are unaffected.
pub use fedserv_api::{
AccountView, AjoinView, BotView, MemoView, SuspensionView, ChanAccessView, ChanAkickView, ChanError, ChanSetting, ChannelView, CertError, CodeKind, Kicker, RegError, Store, TriggerView, VhostView,
AccountView, AjoinView, AkillView, BotView, MemoView, SuspensionView, ChanAccessView, ChanAkickView, ChanError, ChanSetting, ChannelView, CertError, CodeKind, Kicker, RegError, Store, TriggerView, VhostView,
};
#[derive(Debug, Clone, Serialize, Deserialize)]
@ -172,6 +172,10 @@ pub enum Event {
ChannelUsed { channel: String, ts: u64 },
AccountNoExpire { account: String, on: bool },
ChannelNoExpire { channel: String, on: bool },
// Network bans (OperServ AKILL). Global: a ban covers the whole network, so
// every node holds the list and re-applies it at burst.
AkillAdded { mask: String, setter: String, reason: String, ts: u64, expires: Option<u64> },
AkillRemoved { mask: String },
}
// Whether an event replicates across the federation. Account identity is Global
@ -209,7 +213,9 @@ impl Event {
| Event::NickGrouped { .. }
| Event::NickUngrouped { .. }
| Event::AccountSeen { .. }
| Event::AccountNoExpire { .. } => Scope::Global,
| Event::AccountNoExpire { .. }
| Event::AkillAdded { .. }
| Event::AkillRemoved { .. } => Scope::Global,
Event::ChannelRegistered { .. }
| Event::ChannelDropped { .. }
| Event::ChannelMlock { .. }
@ -267,6 +273,18 @@ pub struct Suspension {
pub expires: Option<u64>,
}
// A network ban (AKILL / G-line): a user@host mask, who set it, why, when, and
// an optional absolute-unix-seconds expiry (None = permanent).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Akill {
pub mask: String,
pub setter: String,
pub reason: String,
pub ts: u64,
#[serde(default)]
pub expires: Option<u64>,
}
// A memo left for an account (MemoServ).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Memo {
@ -828,6 +846,8 @@ pub struct Db {
// HostServ node config: the self-serve offer menu, the forbidden-pattern
// blocklist, and the auto-vhost template.
host_cfg: HostConfig,
// Network bans (OperServ AKILL), in insertion order.
akills: Vec<Akill>,
}
// Network-wide HostServ configuration, rebuilt from the event log.
@ -878,11 +898,12 @@ impl Db {
let mut grouped = HashMap::new();
let mut bots = HashMap::new();
let mut host_cfg = HostConfig::default();
let mut akills = Vec::new();
for event in events {
apply(&mut accounts, &mut channels, &mut grouped, &mut bots, &mut host_cfg, event);
apply(&mut accounts, &mut channels, &mut grouped, &mut bots, &mut host_cfg, &mut akills, event);
}
tracing::info!(accounts = accounts.len(), channels = channels.len(), "account store loaded");
Self { accounts, channels, grouped, log, scram_iterations: scram::DEFAULT_ITERATIONS, email_enabled: false, email_brand: "Network Services".to_string(), email_accent: "#4f46e5".to_string(), email_logo: String::new(), codes: HashMap::new(), auth_fails: HashMap::new(), vhost_req_times: HashMap::new(), bots, host_cfg }
Self { accounts, channels, grouped, log, scram_iterations: scram::DEFAULT_ITERATIONS, email_enabled: false, email_brand: "Network Services".to_string(), email_accent: "#4f46e5".to_string(), email_logo: String::new(), codes: HashMap::new(), auth_fails: HashMap::new(), vhost_req_times: HashMap::new(), bots, host_cfg, akills }
}
/// Fold an entry authored by another node into the store — the services-side
@ -898,7 +919,7 @@ impl Db {
_ => None,
};
if let Some(event) = self.log.ingest(entry)? {
apply(&mut self.accounts, &mut self.channels, &mut self.grouped, &mut self.bots, &mut self.host_cfg, event);
apply(&mut self.accounts, &mut self.channels, &mut self.grouped, &mut self.bots, &mut self.host_cfg, &mut self.akills, event);
}
if let Some((name, prev_home)) = watched {
match (prev_home, self.account(&name).map(|c| c.home.clone())) {
@ -968,6 +989,11 @@ impl Db {
if self.host_cfg.template.is_some() {
snapshot.push(Event::VhostTemplateSet { template: self.host_cfg.template.clone() });
}
// Compaction is a good moment to forget akills that have already expired.
let now = now();
for a in self.akills.iter().filter(|a| a.expires.is_none_or(|e| e > now)) {
snapshot.push(Event::AkillAdded { mask: a.mask.clone(), setter: a.setter.clone(), reason: a.reason.clone(), ts: a.ts, expires: a.expires });
}
self.log.compact(snapshot)?;
tracing::info!(before, after = self.log.len(), "compacted event log");
Ok(())
@ -1644,6 +1670,38 @@ impl Db {
.collect()
}
/// Add (or refresh) a network ban. Returns whether the mask was newly added.
pub fn akill_add(&mut self, mask: &str, setter: &str, reason: &str, expires: Option<u64>) -> Result<bool, RegError> {
let fresh = !self.akills.iter().any(|a| a.mask.eq_ignore_ascii_case(mask) && a.expires.is_none_or(|e| e > now()));
self.log
.append(Event::AkillAdded { mask: mask.to_string(), setter: setter.to_string(), reason: reason.to_string(), ts: now(), expires })
.map_err(|_| RegError::Internal)?;
self.akills.retain(|a| !a.mask.eq_ignore_ascii_case(mask));
self.akills.push(Akill { mask: mask.to_string(), setter: setter.to_string(), reason: reason.to_string(), ts: now(), expires });
Ok(fresh)
}
/// Lift a network ban. Returns whether a live (non-expired) one was removed.
pub fn akill_del(&mut self, mask: &str) -> Result<bool, RegError> {
let existed = self.akills.iter().any(|a| a.mask.eq_ignore_ascii_case(mask) && a.expires.is_none_or(|e| e > now()));
if !existed {
return Ok(false);
}
self.log.append(Event::AkillRemoved { mask: mask.to_string() }).map_err(|_| RegError::Internal)?;
self.akills.retain(|a| !a.mask.eq_ignore_ascii_case(mask));
Ok(true)
}
/// The live network bans (expired ones hidden lazily), oldest first.
pub fn akills(&self) -> Vec<AkillView> {
let now = now();
self.akills
.iter()
.filter(|a| a.expires.is_none_or(|e| e > now))
.map(|a| AkillView { mask: a.mask.clone(), setter: a.setter.clone(), reason: a.reason.clone(), ts: a.ts, expires: a.expires })
.collect()
}
/// The account's suspension record, if any (shown in INFO even once expired).
pub fn suspension(&self, account: &str) -> Option<SuspensionView> {
self.accounts
@ -2284,7 +2342,7 @@ fn owns_over(held: &Account, claim: &Account) -> bool {
// Fold one event into the store. Shared by log replay (`open`) and gossip
// ingest, so both routes reconstruct identical state.
fn apply(accounts: &mut HashMap<String, Account>, channels: &mut HashMap<String, ChannelInfo>, grouped: &mut HashMap<String, String>, bots: &mut HashMap<String, Bot>, host_cfg: &mut HostConfig, event: Event) {
fn apply(accounts: &mut HashMap<String, Account>, channels: &mut HashMap<String, ChannelInfo>, grouped: &mut HashMap<String, String>, bots: &mut HashMap<String, Bot>, host_cfg: &mut HostConfig, akills: &mut Vec<Akill>, event: Event) {
match event {
Event::AccountRegistered(a) => {
// Resolve a concurrent registration of the same name deterministically:
@ -2540,6 +2598,15 @@ fn apply(accounts: &mut HashMap<String, Account>, channels: &mut HashMap<String,
c.noexpire = on;
}
}
Event::AkillAdded { mask, setter, reason, ts, expires } => {
// Keyed by mask (case-insensitive): a re-add refreshes in place, so
// replaying over a snapshot stays idempotent.
akills.retain(|a| !a.mask.eq_ignore_ascii_case(&mask));
akills.push(Akill { mask, setter, reason, ts, expires });
}
Event::AkillRemoved { mask } => {
akills.retain(|a| !a.mask.eq_ignore_ascii_case(&mask));
}
}
}
@ -2772,6 +2839,15 @@ impl Store for Db {
fn set_channel_noexpire(&mut self, channel: &str, on: bool) -> Result<bool, ChanError> {
Db::set_channel_noexpire(self, channel, on)
}
fn akill_add(&mut self, mask: &str, setter: &str, reason: &str, expires: Option<u64>) -> Result<bool, RegError> {
Db::akill_add(self, mask, setter, reason, expires)
}
fn akill_del(&mut self, mask: &str) -> Result<bool, RegError> {
Db::akill_del(self, mask)
}
fn akills(&self) -> Vec<AkillView> {
Db::akills(self)
}
fn register_channel(&mut self, name: &str, founder: &str) -> Result<(), ChanError> {
Db::register_channel(self, name, founder)
}
@ -2975,9 +3051,9 @@ mod tests {
ts, home: home.into(), scram256: None, scram512: None, certfps: vec![], verified: true, ajoin: vec![], suspension: None, memos: vec![], greet: String::new(), vhost: None, vhost_request: None, last_seen: ts, noexpire: false,
};
let converge = |first: &Account, second: &Account| {
let (mut acc, mut ch, mut gr, mut bo, mut hc) = (HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new(), HostConfig::default());
apply(&mut acc, &mut ch, &mut gr, &mut bo, &mut hc, Event::AccountRegistered(Box::new(first.clone())));
apply(&mut acc, &mut ch, &mut gr, &mut bo, &mut hc, Event::AccountRegistered(Box::new(second.clone())));
let (mut acc, mut ch, mut gr, mut bo, mut hc, mut ak) = (HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new(), HostConfig::default(), Vec::new());
apply(&mut acc, &mut ch, &mut gr, &mut bo, &mut hc, &mut ak, Event::AccountRegistered(Box::new(first.clone())));
apply(&mut acc, &mut ch, &mut gr, &mut bo, &mut hc, &mut ak, Event::AccountRegistered(Box::new(second.clone())));
acc["alice"].password_hash.clone()
};
// Earlier registration wins, regardless of which claim applies first.

View file

@ -653,6 +653,13 @@ impl Engine {
// clients in CAP LS (IRCv3 SASL 3.2).
// Introduce the registered bots too.
out.extend(self.reconcile_bots());
// Re-assert the network bans over the fresh link, each with its remaining
// duration so the ircd expires it at the right time (permanent = 0).
let now = self.now_secs();
for a in self.db.akills() {
let duration = a.expires.map(|e| e.saturating_sub(now)).unwrap_or(0);
out.push(NetAction::AddLine { kind: "G".to_string(), mask: a.mask, setter: a.setter, duration, reason: a.reason });
}
out.push(NetAction::Metadata {
target: "*".to_string(),
key: "saslmechlist".to_string(),
@ -1511,6 +1518,11 @@ fn audit_summary(event: &db::Event) -> Option<String> {
Some(t) => format!("set the vhost template to \x02{t}\x02"),
None => "cleared the vhost template".to_string(),
},
AkillAdded { mask, reason, expires, .. } => {
let kind = if expires.is_some() { " (temporary)" } else { "" };
format!("set a network ban on \x02{mask}\x02{kind} ({reason})")
}
AkillRemoved { mask } => format!("lifted the network ban on \x02{mask}\x02"),
AccountNoExpire { account, on } => {
let verb = if *on { "pinned" } else { "unpinned" };
format!("{verb} account \x02{account}\x02 against expiry")
@ -3745,6 +3757,63 @@ mod tests {
assert!(unreg, "expired channel had +r cleared");
}
// OperServ AKILL: an admin adds/lists/removes network bans, they drive the
// ircd's G-lines, persist for re-assertion at burst, and non-admins are shut
// out entirely.
#[test]
fn operserv_akill_add_list_del_and_burst() {
use fedserv_operserv::OperServ;
let path = std::env::temp_dir().join("fedserv-akill.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("nobody", "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());
e.set_log_channel(Some("#services".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() });
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: "000AAAAAN".into(), nick: "nobody".into(), host: "h".into() });
e.handle(NetEvent::Privmsg { from: "000AAAAAN".into(), to: "42SAAAAAA".into(), text: "IDENTIFY password1".into() });
// A non-admin can't even see OperServ exists beyond the refusal.
let denied = os(&mut e, "000AAAAAN", "AKILL ADD *@evil.host being evil");
assert!(denied.iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("Access denied"))), "non-admin refused: {denied:?}");
assert!(!denied.iter().any(|a| matches!(a, NetAction::AddLine { .. })), "no ban from a non-admin");
// Admin adds a temporary ban: it drives a G-line and is audited.
let out = os(&mut e, "000AAAAAS", "AKILL ADD +1h *@evil.host spamming");
assert!(out.iter().any(|a| matches!(a, NetAction::AddLine { kind, mask, duration, .. } if kind == "G" && mask == "*@evil.host" && *duration == 3600)), "G-line added: {out:?}");
assert!(out.iter().any(|a| matches!(a, NetAction::Notice { to, text, .. } if to == "#services" && text.contains("*@evil.host"))), "ban audited: {out:?}");
// A too-wide mask is refused outright.
assert!(os(&mut e, "000AAAAAS", "AKILL ADD *@* everything").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("too wide"))), "wildcard mask refused");
// LIST shows it, numbered.
assert!(os(&mut e, "000AAAAAS", "AKILL LIST").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("1.") && text.contains("*@evil.host"))), "listed");
// It survives to burst: startup re-asserts the G-line with a remaining
// duration, not the original 3600.
assert!(e.startup_actions().iter().any(|a| matches!(a, NetAction::AddLine { mask, duration, .. } if mask == "*@evil.host" && *duration > 0 && *duration <= 3600)), "re-asserted at burst");
// DEL by number removes it and lifts the G-line.
let out = os(&mut e, "000AAAAAS", "AKILL DEL 1");
assert!(out.iter().any(|a| matches!(a, NetAction::DelLine { kind, mask } if kind == "G" && mask == "*@evil.host")), "G-line lifted: {out:?}");
assert!(os(&mut e, "000AAAAAS", "AKILL LIST").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("No matching"))), "list now empty");
}
// NOEXPIRE is oper-only.
#[test]
fn noexpire_command_is_oper_gated() {

View file

@ -164,7 +164,9 @@ fn to_wire(entry: &LogEntry) -> Option<ReplicationEvent> {
| Event::AccountSeen { .. }
| Event::ChannelUsed { .. }
| Event::AccountNoExpire { .. }
| Event::ChannelNoExpire { .. } => return None,
| Event::ChannelNoExpire { .. }
| Event::AkillAdded { .. }
| Event::AkillRemoved { .. } => return None,
};
Some(ReplicationEvent { origin: entry.origin().to_string(), seq: entry.seq(), lamport: entry.lamport(), kind: Some(kind) })
}

View file

@ -20,6 +20,7 @@ use fedserv_chanserv::ChanServ;
use fedserv_memoserv::MemoServ;
use fedserv_statserv::StatServ;
use fedserv_hostserv::HostServ;
use fedserv_operserv::OperServ;
use fedserv_example::ExampleServ;
use fedserv_inspircd::InspIrcd;
use fedserv_nickserv::NickServ;
@ -83,6 +84,11 @@ async fn main() -> Result<()> {
uid: format!("{}AAAAAG", cfg.server.sid),
}));
}
if enabled("operserv") {
services.push(Box::new(OperServ {
uid: format!("{}AAAAAH", cfg.server.sid),
}));
}
if enabled("example") {
services.push(Box::new(ExampleServ {
uid: format!("{}AAAAAC", cfg.server.sid),