Skip to main content

runlimit_axum/
lib.rs

1//! Caller-controlled Axum admission middleware for Runlimit.
2//!
3//! [`RateLimitLayer`] evaluates one [`runlimit_core::Check`] before calling the
4//! wrapped service. Applications supply both trust-sensitive operations:
5//!
6//! - a synchronous [`ExtractSubjectKey`] implementation that derives an opaque
7//!   [`runlimit_core::SubjectKey`] from the request; and
8//! - a rejection mapper that converts extraction failures, enforced decisions,
9//!   and backend failures into an Axum [`Response`].
10//!
11//! This crate never interprets forwarding headers, connection metadata, or
12//! application identities. It also does not select response status codes,
13//! bodies, or headers. A shadow denial permits the request and is available to
14//! downstream code as a [`runlimit_core::Decision`] request extension, just
15//! like an allowed decision.
16
17use std::{
18    any::type_name,
19    fmt,
20    future::Future,
21    marker::PhantomData,
22    mem,
23    pin::Pin,
24    sync::Arc,
25    task::{Context, Poll},
26};
27
28use axum::{extract::Request, response::Response};
29use runlimit_core::{Check, Decision, Limiter, SubjectKey};
30use tower::{Layer, Service};
31
32/// A synchronous, application-owned request-to-subject-key boundary.
33///
34/// The extractor receives the complete request and the configured policy.
35/// Implementations decide whether request metadata is trusted and how an
36/// application identity is normalized. Closures with the matching signature
37/// implement this trait automatically.
38///
39/// Extractors should return only opaque [`SubjectKey`] values. In particular,
40/// raw identities should not cross into a Runlimit backend or generic error
41/// and telemetry paths.
42pub trait ExtractSubjectKey<P, B>: Send + Sync {
43    /// Application-defined extraction failure.
44    type Error;
45
46    /// Derives the opaque subject key for this request and policy.
47    ///
48    /// # Errors
49    ///
50    /// Returns an application-defined error when the request does not contain
51    /// usable or trusted subject material.
52    fn extract_subject_key(
53        &self,
54        request: &Request<B>,
55        policy: &P,
56    ) -> Result<SubjectKey, Self::Error>;
57}
58
59impl<P, B, F, E> ExtractSubjectKey<P, B> for F
60where
61    F: Fn(&Request<B>, &P) -> Result<SubjectKey, E> + Send + Sync,
62{
63    type Error = E;
64
65    fn extract_subject_key(
66        &self,
67        request: &Request<B>,
68        policy: &P,
69    ) -> Result<SubjectKey, Self::Error> {
70        self(request, policy)
71    }
72}
73
74/// A rate-limit rejection handed to the application-owned response mapper.
75///
76/// This type deliberately does not implement `IntoResponse`: the application
77/// controls its status, response body, headers, and operational-failure
78/// policy.
79#[non_exhaustive]
80pub enum RateLimitRejection<KeyError, BackendError> {
81    /// The application-owned key extractor rejected the request.
82    Key(KeyError),
83    /// The backend returned an enforced quota or storage-capacity denial.
84    Denied(Decision),
85    /// The backend could not complete the admission check.
86    Backend(BackendError),
87}
88
89impl<KeyError, BackendError> RateLimitRejection<KeyError, BackendError> {
90    /// Returns a stable, non-sensitive label for the rejection category.
91    pub const fn kind(&self) -> RejectionKind {
92        match self {
93            Self::Key(_) => RejectionKind::Key,
94            Self::Denied(_) => RejectionKind::Denied,
95            Self::Backend(_) => RejectionKind::Backend,
96        }
97    }
98}
99
100impl<KeyError, BackendError> fmt::Debug for RateLimitRejection<KeyError, BackendError> {
101    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
102        formatter
103            .debug_struct("RateLimitRejection")
104            .field("kind", &self.kind())
105            .field("details", &Redacted)
106            .finish()
107    }
108}
109
110/// The non-sensitive category of a [`RateLimitRejection`].
111#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
112pub enum RejectionKind {
113    /// Subject-key extraction failed.
114    Key,
115    /// The limiter returned an enforced denial.
116    Denied,
117    /// The limiter backend failed.
118    Backend,
119}
120
121/// A Tower layer that performs one Runlimit admission check per request.
122///
123/// The layer owns one policy and shares the limiter and callback state across
124/// clones. It extracts the key and starts the limiter operation before the
125/// wrapped service is called. Neither the layer nor its service reads or polls
126/// the request body.
127pub struct RateLimitLayer<L: Limiter, K, R> {
128    limiter: Arc<L>,
129    policy: Arc<L::Policy>,
130    key_extractor: Arc<K>,
131    rejection_mapper: Arc<R>,
132}
133
134impl<L: Limiter, K, R> RateLimitLayer<L, K, R> {
135    /// Constructs a layer and moves a limiter into shared ownership.
136    pub fn new(limiter: L, policy: L::Policy, key_extractor: K, rejection_mapper: R) -> Self {
137        Self::from_shared(Arc::new(limiter), policy, key_extractor, rejection_mapper)
138    }
139
140    /// Constructs a layer from an already shared limiter.
141    pub fn from_shared(
142        limiter: Arc<L>,
143        policy: L::Policy,
144        key_extractor: K,
145        rejection_mapper: R,
146    ) -> Self {
147        Self {
148            limiter,
149            policy: Arc::new(policy),
150            key_extractor: Arc::new(key_extractor),
151            rejection_mapper: Arc::new(rejection_mapper),
152        }
153    }
154
155    /// Returns the shared limiter used by this layer.
156    pub const fn limiter(&self) -> &Arc<L> {
157        &self.limiter
158    }
159
160    /// Returns the policy evaluated for every request.
161    pub fn policy(&self) -> &L::Policy {
162        self.policy.as_ref()
163    }
164}
165
166impl<L: Limiter, K, R> Clone for RateLimitLayer<L, K, R> {
167    fn clone(&self) -> Self {
168        Self {
169            limiter: Arc::clone(&self.limiter),
170            policy: Arc::clone(&self.policy),
171            key_extractor: Arc::clone(&self.key_extractor),
172            rejection_mapper: Arc::clone(&self.rejection_mapper),
173        }
174    }
175}
176
177impl<L: Limiter, K, R> fmt::Debug for RateLimitLayer<L, K, R> {
178    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
179        formatter
180            .debug_struct("RateLimitLayer")
181            .field("limiter_type", &type_name::<L>())
182            .field("limiter", &Redacted)
183            .field("policy", &self.policy)
184            .field("key_extractor", &Redacted)
185            .field("rejection_mapper", &Redacted)
186            .finish()
187    }
188}
189
190impl<S, L: Limiter, K, R> Layer<S> for RateLimitLayer<L, K, R> {
191    type Service = RateLimitService<S, L, K, R>;
192
193    fn layer(&self, inner: S) -> Self::Service {
194        RateLimitService {
195            inner,
196            limiter: Arc::clone(&self.limiter),
197            policy: Arc::clone(&self.policy),
198            key_extractor: Arc::clone(&self.key_extractor),
199            rejection_mapper: Arc::clone(&self.rejection_mapper),
200        }
201    }
202}
203
204/// The service produced by [`RateLimitLayer`].
205pub struct RateLimitService<S, L: Limiter, K, R> {
206    inner: S,
207    limiter: Arc<L>,
208    policy: Arc<L::Policy>,
209    key_extractor: Arc<K>,
210    rejection_mapper: Arc<R>,
211}
212
213impl<S: Clone, L: Limiter, K, R> Clone for RateLimitService<S, L, K, R> {
214    fn clone(&self) -> Self {
215        Self {
216            inner: self.inner.clone(),
217            limiter: Arc::clone(&self.limiter),
218            policy: Arc::clone(&self.policy),
219            key_extractor: Arc::clone(&self.key_extractor),
220            rejection_mapper: Arc::clone(&self.rejection_mapper),
221        }
222    }
223}
224
225impl<S, L: Limiter, K, R> fmt::Debug for RateLimitService<S, L, K, R> {
226    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
227        formatter
228            .debug_struct("RateLimitService")
229            .field("inner_type", &type_name::<S>())
230            .field("inner", &Redacted)
231            .field("limiter_type", &type_name::<L>())
232            .field("limiter", &Redacted)
233            .field("policy", &self.policy)
234            .field("key_extractor", &Redacted)
235            .field("rejection_mapper", &Redacted)
236            .finish()
237    }
238}
239
240/// The boxed, sendable response future returned by [`RateLimitService`].
241pub struct ResponseFuture<F> {
242    inner: Pin<Box<dyn Future<Output = F> + Send + 'static>>,
243}
244
245impl<F> Future for ResponseFuture<F> {
246    type Output = F;
247
248    fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
249        self.inner.as_mut().poll(context)
250    }
251}
252
253impl<F> fmt::Debug for ResponseFuture<F> {
254    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
255        formatter
256            .debug_struct("ResponseFuture")
257            .field("state", &Redacted)
258            .field("_output", &PhantomData::<fn() -> F>)
259            .finish()
260    }
261}
262
263impl<S, L, K, R, B> Service<Request<B>> for RateLimitService<S, L, K, R>
264where
265    S: Service<Request<B>, Response = Response> + Clone + Send + 'static,
266    S::Future: Send + 'static,
267    L: Limiter + 'static,
268    L::Policy: 'static,
269    K: ExtractSubjectKey<L::Policy, B> + 'static,
270    K::Error: Send + 'static,
271    R: Fn(RateLimitRejection<K::Error, L::Error>) -> Response + Send + Sync + 'static,
272    B: Send + 'static,
273{
274    type Response = Response;
275    type Error = S::Error;
276    type Future = ResponseFuture<Result<Self::Response, Self::Error>>;
277
278    fn poll_ready(&mut self, context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
279        self.inner.poll_ready(context)
280    }
281
282    fn call(&mut self, mut request: Request<B>) -> Self::Future {
283        let subject = self
284            .key_extractor
285            .extract_subject_key(&request, self.policy.as_ref());
286
287        let limiter = Arc::clone(&self.limiter);
288        let policy = Arc::clone(&self.policy);
289        let rejection_mapper = Arc::clone(&self.rejection_mapper);
290
291        let inner_clone = self.inner.clone();
292        let mut ready_inner = mem::replace(&mut self.inner, inner_clone);
293
294        ResponseFuture {
295            inner: Box::pin(async move {
296                let subject = match subject {
297                    Ok(subject) => subject,
298                    Err(error) => {
299                        return Ok(rejection_mapper(RateLimitRejection::Key(error)));
300                    }
301                };
302
303                let check = Check::new(policy.as_ref(), subject);
304                let decision = match limiter.check(&check).await {
305                    Ok(decision) => decision,
306                    Err(error) => {
307                        return Ok(rejection_mapper(RateLimitRejection::Backend(error)));
308                    }
309                };
310
311                if decision.is_enforced_denial() {
312                    return Ok(rejection_mapper(RateLimitRejection::Denied(decision)));
313                }
314
315                request.extensions_mut().insert(decision);
316                ready_inner.call(request).await
317            }),
318        }
319    }
320}
321
322struct Redacted;
323
324impl fmt::Debug for Redacted {
325    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
326        formatter.write_str("<redacted>")
327    }
328}