diff --git a/README.md b/README.md index ab561e1..644ee79 100644 --- a/README.md +++ b/README.md @@ -296,6 +296,10 @@ max = 5000 # in the batch are withheld. [readpolicy.filters.read_bandwidth] 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 # hex (optional). A whitelisted connection is never metered and takes the # passthrough fast path. @@ -351,19 +355,24 @@ processes, making the effective per-IP budget up to `numThreads × read_bandwidth.bytes_per_minute`. To enforce **one** authoritative budget per IP while keeping every read thread, -set `read_bandwidth.shared_state_path` to a path on `tmpfs` -(e.g. `/dev/shm/noteguard-read-bandwidth`): every `noteguard read` process on the -host then `mmap`s the same file, a fixed open-addressing IP→bucket table guarded -by per-slot spinlocks, so an IP's budget is a single shared bucket regardless of -which process serves a given connection. 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 +every `noteguard read` process on the host `mmap`s the same `tmpfs` file — a +fixed open-addressing IP→bucket table guarded by per-slot spinlocks — so an IP's +budget is a single shared bucket regardless of which process serves a given +connection. **This is the default:** with `read_bandwidth.shared_state_path` +unset, every process attaches to `/dev/shm/noteguard-read-bandwidth` +automatically, so per-IP enforcement holds across processes out of the box — you +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 -resets on reboot. Leaving `shared_state_path` unset keeps the old per-process -behavior (accurate only within a single process). Only `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.) +resets on reboot. Set `shared_state_path` to another `tmpfs` path to override the +location, or to `""` to **opt out** to the old per-process behavior (accurate +only within a single process, so the effective per-IP limit becomes +`numThreads × bytes_per_minute` — for hosts that can't use `tmpfs`). Only +`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) diff --git a/noteguard.toml b/noteguard.toml index 3b90c3e..d464267 100644 --- a/noteguard.toml +++ b/noteguard.toml @@ -95,12 +95,16 @@ max = 5000 [readpolicy.filters.read_bandwidth] bytes_per_minute = 5000000 # 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 -# + reqMonitor` times `bytes_per_minute`. Point every process at one tmpfs file -# and the per-IP budget becomes a single authoritative bucket across all of them -# (see the README). Unset => per-process buckets (accurate only within one -# process). Fails open (delivers) if the file can't be mapped or the table fills. -# shared_state_path = "/dev/shm/noteguard-read-bandwidth" +# so per-process buckets would make the effective per-IP limit up to +# `relay.numThreads.reqWorker + reqMonitor` times `bytes_per_minute`. To enforce +# ONE authoritative per-IP bucket, every process mmaps a single tmpfs file (see +# the README). This is now the DEFAULT: leave `shared_state_path` unset and each +# process attaches to /dev/shm/noteguard-read-bandwidth automatically — no config +# 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 # 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 diff --git a/src/readfilters/bandwidth.rs b/src/readfilters/bandwidth.rs index 5292823..898ae71 100644 --- a/src/readfilters/bandwidth.rs +++ b/src/readfilters/bandwidth.rs @@ -13,6 +13,15 @@ use std::collections::HashMap; /// always affords it and only a drained IP trips the reject. 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. /// ~65k slots × ~80 bytes ≈ 5 MB on tmpfs. fn default_max_ips() -> u32 { @@ -26,12 +35,12 @@ enum Store { /// do I/O). #[default] Uninit, - /// A shared path was configured but its `mmap`/init failed: this process - /// meters nothing and fails open (delivers). Distinct from [`Store::Anon`], - /// which is the intentional no-path mode. + /// The shared file's `mmap`/init failed: this process meters nothing and + /// fails open (delivers). Distinct from a working anonymous map, which is + /// the intentional per-process opt-out (`shared_state_path = ""`). Failed, - /// A working per-IP byte-bucket table (shared file, or a private anonymous - /// map when no path was configured). + /// A working per-IP byte-bucket table: the shared file (the default), or a + /// private anonymous map when the operator opted out with an empty path. Map(SharedByteBuckets), } @@ -49,8 +58,12 @@ enum Store { /// To enforce ONE authoritative budget per IP while keeping N processes, the /// buckets live in a shared `mmap`'d table /// ([`SharedByteBuckets`](crate::readfilters::shm)) named by `shared_state_path`. -/// With no path configured the map is per-process (the old behavior); a -/// configured path that fails to attach fails open (delivers, unmetered). +/// This shared-memory enforcement is the DEFAULT: with `shared_state_path` +/// 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 /// 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 /// `noteguard read` process on the host (all must agree on the path and - /// `max_ips`). `None` (unset, or empty) => a private per-process map — - /// 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 - /// ONE budget per IP across all read processes. A configured but unattachable - /// path fails open (delivers, unmetered). + /// `max_ips`). Three cases: + /// + /// - **Unset (`None`)** — the DEFAULT: attach to [`DEFAULT_SHARED_STATE_PATH`] + /// so the per-IP budget is enforced across every read process out of the + /// 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)] pub shared_state_path: Option, @@ -126,37 +149,46 @@ impl ReadBandwidth { }) } - /// Build the byte-bucket store on first use (construction can't do I/O). A - /// configured `shared_state_path` opens a shared file; unset (or empty) uses - /// a private per-process map; a configured path that fails to attach records + /// Build the byte-bucket store on first use (construction can't do I/O). + /// `shared_state_path` unset defaults to the shared file at + /// [`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). fn ensure_store(&mut self) { if !matches!(self.store, Store::Uninit) { 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() { - Some("") | None => None, + None => Some(DEFAULT_SHARED_STATE_PATH.to_string()), + Some("") => None, Some(p) => Some(p.to_string()), }; self.store = match path { None => match SharedByteBuckets::anonymous(self.max_ips) { Ok(m) => { 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", m.slot_count() ); Store::Map(m) } 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 } }, Some(path) => match SharedByteBuckets::open(&path, self.max_ips) { Ok(m) => { log::info!( - "read_bandwidth: shared byte buckets at {} ({} slots)", + "read_bandwidth: shared byte buckets at {} ({} slots) — \ + cross-process enforcement is ON", path, m.slot_count() ); diff --git a/src/readpolicy.rs b/src/readpolicy.rs index a1c723b..dac4b71 100644 --- a/src/readpolicy.rs +++ b/src/readpolicy.rs @@ -422,6 +422,12 @@ mod tests { /// Build an engine from a `[readpolicy]`-inner TOML fragment (pipeline + /// 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 { let config: ReadPolicyConfig = toml::from_str(config).expect("test config parses"); let mut engine = ReadPolicy::new(); @@ -550,6 +556,7 @@ mod tests { pipeline = ["read_bandwidth"] [filters.read_bandwidth] bytes_per_minute = 1000 + shared_state_path = "" "#, ); let open = engine @@ -569,6 +576,7 @@ mod tests { pipeline = ["read_bandwidth"] [filters.read_bandwidth] bytes_per_minute = {} + shared_state_path = "" "#, size * 2 + 1 )); @@ -590,6 +598,7 @@ mod tests { pipeline = ["read_bandwidth"] [filters.read_bandwidth] bytes_per_minute = {} + shared_state_path = "" "#, size + 1 )); @@ -619,6 +628,7 @@ mod tests { [filters.read_bandwidth] bytes_per_minute = {} whitelist = ["5.5.5.5"] + shared_state_path = "" "#, size )); @@ -647,6 +657,7 @@ mod tests { pipeline = ["read_bandwidth"] [filters.read_bandwidth] bytes_per_minute = {} + shared_state_path = "" "#, size + 1 )); @@ -786,6 +797,7 @@ mod tests { max = 5 [filters.read_bandwidth] bytes_per_minute = {} + shared_state_path = "" "#, size * 2 + 1 ));