Skip to content
Open
11 changes: 11 additions & 0 deletions crates/buzz-push-gateway/migrations/0008_relay_quotas.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
SET LOCAL lock_timeout = '5s';
SET LOCAL statement_timeout = '30s';

CREATE TABLE push_gateway_relay_quotas (
token_fingerprint BYTEA NOT NULL CHECK (length(token_fingerprint) = 32),
relay_pubkey BYTEA NOT NULL CHECK (length(relay_pubkey) = 32),
window_started_at TIMESTAMPTZ NOT NULL,
admitted BIGINT NOT NULL CHECK (admitted >= 0),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (token_fingerprint, relay_pubkey)
);
90 changes: 84 additions & 6 deletions crates/buzz-push-gateway/src/authority.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ pub enum AuthorityError {
Rejected,
#[error("installation authority is already live")]
Conflict,
#[error("delivery quota exceeded; retry after {0} seconds")]
DeliveryRateLimited(i64),
#[error("authority request rate exceeded")]
RateLimited,
#[error("authority store unavailable")]
Expand All @@ -118,8 +120,12 @@ pub struct AssertionCounter {
pub request_expires_at: i64,
pub now: i64,
pub expected_generation: Option<i64>,
pub quota_window_seconds: i64,
}

/// Four non-overlapping destination shares bound approved relay allocations.
pub const MAX_APPROVED_RELAYS: i64 = 4;

/// Every mutating method is an atomic store operation. Implementations must
/// serialize installation assertion counters and delegation generations.
#[async_trait]
Expand Down Expand Up @@ -224,6 +230,7 @@ struct MemoryState {
delivery_auth_replays: HashMap<(String, String), i64>,
delivery_request_replays: HashMap<(String, Uuid), i64>,
endpoint_quotas: HashMap<[u8; 32], (i64, i64)>,
relay_quotas: HashMap<([u8; 32], String), (i64, i64)>,
}

/// Executable reference store used by conformance tests. Production uses the
Expand Down Expand Up @@ -434,6 +441,48 @@ impl AuthorityStore for MemoryAuthorityStore {
{
return Err(AuthorityError::Rejected);
}
let fingerprint = installation.token_fingerprint;
let now = assertion.now;
let window = assertion.quota_window_seconds;
let device = match s.endpoint_quotas.get(&fingerprint) {
Some(&(start, count)) if now.saturating_sub(start) < window => (start, count),
_ => (now, 0),
};
let live: std::collections::HashSet<String> = s
.delegations
.values()
.filter(|old| {
s.installations.get(&old.installation_id).is_some_and(|i| {
i.token_fingerprint == fingerprint
&& !i.revoked
&& i.expires_at >= now
&& i.endpoint_epoch == old.endpoint_epoch
}) && !old.revoked
&& old.expires_at >= now
})
.map(|old| old.relay_pubkey.clone())
.collect();
s.relay_quotas.retain(|(fp, key), (started, _)| {
*fp != fingerprint || *started >= device.0 || live.contains(key)
});
let slots: std::collections::HashSet<String> = live
.into_iter()
.chain(
s.relay_quotas
.keys()
.filter(|(fp, _)| *fp == fingerprint)
.map(|(_, key)| key.clone()),
)
.collect();
if !slots.contains(&d.relay_pubkey) && slots.len() >= MAX_APPROVED_RELAYS as usize {
return Err(AuthorityError::DeliveryRateLimited(
device.0.saturating_add(window).saturating_sub(now).max(1),
));
}
s.endpoint_quotas.entry(fingerprint).or_insert(device);
s.relay_quotas
.entry((fingerprint, d.relay_pubkey.clone()))
.or_insert((device.0, 0));
let installation = s
.installations
.get_mut(&d.installation_id)
Expand Down Expand Up @@ -618,14 +667,40 @@ impl AuthorityStore for MemoryAuthorityStore {
{
return Err(AuthorityError::Rejected);
}
let quota = s.endpoint_quotas.entry(fingerprint).or_insert((now, 0));
if now.saturating_sub(quota.0) >= quota_window_seconds {
*quota = (now, 0);
if quota_window_seconds < 1 || quota_max_deliveries < MAX_APPROVED_RELAYS {
return Err(AuthorityError::Unavailable);
}
if quota.1 >= quota_max_deliveries {
return Err(AuthorityError::Rejected);
let relay_key = (fingerprint, relay.to_owned());
let current = |quota: Option<&(i64, i64)>| match quota {
Some(&(start, count)) if now.saturating_sub(start) < quota_window_seconds => {
(start, count)
}
_ => (now, 0),
};
let device = current(s.endpoint_quotas.get(&fingerprint));
let per_relay = match s.relay_quotas.get(&relay_key) {
Some(&(start, count)) if start == device.0 => (start, count),
_ => (device.0, 0),
};
if device.1 >= quota_max_deliveries
|| per_relay.1 >= quota_max_deliveries / MAX_APPROVED_RELAYS
{
let started = if device.1 >= quota_max_deliveries {
device.0
} else {
per_relay.0
};
return Err(AuthorityError::DeliveryRateLimited(
started
.saturating_add(quota_window_seconds)
.saturating_sub(now)
.max(1),
));
}
quota.1 += 1;
s.endpoint_quotas
.insert(fingerprint, (device.0, device.1 + 1));
s.relay_quotas
.insert(relay_key, (per_relay.0, per_relay.1 + 1));
s.delivery_auth_replays.insert(auth_key, request_expires_at);
s.delivery_request_replays
.insert(request_key, request_expires_at);
Expand Down Expand Up @@ -657,6 +732,8 @@ impl AuthorityStore for MemoryAuthorityStore {
.retain(|_, expires_at| *expires_at >= now);
s.endpoint_quotas
.retain(|_, (started_at, _)| now.saturating_sub(*started_at) < 86_400);
s.relay_quotas
.retain(|_, (started_at, _)| now.saturating_sub(*started_at) < 86_400);
Ok(())
}
}
Expand All @@ -678,6 +755,7 @@ pub(crate) async fn test_assertion(
request_expires_at: i64::MAX,
now: 0,
expected_generation,
quota_window_seconds: 60,
}
}

Expand Down
5 changes: 5 additions & 0 deletions crates/buzz-push-gateway/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,11 @@ impl Config {
bounded_positive("BUZZ_PUSH_ENDPOINT_QUOTA_WINDOW_SECONDS", 10, 86_400)?;
let endpoint_quota_max_deliveries =
bounded_positive("BUZZ_PUSH_ENDPOINT_QUOTA_MAX_DELIVERIES", 10, 10_000)?;
if endpoint_quota_max_deliveries < crate::authority::MAX_APPROVED_RELAYS {
return Err(ConfigError::Invalid(
"BUZZ_PUSH_ENDPOINT_QUOTA_MAX_DELIVERIES",
));
}
let application = parse_application(e)?;
let bind_addr = e
.get("BUZZ_PUSH_BIND_ADDR")
Expand Down
16 changes: 15 additions & 1 deletion crates/buzz-push-gateway/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,12 +126,24 @@ fn authority_error(e: AuthorityError) -> Response {
AuthorityError::StaleGeneration(current_generation) => (StatusCode::CONFLICT, Json(serde_json::json!({"error":"stale_generation", "current_generation": current_generation}))).into_response(),
AuthorityError::Rejected => error(StatusCode::NOT_FOUND, "not_authorized"),
AuthorityError::Conflict => installation_conflict(),
AuthorityError::RateLimited => error(StatusCode::TOO_MANY_REQUESTS, "rate_limited"),
AuthorityError::RateLimited => throttled(60),
AuthorityError::DeliveryRateLimited(seconds) => throttled(seconds),
AuthorityError::Unavailable => {
error(StatusCode::SERVICE_UNAVAILABLE, "temporarily_unavailable")
}
}
}
pub(crate) fn throttled(seconds: i64) -> Response {
let seconds = seconds.max(1);
(
StatusCode::TOO_MANY_REQUESTS,
[(axum::http::header::RETRY_AFTER, seconds.to_string())],
Json(DeliveryResponse::Retry {
retry_after_seconds: Some(seconds),
}),
)
.into_response()
}
fn installation_conflict() -> Response {
error(StatusCode::CONFLICT, "installation_conflict")
}
Expand Down Expand Up @@ -359,6 +371,7 @@ async fn verify_installation_assertion<T: serde::Serialize>(
previous: installation.assertion_counter,
next: verified.counter,
expected_generation: request.expected_generation,
quota_window_seconds: s.endpoint_quota_window_seconds,
now,
})
}
Expand Down Expand Up @@ -711,6 +724,7 @@ async fn deliver(
crate::metrics::record_delivery_error("invalid_grant");
return error(StatusCode::NOT_FOUND, "invalid_grant");
}
Err(AuthorityError::DeliveryRateLimited(seconds)) => return throttled(seconds),
Err(AuthorityError::RateLimited) => {
crate::metrics::record_admission(crate::metrics::Admission::Rejected);
crate::metrics::record_delivery_error("rate_limited");
Expand Down
18 changes: 18 additions & 0 deletions crates/buzz-push-gateway/src/http_protocol_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,24 @@ async fn management_binds_parameters_versions_expiry_and_commits_counter_with_pe
.status(),
StatusCode::OK
);
let body = delivery_body(token, Uuid::new_v4());
assert_eq!(
delivery(&app, body.clone(), &auth(&keys, &body))
.await
.status(),
StatusCode::OK
);
let body = delivery_body(token, Uuid::new_v4());
let signed = auth(&keys, &body);
let limited = delivery(&app, body.clone(), &signed).await;
assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS);
assert_eq!(limited.headers()["retry-after"], "60");
NOW.fetch_add(60, Ordering::SeqCst);
assert_eq!(
delivery(&app, body, &signed).await.status(),
StatusCode::OK,
"quota rejection consumes neither request ID nor auth event ID"
);
let (status, conflict) = delegate_request(&app, id, &relay, 0, 2, 2).await;
assert_eq!(status, StatusCode::CONFLICT);
assert_eq!(conflict["current_generation"], 1);
Expand Down
Loading
Loading