Skip to content

Commit 6a92f0b

Browse files
npub17jjz49l9jjmhhk7cac63j8yt9z555n9cw8vk7v5jz4vzw4ppld5qgj57ccTyler Longwell
andcommitted
feat(auth): community-scope RateLimiter pubkey quotas
RateLimiter::check_and_increment now takes &TenantContext, and rate_limit_key emits buzz:{community}:ratelimit:{pubkey_hex}:{suffix}. Same pubkey active in two communities consumes two independent quotas, matching the S1 cross-community isolation fence in the buzz-relay rewrite spec. check_ip_connection stays operator-global by design. The IP fence runs at connection acceptance, before host->community resolution has completed (or, on resolve failure, instead of it). Threading &TenantContext through it would invert the order of operations. Per- (community, IP) caps, if ever needed as a tenant-fairness signal, belong in an additive LimitType keyed on (community, ip) — not in this trait. RedisRateLimiter in buzz-pubsub follows the new trait signature. AlwaysAllowRateLimiter test impl mirrors it. Two new tests pin the behavior: the key includes the community prefix, and same-pubkey-two- communities yields two distinct Redis keys. Local cargo test -p buzz-auth: 36 passed. Local cargo test -p buzz-pubsub: 3 passed, 6 Redis-required ignored. Workspace-wide check not run locally (sqlx 0.9.0 requires rustc 1.94, local toolchain is 1.89 — same constraint Max hit on the pubsub lane); relying on CI for the full integration compile. Co-authored-by: Tyler Longwell <[email protected]> Signed-off-by: Tyler Longwell <[email protected]>
1 parent e349d76 commit 6a92f0b

2 files changed

Lines changed: 83 additions & 15 deletions

File tree

‎crates/buzz-auth/src/rate_limit.rs‎

Lines changed: 75 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
99
use std::net::IpAddr;
1010

11+
use buzz_core::TenantContext;
1112
use nostr::PublicKey;
1213
use serde::{Deserialize, Serialize};
1314

