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
//! # rocket-governor - rate-limiting implementation for Rocket web framework
//!
//! Provides the [rocket] guard implementing rate-limiting (based on [governor]).
//!
//! Declare a struct and use it with the generic [RocketGovernor] guard.  
//! This requires to implement trait [RocketGovernable] for your struct.
//!
//! ## Example
//!
//! ```rust
//! use rocket::{catchers, get, http::Status, launch, routes};
//! use rocket_governor::{rocket_governor_catcher, Method, Quota, RocketGovernable, RocketGovernor};
//!
//! pub struct RateLimitGuard;
//!
//! impl<'r> RocketGovernable<'r> for RateLimitGuard {
//!     fn quota(_method: Method, _route_name: &str) -> Quota {
//!         Quota::per_second(Self::nonzero(1u32))
//!     }
//! }
//!
//! #[get("/")]
//! fn route_example(_limitguard: RocketGovernor<RateLimitGuard>) -> Status {
//!     Status::Ok
//! }
//!
//! #[launch]
//! fn launch_rocket() -> _ {
//!     rocket::build()
//!         .mount("/", routes![route_example])
//!         .register("/", catchers![rocket_governor_catcher])
//! }
//! ```
//!
//! See [rocket-governor] Github project for more information.
//!
//! ## Features
//!
//! ### Optional feature __limit_info__
//!
//! There is the optional feature __limit_info__ which enables reporting about
//! rate limits in HTTP headers of requests.
//!
//! The implementation is based on headers of
//! [https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-ratelimit-headers]().
//! The feature provides a default implementation of a Rocket fairing
//! which need to be used to get the HTTP headers set.
//!
//! See API documentation for [LimitHeaderGen](crate::LimitHeaderGen).
//!
//! For usage depend on it in Cargo.toml
//! ```toml
//! [dependencies]
//! rocket-governor = { version = "...", features = ["limit_info"] }
//! ```
//!
//! ### Optional feature __logger__
//!
//! There is the optional feature __logger__ which enables some logging output.
//!
//! For usage depend on it in Cargo.toml
//! ```toml
//! [dependencies]
//! rocket-governor = { version = "...", features = ["logger"] }
//! ```
//!
//! [governor]: https://docs.rs/governor/
//! [rocket]: https://docs.rs/rocket/
//! [rocket-governor]: https://github.com/kolbma/rocket-governor/

#![deny(clippy::all)]
#![deny(keyword_idents)]
#![deny(missing_docs)]
#![deny(non_ascii_idents)]
#![deny(unreachable_pub)]
#![deny(unsafe_code)]
#![deny(unused_crate_dependencies)]
#![deny(unused_qualifications)]
//#![deny(unused_results)]
#![deny(warnings)]

use governor::clock::{Clock, DefaultClock};
pub use governor::Quota;
use lazy_static::lazy_static;
pub use limit_error::LimitError;
#[cfg(feature = "limit_info")]
pub use limit_header_gen::LimitHeaderGen;
use logger::{error, info, trace};
use registry::Registry;
#[cfg(feature = "limit_info")]
pub use req_state::ReqState;
pub use rocket::http::Method;
use rocket::{
    async_trait, catch,
    http::Status,
    request::{FromRequest, Outcome},
    Request,
};
pub use rocket_governable::RocketGovernable;
use std::marker::PhantomData;
pub use std::num::NonZeroU32;

pub mod header;
mod limit_error;
#[cfg(feature = "limit_info")]
mod limit_header_gen;
mod logger;
mod registry;
#[cfg(feature = "limit_info")]
mod req_state;
mod rocket_governable;

/// Generic [RocketGovernor] implementation.
///
/// [rocket_governor](crate) is a [rocket] guard implementation of the
/// [governor] rate limiter.
///
/// Declare a struct and use it with the generic [RocketGovernor] guard.
/// This requires to implement [RocketGovernable] for your struct.
///
/// See the top level [crate] documentation.
///
/// [governor]: https://docs.rs/governor/
/// [rocket]: https://docs.rs/rocket/
///
pub struct RocketGovernor<'r, T>
where
    T: RocketGovernable<'r>,
{
    _phantom: PhantomData<&'r T>,
}

lazy_static! {
    static ref CLOCK: DefaultClock = DefaultClock::default();
}

