use std::time::{Duration, Instant};
use axum::http::{HeaderName, Request};
use super::*;
use crate::result::{ClassifyError, ErrorKind};
#[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(MemoryRateLimitStore::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::PrincipalId,
);
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() {
assert_eq!(
RateLimitError::InvalidCapacity.error_kind(),
ErrorKind::Validation
);
assert_eq!(
RateLimitError::StoreUnavailable.error_kind(),
ErrorKind::Unavailable
);
assert_eq!(
RateLimitError::StoreUnavailable.error_code(),
"rate_limit_store_unavailable"
);
}