readpolicy: default read_bandwidth to shared-memory enforcement

The read_bandwidth per-IP byte throttle is only authoritative when every
`noteguard read` process shares one bucket table: strfry runs one process per
read-serving thread, so an IP's reconnects fan across up to numThreads
processes and a per-process bucket enforces bytes_per_minute × N. That shared
table was opt-in via shared_state_path — so the safe, working behavior was
opt-in and the broken-for-enforcement per-process behavior was the default. We
got bitten by this in prod: the filter was enabled but shared_state_path was
unset, so enforcement silently didn't hold across processes.

Flip the default. `shared_state_path` unset now attaches to the standard tmpfs
path (DEFAULT_SHARED_STATE_PATH = /dev/shm/noteguard-read-bandwidth), so
cross-process enforcement is ON out of the box. An explicit empty string
(shared_state_path = "") is the per-process opt-out for hosts that can't use
tmpfs; a non-empty path overrides the location. Fail-open on an unattachable
file is unchanged.

Keep the tests hermetic: every read_bandwidth test config now sets
shared_state_path = "" so `cargo test` uses a fresh in-process map per test
and never creates or depends on the real /dev/shm file.

Also document the new default-on semantics in noteguard.toml and the README.

Changelog-Changed: read_bandwidth now enforces its per-IP budget across read processes by default (shared /dev/shm bucket); set shared_state_path = "" to opt out to per-process buckets
Headway: headway:noteguard/arrive-female-crane
Agentium: agentium:setup-illegal-peanut
This commit is contained in:
William Casarin
2026-09-13 00:26:09 -07:00
parent 9f656006d8
commit 85f8e35e00
4 changed files with 94 additions and 37 deletions
+21 -12
View File
@@ -296,6 +296,10 @@ max = 5000
# in the batch are withheld. # in the batch are withheld.
[readpolicy.filters.read_bandwidth] [readpolicy.filters.read_bandwidth]
bytes_per_minute = 5000000 bytes_per_minute = 5000000
# cross-process enforcement is ON by default: leave shared_state_path unset and
# every read process attaches to /dev/shm/noteguard-read-bandwidth. Set it to ""
# to opt out to per-process buckets, or to another tmpfs path to override.
# shared_state_path = "/dev/shm/noteguard-read-bandwidth"
# exempt entries: an entry matches a connection's client IP OR its authed pubkey # exempt entries: an entry matches a connection's client IP OR its authed pubkey
# hex (optional). A whitelisted connection is never metered and takes the # hex (optional). A whitelisted connection is never metered and takes the
# passthrough fast path. # passthrough fast path.
@@ -351,19 +355,24 @@ processes, making the effective per-IP budget up to `numThreads ×
read_bandwidth.bytes_per_minute`. read_bandwidth.bytes_per_minute`.
To enforce **one** authoritative budget per IP while keeping every read thread, To enforce **one** authoritative budget per IP while keeping every read thread,
set `read_bandwidth.shared_state_path` to a path on `tmpfs` every `noteguard read` process on the host `mmap`s the same `tmpfs` file — a
(e.g. `/dev/shm/noteguard-read-bandwidth`): every `noteguard read` process on the fixed open-addressing IP→bucket table guarded by per-slot spinlocks — so an IP's
host then `mmap`s the same file, a fixed open-addressing IP→bucket table guarded budget is a single shared bucket regardless of which process serves a given
by per-slot spinlocks, so an IP's budget is a single shared bucket regardless of connection. **This is the default:** with `read_bandwidth.shared_state_path`
which process serves a given connection. The table sizes to `max_ips` distinct unset, every process attaches to `/dev/shm/noteguard-read-bandwidth`
IPs (default 65536, no eviction — buckets must survive a reconnect) and *fails automatically, so per-IP enforcement holds across processes out of the box — you
open* (delivers, unmetered) if it fills, if a slot lock can't be taken, or if the don't need to configure anything. The table sizes to `max_ips` distinct IPs
(default 65536, no eviction — buckets must survive a reconnect) and *fails open*
(delivers, unmetered) if it fills, if a slot lock can't be taken, or if the
`mmap` can't be created. It lives on `tmpfs`, so it survives strfry restarts and `mmap` can't be created. It lives on `tmpfs`, so it survives strfry restarts and
resets on reboot. Leaving `shared_state_path` unset keeps the old per-process resets on reboot. Set `shared_state_path` to another `tmpfs` path to override the
behavior (accurate only within a single process). Only `read_bandwidth` needs location, or to `""` to **opt out** to the old per-process behavior (accurate
this; `max_events_per_conn` is keyed by `connId`, which is already pinned to one only within a single process, so the effective per-IP limit becomes
process, so its counter is authoritative as-is. (The write-side `ratelimit` `numThreads × bytes_per_minute` — for hosts that can't use `tmpfs`). Only
filter has the same per-process scoping and is unaffected by this key.) `read_bandwidth` needs this; `max_events_per_conn` is keyed by `connId`, which is
already pinned to one process, so its counter is authoritative as-is. (The
write-side `ratelimit` filter has the same per-process scoping and is unaffected
by this key.)
### NScript read filter (experimental) ### NScript read filter (experimental)
+10 -6
View File
@@ -95,12 +95,16 @@ max = 5000
[readpolicy.filters.read_bandwidth] [readpolicy.filters.read_bandwidth]
bytes_per_minute = 5000000 bytes_per_minute = 5000000
# Shared-memory buckets: strfry runs one plugin process per read-serving thread, # Shared-memory buckets: strfry runs one plugin process per read-serving thread,
# so without this the effective per-IP limit is up to `relay.numThreads.reqWorker # so per-process buckets would make the effective per-IP limit up to
# + reqMonitor` times `bytes_per_minute`. Point every process at one tmpfs file # `relay.numThreads.reqWorker + reqMonitor` times `bytes_per_minute`. To enforce
# and the per-IP budget becomes a single authoritative bucket across all of them # ONE authoritative per-IP bucket, every process mmaps a single tmpfs file (see
# (see the README). Unset => per-process buckets (accurate only within one # the README). This is now the DEFAULT: leave `shared_state_path` unset and each
# process). Fails open (delivers) if the file can't be mapped or the table fills. # process attaches to /dev/shm/noteguard-read-bandwidth automatically — no config
# shared_state_path = "/dev/shm/noteguard-read-bandwidth" # needed for normal use. Fails open (delivers) if the file can't be mapped or the
# table fills.
# shared_state_path = "/dev/shm/noteguard-read-bandwidth" # the default path; set to override
# shared_state_path = "" # OPT OUT: per-process buckets — DISABLES cross-process
# # enforcement (for hosts that can't use tmpfs)
# max_ips = 65536 # distinct IPs the shared table holds before it fails open # max_ips = 65536 # distinct IPs the shared table holds before it fails open
# Exempt entries; each matches a connection's client IP OR its authed pubkey # Exempt entries; each matches a connection's client IP OR its authed pubkey
# hex. A whitelisted connection is never metered, so this filter asks for no # hex. A whitelisted connection is never metered, so this filter asks for no
+51 -19
View File
@@ -13,6 +13,15 @@ use std::collections::HashMap;
/// always affords it and only a drained IP trips the reject. /// always affords it and only a drained IP trips the reject.
const NOMINAL_EVENT_SIZE: u64 = 512; const NOMINAL_EVENT_SIZE: u64 = 512;
/// The shared-memory path used when `shared_state_path` is left unset — the
/// default that gives cross-process enforcement out of the box. A conventional
/// `tmpfs` location so every `noteguard read` process on the host attaches to
/// ONE authoritative per-IP table without the operator having to configure
/// anything. Set the field to `""` to opt back out to a private per-process map.
/// (Same path as [`shm::DEFAULT_PATH`](crate::readfilters::shm::DEFAULT_PATH),
/// which the `dump-buckets` operator tool falls back to.)
const DEFAULT_SHARED_STATE_PATH: &str = crate::readfilters::shm::DEFAULT_PATH;
/// Default table capacity: distinct IPs before the table fills and fails open. /// Default table capacity: distinct IPs before the table fills and fails open.
/// ~65k slots × ~80 bytes ≈ 5 MB on tmpfs. /// ~65k slots × ~80 bytes ≈ 5 MB on tmpfs.
fn default_max_ips() -> u32 { fn default_max_ips() -> u32 {
@@ -26,12 +35,12 @@ enum Store {
/// do I/O). /// do I/O).
#[default] #[default]
Uninit, Uninit,
/// A shared path was configured but its `mmap`/init failed: this process /// The shared file's `mmap`/init failed: this process meters nothing and
/// meters nothing and fails open (delivers). Distinct from [`Store::Anon`], /// fails open (delivers). Distinct from a working anonymous map, which is
/// which is the intentional no-path mode. /// the intentional per-process opt-out (`shared_state_path = ""`).
Failed, Failed,
/// A working per-IP byte-bucket table (shared file, or a private anonymous /// A working per-IP byte-bucket table: the shared file (the default), or a
/// map when no path was configured). /// private anonymous map when the operator opted out with an empty path.
Map(SharedByteBuckets), Map(SharedByteBuckets),
} }
@@ -49,8 +58,12 @@ enum Store {
/// To enforce ONE authoritative budget per IP while keeping N processes, the /// To enforce ONE authoritative budget per IP while keeping N processes, the
/// buckets live in a shared `mmap`'d table /// buckets live in a shared `mmap`'d table
/// ([`SharedByteBuckets`](crate::readfilters::shm)) named by `shared_state_path`. /// ([`SharedByteBuckets`](crate::readfilters::shm)) named by `shared_state_path`.
/// With no path configured the map is per-process (the old behavior); a /// This shared-memory enforcement is the DEFAULT: with `shared_state_path`
/// configured path that fails to attach fails open (delivers, unmetered). /// unset every process attaches to [`DEFAULT_SHARED_STATE_PATH`], so the per-IP
/// budget is authoritative out of the box. Setting it to `""` opts back out to
/// a private per-process map (the old behavior — accurate only within one
/// process). A configured path that fails to attach fails open (delivers,
/// unmetered).
/// ///
/// Once an IP's bucket can't cover the next event, the rest of the batch is /// Once an IP's bucket can't cover the next event, the rest of the batch is
/// withheld ([`EventVerdict::Stop`]). A whitelisted connection is exempt /// withheld ([`EventVerdict::Stop`]). A whitelisted connection is exempt
@@ -68,11 +81,21 @@ pub struct ReadBandwidth {
/// Path to the shared-memory file holding the per-IP buckets, shared by every /// Path to the shared-memory file holding the per-IP buckets, shared by every
/// `noteguard read` process on the host (all must agree on the path and /// `noteguard read` process on the host (all must agree on the path and
/// `max_ips`). `None` (unset, or empty) => a private per-process map — /// `max_ips`). Three cases:
/// accurate only within one process, i.e. the pre-shared-memory behavior. Set ///
/// it to a `tmpfs` path such as `/dev/shm/noteguard-read-bandwidth` to enforce /// - **Unset (`None`)** — the DEFAULT: attach to [`DEFAULT_SHARED_STATE_PATH`]
/// ONE budget per IP across all read processes. A configured but unattachable /// so the per-IP budget is enforced across every read process out of the
/// path fails open (delivers, unmetered). /// box. This is what you want; you shouldn't need to set it.
/// - **Empty (`""`)** — opt out to a private per-process map, accurate only
/// within one process (the pre-shared-memory behavior). This DISABLES
/// cross-process enforcement, so the effective per-IP limit becomes
/// `bytes_per_minute × numThreads`. For hosts that can't use `tmpfs`, or
/// tests that want a fresh isolated bucket.
/// - **A non-empty path** — attach to that file instead of the default (e.g.
/// a different `tmpfs` location).
///
/// A configured (or defaulted) path that fails to attach fails open
/// (delivers, unmetered).
#[serde(default)] #[serde(default)]
pub shared_state_path: Option<String>, pub shared_state_path: Option<String>,
@@ -126,37 +149,46 @@ impl ReadBandwidth {
}) })
} }
/// Build the byte-bucket store on first use (construction can't do I/O). A /// Build the byte-bucket store on first use (construction can't do I/O).
/// configured `shared_state_path` opens a shared file; unset (or empty) uses /// `shared_state_path` unset defaults to the shared file at
/// a private per-process map; a configured path that fails to attach records /// [`DEFAULT_SHARED_STATE_PATH`] (cross-process enforcement, the default); an
/// explicit empty string opts out to a private per-process map; an explicit
/// non-empty path opens that file. A shared file that fails to attach records
/// [`Store::Failed`] so the filter fails open (delivers, unmetered). /// [`Store::Failed`] so the filter fails open (delivers, unmetered).
fn ensure_store(&mut self) { fn ensure_store(&mut self) {
if !matches!(self.store, Store::Uninit) { if !matches!(self.store, Store::Uninit) {
return; return;
} }
// Unset => the default shared path (enforce across processes). An explicit
// "" is the opt-out to a private per-process map. Any other string is that
// path verbatim.
let path = match self.shared_state_path.as_deref() { let path = match self.shared_state_path.as_deref() {
Some("") | None => None, None => Some(DEFAULT_SHARED_STATE_PATH.to_string()),
Some("") => None,
Some(p) => Some(p.to_string()), Some(p) => Some(p.to_string()),
}; };
self.store = match path { self.store = match path {
None => match SharedByteBuckets::anonymous(self.max_ips) { None => match SharedByteBuckets::anonymous(self.max_ips) {
Ok(m) => { Ok(m) => {
log::info!( log::info!(
"read_bandwidth: no shared_state_path; per-process byte buckets \ "read_bandwidth: shared_state_path=\"\"; per-process byte buckets \
({} slots) — cross-process enforcement is OFF", ({} slots) — cross-process enforcement is OFF",
m.slot_count() m.slot_count()
); );
Store::Map(m) Store::Map(m)
} }
Err(e) => { Err(e) => {
log::error!("read_bandwidth: could not allocate byte buckets ({e}); failing open"); log::error!(
"read_bandwidth: could not allocate byte buckets ({e}); failing open"
);
Store::Failed Store::Failed
} }
}, },
Some(path) => match SharedByteBuckets::open(&path, self.max_ips) { Some(path) => match SharedByteBuckets::open(&path, self.max_ips) {
Ok(m) => { Ok(m) => {
log::info!( log::info!(
"read_bandwidth: shared byte buckets at {} ({} slots)", "read_bandwidth: shared byte buckets at {} ({} slots) — \
cross-process enforcement is ON",
path, path,
m.slot_count() m.slot_count()
); );
+12
View File
@@ -422,6 +422,12 @@ mod tests {
/// Build an engine from a `[readpolicy]`-inner TOML fragment (pipeline + /// Build an engine from a `[readpolicy]`-inner TOML fragment (pipeline +
/// filter tables), exercising the real registry + config path. /// filter tables), exercising the real registry + config path.
///
/// NB: every `read_bandwidth` fragment below sets `shared_state_path = ""`
/// (the per-process opt-out). Unset, the filter now DEFAULTS to the shared
/// `/dev/shm` file, so tests would share (and pollute) one real host path and
/// cross-contaminate each other's buckets — `""` gives each test a fresh,
/// isolated, in-process map.
fn engine(config: &str) -> ReadPolicy { fn engine(config: &str) -> ReadPolicy {
let config: ReadPolicyConfig = toml::from_str(config).expect("test config parses"); let config: ReadPolicyConfig = toml::from_str(config).expect("test config parses");
let mut engine = ReadPolicy::new(); let mut engine = ReadPolicy::new();
@@ -550,6 +556,7 @@ mod tests {
pipeline = ["read_bandwidth"] pipeline = ["read_bandwidth"]
[filters.read_bandwidth] [filters.read_bandwidth]
bytes_per_minute = 1000 bytes_per_minute = 1000
shared_state_path = ""
"#, "#,
); );
let open = engine let open = engine
@@ -569,6 +576,7 @@ mod tests {
pipeline = ["read_bandwidth"] pipeline = ["read_bandwidth"]
[filters.read_bandwidth] [filters.read_bandwidth]
bytes_per_minute = {} bytes_per_minute = {}
shared_state_path = ""
"#, "#,
size * 2 + 1 size * 2 + 1
)); ));
@@ -590,6 +598,7 @@ mod tests {
pipeline = ["read_bandwidth"] pipeline = ["read_bandwidth"]
[filters.read_bandwidth] [filters.read_bandwidth]
bytes_per_minute = {} bytes_per_minute = {}
shared_state_path = ""
"#, "#,
size + 1 size + 1
)); ));
@@ -619,6 +628,7 @@ mod tests {
[filters.read_bandwidth] [filters.read_bandwidth]
bytes_per_minute = {} bytes_per_minute = {}
whitelist = ["5.5.5.5"] whitelist = ["5.5.5.5"]
shared_state_path = ""
"#, "#,
size size
)); ));
@@ -647,6 +657,7 @@ mod tests {
pipeline = ["read_bandwidth"] pipeline = ["read_bandwidth"]
[filters.read_bandwidth] [filters.read_bandwidth]
bytes_per_minute = {} bytes_per_minute = {}
shared_state_path = ""
"#, "#,
size + 1 size + 1
)); ));
@@ -786,6 +797,7 @@ mod tests {
max = 5 max = 5
[filters.read_bandwidth] [filters.read_bandwidth]
bytes_per_minute = {} bytes_per_minute = {}
shared_state_path = ""
"#, "#,
size * 2 + 1 size * 2 + 1
)); ));