use std::time::{Duration, Instant};
use axum::http::{HeaderName, Request};
use super::*;
use crate::result::{ClassifyError, ErrorKind};
#[test]
fn idle_cleanup_does_not_reset_unreplenished_allowances() {
let now = Instant::now();
let last_request = now - Duration::from_secs(10);
let limiter =
TokenBucketRateLimiter::new(RateLimitConfig::new(1, 1, Duration::from_secs(60)).unwrap());
assert!(limiter.check_at("key", last_request).unwrap().is_allowed());
assert_eq!(
limiter.prune_idle_at(Duration::from_secs(5), now).unwrap(),
0
);
assert!(!limiter.check_at("key", now).unwrap().is_allowed());
}
#[test]
fn freeing_tracked_slots_does_not_reset_an_exhausted_overflow_bucket() {
for explicit_cleanup in [false, true] {
let now = Instant::now();
let limiter = TokenBucketRateLimiter::with_max_buckets(
RateLimitConfig::new(2, 1, Duration::from_secs(10)).unwrap(),
1,
)
.unwrap();
assert!(limiter.check_at("tracked", now).unwrap().is_allowed());
assert!(limiter.check_at("overflow", now).unwrap().is_allowed());
assert!(limiter.check_at("overflow", now).unwrap().is_allowed());
let cleanup_at = now + Duration::from_secs(10);
if explicit_cleanup {
assert_eq!(
limiter
.prune_idle_at(Duration::from_secs(1), cleanup_at)
.unwrap(),
1
);
}
assert_eq!(
limiter.check_at("overflow", cleanup_at).unwrap(),
RateLimitDecision::allowed(0)
);
for key in ["overflow", "new", "tracked"] {
assert!(!limiter.check_at(key, cleanup_at).unwrap().is_allowed());
}
assert_eq!(limiter.bucket_count().unwrap(), 0);
for _ in 0..2 {
assert!(
limiter
.check_at("new", now + Duration::from_secs(30))
.unwrap()
.is_allowed()
);
}
assert!(
!limiter
.check_at("new", now + Duration::from_secs(30))
.unwrap()
.is_allowed()
);
}
}
#[test]
fn full_overflow_bucket_preserves_its_refill_remainder_while_storage_is_full() {
let start = Instant::now();
let limiter = TokenBucketRateLimiter::with_max_buckets(
RateLimitConfig::new(1, 1, Duration::from_secs(10)).unwrap(),
1,
)
.unwrap();
for (key, seconds) in [
("tracked", 0),
("overflow", 5),
("tracked", 10),
("overflow", 16),
("tracked", 20),
] {
assert!(
limiter
.check_at(key, start + Duration::from_secs(seconds))
.unwrap()
.is_allowed()
);
}
assert_eq!(
limiter
.check_at("overflow", start + Duration::from_secs(24))
.unwrap(),
RateLimitDecision::denied(Duration::from_secs(1))
);
assert!(
limiter
.check_at("overflow", start + Duration::from_secs(25))
.unwrap()
.is_allowed()
);
assert_eq!(limiter.bucket_count().unwrap(), 1);
}
#[tokio::test]
async fn store_owned_clock_keeps_denials_idle_time_and_full_refill_consistent() {
use std::sync::Arc;
let clock = crate::clock::ManualClock::new();
let config = RateLimitConfig::new(2, 1, Duration::from_secs(10)).unwrap();
let store: Arc<dyn RateLimitStore> =
Arc::new(TokenBucketRateLimiter::new(config).with_clock(clock.shared()));
for _ in 0..2 {
assert!(
store
.check("key".into(), config)
.await
.unwrap()
.is_allowed()
);
}
clock.advance(Duration::from_secs(5)).unwrap();
assert!(
!store
.check("key".into(), config)
.await
.unwrap()
.is_allowed()
);
clock.advance(Duration::from_secs(5)).unwrap();
assert_eq!(store.prune_idle(Duration::from_secs(1)).await.unwrap(), 0);
clock.advance(Duration::from_secs(10)).unwrap();
assert_eq!(store.prune_idle(Duration::from_secs(16)).await.unwrap(), 0);
assert_eq!(store.prune_idle(Duration::MAX).await.unwrap(), 0);
assert_eq!(store.prune_idle(Duration::from_secs(15)).await.unwrap(), 1);
assert!(
store
.check("key".into(), config)
.await
.unwrap()
.is_allowed()
);
assert!(
store
.check("key".into(), config)
.await
.unwrap()
.is_allowed()
);
assert!(
!store
.check("key".into(), config)
.await
.unwrap()
.is_allowed()
);
}
#[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 metric_capacity_failures_are_shared_without_changing_rate_limit_decisions() {
use crate::observability::{MetricLabels, MetricRegistry, MetricRegistryLimits};
use std::sync::Arc;
let metrics = Arc::new(MetricRegistry::with_limits(
MetricRegistryLimits::new(1, 1).unwrap(),
));
metrics
.increment_counter("occupied", 1, MetricLabels::default())
.unwrap();
let runtime = RateLimitRuntime::in_memory(
RateLimitConfig::new(1, 1, Duration::from_secs(60)).unwrap(),
RateLimitKeySource::Fixed("bucket".into()),
)
.with_metrics(Some(metrics));
let clone = runtime.clone();
assert!(enforce_rate_limit(&clone, &Request::new(())).await.is_ok());
assert!(matches!(
enforce_rate_limit(&clone, &Request::new(())).await,
Err(RateLimitRejection::Limited { .. })
));
assert_eq!(runtime.failed_recordings(), 2);
}
#[tokio::test]
async fn store_errors_are_counted_without_decisions_or_private_backend_details() {
use crate::observability::{MetricLabels, MetricRegistry, MetricRegistryLimits, metric_names};
use std::sync::Arc;
struct FailingStore;
#[async_trait::async_trait]
impl RateLimitStore for FailingStore {
async fn check(
&self,
_: String,
_: RateLimitConfig,
) -> Result<RateLimitDecision, RateLimitError> {
Err(RateLimitError::Store(
std::io::Error::other("private backend address").into(),
))
}
async fn prune_idle(&self, _: Duration) -> Result<usize, RateLimitError> {
Ok(0)
}
}
for full_metrics in [false, true] {
let metrics = Arc::new(MetricRegistry::with_limits(
MetricRegistryLimits::new(1, 1).unwrap(),
));
if full_metrics {
metrics
.increment_counter("occupied", 1, MetricLabels::default())
.unwrap();
}
let config = RateLimitConfig::new(1, 1, Duration::from_secs(60)).unwrap();
let runtime = RateLimitRuntime::new(
config,
RateLimitKeySource::Fixed("private bucket".into()),
Arc::new(FailingStore),
)
.with_metrics(Some(metrics.clone()));
for _ in 0..2 {
assert_eq!(
enforce_rate_limit(&runtime.clone(), &Request::new(())).await,
Err(RateLimitRejection::Unavailable),
);
}
let missing_key = RateLimitRuntime::new(
config,
RateLimitKeySource::Principal,
Arc::new(FailingStore),
)
.with_metrics(Some(metrics.clone()));
assert_eq!(
enforce_rate_limit(&missing_key, &Request::new(())).await,
Err(RateLimitRejection::MissingKey)
);
assert_eq!(
runtime.failed_recordings(),
if full_metrics { 2 } else { 0 }
);
assert_eq!(missing_key.failed_recordings(), 0);
let snapshot = metrics.snapshot().unwrap();
assert_eq!(snapshot.samples().len(), 1);
if !full_metrics {
let sample = &snapshot.samples()[0];
assert_eq!(sample.name(), metric_names::RATE_LIMIT_STORE_ERRORS_TOTAL);
assert_eq!(sample.value(), 2.0);
assert_eq!(
sample.labels(),
MetricLabels::new([
("stage", "check"),
("error_code", "rate_limit_store_unavailable"),
])
.unwrap()
.as_slice()
);
}
}
}
#[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 now = Instant::now();
let clock = crate::clock::ManualClock::at(now);
let limiter =
std::sync::Arc::new(TokenBucketRateLimiter::new(config).with_clock(clock.shared()));
let runtime =
RateLimitRuntime::from_limiter(limiter.clone(), RateLimitKeySource::Fixed("test".into()));
assert!(
limiter
.check_at("key".to_owned(), now)
.unwrap()
.is_allowed()
);
assert!(
!runtime
.store()
.check("key".to_owned(), config)
.await
.unwrap()
.is_allowed()
);
assert_eq!(runtime.store().prune_idle(Duration::ZERO).await.unwrap(), 0);
clock.advance(Duration::from_secs(60)).unwrap();
assert_eq!(runtime.store().prune_idle(Duration::ZERO).await.unwrap(), 1);
assert!(limiter.check("key".to_owned()).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 token_bucket_preserves_latest_activity_when_checks_arrive_out_of_order() {
let refill_period = Duration::from_secs(10);
let limiter = TokenBucketRateLimiter::new(RateLimitConfig::new(1, 1, refill_period).unwrap());
let earlier = Instant::now();
let later = earlier + Duration::from_millis(2);
assert!(limiter.check_at("user", later).unwrap().is_allowed());
assert!(!limiter.check_at("user", earlier).unwrap().is_allowed());
let cleanup_at = earlier + refill_period + Duration::from_millis(1);
let removed = limiter.prune_idle_at(refill_period, cleanup_at).unwrap();
assert!(
!limiter.check_at("user", cleanup_at).unwrap().is_allowed(),
"idle cleanup must not reset an allowance before its refill is due"
);
assert_eq!(removed, 0);
assert!(
limiter
.check_at("user", later + refill_period)
.unwrap()
.is_allowed()
);
}
#[test]
fn token_bucket_preserves_the_refill_remainder_across_the_duration_range() {
let start = Instant::now();
for (interval, elapsed, retry_after) in [
(
Duration::from_millis(10),
Duration::from_millis(15),
Duration::from_millis(5),
),
(
Duration::from_secs(40_000_000_000),
Duration::from_secs(70_000_000_000),
Duration::from_secs(10_000_000_000),
),
] {
let Some(later) = start.checked_add(elapsed) else {
continue;
};
let limiter = TokenBucketRateLimiter::new(RateLimitConfig::new(1, 1, interval).unwrap());
assert!(limiter.check_at("key", start).unwrap().is_allowed());
assert!(limiter.check_at("key", later).unwrap().is_allowed());
assert_eq!(
limiter.check_at("key", later).unwrap().retry_after(),
Some(retry_after),
);
}
}
#[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 rate_limit_layer_accepts_wrapped_request_bodies() {
use axum::{body::Body, http::StatusCode, response::Response};
use http_body_util::BodyExt as _;
use tower::{Layer as _, ServiceExt as _};
use tower_http::timeout::{RequestBodyTimeoutLayer, TimeoutBody};
let runtime = RateLimitRuntime::in_memory(
RateLimitConfig::new(1, 1, Duration::from_secs(3600)).unwrap(),
RateLimitKeySource::Fixed("account".into()),
);
let inner = tower::service_fn(|request: Request<TimeoutBody<Body>>| async move {
let body = request.into_body().collect().await.unwrap().to_bytes();
Ok::<_, std::convert::Infallible>(Response::new(Body::from(body)))
});
let service = RequestBodyTimeoutLayer::new(Duration::from_secs(1))
.layer(RateLimitLayer::new(runtime).layer(inner));
let response = service
.clone()
.oneshot(Request::new(Body::from("request body")))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response.into_body().collect().await.unwrap().to_bytes(),
"request body"
);
let response = service.oneshot(Request::new(Body::empty())).await.unwrap();
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
}
#[tokio::test]
async fn rate_limit_layer_preserves_non_send_errors_and_consumes_allowance() {
use axum::{http::StatusCode, response::Response};
use tower::{Layer as _, ServiceExt as _};
let clock = crate::clock::ManualClock::new();
let runtime = RateLimitRuntime::from_limiter(
std::sync::Arc::new(
TokenBucketRateLimiter::new(
RateLimitConfig::new(1, 1, Duration::from_secs(60)).unwrap(),
)
.with_clock(clock.shared()),
),
RateLimitKeySource::Fixed("account".into()),
);
let inner = tower::service_fn(|_: Request<()>| async {
tokio::task::yield_now().await;
Err::<Response, _>(std::rc::Rc::new(String::from("local service failure")))
});
let service = RateLimitLayer::new(runtime).layer(inner);
let error = service.clone().oneshot(Request::new(())).await.unwrap_err();
assert_eq!(error.as_str(), "local service failure");
let response = service.oneshot(Request::new(())).await.unwrap();
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
assert_eq!(response.headers()[axum::http::header::RETRY_AFTER], "60");
}
#[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)
);
}
#[tokio::test]
async fn repeated_trusted_headers_fail_closed_without_consuming_tokens() {
use axum::{body::to_bytes, http::StatusCode, response::IntoResponse as _};
let runtime = RateLimitRuntime::in_memory(
RateLimitConfig::new(1, 1, Duration::from_secs(3600)).unwrap(),
RateLimitKeySource::trusted_header_from_upstream(HeaderName::from_static("x-account-id")),
);
for second in ["account", "other"] {
let request = Request::builder()
.header("x-account-id", "account")
.header("x-account-id", second)
.body(())
.unwrap();
let rejection = enforce_rate_limit(&runtime, &request).await.unwrap_err();
assert_eq!(rejection, RateLimitRejection::MissingKey);
let response = rejection.into_response();
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
let body = to_bytes(response.into_body(), 4096).await.unwrap();
let problem: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(problem["code"], "rate_limit_key_unavailable");
}
let request = Request::builder()
.header("x-account-id", "account")
.body(())
.unwrap();
assert!(enforce_rate_limit(&runtime, &request).await.is_ok());
}
#[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-"))
);
}
#[tokio::test]
async fn tenant_keys_share_capacity_across_identities_and_reject_missing_tenants() {
use crate::{
auth::Principal,
http::{IdempotencyScope, VerifiedAuthentication},
};
let runtime = RateLimitRuntime::in_memory(
RateLimitConfig::new(1, 1, Duration::from_secs(3600)).unwrap(),
RateLimitKeySource::Tenant,
);
let request = |principal: Principal| {
let mut request = Request::new(());
VerifiedAuthentication::new(principal, IdempotencyScope::new("test")).install(&mut request);
request
};
let tenant_a_user = request(
Principal::user("alice")
.unwrap()
.with_tenant_id("tenant-a")
.unwrap(),
);
let tenant_a_client = request(
Principal::client("automation")
.unwrap()
.with_tenant_id("tenant-a")
.unwrap(),
);
let tenant_b = request(
Principal::user("alice")
.unwrap()
.with_tenant_id("tenant-b")
.unwrap(),
);
let tenant_a_key = RateLimitKeySource::Tenant.key_for(&tenant_a_user).unwrap();
assert_eq!(
RateLimitKeySource::Tenant.key_for(&tenant_a_client),
Some(tenant_a_key.clone())
);
assert!(!tenant_a_key.contains("tenant-a"));
assert_ne!(
RateLimitKeySource::Principal.key_for(&tenant_a_user),
Some(tenant_a_key)
);
assert!(enforce_rate_limit(&runtime, &tenant_a_user).await.is_ok());
assert!(matches!(
enforce_rate_limit(&runtime, &tenant_a_client).await,
Err(RateLimitRejection::Limited { .. })
));
assert!(enforce_rate_limit(&runtime, &tenant_b).await.is_ok());
for missing in [
request(Principal::user("tenantless").unwrap()),
Request::builder()
.header("x-tenant-id", "tenant-a")
.body(())
.unwrap(),
] {
assert_eq!(
enforce_rate_limit(&runtime, &missing).await,
Err(RateLimitRejection::MissingKey)
);
}
}