HostServ: forbidden-vhost patterns + auto-vhost template
FORBID <regex> / FORBIDLIST / FORBIDDEL let operators block impersonating user requests (e.g. (?i)(admin|staff)); REQUEST refuses a matching host. Matching reuses the linear-time RegexSet, so untrusted patterns are safe. TEMPLATE <$account...> sets a network auto-vhost pattern; DEFAULT gives a user $account.users.example with their sanitised account name. HostServ's node config (offers/forbidden/template) is consolidated into one HostConfig threaded through the log replay.
This commit is contained in:
parent
2c32dcdc63
commit
6a8e02f004
9 changed files with 302 additions and 22 deletions
|
|
@ -606,6 +606,12 @@ pub trait Store {
|
||||||
fn vhost_offer_add(&mut self, host: &str) -> Result<bool, RegError>;
|
fn vhost_offer_add(&mut self, host: &str) -> Result<bool, RegError>;
|
||||||
fn vhost_offer_del(&mut self, index: usize) -> Result<Option<String>, RegError>;
|
fn vhost_offer_del(&mut self, index: usize) -> Result<Option<String>, RegError>;
|
||||||
fn vhost_offers(&self) -> Vec<String>;
|
fn vhost_offers(&self) -> Vec<String>;
|
||||||
|
fn vhost_forbid_add(&mut self, pattern: &str) -> Result<bool, RegError>;
|
||||||
|
fn vhost_forbid_del(&mut self, index: usize) -> Result<Option<String>, RegError>;
|
||||||
|
fn vhost_forbidden(&self) -> Vec<String>;
|
||||||
|
fn vhost_is_forbidden(&self, host: &str) -> bool;
|
||||||
|
fn set_vhost_template(&mut self, template: Option<String>) -> Result<(), RegError>;
|
||||||
|
fn vhost_template(&self) -> Option<String>;
|
||||||
fn group_nick(&mut self, nick: &str, account: &str) -> Result<(), RegError>;
|
fn group_nick(&mut self, nick: &str, account: &str) -> Result<(), RegError>;
|
||||||
fn ungroup_nick(&mut self, nick: &str) -> Result<bool, RegError>;
|
fn ungroup_nick(&mut self, nick: &str) -> Result<bool, RegError>;
|
||||||
fn drop_account(&mut self, account: &str) -> Result<bool, RegError>;
|
fn drop_account(&mut self, account: &str) -> Result<bool, RegError>;
|
||||||
|
|
|
||||||
32
hostserv/src/default.rs
Normal file
32
hostserv/src/default.rs
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
use fedserv_api::{Sender, ServiceCtx, Store};
|
||||||
|
|
||||||
|
// DEFAULT: give yourself the auto-vhost from the network template, with your
|
||||||
|
// account name substituted for $account.
|
||||||
|
pub fn handle(me: &str, from: &Sender, ctx: &mut ServiceCtx, db: &mut dyn Store) {
|
||||||
|
let Some(account) = from.account else {
|
||||||
|
ctx.notice(me, from.uid, "You need to identify to NickServ first.");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(template) = db.vhost_template() else {
|
||||||
|
ctx.notice(me, from.uid, "This network has no auto-vhost template.");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
// Sanitise the account into a host-safe label (lowercase, alphanumerics only).
|
||||||
|
let label: String = account.to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect();
|
||||||
|
if label.is_empty() {
|
||||||
|
ctx.notice(me, from.uid, "Your account name has no usable characters for a vhost.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let host = template.replace("$account", &label);
|
||||||
|
if !super::valid_vhost(&host) || db.vhost_is_forbidden(&host) {
|
||||||
|
ctx.notice(me, from.uid, "Sorry, a vhost couldn't be generated for your account.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match db.set_vhost(account, &host, "template") {
|
||||||
|
Ok(()) => {
|
||||||
|
ctx.apply_vhost(from.uid, &host);
|
||||||
|
ctx.notice(me, from.uid, format!("You now have the vhost \x02{host}\x02."));
|
||||||
|
}
|
||||||
|
Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."),
|
||||||
|
}
|
||||||
|
}
|
||||||
51
hostserv/src/forbid.rs
Normal file
51
hostserv/src/forbid.rs
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
use fedserv_api::{Sender, ServiceCtx, Store};
|
||||||
|
|
||||||
|
// FORBID <pattern>: block user-requested vhosts matching this regex (operators),
|
||||||
|
// e.g. (?i)(oper|admin|staff|services) to stop impersonation.
|
||||||
|
pub fn add(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) {
|
||||||
|
if !super::require_oper(me, from, ctx) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if args.len() < 2 {
|
||||||
|
ctx.notice(me, from.uid, "Syntax: FORBID <regex>");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let pattern = args[1..].join(" ");
|
||||||
|
match db.vhost_forbid_add(&pattern) {
|
||||||
|
Ok(true) => ctx.notice(me, from.uid, format!("Forbidden vhost pattern added: {pattern}")),
|
||||||
|
Ok(false) => ctx.notice(me, from.uid, "That pattern is already forbidden."),
|
||||||
|
Err(_) => ctx.notice(me, from.uid, format!("\x02{pattern}\x02 isn't a valid regular expression.")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FORBIDLIST: the forbidden-pattern list (operators).
|
||||||
|
pub fn list(me: &str, from: &Sender, ctx: &mut ServiceCtx, db: &dyn Store) {
|
||||||
|
if !super::require_oper(me, from, ctx) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let forbidden = db.vhost_forbidden();
|
||||||
|
if forbidden.is_empty() {
|
||||||
|
ctx.notice(me, from.uid, "No vhost patterns are forbidden.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ctx.notice(me, from.uid, format!("Forbidden vhost patterns ({}):", forbidden.len()));
|
||||||
|
for (i, p) in forbidden.iter().enumerate() {
|
||||||
|
ctx.notice(me, from.uid, format!(" {}. {p}", i + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FORBIDDEL <number>: remove a forbidden pattern (operators).
|
||||||
|
pub fn del(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) {
|
||||||
|
if !super::require_oper(me, from, ctx) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(n) = args.get(1).and_then(|s| s.parse::<usize>().ok()) else {
|
||||||
|
ctx.notice(me, from.uid, "Syntax: FORBIDDEL <number> (see FORBIDLIST)");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
match db.vhost_forbid_del(n) {
|
||||||
|
Ok(Some(pattern)) => ctx.notice(me, from.uid, format!("Removed forbidden pattern: {pattern}")),
|
||||||
|
Ok(None) => ctx.notice(me, from.uid, format!("There's no forbidden pattern #\x02{n}\x02.")),
|
||||||
|
Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -25,6 +25,12 @@ mod approve;
|
||||||
mod offer;
|
mod offer;
|
||||||
#[path = "take.rs"]
|
#[path = "take.rs"]
|
||||||
mod take;
|
mod take;
|
||||||
|
#[path = "forbid.rs"]
|
||||||
|
mod forbid;
|
||||||
|
#[path = "template.rs"]
|
||||||
|
mod template;
|
||||||
|
#[path = "default.rs"]
|
||||||
|
mod default;
|
||||||
|
|
||||||
pub struct HostServ {
|
pub struct HostServ {
|
||||||
pub uid: String,
|
pub uid: String,
|
||||||
|
|
@ -60,6 +66,11 @@ impl Service for HostServ {
|
||||||
Some("OFFERLIST") => offer::list(me, from, ctx, db),
|
Some("OFFERLIST") => offer::list(me, from, ctx, db),
|
||||||
Some("OFFERDEL") => offer::del(me, from, args, ctx, db),
|
Some("OFFERDEL") => offer::del(me, from, args, ctx, db),
|
||||||
Some("TAKE") => take::handle(me, from, args, ctx, db),
|
Some("TAKE") => take::handle(me, from, args, ctx, db),
|
||||||
|
Some("FORBID") => forbid::add(me, from, args, ctx, db),
|
||||||
|
Some("FORBIDLIST") => forbid::list(me, from, ctx, db),
|
||||||
|
Some("FORBIDDEL") => forbid::del(me, from, args, ctx, db),
|
||||||
|
Some("TEMPLATE") => template::handle(me, from, args, ctx, db),
|
||||||
|
Some("DEFAULT") => default::handle(me, from, ctx, db),
|
||||||
Some("HELP") | None => ctx.notice(me, from.uid, "HostServ gives you a vhost: \x02ON\x02 activates your assigned vhost, \x02OFF\x02 restores your normal host, \x02REQUEST\x02 <host> asks for one, \x02OFFERLIST\x02 + \x02TAKE\x02 <n> pick from the menu. Operators use \x02SET\x02/\x02DEL\x02 <account>, \x02LIST\x02, \x02WAITING\x02 + \x02ACTIVATE\x02/\x02REJECT\x02, and \x02OFFER\x02/\x02OFFERDEL\x02 for the menu."),
|
Some("HELP") | None => ctx.notice(me, from.uid, "HostServ gives you a vhost: \x02ON\x02 activates your assigned vhost, \x02OFF\x02 restores your normal host, \x02REQUEST\x02 <host> asks for one, \x02OFFERLIST\x02 + \x02TAKE\x02 <n> pick from the menu. Operators use \x02SET\x02/\x02DEL\x02 <account>, \x02LIST\x02, \x02WAITING\x02 + \x02ACTIVATE\x02/\x02REJECT\x02, and \x02OFFER\x02/\x02OFFERDEL\x02 for the menu."),
|
||||||
Some(other) => ctx.notice(me, from.uid, format!("I don't know the command \x02{other}\x02. Try \x02HELP\x02.")),
|
Some(other) => ctx.notice(me, from.uid, format!("I don't know the command \x02{other}\x02. Try \x02HELP\x02.")),
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,10 @@ pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db:
|
||||||
ctx.notice(me, from.uid, format!("\x02{host}\x02 isn't a valid host (letters, digits, hyphens and dots)."));
|
ctx.notice(me, from.uid, format!("\x02{host}\x02 isn't a valid host (letters, digits, hyphens and dots)."));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if db.vhost_is_forbidden(host) {
|
||||||
|
ctx.notice(me, from.uid, format!("\x02{host}\x02 isn't allowed here. Please choose another."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
match db.request_vhost(account, host) {
|
match db.request_vhost(account, host) {
|
||||||
Ok(()) => ctx.notice(me, from.uid, format!("Requested vhost \x02{host}\x02 — an operator will review it.")),
|
Ok(()) => ctx.notice(me, from.uid, format!("Requested vhost \x02{host}\x02 — an operator will review it.")),
|
||||||
Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."),
|
Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."),
|
||||||
|
|
|
||||||
32
hostserv/src/template.rs
Normal file
32
hostserv/src/template.rs
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
use fedserv_api::{Sender, ServiceCtx, Store};
|
||||||
|
|
||||||
|
// TEMPLATE [<pattern>]: show the auto-vhost template, or (operators) set it.
|
||||||
|
// Use $account for the requester's sanitised account name, e.g.
|
||||||
|
// $account.users.example. Give no argument to show it, OFF to clear it.
|
||||||
|
pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) {
|
||||||
|
match args.get(1) {
|
||||||
|
None => match db.vhost_template() {
|
||||||
|
Some(t) => ctx.notice(me, from.uid, format!("Auto-vhost template: \x02{t}\x02. Users apply it with \x02DEFAULT\x02.")),
|
||||||
|
None => ctx.notice(me, from.uid, "No auto-vhost template is set."),
|
||||||
|
},
|
||||||
|
Some(&arg) => {
|
||||||
|
if !super::require_oper(me, from, ctx) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if arg.eq_ignore_ascii_case("OFF") {
|
||||||
|
let _ = db.set_vhost_template(None);
|
||||||
|
ctx.notice(me, from.uid, "Auto-vhost template cleared.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let template = args[1..].join(" ");
|
||||||
|
if !template.contains("$account") || !super::valid_vhost(&template.replace("$account", "x")) {
|
||||||
|
ctx.notice(me, from.uid, "The template must contain \x02$account\x02 and form a valid host, e.g. \x02$account.users.example\x02.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match db.set_vhost_template(Some(template.clone())) {
|
||||||
|
Ok(()) => ctx.notice(me, from.uid, format!("Auto-vhost template set to \x02{template}\x02.")),
|
||||||
|
Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
140
src/engine/db.rs
140
src/engine/db.rs
|
|
@ -150,6 +150,9 @@ pub enum Event {
|
||||||
BotRemoved { nick: String },
|
BotRemoved { nick: String },
|
||||||
VhostOfferAdded { host: String },
|
VhostOfferAdded { host: String },
|
||||||
VhostOfferRemoved { host: String },
|
VhostOfferRemoved { host: String },
|
||||||
|
VhostForbidAdded { pattern: String },
|
||||||
|
VhostForbidRemoved { pattern: String },
|
||||||
|
VhostTemplateSet { template: Option<String> },
|
||||||
}
|
}
|
||||||
|
|
||||||
// Whether an event replicates across the federation. Account identity is Global
|
// Whether an event replicates across the federation. Account identity is Global
|
||||||
|
|
@ -208,7 +211,10 @@ impl Event {
|
||||||
| Event::BotAdded(_)
|
| Event::BotAdded(_)
|
||||||
| Event::BotRemoved { .. }
|
| Event::BotRemoved { .. }
|
||||||
| Event::VhostOfferAdded { .. }
|
| Event::VhostOfferAdded { .. }
|
||||||
| Event::VhostOfferRemoved { .. } => Scope::Local,
|
| Event::VhostOfferRemoved { .. }
|
||||||
|
| Event::VhostForbidAdded { .. }
|
||||||
|
| Event::VhostForbidRemoved { .. }
|
||||||
|
| Event::VhostTemplateSet { .. } => Scope::Local,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -780,8 +786,20 @@ pub struct Db {
|
||||||
auth_fails: HashMap<String, AuthThrottle>,
|
auth_fails: HashMap<String, AuthThrottle>,
|
||||||
// Registered service bots (BotServ), keyed by casefolded nick.
|
// Registered service bots (BotServ), keyed by casefolded nick.
|
||||||
bots: HashMap<String, Bot>,
|
bots: HashMap<String, Bot>,
|
||||||
// HostServ vhost offers: a menu of specs users may self-assign with TAKE.
|
// HostServ node config: the self-serve offer menu, the forbidden-pattern
|
||||||
vhost_offers: Vec<String>,
|
// blocklist, and the auto-vhost template.
|
||||||
|
host_cfg: HostConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Network-wide HostServ configuration, rebuilt from the event log.
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct HostConfig {
|
||||||
|
// Specs users may self-assign with TAKE.
|
||||||
|
pub offers: Vec<String>,
|
||||||
|
// Regex patterns a user-requested/taken vhost may not match (anti-impersonation).
|
||||||
|
pub forbidden: Vec<String>,
|
||||||
|
// Auto-vhost template, e.g. "$account.users.example" (DEFAULT substitutes).
|
||||||
|
pub template: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
// A pending emailed code and how many wrong guesses remain before it is burned.
|
// A pending emailed code and how many wrong guesses remain before it is burned.
|
||||||
|
|
@ -820,12 +838,12 @@ impl Db {
|
||||||
let mut channels = HashMap::new();
|
let mut channels = HashMap::new();
|
||||||
let mut grouped = HashMap::new();
|
let mut grouped = HashMap::new();
|
||||||
let mut bots = HashMap::new();
|
let mut bots = HashMap::new();
|
||||||
let mut vhost_offers = Vec::new();
|
let mut host_cfg = HostConfig::default();
|
||||||
for event in events {
|
for event in events {
|
||||||
apply(&mut accounts, &mut channels, &mut grouped, &mut bots, &mut vhost_offers, event);
|
apply(&mut accounts, &mut channels, &mut grouped, &mut bots, &mut host_cfg, event);
|
||||||
}
|
}
|
||||||
tracing::info!(accounts = accounts.len(), channels = channels.len(), "account store loaded");
|
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(), bots, vhost_offers }
|
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(), bots, host_cfg }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fold an entry authored by another node into the store — the services-side
|
/// Fold an entry authored by another node into the store — the services-side
|
||||||
|
|
@ -841,7 +859,7 @@ impl Db {
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
if let Some(event) = self.log.ingest(entry)? {
|
if let Some(event) = self.log.ingest(entry)? {
|
||||||
apply(&mut self.accounts, &mut self.channels, &mut self.grouped, &mut self.bots, &mut self.vhost_offers, event);
|
apply(&mut self.accounts, &mut self.channels, &mut self.grouped, &mut self.bots, &mut self.host_cfg, event);
|
||||||
}
|
}
|
||||||
if let Some((name, prev_home)) = watched {
|
if let Some((name, prev_home)) = watched {
|
||||||
match (prev_home, self.account(&name).map(|c| c.home.clone())) {
|
match (prev_home, self.account(&name).map(|c| c.home.clone())) {
|
||||||
|
|
@ -902,9 +920,15 @@ impl Db {
|
||||||
for b in self.bots.values() {
|
for b in self.bots.values() {
|
||||||
snapshot.push(Event::BotAdded(b.clone()));
|
snapshot.push(Event::BotAdded(b.clone()));
|
||||||
}
|
}
|
||||||
for host in &self.vhost_offers {
|
for host in &self.host_cfg.offers {
|
||||||
snapshot.push(Event::VhostOfferAdded { host: host.clone() });
|
snapshot.push(Event::VhostOfferAdded { host: host.clone() });
|
||||||
}
|
}
|
||||||
|
for pattern in &self.host_cfg.forbidden {
|
||||||
|
snapshot.push(Event::VhostForbidAdded { pattern: pattern.clone() });
|
||||||
|
}
|
||||||
|
if self.host_cfg.template.is_some() {
|
||||||
|
snapshot.push(Event::VhostTemplateSet { template: self.host_cfg.template.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(())
|
||||||
|
|
@ -1246,28 +1270,73 @@ impl Db {
|
||||||
|
|
||||||
/// Add a vhost offer to the self-serve menu. Ok(false) if already offered.
|
/// Add a vhost offer to the self-serve menu. Ok(false) if already offered.
|
||||||
pub fn vhost_offer_add(&mut self, host: &str) -> Result<bool, RegError> {
|
pub fn vhost_offer_add(&mut self, host: &str) -> Result<bool, RegError> {
|
||||||
if self.vhost_offers.iter().any(|o| o == host) {
|
if self.host_cfg.offers.iter().any(|o| o == host) {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
self.log.append(Event::VhostOfferAdded { host: host.to_string() }).map_err(|_| RegError::Internal)?;
|
self.log.append(Event::VhostOfferAdded { host: host.to_string() }).map_err(|_| RegError::Internal)?;
|
||||||
self.vhost_offers.push(host.to_string());
|
self.host_cfg.offers.push(host.to_string());
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remove the offer at 1-based `index`. Returns the removed spec, if valid.
|
/// Remove the offer at 1-based `index`. Returns the removed spec, if valid.
|
||||||
pub fn vhost_offer_del(&mut self, index: usize) -> Result<Option<String>, RegError> {
|
pub fn vhost_offer_del(&mut self, index: usize) -> Result<Option<String>, RegError> {
|
||||||
if index == 0 || index > self.vhost_offers.len() {
|
if index == 0 || index > self.host_cfg.offers.len() {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
let host = self.vhost_offers[index - 1].clone();
|
let host = self.host_cfg.offers[index - 1].clone();
|
||||||
self.log.append(Event::VhostOfferRemoved { host: host.clone() }).map_err(|_| RegError::Internal)?;
|
self.log.append(Event::VhostOfferRemoved { host: host.clone() }).map_err(|_| RegError::Internal)?;
|
||||||
self.vhost_offers.retain(|o| o != &host);
|
self.host_cfg.offers.retain(|o| o != &host);
|
||||||
Ok(Some(host))
|
Ok(Some(host))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The self-serve vhost offer menu.
|
/// The self-serve vhost offer menu.
|
||||||
pub fn vhost_offers(&self) -> &[String] {
|
pub fn vhost_offers(&self) -> &[String] {
|
||||||
&self.vhost_offers
|
&self.host_cfg.offers
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a forbidden vhost regex (anti-impersonation). Validates it compiles;
|
||||||
|
/// Ok(false) if already present.
|
||||||
|
pub fn vhost_forbid_add(&mut self, pattern: &str) -> Result<bool, RegError> {
|
||||||
|
if regex::RegexBuilder::new(pattern).size_limit(BADWORD_SIZE_LIMIT).build().is_err() {
|
||||||
|
return Err(RegError::Internal);
|
||||||
|
}
|
||||||
|
if self.host_cfg.forbidden.iter().any(|p| p == pattern) {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
self.log.append(Event::VhostForbidAdded { pattern: pattern.to_string() }).map_err(|_| RegError::Internal)?;
|
||||||
|
self.host_cfg.forbidden.push(pattern.to_string());
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove the forbidden pattern at 1-based `index`; returns it if valid.
|
||||||
|
pub fn vhost_forbid_del(&mut self, index: usize) -> Result<Option<String>, RegError> {
|
||||||
|
if index == 0 || index > self.host_cfg.forbidden.len() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let pattern = self.host_cfg.forbidden[index - 1].clone();
|
||||||
|
self.log.append(Event::VhostForbidRemoved { pattern: pattern.clone() }).map_err(|_| RegError::Internal)?;
|
||||||
|
self.host_cfg.forbidden.retain(|p| p != &pattern);
|
||||||
|
Ok(Some(pattern))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn vhost_forbidden(&self) -> &[String] {
|
||||||
|
&self.host_cfg.forbidden
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `host` matches a forbidden pattern (case-insensitive).
|
||||||
|
pub fn vhost_is_forbidden(&self, host: &str) -> bool {
|
||||||
|
!self.host_cfg.forbidden.is_empty() && build_badword_set(&self.host_cfg.forbidden).is_match(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set (or clear) the auto-vhost template, e.g. "$account.users.example".
|
||||||
|
pub fn set_vhost_template(&mut self, template: Option<String>) -> Result<(), RegError> {
|
||||||
|
self.log.append(Event::VhostTemplateSet { template: template.clone() }).map_err(|_| RegError::Internal)?;
|
||||||
|
self.host_cfg.template = template;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn vhost_template(&self) -> Option<&str> {
|
||||||
|
self.host_cfg.template.as_deref()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Every account that has a vhost, as (account, host, setter).
|
/// Every account that has a vhost, as (account, host, setter).
|
||||||
|
|
@ -2065,7 +2134,7 @@ fn owns_over(held: &Account, claim: &Account) -> bool {
|
||||||
|
|
||||||
// Fold one event into the store. Shared by log replay (`open`) and gossip
|
// Fold one event into the store. Shared by log replay (`open`) and gossip
|
||||||
// ingest, so both routes reconstruct identical state.
|
// 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>, offers: &mut Vec<String>, 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, event: Event) {
|
||||||
match event {
|
match event {
|
||||||
Event::AccountRegistered(a) => {
|
Event::AccountRegistered(a) => {
|
||||||
// Resolve a concurrent registration of the same name deterministically:
|
// Resolve a concurrent registration of the same name deterministically:
|
||||||
|
|
@ -2278,12 +2347,23 @@ fn apply(accounts: &mut HashMap<String, Account>, channels: &mut HashMap<String,
|
||||||
bots.remove(&key(&nick));
|
bots.remove(&key(&nick));
|
||||||
}
|
}
|
||||||
Event::VhostOfferAdded { host } => {
|
Event::VhostOfferAdded { host } => {
|
||||||
if !offers.iter().any(|o| o == &host) {
|
if !host_cfg.offers.iter().any(|o| o == &host) {
|
||||||
offers.push(host);
|
host_cfg.offers.push(host);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Event::VhostOfferRemoved { host } => {
|
Event::VhostOfferRemoved { host } => {
|
||||||
offers.retain(|o| o != &host);
|
host_cfg.offers.retain(|o| o != &host);
|
||||||
|
}
|
||||||
|
Event::VhostForbidAdded { pattern } => {
|
||||||
|
if !host_cfg.forbidden.iter().any(|p| p == &pattern) {
|
||||||
|
host_cfg.forbidden.push(pattern);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::VhostForbidRemoved { pattern } => {
|
||||||
|
host_cfg.forbidden.retain(|p| p != &pattern);
|
||||||
|
}
|
||||||
|
Event::VhostTemplateSet { template } => {
|
||||||
|
host_cfg.template = template;
|
||||||
}
|
}
|
||||||
Event::ChannelEntryMsgSet { channel, msg } => {
|
Event::ChannelEntryMsgSet { channel, msg } => {
|
||||||
if let Some(c) = channels.get_mut(&key(&channel)) {
|
if let Some(c) = channels.get_mut(&key(&channel)) {
|
||||||
|
|
@ -2451,6 +2531,24 @@ impl Store for Db {
|
||||||
fn vhost_offers(&self) -> Vec<String> {
|
fn vhost_offers(&self) -> Vec<String> {
|
||||||
Db::vhost_offers(self).to_vec()
|
Db::vhost_offers(self).to_vec()
|
||||||
}
|
}
|
||||||
|
fn vhost_forbid_add(&mut self, pattern: &str) -> Result<bool, RegError> {
|
||||||
|
Db::vhost_forbid_add(self, pattern)
|
||||||
|
}
|
||||||
|
fn vhost_forbid_del(&mut self, index: usize) -> Result<Option<String>, RegError> {
|
||||||
|
Db::vhost_forbid_del(self, index)
|
||||||
|
}
|
||||||
|
fn vhost_forbidden(&self) -> Vec<String> {
|
||||||
|
Db::vhost_forbidden(self).to_vec()
|
||||||
|
}
|
||||||
|
fn vhost_is_forbidden(&self, host: &str) -> bool {
|
||||||
|
Db::vhost_is_forbidden(self, host)
|
||||||
|
}
|
||||||
|
fn set_vhost_template(&mut self, template: Option<String>) -> Result<(), RegError> {
|
||||||
|
Db::set_vhost_template(self, template)
|
||||||
|
}
|
||||||
|
fn vhost_template(&self) -> Option<String> {
|
||||||
|
Db::vhost_template(self).map(str::to_string)
|
||||||
|
}
|
||||||
fn group_nick(&mut self, nick: &str, account: &str) -> Result<(), RegError> {
|
fn group_nick(&mut self, nick: &str, account: &str) -> Result<(), RegError> {
|
||||||
Db::group_nick(self, nick, account)
|
Db::group_nick(self, nick, account)
|
||||||
}
|
}
|
||||||
|
|
@ -2693,9 +2791,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,
|
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,
|
||||||
};
|
};
|
||||||
let converge = |first: &Account, second: &Account| {
|
let converge = |first: &Account, second: &Account| {
|
||||||
let (mut acc, mut ch, mut gr, mut bo, mut of) = (HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new(), Vec::new());
|
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 of, Event::AccountRegistered(first.clone()));
|
apply(&mut acc, &mut ch, &mut gr, &mut bo, &mut hc, Event::AccountRegistered(first.clone()));
|
||||||
apply(&mut acc, &mut ch, &mut gr, &mut bo, &mut of, Event::AccountRegistered(second.clone()));
|
apply(&mut acc, &mut ch, &mut gr, &mut bo, &mut hc, Event::AccountRegistered(second.clone()));
|
||||||
acc["alice"].password_hash.clone()
|
acc["alice"].password_hash.clone()
|
||||||
};
|
};
|
||||||
// Earlier registration wins, regardless of which claim applies first.
|
// Earlier registration wins, regardless of which claim applies first.
|
||||||
|
|
|
||||||
|
|
@ -2686,6 +2686,49 @@ mod tests {
|
||||||
assert!(hs(&mut e, "000AAAAAB", "SET alice not a host").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("isn't a valid host"))), "host validated");
|
assert!(hs(&mut e, "000AAAAAB", "SET alice not a host").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("isn't a valid host"))), "host validated");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Forbidden patterns block impersonating requests; the template + DEFAULT
|
||||||
|
// gives a user a $account-based vhost.
|
||||||
|
#[test]
|
||||||
|
fn hostserv_forbid_and_template() {
|
||||||
|
use fedserv_hostserv::HostServ;
|
||||||
|
use fedserv_nickserv::NickServ;
|
||||||
|
let path = std::env::temp_dir().join("fedserv-hsforbid.jsonl");
|
||||||
|
let _ = std::fs::remove_file(&path);
|
||||||
|
let mut db = Db::open(&path, "42S");
|
||||||
|
db.scram_iterations = 4096;
|
||||||
|
db.register("boss", "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(HostServ { uid: "42SAAAAAG".into() }),
|
||||||
|
],
|
||||||
|
db,
|
||||||
|
);
|
||||||
|
e.set_sid("42S".into());
|
||||||
|
let mut opers = std::collections::HashMap::new();
|
||||||
|
opers.insert("boss".to_string(), Privs::default().with(fedserv_api::Priv::Admin));
|
||||||
|
e.set_opers(opers);
|
||||||
|
let ns = |e: &mut Engine, uid: &str, t: &str| e.handle(NetEvent::Privmsg { from: uid.into(), to: "42SAAAAAA".into(), text: t.into() });
|
||||||
|
let hs = |e: &mut Engine, uid: &str, t: &str| e.handle(NetEvent::Privmsg { from: uid.into(), to: "42SAAAAAG".into(), text: t.into() });
|
||||||
|
e.handle(NetEvent::UserConnect { uid: "000AAAAAB".into(), nick: "boss".into(), host: "realhost".into() });
|
||||||
|
e.handle(NetEvent::UserConnect { uid: "000AAAAAV".into(), nick: "alice".into(), host: "realhost".into() });
|
||||||
|
ns(&mut e, "000AAAAAB", "IDENTIFY password1");
|
||||||
|
ns(&mut e, "000AAAAAV", "IDENTIFY password1");
|
||||||
|
let says = |out: &[NetAction], n: &str| out.iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains(n)));
|
||||||
|
|
||||||
|
// Forbid impersonating hosts; a matching request is refused, others pass.
|
||||||
|
hs(&mut e, "000AAAAAB", "FORBID (?i)(admin|staff)");
|
||||||
|
assert!(says(&hs(&mut e, "000AAAAAV", "REQUEST admin.example"), "isn't allowed"), "impersonating request blocked");
|
||||||
|
assert!(says(&hs(&mut e, "000AAAAAV", "REQUEST cool.example"), "will review"), "clean request allowed");
|
||||||
|
assert!(says(&hs(&mut e, "000AAAAAV", "FORBID x"), "Access denied"), "FORBID oper-gated");
|
||||||
|
|
||||||
|
// A template lets a user self-serve a $account vhost.
|
||||||
|
hs(&mut e, "000AAAAAB", "TEMPLATE $account.users.example");
|
||||||
|
let out = hs(&mut e, "000AAAAAV", "DEFAULT");
|
||||||
|
assert!(out.iter().any(|a| matches!(a, NetAction::SetHost { uid, host } if uid == "000AAAAAV" && host == "alice.users.example")), "template applied: {out:?}");
|
||||||
|
}
|
||||||
|
|
||||||
// The vhost OFFER menu: operators OFFER specs, users TAKE them self-serve.
|
// The vhost OFFER menu: operators OFFER specs, users TAKE them self-serve.
|
||||||
#[test]
|
#[test]
|
||||||
fn hostserv_offer_menu() {
|
fn hostserv_offer_menu() {
|
||||||
|
|
|
||||||
|
|
@ -154,7 +154,10 @@ fn to_wire(entry: &LogEntry) -> Option<ReplicationEvent> {
|
||||||
| Event::BotAdded(_)
|
| Event::BotAdded(_)
|
||||||
| Event::BotRemoved { .. }
|
| Event::BotRemoved { .. }
|
||||||
| Event::VhostOfferAdded { .. }
|
| Event::VhostOfferAdded { .. }
|
||||||
| Event::VhostOfferRemoved { .. } => return None,
|
| Event::VhostOfferRemoved { .. }
|
||||||
|
| Event::VhostForbidAdded { .. }
|
||||||
|
| Event::VhostForbidRemoved { .. }
|
||||||
|
| Event::VhostTemplateSet { .. } => 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) })
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue