OperServ: add SET READONLY lockdown
All checks were successful
CI / check (push) Successful in 3m31s

This commit is contained in:
Jean Chevronnet 2026-07-16 01:05:48 +00:00
parent b2442f85e6
commit 0027decdb7
No known key found for this signature in database
8 changed files with 112 additions and 2 deletions

View file

@ -973,6 +973,10 @@ pub trait Store {
// Network defence level (OperServ DEFCON) and its derived registration freezes.
fn defcon(&self) -> u8;
fn set_defcon(&mut self, level: u8);
// OperServ SET READONLY: operator lockdown that refuses locally-authored
// writes. Ephemeral (resets on restart).
fn readonly(&self) -> bool;
fn set_readonly(&mut self, on: bool);
fn registrations_frozen(&self) -> bool;
fn channel_regs_frozen(&self) -> bool;
// Whether account identity is owned externally (website); when true, IRC

View file

@ -39,6 +39,8 @@ mod logsearch;
mod defcon;
#[path = "shutdown.rs"]
mod shutdown;
#[path = "set.rs"]
mod set;
pub struct OperServ {
pub uid: String,
@ -90,6 +92,7 @@ impl Service for OperServ {
Some(cmd) if cmd.eq_ignore_ascii_case("CHANKILL") => chankill::handle(me, from, args, ctx, net, db),
Some(cmd) if cmd.eq_ignore_ascii_case("LOGSEARCH") => logsearch::handle(me, from, args, ctx, net),
Some(cmd) if cmd.eq_ignore_ascii_case("DEFCON") => defcon::handle(me, from, args, ctx, db),
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("HELP") => echo_api::help(me, from, ctx, BLURB, TOPICS, args.get(1).copied()),
@ -125,6 +128,7 @@ const TOPICS: &[HelpEntry] = &[
HelpEntry { cmd: "JUPE", summary: "jupe a server name", detail: "Syntax: \x02JUPE <server.name> [reason] | JUPE DEL <server.name> | JUPE LIST\x02\nBlocks a server name from linking." },
HelpEntry { cmd: "LOGSEARCH", summary: "search the action log", detail: "Syntax: \x02LOGSEARCH [pattern]\x02\nSearches the incident and action log." },
HelpEntry { cmd: "DEFCON", summary: "network defence level", detail: "Syntax: \x02DEFCON [1-5]\x02\nShows or sets the network defence level (5 = normal, 1 = lockdown)." },
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)." },
];

View file

@ -0,0 +1,35 @@
use echo_api::{Priv, Sender, ServiceCtx, Store};
// SET READONLY {ON|OFF}: put services into (or out of) read-only lockdown.
// While on, no new registrations or changes are accepted; existing data and
// gossip replication keep working. Admin-only. No argument reports the state.
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 — SET is for services operators.");
return;
}
match args.get(1).map(|s| s.to_ascii_uppercase()).as_deref() {
Some("READONLY") => {
let Some(on) = args.get(2).and_then(|s| parse_toggle(s)) else {
let state = if db.readonly() { "ON" } else { "OFF" };
ctx.notice(me, from.uid, format!("READONLY is currently \x02{state}\x02. Syntax: SET READONLY {{ON|OFF}}"));
return;
};
db.set_readonly(on);
if on {
ctx.notice(me, from.uid, "Services are now \x02read-only\x02 — no changes will be accepted.");
} else {
ctx.notice(me, from.uid, "Services are no longer read-only.");
}
}
_ => ctx.notice(me, from.uid, "Syntax: SET READONLY {ON|OFF}"),
}
}
fn parse_toggle(s: &str) -> Option<bool> {
match s.to_ascii_uppercase().as_str() {
"ON" | "TRUE" | "YES" => Some(true),
"OFF" | "FALSE" | "NO" => Some(false),
_ => None,
}
}

View file

