-
Notifications
You must be signed in to change notification settings - Fork 1k
cubeapi: key the rate limiter on the validated identity, not an unvalidated header #1380
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from 1 commit
7f6c39c
3ef5ef4
5511d29
2fdf4da
f05fdd4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -18,13 +18,11 @@ pub async fn rate_limit( | |
| request: Request, | ||
| next: Next, | ||
| ) -> Result<Response, AppError> { | ||
| // Extract key; fall back to IP or "anonymous" | ||
| let key = request | ||
| .headers() | ||
| .get("X-API-Key") | ||
| .and_then(|v| v.to_str().ok()) | ||
| .unwrap_or("anonymous") | ||
| .to_string(); | ||
| .extensions() | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Stale doc comments now that the key comes from the validated identity, not the header. The module doc above still reads: "Per-API-key token bucket rate limiter middleware. Reads the X-API-Key header and checks the shared governor limiter." That's no longer accurate — this now keys on the |
||
| .get::<crate::middleware::auth::RateLimitIdentity>() | ||
| .map(|id| id.0.clone()) | ||
| .unwrap_or_else(|| "unauthenticated".to_string()); | ||
|
|
||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This fallback masks a fragile layering invariant. The fix only works because, in |
||
| match state.rate_limiter.check_key(&key) { | ||
| Ok(_) => Ok(next.run(request).await), | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -38,6 +38,7 @@ impl AppState { | |
| pub async fn new(config: crate::config::ServerConfig, logger: ArcLogger) -> Self { | ||
| let quota = Quota::per_second(NonZeroU32::new(config.rate_limit_per_sec.max(1)).unwrap()); | ||
| let rate_limiter = Arc::new(RateLimiter::keyed(quota)); | ||
| spawn_rate_limiter_gc(rate_limiter.clone()); | ||
|
|
||
| let http_client = reqwest::Client::builder() | ||
| .pool_max_idle_per_host(100) | ||
|
|
@@ -57,3 +58,13 @@ impl AppState { | |
| } | ||
| } | ||
| } | ||
|
|
||
| fn spawn_rate_limiter_gc(limiter: Arc<DefaultKeyedRateLimiter<String>>) { | ||
| tokio::spawn(async move { | ||
| let mut ticker = tokio::time::interval(std::time::Duration::from_secs(60)); | ||
| loop { | ||
| ticker.tick().await; | ||
| limiter.retain_recent(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This call won't compile against the pinned Also check the semantics once you add the argument: let window = std::time::Instant::now() - std::time::Duration::from_secs(120);
limiter.retain_recent(window);so recently-active keys (and the burst they've accrued) survive the sweep while abandoned keys are reclaimed. |
||
| } | ||
| }); | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The callback-mode identity stores the raw credential as the bucket key. For Bearer tokens this is often a multi-KB JWT, so every distinct token becomes a large DashMap entry that lingers until the GC sweep — and raw credentials stay resident in memory past the request. Since the limiter only needs to distinguish identities (not read the token back), key on a fixed-size hash instead, e.g.
format!("bearer:{}", sha256(token))/format!("apikey:{}", sha256(key)). That preserves per-tenant separation while bounding per-key memory and not retaining plaintext secrets. (This is also the shape of the unbounded-growth attack the GC instate.rsis meant to bound — hashing makes each entry small regardless.)