Skip to main content

runlimit_http/
draft_11.rs

1//! Response fields from `draft-ietf-httpapi-ratelimit-headers-11`.
2//!
3//! The draft defines `RateLimit-Policy` for stable quota policy metadata and
4//! `RateLimit` for the service limit currently available to a client. Both are
5//! HTTP Structured Field lists whose members identify policies with String
6//! items.
7//!
8//! This module emits one list member at a time. Applications remain
9//! responsible for selecting policies, combining multiple members when
10//! appropriate, and deciding whether to attach the fields to a response.
11//! Partition keys are intentionally unsupported so subject material cannot be
12//! exposed accidentally.
13
14use std::time::Duration;
15
16use http::{HeaderName, HeaderValue};
17use runlimit_core::{Decision, DecisionView, RateLimitPolicy};
18use thiserror::Error;
19
20/// Largest integer representable by an RFC 9651 Structured Field.
21pub const MAX_STRUCTURED_FIELD_INTEGER: u64 = 999_999_999_999_999;
22
23/// Maximum accepted byte length of a public policy name.
24pub const MAX_POLICY_NAME_LENGTH: usize = 128;
25
26/// A typed HTTP header name and value.
27pub type HeaderField = (HeaderName, HeaderValue);
28
29/// Encodes one `RateLimit-Policy` field.
30///
31/// The result has the form `"name";q=N;w=S`, where `q` is
32/// [`RateLimitPolicy::quota`] and `w` is its exact whole-second
33/// [`RateLimitPolicy::quota_period`]. The default quota unit from the draft is
34/// requests; this helper therefore omits the optional `qu` parameter.
35///
36/// # Errors
37///
38/// Returns [`EncodingError`] when the public policy name is unsafe for an
39/// HTTP Structured Field String, a numeric value exceeds the Structured Field
40/// integer range, or the quota period is zero or not an exact whole number of
41/// seconds.
42pub fn quota_policy<P: RateLimitPolicy + ?Sized>(
43    name: &str,
44    policy: &P,
45) -> Result<HeaderField, EncodingError> {
46    let name = encode_policy_name(name)?;
47    let quota = structured_integer(policy.quota())?;
48    let period = policy.quota_period();
49    if period.is_zero() {
50        return Err(EncodingError::ZeroQuotaPeriod);
51    }
52    if period.subsec_nanos() != 0 {
53        return Err(EncodingError::QuotaPeriodNotWholeSeconds { actual: period });
54    }
55    let period = structured_integer(period.as_secs())?;
56    let value = header_value(format!("{name};q={quota};w={period}"))?;
57
58    Ok((HeaderName::from_static("ratelimit-policy"), value))
59}
60
61/// Encodes one `RateLimit` field.
62///
63/// An allowed decision uses the immediately available allowance and rounds
64/// its replenishment duration up to whole seconds. An enforced or shadow quota
65/// denial uses `r=0` and rounds the backend's retry duration up in the same
66/// way. Thus a shadow denial exposes the service value that would have applied
67/// if the policy were enforced, without creating a `Retry-After` field or
68/// choosing an HTTP status.
69///
70/// Storage-capacity denials cannot be represented as a quota service limit and
71/// return [`EncodingError::UnsupportedDecision`].
72///
73/// # Errors
74///
75/// Returns [`EncodingError`] when the public policy name is unsafe, a numeric
76/// value exceeds the Structured Field integer range, or the decision lacks
77/// quota service metadata.
78pub fn service_limit(name: &str, decision: &Decision) -> Result<HeaderField, EncodingError> {
79    let name = encode_policy_name(name)?;
80    let (available, effective_window) = match decision.view() {
81        DecisionView::Allowed {
82            available,
83            replenishes_after,
84            ..
85        } => (available, replenishes_after),
86        DecisionView::Denied { denial } => match denial.quota() {
87            Some(denial) => (0, denial.retry_after()),
88            None => return Err(EncodingError::UnsupportedDecision),
89        },
90        DecisionView::ShadowDenied { denial } => (0, denial.retry_after()),
91    };
92    let available = structured_integer(available)?;
93    let effective_window = structured_integer(ceil_seconds(effective_window))?;
94    let value = header_value(format!("{name};r={available};t={effective_window}"))?;
95
96    Ok((HeaderName::from_static("ratelimit"), value))
97}
98
99fn encode_policy_name(name: &str) -> Result<String, EncodingError> {
100    if name.is_empty() {
101        return Err(EncodingError::EmptyPolicyName);
102    }
103    if name.len() > MAX_POLICY_NAME_LENGTH {
104        return Err(EncodingError::PolicyNameTooLong {
105            actual: name.len(),
106            maximum: MAX_POLICY_NAME_LENGTH,
107        });
108    }
109
110    let mut encoded = String::with_capacity(name.len() + 2);
111    encoded.push('"');
112    for (index, character) in name.char_indices() {
113        if !matches!(character, '\u{20}'..='\u{7e}') {
114            return Err(EncodingError::InvalidPolicyNameCharacter { index, character });
115        }
116        if matches!(character, '"' | '\\') {
117            encoded.push('\\');
118        }
119        encoded.push(character);
120    }
121    encoded.push('"');
122    Ok(encoded)
123}
124
125fn structured_integer(value: u64) -> Result<u64, EncodingError> {
126    if value > MAX_STRUCTURED_FIELD_INTEGER {
127        return Err(EncodingError::StructuredFieldIntegerTooLarge {
128            actual: value,
129            maximum: MAX_STRUCTURED_FIELD_INTEGER,
130        });
131    }
132    Ok(value)
133}
134
135fn ceil_seconds(duration: Duration) -> u64 {
136    duration
137        .as_secs()
138        .saturating_add(u64::from(duration.subsec_nanos() != 0))
139}
140
141fn header_value(value: String) -> Result<HeaderValue, EncodingError> {
142    HeaderValue::try_from(value).map_err(|_| EncodingError::InvalidHeaderValue)
143}
144
145/// Failure to encode draft-11 response metadata.
146#[derive(Clone, Debug, Error, Eq, PartialEq)]
147#[non_exhaustive]
148pub enum EncodingError {
149    /// The public policy name was empty.
150    #[error("RateLimit policy name must not be empty")]
151    EmptyPolicyName,
152    /// The public policy name exceeded [`MAX_POLICY_NAME_LENGTH`].
153    #[error("RateLimit policy name is {actual} bytes; the maximum is {maximum}")]
154    PolicyNameTooLong {
155        /// Supplied byte length.
156        actual: usize,
157        /// Largest accepted byte length.
158        maximum: usize,
159    },
160    /// The public policy name contained a character outside visible ASCII.
161    #[error(
162        "RateLimit policy name contains invalid character {character:?} at byte index {index}; \
163         use visible ASCII"
164    )]
165    InvalidPolicyNameCharacter {
166        /// Zero-based byte index of the invalid character.
167        index: usize,
168        /// Invalid character.
169        character: char,
170    },
171    /// A value exceeded the RFC 9651 Structured Field integer range.
172    #[error("Structured Field integer {actual} exceeds maximum {maximum}")]
173    StructuredFieldIntegerTooLarge {
174        /// Supplied integer.
175        actual: u64,
176        /// Largest representable integer.
177        maximum: u64,
178    },
179    /// The policy's replenishment period was zero.
180    #[error("RateLimit-Policy quota period must be greater than zero")]
181    ZeroQuotaPeriod,
182    /// The policy's replenishment period was not an exact whole second.
183    #[error("RateLimit-Policy quota period {actual:?} is not an exact whole number of seconds")]
184    QuotaPeriodNotWholeSeconds {
185        /// Supplied quota period.
186        actual: Duration,
187    },
188    /// The decision did not describe an allowed allowance or quota denial.
189    #[error("the decision cannot be represented as a RateLimit quota service limit")]
190    UnsupportedDecision,
191    /// A validated field unexpectedly failed the HTTP value grammar.
192    #[error("encoded RateLimit metadata is not a valid HTTP header value")]
193    InvalidHeaderValue,
194}
195
196#[cfg(test)]
197mod tests {
198    use std::time::Duration;
199
200    use runlimit_core::{
201        Decision, Denial, FixedWindowPolicy, GcraPolicy, PolicyFingerprint, PolicyId, QuotaDenial,
202        QuotaMode, RateLimitPolicy, ScopeId,
203    };
204
205    use super::{
206        EncodingError, MAX_POLICY_NAME_LENGTH, MAX_STRUCTURED_FIELD_INTEGER, quota_policy,
207        service_limit,
208    };
209
210    fn fixed_policy(limit: u64, window: Duration) -> FixedWindowPolicy {
211        FixedWindowPolicy::new(
212            PolicyId::new("api.search").unwrap(),
213            ScopeId::new("client").unwrap(),
214            limit,
215            window,
216        )
217        .unwrap()
218    }
219
220    #[derive(Debug)]
221    struct PeriodOverride {
222        policy: FixedWindowPolicy,
223        period: Duration,
224    }
225
226    impl RateLimitPolicy for PeriodOverride {
227        fn id(&self) -> &PolicyId {
228            self.policy.id()
229        }
230
231        fn scope(&self) -> &ScopeId {
232            self.policy.scope()
233        }
234
235        fn quota(&self) -> u64 {
236            self.policy.limit()
237        }
238
239        fn quota_period(&self) -> Duration {
240            self.period
241        }
242
243        fn capacity(&self) -> u64 {
244            self.policy.limit()
245        }
246
247        fn fingerprint(&self) -> PolicyFingerprint {
248            self.policy.fingerprint()
249        }
250
251        fn quota_mode(&self) -> QuotaMode {
252            self.policy.quota_mode()
253        }
254    }
255
256    #[test]
257    fn encodes_exact_draft_11_golden_fields() {
258        let policy = fixed_policy(100, Duration::from_secs(60));
259        let policy_field = quota_policy("search", &policy).unwrap();
260        let service_field = service_limit(
261            "search",
262            &Decision::allowed(100, 49, Duration::from_secs(37)),
263        )
264        .unwrap();
265
266        assert_eq!(policy_field.0.as_str(), "ratelimit-policy");
267        assert_eq!(policy_field.1, "\"search\";q=100;w=60");
268        assert_eq!(service_field.0.as_str(), "ratelimit");
269        assert_eq!(service_field.1, "\"search\";r=49;t=37");
270    }
271
272    #[test]
273    fn uses_algorithm_neutral_gcra_policy_metadata() {
274        let policy = GcraPolicy::new(
275            PolicyId::new("api.upload").unwrap(),
276            ScopeId::new("account").unwrap(),
277            10,
278            Duration::from_secs(60),
279            4,
280        )
281        .unwrap();
282
283        assert_eq!(
284            quota_policy("upload", &policy).unwrap().1,
285            "\"upload\";q=10;w=60"
286        );
287    }
288
289    #[test]
290    fn quota_and_shadow_denials_are_would_deny_service_values() {
291        let denial = QuotaDenial::try_new(10, Duration::from_millis(1_001)).unwrap();
292
293        assert_eq!(
294            service_limit("default", &Decision::denied(denial))
295                .unwrap()
296                .1,
297            "\"default\";r=0;t=2"
298        );
299        assert_eq!(
300            service_limit("default", &Decision::shadow_denied(denial))
301                .unwrap()
302                .1,
303            "\"default\";r=0;t=2"
304        );
305    }
306
307    #[test]
308    fn rounds_allowed_effective_windows_up_to_whole_seconds() {
309        let decision = Decision::allowed(10, 9, Duration::from_nanos(1));
310
311        assert_eq!(
312            service_limit("default", &decision).unwrap().1,
313            "\"default\";r=9;t=1"
314        );
315    }
316
317    #[test]
318    fn escapes_structured_field_strings_without_header_injection() {
319        let policy = fixed_policy(5, Duration::from_secs(1));
320
321        assert_eq!(
322            quota_policy("quoted \"name\" \\ path", &policy).unwrap().1,
323            "\"quoted \\\"name\\\" \\\\ path\";q=5;w=1"
324        );
325        assert_eq!(
326            quota_policy("bad\r\ninjected: value", &policy),
327            Err(EncodingError::InvalidPolicyNameCharacter {
328                index: 3,
329                character: '\r',
330            })
331        );
332        assert_eq!(
333            quota_policy("café", &policy),
334            Err(EncodingError::InvalidPolicyNameCharacter {
335                index: 3,
336                character: 'é',
337            })
338        );
339    }
340
341    #[test]
342    fn rejects_empty_and_oversized_policy_names() {
343        let policy = fixed_policy(5, Duration::from_secs(1));
344
345        assert_eq!(
346            quota_policy("", &policy),
347            Err(EncodingError::EmptyPolicyName)
348        );
349        assert_eq!(
350            quota_policy(&"a".repeat(MAX_POLICY_NAME_LENGTH + 1), &policy),
351            Err(EncodingError::PolicyNameTooLong {
352                actual: MAX_POLICY_NAME_LENGTH + 1,
353                maximum: MAX_POLICY_NAME_LENGTH,
354            })
355        );
356    }
357
358    #[test]
359    fn accepts_the_structured_field_integer_maximum_and_rejects_larger_values() {
360        let maximum = fixed_policy(MAX_STRUCTURED_FIELD_INTEGER, Duration::from_secs(1));
361        let too_large = fixed_policy(MAX_STRUCTURED_FIELD_INTEGER + 1, Duration::from_secs(1));
362
363        assert_eq!(
364            quota_policy("maximum", &maximum).unwrap().1,
365            "\"maximum\";q=999999999999999;w=1"
366        );
367        assert_eq!(
368            quota_policy("too-large", &too_large),
369            Err(EncodingError::StructuredFieldIntegerTooLarge {
370                actual: MAX_STRUCTURED_FIELD_INTEGER + 1,
371                maximum: MAX_STRUCTURED_FIELD_INTEGER,
372            })
373        );
374        assert_eq!(
375            service_limit(
376                "too-large",
377                &Decision::allowed(
378                    MAX_STRUCTURED_FIELD_INTEGER + 1,
379                    MAX_STRUCTURED_FIELD_INTEGER + 1,
380                    Duration::from_secs(1),
381                ),
382            ),
383            Err(EncodingError::StructuredFieldIntegerTooLarge {
384                actual: MAX_STRUCTURED_FIELD_INTEGER + 1,
385                maximum: MAX_STRUCTURED_FIELD_INTEGER,
386            })
387        );
388    }
389
390    #[test]
391    fn rejects_non_whole_second_policy_periods() {
392        let policy = fixed_policy(5, Duration::from_millis(1_500));
393
394        assert_eq!(
395            quota_policy("fractional", &policy),
396            Err(EncodingError::QuotaPeriodNotWholeSeconds {
397                actual: Duration::from_millis(1_500),
398            })
399        );
400    }
401
402    #[test]
403    fn rejects_zero_policy_periods_from_custom_policies() {
404        let policy = PeriodOverride {
405            policy: fixed_policy(5, Duration::from_secs(1)),
406            period: Duration::ZERO,
407        };
408
409        assert_eq!(
410            quota_policy("zero", &policy),
411            Err(EncodingError::ZeroQuotaPeriod)
412        );
413    }
414
415    #[test]
416    fn rejects_capacity_denials_as_quota_service_limits() {
417        let decision = Decision::denied(Denial::storage_capacity(Some(Duration::from_secs(1))));
418        assert_eq!(
419            service_limit("default", &decision),
420            Err(EncodingError::UnsupportedDecision)
421        );
422    }
423
424    #[test]
425    fn rejects_effective_windows_above_the_structured_field_integer_maximum() {
426        let decision =
427            Decision::allowed(1, 0, Duration::from_secs(MAX_STRUCTURED_FIELD_INTEGER + 1));
428
429        assert_eq!(
430            service_limit("default", &decision),
431            Err(EncodingError::StructuredFieldIntegerTooLarge {
432                actual: MAX_STRUCTURED_FIELD_INTEGER + 1,
433                maximum: MAX_STRUCTURED_FIELD_INTEGER,
434            })
435        );
436    }
437}