mirror of
https://github.com/block/buzz.git
synced 2026-11-26 19:21:50 +00:00
fix(push-gateway): answer 429, not 404, when the delivery quota is exhausted (#9803)
When an endpoint's delivery quota is exhausted, both authority stores
returned `AuthorityError::Rejected`, so `/v1/deliveries` answered `404
invalid_grant`. NIP-PL already specifies `429 {"error":"rate_limited"}`
for this case.
The 404 matters because the relay treats a 404 on a retry attempt as a
terminal replay and completes the wake, so a throttled wake was silently
dropped. On a first attempt it failed the wake. A 429 takes the relay's
existing retry-with-backoff path instead.
### Change
- Memory and Postgres stores return `RateLimited` on quota exhaustion.
`http.rs` already maps that to `429 rate_limited`.
- The rate-limited attempt still charges no quota and consumes no
auth-event or request-id fence, so the relay's retry with the same
request id is admitted once the window reopens.
- No doc change: NIP-PL and the deployment doc already describe 429.
### Validation
- Memory store: an exhausted quota returns `RateLimited`, leaves replay
rows and the quota counter unchanged, and the same auth event and
request id are admitted after the window.
- Postgres (ignored test, run locally against a temporary database): the
quota-ceiling race test now also asserts the loser is `RateLimited`.
- HTTP: the eleventh delivery under a quota of ten answers `429
{"error":"rate_limited"}` and reaches no transport.
- With the two store lines reverted, all three tests fail.
### Regressions
None expected. Only the quota-exhaustion result changes; grant,
authority and replay failures still collapse to `404 invalid_grant`.
---------
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
This commit is contained in:
@@ -235,7 +235,8 @@ pub trait AuthorityStore: Send + Sync {
|
||||
/// id as finished (later replays are `Rejected`), retryable outcomes
|
||||
/// release it. The one-use auth event admitted by `authorize_delivery` is
|
||||
/// always retained. If the gateway dies before finishing, the id stays in
|
||||
/// flight until its request expires, so the relay keeps retrying until then.
|
||||
/// flight until its request expires, so the relay keeps retrying until its
|
||||
/// attempt limit or the request expiry, whichever comes first.
|
||||
async fn finish_delivery(
|
||||
&self,
|
||||
permit: DeliveryPermit,
|
||||
@@ -619,7 +620,7 @@ impl AuthorityStore for MemoryAuthorityStore {
|
||||
*quota = (now, 0);
|
||||
}
|
||||
if quota.1 >= quota_max_deliveries {
|
||||
return Err(AuthorityError::Rejected);
|
||||
return Err(AuthorityError::RateLimited);
|
||||
}
|
||||
quota.1 += 1;
|
||||
s.delivery_auth_replays.insert(auth_key, request_expires_at);
|
||||
@@ -777,6 +778,51 @@ mod tests {
|
||||
.expect("quota reopens after the rolling window");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn exhausted_delivery_quota_is_rate_limited_without_consuming_fences() {
|
||||
let store = store().await;
|
||||
let deliver = |event: String, request: Uuid, now: i64| {
|
||||
let store = &store;
|
||||
async move {
|
||||
store
|
||||
.authorize_delivery(
|
||||
Uuid::from_u128(2),
|
||||
&"11".repeat(32),
|
||||
1,
|
||||
1,
|
||||
&event,
|
||||
request,
|
||||
now + 100,
|
||||
60,
|
||||
2,
|
||||
now,
|
||||
)
|
||||
.await
|
||||
}
|
||||
};
|
||||
deliver("22".repeat(32), Uuid::new_v4(), 1_000)
|
||||
.await
|
||||
.unwrap();
|
||||
deliver("33".repeat(32), Uuid::new_v4(), 1_000)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let (event, request) = ("44".repeat(32), Uuid::new_v4());
|
||||
assert_eq!(
|
||||
deliver(event.clone(), request, 1_000).await.err(),
|
||||
Some(AuthorityError::RateLimited)
|
||||
);
|
||||
{
|
||||
let s = store.0.lock().unwrap();
|
||||
assert_eq!(s.delivery_auth_replays.len(), 2);
|
||||
assert_eq!(s.delivery_request_replays.len(), 2);
|
||||
assert_eq!(s.endpoint_quotas.values().next().unwrap().1, 2);
|
||||
}
|
||||
deliver(event, request, 1_060)
|
||||
.await
|
||||
.expect("the rate-limited attempt left its auth event and request id unused");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authenticated_delegation_renews_installation_lifetime() {
|
||||
let store = store().await;
|
||||
|
||||
@@ -251,8 +251,7 @@ const ANDROID_ENROLL_DOMAIN: &str = "buzz.push.enroll.android.v1";
|
||||
/// How long a relay should wait before retrying a request whose earlier
|
||||
/// attempt is still in flight. Long enough for a send that is minting or
|
||||
/// waiting on the push service to finish, short enough to keep wakes prompt.
|
||||
/// The relay doubles it on each attempt, so its retries land about 4, 14, 34
|
||||
/// and 74 seconds after the first attempt, not every 5 seconds.
|
||||
/// The relay backs off from this value; its schedule lives in the relay.
|
||||
const IN_FLIGHT_RETRY_AFTER_SECONDS: i64 = 5;
|
||||
|
||||
/// The Android enrollment transcript: the iOS one without `key_id`, since the
|
||||
|
||||
@@ -434,6 +434,28 @@ async fn invalid_event_id_and_signature_are_rejected() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn exhausted_endpoint_quota_answers_429_rate_limited() {
|
||||
let (app, keys, body, sends) = fixture().await;
|
||||
let mut delivery: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
let mut deliver = || {
|
||||
delivery["request_id"] = serde_json::json!(Uuid::new_v4());
|
||||
let body = serde_json::to_vec(&delivery).unwrap();
|
||||
let auth = signed_header(&keys, DIRECT_URL, "POST", &body);
|
||||
app.clone().oneshot(request(DIRECT_URL, None, auth, body))
|
||||
};
|
||||
for _ in 0..10 {
|
||||
assert_eq!(deliver().await.unwrap().status(), StatusCode::OK);
|
||||
}
|
||||
let response = deliver().await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(&bytes[..], br#"{"error":"rate_limited"}"#);
|
||||
assert_eq!(sends.load(Ordering::SeqCst), 10);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn grant_signer_and_replay_checks_remain_enforced() {
|
||||
let (app, keys, body, sends) = fixture().await;
|
||||
|
||||
@@ -513,7 +513,7 @@ impl AuthorityStore for PostgresAuthorityStore {
|
||||
let quota = sqlx::query("INSERT INTO push_gateway_endpoint_quotas(token_fingerprint,window_started_at,admitted) VALUES($1,$2,1) ON CONFLICT(token_fingerprint) DO UPDATE SET window_started_at=CASE WHEN push_gateway_endpoint_quotas.window_started_at <= $2 - make_interval(secs => $3::double precision) THEN $2 ELSE push_gateway_endpoint_quotas.window_started_at END, admitted=CASE WHEN push_gateway_endpoint_quotas.window_started_at <= $2 - make_interval(secs => $3::double precision) THEN 1 ELSE push_gateway_endpoint_quotas.admitted + 1 END, updated_at=now() WHERE push_gateway_endpoint_quotas.window_started_at <= $2 - make_interval(secs => $3::double precision) OR push_gateway_endpoint_quotas.admitted < $4")
|
||||
.bind(fingerprint).bind(at(now)?).bind(quota_window_seconds).bind(quota_max_deliveries).execute(&mut *tx).await.map_err(db)?;
|
||||
if quota.rows_affected() != 1 {
|
||||
return Err(AuthorityError::Rejected);
|
||||
return Err(AuthorityError::RateLimited);
|
||||
}
|
||||
let auth_inserted = sqlx::query("INSERT INTO push_gateway_delivery_auth_replays(relay_pubkey,auth_event_id,expires_at) VALUES($1,$2,$3) ON CONFLICT DO NOTHING")
|
||||
.bind(&relay_bytes).bind(event_bytes).bind(at(request_expires_at)?).execute(&mut *tx).await.map_err(db)?;
|
||||
@@ -1315,8 +1315,8 @@ mod postgres_tests {
|
||||
// txns before either commits) would admit BOTH and burn the ceiling; the
|
||||
// correct behavior relies on Postgres re-checking the ON CONFLICT DO UPDATE
|
||||
// predicate against the row it just locked, so the loser sees admitted=1,
|
||||
// fails `1 < 1`, updates zero rows, and rejects. Exactly one Ok, and the
|
||||
// persisted counter must never exceed the ceiling.
|
||||
// fails `1 < 1`, updates zero rows, and is rate-limited. Exactly one Ok, and
|
||||
// the persisted counter must never exceed the ceiling.
|
||||
#[tokio::test]
|
||||
#[ignore = "requires PostgreSQL"]
|
||||
async fn concurrent_admissions_never_over_admit_past_quota_ceiling() {
|
||||
@@ -1335,6 +1335,12 @@ mod postgres_tests {
|
||||
1,
|
||||
"quota ceiling of 1 admits exactly one of two concurrent attempts"
|
||||
);
|
||||
assert!(
|
||||
[&a, &b]
|
||||
.iter()
|
||||
.any(|r| r.as_ref().err() == Some(&AuthorityError::RateLimited)),
|
||||
"the quota loser is rate-limited, not rejected"
|
||||
);
|
||||
|
||||
let admitted: i64 = sqlx::query_scalar("SELECT admitted FROM push_gateway_endpoint_quotas")
|
||||
.fetch_one(&pool)
|
||||
@@ -1362,6 +1368,62 @@ mod postgres_tests {
|
||||
drop_schema(&schema).await;
|
||||
}
|
||||
|
||||
// A retry of a finished request at a full quota must still read as a
|
||||
// replay (404), not as rate limiting (429): the relay requeues 429 but
|
||||
// treats a retry's 404 as the wake already delivered. A fresh request at
|
||||
// the same full quota is rate-limited, and neither charges the quota.
|
||||
#[tokio::test]
|
||||
#[ignore = "requires PostgreSQL"]
|
||||
async fn replay_at_full_quota_is_rejected_and_fresh_request_rate_limited() {
|
||||
let (pool, schema) = full_schema(2).await;
|
||||
install_authority(&pool).await;
|
||||
let store = PostgresAuthorityStore::new(pool.clone());
|
||||
let admitted_request = Uuid::new_v4();
|
||||
let permit = admit_with_quota(&store, &"22".repeat(32), admitted_request, 1)
|
||||
.await
|
||||
.expect("first delivery fills the quota");
|
||||
store
|
||||
.finish_delivery(permit, DeliveryDisposition::Terminal)
|
||||
.await
|
||||
.expect("first delivery finishes");
|
||||
|
||||
assert_eq!(
|
||||
admit_with_quota(&store, &"33".repeat(32), admitted_request, 1)
|
||||
.await
|
||||
.err(),
|
||||
Some(AuthorityError::Rejected),
|
||||
"a retry of the finished request is a replay even at a full quota"
|
||||
);
|
||||
assert_eq!(
|
||||
admit_with_quota(&store, &"44".repeat(32), Uuid::new_v4(), 1)
|
||||
.await
|
||||
.err(),
|
||||
Some(AuthorityError::RateLimited),
|
||||
"a fresh request at a full quota is rate-limited"
|
||||
);
|
||||
|
||||
let admitted: i64 = sqlx::query_scalar("SELECT admitted FROM push_gateway_endpoint_quotas")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("read quota");
|
||||
assert_eq!(admitted, 1, "neither refused attempt charges the quota");
|
||||
let requests: i64 =
|
||||
sqlx::query_scalar("SELECT count(*) FROM push_gateway_delivery_request_replays")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("count request replays");
|
||||
assert_eq!(requests, 1, "the rate-limited request leaves no fence");
|
||||
let auth_events: i64 =
|
||||
sqlx::query_scalar("SELECT count(*) FROM push_gateway_delivery_auth_replays")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("count auth replays");
|
||||
assert_eq!(auth_events, 1, "refused attempts consume no auth fence");
|
||||
|
||||
pool.close().await;
|
||||
drop_schema(&schema).await;
|
||||
}
|
||||
|
||||
// Red-team: Retryable release is unconditional (deletes the request-id row on
|
||||
// the pool, not inside a tx). Attack the window where a losing delivery's
|
||||
// release races a fresh admission that legitimately re-took the same
|
||||
|
||||
@@ -210,7 +210,7 @@ The gateway serves Prometheus metrics at `GET /metrics` on the **private health
|
||||
| `push_gateway_reaper_failures_total` | counter | — | Retention reaper sweep failures. |
|
||||
| `push_gateway_readiness_failures_total` | counter | `cause` = `not_accepting` \| `authority` | Readiness probe failures by cause. |
|
||||
|
||||
`push_gateway_delivery_errors_total` is intentionally **narrow**: it counts only selected exit classes of the delivery handler (`/v1/deliveries` and its `/v1/deliveries/apns` alias). `class` ∈ `invalid_grant` (grant rejected at the admission seam, before a permit is issued), `rate_limited`, `temporarily_unavailable` (authority unavailable at the admission seam), `profile_mismatch`, `profile_disabled`, `token_custody` (endpoint-token open failure), `finish_failed` (detached disposition/join failure returned as 503). Request/auth/attestation/grant validation on the enrollment, delegation, rotation, and revocation handlers is **not** counted by this metric; it is a delivery-hot-path signal, not a total error rate across the API.
|
||||
`push_gateway_delivery_errors_total` is intentionally **narrow**: it counts only selected exit classes of the delivery handler (`/v1/deliveries` and its `/v1/deliveries/apns` alias). `class` ∈ `invalid_grant` (grant rejected at the admission seam, before a permit is issued), `rate_limited`, `temporarily_unavailable` (authority unavailable at the admission seam), `profile_mismatch`, `profile_disabled`, `token_custody` (endpoint-token open failure), `finish_failed` (a detached disposition/join failure, returned as 503, or a failed terminal finish, which still returns the provider's answer). Request/auth/attestation/grant validation on the enrollment, delegation, rotation, and revocation handlers is **not** counted by this metric; it is a delivery-hot-path signal, not a total error rate across the API.
|
||||
|
||||
Scraping is **opt-in** and off by default, so the default chart render is unchanged and `8081` keeps no pod ingress. For prometheus-operator, set `podMonitor.enabled=true` and `networkPolicy.monitoring.enabled=true` with `networkPolicy.monitoring.namespaceSelector` / `podSelector` naming your scraper. For Datadog Autodiscovery, leave `podMonitor.enabled=false`, supply the OpenMetrics check through `podAnnotations`, and enable the same narrowly selected NetworkPolicy ingress:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user