-
Notifications
You must be signed in to change notification settings - Fork 8
feat(api): Add global IP rate limiting framework (ADR-0022 phase 1) #846
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: main
Are you sure you want to change the base?
Changes from all commits
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 |
|---|---|---|
|
|
@@ -16,7 +16,7 @@ use { | |
| axum::{ | ||
| Json, | ||
| extract::rejection::JsonRejection, | ||
| http::StatusCode, | ||
| http::{HeaderValue, StatusCode, header}, | ||
| response::{IntoResponse, Response}, | ||
| }, | ||
| serde_json::json, | ||
|
|
@@ -41,6 +41,25 @@ use crate::error::KeystoneApiError; | |
|
|
||
| impl IntoResponse for KeystoneApiError { | ||
| fn into_response(self) -> Response { | ||
| // Rate-limit rejections need a `Retry-After` header in addition to the | ||
| // JSON body, so they are handled before the generic status-code path | ||
| // (ADR-0022 Invariants 3 and 4). | ||
| if let KeystoneApiError::TooManyRequests { retry_after } = &self { | ||
| let body = Json(json!({ | ||
| "error": { | ||
| "code": StatusCode::TOO_MANY_REQUESTS.as_u16(), | ||
| "message": self.to_string(), | ||
| } | ||
| })); | ||
| let retry_value = HeaderValue::from_str(&retry_after.to_string()) | ||
| .unwrap_or_else(|_| HeaderValue::from_static("60")); | ||
| let mut response = (StatusCode::TOO_MANY_REQUESTS, body).into_response(); | ||
| response | ||
| .headers_mut() | ||
| .insert(header::RETRY_AFTER, retry_value); | ||
| return response; | ||
| } | ||
|
|
||
| let status_code = match self { | ||
| KeystoneApiError::Conflict(_) => StatusCode::CONFLICT, | ||
| KeystoneApiError::NotFound { .. } => StatusCode::NOT_FOUND, | ||
|
|
@@ -54,7 +73,6 @@ impl IntoResponse for KeystoneApiError { | |
| KeystoneApiError::InternalError(_) | KeystoneApiError::Other(..) => { | ||
| StatusCode::INTERNAL_SERVER_ERROR | ||
| } | ||
| KeystoneApiError::TooManyRequests => StatusCode::TOO_MANY_REQUESTS, | ||
| _ => StatusCode::BAD_REQUEST, | ||
| }; | ||
|
|
||
|
|
@@ -588,4 +606,29 @@ mod tests { | |
| KeystoneApiError::InternalError(msg) if msg.contains("test error") | ||
| )); | ||
| } | ||
|
|
||
| #[test] | ||
| fn too_many_requests_returns_429_with_retry_after() { | ||
| let err = KeystoneApiError::TooManyRequests { retry_after: 42 }; | ||
| let response = <KeystoneApiError as IntoResponse>::into_response(err); | ||
| assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS); | ||
| let retry_after = response | ||
| .headers() | ||
| .get(header::RETRY_AFTER) | ||
| .expect("Retry-After header must be present"); | ||
| assert_eq!(retry_after.to_str().unwrap(), "42"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn too_many_requests_retry_after_fallback_on_large_value() { | ||
|
Collaborator
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. test name is not suitable, you are not testing rate limiting at all. Instead the test only verifies header construction |
||
| // u64::MAX cannot fit in a header value — the fallback must be "60". | ||
| // In practice our handler always passes a small Duration::as_secs() | ||
| // value, but the fallback path must be covered. | ||
| // We verify the fallback by constructing a HeaderValue that fails. | ||
| let bad_value = "not\na valid\nheader"; | ||
| let result = HeaderValue::from_str(bad_value); | ||
| assert!(result.is_err(), "sanity: newlines must be rejected"); | ||
| let fallback = result.unwrap_or_else(|_| HeaderValue::from_static("60")); | ||
| assert_eq!(fallback.to_str().unwrap(), "60"); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
| // | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| //! Rate limiting configuration sections (ADR-0022). | ||
| //! | ||
| //! Each `[rate_limit_*]` INI section deserializes into a [`RateLimitSection`]. | ||
| //! The section carries only the *policy* scalars; the actual `governor` | ||
| //! [`RateLimiter`](https://docs.rs/governor) instances live in | ||
| //! [`crate::rate_limit::RateLimitState`] and are constructed once at startup | ||
| //! from these values. | ||
| //! | ||
| //! # Security invariant (ADR-0022 §2, config bounds) | ||
| //! | ||
| //! If `enabled = true` and either `burst_size` or `replenish_rate_per_second` | ||
| //! falls outside `[1, 100000]`, the application **must** refuse to start. This | ||
| //! is enforced in | ||
| //! [`RateLimitState::from_config`](openstack_keystone_core::rate_limit::RateLimitState::from_config), | ||
| //! not here — a disabled section with out-of-range values is harmless and must | ||
| //! not cause a startup failure, so the bound cannot be a field-level | ||
| //! `validator` range that would fire unconditionally. | ||
|
|
||
| use serde::Deserialize; | ||
|
|
||
| /// Default burst capacity when the key is absent from the config file. | ||
| fn default_burst_size() -> u32 { | ||
| 100 | ||
| } | ||
|
|
||
| /// Default replenishment rate when the key is absent from the config file. | ||
| fn default_replenish_rate_per_second() -> u32 { | ||
| 10 | ||
| } | ||
|
|
||
| /// A single rate-limiting bucket, mapped from one INI `[rate_limit_*]` section. | ||
| /// | ||
| /// The same struct is reused for every bucket (global-IP, per-user, per-domain | ||
| /// …) so operators see a consistent configuration shape across all limiters. | ||
| /// | ||
| /// ```ini | ||
| /// [rate_limit_global_ip] | ||
| /// enabled = true | ||
| /// burst_size = 100 | ||
| /// replenish_rate_per_second = 10 | ||
| /// ``` | ||
| #[derive(Debug, Deserialize, Clone)] | ||
| pub struct RateLimitSection { | ||
| /// When `false` (the default) the corresponding `governor` limiter is not | ||
| /// instantiated and the handler bypasses this check entirely. | ||
| #[serde(default)] | ||
| pub enabled: bool, | ||
|
|
||
| /// Maximum number of cells that can be consumed in a burst before | ||
| /// replenishment kicks in. Must be within `[1, 100000]` when | ||
| /// `enabled = true`. | ||
| #[serde(default = "default_burst_size")] | ||
|
Collaborator
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. we should add validation for both values to be [1, 100000] - this is defined in the ADR
Collaborator
Author
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. Done — added the |
||
| pub burst_size: u32, | ||
|
|
||
| /// How many cells are added back to the bucket per second. Must be within | ||
| /// `[1, 100000]` when `enabled = true`. | ||
| #[serde(default = "default_replenish_rate_per_second")] | ||
| pub replenish_rate_per_second: u32, | ||
| } | ||
|
|
||
| impl Default for RateLimitSection { | ||
| fn default() -> Self { | ||
| Self { | ||
| enabled: false, | ||
| burst_size: default_burst_size(), | ||
| replenish_rate_per_second: default_replenish_rate_per_second(), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use serde_json::json; | ||
|
|
||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn default_is_disabled() { | ||
| let s = RateLimitSection::default(); | ||
| assert!(!s.enabled); | ||
| assert_eq!(s.burst_size, 100); | ||
| assert_eq!(s.replenish_rate_per_second, 10); | ||
| } | ||
|
|
||
| #[test] | ||
| fn deserialize_enabled_section() { | ||
| let s: RateLimitSection = serde_json::from_value(json!({"enabled": true, "burst_size": 5, | ||
| "replenish_rate_per_second": 1})) | ||
| .unwrap(); | ||
| assert!(s.enabled); | ||
| assert_eq!(s.burst_size, 5); | ||
| assert_eq!(s.replenish_rate_per_second, 1); | ||
| } | ||
|
|
||
| #[test] | ||
| fn deserialize_disabled_ignores_zero_values() { | ||
| // Disabled sections with zero limits are valid config (no startup failure). | ||
| let s: RateLimitSection = serde_json::from_value(json!({"enabled": false, "burst_size": 0, | ||
| "replenish_rate_per_second": 0})) | ||
| .unwrap(); | ||
| assert!(!s.enabled); | ||
| } | ||
|
|
||
| #[test] | ||
| fn deserialize_defaults_when_fields_absent() { | ||
| let s: RateLimitSection = serde_json::from_value(json!({})).unwrap(); | ||
| assert!(!s.enabled); | ||
| assert_eq!(s.burst_size, 100); | ||
| assert_eq!(s.replenish_rate_per_second, 10); | ||
| } | ||
| } | ||
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.
let's do "Rate limit exceeded. Retry in {retry_after} seconds." instead