filters: share the IP-ban logic between ratelimit and content

Extract the per-IP strike counter + temporary IP-ban that `ratelimit` grew
into a reusable `BanTracker` (src/filters/ban.rs), embedded in a filter with
`#[serde(flatten)]` so its `ban_after` / `ban_duration_secs` / `ban_message`
knobs stay at the filter's own config level. The tracker holds state; the
filter decides what a "strike" is and how to respond while banned.

`ratelimit` keeps its consecutive-streak policy (any accepted post calls
`reset`), and now `content` reuses the same machinery with a cumulative
policy: content violations accrue per IP without a clean note resetting them,
and once they cross `ban_after` every note from that IP is silently
shadow-rejected — matching content's existing stealth stance rather than
revealing a visible reject. Banning stays opt-in; with `ban_after` unset both
filters store zero per-IP state and behave exactly as before.

Changelog-Added: Content filter can now IP-ban repeat offenders after N violations, reusing the ratelimit ban mechanism

Headway: headway:noteguard/depend-jeans-enable
Agentium: agentium:voyage-hamster-exile
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
William Casarin
2026-09-08 21:59:28 -07:00
co-authored by Claude Opus 4.8
parent 4b16308ff0
commit 64f246e547
5 changed files with 280 additions and 90 deletions
+8
View File
@@ -21,6 +21,14 @@ filters = [
"https://cdn.nostr.build/i/some-spammy-or-abusive-image-image.png",
"Damus Airdrop",
]
# IP-ban repeat offenders (same knobs as `filters.ratelimit`). Content
# violations accrue *cumulatively* per IP — unlike ratelimit's consecutive
# streak, a clean note does not reset the count — and once they cross
# `ban_after`, every note from that IP is silently shadow-rejected for
# `ban_duration_secs`. Omit `ban_after` to disable banning (match-only, as
# before). `ban_message` is unused here since the ban is a stealth shadow-reject.
ban_after = 5
ban_duration_secs = 3600 # one hour
[filters.whitelist]
pubkeys = ["16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93"]
+122
View File
@@ -0,0 +1,122 @@
//! Reusable per-IP strike counter + temporary IP-ban, shared by write-path
//! filters that want to escalate repeat offenders into a short block.
//!
//! A filter embeds a [`BanTracker`] with `#[serde(flatten)]`, so its
//! `ban_after` / `ban_duration_secs` / `ban_message` knobs live at the filter's
//! own config table level. The tracker keeps the state; the *filter* decides
//! what a "strike" is (a rate-limit hit, a content match, …) and what action to
//! return while banned (a visible `Reject`, a stealth `ShadowReject`, …).
//!
//! Two streak policies fall out of which methods a filter calls:
//!
//! * **Consecutive** (e.g. `ratelimit`): call [`reset`](BanTracker::reset) on
//! every clean event, so only an unbroken run of violations bans.
//! * **Cumulative** (e.g. `content`): never call `reset`, so violations accrue
//! across a session until they cross the threshold.
//!
//! When `ban_after` is unset the tracker is inert and stores no per-IP state, so
//! a filter that leaves banning unconfigured behaves exactly as it did before.
use serde::{Deserialize, Deserializer};
use std::collections::HashMap;
use std::time::{Duration, Instant};
/// Default ban length once an IP crosses the threshold: one hour.
const DEFAULT_BAN_DURATION_SECS: u64 = 3600;
/// The `ban_*` knobs, deserialized flat into the embedding filter's config.
#[derive(Deserialize, Default)]
struct BanConfig {
/// IP-ban an offender after this many strikes. `None` disables banning.
ban_after: Option<i32>,
/// How long a ban lasts, in seconds. Defaults to [`DEFAULT_BAN_DURATION_SECS`].
ban_duration_secs: Option<u64>,
/// Message returned to a banned IP (filters that shadow-reject may ignore it).
ban_message: Option<String>,
}
struct BanState {
strikes: i32,
banned_until: Option<Instant>,
}
/// Per-IP strike tracking plus the active-ban set. See the [module docs](self).
#[derive(Default)]
pub struct BanTracker {
config: BanConfig,
ips: HashMap<String, BanState>,
}
// Deserialized via the flattened `BanConfig`; the state map always starts empty.
impl<'de> Deserialize<'de> for BanTracker {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(BanTracker {
config: BanConfig::deserialize(deserializer)?,
ips: HashMap::new(),
})
}
}
impl BanTracker {
/// The message handed to a banned IP, or a generic fallback.
pub fn message(&self) -> &str {
self.config
.ban_message
.as_deref()
.unwrap_or("banned: too many violations, try again later")
}
/// Whether `ip` is under an active ban. An expired ban is cleared here, along
/// with its strike streak, so the next event starts fresh.
pub fn is_banned(&mut self, ip: &str, now: Instant) -> bool {
let Some(state) = self.ips.get_mut(ip) else {
return false;
};
match state.banned_until {
Some(until) if now < until => true,
Some(_) => {
state.banned_until = None;
state.strikes = 0;
false
}
None => false,
}
}
/// Record a violation for `ip`. Returns `true` if this strike crossed
/// `ban_after` and the IP is now banned. A no-op returning `false` when
/// banning is disabled, so callers keep zero per-IP state in that case.
pub fn strike(&mut self, ip: &str, now: Instant) -> bool {
let Some(ban_after) = self.config.ban_after else {
return false;
};
let state = self.ips.entry(ip.to_owned()).or_insert(BanState {
strikes: 0,
banned_until: None,
});
state.strikes += 1;
if state.strikes >= ban_after {
let secs = self
.config
.ban_duration_secs
.unwrap_or(DEFAULT_BAN_DURATION_SECS);
state.banned_until = Some(now + Duration::from_secs(secs));
true
} else {
false
}
}
/// Clear `ip`'s strike streak after a clean event (the "consecutive" policy).
/// Filters with cumulative semantics simply never call this.
pub fn reset(&mut self, ip: &str) {
if let Some(state) = self.ips.get_mut(ip) {
state.strikes = 0;
}
}
}
+107 -8
View File
@@ -1,5 +1,7 @@
use crate::filters::ban::BanTracker;
use crate::{Action, InputMessage, NoteFilter, OutputMessage};
use serde::Deserialize;
use std::time::Instant;
use unicode_security::skeleton;
#[derive(Deserialize, Default)]
@@ -12,6 +14,13 @@ pub struct Content {
/// spam — that a raw byte-wise `contains` check silently misses.
#[serde(skip)]
normalized: Option<Vec<String>>,
/// IP-ban repeat offenders. Content violations accrue *cumulatively* per IP
/// (a matching note never resets the count); once they cross `ban_after`
/// every note from that IP is shadow-rejected until the ban expires. See
/// [`BanTracker`]. Flattened so `ban_after` etc. sit at this filter's level.
#[serde(flatten)]
ban: BanTracker,
}
/// Fold a string to its UTS #39 confusables skeleton, case-folded, so that
@@ -25,15 +34,28 @@ fn normalize(s: &str) -> String {
impl NoteFilter for Content {
fn filter_note(&mut self, msg: &InputMessage) -> OutputMessage {
let normalized = self
.normalized
.get_or_insert_with(|| self.filters.iter().map(|f| normalize(f)).collect());
let now = Instant::now();
let content = normalize(&msg.event.content);
for filter in normalized.iter() {
if content.contains(filter) {
return OutputMessage::new(msg.event.id.clone(), Action::ShadowReject, None);
}
// A banned IP has everything silently dropped, not just matching notes —
// shadow-rejected to keep the ban invisible to the offender, like a
// content match itself.
if self.ban.is_banned(&msg.source_info, now) {
return OutputMessage::new(msg.event.id.clone(), Action::ShadowReject, None);
}
let matched = {
let normalized = self
.normalized
.get_or_insert_with(|| self.filters.iter().map(|f| normalize(f)).collect());
let content = normalize(&msg.event.content);
normalized.iter().any(|filter| content.contains(filter))
};
if matched {
// Count the violation (may trip a ban for next time); either way this
// note is shadow-rejected.
self.ban.strike(&msg.source_info, now);
return OutputMessage::new(msg.event.id.clone(), Action::ShadowReject, None);
}
OutputMessage::new(msg.event.id.clone(), Action::Accept, None)
@@ -43,3 +65,80 @@ impl NoteFilter for Content {
"content"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Note;
fn msg(id: &str, ip: &str, content: &str) -> InputMessage {
InputMessage {
message_type: "new".to_string(),
event: Note {
id: id.to_string(),
pubkey: "pk".to_string(),
created_at: 0,
kind: 1,
tags: vec![],
content: content.to_string(),
sig: "sig".to_string(),
},
received_at: 0,
source_type: "IP4".to_string(),
source_info: ip.to_string(),
}
}
fn content(toml_cfg: &str) -> Content {
toml::from_str(toml_cfg).expect("valid content config")
}
#[test]
fn matches_shadow_reject_without_banning() {
let mut c = content("filters = [\"spam\"]\n");
assert_eq!(
c.filter_note(&msg("e1", "1.2.3.4", "buy spam now")).action,
Action::ShadowReject
);
// No ban configured, so a clean note from the same IP still passes.
assert_eq!(
c.filter_note(&msg("e2", "1.2.3.4", "hello")).action,
Action::Accept
);
}
#[test]
fn bans_after_cumulative_violations() {
let mut c = content("filters = [\"spam\"]\nban_after = 3\n");
// Clean notes interleaved with spam must NOT reset the streak.
assert_eq!(
c.filter_note(&msg("e1", "9.9.9.9", "spam")).action,
Action::ShadowReject
);
assert_eq!(
c.filter_note(&msg("e2", "9.9.9.9", "hello")).action,
Action::Accept
);
assert_eq!(
c.filter_note(&msg("e3", "9.9.9.9", "spam")).action,
Action::ShadowReject
);
// Third violation trips the ban.
assert_eq!(
c.filter_note(&msg("e4", "9.9.9.9", "spam")).action,
Action::ShadowReject
);
// Now banned: even a perfectly clean note is silently dropped.
assert_eq!(
c.filter_note(&msg("e5", "9.9.9.9", "totally fine")).action,
Action::ShadowReject
);
// A different IP is unaffected.
assert_eq!(
c.filter_note(&msg("e6", "8.8.8.8", "totally fine")).action,
Action::Accept
);
}
}
+1
View File
@@ -1,3 +1,4 @@
mod ban;
mod blacklist;
mod content;
mod kinds;
+42 -82
View File
@@ -1,20 +1,12 @@
use crate::filters::ban::BanTracker;
use crate::{Action, InputMessage, NoteFilter, OutputMessage};
use serde::Deserialize;
use std::collections::HashMap;
use std::time::{Duration, Instant};
/// Default IP-ban duration once an IP trips [`RateLimit::ban_after`]: one hour.
const DEFAULT_BAN_DURATION_SECS: u64 = 3600;
pub struct Tokens {
pub tokens: i32,
pub last_post: Instant,
/// Consecutive rate-limit rejections since the last accepted post. Reset to
/// zero whenever a post is accepted, and whenever an expired ban is cleared.
pub strikes: i32,
/// When set and still in the future, every post from this IP is rejected
/// outright (the IP-ban). Cleared, along with `strikes`, once it elapses.
pub banned_until: Option<Instant>,
}
#[derive(Deserialize, Default)]
@@ -23,29 +15,16 @@ pub struct RateLimit {
pub whitelist: Option<Vec<String>>,
pub message: Option<String>,
/// IP-ban an offender after this many *consecutive* rate-limit rejections.
/// `None` (the default) disables banning: the filter only ever rate-limits.
pub ban_after: Option<i32>,
/// How long an IP-ban lasts, in seconds. Defaults to
/// [`DEFAULT_BAN_DURATION_SECS`] (one hour) when `ban_after` is set.
pub ban_duration_secs: Option<u64>,
/// Message returned to a banned IP. Falls back to a generic notice.
pub ban_message: Option<String>,
/// IP-ban persistent offenders. `ban_after` *consecutive* rate-limit
/// rejections (a streak any accepted post resets) trips a ban; see
/// [`BanTracker`]. Flattened so `ban_after` etc. sit at this filter's level.
#[serde(flatten)]
pub ban: BanTracker,
#[serde(skip)]
pub sources: HashMap<String, Tokens>,
}
impl RateLimit {
fn ban_reject(&self, id: String) -> OutputMessage {
let message = self
.ban_message
.as_deref()
.unwrap_or("banned: too many rate-limit violations, try again later");
OutputMessage::new(id, Action::Reject, Some(message.to_owned()))
}
}
impl NoteFilter for RateLimit {
fn name(&self) -> &'static str {
"ratelimit"
@@ -60,31 +39,28 @@ impl NoteFilter for RateLimit {
let now = Instant::now();
// Enforce an active IP-ban before touching the token bucket, so a banned
// IP cannot refill or reset anything by continuing to hammer us.
if self.ban.is_banned(&msg.source_info, now) {
return OutputMessage::new(
msg.event.id.clone(),
Action::Reject,
Some(self.ban.message().to_owned()),
);
}
if !self.sources.contains_key(&msg.source_info) {
self.sources.insert(
msg.source_info.to_owned(),
Tokens {
last_post: now,
tokens: self.posts_per_minute,
strikes: 0,
banned_until: None,
},
);
return OutputMessage::new(msg.event.id.clone(), Action::Accept, None);
}
let entry = self.sources.get_mut(&msg.source_info).expect("impossiburu");
// Enforce an active IP-ban before touching the token bucket, so a banned
// IP cannot refill or reset anything by continuing to hammer us.
if let Some(until) = entry.banned_until {
if now < until {
return self.ban_reject(msg.event.id.clone());
}
entry.banned_until = None;
entry.strikes = 0;
}
let mut diff = now - entry.last_post;
let min = Duration::from_secs(60);
@@ -107,13 +83,12 @@ impl NoteFilter for RateLimit {
if entry.tokens == 0 {
// Persistent offender: escalate a streak of rate-limit hits into an
// IP-ban once it crosses the configured threshold.
if let Some(ban_after) = self.ban_after {
entry.strikes += 1;
if entry.strikes >= ban_after {
let secs = self.ban_duration_secs.unwrap_or(DEFAULT_BAN_DURATION_SECS);
entry.banned_until = Some(now + Duration::from_secs(secs));
return self.ban_reject(msg.event.id.clone());
}
if self.ban.strike(&msg.source_info, now) {
return OutputMessage::new(
msg.event.id.clone(),
Action::Reject,
Some(self.ban.message().to_owned()),
);
}
let message = self
@@ -130,7 +105,7 @@ impl NoteFilter for RateLimit {
entry.last_post = now;
// A successful post breaks the rate-limit streak.
entry.strikes = 0;
self.ban.reset(&msg.source_info);
OutputMessage::new(msg.event.id.clone(), Action::Accept, None)
}
}
@@ -158,13 +133,13 @@ mod tests {
}
}
fn ratelimit(toml_cfg: &str) -> RateLimit {
toml::from_str(toml_cfg).expect("valid ratelimit config")
}
#[test]
fn bans_after_consecutive_strikes() {
let mut rl = RateLimit {
posts_per_minute: 1,
ban_after: Some(3),
..Default::default()
};
let mut rl = ratelimit("posts_per_minute = 1\nban_after = 3\n");
// First post seeds the bucket and is accepted.
assert_eq!(rl.filter_note(&msg("e1", "1.2.3.4")).action, Action::Accept);
@@ -188,10 +163,7 @@ mod tests {
#[test]
fn no_ban_when_unconfigured() {
let mut rl = RateLimit {
posts_per_minute: 1,
..Default::default()
};
let mut rl = ratelimit("posts_per_minute = 1\n");
assert_eq!(rl.filter_note(&msg("e1", "1.2.3.4")).action, Action::Accept);
// Without `ban_after`, persistent hammering only ever rate-limits.
@@ -204,12 +176,7 @@ mod tests {
#[test]
fn whitelisted_ip_is_never_banned() {
let mut rl = RateLimit {
posts_per_minute: 1,
ban_after: Some(2),
whitelist: Some(vec!["1.2.3.4".to_string()]),
..Default::default()
};
let mut rl = ratelimit("posts_per_minute = 1\nban_after = 2\nwhitelist = [\"1.2.3.4\"]\n");
for i in 0..10 {
let r = rl.filter_note(&msg(&format!("e{i}"), "1.2.3.4"));
@@ -218,29 +185,22 @@ mod tests {
}
#[test]
fn expired_ban_clears_and_allows_again() {
let mut rl = RateLimit {
posts_per_minute: 2,
ban_after: Some(2),
..Default::default()
};
fn a_successful_post_resets_the_streak() {
let mut rl = ratelimit("posts_per_minute = 2\nban_after = 2\n");
// Seed + drain the bucket, then two back-to-back rejections trip the ban.
// Seed + drain, then one rate-limit rejection (strike 1).
assert_eq!(rl.filter_note(&msg("e1", "5.6.7.8")).action, Action::Accept);
assert_eq!(rl.filter_note(&msg("e2", "5.6.7.8")).action, Action::Accept);
assert_eq!(rl.filter_note(&msg("e3", "5.6.7.8")).action, Action::Reject);
assert!(rl
.filter_note(&msg("e4", "5.6.7.8"))
.msg
.unwrap()
.contains("banned"));
// Force the ban into the past and let the bucket refill: the next post
// should clear the ban, reset strikes, and be accepted.
let entry = rl.sources.get_mut("5.6.7.8").unwrap();
entry.banned_until = Some(Instant::now() - Duration::from_secs(1));
entry.last_post = Instant::now() - Duration::from_secs(120);
assert_eq!(rl.filter_note(&msg("e5", "5.6.7.8")).action, Action::Accept);
assert_eq!(rl.sources.get("5.6.7.8").unwrap().strikes, 0);
// Refill the bucket so the next post is accepted, resetting the streak.
rl.sources.get_mut("5.6.7.8").unwrap().last_post = Instant::now() - Duration::from_secs(120);
assert_eq!(rl.filter_note(&msg("e4", "5.6.7.8")).action, Action::Accept);
// A fresh streak now needs the full `ban_after` again — the next lone
// rejection must NOT ban.
let r = rl.filter_note(&msg("e5", "5.6.7.8"));
assert_eq!(r.action, Action::Reject);
assert!(!r.msg.unwrap().contains("banned"));
}
}