@@ -147,22 +148,43 @@ impl Default for RateLimitConfig {
147148
/// The Redis-backed production implementation lives in `buzz-relay` / `buzz-pubsub`.
148149
/// A no-op `AlwaysAllowRateLimiter` is provided for unit tests.
149150
///
151+
/// ## Tenant scoping
152+
///
153+
/// Pubkey-keyed limits ([`check_and_increment`]) take `&TenantContext` and the Redis
154+
/// key is community-prefixed (`buzz:{community}:ratelimit:{pubkey}:{suffix}`). The
155+
/// same pubkey active in two communities consumes two independent quotas — that is
156+
/// the correct behavior under multi-tenant isolation (S1 cross-community fence).
157+
///
158+
/// IP-keyed limits ([`check_ip_connection`]) are **operator-global** by design. They
159+
/// gate connection acceptance at the network edge, before host→community resolution
160+
/// has completed (or, on resolve failure, instead of it). Threading `&TenantContext`
161+
/// through the connection-rate fence would invert the order of operations. If
162+
/// per-(community, IP) caps are ever needed as a tenant-fairness signal, that
163+
/// belongs in an additive `LimitType` keyed on `(community, ip)`, not in this trait.
164+
///
150165
/// ⚠️ The fixed-window algorithm used by the Redis implementation allows up to 2×
151166
/// burst at window boundaries. Upgrade to a sliding window or token bucket if strict
152167
/// per-second limiting is required.
153168
pub trait RateLimiter: Send + Sync {
154-
/// Increment the counter for `pubkey` + `limit_type` and return whether the
155-
/// request is within the configured `limit` for the given `window_secs`.
169+
/// Increment the per-(community, pubkey) counter for `limit_type` and return
170+
/// whether the request is within `limit` for the given `window_secs`.
171+
///
172+
/// `ctx` scopes the counter to the resolved community; the same pubkey in two
173+
/// communities is two independent quotas.
156174
fn check_and_increment(
157175
&self,
176+
ctx: &TenantContext,
158177
pubkey: &PublicKey,
159178
limit_type: LimitType,
160179
window_secs: u64,
161180
limit: u64,
162181
) -> impl std::future::Future<Output = Result<RateLimitResult, AuthError>> + Send;
163182

164183
/// Increment the per-IP connection counter and return whether the connection
165-
/// is within the configured `limit` for the given `window_secs`.
184+
/// is within `limit` for the given `window_secs`.
185+
///
186+
/// Operator-global — see trait docs. This fence runs before / outside of host
187+
/// resolution and intentionally does not take a `TenantContext`.
166188
fn check_ip_connection(
167189
&self,
168190
ip: &IpAddr,
@@ -171,16 +193,23 @@ pub trait RateLimiter: Send + Sync {
171193
) -> impl std::future::Future<Output = Result<RateLimitResult, AuthError>> + Send;
172194
}
173195

174-
/// Redis key for pubkey-based rate limit: `buzz:ratelimit:<hex>:<suffix>`
175-
pub fn rate_limit_key(pubkey: &PublicKey, limit_type: &LimitType) -> String {
196+
/// Redis key for pubkey-based rate limit:
197+
/// `buzz:{community}:ratelimit:{pubkey_hex}:{suffix}`.
198+
///
199+
/// Community-prefixed: the same pubkey in two communities maps to two distinct
200+
/// keys, so quotas don't bleed across the tenancy fence.
201+
pub fn rate_limit_key(ctx: &TenantContext, pubkey: &PublicKey, limit_type: &LimitType) -> String {
176202
format!(
177-
"buzz:ratelimit:{}:{}",
203+
"buzz:{}:ratelimit:{}:{}",
204+
ctx.community(),
178205
pubkey.to_hex(),
179206
limit_type.key_suffix()
180207
)
181208
}
182209

183-
/// Redis key for IP-based rate limit: `buzz:ratelimit:ip:<ip>:conn`
210+
/// Redis key for IP-based rate limit: `buzz:ratelimit:ip:{ip}:conn`.
211+
///
212+
/// Operator-global by design — see [`RateLimiter`] docs.
184213
pub fn ip_rate_limit_key(ip: &IpAddr) -> String {
185214
format!("buzz:ratelimit:ip:{}:conn", ip)
186215
}
@@ -193,6 +222,7 @@ pub struct AlwaysAllowRateLimiter;
193222
impl RateLimiter for AlwaysAllowRateLimiter {
194223
async fn check_and_increment(
195224
&self,
225+
_ctx: &TenantContext,
196226
_pubkey: &PublicKey,
197227
_limit_type: LimitType,
198228
window_secs: u64,
@@ -214,29 +244,63 @@ impl RateLimiter for AlwaysAllowRateLimiter {
214244
#[cfg(test)]
215245
mod tests {
216246
use super::*;
247+
use buzz_core::CommunityId;
217248
use nostr::Keys;
249+
use sha2::Digest;
218250
use std::net::Ipv4Addr;
251+
use uuid::Uuid;
252+
253+
fn fixture_ctx(host: &str) -> TenantContext {
254+
// Deterministic community id from host so test assertions can name the prefix.
255+
let bytes = sha2::Sha256::digest(host.as_bytes());
256+
let mut uuid_bytes = [0u8; 16];
257+
uuid_bytes.copy_from_slice(&bytes[..16]);
258+
let id = CommunityId::from_uuid(Uuid::from_bytes(uuid_bytes));
259+
TenantContext::resolved(id, host)
260+
}
219261

220262
#[test]
221-
fn rate_limit_key_format() {
263+
fn rate_limit_key_includes_community_prefix() {
264+
let ctx = fixture_ctx("relay-a.example");
222265
let keys = Keys::generate();
223-
let key = rate_limit_key(&keys.public_key(), &LimitType::Messages);
224-
assert!(key.starts_with("buzz:ratelimit:"));
266+
let key = rate_limit_key(&ctx, &keys.public_key(), &LimitType::Messages);
267+
let expected_prefix = format!("buzz:{}:ratelimit:", ctx.community());
268+
assert!(
269+
key.starts_with(&expected_prefix),
270+
"key {key} should start with {expected_prefix}"
271+
);
225272
assert!(key.ends_with(":msg"));
226273
}
227274

275+
#[test]
276+
fn rate_limit_key_isolates_communities_for_same_pubkey() {
277+
// The S1 cross-community isolation fence at the rate-limit key layer:
278+
// same pubkey, two communities -> two distinct Redis keys -> independent quotas.
279+
let keys = Keys::generate();
280+
let ctx_a = fixture_ctx("relay-a.example");
281+
let ctx_b = fixture_ctx("relay-b.example");
282+
let key_a = rate_limit_key(&ctx_a, &keys.public_key(), &LimitType::Messages);
283+
let key_b = rate_limit_key(&ctx_b, &keys.public_key(), &LimitType::Messages);
284+
assert_ne!(
285+
key_a, key_b,
286+
"same pubkey in two communities must not share a rate-limit key"
287+
);
288+
}
289+
228290
#[test]
229291
fn ip_rate_limit_key_format() {
292+
// IP fence stays operator-global — no community in the key.
230293
let ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
231294
assert_eq!(ip_rate_limit_key(&ip), "buzz:ratelimit:ip:192.168.1.1:conn");
232295
}
233296

234297
#[tokio::test]
235298
async fn always_allow_limiter() {
236299
let limiter = AlwaysAllowRateLimiter;
300+
let ctx = fixture_ctx("relay-a.example");
237301
let keys = Keys::generate();
238302
let result = limiter
239-
.check_and_increment(&keys.public_key(), LimitType::Messages, 60, 60)
303+
.check_and_increment(&ctx, &keys.public_key(), LimitType::Messages, 60, 60)
240304
.await
241305
.unwrap();
242306
assert!(result.allowed);

‎crates/buzz-pubsub/src/rate_limiter.rs‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use buzz_auth::{
1313
error::AuthError,
1414
rate_limit::{LimitType, RateLimitResult, RateLimiter},
1515
};
16+
use buzz_core::TenantContext;
1617
use nostr::PublicKey;
1718
use redis::Script;
1819

@@ -79,9 +80,11 @@ async fn run_rate_limit(
7980

8081
/// Redis-backed rate limiter using fixed-window counters.
8182
///
82-
/// Each key is `buzz:ratelimit:<pubkey_hex>:<suffix>` (pubkey) or
83-
/// `buzz:ratelimit:ip:<ip>:conn` (IP). The counter and its TTL are managed
84-
/// atomically via a Lua script to prevent keys from persisting without expiry.
83+
/// Pubkey keys are community-scoped via `&TenantContext`:
84+
/// `buzz:{community}:ratelimit:{pubkey_hex}:{suffix}`. IP keys remain
85+
/// operator-global: `buzz:ratelimit:ip:{ip}:conn`. The counter and its TTL are
86+
/// managed atomically via a Lua script to prevent keys from persisting without
87+
/// expiry.
8588
pub struct RedisRateLimiter {
8689
pool: deadpool_redis::Pool,
8790
}
@@ -96,12 +99,13 @@ impl RedisRateLimiter {
9699
impl RateLimiter for RedisRateLimiter {
97100
async fn check_and_increment(
98101
&self,
102+
ctx: &TenantContext,
99103
pubkey: &PublicKey,
100104
limit_type: LimitType,
101105
window_secs: u64,
102106
limit: u64,
103107
) -> Result<RateLimitResult, AuthError> {
104-
let key = buzz_auth::rate_limit::rate_limit_key(pubkey, &limit_type);
108+
let key = buzz_auth::rate_limit::rate_limit_key(ctx, pubkey, &limit_type);
105109
run_rate_limit(&self.pool, &key, window_secs, limit).await
106110
}
107111

0 commit comments

Comments
 (0)