Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions crates/api-types/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,17 @@ pub enum KeystoneApiError {
#[error("selected authentication is forbidden")]
SelectedAuthenticationForbidden,

/// Rate limit exceeded (HTTP 429 Too Many Requests).
///
/// `retry_after` is the number of seconds the client must wait before
/// retrying. Surfaced via the `Retry-After` response header (ADR-0022,
/// Invariant 3). No key-identifying information is included.
#[error("Rate limit exceeded. Retry in {retry_after}s.")]
TooManyRequests {
/// Minimum seconds to wait before retrying.
retry_after: u64,
},

/// (de)serialization error.
#[error(transparent)]
Serde {
Expand All @@ -86,9 +97,6 @@ pub enum KeystoneApiError {
#[error("missing x-subject-token header")]
SubjectTokenMissing,

#[error("rate limit exceeded, retry later")]
TooManyRequests,

#[error("The request you have made requires authentication.")]
UnauthorizedNoContext,

Expand Down
47 changes: 45 additions & 2 deletions crates/api-types/src/error_conv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use {
axum::{
Json,
extract::rejection::JsonRejection,
http::StatusCode,
http::{HeaderValue, StatusCode, header},
response::{IntoResponse, Response},
},
serde_json::json,
Expand All @@ -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,
Expand All @@ -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,
};

Expand Down Expand Up @@ -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() {
// 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");
}
}
11 changes: 11 additions & 0 deletions crates/config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ mod k8s_auth;
mod listener;
mod mapping;
mod policy;
mod rate_limit;
mod resource;
mod revoke;
mod role;
Expand Down Expand Up @@ -109,6 +110,7 @@ pub use k8s_auth::*;
pub use listener::*;
pub use mapping::*;
pub use policy::*;
pub use rate_limit::*;
pub use resource::*;
pub use revoke::*;
pub use role::*;
Expand Down Expand Up @@ -214,6 +216,15 @@ pub struct Config {
#[serde(rename = "interface_admin", default)]
pub interface_admin: Option<AdminInterface>,

/// Global per-IP rate limiting (ADR-0022, §1).
///
/// Maps to the `[rate_limit_global_ip]` INI section. When `enabled =
/// false` (the default) the governor is not instantiated and all requests
/// bypass the check. Set `enabled = true` together with valid
/// `burst_size` and `replenish_rate_per_second` to activate.
#[serde(rename = "rate_limit_global_ip", default)]
pub rate_limit_global_ip: RateLimitSection,

/// Resource provider configuration.
#[serde(default)]
pub resource: ResourceProvider,
Expand Down
125 changes: 125 additions & 0 deletions crates/config/src/rate_limit.rs
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")]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done — added the [1, 100000] bound for both burst_size and replenish_rate_per_second (ADR-0022 config-bounds table). Enforced in build_limiter/from_config as a fail-hard startup error alongside the existing zero check, via a small validated_scalar helper. I kept it there rather than a field-level validator range(min=1, max=100000) because a disabled section must be allowed to carry out-of-range/zero values without aborting startup (existing invariant + tests) — a field-level range would fire unconditionally. Added tests for the upper bound and the 100000 boundary; field docs updated.

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);
}
}
6 changes: 6 additions & 0 deletions crates/core-types/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,12 @@ pub enum KeystoneError {
#[error("raft storage is not available")]
RaftNotAvailable,

/// Rate limit configuration is invalid (e.g. replenish rate or burst is
/// zero while the limiter is enabled). The application must refuse to
/// start when this error is returned (ADR-0022, Invariant 2).
#[error("invalid rate limit configuration: {0}")]
RateLimitConfig(String),

/// Resource provider.
#[error(transparent)]
ResourceProvider {
Expand Down
24 changes: 13 additions & 11 deletions crates/core/src/api/api_key_auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use std::ops::Deref;

use axum::extract::{ConnectInfo, FromRef, FromRequestParts, Path};
use axum::http::request::Parts;
use governor::clock::Clock as _;
use ipnet::IpNet;
use tracing::warn;

Expand Down Expand Up @@ -92,23 +93,24 @@ where
// brute-force garbage traffic doesn't bypass rate limiting by
// sending malformed tokens.
if let Some(ip) = peer_ip
&& state
.api_key_rate_limiter
.check_key(&ip.to_string())
.is_err()
&& let Err(not_until) = state.api_key_rate_limiter.check_key(&ip.to_string())
{
return Err(KeystoneApiError::TooManyRequests);
let retry_after = not_until
.wait_time_from(state.api_key_rate_limiter.clock().now())
.as_secs()
.max(1);
return Err(KeystoneApiError::TooManyRequests { retry_after });
}
return Err(AuthenticationError::Unauthorized.into());
}
};

if state
.api_key_rate_limiter
.check_key(&parsed.lookup_hash)
.is_err()
{
return Err(KeystoneApiError::TooManyRequests);
if let Err(not_until) = state.api_key_rate_limiter.check_key(&parsed.lookup_hash) {
let retry_after = not_until
.wait_time_from(state.api_key_rate_limiter.clock().now())
.as_secs()
.max(1);
return Err(KeystoneApiError::TooManyRequests { retry_after });
}

// Step 2: database lookup & IP allowlisting.
Expand Down
15 changes: 15 additions & 0 deletions crates/core/src/api/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,9 @@ mod tests {
api_key_rate_limiter: std::sync::Arc::new(governor::RateLimiter::keyed(
governor::Quota::per_minute(std::num::NonZeroU32::new(60).unwrap()),
)),
rate_limiters: crate::rate_limit::RateLimitState {
global_ip_limiter: None,
},
shutdown: false,
};
Arc::new(service)
Expand Down Expand Up @@ -342,6 +345,9 @@ mod tests {
api_key_rate_limiter: std::sync::Arc::new(governor::RateLimiter::keyed(
governor::Quota::per_minute(std::num::NonZeroU32::new(60).unwrap()),
)),
rate_limiters: crate::rate_limit::RateLimitState {
global_ip_limiter: None,
},
shutdown: false,
});

Expand Down Expand Up @@ -445,6 +451,9 @@ mod tests {
api_key_rate_limiter: std::sync::Arc::new(governor::RateLimiter::keyed(
governor::Quota::per_minute(std::num::NonZeroU32::new(60).unwrap()),
)),
rate_limiters: crate::rate_limit::RateLimitState {
global_ip_limiter: None,
},
shutdown: false,
});

Expand Down Expand Up @@ -512,6 +521,9 @@ mod tests {
api_key_rate_limiter: std::sync::Arc::new(governor::RateLimiter::keyed(
governor::Quota::per_minute(std::num::NonZeroU32::new(60).unwrap()),
)),
rate_limiters: crate::rate_limit::RateLimitState {
global_ip_limiter: None,
},
shutdown: false,
});

Expand Down Expand Up @@ -578,6 +590,9 @@ mod tests {
api_key_rate_limiter: std::sync::Arc::new(governor::RateLimiter::keyed(
governor::Quota::per_minute(std::num::NonZeroU32::new(60).unwrap()),
)),
rate_limiters: crate::rate_limit::RateLimitState {
global_ip_limiter: None,
},
shutdown: false,
});

Expand Down
Loading
Loading