footing 0.1.21

Feature-gated foundations for Rust backend services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
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 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 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 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),
        ),
    ] {
        // Some platforms cannot represent instants beyond u64 nanoseconds.
        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 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-"))
    );
}