#[doc(hidden)]
impl<'r, T> RocketGovernor<'r, T>
where
    T: RocketGovernable<'r>,
{
    /// Handler used in `FromRequest::from_request(request: &'r Request)`.
    #[inline(always)]
    pub fn handle_from_request(request: &'r Request) -> Outcome<Self, LimitError> {
        let res = request.local_cache(|| {
            if let Some(route) = request.route() {
                if let Some(route_name) = &route.name {
                    let limiter = Registry::get_or_insert::<T>(
                        route.method,
                        route_name,
                        T::quota(route.method, route_name),
                    );
                    if let Some(client_ip) = request.client_ip() {
                        let limit_check_res = limiter.check_key(&client_ip);
                        match limit_check_res {
                            Ok(state) => {
                                #[allow(unused_variables)] // only used in trace or when feature limit_info
                                let request_capacity = state.remaining_burst_capacity();
                                trace!(
                                    "not governed ip {} method {} route {}: remaining request capacity {}",
                                    &client_ip,
                                    &route.method,
                                    route_name,
                                    request_capacity
                                );

                                #[cfg(feature = "limit_info")] {
                                    // `local_cache` lookup works by type and so it doesn't work to catch
                                    // `LimitError` and handle different Ok objects:
                                    // See https://rocket.rs/v0.5-rc/guide/state/#request-local-state
                                    // State wrapper is so cached separate...
                                    let req_state = ReqState::new(state.quota(), request_capacity);
                                    let is_req_state_allowed = T::limit_info_allow(Some(route.method), Some(route_name), &req_state);
                                    if is_req_state_allowed {
                                        // For safety and speed this is used by default in a limited way, see:
                                        // * Information disclosure:
                                        //   https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-ratelimit-headers#section-6.2
                                        //
                                        let _ = request.local_cache(|| req_state);
                                    }
                                }

                                Ok(()) // needs to be something not changing during request
                            }
                            Err(notuntil) => {
                                let wait_time = notuntil.wait_time_from(CLOCK.now()).as_secs();
                                info!(
                                    "ip {} method {} route {} limited {} sec",
                                    &client_ip, &route.method, route_name, &wait_time
                                );
                                Err(LimitError::GovernedRequest(wait_time, notuntil.quota()))
                            }
                        }
                    } else {
                        error!(
                            "missing ip - method {} route {}: request: {:?}",
                            &route.method, route_name, request
                        );
                        Err(LimitError::MissingClientIpAddr)
                    }
                } else {
                    error!("route without name: request: {:?}", request);
                    Err(LimitError::MissingRouteName)
                }
            } else {
                error!("routing failure: request: {:?}", request);
                Err(LimitError::MissingRoute)
            }
        });

        match res {
            Ok(_) => {
                #[cfg(feature = "limit_info")]
                {
                    // available if `T::limit_info_allow()` is true
                    let state_opt = ReqState::get_or_default(&request);
                    #[allow(unused_variables)] // state only used in trace
                    if let Some(state) = state_opt {
                        trace!(
                            "request_capacity: {} rate-limit: {}",
                            state.request_capacity,
                            state.quota.burst_size().get()
                        );
                    }
                }

                // Forward request
                Outcome::Success(Self::default())
            }
            Err(e) => {
                let e = e.clone();
                match e {
                    LimitError::GovernedRequest(_, _) => {
                        Outcome::Failure((Status::TooManyRequests, e))
                    }
                    _ => Outcome::Failure((Status::BadRequest, e)),
                }
            }
        }
    }
}

#[doc(hidden)]
impl<'r, T> Default for RocketGovernor<'r, T>
where
    T: RocketGovernable<'r>,
{
    fn default() -> Self {
        Self {
            _phantom: PhantomData,
        }
    }
}

#[doc(hidden)]
#[async_trait]
impl<'r, T> FromRequest<'r> for RocketGovernor<'r, T>
where
    T: RocketGovernable<'r>,
{
    type Error = LimitError;

    async fn from_request(request: &'r Request<'_>) -> Outcome<Self, LimitError> {
        Self::handle_from_request(request)
    }
}

/// A default implementation for Rocket [Catcher] handling HTTP TooManyRequests responses.
///
/// ## Example
///
/// ```rust
/// use rocket::{catchers, launch};
/// use rocket_governor::rocket_governor_catcher;
///
/// #[launch]
/// fn launch_rocket() -> _ {
///     rocket::build()
///         .register("/", catchers![rocket_governor_catcher])
/// }
/// ```
///
/// [Catcher]: https://api.rocket.rs/v0.5-rc/rocket/struct.Catcher.html
#[catch(429)]
pub fn rocket_governor_catcher<'r>(request: &'r Request) -> &'r LimitError {
    let cached_res: &Result<(), LimitError> = request.local_cache(|| Err(LimitError::Error));
    if let Err(limit_err) = cached_res {
        limit_err
    } else {
        &LimitError::Error
    }
}