@ -680,11 +680,15 @@ pub struct EventLog {
versions: HashMap<String, u64>, // per-origin highest seq applied (version vector)
entries: Vec<LogEntry>, // full log, kept so peers can pull what they lack
outbound: Option<broadcast::Sender<LogEntry>>, // push newly committed entries to peers
// Operator lockdown (OperServ SET READONLY): while set, locally-authored
// writes are refused. Ephemeral — it resets on restart and never persists,
// and gossip ingestion is unaffected so a read-only node stays in sync.
readonly: bool,
}
impl EventLog {
fn open(path: PathBuf, origin: String) -> (Self, Vec<Event>) {
let mut log = Self { path, origin, lamport: 0, versions: HashMap::new(), entries: Vec::new(), outbound: None };
let mut log = Self { path, origin, lamport: 0, versions: HashMap::new(), entries: Vec::new(), outbound: None, readonly: false };
if let Ok(data) = std::fs::read_to_string(&log.path) {
for line in data.lines().filter(|l| !l.trim().is_empty()) {
match serde_json::from_str::<LogEntry>(line) {
@ -719,6 +723,10 @@ impl EventLog {
// Lamport clock and are pushed to peers; local (channel) events are written
// for restart but never gossiped and carry no version-vector identity.
fn append(&mut self, event: Event) -> std::io::Result<()> {
// Operator lockdown refuses every locally-authored write at this one seam.
if self.readonly {
return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "services are read-only"));
}
let global = event.scope() == Scope::Global;
let entry = if global {
self.lamport += 1;

View file

@ -197,6 +197,17 @@ impl Db {
self.defcon = level.clamp(1, 5);
}
/// Whether the services are in operator read-only lockdown.
pub fn readonly(&self) -> bool {
self.log.readonly
}
/// Enter or leave read-only lockdown: while on, locally-authored writes are
/// refused. Ephemeral (never persisted); gossip ingestion is unaffected.
pub fn set_readonly(&mut self, on: bool) {
self.log.readonly = on;
}
/// Whether new nick/account registrations are frozen (defcon 3 or lower).
pub fn registrations_frozen(&self) -> bool {
self.defcon <= 3

View file

@ -228,6 +228,12 @@ impl Store for Db {
fn set_defcon(&mut self, level: u8) {
Db::set_defcon(self, level)
}
fn readonly(&self) -> bool {
Db::readonly(self)
}
fn set_readonly(&mut self, on: bool) {
Db::set_readonly(self, on)
}
fn registrations_frozen(&self) -> bool {
Db::registrations_frozen(self)
}

View file

@ -200,7 +200,7 @@ impl Engine {
if self.db.external_accounts() {
return Some(reg_reply(reply, RegOutcome::External, account));
}
if self.db.registrations_frozen() {
if self.db.registrations_frozen() || self.db.readonly() {
return Some(reg_reply(reply, RegOutcome::Frozen, account));
}
if self.db.exists(account) {

View file

@ -1155,6 +1155,48 @@
assert!(notice(&e.handle(NetEvent::Privmsg { from: "000AAAAAD".into(), to: "42SAAAAAH".into(), text: "FORBID ADD NICK x y".into() }), "Access denied"), "non-oper refused");
}
// OperServ SET READONLY locks out writes: while on, a channel can't be
// registered; turning it off restores normal service.
#[test]
fn operserv_set_readonly_blocks_writes() {
use echo_chanserv::ChanServ;
use echo_nickserv::NickServ;
use echo_operserv::OperServ;
let path = std::env::temp_dir().join("echo-osreadonly.jsonl");
let _ = std::fs::remove_file(&path);
let mut db = Db::open(&path, "42S");
db.scram_iterations = 4096;
db.register("boss", "pw", None).unwrap();
let mut e = Engine::new(
vec![
Box::new(NickServ { uid: "42SAAAAAA".into(), guest_nick: "Guest".into(), guest_seq: 0 }),
Box::new(ChanServ { uid: "42SAAAAAB".into() }),
Box::new(OperServ { uid: "42SAAAAAH".into() }),
],
db,
);
let mut opers = std::collections::HashMap::new();
opers.insert("boss".to_string(), Privs::default().with(echo_api::Priv::Admin));
e.set_opers(opers);
e.handle(NetEvent::UserConnect { uid: "000AAAAAB".into(), nick: "boss".into(), host: "h".into(), ip: "0.0.0.0".into() });
e.handle(NetEvent::Privmsg { from: "000AAAAAB".into(), to: "42SAAAAAA".into(), text: "IDENTIFY pw".into() });
e.handle(NetEvent::Join { uid: "000AAAAAB".into(), channel: "#c".into(), op: true });
let os = |e: &mut Engine, t: &str| e.handle(NetEvent::Privmsg { from: "000AAAAAB".into(), to: "42SAAAAAH".into(), text: t.into() });
let cs = |e: &mut Engine, t: &str| e.handle(NetEvent::Privmsg { from: "000AAAAAB".into(), to: "42SAAAAAB".into(), text: t.into() });
let notice = |out: &[NetAction], n: &str| out.iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains(n)));
assert!(notice(&os(&mut e, "SET READONLY ON"), "read-only"), "readonly enabled");
assert!(e.db.readonly(), "flag set");
let out = cs(&mut e, "REGISTER #c");
assert!(!notice(&out, "now registered"), "register blocked while read-only: {out:?}");
assert!(e.db.channel("#c").is_none(), "no channel written");
assert!(notice(&os(&mut e, "SET READONLY OFF"), "no longer"), "readonly cleared");
assert!(!e.db.readonly(), "flag cleared");
assert!(notice(&cs(&mut e, "REGISTER #c"), "now registered"), "register works again");
assert!(e.db.channel("#c").is_some(), "channel written");
}
// OperServ SHUTDOWN/RESTART (admin) emit a Shutdown action (which the link
// layer turns into a process exit) and are refused to non-operators.
#[test]