use std::time::{Duration, Instant};
use axum::http::{HeaderName, Request};
use super::*;
use crate::result::{ClassifyError, ErrorKind};
#[test]
fn limiter_accepts_non_clone_keys_and_preserves_overflow_limits() {
#[derive(PartialEq, Eq, Hash)]
struct Key(u32);
let config = RateLimitConfig::new(1, 1, Duration::from_secs(10)).unwrap();
let limiter = TokenBucketRateLimiter::with_max_buckets(config, 1).unwrap();
let now = Instant::now();
assert!(limiter.check_at(Key(1), now).unwrap().is_allowed());
assert!(!limiter.check_at(Key(1), now).unwrap().is_allowed());
assert!(limiter.check_at(Key(2), now).unwrap().is_allowed());
assert!(!limiter.check_at(Key(3), now).unwrap().is_allowed());
assert_eq!(limiter.bucket_count().unwrap(), 1);
assert!(
limiter
.check_at(Key(3), now + Duration::from_secs(10))
.unwrap()
.is_allowed()
);
assert!(
!limiter
.check_at(Key(3), now + Duration::from_secs(10))
.unwrap()
.is_allowed()
);
}
#[tokio::test]
async fn runtime_uses_the_existing_limiter_state_and_store_contract() {
let config = RateLimitConfig::new(1, 1, Duration::from_secs(60)).unwrap();
let limiter = std::sync::Arc::new(TokenBucketRateLimiter::new(config));
let runtime =
RateLimitRuntime::from_limiter(limiter.clone(), RateLimitKeySource::Fixed("test".into()));
let now = Instant::now();
assert!(
limiter
.check_at("key".to_owned(), now)
.unwrap()
.is_allowed()
);
assert!(
!runtime
.store()
.check("key".to_owned(), config, now)
.await
.unwrap()
.is_allowed()
);
assert_eq!(
runtime
.store()
.prune_idle(now + Duration::from_secs(1))
.await
.unwrap(),
1
);
assert!(
limiter
.check_at("key".to_owned(), now + Duration::from_secs(1))
.unwrap()
.is_allowed()
);
}
#[test]
fn mismatched_policy_cannot_reset_regular_or_overflow_allowances() {
let slow = RateLimitConfig::new(1, 1, Duration::from_secs(3600)).unwrap();
let limiter = TokenBucketRateLimiter::with_max_buckets(slow, 1).unwrap();
let now = Instant::now();
assert!(limiter.check_at("regular", now).unwrap().is_allowed());
assert!(limiter.check_at("overflow", now).unwrap().is_allowed());
let later = now + Duration::from_secs(2);
for other in [
RateLimitConfig::new(1, 1, Duration::from_secs(1)).unwrap(),
RateLimitConfig::new(2, 1, Duration::from_secs(3600)).unwrap(),
RateLimitConfig::new(1, 2, Duration::from_secs(3600)).unwrap(),
] {
for key in ["regular", "overflow", "new"] {
let error = limiter.check_at_with_config(key, other, later).unwrap_err();
assert!(matches!(error, RateLimitError::ConfigMismatch));
assert_eq!(error.error_kind(), ErrorKind::Validation);
assert_eq!(error.error_code(), "rate_limit_config_mismatch");
}
}
assert_eq!(limiter.bucket_count().unwrap(), 1);
assert!(!limiter.check_at("regular", later).unwrap().is_allowed());
assert!(!limiter.check_at("overflow", later).unwrap().is_allowed());
assert!(!limiter.check_at("new", later).unwrap().is_allowed());
assert!(
limiter
.check_at("regular", now + Duration::from_secs(3600))
.unwrap()
.is_allowed()
);
}
#[tokio::test]
async fn runtime_rejects_a_policy_incompatible_with_its_memory_store() {
let slow = RateLimitConfig::new(1, 1, Duration::from_secs(3600)).unwrap();
let fast = RateLimitConfig::new(1, 1, Duration::from_secs(1)).unwrap();
let runtime = RateLimitRuntime::new(
fast,
RateLimitKeySource::Fixed("account".into()),
std::sync::Arc::new(TokenBucketRateLimiter::new(slow)),
);
assert_eq!(
enforce_rate_limit(&runtime, &Request::new(())).await,
Err(RateLimitRejection::Unavailable)
);
}
#[test]
fn token_bucket_denies_after_capacity_and_refills() {
let config = RateLimitConfig::new(2, 1, Duration::from_secs(10)).unwrap();
let limiter = TokenBucketRateLimiter::new(config);
let now = Instant::now();
assert!(limiter.check_at("user", now).unwrap().is_allowed());
assert!(limiter.check_at("user", now).unwrap().is_allowed());
assert!(!limiter.check_at("user", now).unwrap().is_allowed());
assert!(
limiter
.check_at("user", now + Duration::from_secs(10))
.unwrap()
.is_allowed()
);
}
#[test]
fn rate_limit_debug_does_not_expose_bucket_or_fixed_keys() {
let config = RateLimitConfig::new(2, 1, Duration::from_secs(10)).unwrap();
let limiter = TokenBucketRateLimiter::new(config);
let private_key = "private-account-rate-limit-key";
limiter
.check(private_key.to_owned())
.expect("rate limit check should succeed");
let output = format!(
"{limiter:?} {:?}",
RateLimitKeySource::Fixed(private_key.to_owned())
);
assert!(output.contains("bucket_count"));
assert!(output.contains("[REDACTED]"));
assert!(!output.contains(private_key));
}
#[test]
fn rate_limit_config_rejects_zero_refill_interval() {
let error = RateLimitConfig::new(2, 1, Duration::ZERO)
.expect_err("zero refill interval must be rejected at construction");
assert!(matches!(error, RateLimitError::InvalidRefillInterval));
}
#[test]
fn token_bucket_uses_bounded_overflow_bucket_for_excess_keys() {
let limiter = TokenBucketRateLimiter::with_max_buckets(
RateLimitConfig::new(1, 1, Duration::from_secs(10)).unwrap(),
2,
)
.unwrap();
let now = Instant::now();
assert!(limiter.check_at("first", now).unwrap().is_allowed());
assert!(limiter.check_at("second", now).unwrap().is_allowed());
assert!(limiter.check_at("third", now).unwrap().is_allowed());
assert!(
!limiter.check_at("fourth", now).unwrap().is_allowed(),
"all excess keys should share one bounded overflow bucket"
);
assert_eq!(limiter.bucket_count().unwrap(), 2);
assert!(!limiter.check_at("first", now).unwrap().is_allowed());
assert_eq!(limiter.bucket_count().unwrap(), 2);
assert!(
limiter
.check_at("third", now + Duration::from_secs(10))
.unwrap()
.is_allowed()
);
assert_eq!(limiter.bucket_count().unwrap(), 1);
}
#[test]
fn header_key_source_hashes_and_bounds_untrusted_values() {
let source =
RateLimitKeySource::trusted_header_from_upstream(HeaderName::from_static("x-account-id"));
let private_value = "private-account-identifier";
let request = Request::builder()
.header("x-account-id", private_value)
.body(())
.expect("request should build");
let key = source.key_for(&request).expect("header key should exist");
assert!(key.starts_with("header:"));
assert!(!key.contains(private_value));
assert_eq!(source.key_for(&request).as_deref(), Some(key.as_str()));
let oversized = Request::builder()
.header(
"x-account-id",
"x".repeat(MAX_RATE_LIMIT_HEADER_VALUE_BYTES + 1),
)
.body(())
.expect("request should build");
assert!(source.key_for(&oversized).is_none());
}
#[tokio::test]
async fn missing_stable_key_fails_closed_instead_of_sharing_anonymous_bucket() {
let runtime = RateLimitRuntime::in_memory(
RateLimitConfig::new(1, 1, Duration::from_secs(60)).unwrap(),
RateLimitKeySource::Principal,
);
let request = Request::new(());
assert_eq!(
enforce_rate_limit(&runtime, &request).await,
Err(RateLimitRejection::MissingKey)
);
}
#[test]
fn retry_after_header_seconds_rounds_subsecond_delays_up() {
assert_eq!(retry_after_header_seconds(Duration::ZERO), 0);
assert_eq!(retry_after_header_seconds(Duration::from_millis(1)), 1);
assert_eq!(retry_after_header_seconds(Duration::from_millis(1500)), 2);
assert_eq!(retry_after_header_seconds(Duration::from_secs(3)), 3);
}
#[test]
fn rate_limit_decision_encodes_allowed_and_denied_invariants() {
let allowed = RateLimitDecision::allowed(7);
assert!(allowed.is_allowed());
assert_eq!(allowed.remaining(), 7);
assert_eq!(allowed.retry_after(), None);
let denied = RateLimitDecision::denied(Duration::from_secs(3));
assert!(!denied.is_allowed());
assert_eq!(denied.remaining(), 0);
assert_eq!(denied.retry_after(), Some(Duration::from_secs(3)));
}
#[test]
fn rate_limit_errors_are_classified() {
use std::error::Error;
let secret = "redis://user:private-password@internal-host";
let error = RateLimitError::Store(std::io::Error::other(secret).into());
assert_eq!(
RateLimitError::InvalidCapacity.error_kind(),
ErrorKind::Validation
);
assert_eq!(error.error_kind(), ErrorKind::Unavailable);
assert_eq!(error.error_code(), "rate_limit_store_unavailable");
assert_eq!(error.source().unwrap().to_string(), secret);
assert!(
error
.source()
.unwrap()
.downcast_ref::<std::io::Error>()
.is_some()
);
assert!(!error.to_string().contains(secret));
assert!(!format!("{error:?}").contains(secret));
}
#[test]
fn principal_keys_isolate_tenants_kinds_and_identifiers() {
use crate::{auth::Principal, http::RequestContext};
let key = |principal| {
let mut request = axum::http::Request::new(());
let context = RequestContext::from_headers(request.headers()).with_principal(principal);
request.extensions_mut().insert(context);
super::RateLimitKeySource::Principal
.key_for(&request)
.unwrap()
};
let principals = [
Principal::user("42").unwrap(),
Principal::client("42").unwrap(),
Principal::service_account("42").unwrap(),
Principal::user("42")
.unwrap()
.with_tenant_id("tenant-a")
.unwrap(),
Principal::user("42")
.unwrap()
.with_tenant_id("tenant-b")
.unwrap(),
Principal::user("43").unwrap(),
];
let keys: std::collections::HashSet<_> = principals.iter().cloned().map(key).collect();
assert_eq!(keys.len(), principals.len());
assert_eq!(key(principals[0].clone()), key(principals[0].clone()));
assert!(
keys.iter()
.all(|key| key.starts_with("principal:") && !key.contains("tenant-"))
);
}